spirv_msl.cpp 728 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425
  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. for (uint32_t variant = 0; variant < 12; variant++)
  5462. {
  5463. bool is_multidim = spv_func == SPVFuncImplArrayCopyMultidim;
  5464. const char* dim = is_multidim ? "[N][M]" : "[N]";
  5465. statement("template<typename T, uint N", is_multidim ? ", uint M>" : ">");
  5466. statement("inline void spvArrayCopy", function_name_tags[variant], "(",
  5467. dst_address_space[variant], " T (&dst)", dim, ", ",
  5468. src_address_space[variant], " T (&src)", dim, ")");
  5469. begin_scope();
  5470. statement("for (uint i = 0; i < N; i++)");
  5471. begin_scope();
  5472. if (is_multidim)
  5473. statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);");
  5474. else
  5475. statement("dst[i] = src[i];");
  5476. end_scope();
  5477. end_scope();
  5478. statement("");
  5479. }
  5480. break;
  5481. }
  5482. // Support for Metal 2.1's new texture_buffer type.
  5483. case SPVFuncImplTexelBufferCoords:
  5484. {
  5485. if (msl_options.texel_buffer_texture_width > 0)
  5486. {
  5487. string tex_width_str = convert_to_string(msl_options.texel_buffer_texture_width);
  5488. statement("// Returns 2D texture coords corresponding to 1D texel buffer coords");
  5489. statement(force_inline);
  5490. statement("uint2 spvTexelBufferCoord(uint tc)");
  5491. begin_scope();
  5492. statement(join("return uint2(tc % ", tex_width_str, ", tc / ", tex_width_str, ");"));
  5493. end_scope();
  5494. statement("");
  5495. }
  5496. else
  5497. {
  5498. statement("// Returns 2D texture coords corresponding to 1D texel buffer coords");
  5499. statement(
  5500. "#define spvTexelBufferCoord(tc, tex) uint2((tc) % (tex).get_width(), (tc) / (tex).get_width())");
  5501. statement("");
  5502. }
  5503. break;
  5504. }
  5505. // Emulate texture2D atomic operations
  5506. case SPVFuncImplImage2DAtomicCoords:
  5507. {
  5508. if (msl_options.supports_msl_version(1, 2))
  5509. {
  5510. statement("// The required alignment of a linear texture of R32Uint format.");
  5511. statement("constant uint spvLinearTextureAlignmentOverride [[function_constant(",
  5512. msl_options.r32ui_alignment_constant_id, ")]];");
  5513. statement("constant uint spvLinearTextureAlignment = ",
  5514. "is_function_constant_defined(spvLinearTextureAlignmentOverride) ? ",
  5515. "spvLinearTextureAlignmentOverride : ", msl_options.r32ui_linear_texture_alignment, ";");
  5516. }
  5517. else
  5518. {
  5519. statement("// The required alignment of a linear texture of R32Uint format.");
  5520. statement("constant uint spvLinearTextureAlignment = ", msl_options.r32ui_linear_texture_alignment,
  5521. ";");
  5522. }
  5523. statement("// Returns buffer coords corresponding to 2D texture coords for emulating 2D texture atomics");
  5524. statement("#define spvImage2DAtomicCoord(tc, tex) (((((tex).get_width() + ",
  5525. " spvLinearTextureAlignment / 4 - 1) & ~(",
  5526. " spvLinearTextureAlignment / 4 - 1)) * (tc).y) + (tc).x)");
  5527. statement("");
  5528. break;
  5529. }
  5530. // Fix up gradient vectors when sampling a cube texture for Apple Silicon.
  5531. // h/t Alexey Knyazev (https://github.com/KhronosGroup/MoltenVK/issues/2068#issuecomment-1817799067) for the code.
  5532. case SPVFuncImplGradientCube:
  5533. statement("static inline gradientcube spvGradientCube(float3 P, float3 dPdx, float3 dPdy)");
  5534. begin_scope();
  5535. statement("// Major axis selection");
  5536. statement("float3 absP = abs(P);");
  5537. statement("bool xMajor = absP.x >= max(absP.y, absP.z);");
  5538. statement("bool yMajor = absP.y >= absP.z;");
  5539. statement("float3 Q = xMajor ? P.yzx : (yMajor ? P.xzy : P);");
  5540. statement("float3 dQdx = xMajor ? dPdx.yzx : (yMajor ? dPdx.xzy : dPdx);");
  5541. statement("float3 dQdy = xMajor ? dPdy.yzx : (yMajor ? dPdy.xzy : dPdy);");
  5542. statement_no_indent("");
  5543. statement("// Skip a couple of operations compared to usual projection");
  5544. statement("float4 d = float4(dQdx.xy, dQdy.xy) - (Q.xy / Q.z).xyxy * float4(dQdx.zz, dQdy.zz);");
  5545. statement_no_indent("");
  5546. statement("// Final swizzle to put the intermediate values into non-ignored components");
  5547. statement("// X major: X and Z");
  5548. statement("// Y major: X and Y");
  5549. statement("// Z major: Y and Z");
  5550. statement("return gradientcube(xMajor ? d.xxy : d.xyx, xMajor ? d.zzw : d.zwz);");
  5551. end_scope();
  5552. statement("");
  5553. break;
  5554. // "fadd" intrinsic support
  5555. case SPVFuncImplFAdd:
  5556. statement("template<typename T>");
  5557. statement("[[clang::optnone]] T spvFAdd(T l, T r)");
  5558. begin_scope();
  5559. statement("return fma(T(1), l, r);");
  5560. end_scope();
  5561. statement("");
  5562. break;
  5563. // "fsub" intrinsic support
  5564. case SPVFuncImplFSub:
  5565. statement("template<typename T>");
  5566. statement("[[clang::optnone]] T spvFSub(T l, T r)");
  5567. begin_scope();
  5568. statement("return fma(T(-1), r, l);");
  5569. end_scope();
  5570. statement("");
  5571. break;
  5572. // "fmul' intrinsic support
  5573. case SPVFuncImplFMul:
  5574. statement("template<typename T>");
  5575. statement("[[clang::optnone]] T spvFMul(T l, T r)");
  5576. begin_scope();
  5577. statement("return fma(l, r, T(0));");
  5578. end_scope();
  5579. statement("");
  5580. statement("template<typename T, int Cols, int Rows>");
  5581. statement("[[clang::optnone]] vec<T, Cols> spvFMulVectorMatrix(vec<T, Rows> v, matrix<T, Cols, Rows> m)");
  5582. begin_scope();
  5583. statement("vec<T, Cols> res = vec<T, Cols>(0);");
  5584. statement("for (uint i = Rows; i > 0; --i)");
  5585. begin_scope();
  5586. statement("vec<T, Cols> tmp(0);");
  5587. statement("for (uint j = 0; j < Cols; ++j)");
  5588. begin_scope();
  5589. statement("tmp[j] = m[j][i - 1];");
  5590. end_scope();
  5591. statement("res = fma(tmp, vec<T, Cols>(v[i - 1]), res);");
  5592. end_scope();
  5593. statement("return res;");
  5594. end_scope();
  5595. statement("");
  5596. statement("template<typename T, int Cols, int Rows>");
  5597. statement("[[clang::optnone]] vec<T, Rows> spvFMulMatrixVector(matrix<T, Cols, Rows> m, vec<T, Cols> v)");
  5598. begin_scope();
  5599. statement("vec<T, Rows> res = vec<T, Rows>(0);");
  5600. statement("for (uint i = Cols; i > 0; --i)");
  5601. begin_scope();
  5602. statement("res = fma(m[i - 1], vec<T, Rows>(v[i - 1]), res);");
  5603. end_scope();
  5604. statement("return res;");
  5605. end_scope();
  5606. statement("");
  5607. statement("template<typename T, int LCols, int LRows, int RCols, int RRows>");
  5608. statement("[[clang::optnone]] matrix<T, RCols, LRows> spvFMulMatrixMatrix(matrix<T, LCols, LRows> l, matrix<T, RCols, RRows> r)");
  5609. begin_scope();
  5610. statement("matrix<T, RCols, LRows> res;");
  5611. statement("for (uint i = 0; i < RCols; i++)");
  5612. begin_scope();
  5613. statement("vec<T, RCols> tmp(0);");
  5614. statement("for (uint j = 0; j < LCols; j++)");
  5615. begin_scope();
  5616. statement("tmp = fma(vec<T, RCols>(r[i][j]), l[j], tmp);");
  5617. end_scope();
  5618. statement("res[i] = tmp;");
  5619. end_scope();
  5620. statement("return res;");
  5621. end_scope();
  5622. statement("");
  5623. break;
  5624. case SPVFuncImplQuantizeToF16:
  5625. // Ensure fast-math is disabled to match Vulkan results.
  5626. // SpvHalfTypeSelector is used to match the half* template type to the float* template type.
  5627. // Depending on GPU, MSL does not always flush converted subnormal halfs to zero,
  5628. // as required by OpQuantizeToF16, so check for subnormals and flush them to zero.
  5629. statement("template <typename F> struct SpvHalfTypeSelector;");
  5630. statement("template <> struct SpvHalfTypeSelector<float> { public: using H = half; };");
  5631. statement("template<uint N> struct SpvHalfTypeSelector<vec<float, N>> { using H = vec<half, N>; };");
  5632. statement("template<typename F, typename H = typename SpvHalfTypeSelector<F>::H>");
  5633. statement("[[clang::optnone]] F spvQuantizeToF16(F fval)");
  5634. begin_scope();
  5635. statement("H hval = H(fval);");
  5636. statement("hval = select(copysign(H(0), hval), hval, isnormal(hval) || isinf(hval) || isnan(hval));");
  5637. statement("return F(hval);");
  5638. end_scope();
  5639. statement("");
  5640. break;
  5641. // Emulate texturecube_array with texture2d_array for iOS where this type is not available
  5642. case SPVFuncImplCubemapTo2DArrayFace:
  5643. statement(force_inline);
  5644. statement("float3 spvCubemapTo2DArrayFace(float3 P)");
  5645. begin_scope();
  5646. statement("float3 Coords = abs(P.xyz);");
  5647. statement("float CubeFace = 0;");
  5648. statement("float ProjectionAxis = 0;");
  5649. statement("float u = 0;");
  5650. statement("float v = 0;");
  5651. statement("if (Coords.x >= Coords.y && Coords.x >= Coords.z)");
  5652. begin_scope();
  5653. statement("CubeFace = P.x >= 0 ? 0 : 1;");
  5654. statement("ProjectionAxis = Coords.x;");
  5655. statement("u = P.x >= 0 ? -P.z : P.z;");
  5656. statement("v = -P.y;");
  5657. end_scope();
  5658. statement("else if (Coords.y >= Coords.x && Coords.y >= Coords.z)");
  5659. begin_scope();
  5660. statement("CubeFace = P.y >= 0 ? 2 : 3;");
  5661. statement("ProjectionAxis = Coords.y;");
  5662. statement("u = P.x;");
  5663. statement("v = P.y >= 0 ? P.z : -P.z;");
  5664. end_scope();
  5665. statement("else");
  5666. begin_scope();
  5667. statement("CubeFace = P.z >= 0 ? 4 : 5;");
  5668. statement("ProjectionAxis = Coords.z;");
  5669. statement("u = P.z >= 0 ? P.x : -P.x;");
  5670. statement("v = -P.y;");
  5671. end_scope();
  5672. statement("u = 0.5 * (u/ProjectionAxis + 1);");
  5673. statement("v = 0.5 * (v/ProjectionAxis + 1);");
  5674. statement("return float3(u, v, CubeFace);");
  5675. end_scope();
  5676. statement("");
  5677. break;
  5678. case SPVFuncImplInverse4x4:
  5679. statement("// Returns the determinant of a 2x2 matrix.");
  5680. statement(force_inline);
  5681. statement("float spvDet2x2(float a1, float a2, float b1, float b2)");
  5682. begin_scope();
  5683. statement("return a1 * b2 - b1 * a2;");
  5684. end_scope();
  5685. statement("");
  5686. statement("// Returns the determinant of a 3x3 matrix.");
  5687. statement(force_inline);
  5688. statement("float spvDet3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, "
  5689. "float c2, float c3)");
  5690. begin_scope();
  5691. statement("return a1 * spvDet2x2(b2, b3, c2, c3) - b1 * spvDet2x2(a2, a3, c2, c3) + c1 * spvDet2x2(a2, a3, "
  5692. "b2, b3);");
  5693. end_scope();
  5694. statement("");
  5695. statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
  5696. statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
  5697. statement(force_inline);
  5698. statement("float4x4 spvInverse4x4(float4x4 m)");
  5699. begin_scope();
  5700. statement("float4x4 adj; // The adjoint matrix (inverse after dividing by determinant)");
  5701. statement_no_indent("");
  5702. statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
  5703. 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], "
  5704. "m[3][3]);");
  5705. 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], "
  5706. "m[3][3]);");
  5707. 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], "
  5708. "m[3][3]);");
  5709. 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], "
  5710. "m[2][3]);");
  5711. statement_no_indent("");
  5712. 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], "
  5713. "m[3][3]);");
  5714. 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], "
  5715. "m[3][3]);");
  5716. 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], "
  5717. "m[3][3]);");
  5718. 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], "
  5719. "m[2][3]);");
  5720. statement_no_indent("");
  5721. 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], "
  5722. "m[3][3]);");
  5723. 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], "
  5724. "m[3][3]);");
  5725. 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], "
  5726. "m[3][3]);");
  5727. 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], "
  5728. "m[2][3]);");
  5729. statement_no_indent("");
  5730. 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], "
  5731. "m[3][2]);");
  5732. 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], "
  5733. "m[3][2]);");
  5734. 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], "
  5735. "m[3][2]);");
  5736. 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], "
  5737. "m[2][2]);");
  5738. statement_no_indent("");
  5739. statement("// Calculate the determinant as a combination of the cofactors of the first row.");
  5740. statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]) + (adj[0][3] "
  5741. "* m[3][0]);");
  5742. statement_no_indent("");
  5743. statement("// Divide the classical adjoint matrix by the determinant.");
  5744. statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
  5745. statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
  5746. end_scope();
  5747. statement("");
  5748. break;
  5749. case SPVFuncImplInverse3x3:
  5750. if (spv_function_implementations.count(SPVFuncImplInverse4x4) == 0)
  5751. {
  5752. statement("// Returns the determinant of a 2x2 matrix.");
  5753. statement(force_inline);
  5754. statement("float spvDet2x2(float a1, float a2, float b1, float b2)");
  5755. begin_scope();
  5756. statement("return a1 * b2 - b1 * a2;");
  5757. end_scope();
  5758. statement("");
  5759. }
  5760. statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
  5761. statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
  5762. statement(force_inline);
  5763. statement("float3x3 spvInverse3x3(float3x3 m)");
  5764. begin_scope();
  5765. statement("float3x3 adj; // The adjoint matrix (inverse after dividing by determinant)");
  5766. statement_no_indent("");
  5767. statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
  5768. statement("adj[0][0] = spvDet2x2(m[1][1], m[1][2], m[2][1], m[2][2]);");
  5769. statement("adj[0][1] = -spvDet2x2(m[0][1], m[0][2], m[2][1], m[2][2]);");
  5770. statement("adj[0][2] = spvDet2x2(m[0][1], m[0][2], m[1][1], m[1][2]);");
  5771. statement_no_indent("");
  5772. statement("adj[1][0] = -spvDet2x2(m[1][0], m[1][2], m[2][0], m[2][2]);");
  5773. statement("adj[1][1] = spvDet2x2(m[0][0], m[0][2], m[2][0], m[2][2]);");
  5774. statement("adj[1][2] = -spvDet2x2(m[0][0], m[0][2], m[1][0], m[1][2]);");
  5775. statement_no_indent("");
  5776. statement("adj[2][0] = spvDet2x2(m[1][0], m[1][1], m[2][0], m[2][1]);");
  5777. statement("adj[2][1] = -spvDet2x2(m[0][0], m[0][1], m[2][0], m[2][1]);");
  5778. statement("adj[2][2] = spvDet2x2(m[0][0], m[0][1], m[1][0], m[1][1]);");
  5779. statement_no_indent("");
  5780. statement("// Calculate the determinant as a combination of the cofactors of the first row.");
  5781. statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]);");
  5782. statement_no_indent("");
  5783. statement("// Divide the classical adjoint matrix by the determinant.");
  5784. statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
  5785. statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
  5786. end_scope();
  5787. statement("");
  5788. break;
  5789. case SPVFuncImplInverse2x2:
  5790. statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
  5791. statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
  5792. statement(force_inline);
  5793. statement("float2x2 spvInverse2x2(float2x2 m)");
  5794. begin_scope();
  5795. statement("float2x2 adj; // The adjoint matrix (inverse after dividing by determinant)");
  5796. statement_no_indent("");
  5797. statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
  5798. statement("adj[0][0] = m[1][1];");
  5799. statement("adj[0][1] = -m[0][1];");
  5800. statement_no_indent("");
  5801. statement("adj[1][0] = -m[1][0];");
  5802. statement("adj[1][1] = m[0][0];");
  5803. statement_no_indent("");
  5804. statement("// Calculate the determinant as a combination of the cofactors of the first row.");
  5805. statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]);");
  5806. statement_no_indent("");
  5807. statement("// Divide the classical adjoint matrix by the determinant.");
  5808. statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
  5809. statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
  5810. end_scope();
  5811. statement("");
  5812. break;
  5813. case SPVFuncImplGetSwizzle:
  5814. statement("enum class spvSwizzle : uint");
  5815. begin_scope();
  5816. statement("none = 0,");
  5817. statement("zero,");
  5818. statement("one,");
  5819. statement("red,");
  5820. statement("green,");
  5821. statement("blue,");
  5822. statement("alpha");
  5823. end_scope_decl();
  5824. statement("");
  5825. statement("template<typename T>");
  5826. statement("inline T spvGetSwizzle(vec<T, 4> x, T c, spvSwizzle s)");
  5827. begin_scope();
  5828. statement("switch (s)");
  5829. begin_scope();
  5830. statement("case spvSwizzle::none:");
  5831. statement(" return c;");
  5832. statement("case spvSwizzle::zero:");
  5833. statement(" return 0;");
  5834. statement("case spvSwizzle::one:");
  5835. statement(" return 1;");
  5836. statement("case spvSwizzle::red:");
  5837. statement(" return x.r;");
  5838. statement("case spvSwizzle::green:");
  5839. statement(" return x.g;");
  5840. statement("case spvSwizzle::blue:");
  5841. statement(" return x.b;");
  5842. statement("case spvSwizzle::alpha:");
  5843. statement(" return x.a;");
  5844. end_scope();
  5845. end_scope();
  5846. statement("");
  5847. break;
  5848. case SPVFuncImplTextureSwizzle:
  5849. statement("// Wrapper function that swizzles texture samples and fetches.");
  5850. statement("template<typename T>");
  5851. statement("inline vec<T, 4> spvTextureSwizzle(vec<T, 4> x, uint s)");
  5852. begin_scope();
  5853. statement("if (!s)");
  5854. statement(" return x;");
  5855. statement("return vec<T, 4>(spvGetSwizzle(x, x.r, spvSwizzle((s >> 0) & 0xFF)), "
  5856. "spvGetSwizzle(x, x.g, spvSwizzle((s >> 8) & 0xFF)), spvGetSwizzle(x, x.b, spvSwizzle((s >> 16) "
  5857. "& 0xFF)), "
  5858. "spvGetSwizzle(x, x.a, spvSwizzle((s >> 24) & 0xFF)));");
  5859. end_scope();
  5860. statement("");
  5861. statement("template<typename T>");
  5862. statement("inline T spvTextureSwizzle(T x, uint s)");
  5863. begin_scope();
  5864. statement("return spvTextureSwizzle(vec<T, 4>(x, 0, 0, 1), s).x;");
  5865. end_scope();
  5866. statement("");
  5867. break;
  5868. case SPVFuncImplGatherReturn:
  5869. statement("template<typename Tex, typename... Tp>");
  5870. statement("using spvGatherReturn = decltype(declval<Tex>().gather(declval<sampler>(), declval<Tp>()...));");
  5871. statement("");
  5872. break;
  5873. case SPVFuncImplGatherCompareReturn:
  5874. statement("template<typename Tex, typename... Tp>");
  5875. statement("using spvGatherCompareReturn = decltype(declval<Tex>().gather_compare(declval<sampler>(), declval<Tp>()...));");
  5876. statement("");
  5877. break;
  5878. case SPVFuncImplGatherSwizzle:
  5879. statement("// Wrapper function that swizzles texture gathers.");
  5880. statement("template<typename Tex, typename... Ts>");
  5881. statement("inline spvGatherReturn<Tex, Ts...> spvGatherSwizzle(const thread Tex& t, sampler s, "
  5882. "uint sw, component c, Ts... params) METAL_CONST_ARG(c)");
  5883. begin_scope();
  5884. statement("if (sw)");
  5885. begin_scope();
  5886. statement("switch (spvSwizzle((sw >> (uint(c) * 8)) & 0xFF))");
  5887. begin_scope();
  5888. statement("case spvSwizzle::none:");
  5889. statement(" break;");
  5890. statement("case spvSwizzle::zero:");
  5891. statement(" return spvGatherReturn<Tex, Ts...>(0, 0, 0, 0);");
  5892. statement("case spvSwizzle::one:");
  5893. statement(" return spvGatherReturn<Tex, Ts...>(1, 1, 1, 1);");
  5894. statement("case spvSwizzle::red:");
  5895. statement(" return t.gather(s, params..., component::x);");
  5896. statement("case spvSwizzle::green:");
  5897. statement(" return t.gather(s, params..., component::y);");
  5898. statement("case spvSwizzle::blue:");
  5899. statement(" return t.gather(s, params..., component::z);");
  5900. statement("case spvSwizzle::alpha:");
  5901. statement(" return t.gather(s, params..., component::w);");
  5902. end_scope();
  5903. end_scope();
  5904. // texture::gather insists on its component parameter being a constant
  5905. // expression, so we need this silly workaround just to compile the shader.
  5906. statement("switch (c)");
  5907. begin_scope();
  5908. statement("case component::x:");
  5909. statement(" return t.gather(s, params..., component::x);");
  5910. statement("case component::y:");
  5911. statement(" return t.gather(s, params..., component::y);");
  5912. statement("case component::z:");
  5913. statement(" return t.gather(s, params..., component::z);");
  5914. statement("case component::w:");
  5915. statement(" return t.gather(s, params..., component::w);");
  5916. end_scope();
  5917. end_scope();
  5918. statement("");
  5919. break;
  5920. case SPVFuncImplGatherCompareSwizzle:
  5921. statement("// Wrapper function that swizzles depth texture gathers.");
  5922. statement("template<typename Tex, typename... Ts>");
  5923. statement("inline spvGatherCompareReturn<Tex, Ts...> spvGatherCompareSwizzle(const thread Tex& t, sampler s, uint sw, Ts... params)");
  5924. begin_scope();
  5925. statement("if (sw)");
  5926. begin_scope();
  5927. statement("switch (spvSwizzle(sw & 0xFF))");
  5928. begin_scope();
  5929. statement("case spvSwizzle::none:");
  5930. statement("case spvSwizzle::red:");
  5931. statement(" break;");
  5932. statement("case spvSwizzle::zero:");
  5933. statement("case spvSwizzle::green:");
  5934. statement("case spvSwizzle::blue:");
  5935. statement("case spvSwizzle::alpha:");
  5936. statement(" return spvGatherCompareReturn<Tex, Ts...>(0, 0, 0, 0);");
  5937. statement("case spvSwizzle::one:");
  5938. statement(" return spvGatherCompareReturn<Tex, Ts...>(1, 1, 1, 1);");
  5939. end_scope();
  5940. end_scope();
  5941. statement("return t.gather_compare(s, params...);");
  5942. end_scope();
  5943. statement("");
  5944. break;
  5945. case SPVFuncImplGatherConstOffsets:
  5946. // Because we are passing a texture reference, we have to output an overloaded version of this function for each address space.
  5947. for (uint32_t i = 0; i < texture_addr_space_count; i++)
  5948. {
  5949. statement("// Wrapper function that processes a ", texture_addr_spaces[i], " texture gather with a constant offset array.");
  5950. statement("template<typename Tex, typename Toff, typename... Tp>");
  5951. statement("inline spvGatherReturn<Tex, Tp...> spvGatherConstOffsets(const ", texture_addr_spaces[i], " Tex& t, sampler s, "
  5952. "Toff coffsets, component c, Tp... params) METAL_CONST_ARG(c)");
  5953. begin_scope();
  5954. statement("spvGatherReturn<Tex, Tp...> rslts[4];");
  5955. statement("for (uint i = 0; i < 4; i++)");
  5956. begin_scope();
  5957. statement("switch (c)");
  5958. begin_scope();
  5959. // Work around texture::gather() requiring its component parameter to be a constant expression
  5960. statement("case component::x:");
  5961. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::x);");
  5962. statement(" break;");
  5963. statement("case component::y:");
  5964. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::y);");
  5965. statement(" break;");
  5966. statement("case component::z:");
  5967. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::z);");
  5968. statement(" break;");
  5969. statement("case component::w:");
  5970. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::w);");
  5971. statement(" break;");
  5972. end_scope();
  5973. end_scope();
  5974. // Pull all values from the i0j0 component of each gather footprint
  5975. statement("return spvGatherReturn<Tex, Tp...>(rslts[0].w, rslts[1].w, rslts[2].w, rslts[3].w);");
  5976. end_scope();
  5977. statement("");
  5978. }
  5979. break;
  5980. case SPVFuncImplGatherCompareConstOffsets:
  5981. // Because we are passing a texture reference, we have to output an overloaded version of this function for each address space.
  5982. for (uint32_t i = 0; i < texture_addr_space_count; i++)
  5983. {
  5984. statement("// Wrapper function that processes a ", texture_addr_spaces[i], " texture gather with a constant offset array.");
  5985. statement("template<typename Tex, typename Toff, typename... Tp>");
  5986. statement("inline spvGatherCompareReturn<Tex, Tp...> spvGatherCompareConstOffsets(const ", texture_addr_spaces[i], " Tex& t, sampler s, "
  5987. "Toff coffsets, Tp... params)");
  5988. begin_scope();
  5989. statement("spvGatherCompareReturn<Tex, Tp...> rslts[4];");
  5990. statement("for (uint i = 0; i < 4; i++)");
  5991. begin_scope();
  5992. statement(" rslts[i] = t.gather_compare(s, params..., coffsets[i]);");
  5993. end_scope();
  5994. // Pull all values from the i0j0 component of each gather footprint
  5995. statement("return spvGatherCompareReturn<Tex, Tp...>(rslts[0].w, rslts[1].w, rslts[2].w, rslts[3].w);");
  5996. end_scope();
  5997. statement("");
  5998. }
  5999. break;
  6000. case SPVFuncImplSubgroupBroadcast:
  6001. // Metal doesn't allow broadcasting boolean values directly, but we can work around that by broadcasting
  6002. // them as integers.
  6003. statement("template<typename T>");
  6004. statement("inline T spvSubgroupBroadcast(T value, ushort lane)");
  6005. begin_scope();
  6006. if (msl_options.use_quadgroup_operation())
  6007. statement("return quad_broadcast(value, lane);");
  6008. else
  6009. statement("return simd_broadcast(value, lane);");
  6010. end_scope();
  6011. statement("");
  6012. statement("template<>");
  6013. statement("inline bool spvSubgroupBroadcast(bool value, ushort lane)");
  6014. begin_scope();
  6015. if (msl_options.use_quadgroup_operation())
  6016. statement("return !!quad_broadcast((ushort)value, lane);");
  6017. else
  6018. statement("return !!simd_broadcast((ushort)value, lane);");
  6019. end_scope();
  6020. statement("");
  6021. statement("template<uint N>");
  6022. statement("inline vec<bool, N> spvSubgroupBroadcast(vec<bool, N> value, ushort lane)");
  6023. begin_scope();
  6024. if (msl_options.use_quadgroup_operation())
  6025. statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);");
  6026. else
  6027. statement("return (vec<bool, N>)simd_broadcast((vec<ushort, N>)value, lane);");
  6028. end_scope();
  6029. statement("");
  6030. break;
  6031. case SPVFuncImplSubgroupBroadcastFirst:
  6032. statement("template<typename T>");
  6033. statement("inline T spvSubgroupBroadcastFirst(T value)");
  6034. begin_scope();
  6035. if (msl_options.use_quadgroup_operation())
  6036. statement("return quad_broadcast_first(value);");
  6037. else
  6038. statement("return simd_broadcast_first(value);");
  6039. end_scope();
  6040. statement("");
  6041. statement("template<>");
  6042. statement("inline bool spvSubgroupBroadcastFirst(bool value)");
  6043. begin_scope();
  6044. if (msl_options.use_quadgroup_operation())
  6045. statement("return !!quad_broadcast_first((ushort)value);");
  6046. else
  6047. statement("return !!simd_broadcast_first((ushort)value);");
  6048. end_scope();
  6049. statement("");
  6050. statement("template<uint N>");
  6051. statement("inline vec<bool, N> spvSubgroupBroadcastFirst(vec<bool, N> value)");
  6052. begin_scope();
  6053. if (msl_options.use_quadgroup_operation())
  6054. statement("return (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value);");
  6055. else
  6056. statement("return (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value);");
  6057. end_scope();
  6058. statement("");
  6059. break;
  6060. case SPVFuncImplSubgroupBallot:
  6061. statement("inline uint4 spvSubgroupBallot(bool value)");
  6062. begin_scope();
  6063. if (msl_options.use_quadgroup_operation())
  6064. {
  6065. statement("return uint4((quad_vote::vote_t)quad_ballot(value), 0, 0, 0);");
  6066. }
  6067. else if (msl_options.is_ios())
  6068. {
  6069. // The current simd_vote on iOS uses a 32-bit integer-like object.
  6070. statement("return uint4((simd_vote::vote_t)simd_ballot(value), 0, 0, 0);");
  6071. }
  6072. else
  6073. {
  6074. statement("simd_vote vote = simd_ballot(value);");
  6075. statement("// simd_ballot() returns a 64-bit integer-like object, but");
  6076. statement("// SPIR-V callers expect a uint4. We must convert.");
  6077. statement("// FIXME: This won't include higher bits if Apple ever supports");
  6078. statement("// 128 lanes in an SIMD-group.");
  6079. statement("return uint4(as_type<uint2>((simd_vote::vote_t)vote), 0, 0);");
  6080. }
  6081. end_scope();
  6082. statement("");
  6083. break;
  6084. case SPVFuncImplSubgroupBallotBitExtract:
  6085. statement("inline bool spvSubgroupBallotBitExtract(uint4 ballot, uint bit)");
  6086. begin_scope();
  6087. statement("return !!extract_bits(ballot[bit / 32], bit % 32, 1);");
  6088. end_scope();
  6089. statement("");
  6090. break;
  6091. case SPVFuncImplSubgroupBallotFindLSB:
  6092. statement("inline uint spvSubgroupBallotFindLSB(uint4 ballot, uint gl_SubgroupSize)");
  6093. begin_scope();
  6094. if (msl_options.is_ios())
  6095. {
  6096. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
  6097. }
  6098. else
  6099. {
  6100. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
  6101. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
  6102. }
  6103. statement("ballot &= mask;");
  6104. statement("return select(ctz(ballot.x), select(32 + ctz(ballot.y), select(64 + ctz(ballot.z), select(96 + "
  6105. "ctz(ballot.w), uint(-1), ballot.w == 0), ballot.z == 0), ballot.y == 0), ballot.x == 0);");
  6106. end_scope();
  6107. statement("");
  6108. break;
  6109. case SPVFuncImplSubgroupBallotFindMSB:
  6110. statement("inline uint spvSubgroupBallotFindMSB(uint4 ballot, uint gl_SubgroupSize)");
  6111. begin_scope();
  6112. if (msl_options.is_ios())
  6113. {
  6114. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
  6115. }
  6116. else
  6117. {
  6118. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
  6119. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
  6120. }
  6121. statement("ballot &= mask;");
  6122. statement("return select(128 - (clz(ballot.w) + 1), select(96 - (clz(ballot.z) + 1), select(64 - "
  6123. "(clz(ballot.y) + 1), select(32 - (clz(ballot.x) + 1), uint(-1), ballot.x == 0), ballot.y == 0), "
  6124. "ballot.z == 0), ballot.w == 0);");
  6125. end_scope();
  6126. statement("");
  6127. break;
  6128. case SPVFuncImplSubgroupBallotBitCount:
  6129. statement("inline uint spvPopCount4(uint4 ballot)");
  6130. begin_scope();
  6131. statement("return popcount(ballot.x) + popcount(ballot.y) + popcount(ballot.z) + popcount(ballot.w);");
  6132. end_scope();
  6133. statement("");
  6134. statement("inline uint spvSubgroupBallotBitCount(uint4 ballot, uint gl_SubgroupSize)");
  6135. begin_scope();
  6136. if (msl_options.is_ios())
  6137. {
  6138. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
  6139. }
  6140. else
  6141. {
  6142. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
  6143. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
  6144. }
  6145. statement("return spvPopCount4(ballot & mask);");
  6146. end_scope();
  6147. statement("");
  6148. statement("inline uint spvSubgroupBallotInclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)");
  6149. begin_scope();
  6150. if (msl_options.is_ios())
  6151. {
  6152. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID + 1), uint3(0));");
  6153. }
  6154. else
  6155. {
  6156. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID + 1, 32u)), "
  6157. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID + 1 - 32, 0)), "
  6158. "uint2(0));");
  6159. }
  6160. statement("return spvPopCount4(ballot & mask);");
  6161. end_scope();
  6162. statement("");
  6163. statement("inline uint spvSubgroupBallotExclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)");
  6164. begin_scope();
  6165. if (msl_options.is_ios())
  6166. {
  6167. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID), uint2(0));");
  6168. }
  6169. else
  6170. {
  6171. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID, 32u)), "
  6172. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID - 32, 0)), uint2(0));");
  6173. }
  6174. statement("return spvPopCount4(ballot & mask);");
  6175. end_scope();
  6176. statement("");
  6177. break;
  6178. case SPVFuncImplSubgroupAllEqual:
  6179. // Metal doesn't provide a function to evaluate this directly. But, we can
  6180. // implement this by comparing every thread's value to one thread's value
  6181. // (in this case, the value of the first active thread). Then, by the transitive
  6182. // property of equality, if all comparisons return true, then they are all equal.
  6183. statement("template<typename T>");
  6184. statement("inline bool spvSubgroupAllEqual(T value)");
  6185. begin_scope();
  6186. if (msl_options.use_quadgroup_operation())
  6187. statement("return quad_all(all(value == quad_broadcast_first(value)));");
  6188. else
  6189. statement("return simd_all(all(value == simd_broadcast_first(value)));");
  6190. end_scope();
  6191. statement("");
  6192. statement("template<>");
  6193. statement("inline bool spvSubgroupAllEqual(bool value)");
  6194. begin_scope();
  6195. if (msl_options.use_quadgroup_operation())
  6196. statement("return quad_all(value) || !quad_any(value);");
  6197. else
  6198. statement("return simd_all(value) || !simd_any(value);");
  6199. end_scope();
  6200. statement("");
  6201. statement("template<uint N>");
  6202. statement("inline bool spvSubgroupAllEqual(vec<bool, N> value)");
  6203. begin_scope();
  6204. if (msl_options.use_quadgroup_operation())
  6205. statement("return quad_all(all(value == (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value)));");
  6206. else
  6207. statement("return simd_all(all(value == (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value)));");
  6208. end_scope();
  6209. statement("");
  6210. break;
  6211. case SPVFuncImplSubgroupShuffle:
  6212. statement("template<typename T>");
  6213. statement("inline T spvSubgroupShuffle(T value, ushort lane)");
  6214. begin_scope();
  6215. if (msl_options.use_quadgroup_operation())
  6216. statement("return quad_shuffle(value, lane);");
  6217. else
  6218. statement("return simd_shuffle(value, lane);");
  6219. end_scope();
  6220. statement("");
  6221. statement("template<>");
  6222. statement("inline bool spvSubgroupShuffle(bool value, ushort lane)");
  6223. begin_scope();
  6224. if (msl_options.use_quadgroup_operation())
  6225. statement("return !!quad_shuffle((ushort)value, lane);");
  6226. else
  6227. statement("return !!simd_shuffle((ushort)value, lane);");
  6228. end_scope();
  6229. statement("");
  6230. statement("template<uint N>");
  6231. statement("inline vec<bool, N> spvSubgroupShuffle(vec<bool, N> value, ushort lane)");
  6232. begin_scope();
  6233. if (msl_options.use_quadgroup_operation())
  6234. statement("return (vec<bool, N>)quad_shuffle((vec<ushort, N>)value, lane);");
  6235. else
  6236. statement("return (vec<bool, N>)simd_shuffle((vec<ushort, N>)value, lane);");
  6237. end_scope();
  6238. statement("");
  6239. if (msl_options.supports_msl_version(2, 2))
  6240. {
  6241. // Despite being a template in MSL, it does not support 64-bit shuffles.
  6242. // Unsure if there's a cleaner way to statically unroll based on vec<> template, but this will do.
  6243. statement("template<>");
  6244. statement("inline ulong spvSubgroupShuffle(ulong value, ushort lane)");
  6245. begin_scope();
  6246. statement("return as_type<ulong>(spvSubgroupShuffle(as_type<uint2>(value), lane));");
  6247. end_scope();
  6248. statement("");
  6249. statement("template<>");
  6250. statement("inline ulong2 spvSubgroupShuffle(ulong2 value, ushort lane)");
  6251. begin_scope();
  6252. statement("return ulong2(spvSubgroupShuffle(value.x, lane), spvSubgroupShuffle(value.y, lane));");
  6253. end_scope();
  6254. statement("");
  6255. statement("inline ulong3 spvSubgroupShuffle(ulong3 value, ushort lane)");
  6256. begin_scope();
  6257. statement("return ulong3(spvSubgroupShuffle(value.xy, lane), spvSubgroupShuffle(value.z, lane));");
  6258. end_scope();
  6259. statement("");
  6260. statement("inline ulong4 spvSubgroupShuffle(ulong4 value, ushort lane)");
  6261. begin_scope();
  6262. statement("return ulong4(spvSubgroupShuffle(value.xy, lane), spvSubgroupShuffle(value.zw, lane));");
  6263. end_scope();
  6264. statement("");
  6265. statement("template<uint N>");
  6266. statement("inline vec<long, N> spvSubgroupShuffle(vec<long, N> value, ushort lane)");
  6267. begin_scope();
  6268. statement("return vec<long, N>(spvSubgroupShuffle(vec<ulong, N>(value), lane));");
  6269. end_scope();
  6270. statement("");
  6271. }
  6272. break;
  6273. case SPVFuncImplSubgroupShuffleXor:
  6274. statement("template<typename T>");
  6275. statement("inline T spvSubgroupShuffleXor(T value, ushort mask)");
  6276. begin_scope();
  6277. if (msl_options.use_quadgroup_operation())
  6278. statement("return quad_shuffle_xor(value, mask);");
  6279. else
  6280. statement("return simd_shuffle_xor(value, mask);");
  6281. end_scope();
  6282. statement("");
  6283. statement("template<>");
  6284. statement("inline bool spvSubgroupShuffleXor(bool value, ushort mask)");
  6285. begin_scope();
  6286. if (msl_options.use_quadgroup_operation())
  6287. statement("return !!quad_shuffle_xor((ushort)value, mask);");
  6288. else
  6289. statement("return !!simd_shuffle_xor((ushort)value, mask);");
  6290. end_scope();
  6291. statement("");
  6292. statement("template<uint N>");
  6293. statement("inline vec<bool, N> spvSubgroupShuffleXor(vec<bool, N> value, ushort mask)");
  6294. begin_scope();
  6295. if (msl_options.use_quadgroup_operation())
  6296. statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, mask);");
  6297. else
  6298. statement("return (vec<bool, N>)simd_shuffle_xor((vec<ushort, N>)value, mask);");
  6299. end_scope();
  6300. statement("");
  6301. break;
  6302. case SPVFuncImplSubgroupShuffleUp:
  6303. statement("template<typename T>");
  6304. statement("inline T spvSubgroupShuffleUp(T value, ushort delta)");
  6305. begin_scope();
  6306. if (msl_options.use_quadgroup_operation())
  6307. statement("return quad_shuffle_up(value, delta);");
  6308. else
  6309. statement("return simd_shuffle_up(value, delta);");
  6310. end_scope();
  6311. statement("");
  6312. statement("template<>");
  6313. statement("inline bool spvSubgroupShuffleUp(bool value, ushort delta)");
  6314. begin_scope();
  6315. if (msl_options.use_quadgroup_operation())
  6316. statement("return !!quad_shuffle_up((ushort)value, delta);");
  6317. else
  6318. statement("return !!simd_shuffle_up((ushort)value, delta);");
  6319. end_scope();
  6320. statement("");
  6321. statement("template<uint N>");
  6322. statement("inline vec<bool, N> spvSubgroupShuffleUp(vec<bool, N> value, ushort delta)");
  6323. begin_scope();
  6324. if (msl_options.use_quadgroup_operation())
  6325. statement("return (vec<bool, N>)quad_shuffle_up((vec<ushort, N>)value, delta);");
  6326. else
  6327. statement("return (vec<bool, N>)simd_shuffle_up((vec<ushort, N>)value, delta);");
  6328. end_scope();
  6329. statement("");
  6330. break;
  6331. case SPVFuncImplSubgroupShuffleDown:
  6332. statement("template<typename T>");
  6333. statement("inline T spvSubgroupShuffleDown(T value, ushort delta)");
  6334. begin_scope();
  6335. if (msl_options.use_quadgroup_operation())
  6336. statement("return quad_shuffle_down(value, delta);");
  6337. else
  6338. statement("return simd_shuffle_down(value, delta);");
  6339. end_scope();
  6340. statement("");
  6341. statement("template<>");
  6342. statement("inline bool spvSubgroupShuffleDown(bool value, ushort delta)");
  6343. begin_scope();
  6344. if (msl_options.use_quadgroup_operation())
  6345. statement("return !!quad_shuffle_down((ushort)value, delta);");
  6346. else
  6347. statement("return !!simd_shuffle_down((ushort)value, delta);");
  6348. end_scope();
  6349. statement("");
  6350. statement("template<uint N>");
  6351. statement("inline vec<bool, N> spvSubgroupShuffleDown(vec<bool, N> value, ushort delta)");
  6352. begin_scope();
  6353. if (msl_options.use_quadgroup_operation())
  6354. statement("return (vec<bool, N>)quad_shuffle_down((vec<ushort, N>)value, delta);");
  6355. else
  6356. statement("return (vec<bool, N>)simd_shuffle_down((vec<ushort, N>)value, delta);");
  6357. end_scope();
  6358. statement("");
  6359. break;
  6360. case SPVFuncImplSubgroupRotate:
  6361. statement("template<typename T>");
  6362. statement("inline T spvSubgroupRotate(T value, ushort delta)");
  6363. begin_scope();
  6364. if (msl_options.use_quadgroup_operation())
  6365. statement("return quad_shuffle_rotate_down(value, delta);");
  6366. else
  6367. statement("return simd_shuffle_rotate_down(value, delta);");
  6368. end_scope();
  6369. statement("");
  6370. statement("template<>");
  6371. statement("inline bool spvSubgroupRotate(bool value, ushort delta)");
  6372. begin_scope();
  6373. if (msl_options.use_quadgroup_operation())
  6374. statement("return !!quad_shuffle_rotate_down((ushort)value, delta);");
  6375. else
  6376. statement("return !!simd_shuffle_rotate_down((ushort)value, delta);");
  6377. end_scope();
  6378. statement("");
  6379. statement("template<uint N>");
  6380. statement("inline vec<bool, N> spvSubgroupRotate(vec<bool, N> value, ushort delta)");
  6381. begin_scope();
  6382. if (msl_options.use_quadgroup_operation())
  6383. statement("return (vec<bool, N>)quad_shuffle_rotate_down((vec<ushort, N>)value, delta);");
  6384. else
  6385. statement("return (vec<bool, N>)simd_shuffle_rotate_down((vec<ushort, N>)value, delta);");
  6386. end_scope();
  6387. statement("");
  6388. break;
  6389. // C++ disallows partial specializations of function templates,
  6390. // hence the use of a struct.
  6391. // clang-format off
  6392. #define FUNC_SUBGROUP_CLUSTERED(spv, msl, combine, op, ident) \
  6393. case SPVFuncImplSubgroupClustered##spv: \
  6394. statement("template<uint N, uint offset>"); \
  6395. statement("struct spvClustered" #spv "Detail;"); \
  6396. statement(""); \
  6397. statement("// Base cases"); \
  6398. statement("template<>"); \
  6399. statement("struct spvClustered" #spv "Detail<1, 0>"); \
  6400. begin_scope(); \
  6401. statement("template<typename T>"); \
  6402. statement("static T op(T value, uint)"); \
  6403. begin_scope(); \
  6404. statement("return value;"); \
  6405. end_scope(); \
  6406. end_scope_decl(); \
  6407. statement(""); \
  6408. statement("template<uint offset>"); \
  6409. statement("struct spvClustered" #spv "Detail<1, offset>"); \
  6410. begin_scope(); \
  6411. statement("template<typename T>"); \
  6412. statement("static T op(T value, uint lid)"); \
  6413. begin_scope(); \
  6414. statement("// If the target lane is inactive, then return identity."); \
  6415. if (msl_options.use_quadgroup_operation()) \
  6416. statement("if (!extract_bits((quad_vote::vote_t)quad_active_threads_mask(), (lid ^ offset), 1))"); \
  6417. else \
  6418. statement("if (!extract_bits(as_type<uint2>((simd_vote::vote_t)simd_active_threads_mask())[(lid ^ offset) / 32], (lid ^ offset) % 32, 1))"); \
  6419. statement(" return " #ident ";"); \
  6420. if (msl_options.use_quadgroup_operation()) \
  6421. statement("return quad_shuffle_xor(value, offset);"); \
  6422. else \
  6423. statement("return simd_shuffle_xor(value, offset);"); \
  6424. end_scope(); \
  6425. end_scope_decl(); \
  6426. statement(""); \
  6427. statement("template<>"); \
  6428. statement("struct spvClustered" #spv "Detail<4, 0>"); \
  6429. begin_scope(); \
  6430. statement("template<typename T>"); \
  6431. statement("static T op(T value, uint)"); \
  6432. begin_scope(); \
  6433. statement("return quad_" #msl "(value);"); \
  6434. end_scope(); \
  6435. end_scope_decl(); \
  6436. statement(""); \
  6437. statement("template<uint offset>"); \
  6438. statement("struct spvClustered" #spv "Detail<4, offset>"); \
  6439. begin_scope(); \
  6440. statement("template<typename T>"); \
  6441. statement("static T op(T value, uint lid)"); \
  6442. begin_scope(); \
  6443. statement("// Here, we care if any of the lanes in the quad are active."); \
  6444. 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);"); \
  6445. statement("if (!quad_mask)"); \
  6446. statement(" return " #ident ";"); \
  6447. statement("// But we need to make sure we shuffle from an active lane."); \
  6448. if (msl_options.use_quadgroup_operation()) \
  6449. SPIRV_CROSS_THROW("Subgroup size with quadgroup operation cannot exceed 4."); \
  6450. else \
  6451. statement("return simd_shuffle(quad_" #msl "(value), ((lid ^ offset) & ~3) | ctz(quad_mask));"); \
  6452. end_scope(); \
  6453. end_scope_decl(); \
  6454. statement(""); \
  6455. statement("// General case"); \
  6456. statement("template<uint N, uint offset>"); \
  6457. statement("struct spvClustered" #spv "Detail"); \
  6458. begin_scope(); \
  6459. statement("template<typename T>"); \
  6460. statement("static T op(T value, uint lid)"); \
  6461. begin_scope(); \
  6462. 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)") ";"); \
  6463. end_scope(); \
  6464. end_scope_decl(); \
  6465. statement(""); \
  6466. statement("template<uint N, typename T>"); \
  6467. statement("T spvClustered_" #msl "(T value, uint lid)"); \
  6468. begin_scope(); \
  6469. statement("return spvClustered" #spv "Detail<N, 0>::op(value, lid);"); \
  6470. end_scope(); \
  6471. statement(""); \
  6472. break
  6473. #define BINOP(msl, op, l, r) l " " #op " " r
  6474. #define BINFUNC(msl, op, l, r) #msl "(" l ", " r ")"
  6475. FUNC_SUBGROUP_CLUSTERED(Add, sum, BINOP, +, 0);
  6476. FUNC_SUBGROUP_CLUSTERED(Mul, product, BINOP, *, 1);
  6477. FUNC_SUBGROUP_CLUSTERED(Min, min, BINFUNC, , numeric_limits<T>::max());
  6478. FUNC_SUBGROUP_CLUSTERED(Max, max, BINFUNC, , numeric_limits<T>::min());
  6479. FUNC_SUBGROUP_CLUSTERED(And, and, BINOP, &, ~T(0));
  6480. FUNC_SUBGROUP_CLUSTERED(Or, or, BINOP, |, 0);
  6481. FUNC_SUBGROUP_CLUSTERED(Xor, xor, BINOP, ^, 0);
  6482. // clang-format on
  6483. #undef FUNC_SUBGROUP_CLUSTERED
  6484. #undef BINOP
  6485. #undef BINFUNC
  6486. case SPVFuncImplQuadBroadcast:
  6487. statement("template<typename T>");
  6488. statement("inline T spvQuadBroadcast(T value, uint lane)");
  6489. begin_scope();
  6490. statement("return quad_broadcast(value, lane);");
  6491. end_scope();
  6492. statement("");
  6493. statement("template<>");
  6494. statement("inline bool spvQuadBroadcast(bool value, uint lane)");
  6495. begin_scope();
  6496. statement("return !!quad_broadcast((ushort)value, lane);");
  6497. end_scope();
  6498. statement("");
  6499. statement("template<uint N>");
  6500. statement("inline vec<bool, N> spvQuadBroadcast(vec<bool, N> value, uint lane)");
  6501. begin_scope();
  6502. statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);");
  6503. end_scope();
  6504. statement("");
  6505. break;
  6506. case SPVFuncImplQuadSwap:
  6507. // We can implement this easily based on the following table giving
  6508. // the target lane ID from the direction and current lane ID:
  6509. // Direction
  6510. // | 0 | 1 | 2 |
  6511. // ---+---+---+---+
  6512. // L 0 | 1 2 3
  6513. // a 1 | 0 3 2
  6514. // n 2 | 3 0 1
  6515. // e 3 | 2 1 0
  6516. // Notice that target = source ^ (direction + 1).
  6517. statement("template<typename T>");
  6518. statement("inline T spvQuadSwap(T value, uint dir)");
  6519. begin_scope();
  6520. statement("return quad_shuffle_xor(value, dir + 1);");
  6521. end_scope();
  6522. statement("");
  6523. statement("template<>");
  6524. statement("inline bool spvQuadSwap(bool value, uint dir)");
  6525. begin_scope();
  6526. statement("return !!quad_shuffle_xor((ushort)value, dir + 1);");
  6527. end_scope();
  6528. statement("");
  6529. statement("template<uint N>");
  6530. statement("inline vec<bool, N> spvQuadSwap(vec<bool, N> value, uint dir)");
  6531. begin_scope();
  6532. statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, dir + 1);");
  6533. end_scope();
  6534. statement("");
  6535. break;
  6536. case SPVFuncImplReflectScalar:
  6537. // Metal does not support scalar versions of these functions.
  6538. // Ensure fast-math is disabled to match Vulkan results.
  6539. statement("template<typename T>");
  6540. statement("[[clang::optnone]] T spvReflect(T i, T n)");
  6541. begin_scope();
  6542. statement("return i - T(2) * i * n * n;");
  6543. end_scope();
  6544. statement("");
  6545. break;
  6546. case SPVFuncImplRefractScalar:
  6547. // Metal does not support scalar versions of these functions.
  6548. statement("template<typename T>");
  6549. statement("inline T spvRefract(T i, T n, T eta)");
  6550. begin_scope();
  6551. statement("T NoI = n * i;");
  6552. statement("T NoI2 = NoI * NoI;");
  6553. statement("T k = T(1) - eta * eta * (T(1) - NoI2);");
  6554. statement("if (k < T(0))");
  6555. begin_scope();
  6556. statement("return T(0);");
  6557. end_scope();
  6558. statement("else");
  6559. begin_scope();
  6560. statement("return eta * i - (eta * NoI + sqrt(k)) * n;");
  6561. end_scope();
  6562. end_scope();
  6563. statement("");
  6564. break;
  6565. case SPVFuncImplFaceForwardScalar:
  6566. // Metal does not support scalar versions of these functions.
  6567. statement("template<typename T>");
  6568. statement("inline T spvFaceForward(T n, T i, T nref)");
  6569. begin_scope();
  6570. statement("return i * nref < T(0) ? n : -n;");
  6571. end_scope();
  6572. statement("");
  6573. break;
  6574. case SPVFuncImplChromaReconstructNearest2Plane:
  6575. statement("template<typename T, typename... LodOptions>");
  6576. statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, sampler "
  6577. "samp, float2 coord, LodOptions... options)");
  6578. begin_scope();
  6579. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6580. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6581. statement("ycbcr.br = plane1.sample(samp, coord, options...).rg;");
  6582. statement("return ycbcr;");
  6583. end_scope();
  6584. statement("");
  6585. break;
  6586. case SPVFuncImplChromaReconstructNearest3Plane:
  6587. statement("template<typename T, typename... LodOptions>");
  6588. statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, "
  6589. "texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6590. begin_scope();
  6591. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6592. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6593. statement("ycbcr.b = plane1.sample(samp, coord, options...).r;");
  6594. statement("ycbcr.r = plane2.sample(samp, coord, options...).r;");
  6595. statement("return ycbcr;");
  6596. end_scope();
  6597. statement("");
  6598. break;
  6599. case SPVFuncImplChromaReconstructLinear422CositedEven2Plane:
  6600. statement("template<typename T, typename... LodOptions>");
  6601. statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> "
  6602. "plane1, sampler samp, float2 coord, LodOptions... options)");
  6603. begin_scope();
  6604. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6605. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6606. statement("if (fract(coord.x * plane1.get_width()) != 0.0)");
  6607. begin_scope();
  6608. statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, options...), "
  6609. "plane1.sample(samp, coord, options..., int2(1, 0)), 0.5).rg);");
  6610. end_scope();
  6611. statement("else");
  6612. begin_scope();
  6613. statement("ycbcr.br = plane1.sample(samp, coord, options...).rg;");
  6614. end_scope();
  6615. statement("return ycbcr;");
  6616. end_scope();
  6617. statement("");
  6618. break;
  6619. case SPVFuncImplChromaReconstructLinear422CositedEven3Plane:
  6620. statement("template<typename T, typename... LodOptions>");
  6621. statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> "
  6622. "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6623. begin_scope();
  6624. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6625. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6626. statement("if (fract(coord.x * plane1.get_width()) != 0.0)");
  6627. begin_scope();
  6628. statement("ycbcr.b = T(mix(plane1.sample(samp, coord, options...), "
  6629. "plane1.sample(samp, coord, options..., int2(1, 0)), 0.5).r);");
  6630. statement("ycbcr.r = T(mix(plane2.sample(samp, coord, options...), "
  6631. "plane2.sample(samp, coord, options..., int2(1, 0)), 0.5).r);");
  6632. end_scope();
  6633. statement("else");
  6634. begin_scope();
  6635. statement("ycbcr.b = plane1.sample(samp, coord, options...).r;");
  6636. statement("ycbcr.r = plane2.sample(samp, coord, options...).r;");
  6637. end_scope();
  6638. statement("return ycbcr;");
  6639. end_scope();
  6640. statement("");
  6641. break;
  6642. case SPVFuncImplChromaReconstructLinear422Midpoint2Plane:
  6643. statement("template<typename T, typename... LodOptions>");
  6644. statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> "
  6645. "plane1, sampler samp, float2 coord, LodOptions... options)");
  6646. begin_scope();
  6647. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6648. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6649. statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);");
  6650. statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, options...), "
  6651. "plane1.sample(samp, coord, options..., offs), 0.25).rg);");
  6652. statement("return ycbcr;");
  6653. end_scope();
  6654. statement("");
  6655. break;
  6656. case SPVFuncImplChromaReconstructLinear422Midpoint3Plane:
  6657. statement("template<typename T, typename... LodOptions>");
  6658. statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> "
  6659. "plane1, texture2d<T> plane2, sampler 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("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);");
  6664. statement("ycbcr.b = T(mix(plane1.sample(samp, coord, options...), "
  6665. "plane1.sample(samp, coord, options..., offs), 0.25).r);");
  6666. statement("ycbcr.r = T(mix(plane2.sample(samp, coord, options...), "
  6667. "plane2.sample(samp, coord, options..., offs), 0.25).r);");
  6668. statement("return ycbcr;");
  6669. end_scope();
  6670. statement("");
  6671. break;
  6672. case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane:
  6673. statement("template<typename T, typename... LodOptions>");
  6674. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, "
  6675. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6676. begin_scope();
  6677. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6678. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6679. statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);");
  6680. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6681. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6682. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6683. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6684. statement("return ycbcr;");
  6685. end_scope();
  6686. statement("");
  6687. break;
  6688. case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane:
  6689. statement("template<typename T, typename... LodOptions>");
  6690. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, "
  6691. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6692. begin_scope();
  6693. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6694. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6695. statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);");
  6696. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6697. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6698. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6699. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6700. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6701. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6702. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6703. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6704. statement("return ycbcr;");
  6705. end_scope();
  6706. statement("");
  6707. break;
  6708. case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane:
  6709. statement("template<typename T, typename... LodOptions>");
  6710. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, "
  6711. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6712. begin_scope();
  6713. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6714. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6715. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6716. "0)) * 0.5);");
  6717. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6718. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6719. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6720. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6721. statement("return ycbcr;");
  6722. end_scope();
  6723. statement("");
  6724. break;
  6725. case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane:
  6726. statement("template<typename T, typename... LodOptions>");
  6727. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, "
  6728. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6729. begin_scope();
  6730. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6731. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6732. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6733. "0)) * 0.5);");
  6734. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6735. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6736. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6737. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6738. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6739. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6740. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6741. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6742. statement("return ycbcr;");
  6743. end_scope();
  6744. statement("");
  6745. break;
  6746. case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane:
  6747. statement("template<typename T, typename... LodOptions>");
  6748. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, "
  6749. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6750. begin_scope();
  6751. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6752. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6753. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, "
  6754. "0.5)) * 0.5);");
  6755. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6756. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6757. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6758. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6759. statement("return ycbcr;");
  6760. end_scope();
  6761. statement("");
  6762. break;
  6763. case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane:
  6764. statement("template<typename T, typename... LodOptions>");
  6765. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, "
  6766. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6767. begin_scope();
  6768. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6769. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6770. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, "
  6771. "0.5)) * 0.5);");
  6772. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6773. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6774. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6775. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6776. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6777. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6778. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6779. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6780. statement("return ycbcr;");
  6781. end_scope();
  6782. statement("");
  6783. break;
  6784. case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane:
  6785. statement("template<typename T, typename... LodOptions>");
  6786. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, "
  6787. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6788. begin_scope();
  6789. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6790. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6791. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6792. "0.5)) * 0.5);");
  6793. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6794. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6795. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6796. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6797. statement("return ycbcr;");
  6798. end_scope();
  6799. statement("");
  6800. break;
  6801. case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane:
  6802. statement("template<typename T, typename... LodOptions>");
  6803. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, "
  6804. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6805. begin_scope();
  6806. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6807. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6808. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6809. "0.5)) * 0.5);");
  6810. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6811. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6812. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6813. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6814. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6815. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6816. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6817. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6818. statement("return ycbcr;");
  6819. end_scope();
  6820. statement("");
  6821. break;
  6822. case SPVFuncImplExpandITUFullRange:
  6823. statement("template<typename T>");
  6824. statement("inline vec<T, 4> spvExpandITUFullRange(vec<T, 4> ycbcr, int n)");
  6825. begin_scope();
  6826. statement("ycbcr.br -= exp2(T(n-1))/(exp2(T(n))-1);");
  6827. statement("return ycbcr;");
  6828. end_scope();
  6829. statement("");
  6830. break;
  6831. case SPVFuncImplExpandITUNarrowRange:
  6832. statement("template<typename T>");
  6833. statement("inline vec<T, 4> spvExpandITUNarrowRange(vec<T, 4> ycbcr, int n)");
  6834. begin_scope();
  6835. statement("ycbcr.g = (ycbcr.g * (exp2(T(n)) - 1) - ldexp(T(16), n - 8))/ldexp(T(219), n - 8);");
  6836. statement("ycbcr.br = (ycbcr.br * (exp2(T(n)) - 1) - ldexp(T(128), n - 8))/ldexp(T(224), n - 8);");
  6837. statement("return ycbcr;");
  6838. end_scope();
  6839. statement("");
  6840. break;
  6841. case SPVFuncImplConvertYCbCrBT709:
  6842. statement("// cf. Khronos Data Format Specification, section 15.1.1");
  6843. statement("constant float3x3 spvBT709Factors = {{1, 1, 1}, {0, -0.13397432/0.7152, 1.8556}, {1.5748, "
  6844. "-0.33480248/0.7152, 0}};");
  6845. statement("");
  6846. statement("template<typename T>");
  6847. statement("inline vec<T, 4> spvConvertYCbCrBT709(vec<T, 4> ycbcr)");
  6848. begin_scope();
  6849. statement("vec<T, 4> rgba;");
  6850. statement("rgba.rgb = vec<T, 3>(spvBT709Factors * ycbcr.gbr);");
  6851. statement("rgba.a = ycbcr.a;");
  6852. statement("return rgba;");
  6853. end_scope();
  6854. statement("");
  6855. break;
  6856. case SPVFuncImplConvertYCbCrBT601:
  6857. statement("// cf. Khronos Data Format Specification, section 15.1.2");
  6858. statement("constant float3x3 spvBT601Factors = {{1, 1, 1}, {0, -0.202008/0.587, 1.772}, {1.402, "
  6859. "-0.419198/0.587, 0}};");
  6860. statement("");
  6861. statement("template<typename T>");
  6862. statement("inline vec<T, 4> spvConvertYCbCrBT601(vec<T, 4> ycbcr)");
  6863. begin_scope();
  6864. statement("vec<T, 4> rgba;");
  6865. statement("rgba.rgb = vec<T, 3>(spvBT601Factors * ycbcr.gbr);");
  6866. statement("rgba.a = ycbcr.a;");
  6867. statement("return rgba;");
  6868. end_scope();
  6869. statement("");
  6870. break;
  6871. case SPVFuncImplConvertYCbCrBT2020:
  6872. statement("// cf. Khronos Data Format Specification, section 15.1.3");
  6873. statement("constant float3x3 spvBT2020Factors = {{1, 1, 1}, {0, -0.11156702/0.6780, 1.8814}, {1.4746, "
  6874. "-0.38737742/0.6780, 0}};");
  6875. statement("");
  6876. statement("template<typename T>");
  6877. statement("inline vec<T, 4> spvConvertYCbCrBT2020(vec<T, 4> ycbcr)");
  6878. begin_scope();
  6879. statement("vec<T, 4> rgba;");
  6880. statement("rgba.rgb = vec<T, 3>(spvBT2020Factors * ycbcr.gbr);");
  6881. statement("rgba.a = ycbcr.a;");
  6882. statement("return rgba;");
  6883. end_scope();
  6884. statement("");
  6885. break;
  6886. case SPVFuncImplDynamicImageSampler:
  6887. statement("enum class spvFormatResolution");
  6888. begin_scope();
  6889. statement("_444 = 0,");
  6890. statement("_422,");
  6891. statement("_420");
  6892. end_scope_decl();
  6893. statement("");
  6894. statement("enum class spvChromaFilter");
  6895. begin_scope();
  6896. statement("nearest = 0,");
  6897. statement("linear");
  6898. end_scope_decl();
  6899. statement("");
  6900. statement("enum class spvXChromaLocation");
  6901. begin_scope();
  6902. statement("cosited_even = 0,");
  6903. statement("midpoint");
  6904. end_scope_decl();
  6905. statement("");
  6906. statement("enum class spvYChromaLocation");
  6907. begin_scope();
  6908. statement("cosited_even = 0,");
  6909. statement("midpoint");
  6910. end_scope_decl();
  6911. statement("");
  6912. statement("enum class spvYCbCrModelConversion");
  6913. begin_scope();
  6914. statement("rgb_identity = 0,");
  6915. statement("ycbcr_identity,");
  6916. statement("ycbcr_bt_709,");
  6917. statement("ycbcr_bt_601,");
  6918. statement("ycbcr_bt_2020");
  6919. end_scope_decl();
  6920. statement("");
  6921. statement("enum class spvYCbCrRange");
  6922. begin_scope();
  6923. statement("itu_full = 0,");
  6924. statement("itu_narrow");
  6925. end_scope_decl();
  6926. statement("");
  6927. statement("struct spvComponentBits");
  6928. begin_scope();
  6929. statement("constexpr explicit spvComponentBits(int v) thread : value(v) {}");
  6930. statement("uchar value : 6;");
  6931. end_scope_decl();
  6932. statement("// A class corresponding to metal::sampler which holds sampler");
  6933. statement("// Y'CbCr conversion info.");
  6934. statement("struct spvYCbCrSampler");
  6935. begin_scope();
  6936. statement("constexpr spvYCbCrSampler() thread : val(build()) {}");
  6937. statement("template<typename... Ts>");
  6938. statement("constexpr spvYCbCrSampler(Ts... t) thread : val(build(t...)) {}");
  6939. statement("constexpr spvYCbCrSampler(const thread spvYCbCrSampler& s) thread = default;");
  6940. statement("");
  6941. statement("spvFormatResolution get_resolution() const thread");
  6942. begin_scope();
  6943. statement("return spvFormatResolution((val & resolution_mask) >> resolution_base);");
  6944. end_scope();
  6945. statement("spvChromaFilter get_chroma_filter() const thread");
  6946. begin_scope();
  6947. statement("return spvChromaFilter((val & chroma_filter_mask) >> chroma_filter_base);");
  6948. end_scope();
  6949. statement("spvXChromaLocation get_x_chroma_offset() const thread");
  6950. begin_scope();
  6951. statement("return spvXChromaLocation((val & x_chroma_off_mask) >> x_chroma_off_base);");
  6952. end_scope();
  6953. statement("spvYChromaLocation get_y_chroma_offset() const thread");
  6954. begin_scope();
  6955. statement("return spvYChromaLocation((val & y_chroma_off_mask) >> y_chroma_off_base);");
  6956. end_scope();
  6957. statement("spvYCbCrModelConversion get_ycbcr_model() const thread");
  6958. begin_scope();
  6959. statement("return spvYCbCrModelConversion((val & ycbcr_model_mask) >> ycbcr_model_base);");
  6960. end_scope();
  6961. statement("spvYCbCrRange get_ycbcr_range() const thread");
  6962. begin_scope();
  6963. statement("return spvYCbCrRange((val & ycbcr_range_mask) >> ycbcr_range_base);");
  6964. end_scope();
  6965. statement("int get_bpc() const thread { return (val & bpc_mask) >> bpc_base; }");
  6966. statement("");
  6967. statement("private:");
  6968. statement("ushort val;");
  6969. statement("");
  6970. statement("constexpr static constant ushort resolution_bits = 2;");
  6971. statement("constexpr static constant ushort chroma_filter_bits = 2;");
  6972. statement("constexpr static constant ushort x_chroma_off_bit = 1;");
  6973. statement("constexpr static constant ushort y_chroma_off_bit = 1;");
  6974. statement("constexpr static constant ushort ycbcr_model_bits = 3;");
  6975. statement("constexpr static constant ushort ycbcr_range_bit = 1;");
  6976. statement("constexpr static constant ushort bpc_bits = 6;");
  6977. statement("");
  6978. statement("constexpr static constant ushort resolution_base = 0;");
  6979. statement("constexpr static constant ushort chroma_filter_base = 2;");
  6980. statement("constexpr static constant ushort x_chroma_off_base = 4;");
  6981. statement("constexpr static constant ushort y_chroma_off_base = 5;");
  6982. statement("constexpr static constant ushort ycbcr_model_base = 6;");
  6983. statement("constexpr static constant ushort ycbcr_range_base = 9;");
  6984. statement("constexpr static constant ushort bpc_base = 10;");
  6985. statement("");
  6986. statement(
  6987. "constexpr static constant ushort resolution_mask = ((1 << resolution_bits) - 1) << resolution_base;");
  6988. statement("constexpr static constant ushort chroma_filter_mask = ((1 << chroma_filter_bits) - 1) << "
  6989. "chroma_filter_base;");
  6990. statement("constexpr static constant ushort x_chroma_off_mask = ((1 << x_chroma_off_bit) - 1) << "
  6991. "x_chroma_off_base;");
  6992. statement("constexpr static constant ushort y_chroma_off_mask = ((1 << y_chroma_off_bit) - 1) << "
  6993. "y_chroma_off_base;");
  6994. statement("constexpr static constant ushort ycbcr_model_mask = ((1 << ycbcr_model_bits) - 1) << "
  6995. "ycbcr_model_base;");
  6996. statement("constexpr static constant ushort ycbcr_range_mask = ((1 << ycbcr_range_bit) - 1) << "
  6997. "ycbcr_range_base;");
  6998. statement("constexpr static constant ushort bpc_mask = ((1 << bpc_bits) - 1) << bpc_base;");
  6999. statement("");
  7000. statement("static constexpr ushort build()");
  7001. begin_scope();
  7002. statement("return 0;");
  7003. end_scope();
  7004. statement("");
  7005. statement("template<typename... Ts>");
  7006. statement("static constexpr ushort build(spvFormatResolution res, Ts... t)");
  7007. begin_scope();
  7008. statement("return (ushort(res) << resolution_base) | (build(t...) & ~resolution_mask);");
  7009. end_scope();
  7010. statement("");
  7011. statement("template<typename... Ts>");
  7012. statement("static constexpr ushort build(spvChromaFilter filt, Ts... t)");
  7013. begin_scope();
  7014. statement("return (ushort(filt) << chroma_filter_base) | (build(t...) & ~chroma_filter_mask);");
  7015. end_scope();
  7016. statement("");
  7017. statement("template<typename... Ts>");
  7018. statement("static constexpr ushort build(spvXChromaLocation loc, Ts... t)");
  7019. begin_scope();
  7020. statement("return (ushort(loc) << x_chroma_off_base) | (build(t...) & ~x_chroma_off_mask);");
  7021. end_scope();
  7022. statement("");
  7023. statement("template<typename... Ts>");
  7024. statement("static constexpr ushort build(spvYChromaLocation loc, Ts... t)");
  7025. begin_scope();
  7026. statement("return (ushort(loc) << y_chroma_off_base) | (build(t...) & ~y_chroma_off_mask);");
  7027. end_scope();
  7028. statement("");
  7029. statement("template<typename... Ts>");
  7030. statement("static constexpr ushort build(spvYCbCrModelConversion model, Ts... t)");
  7031. begin_scope();
  7032. statement("return (ushort(model) << ycbcr_model_base) | (build(t...) & ~ycbcr_model_mask);");
  7033. end_scope();
  7034. statement("");
  7035. statement("template<typename... Ts>");
  7036. statement("static constexpr ushort build(spvYCbCrRange range, Ts... t)");
  7037. begin_scope();
  7038. statement("return (ushort(range) << ycbcr_range_base) | (build(t...) & ~ycbcr_range_mask);");
  7039. end_scope();
  7040. statement("");
  7041. statement("template<typename... Ts>");
  7042. statement("static constexpr ushort build(spvComponentBits bpc, Ts... t)");
  7043. begin_scope();
  7044. statement("return (ushort(bpc.value) << bpc_base) | (build(t...) & ~bpc_mask);");
  7045. end_scope();
  7046. end_scope_decl();
  7047. statement("");
  7048. statement("// A class which can hold up to three textures and a sampler, including");
  7049. statement("// Y'CbCr conversion info, used to pass combined image-samplers");
  7050. statement("// dynamically to functions.");
  7051. statement("template<typename T>");
  7052. statement("struct spvDynamicImageSampler");
  7053. begin_scope();
  7054. statement("texture2d<T> plane0;");
  7055. statement("texture2d<T> plane1;");
  7056. statement("texture2d<T> plane2;");
  7057. statement("sampler samp;");
  7058. statement("spvYCbCrSampler ycbcr_samp;");
  7059. statement("uint swizzle = 0;");
  7060. statement("");
  7061. if (msl_options.swizzle_texture_samples)
  7062. {
  7063. statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, uint sw) thread :");
  7064. statement(" plane0(tex), samp(samp), swizzle(sw) {}");
  7065. }
  7066. else
  7067. {
  7068. statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp) thread :");
  7069. statement(" plane0(tex), samp(samp) {}");
  7070. }
  7071. statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, spvYCbCrSampler ycbcr_samp, "
  7072. "uint sw) thread :");
  7073. statement(" plane0(tex), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}");
  7074. statement("constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1,");
  7075. statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :");
  7076. statement(" plane0(plane0), plane1(plane1), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}");
  7077. statement(
  7078. "constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1, texture2d<T> plane2,");
  7079. statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :");
  7080. statement(" plane0(plane0), plane1(plane1), plane2(plane2), samp(samp), ycbcr_samp(ycbcr_samp), "
  7081. "swizzle(sw) {}");
  7082. statement("");
  7083. // XXX This is really hard to follow... I've left comments to make it a bit easier.
  7084. statement("template<typename... LodOptions>");
  7085. statement("vec<T, 4> do_sample(float2 coord, LodOptions... options) const thread");
  7086. begin_scope();
  7087. statement("if (!is_null_texture(plane1))");
  7088. begin_scope();
  7089. statement("if (ycbcr_samp.get_resolution() == spvFormatResolution::_444 ||");
  7090. statement(" ycbcr_samp.get_chroma_filter() == spvChromaFilter::nearest)");
  7091. begin_scope();
  7092. statement("if (!is_null_texture(plane2))");
  7093. statement(" return spvChromaReconstructNearest(plane0, plane1, plane2, samp, coord, options...);");
  7094. statement("return spvChromaReconstructNearest(plane0, plane1, samp, coord, options...);");
  7095. end_scope(); // if (resolution == 422 || chroma_filter == nearest)
  7096. statement("switch (ycbcr_samp.get_resolution())");
  7097. begin_scope();
  7098. statement("case spvFormatResolution::_444: break;");
  7099. statement("case spvFormatResolution::_422:");
  7100. begin_scope();
  7101. statement("switch (ycbcr_samp.get_x_chroma_offset())");
  7102. begin_scope();
  7103. statement("case spvXChromaLocation::cosited_even:");
  7104. statement(" if (!is_null_texture(plane2))");
  7105. statement(" return spvChromaReconstructLinear422CositedEven(");
  7106. statement(" plane0, plane1, plane2, samp,");
  7107. statement(" coord, options...);");
  7108. statement(" return spvChromaReconstructLinear422CositedEven(");
  7109. statement(" plane0, plane1, samp, coord,");
  7110. statement(" options...);");
  7111. statement("case spvXChromaLocation::midpoint:");
  7112. statement(" if (!is_null_texture(plane2))");
  7113. statement(" return spvChromaReconstructLinear422Midpoint(");
  7114. statement(" plane0, plane1, plane2, samp,");
  7115. statement(" coord, options...);");
  7116. statement(" return spvChromaReconstructLinear422Midpoint(");
  7117. statement(" plane0, plane1, samp, coord,");
  7118. statement(" options...);");
  7119. end_scope(); // switch (x_chroma_offset)
  7120. end_scope(); // case 422:
  7121. statement("case spvFormatResolution::_420:");
  7122. begin_scope();
  7123. statement("switch (ycbcr_samp.get_x_chroma_offset())");
  7124. begin_scope();
  7125. statement("case spvXChromaLocation::cosited_even:");
  7126. begin_scope();
  7127. statement("switch (ycbcr_samp.get_y_chroma_offset())");
  7128. begin_scope();
  7129. statement("case spvYChromaLocation::cosited_even:");
  7130. statement(" if (!is_null_texture(plane2))");
  7131. statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven(");
  7132. statement(" plane0, plane1, plane2, samp,");
  7133. statement(" coord, options...);");
  7134. statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven(");
  7135. statement(" plane0, plane1, samp, coord,");
  7136. statement(" options...);");
  7137. statement("case spvYChromaLocation::midpoint:");
  7138. statement(" if (!is_null_texture(plane2))");
  7139. statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint(");
  7140. statement(" plane0, plane1, plane2, samp,");
  7141. statement(" coord, options...);");
  7142. statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint(");
  7143. statement(" plane0, plane1, samp, coord,");
  7144. statement(" options...);");
  7145. end_scope(); // switch (y_chroma_offset)
  7146. end_scope(); // case x::cosited_even:
  7147. statement("case spvXChromaLocation::midpoint:");
  7148. begin_scope();
  7149. statement("switch (ycbcr_samp.get_y_chroma_offset())");
  7150. begin_scope();
  7151. statement("case spvYChromaLocation::cosited_even:");
  7152. statement(" if (!is_null_texture(plane2))");
  7153. statement(" return spvChromaReconstructLinear420XMidpointYCositedEven(");
  7154. statement(" plane0, plane1, plane2, samp,");
  7155. statement(" coord, options...);");
  7156. statement(" return spvChromaReconstructLinear420XMidpointYCositedEven(");
  7157. statement(" plane0, plane1, samp, coord,");
  7158. statement(" options...);");
  7159. statement("case spvYChromaLocation::midpoint:");
  7160. statement(" if (!is_null_texture(plane2))");
  7161. statement(" return spvChromaReconstructLinear420XMidpointYMidpoint(");
  7162. statement(" plane0, plane1, plane2, samp,");
  7163. statement(" coord, options...);");
  7164. statement(" return spvChromaReconstructLinear420XMidpointYMidpoint(");
  7165. statement(" plane0, plane1, samp, coord,");
  7166. statement(" options...);");
  7167. end_scope(); // switch (y_chroma_offset)
  7168. end_scope(); // case x::midpoint
  7169. end_scope(); // switch (x_chroma_offset)
  7170. end_scope(); // case 420:
  7171. end_scope(); // switch (resolution)
  7172. end_scope(); // if (multiplanar)
  7173. statement("return plane0.sample(samp, coord, options...);");
  7174. end_scope(); // do_sample()
  7175. statement("template <typename... LodOptions>");
  7176. statement("vec<T, 4> sample(float2 coord, LodOptions... options) const thread");
  7177. begin_scope();
  7178. statement("vec<T, 4> s = spvTextureSwizzle(do_sample(coord, options...), swizzle);");
  7179. statement("if (ycbcr_samp.get_ycbcr_model() == spvYCbCrModelConversion::rgb_identity)");
  7180. statement(" return s;");
  7181. statement("");
  7182. statement("switch (ycbcr_samp.get_ycbcr_range())");
  7183. begin_scope();
  7184. statement("case spvYCbCrRange::itu_full:");
  7185. statement(" s = spvExpandITUFullRange(s, ycbcr_samp.get_bpc());");
  7186. statement(" break;");
  7187. statement("case spvYCbCrRange::itu_narrow:");
  7188. statement(" s = spvExpandITUNarrowRange(s, ycbcr_samp.get_bpc());");
  7189. statement(" break;");
  7190. end_scope();
  7191. statement("");
  7192. statement("switch (ycbcr_samp.get_ycbcr_model())");
  7193. begin_scope();
  7194. statement("case spvYCbCrModelConversion::rgb_identity:"); // Silence Clang warning
  7195. statement("case spvYCbCrModelConversion::ycbcr_identity:");
  7196. statement(" return s;");
  7197. statement("case spvYCbCrModelConversion::ycbcr_bt_709:");
  7198. statement(" return spvConvertYCbCrBT709(s);");
  7199. statement("case spvYCbCrModelConversion::ycbcr_bt_601:");
  7200. statement(" return spvConvertYCbCrBT601(s);");
  7201. statement("case spvYCbCrModelConversion::ycbcr_bt_2020:");
  7202. statement(" return spvConvertYCbCrBT2020(s);");
  7203. end_scope();
  7204. end_scope();
  7205. statement("");
  7206. // Sampler Y'CbCr conversion forbids offsets.
  7207. statement("vec<T, 4> sample(float2 coord, int2 offset) const thread");
  7208. begin_scope();
  7209. if (msl_options.swizzle_texture_samples)
  7210. statement("return spvTextureSwizzle(plane0.sample(samp, coord, offset), swizzle);");
  7211. else
  7212. statement("return plane0.sample(samp, coord, offset);");
  7213. end_scope();
  7214. statement("template<typename lod_options>");
  7215. statement("vec<T, 4> sample(float2 coord, lod_options options, int2 offset) const thread");
  7216. begin_scope();
  7217. if (msl_options.swizzle_texture_samples)
  7218. statement("return spvTextureSwizzle(plane0.sample(samp, coord, options, offset), swizzle);");
  7219. else
  7220. statement("return plane0.sample(samp, coord, options, offset);");
  7221. end_scope();
  7222. statement("#if __HAVE_MIN_LOD_CLAMP__");
  7223. statement("vec<T, 4> sample(float2 coord, bias b, min_lod_clamp min_lod, int2 offset) const thread");
  7224. begin_scope();
  7225. statement("return plane0.sample(samp, coord, b, min_lod, offset);");
  7226. end_scope();
  7227. statement(
  7228. "vec<T, 4> sample(float2 coord, gradient2d grad, min_lod_clamp min_lod, int2 offset) const thread");
  7229. begin_scope();
  7230. statement("return plane0.sample(samp, coord, grad, min_lod, offset);");
  7231. end_scope();
  7232. statement("#endif");
  7233. statement("");
  7234. // Y'CbCr conversion forbids all operations but sampling.
  7235. statement("vec<T, 4> read(uint2 coord, uint lod = 0) const thread");
  7236. begin_scope();
  7237. statement("return plane0.read(coord, lod);");
  7238. end_scope();
  7239. statement("");
  7240. statement("vec<T, 4> gather(float2 coord, int2 offset = int2(0), component c = component::x) const thread");
  7241. begin_scope();
  7242. if (msl_options.swizzle_texture_samples)
  7243. statement("return spvGatherSwizzle(plane0, samp, swizzle, c, coord, offset);");
  7244. else
  7245. statement("return plane0.gather(samp, coord, offset, c);");
  7246. end_scope();
  7247. end_scope_decl();
  7248. statement("");
  7249. break;
  7250. case SPVFuncImplRayQueryIntersectionParams:
  7251. statement("intersection_params spvMakeIntersectionParams(uint flags)");
  7252. begin_scope();
  7253. statement("intersection_params ip;");
  7254. statement("if ((flags & ", RayFlagsOpaqueKHRMask, ") != 0)");
  7255. statement(" ip.force_opacity(forced_opacity::opaque);");
  7256. statement("if ((flags & ", RayFlagsNoOpaqueKHRMask, ") != 0)");
  7257. statement(" ip.force_opacity(forced_opacity::non_opaque);");
  7258. statement("if ((flags & ", RayFlagsTerminateOnFirstHitKHRMask, ") != 0)");
  7259. statement(" ip.accept_any_intersection(true);");
  7260. // RayFlagsSkipClosestHitShaderKHRMask is not available in MSL
  7261. statement("if ((flags & ", RayFlagsCullBackFacingTrianglesKHRMask, ") != 0)");
  7262. statement(" ip.set_triangle_cull_mode(triangle_cull_mode::back);");
  7263. statement("if ((flags & ", RayFlagsCullFrontFacingTrianglesKHRMask, ") != 0)");
  7264. statement(" ip.set_triangle_cull_mode(triangle_cull_mode::front);");
  7265. statement("if ((flags & ", RayFlagsCullOpaqueKHRMask, ") != 0)");
  7266. statement(" ip.set_opacity_cull_mode(opacity_cull_mode::opaque);");
  7267. statement("if ((flags & ", RayFlagsCullNoOpaqueKHRMask, ") != 0)");
  7268. statement(" ip.set_opacity_cull_mode(opacity_cull_mode::non_opaque);");
  7269. statement("if ((flags & ", RayFlagsSkipTrianglesKHRMask, ") != 0)");
  7270. statement(" ip.set_geometry_cull_mode(geometry_cull_mode::triangle);");
  7271. statement("if ((flags & ", RayFlagsSkipAABBsKHRMask, ") != 0)");
  7272. statement(" ip.set_geometry_cull_mode(geometry_cull_mode::bounding_box);");
  7273. statement("return ip;");
  7274. end_scope();
  7275. statement("");
  7276. break;
  7277. case SPVFuncImplVariableDescriptor:
  7278. statement("template<typename T>");
  7279. statement("struct spvDescriptor");
  7280. begin_scope();
  7281. statement("T value;");
  7282. end_scope_decl();
  7283. statement("");
  7284. break;
  7285. case SPVFuncImplVariableSizedDescriptor:
  7286. statement("template<typename T>");
  7287. statement("struct spvBufferDescriptor;");
  7288. statement("");
  7289. statement("template<typename T>");
  7290. statement("struct spvBufferDescriptor<device T*>");
  7291. begin_scope();
  7292. statement("device T* value;");
  7293. statement("int length;");
  7294. statement("int padding;");
  7295. end_scope_decl();
  7296. statement("");
  7297. break;
  7298. case SPVFuncImplVariableDescriptorArray:
  7299. if (spv_function_implementations.count(SPVFuncImplVariableDescriptor) != 0)
  7300. {
  7301. statement("template<typename T>");
  7302. statement("struct spvDescriptorArray");
  7303. begin_scope();
  7304. statement("spvDescriptorArray(const device spvDescriptor<T>* ptr_) : ptr(&ptr_->value) {}");
  7305. statement("spvDescriptorArray(const device void *ptr_) : spvDescriptorArray(static_cast<const device spvDescriptor<T>*>(ptr_)) {}");
  7306. statement("const device T& operator [] (size_t i) const { return ptr[i]; }");
  7307. statement("const device T* ptr;");
  7308. end_scope_decl();
  7309. statement("");
  7310. }
  7311. else
  7312. {
  7313. statement("template<typename T>");
  7314. statement("struct spvDescriptorArray;");
  7315. statement("");
  7316. }
  7317. if (msl_options.runtime_array_rich_descriptor &&
  7318. spv_function_implementations.count(SPVFuncImplVariableSizedDescriptor) != 0)
  7319. {
  7320. statement("template<typename T>");
  7321. statement("struct spvDescriptorArray<device T*>");
  7322. begin_scope();
  7323. statement("spvDescriptorArray(const device spvBufferDescriptor<device T*>* ptr_) : ptr(ptr_) {}");
  7324. statement("spvDescriptorArray(const device void *ptr_) : spvDescriptorArray(static_cast<const device spvBufferDescriptor<device T*>*>(ptr_)) {}");
  7325. statement("device T* operator [] (size_t i) const { return ptr[i].value; }");
  7326. statement("int length(int i) const { return ptr[i].length; }");
  7327. statement("const device spvBufferDescriptor<device T*>* ptr;");
  7328. end_scope_decl();
  7329. statement("");
  7330. }
  7331. break;
  7332. case SPVFuncImplPaddedStd140:
  7333. // .data is used in access chain.
  7334. statement("template <typename T>");
  7335. statement("struct spvPaddedStd140 { alignas(16) T data; };");
  7336. statement("template <typename T, int n>");
  7337. statement("using spvPaddedStd140Matrix = spvPaddedStd140<T>[n];");
  7338. statement("");
  7339. break;
  7340. case SPVFuncImplReduceAdd:
  7341. // Metal doesn't support __builtin_reduce_add or simd_reduce_add, so we need this.
  7342. // Metal also doesn't support the other vector builtins, which would have been useful to make this a single template.
  7343. statement("template <typename T>");
  7344. statement("T reduce_add(vec<T, 2> v) { return v.x + v.y; }");
  7345. statement("template <typename T>");
  7346. statement("T reduce_add(vec<T, 3> v) { return v.x + v.y + v.z; }");
  7347. statement("template <typename T>");
  7348. statement("T reduce_add(vec<T, 4> v) { return v.x + v.y + v.z + v.w; }");
  7349. statement("");
  7350. break;
  7351. case SPVFuncImplImageFence:
  7352. statement("template <typename ImageT>");
  7353. statement("void spvImageFence(ImageT img) { img.fence(); }");
  7354. statement("");
  7355. break;
  7356. case SPVFuncImplTextureCast:
  7357. statement("template <typename T, typename U>");
  7358. statement("T spvTextureCast(U img)");
  7359. begin_scope();
  7360. // MSL complains if you try to cast the texture itself, but casting the reference type is ... ok? *shrug*
  7361. // Gotta go what you gotta do I suppose.
  7362. statement("return reinterpret_cast<thread const T &>(img);");
  7363. end_scope();
  7364. statement("");
  7365. break;
  7366. case SPVFuncImplMulExtended:
  7367. // Compiler may hit an internal error with mulhi, but doesn't when encapsulated for some reason.
  7368. statement("template<typename T, typename U, typename V>");
  7369. statement("[[clang::optnone]] T spvMulExtended(V l, V r)");
  7370. begin_scope();
  7371. statement("return T{U(l * r), U(mulhi(l, r))};");
  7372. end_scope();
  7373. statement("");
  7374. break;
  7375. case SPVFuncImplSetMeshOutputsEXT:
  7376. statement("void spvSetMeshOutputsEXT(uint gl_LocalInvocationIndex, threadgroup uint2& spvMeshSizes, uint vertexCount, uint primitiveCount)");
  7377. begin_scope();
  7378. statement("if (gl_LocalInvocationIndex == 0)");
  7379. begin_scope();
  7380. statement("spvMeshSizes.x = vertexCount;");
  7381. statement("spvMeshSizes.y = primitiveCount;");
  7382. end_scope();
  7383. end_scope();
  7384. statement("");
  7385. break;
  7386. case SPVFuncImplAssume:
  7387. statement_no_indent("#if defined(__has_builtin)");
  7388. statement_no_indent("#if !defined(SPV_ASSUME) && __has_builtin(__builtin_assume)");
  7389. statement_no_indent("#define SPV_ASSUME(x) __builtin_assume(x);");
  7390. statement_no_indent("#endif");
  7391. statement_no_indent("#if !defined(SPV_EXPECT) && __has_builtin(__builtin_expect)");
  7392. statement_no_indent("#define SPV_EXPECT(x, y) __builtin_expect(x, y);");
  7393. statement_no_indent("#endif");
  7394. statement_no_indent("#endif");
  7395. statement_no_indent("#ifndef SPV_ASSUME");
  7396. statement_no_indent("#define SPV_ASSUME(x)");
  7397. statement_no_indent("#endif");
  7398. statement_no_indent("#ifndef SPV_EXPECT");
  7399. statement_no_indent("#define SPV_EXPECT(x, y) x");
  7400. statement_no_indent("#endif");
  7401. break;
  7402. default:
  7403. break;
  7404. }
  7405. }
  7406. }
  7407. static string inject_top_level_storage_qualifier(const string &expr, const string &qualifier)
  7408. {
  7409. // Easier to do this through text munging since the qualifier does not exist in the type system at all,
  7410. // and plumbing in all that information is not very helpful.
  7411. size_t last_reference = expr.find_last_of('&');
  7412. size_t last_pointer = expr.find_last_of('*');
  7413. size_t last_significant = string::npos;
  7414. if (last_reference == string::npos)
  7415. last_significant = last_pointer;
  7416. else if (last_pointer == string::npos)
  7417. last_significant = last_reference;
  7418. else
  7419. last_significant = max<size_t>(last_reference, last_pointer);
  7420. if (last_significant == string::npos)
  7421. return join(qualifier, " ", expr);
  7422. else
  7423. {
  7424. return join(expr.substr(0, last_significant + 1), " ",
  7425. qualifier, expr.substr(last_significant + 1, string::npos));
  7426. }
  7427. }
  7428. void CompilerMSL::declare_constant_arrays()
  7429. {
  7430. bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1;
  7431. // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to
  7432. // global constants directly, so we are able to use constants as variable expressions.
  7433. bool emitted = false;
  7434. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
  7435. if (c.specialization)
  7436. return;
  7437. auto &type = this->get<SPIRType>(c.constant_type);
  7438. // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries.
  7439. // FIXME: However, hoisting constants to main() means we need to pass down constant arrays to leaf functions if they are used there.
  7440. // If there are multiple functions in the module, drop this case to avoid breaking use cases which do not need to
  7441. // link into Metal libraries. This is hacky.
  7442. if (is_array(type) && (!fully_inlined || is_scalar(type) || is_vector(type)))
  7443. {
  7444. add_resource_name(c.self);
  7445. auto name = to_name(c.self);
  7446. statement(inject_top_level_storage_qualifier(variable_decl(type, name), "constant"),
  7447. " = ", constant_expression(c), ";");
  7448. emitted = true;
  7449. }
  7450. });
  7451. if (emitted)
  7452. statement("");
  7453. }
  7454. // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
  7455. void CompilerMSL::declare_complex_constant_arrays()
  7456. {
  7457. // If we do not have a fully inlined module, we did not opt in to
  7458. // declaring constant arrays of complex types. See CompilerMSL::declare_constant_arrays().
  7459. bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1;
  7460. if (!fully_inlined)
  7461. return;
  7462. // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to
  7463. // global constants directly, so we are able to use constants as variable expressions.
  7464. bool emitted = false;
  7465. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
  7466. if (c.specialization)
  7467. return;
  7468. auto &type = this->get<SPIRType>(c.constant_type);
  7469. if (is_array(type) && !(is_scalar(type) || is_vector(type)))
  7470. {
  7471. add_resource_name(c.self);
  7472. auto name = to_name(c.self);
  7473. statement("", variable_decl(type, name), " = ", constant_expression(c), ";");
  7474. emitted = true;
  7475. }
  7476. });
  7477. if (emitted)
  7478. statement("");
  7479. }
  7480. void CompilerMSL::emit_resources()
  7481. {
  7482. declare_constant_arrays();
  7483. // Emit the special [[stage_in]] and [[stage_out]] interface blocks which we created.
  7484. emit_interface_block(stage_out_var_id);
  7485. emit_interface_block(patch_stage_out_var_id);
  7486. emit_interface_block(stage_in_var_id);
  7487. emit_interface_block(patch_stage_in_var_id);
  7488. if (get_execution_model() == ExecutionModelMeshEXT)
  7489. {
  7490. auto &execution = get_entry_point();
  7491. const char *topology = "";
  7492. if (execution.flags.get(ExecutionModeOutputTrianglesEXT))
  7493. topology = "topology::triangle";
  7494. else if (execution.flags.get(ExecutionModeOutputLinesEXT))
  7495. topology = "topology::line";
  7496. else if (execution.flags.get(ExecutionModeOutputPoints))
  7497. topology = "topology::point";
  7498. const char *per_vertex = mesh_out_per_vertex ? "spvPerVertex" : "float4";
  7499. const char *per_primitive = mesh_out_per_primitive ? "spvPerPrimitive" : "void";
  7500. statement("using spvMesh_t = mesh<", per_vertex, ", ", per_primitive, ", ", execution.output_vertices, ", ",
  7501. execution.output_primitives, ", ", topology, ">;");
  7502. statement("");
  7503. }
  7504. }
  7505. // Emit declarations for the specialization Metal function constants
  7506. void CompilerMSL::emit_specialization_constants_and_structs()
  7507. {
  7508. SpecializationConstant wg_x, wg_y, wg_z;
  7509. ID workgroup_size_id = get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
  7510. if (workgroup_size_id == 0 && is_mesh_shader())
  7511. {
  7512. auto &execution = get_entry_point();
  7513. statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup),
  7514. " [[maybe_unused]] = ", "uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ",
  7515. execution.workgroup_size.z, ");");
  7516. statement("");
  7517. }
  7518. bool emitted = false;
  7519. unordered_set<uint32_t> declared_structs;
  7520. unordered_set<uint32_t> aligned_structs;
  7521. // First, we need to deal with scalar block layout.
  7522. // 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.
  7523. // In that case, if such a case exists for a struct, we must force that all elements of the struct become packed_ types.
  7524. // This makes the struct alignment as small as physically possible.
  7525. // When we actually align the struct later, we can insert padding as necessary to make the packed members behave like normally aligned types.
  7526. ir.for_each_typed_id<SPIRType>([&](uint32_t type_id, const SPIRType &type) {
  7527. if (type.basetype == SPIRType::Struct &&
  7528. has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked))
  7529. mark_scalar_layout_structs(type);
  7530. });
  7531. bool builtin_block_type_is_required = is_mesh_shader();
  7532. // Very special case. If gl_PerVertex is initialized as an array (tessellation)
  7533. // we have to potentially emit the gl_PerVertex struct type so that we can emit a constant LUT.
  7534. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
  7535. auto &type = this->get<SPIRType>(c.constant_type);
  7536. if (is_array(type) && has_decoration(type.self, DecorationBlock) && is_builtin_type(type))
  7537. builtin_block_type_is_required = true;
  7538. });
  7539. // Very particular use of the soft loop lock.
  7540. // align_struct may need to create custom types on the fly, but we don't care about
  7541. // these types for purpose of iterating over them in ir.ids_for_type and friends.
  7542. auto loop_lock = ir.create_loop_soft_lock();
  7543. // Physical storage buffer pointers can have cyclical references,
  7544. // so emit forward declarations of them before other structs.
  7545. // Ignore type_id because we want the underlying struct type from the pointer.
  7546. ir.for_each_typed_id<SPIRType>([&](uint32_t /* type_id */, const SPIRType &type) {
  7547. if (type.basetype == SPIRType::Struct &&
  7548. type.pointer && type.storage == StorageClassPhysicalStorageBuffer &&
  7549. declared_structs.count(type.self) == 0)
  7550. {
  7551. statement("struct ", to_name(type.self), ";");
  7552. declared_structs.insert(type.self);
  7553. emitted = true;
  7554. }
  7555. });
  7556. if (emitted)
  7557. statement("");
  7558. emitted = false;
  7559. declared_structs.clear();
  7560. // It is possible to have multiple spec constants that use the same spec constant ID.
  7561. // The most common cause of this is defining spec constants in GLSL while also declaring
  7562. // the workgroup size to use those spec constants. But, Metal forbids declaring more than
  7563. // one variable with the same function constant ID.
  7564. // In this case, we must only declare one variable with the [[function_constant(id)]]
  7565. // attribute, and use its initializer to initialize all the spec constants with
  7566. // that ID.
  7567. std::unordered_map<uint32_t, ConstantID> unique_func_constants;
  7568. for (auto &id_ : ir.ids_for_constant_undef_or_type)
  7569. {
  7570. auto &id = ir.ids[id_];
  7571. if (id.get_type() == TypeConstant)
  7572. {
  7573. auto &c = id.get<SPIRConstant>();
  7574. if (c.self == workgroup_size_id)
  7575. {
  7576. // TODO: This can be expressed as a [[threads_per_threadgroup]] input semantic, but we need to know
  7577. // the work group size at compile time in SPIR-V, and [[threads_per_threadgroup]] would need to be passed around as a global.
  7578. // The work group size may be a specialization constant.
  7579. statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup),
  7580. " [[maybe_unused]] = ", constant_expression(get<SPIRConstant>(workgroup_size_id)), ";");
  7581. emitted = true;
  7582. }
  7583. else if (c.specialization)
  7584. {
  7585. auto &type = get<SPIRType>(c.constant_type);
  7586. string sc_type_name = type_to_glsl(type);
  7587. add_resource_name(c.self);
  7588. string sc_name = to_name(c.self);
  7589. // Function constants are only supported in MSL 1.2 and later.
  7590. // If we don't support it just declare the "default" directly.
  7591. // This "default" value can be overridden to the true specialization constant by the API user.
  7592. // Specialization constants which are used as array length expressions cannot be function constants in MSL,
  7593. // so just fall back to macros.
  7594. if (msl_options.supports_msl_version(1, 2) && has_decoration(c.self, DecorationSpecId) &&
  7595. !c.is_used_as_array_length)
  7596. {
  7597. // Only scalar, non-composite values can be function constants.
  7598. uint32_t constant_id = get_decoration(c.self, DecorationSpecId);
  7599. if (!unique_func_constants.count(constant_id))
  7600. unique_func_constants.insert(make_pair(constant_id, c.self));
  7601. SPIRType::BaseType sc_tmp_type = expression_type(unique_func_constants[constant_id]).basetype;
  7602. string sc_tmp_name = to_name(unique_func_constants[constant_id]) + "_tmp";
  7603. if (unique_func_constants[constant_id] == c.self)
  7604. statement("constant ", sc_type_name, " ", sc_tmp_name, " [[function_constant(", constant_id,
  7605. ")]];");
  7606. // RenderDoc and other instrumentation may reuse the same SpecId with different base types.
  7607. // We deduplicate to one [[function_constant(id)]] temp and then initialize all variants from it.
  7608. // Metal forbids as_type to/from 'bool', so if either side is Boolean, avoid bitcasting here and
  7609. // prefer a value cast via a constructor instead (e.g. uint(tmp) / float(tmp) / bool(tmp)).
  7610. // This preserves expected toggle semantics and prevents illegal MSL like as_type<uint>(bool_tmp).
  7611. {
  7612. string sc_true_expr;
  7613. if (sc_tmp_type == type.basetype)
  7614. sc_true_expr = sc_tmp_name;
  7615. else if (sc_tmp_type == SPIRType::Boolean || type.basetype == SPIRType::Boolean)
  7616. sc_true_expr = join(sc_type_name, "(", sc_tmp_name, ")");
  7617. else
  7618. sc_true_expr = bitcast_expression(type, sc_tmp_type, sc_tmp_name);
  7619. statement("constant ", sc_type_name, " ", sc_name, " = is_function_constant_defined(", sc_tmp_name,
  7620. ") ? ", sc_true_expr, " : ", constant_expression(c), ";");
  7621. }
  7622. }
  7623. else if (has_decoration(c.self, DecorationSpecId))
  7624. {
  7625. // Fallback to macro overrides.
  7626. uint32_t constant_id = get_decoration(c.self, DecorationSpecId);
  7627. c.specialization_constant_macro_name =
  7628. constant_value_macro_name(constant_id);
  7629. statement("#ifndef ", c.specialization_constant_macro_name);
  7630. statement("#define ", c.specialization_constant_macro_name, " ", constant_expression(c));
  7631. statement("#endif");
  7632. statement("constant ", sc_type_name, " ", sc_name, " = ", c.specialization_constant_macro_name,
  7633. ";");
  7634. // Record the usage of macro
  7635. constant_macro_ids.insert(constant_id);
  7636. }
  7637. else
  7638. {
  7639. // Composite specialization constants must be built from other specialization constants.
  7640. statement("constant ", sc_type_name, " ", sc_name, " = ", constant_expression(c), ";");
  7641. }
  7642. emitted = true;
  7643. }
  7644. }
  7645. else if (id.get_type() == TypeConstantOp)
  7646. {
  7647. auto &c = id.get<SPIRConstantOp>();
  7648. auto &type = get<SPIRType>(c.basetype);
  7649. add_resource_name(c.self);
  7650. auto name = to_name(c.self);
  7651. statement("constant ", variable_decl(type, name), " = ", constant_op_expression(c), ";");
  7652. emitted = true;
  7653. }
  7654. else if (id.get_type() == TypeType)
  7655. {
  7656. // Output non-builtin interface structs. These include local function structs
  7657. // and structs nested within uniform and read-write buffers.
  7658. auto &type = id.get<SPIRType>();
  7659. TypeID type_id = type.self;
  7660. bool is_struct = (type.basetype == SPIRType::Struct) && type.array.empty() && !type.pointer;
  7661. bool is_block =
  7662. has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
  7663. bool is_builtin_block = is_block && is_builtin_type(type);
  7664. bool is_declarable_struct = is_struct && (!is_builtin_block || builtin_block_type_is_required);
  7665. // We'll declare this later.
  7666. if (stage_out_var_id && get_stage_out_struct_type().self == type_id)
  7667. is_declarable_struct = false;
  7668. if (patch_stage_out_var_id && get_patch_stage_out_struct_type().self == type_id)
  7669. is_declarable_struct = false;
  7670. if (stage_in_var_id && get_stage_in_struct_type().self == type_id)
  7671. is_declarable_struct = false;
  7672. if (patch_stage_in_var_id && get_patch_stage_in_struct_type().self == type_id)
  7673. is_declarable_struct = false;
  7674. // Special case. Declare builtin struct anyways if we need to emit a threadgroup version of it.
  7675. if (stage_out_masked_builtin_type_id == type_id)
  7676. is_declarable_struct = true;
  7677. // Align and emit declarable structs...but avoid declaring each more than once.
  7678. if (is_declarable_struct && declared_structs.count(type_id) == 0)
  7679. {
  7680. if (emitted)
  7681. statement("");
  7682. emitted = false;
  7683. declared_structs.insert(type_id);
  7684. if (has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked))
  7685. align_struct(type, aligned_structs);
  7686. // Make sure we declare the underlying struct type, and not the "decorated" type with pointers, etc.
  7687. emit_struct(get<SPIRType>(type_id));
  7688. }
  7689. }
  7690. else if (id.get_type() == TypeUndef)
  7691. {
  7692. auto &undef = id.get<SPIRUndef>();
  7693. auto &type = get<SPIRType>(undef.basetype);
  7694. // OpUndef can be void for some reason ...
  7695. if (type.basetype == SPIRType::Void)
  7696. return;
  7697. // Undefined global memory is not allowed in MSL.
  7698. // Declare constant and init to zeros. Use {}, as global constructors can break Metal.
  7699. statement(
  7700. inject_top_level_storage_qualifier(variable_decl(type, to_name(undef.self), undef.self), "constant"),
  7701. " = {};");
  7702. emitted = true;
  7703. }
  7704. }
  7705. if (emitted)
  7706. statement("");
  7707. }
  7708. void CompilerMSL::emit_binary_ptr_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op)
  7709. {
  7710. bool forward = should_forward(op0) && should_forward(op1);
  7711. emit_op(result_type, result_id, join(to_ptr_expression(op0), " ", op, " ", to_ptr_expression(op1)), forward);
  7712. inherit_expression_dependencies(result_id, op0);
  7713. inherit_expression_dependencies(result_id, op1);
  7714. }
  7715. string CompilerMSL::to_ptr_expression(uint32_t id, bool register_expression_read)
  7716. {
  7717. auto *e = maybe_get<SPIRExpression>(id);
  7718. auto expr = enclose_expression(e && e->need_transpose ? e->expression : to_expression(id, register_expression_read));
  7719. if (!should_dereference(id))
  7720. expr = address_of_expression(expr);
  7721. return expr;
  7722. }
  7723. void CompilerMSL::emit_binary_unord_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
  7724. const char *op)
  7725. {
  7726. bool forward = should_forward(op0) && should_forward(op1);
  7727. emit_op(result_type, result_id,
  7728. join("(isunordered(", to_enclosed_unpacked_expression(op0), ", ", to_enclosed_unpacked_expression(op1),
  7729. ") || ", to_enclosed_unpacked_expression(op0), " ", op, " ", to_enclosed_unpacked_expression(op1),
  7730. ")"),
  7731. forward);
  7732. inherit_expression_dependencies(result_id, op0);
  7733. inherit_expression_dependencies(result_id, op1);
  7734. }
  7735. bool CompilerMSL::emit_tessellation_io_load(uint32_t result_type_id, uint32_t id, uint32_t ptr)
  7736. {
  7737. auto &ptr_type = expression_type(ptr);
  7738. auto &result_type = get<SPIRType>(result_type_id);
  7739. if (ptr_type.storage != StorageClassInput && ptr_type.storage != StorageClassOutput)
  7740. return false;
  7741. if (ptr_type.storage == StorageClassOutput && is_tese_shader())
  7742. return false;
  7743. if (has_decoration(ptr, DecorationPatch))
  7744. return false;
  7745. bool ptr_is_io_variable = ir.ids[ptr].get_type() == TypeVariable;
  7746. bool flattened_io = variable_storage_requires_stage_io(ptr_type.storage);
  7747. bool flat_data_type = flattened_io &&
  7748. (is_matrix(result_type) || is_array(result_type) || result_type.basetype == SPIRType::Struct);
  7749. // Edge case, even with multi-patch workgroups, we still need to unroll load
  7750. // if we're loading control points directly.
  7751. if (ptr_is_io_variable && is_array(result_type))
  7752. flat_data_type = true;
  7753. if (!flat_data_type)
  7754. return false;
  7755. // Now, we must unflatten a composite type and take care of interleaving array access with gl_in/gl_out.
  7756. // Lots of painful code duplication since we *really* should not unroll these kinds of loads in entry point fixup
  7757. // unless we're forced to do this when the code is emitting inoptimal OpLoads.
  7758. string expr;
  7759. uint32_t interface_index = get_extended_decoration(ptr, SPIRVCrossDecorationInterfaceMemberIndex);
  7760. auto *var = maybe_get_backing_variable(ptr);
  7761. auto &expr_type = get_pointee_type(ptr_type.self);
  7762. const auto &iface_type = expression_type(stage_in_ptr_var_id);
  7763. if (!flattened_io)
  7764. {
  7765. // Simplest case for multi-patch workgroups, just unroll array as-is.
  7766. if (interface_index == uint32_t(-1))
  7767. return false;
  7768. expr += type_to_glsl(result_type) + "({ ";
  7769. uint32_t num_control_points = to_array_size_literal(result_type, uint32_t(result_type.array.size()) - 1);
  7770. for (uint32_t i = 0; i < num_control_points; i++)
  7771. {
  7772. const uint32_t indices[2] = { i, interface_index };
  7773. AccessChainMeta meta;
  7774. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7775. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7776. if (i + 1 < num_control_points)
  7777. expr += ", ";
  7778. }
  7779. expr += " })";
  7780. }
  7781. else if (result_type.array.size() > 2)
  7782. {
  7783. SPIRV_CROSS_THROW("Cannot load tessellation IO variables with more than 2 dimensions.");
  7784. }
  7785. else if (result_type.array.size() == 2)
  7786. {
  7787. if (!ptr_is_io_variable)
  7788. SPIRV_CROSS_THROW("Loading an array-of-array must be loaded directly from an IO variable.");
  7789. if (interface_index == uint32_t(-1))
  7790. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7791. if (result_type.basetype == SPIRType::Struct || is_matrix(result_type))
  7792. SPIRV_CROSS_THROW("Cannot load array-of-array of composite type in tessellation IO.");
  7793. expr += type_to_glsl(result_type) + "({ ";
  7794. uint32_t num_control_points = to_array_size_literal(result_type, 1);
  7795. uint32_t base_interface_index = interface_index;
  7796. auto &sub_type = get<SPIRType>(result_type.parent_type);
  7797. for (uint32_t i = 0; i < num_control_points; i++)
  7798. {
  7799. expr += type_to_glsl(sub_type) + "({ ";
  7800. interface_index = base_interface_index;
  7801. uint32_t array_size = to_array_size_literal(result_type, 0);
  7802. for (uint32_t j = 0; j < array_size; j++, interface_index++)
  7803. {
  7804. const uint32_t indices[2] = { i, interface_index };
  7805. AccessChainMeta meta;
  7806. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7807. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7808. if (!is_matrix(sub_type) && sub_type.basetype != SPIRType::Struct &&
  7809. expr_type.vecsize > sub_type.vecsize)
  7810. expr += vector_swizzle(sub_type.vecsize, 0);
  7811. if (j + 1 < array_size)
  7812. expr += ", ";
  7813. }
  7814. expr += " })";
  7815. if (i + 1 < num_control_points)
  7816. expr += ", ";
  7817. }
  7818. expr += " })";
  7819. }
  7820. else if (result_type.basetype == SPIRType::Struct)
  7821. {
  7822. bool is_array_of_struct = is_array(result_type);
  7823. if (is_array_of_struct && !ptr_is_io_variable)
  7824. SPIRV_CROSS_THROW("Loading array of struct from IO variable must come directly from IO variable.");
  7825. uint32_t num_control_points = 1;
  7826. if (is_array_of_struct)
  7827. {
  7828. num_control_points = to_array_size_literal(result_type, 0);
  7829. expr += type_to_glsl(result_type) + "({ ";
  7830. }
  7831. auto &struct_type = is_array_of_struct ? get<SPIRType>(result_type.parent_type) : result_type;
  7832. assert(struct_type.array.empty());
  7833. for (uint32_t i = 0; i < num_control_points; i++)
  7834. {
  7835. expr += type_to_glsl(struct_type) + "{ ";
  7836. for (uint32_t j = 0; j < uint32_t(struct_type.member_types.size()); j++)
  7837. {
  7838. // The base interface index is stored per variable for structs.
  7839. if (var)
  7840. {
  7841. interface_index =
  7842. get_extended_member_decoration(var->self, j, SPIRVCrossDecorationInterfaceMemberIndex);
  7843. }
  7844. if (interface_index == uint32_t(-1))
  7845. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7846. const auto &mbr_type = get<SPIRType>(struct_type.member_types[j]);
  7847. const auto &expr_mbr_type = get<SPIRType>(expr_type.member_types[j]);
  7848. if (is_matrix(mbr_type) && ptr_type.storage == StorageClassInput)
  7849. {
  7850. expr += type_to_glsl(mbr_type) + "(";
  7851. for (uint32_t k = 0; k < mbr_type.columns; k++, interface_index++)
  7852. {
  7853. if (is_array_of_struct)
  7854. {
  7855. const uint32_t indices[2] = { i, interface_index };
  7856. AccessChainMeta meta;
  7857. expr += access_chain_internal(
  7858. stage_in_ptr_var_id, indices, 2,
  7859. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7860. }
  7861. else
  7862. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7863. if (expr_mbr_type.vecsize > mbr_type.vecsize)
  7864. expr += vector_swizzle(mbr_type.vecsize, 0);
  7865. if (k + 1 < mbr_type.columns)
  7866. expr += ", ";
  7867. }
  7868. expr += ")";
  7869. }
  7870. else if (is_array(mbr_type))
  7871. {
  7872. expr += type_to_glsl(mbr_type) + "({ ";
  7873. uint32_t array_size = to_array_size_literal(mbr_type, 0);
  7874. for (uint32_t k = 0; k < array_size; k++, interface_index++)
  7875. {
  7876. if (is_array_of_struct)
  7877. {
  7878. const uint32_t indices[2] = { i, interface_index };
  7879. AccessChainMeta meta;
  7880. expr += access_chain_internal(
  7881. stage_in_ptr_var_id, indices, 2,
  7882. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7883. }
  7884. else
  7885. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7886. if (expr_mbr_type.vecsize > mbr_type.vecsize)
  7887. expr += vector_swizzle(mbr_type.vecsize, 0);
  7888. if (k + 1 < array_size)
  7889. expr += ", ";
  7890. }
  7891. expr += " })";
  7892. }
  7893. else
  7894. {
  7895. if (is_array_of_struct)
  7896. {
  7897. const uint32_t indices[2] = { i, interface_index };
  7898. AccessChainMeta meta;
  7899. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7900. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT,
  7901. &meta);
  7902. }
  7903. else
  7904. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7905. if (expr_mbr_type.vecsize > mbr_type.vecsize)
  7906. expr += vector_swizzle(mbr_type.vecsize, 0);
  7907. }
  7908. if (j + 1 < struct_type.member_types.size())
  7909. expr += ", ";
  7910. }
  7911. expr += " }";
  7912. if (i + 1 < num_control_points)
  7913. expr += ", ";
  7914. }
  7915. if (is_array_of_struct)
  7916. expr += " })";
  7917. }
  7918. else if (is_matrix(result_type))
  7919. {
  7920. bool is_array_of_matrix = is_array(result_type);
  7921. if (is_array_of_matrix && !ptr_is_io_variable)
  7922. SPIRV_CROSS_THROW("Loading array of matrix from IO variable must come directly from IO variable.");
  7923. if (interface_index == uint32_t(-1))
  7924. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7925. if (is_array_of_matrix)
  7926. {
  7927. // Loading a matrix from each control point.
  7928. uint32_t base_interface_index = interface_index;
  7929. uint32_t num_control_points = to_array_size_literal(result_type, 0);
  7930. expr += type_to_glsl(result_type) + "({ ";
  7931. auto &matrix_type = get_variable_element_type(get<SPIRVariable>(ptr));
  7932. for (uint32_t i = 0; i < num_control_points; i++)
  7933. {
  7934. interface_index = base_interface_index;
  7935. expr += type_to_glsl(matrix_type) + "(";
  7936. for (uint32_t j = 0; j < result_type.columns; j++, interface_index++)
  7937. {
  7938. const uint32_t indices[2] = { i, interface_index };
  7939. AccessChainMeta meta;
  7940. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7941. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7942. if (expr_type.vecsize > result_type.vecsize)
  7943. expr += vector_swizzle(result_type.vecsize, 0);
  7944. if (j + 1 < result_type.columns)
  7945. expr += ", ";
  7946. }
  7947. expr += ")";
  7948. if (i + 1 < num_control_points)
  7949. expr += ", ";
  7950. }
  7951. expr += " })";
  7952. }
  7953. else
  7954. {
  7955. expr += type_to_glsl(result_type) + "(";
  7956. for (uint32_t i = 0; i < result_type.columns; i++, interface_index++)
  7957. {
  7958. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7959. if (expr_type.vecsize > result_type.vecsize)
  7960. expr += vector_swizzle(result_type.vecsize, 0);
  7961. if (i + 1 < result_type.columns)
  7962. expr += ", ";
  7963. }
  7964. expr += ")";
  7965. }
  7966. }
  7967. else if (ptr_is_io_variable)
  7968. {
  7969. assert(is_array(result_type));
  7970. assert(result_type.array.size() == 1);
  7971. if (interface_index == uint32_t(-1))
  7972. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7973. // We're loading an array directly from a global variable.
  7974. // This means we're loading one member from each control point.
  7975. expr += type_to_glsl(result_type) + "({ ";
  7976. uint32_t num_control_points = to_array_size_literal(result_type, 0);
  7977. for (uint32_t i = 0; i < num_control_points; i++)
  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, &meta);
  7983. if (expr_type.vecsize > result_type.vecsize)
  7984. expr += vector_swizzle(result_type.vecsize, 0);
  7985. if (i + 1 < num_control_points)
  7986. expr += ", ";
  7987. }
  7988. expr += " })";
  7989. }
  7990. else
  7991. {
  7992. // We're loading an array from a concrete control point.
  7993. assert(is_array(result_type));
  7994. assert(result_type.array.size() == 1);
  7995. if (interface_index == uint32_t(-1))
  7996. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7997. expr += type_to_glsl(result_type) + "({ ";
  7998. uint32_t array_size = to_array_size_literal(result_type, 0);
  7999. for (uint32_t i = 0; i < array_size; i++, interface_index++)
  8000. {
  8001. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  8002. if (expr_type.vecsize > result_type.vecsize)
  8003. expr += vector_swizzle(result_type.vecsize, 0);
  8004. if (i + 1 < array_size)
  8005. expr += ", ";
  8006. }
  8007. expr += " })";
  8008. }
  8009. emit_op(result_type_id, id, expr, false);
  8010. register_read(id, ptr, false);
  8011. return true;
  8012. }
  8013. bool CompilerMSL::emit_tessellation_access_chain(const uint32_t *ops, uint32_t length)
  8014. {
  8015. // If this is a per-vertex output, remap it to the I/O array buffer.
  8016. // Any object which did not go through IO flattening shenanigans will go there instead.
  8017. // We will unflatten on-demand instead as needed, but not all possible cases can be supported, especially with arrays.
  8018. auto *var = maybe_get_backing_variable(ops[2]);
  8019. bool patch = false;
  8020. bool flat_data = false;
  8021. bool ptr_is_chain = false;
  8022. bool flatten_composites = false;
  8023. bool is_block = false;
  8024. bool is_arrayed = false;
  8025. if (var)
  8026. {
  8027. auto &type = get_variable_data_type(*var);
  8028. is_block = has_decoration(type.self, DecorationBlock);
  8029. is_arrayed = !type.array.empty();
  8030. flatten_composites = variable_storage_requires_stage_io(var->storage);
  8031. patch = has_decoration(ops[2], DecorationPatch) || is_patch_block(type);
  8032. // Should match strip_array in add_interface_block.
  8033. flat_data = var->storage == StorageClassInput || (var->storage == StorageClassOutput && is_tesc_shader());
  8034. // Patch inputs are treated as normal block IO variables, so they don't deal with this path at all.
  8035. if (patch && (!is_block || is_arrayed || var->storage == StorageClassInput))
  8036. flat_data = false;
  8037. // We might have a chained access chain, where
  8038. // we first take the access chain to the control point, and then we chain into a member or something similar.
  8039. // In this case, we need to skip gl_in/gl_out remapping.
  8040. // Also, skip ptr chain for patches.
  8041. ptr_is_chain = var->self != ID(ops[2]);
  8042. }
  8043. bool builtin_variable = false;
  8044. bool variable_is_flat = false;
  8045. if (var && flat_data)
  8046. {
  8047. builtin_variable = is_builtin_variable(*var);
  8048. BuiltIn bi_type = BuiltInMax;
  8049. if (builtin_variable && !is_block)
  8050. bi_type = BuiltIn(get_decoration(var->self, DecorationBuiltIn));
  8051. variable_is_flat = !builtin_variable || is_block ||
  8052. bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
  8053. bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance;
  8054. }
  8055. if (variable_is_flat)
  8056. {
  8057. // If output is masked, it is emitted as a "normal" variable, just go through normal code paths.
  8058. // Only check this for the first level of access chain.
  8059. // Dealing with this for partial access chains should be possible, but awkward.
  8060. if (var->storage == StorageClassOutput && !ptr_is_chain)
  8061. {
  8062. bool masked = false;
  8063. if (is_block)
  8064. {
  8065. uint32_t relevant_member_index = patch ? 3 : 4;
  8066. // FIXME: This won't work properly if the application first access chains into gl_out element,
  8067. // then access chains into the member. Super weird, but theoretically possible ...
  8068. if (length > relevant_member_index)
  8069. {
  8070. uint32_t mbr_idx = get<SPIRConstant>(ops[relevant_member_index]).scalar();
  8071. masked = is_stage_output_block_member_masked(*var, mbr_idx, true);
  8072. }
  8073. }
  8074. else if (var)
  8075. masked = is_stage_output_variable_masked(*var);
  8076. if (masked)
  8077. return false;
  8078. }
  8079. AccessChainMeta meta;
  8080. SmallVector<uint32_t> indices;
  8081. uint32_t next_id = ir.increase_bound_by(1);
  8082. indices.reserve(length - 3 + 1);
  8083. uint32_t first_non_array_index = (ptr_is_chain ? 3 : 4) - (patch ? 1 : 0);
  8084. VariableID stage_var_id;
  8085. if (patch)
  8086. stage_var_id = var->storage == StorageClassInput ? patch_stage_in_var_id : patch_stage_out_var_id;
  8087. else
  8088. stage_var_id = var->storage == StorageClassInput ? stage_in_ptr_var_id : stage_out_ptr_var_id;
  8089. VariableID ptr = ptr_is_chain ? VariableID(ops[2]) : stage_var_id;
  8090. if (!ptr_is_chain && !patch)
  8091. {
  8092. // Index into gl_in/gl_out with first array index.
  8093. indices.push_back(ops[first_non_array_index - 1]);
  8094. }
  8095. auto &result_ptr_type = get<SPIRType>(ops[0]);
  8096. uint32_t const_mbr_id = next_id++;
  8097. uint32_t index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex);
  8098. // If we have a pointer chain expression, and we are no longer pointing to a composite
  8099. // object, we are in the clear. There is no longer a need to flatten anything.
  8100. bool further_access_chain_is_trivial = false;
  8101. if (ptr_is_chain && flatten_composites)
  8102. {
  8103. auto &ptr_type = expression_type(ptr);
  8104. if (!is_array(ptr_type) && !is_matrix(ptr_type) && ptr_type.basetype != SPIRType::Struct)
  8105. further_access_chain_is_trivial = true;
  8106. }
  8107. if (!further_access_chain_is_trivial && (flatten_composites || is_block))
  8108. {
  8109. uint32_t i = first_non_array_index;
  8110. auto *type = &get_variable_element_type(*var);
  8111. if (index == uint32_t(-1) && length >= (first_non_array_index + 1))
  8112. {
  8113. // Maybe this is a struct type in the input class, in which case
  8114. // we put it as a decoration on the corresponding member.
  8115. uint32_t mbr_idx = get_constant(ops[first_non_array_index]).scalar();
  8116. index = get_extended_member_decoration(var->self, mbr_idx,
  8117. SPIRVCrossDecorationInterfaceMemberIndex);
  8118. assert(index != uint32_t(-1));
  8119. i++;
  8120. type = &get<SPIRType>(type->member_types[mbr_idx]);
  8121. }
  8122. // In this case, we're poking into flattened structures and arrays, so now we have to
  8123. // combine the following indices. If we encounter a non-constant index,
  8124. // we're hosed.
  8125. for (; flatten_composites && i < length; ++i)
  8126. {
  8127. if (!is_array(*type) && !is_matrix(*type) && type->basetype != SPIRType::Struct)
  8128. break;
  8129. auto *c = maybe_get<SPIRConstant>(ops[i]);
  8130. if (!c || c->specialization)
  8131. SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable in tessellation. "
  8132. "This is currently unsupported.");
  8133. // We're in flattened space, so just increment the member index into IO block.
  8134. // We can only do this once in the current implementation, so either:
  8135. // Struct, Matrix or 1-dimensional array for a control point.
  8136. if (type->basetype == SPIRType::Struct && var->storage == StorageClassOutput)
  8137. {
  8138. // Need to consider holes, since individual block members might be masked away.
  8139. uint32_t mbr_idx = c->scalar();
  8140. for (uint32_t j = 0; j < mbr_idx; j++)
  8141. if (!is_stage_output_block_member_masked(*var, j, true))
  8142. index++;
  8143. }
  8144. else
  8145. index += c->scalar();
  8146. if (type->parent_type)
  8147. type = &get<SPIRType>(type->parent_type);
  8148. else if (type->basetype == SPIRType::Struct)
  8149. type = &get<SPIRType>(type->member_types[c->scalar()]);
  8150. }
  8151. // We're not going to emit the actual member name, we let any further OpLoad take care of that.
  8152. // Tag the access chain with the member index we're referencing.
  8153. auto &result_pointee_type = get_pointee_type(result_ptr_type);
  8154. bool defer_access_chain = flatten_composites && (is_matrix(result_pointee_type) || is_array(result_pointee_type) ||
  8155. result_pointee_type.basetype == SPIRType::Struct);
  8156. if (!defer_access_chain)
  8157. {
  8158. // Access the appropriate member of gl_in/gl_out.
  8159. set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false);
  8160. indices.push_back(const_mbr_id);
  8161. // Member index is now irrelevant.
  8162. index = uint32_t(-1);
  8163. // Append any straggling access chain indices.
  8164. if (i < length)
  8165. indices.insert(indices.end(), ops + i, ops + length);
  8166. }
  8167. else
  8168. {
  8169. // We must have consumed the entire access chain if we're deferring it.
  8170. assert(i == length);
  8171. }
  8172. if (index != uint32_t(-1))
  8173. set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, index);
  8174. else
  8175. unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex);
  8176. }
  8177. else
  8178. {
  8179. if (index != uint32_t(-1))
  8180. {
  8181. set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false);
  8182. indices.push_back(const_mbr_id);
  8183. }
  8184. // Member index is now irrelevant.
  8185. index = uint32_t(-1);
  8186. unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex);
  8187. indices.insert(indices.end(), ops + first_non_array_index, ops + length);
  8188. }
  8189. // We use the pointer to the base of the input/output array here,
  8190. // so this is always a pointer chain.
  8191. string e;
  8192. if (!ptr_is_chain)
  8193. {
  8194. // This is the start of an access chain, use ptr_chain to index into control point array.
  8195. e = access_chain(ptr, indices.data(), uint32_t(indices.size()), result_ptr_type, &meta, !patch);
  8196. }
  8197. else
  8198. {
  8199. // If we're accessing a struct, we need to use member indices which are based on the IO block,
  8200. // not actual struct type, so we have to use a split access chain here where
  8201. // first path resolves the control point index, i.e. gl_in[index], and second half deals with
  8202. // looking up flattened member name.
  8203. // However, it is possible that we partially accessed a struct,
  8204. // by taking pointer to member inside the control-point array.
  8205. // For this case, we fall back to a natural access chain since we have already dealt with remapping struct members.
  8206. // One way to check this here is if we have 2 implied read expressions.
  8207. // First one is the gl_in/gl_out struct itself, then an index into that array.
  8208. // If we have traversed further, we use a normal access chain formulation.
  8209. auto *ptr_expr = maybe_get<SPIRExpression>(ptr);
  8210. bool split_access_chain_formulation = flatten_composites && ptr_expr &&
  8211. ptr_expr->implied_read_expressions.size() == 2 &&
  8212. !further_access_chain_is_trivial;
  8213. if (split_access_chain_formulation)
  8214. {
  8215. e = join(to_expression(ptr),
  8216. access_chain_internal(stage_var_id, indices.data(), uint32_t(indices.size()),
  8217. ACCESS_CHAIN_CHAIN_ONLY_BIT, &meta));
  8218. }
  8219. else
  8220. {
  8221. e = access_chain_internal(ptr, indices.data(), uint32_t(indices.size()), 0, &meta);
  8222. }
  8223. }
  8224. // Get the actual type of the object that was accessed. If it's a vector type and we changed it,
  8225. // then we'll need to add a swizzle.
  8226. // For this, we can't necessarily rely on the type of the base expression, because it might be
  8227. // another access chain, and it will therefore already have the "correct" type.
  8228. auto *expr_type = &get_variable_data_type(*var);
  8229. if (has_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID))
  8230. expr_type = &get<SPIRType>(get_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID));
  8231. for (uint32_t i = 3; i < length; i++)
  8232. {
  8233. if (!is_array(*expr_type) && expr_type->basetype == SPIRType::Struct)
  8234. expr_type = &get<SPIRType>(expr_type->member_types[get<SPIRConstant>(ops[i]).scalar()]);
  8235. else
  8236. expr_type = &get<SPIRType>(expr_type->parent_type);
  8237. }
  8238. if (!is_array(*expr_type) && !is_matrix(*expr_type) && expr_type->basetype != SPIRType::Struct &&
  8239. expr_type->vecsize > result_ptr_type.vecsize)
  8240. e += vector_swizzle(result_ptr_type.vecsize, 0);
  8241. auto &expr = set<SPIRExpression>(ops[1], std::move(e), ops[0], should_forward(ops[2]));
  8242. expr.loaded_from = var->self;
  8243. expr.need_transpose = meta.need_transpose;
  8244. expr.access_chain = true;
  8245. // Mark the result as being packed if necessary.
  8246. if (meta.storage_is_packed)
  8247. set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypePacked);
  8248. if (meta.storage_physical_type != 0)
  8249. set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypeID, meta.storage_physical_type);
  8250. if (meta.storage_is_invariant)
  8251. set_decoration(ops[1], DecorationInvariant);
  8252. // Save the type we found in case the result is used in another access chain.
  8253. set_extended_decoration(ops[1], SPIRVCrossDecorationTessIOOriginalInputTypeID, expr_type->self);
  8254. // If we have some expression dependencies in our access chain, this access chain is technically a forwarded
  8255. // temporary which could be subject to invalidation.
  8256. // Need to assume we're forwarded while calling inherit_expression_depdendencies.
  8257. forwarded_temporaries.insert(ops[1]);
  8258. // The access chain itself is never forced to a temporary, but its dependencies might.
  8259. suppressed_usage_tracking.insert(ops[1]);
  8260. for (uint32_t i = 2; i < length; i++)
  8261. {
  8262. inherit_expression_dependencies(ops[1], ops[i]);
  8263. add_implied_read_expression(expr, ops[i]);
  8264. }
  8265. // If we have no dependencies after all, i.e., all indices in the access chain are immutable temporaries,
  8266. // we're not forwarded after all.
  8267. if (expr.expression_dependencies.empty())
  8268. forwarded_temporaries.erase(ops[1]);
  8269. return true;
  8270. }
  8271. // If this is the inner tessellation level, and we're tessellating triangles,
  8272. // drop the last index. It isn't an array in this case, so we can't have an
  8273. // array reference here. We need to make this ID a variable instead of an
  8274. // expression so we don't try to dereference it as a variable pointer.
  8275. // Don't do this if the index is a constant 1, though. We need to drop stores
  8276. // to that one.
  8277. auto *m = ir.find_meta(var ? var->self : ID(0));
  8278. if (is_tesc_shader() && var && m && m->decoration.builtin_type == BuiltInTessLevelInner &&
  8279. is_tessellating_triangles())
  8280. {
  8281. auto *c = maybe_get<SPIRConstant>(ops[3]);
  8282. if (c && c->scalar() == 1)
  8283. return false;
  8284. auto &dest_var = set<SPIRVariable>(ops[1], *var);
  8285. dest_var.basetype = ops[0];
  8286. ir.meta[ops[1]] = ir.meta[ops[2]];
  8287. inherit_expression_dependencies(ops[1], ops[2]);
  8288. return true;
  8289. }
  8290. return false;
  8291. }
  8292. bool CompilerMSL::is_out_of_bounds_tessellation_level(uint32_t id_lhs)
  8293. {
  8294. if (!is_tessellating_triangles())
  8295. return false;
  8296. // In SPIR-V, TessLevelInner always has two elements and TessLevelOuter always has
  8297. // four. This is true even if we are tessellating triangles. This allows clients
  8298. // to use a single tessellation control shader with multiple tessellation evaluation
  8299. // shaders.
  8300. // In Metal, however, only the first element of TessLevelInner and the first three
  8301. // of TessLevelOuter are accessible. This stems from how in Metal, the tessellation
  8302. // levels must be stored to a dedicated buffer in a particular format that depends
  8303. // on the patch type. Therefore, in Triangles mode, any store to the second
  8304. // inner level or the fourth outer level must be dropped.
  8305. const auto *e = maybe_get<SPIRExpression>(id_lhs);
  8306. if (!e || !e->access_chain)
  8307. return false;
  8308. BuiltIn builtin = BuiltIn(get_decoration(e->loaded_from, DecorationBuiltIn));
  8309. if (builtin != BuiltInTessLevelInner && builtin != BuiltInTessLevelOuter)
  8310. return false;
  8311. auto *c = maybe_get<SPIRConstant>(e->implied_read_expressions[1]);
  8312. if (!c)
  8313. return false;
  8314. return (builtin == BuiltInTessLevelInner && c->scalar() == 1) ||
  8315. (builtin == BuiltInTessLevelOuter && c->scalar() == 3);
  8316. }
  8317. bool CompilerMSL::prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type,
  8318. StorageClass storage, bool &is_packed)
  8319. {
  8320. // If there is any risk of writes happening with the access chain in question,
  8321. // and there is a risk of concurrent write access to other components,
  8322. // we must cast the access chain to a plain pointer to ensure we only access the exact scalars we expect.
  8323. // The MSL compiler refuses to allow component-level access for any non-packed vector types.
  8324. // MSL refuses to take address or reference to vector component, even for packed types, so just force
  8325. // through the pointer cast. No much we can do sadly.
  8326. // For packed types, we could technically omit this if we know the reference does not have to turn into a pointer
  8327. // of some kind, but that requires external analysis passes to figure out, and
  8328. // this case is likely rare enough that we don't need to bother.
  8329. if (storage == StorageClassStorageBuffer || storage == StorageClassWorkgroup)
  8330. {
  8331. const char *addr_space = storage == StorageClassWorkgroup ? "threadgroup" : "device";
  8332. expr = join("((", addr_space, " ", type_to_glsl(type), "*)&", enclose_expression(expr), ")");
  8333. // Further indexing should happen with packed rules (array index, not swizzle).
  8334. is_packed = true;
  8335. return true;
  8336. }
  8337. else
  8338. return false;
  8339. }
  8340. bool CompilerMSL::access_chain_needs_stage_io_builtin_translation(uint32_t base)
  8341. {
  8342. auto *var = maybe_get_backing_variable(base);
  8343. if (!var || !is_tessellation_shader())
  8344. return true;
  8345. // We only need to rewrite builtin access chains when accessing flattened builtins like gl_ClipDistance_N.
  8346. // Avoid overriding it back to just gl_ClipDistance.
  8347. // This can only happen in scenarios where we cannot flatten/unflatten access chains, so, the only case
  8348. // where this triggers is evaluation shader inputs.
  8349. bool redirect_builtin = is_tese_shader() ? var->storage == StorageClassOutput : false;
  8350. return redirect_builtin;
  8351. }
  8352. // Sets the interface member index for an access chain to a pull-model interpolant.
  8353. void CompilerMSL::fix_up_interpolant_access_chain(const uint32_t *ops, uint32_t length)
  8354. {
  8355. auto *var = maybe_get_backing_variable(ops[2]);
  8356. if (!var || !pull_model_inputs.count(var->self))
  8357. return;
  8358. // Get the base index.
  8359. uint32_t interface_index;
  8360. auto &var_type = get_variable_data_type(*var);
  8361. auto &result_type = get<SPIRType>(ops[0]);
  8362. auto *type = &var_type;
  8363. if (has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex))
  8364. {
  8365. interface_index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex);
  8366. }
  8367. else
  8368. {
  8369. // Assume an access chain into a struct variable.
  8370. assert(var_type.basetype == SPIRType::Struct);
  8371. auto &c = get<SPIRConstant>(ops[3 + var_type.array.size()]);
  8372. interface_index =
  8373. get_extended_member_decoration(var->self, c.scalar(), SPIRVCrossDecorationInterfaceMemberIndex);
  8374. }
  8375. // Accumulate indices. We'll have to skip over the one for the struct, if present, because we already accounted
  8376. // for that getting the base index.
  8377. for (uint32_t i = 3; i < length; ++i)
  8378. {
  8379. if (is_vector(*type) && !is_array(*type) && is_scalar(result_type))
  8380. {
  8381. // We don't want to combine the next index. Actually, we need to save it
  8382. // so we know to apply a swizzle to the result of the interpolation.
  8383. set_extended_decoration(ops[1], SPIRVCrossDecorationInterpolantComponentExpr, ops[i]);
  8384. break;
  8385. }
  8386. auto *c = maybe_get<SPIRConstant>(ops[i]);
  8387. if (!c || c->specialization)
  8388. SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable using pull-model "
  8389. "interpolation. This is currently unsupported.");
  8390. if (type->parent_type)
  8391. type = &get<SPIRType>(type->parent_type);
  8392. else if (type->basetype == SPIRType::Struct)
  8393. type = &get<SPIRType>(type->member_types[c->scalar()]);
  8394. if (!has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex) &&
  8395. i - 3 == var_type.array.size())
  8396. continue;
  8397. interface_index += c->scalar();
  8398. }
  8399. // Save this to the access chain itself so we can recover it later when calling an interpolation function.
  8400. set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, interface_index);
  8401. }
  8402. // If the physical type of a physical buffer pointer has been changed
  8403. // to a ulong or ulongn vector, add a cast back to the pointer type.
  8404. bool CompilerMSL::check_physical_type_cast(std::string &expr, const SPIRType *type, uint32_t physical_type)
  8405. {
  8406. auto *p_physical_type = maybe_get<SPIRType>(physical_type);
  8407. if (p_physical_type &&
  8408. p_physical_type->storage == StorageClassPhysicalStorageBuffer &&
  8409. p_physical_type->basetype == to_unsigned_basetype(64))
  8410. {
  8411. if (p_physical_type->vecsize > 1)
  8412. expr += ".x";
  8413. expr = join("((", type_to_glsl(*type), ")", expr, ")");
  8414. return true;
  8415. }
  8416. return false;
  8417. }
  8418. // Override for MSL-specific syntax instructions
  8419. void CompilerMSL::emit_instruction(const Instruction &instruction)
  8420. {
  8421. #define MSL_BOP(op) emit_binary_op(ops[0], ops[1], ops[2], ops[3], #op)
  8422. #define MSL_PTR_BOP(op) emit_binary_ptr_op(ops[0], ops[1], ops[2], ops[3], #op)
  8423. // MSL does care about implicit integer promotion, but those cases are all handled in common code.
  8424. #define MSL_BOP_CAST(op, type) \
  8425. emit_binary_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode), false)
  8426. #define MSL_UOP(op) emit_unary_op(ops[0], ops[1], ops[2], #op)
  8427. #define MSL_QFOP(op) emit_quaternary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], #op)
  8428. #define MSL_TFOP(op) emit_trinary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], #op)
  8429. #define MSL_BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
  8430. #define MSL_BFOP_CAST(op, type) \
  8431. emit_binary_func_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode))
  8432. #define MSL_UFOP(op) emit_unary_func_op(ops[0], ops[1], ops[2], #op)
  8433. #define MSL_UNORD_BOP(op) emit_binary_unord_op(ops[0], ops[1], ops[2], ops[3], #op)
  8434. auto ops = stream(instruction);
  8435. auto opcode = static_cast<Op>(instruction.op);
  8436. opcode = get_remapped_spirv_op(opcode);
  8437. // If we need to do implicit bitcasts, make sure we do it with the correct type.
  8438. uint32_t integer_width = get_integer_width_for_instruction(instruction);
  8439. auto int_type = to_signed_basetype(integer_width);
  8440. auto uint_type = to_unsigned_basetype(integer_width);
  8441. switch (opcode)
  8442. {
  8443. case OpLoad:
  8444. {
  8445. uint32_t id = ops[1];
  8446. uint32_t ptr = ops[2];
  8447. if (is_tessellation_shader())
  8448. {
  8449. if (!emit_tessellation_io_load(ops[0], id, ptr))
  8450. CompilerGLSL::emit_instruction(instruction);
  8451. }
  8452. else
  8453. {
  8454. // Sample mask input for Metal is not an array
  8455. if (BuiltIn(get_decoration(ptr, DecorationBuiltIn)) == BuiltInSampleMask)
  8456. set_decoration(id, DecorationBuiltIn, BuiltInSampleMask);
  8457. CompilerGLSL::emit_instruction(instruction);
  8458. }
  8459. break;
  8460. }
  8461. // Comparisons
  8462. case OpIEqual:
  8463. MSL_BOP_CAST(==, int_type);
  8464. break;
  8465. case OpLogicalEqual:
  8466. case OpFOrdEqual:
  8467. MSL_BOP(==);
  8468. break;
  8469. case OpINotEqual:
  8470. MSL_BOP_CAST(!=, int_type);
  8471. break;
  8472. case OpLogicalNotEqual:
  8473. case OpFOrdNotEqual:
  8474. // TODO: Should probably negate the == result here.
  8475. // Typically OrdNotEqual comes from GLSL which itself does not really specify what
  8476. // happens with NaN.
  8477. // Consider fixing this if we run into real issues.
  8478. MSL_BOP(!=);
  8479. break;
  8480. case OpUGreaterThan:
  8481. MSL_BOP_CAST(>, uint_type);
  8482. break;
  8483. case OpSGreaterThan:
  8484. MSL_BOP_CAST(>, int_type);
  8485. break;
  8486. case OpFOrdGreaterThan:
  8487. MSL_BOP(>);
  8488. break;
  8489. case OpUGreaterThanEqual:
  8490. MSL_BOP_CAST(>=, uint_type);
  8491. break;
  8492. case OpSGreaterThanEqual:
  8493. MSL_BOP_CAST(>=, int_type);
  8494. break;
  8495. case OpFOrdGreaterThanEqual:
  8496. MSL_BOP(>=);
  8497. break;
  8498. case OpULessThan:
  8499. MSL_BOP_CAST(<, uint_type);
  8500. break;
  8501. case OpSLessThan:
  8502. MSL_BOP_CAST(<, int_type);
  8503. break;
  8504. case OpFOrdLessThan:
  8505. MSL_BOP(<);
  8506. break;
  8507. case OpULessThanEqual:
  8508. MSL_BOP_CAST(<=, uint_type);
  8509. break;
  8510. case OpSLessThanEqual:
  8511. MSL_BOP_CAST(<=, int_type);
  8512. break;
  8513. case OpFOrdLessThanEqual:
  8514. MSL_BOP(<=);
  8515. break;
  8516. case OpFUnordEqual:
  8517. MSL_UNORD_BOP(==);
  8518. break;
  8519. case OpFUnordNotEqual:
  8520. // not equal in MSL generates une opcodes to begin with.
  8521. // Since unordered not equal is how it works in C, just inherit that behavior.
  8522. MSL_BOP(!=);
  8523. break;
  8524. case OpFUnordGreaterThan:
  8525. MSL_UNORD_BOP(>);
  8526. break;
  8527. case OpFUnordGreaterThanEqual:
  8528. MSL_UNORD_BOP(>=);
  8529. break;
  8530. case OpFUnordLessThan:
  8531. MSL_UNORD_BOP(<);
  8532. break;
  8533. case OpFUnordLessThanEqual:
  8534. MSL_UNORD_BOP(<=);
  8535. break;
  8536. // Pointer math
  8537. case OpPtrEqual:
  8538. MSL_PTR_BOP(==);
  8539. break;
  8540. case OpPtrNotEqual:
  8541. MSL_PTR_BOP(!=);
  8542. break;
  8543. case OpPtrDiff:
  8544. MSL_PTR_BOP(-);
  8545. break;
  8546. // Derivatives
  8547. case OpDPdx:
  8548. case OpDPdxFine:
  8549. case OpDPdxCoarse:
  8550. MSL_UFOP(dfdx);
  8551. register_control_dependent_expression(ops[1]);
  8552. break;
  8553. case OpDPdy:
  8554. case OpDPdyFine:
  8555. case OpDPdyCoarse:
  8556. MSL_UFOP(dfdy);
  8557. register_control_dependent_expression(ops[1]);
  8558. break;
  8559. case OpFwidth:
  8560. case OpFwidthCoarse:
  8561. case OpFwidthFine:
  8562. MSL_UFOP(fwidth);
  8563. register_control_dependent_expression(ops[1]);
  8564. break;
  8565. // Bitfield
  8566. case OpBitFieldInsert:
  8567. {
  8568. emit_bitfield_insert_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], "insert_bits", SPIRType::UInt);
  8569. break;
  8570. }
  8571. case OpBitFieldSExtract:
  8572. {
  8573. emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", int_type, int_type,
  8574. SPIRType::UInt, SPIRType::UInt);
  8575. break;
  8576. }
  8577. case OpBitFieldUExtract:
  8578. {
  8579. emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", uint_type, uint_type,
  8580. SPIRType::UInt, SPIRType::UInt);
  8581. break;
  8582. }
  8583. case OpBitReverse:
  8584. // BitReverse does not have issues with sign since result type must match input type.
  8585. MSL_UFOP(reverse_bits);
  8586. break;
  8587. case OpBitCount:
  8588. {
  8589. auto basetype = expression_type(ops[2]).basetype;
  8590. emit_unary_func_op_cast(ops[0], ops[1], ops[2], "popcount", basetype, basetype);
  8591. break;
  8592. }
  8593. case OpSMod:
  8594. MSL_BFOP(spvSMod);
  8595. break;
  8596. case OpFRem:
  8597. MSL_BFOP(fmod);
  8598. break;
  8599. case OpFMul:
  8600. if (msl_options.invariant_float_math || has_legacy_nocontract(ops[0], ops[1]))
  8601. MSL_BFOP(spvFMul);
  8602. else
  8603. MSL_BOP(*);
  8604. break;
  8605. case OpFAdd:
  8606. if (msl_options.invariant_float_math || has_legacy_nocontract(ops[0], ops[1]))
  8607. MSL_BFOP(spvFAdd);
  8608. else
  8609. MSL_BOP(+);
  8610. break;
  8611. case OpFSub:
  8612. if (msl_options.invariant_float_math || has_legacy_nocontract(ops[0], ops[1]))
  8613. MSL_BFOP(spvFSub);
  8614. else
  8615. MSL_BOP(-);
  8616. break;
  8617. case OpFmaKHR:
  8618. MSL_TFOP(fma);
  8619. break;
  8620. // Atomics
  8621. case OpAtomicExchange:
  8622. {
  8623. uint32_t result_type = ops[0];
  8624. uint32_t id = ops[1];
  8625. uint32_t ptr = ops[2];
  8626. uint32_t mem_sem = ops[4];
  8627. uint32_t val = ops[5];
  8628. emit_atomic_func_op(result_type, id, "atomic_exchange", opcode, mem_sem, mem_sem, false, ptr, val);
  8629. break;
  8630. }
  8631. case OpAtomicCompareExchange:
  8632. {
  8633. uint32_t result_type = ops[0];
  8634. uint32_t id = ops[1];
  8635. uint32_t ptr = ops[2];
  8636. uint32_t mem_sem_pass = ops[4];
  8637. uint32_t mem_sem_fail = ops[5];
  8638. uint32_t val = ops[6];
  8639. uint32_t comp = ops[7];
  8640. emit_atomic_func_op(result_type, id, "atomic_compare_exchange_weak", opcode,
  8641. mem_sem_pass, mem_sem_fail, true,
  8642. ptr, comp, true, false, val);
  8643. break;
  8644. }
  8645. case OpAtomicCompareExchangeWeak:
  8646. SPIRV_CROSS_THROW("OpAtomicCompareExchangeWeak is only supported in kernel profile.");
  8647. case OpAtomicLoad:
  8648. {
  8649. uint32_t result_type = ops[0];
  8650. uint32_t id = ops[1];
  8651. uint32_t ptr = ops[2];
  8652. uint32_t mem_sem = ops[4];
  8653. check_atomic_image(ptr);
  8654. emit_atomic_func_op(result_type, id, "atomic_load", opcode, mem_sem, mem_sem, false, ptr, 0);
  8655. break;
  8656. }
  8657. case OpAtomicStore:
  8658. {
  8659. uint32_t result_type = expression_type(ops[0]).self;
  8660. uint32_t id = ops[0];
  8661. uint32_t ptr = ops[0];
  8662. uint32_t mem_sem = ops[2];
  8663. uint32_t val = ops[3];
  8664. check_atomic_image(ptr);
  8665. emit_atomic_func_op(result_type, id, "atomic_store", opcode, mem_sem, mem_sem, false, ptr, val);
  8666. break;
  8667. }
  8668. #define MSL_AFMO_IMPL(op, valsrc, valconst) \
  8669. do \
  8670. { \
  8671. uint32_t result_type = ops[0]; \
  8672. uint32_t id = ops[1]; \
  8673. uint32_t ptr = ops[2]; \
  8674. uint32_t mem_sem = ops[4]; \
  8675. uint32_t val = valsrc; \
  8676. emit_atomic_func_op(result_type, id, "atomic_fetch_" #op, opcode, \
  8677. mem_sem, mem_sem, false, ptr, val, \
  8678. false, valconst); \
  8679. } while (false)
  8680. #define MSL_AFMO(op) MSL_AFMO_IMPL(op, ops[5], false)
  8681. #define MSL_AFMIO(op) MSL_AFMO_IMPL(op, 1, true)
  8682. case OpAtomicIIncrement:
  8683. MSL_AFMIO(add);
  8684. break;
  8685. case OpAtomicIDecrement:
  8686. MSL_AFMIO(sub);
  8687. break;
  8688. case OpAtomicIAdd:
  8689. case OpAtomicFAddEXT:
  8690. MSL_AFMO(add);
  8691. break;
  8692. case OpAtomicISub:
  8693. MSL_AFMO(sub);
  8694. break;
  8695. case OpAtomicSMin:
  8696. case OpAtomicUMin:
  8697. MSL_AFMO(min);
  8698. break;
  8699. case OpAtomicSMax:
  8700. case OpAtomicUMax:
  8701. MSL_AFMO(max);
  8702. break;
  8703. case OpAtomicAnd:
  8704. MSL_AFMO(and);
  8705. break;
  8706. case OpAtomicOr:
  8707. MSL_AFMO(or);
  8708. break;
  8709. case OpAtomicXor:
  8710. MSL_AFMO(xor);
  8711. break;
  8712. // Images
  8713. // Reads == Fetches in Metal
  8714. case OpImageRead:
  8715. {
  8716. // Mark that this shader reads from this image
  8717. uint32_t img_id = ops[2];
  8718. auto &type = expression_type(img_id);
  8719. auto *p_var = maybe_get_backing_variable(img_id);
  8720. if (type.image.dim != DimSubpassData)
  8721. {
  8722. if (p_var && has_decoration(p_var->self, DecorationNonReadable))
  8723. {
  8724. unset_decoration(p_var->self, DecorationNonReadable);
  8725. force_recompile();
  8726. }
  8727. }
  8728. // Metal requires explicit fences to break up RAW hazards, even within the same shader invocation
  8729. if (msl_options.readwrite_texture_fences && p_var && !has_decoration(p_var->self, DecorationNonWritable))
  8730. {
  8731. add_spv_func_and_recompile(SPVFuncImplImageFence);
  8732. // Need to wrap this with a value type,
  8733. // since the Metal headers are broken and do not consider case when the image is a reference.
  8734. statement("spvImageFence(", to_expression(img_id), ");");
  8735. }
  8736. emit_texture_op(instruction, false);
  8737. break;
  8738. }
  8739. // Emulate texture2D atomic operations
  8740. case OpImageTexelPointer:
  8741. {
  8742. // When using the pointer, we need to know which variable it is actually loaded from.
  8743. auto *var = maybe_get_backing_variable(ops[2]);
  8744. if (var && atomic_image_vars_emulated.count(var->self))
  8745. {
  8746. uint32_t result_type = ops[0];
  8747. uint32_t id = ops[1];
  8748. std::string coord = to_expression(ops[3]);
  8749. auto &type = expression_type(ops[2]);
  8750. if (type.image.dim == Dim2D)
  8751. {
  8752. coord = join("spvImage2DAtomicCoord(", coord, ", ", to_expression(ops[2]), ")");
  8753. }
  8754. auto &e = set<SPIRExpression>(id, join(to_expression(ops[2]), "_atomic[", coord, "]"), result_type, true);
  8755. e.loaded_from = var ? var->self : ID(0);
  8756. inherit_expression_dependencies(id, ops[3]);
  8757. }
  8758. else
  8759. {
  8760. uint32_t result_type = ops[0];
  8761. uint32_t id = ops[1];
  8762. // Virtual expression. Split this up in the actual image atomic.
  8763. // In GLSL and HLSL we are able to resolve the dereference inline, but MSL has
  8764. // image.op(coord, ...) syntax.
  8765. auto &e =
  8766. set<SPIRExpression>(id, join(to_expression(ops[2]), "@",
  8767. bitcast_expression(SPIRType::UInt, ops[3])),
  8768. result_type, true);
  8769. // When using the pointer, we need to know which variable it is actually loaded from.
  8770. e.loaded_from = var ? var->self : ID(0);
  8771. inherit_expression_dependencies(id, ops[3]);
  8772. }
  8773. break;
  8774. }
  8775. case OpImageWrite:
  8776. {
  8777. uint32_t img_id = ops[0];
  8778. uint32_t coord_id = ops[1];
  8779. uint32_t texel_id = ops[2];
  8780. const uint32_t *opt = &ops[3];
  8781. uint32_t length = instruction.length - 3;
  8782. // Bypass pointers because we need the real image struct
  8783. auto &type = expression_type(img_id);
  8784. auto &img_type = get<SPIRType>(type.self);
  8785. // Ensure this image has been marked as being written to and force a
  8786. // recommpile so that the image type output will include write access
  8787. auto *p_var = maybe_get_backing_variable(img_id);
  8788. if (p_var && has_decoration(p_var->self, DecorationNonWritable))
  8789. {
  8790. unset_decoration(p_var->self, DecorationNonWritable);
  8791. force_recompile();
  8792. }
  8793. bool forward = false;
  8794. uint32_t bias = 0;
  8795. uint32_t lod = 0;
  8796. uint32_t flags = 0;
  8797. if (length)
  8798. {
  8799. flags = *opt++;
  8800. length--;
  8801. }
  8802. auto test = [&](uint32_t &v, uint32_t flag) {
  8803. if (length && (flags & flag))
  8804. {
  8805. v = *opt++;
  8806. length--;
  8807. }
  8808. };
  8809. test(bias, ImageOperandsBiasMask);
  8810. test(lod, ImageOperandsLodMask);
  8811. auto &texel_type = expression_type(texel_id);
  8812. auto store_type = texel_type;
  8813. store_type.vecsize = 4;
  8814. TextureFunctionArguments args = {};
  8815. args.base.img = img_id;
  8816. args.base.imgtype = &img_type;
  8817. args.base.is_fetch = true;
  8818. args.coord = coord_id;
  8819. args.lod = lod;
  8820. string expr;
  8821. if (needs_frag_discard_checks())
  8822. expr = join("(", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), " ? ((void)0) : ");
  8823. expr += join(to_expression(img_id), ".write(",
  8824. remap_swizzle(store_type, texel_type.vecsize, to_expression(texel_id)), ", ",
  8825. CompilerMSL::to_function_args(args, &forward), ")");
  8826. if (needs_frag_discard_checks())
  8827. expr += ")";
  8828. statement(expr, ";");
  8829. if (p_var && variable_storage_is_aliased(*p_var))
  8830. flush_all_aliased_variables();
  8831. break;
  8832. }
  8833. case OpImageQuerySize:
  8834. case OpImageQuerySizeLod:
  8835. {
  8836. uint32_t rslt_type_id = ops[0];
  8837. auto &rslt_type = get<SPIRType>(rslt_type_id);
  8838. uint32_t id = ops[1];
  8839. uint32_t img_id = ops[2];
  8840. string img_exp = to_expression(img_id);
  8841. auto &img_type = expression_type(img_id);
  8842. Dim img_dim = img_type.image.dim;
  8843. bool img_is_array = img_type.image.arrayed;
  8844. if (img_type.basetype != SPIRType::Image)
  8845. SPIRV_CROSS_THROW("Invalid type for OpImageQuerySize.");
  8846. string lod;
  8847. if (opcode == OpImageQuerySizeLod)
  8848. {
  8849. // LOD index defaults to zero, so don't bother outputing level zero index
  8850. string decl_lod = to_expression(ops[3]);
  8851. if (decl_lod != "0")
  8852. lod = decl_lod;
  8853. }
  8854. string expr = type_to_glsl(rslt_type) + "(";
  8855. expr += img_exp + ".get_width(" + lod + ")";
  8856. if (img_dim == Dim2D || img_dim == DimCube || img_dim == Dim3D)
  8857. expr += ", " + img_exp + ".get_height(" + lod + ")";
  8858. if (img_dim == Dim3D)
  8859. expr += ", " + img_exp + ".get_depth(" + lod + ")";
  8860. if (img_is_array)
  8861. {
  8862. expr += ", " + img_exp + ".get_array_size()";
  8863. if (img_dim == DimCube && msl_options.emulate_cube_array)
  8864. expr += " / 6";
  8865. }
  8866. expr += ")";
  8867. emit_op(rslt_type_id, id, expr, should_forward(img_id));
  8868. break;
  8869. }
  8870. case OpImageQueryLod:
  8871. {
  8872. if (!msl_options.supports_msl_version(2, 2))
  8873. SPIRV_CROSS_THROW("ImageQueryLod is only supported on MSL 2.2 and up.");
  8874. uint32_t result_type = ops[0];
  8875. uint32_t id = ops[1];
  8876. uint32_t image_id = ops[2];
  8877. uint32_t coord_id = ops[3];
  8878. emit_uninitialized_temporary_expression(result_type, id);
  8879. std::string coord_expr = to_expression(coord_id);
  8880. auto sampler_expr = to_sampler_expression(image_id);
  8881. auto *combined = maybe_get<SPIRCombinedImageSampler>(image_id);
  8882. auto image_expr = combined ? to_expression(combined->image) : to_expression(image_id);
  8883. const SPIRType &image_type = expression_type(image_id);
  8884. const SPIRType &coord_type = expression_type(coord_id);
  8885. switch (image_type.image.dim)
  8886. {
  8887. case Dim1D:
  8888. if (!msl_options.texture_1D_as_2D)
  8889. SPIRV_CROSS_THROW("ImageQueryLod is not supported on 1D textures.");
  8890. [[fallthrough]];
  8891. case Dim2D:
  8892. if (coord_type.vecsize > 2)
  8893. coord_expr = enclose_expression(coord_expr) + ".xy";
  8894. break;
  8895. case DimCube:
  8896. case Dim3D:
  8897. if (coord_type.vecsize > 3)
  8898. coord_expr = enclose_expression(coord_expr) + ".xyz";
  8899. break;
  8900. default:
  8901. SPIRV_CROSS_THROW("Bad image type given to OpImageQueryLod");
  8902. }
  8903. // TODO: It is unclear if calculcate_clamped_lod also conditionally rounds
  8904. // the reported LOD based on the sampler. NEAREST miplevel should
  8905. // round the LOD, but LINEAR miplevel should not round.
  8906. // Let's hope this does not become an issue ...
  8907. statement(to_expression(id), ".x = ", image_expr, ".calculate_clamped_lod(", sampler_expr, ", ",
  8908. coord_expr, ");");
  8909. statement(to_expression(id), ".y = ", image_expr, ".calculate_unclamped_lod(", sampler_expr, ", ",
  8910. coord_expr, ");");
  8911. register_control_dependent_expression(id);
  8912. break;
  8913. }
  8914. #define MSL_ImgQry(qrytype) \
  8915. do \
  8916. { \
  8917. uint32_t rslt_type_id = ops[0]; \
  8918. auto &rslt_type = get<SPIRType>(rslt_type_id); \
  8919. uint32_t id = ops[1]; \
  8920. uint32_t img_id = ops[2]; \
  8921. string img_exp = to_expression(img_id); \
  8922. string expr = type_to_glsl(rslt_type) + "(" + img_exp + ".get_num_" #qrytype "())"; \
  8923. emit_op(rslt_type_id, id, expr, should_forward(img_id)); \
  8924. } while (false)
  8925. case OpImageQueryLevels:
  8926. MSL_ImgQry(mip_levels);
  8927. break;
  8928. case OpImageQuerySamples:
  8929. MSL_ImgQry(samples);
  8930. break;
  8931. case OpImage:
  8932. {
  8933. uint32_t result_type = ops[0];
  8934. uint32_t id = ops[1];
  8935. auto *combined = maybe_get<SPIRCombinedImageSampler>(ops[2]);
  8936. if (combined)
  8937. {
  8938. auto &e = emit_op(result_type, id, to_expression(combined->image), true, true);
  8939. auto *var = maybe_get_backing_variable(combined->image);
  8940. if (var)
  8941. e.loaded_from = var->self;
  8942. }
  8943. else
  8944. {
  8945. auto *var = maybe_get_backing_variable(ops[2]);
  8946. SPIRExpression *e;
  8947. if (var && has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler))
  8948. e = &emit_op(result_type, id, join(to_expression(ops[2]), ".plane0"), true, true);
  8949. else
  8950. e = &emit_op(result_type, id, to_expression(ops[2]), true, true);
  8951. if (var)
  8952. e->loaded_from = var->self;
  8953. }
  8954. break;
  8955. }
  8956. // Casting
  8957. case OpQuantizeToF16:
  8958. {
  8959. uint32_t result_type = ops[0];
  8960. uint32_t id = ops[1];
  8961. uint32_t arg = ops[2];
  8962. string exp = join("spvQuantizeToF16(", to_expression(arg), ")");
  8963. emit_op(result_type, id, exp, should_forward(arg));
  8964. break;
  8965. }
  8966. case OpInBoundsAccessChain:
  8967. case OpAccessChain:
  8968. case OpPtrAccessChain:
  8969. if (is_tessellation_shader())
  8970. {
  8971. if (!emit_tessellation_access_chain(ops, instruction.length))
  8972. CompilerGLSL::emit_instruction(instruction);
  8973. }
  8974. else
  8975. CompilerGLSL::emit_instruction(instruction);
  8976. fix_up_interpolant_access_chain(ops, instruction.length);
  8977. break;
  8978. case OpStore:
  8979. {
  8980. const auto &type = expression_type(ops[0]);
  8981. if (is_out_of_bounds_tessellation_level(ops[0]))
  8982. break;
  8983. if (needs_frag_discard_checks() &&
  8984. (type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform))
  8985. {
  8986. // If we're in a continue block, this kludge will make the block too complex
  8987. // to emit normally.
  8988. assert(current_emitting_block);
  8989. auto cont_type = continue_block_type(*current_emitting_block);
  8990. if (cont_type != SPIRBlock::ContinueNone && cont_type != SPIRBlock::ComplexLoop)
  8991. {
  8992. current_emitting_block->complex_continue = true;
  8993. force_recompile();
  8994. }
  8995. statement("if (!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), ")");
  8996. begin_scope();
  8997. }
  8998. if (!maybe_emit_array_assignment(ops[0], ops[1]))
  8999. CompilerGLSL::emit_instruction(instruction);
  9000. if (needs_frag_discard_checks() &&
  9001. (type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform))
  9002. end_scope();
  9003. if (has_decoration(ops[0], DecorationBuiltIn) && get_decoration(ops[0], DecorationBuiltIn) == BuiltInPointSize)
  9004. writes_to_point_size = true;
  9005. break;
  9006. }
  9007. // Compute barriers
  9008. case OpMemoryBarrier:
  9009. emit_barrier(0, ops[0], ops[1]);
  9010. break;
  9011. case OpControlBarrier:
  9012. // In GLSL a memory barrier is often followed by a control barrier.
  9013. // But in MSL, memory barriers are also control barriers (before MSL 3.2), so don't
  9014. // emit a simple control barrier if a memory barrier has just been emitted.
  9015. if (previous_instruction_opcode != OpMemoryBarrier || msl_options.supports_msl_version(3, 2))
  9016. emit_barrier(ops[0], ops[1], ops[2]);
  9017. break;
  9018. case OpOuterProduct:
  9019. {
  9020. uint32_t result_type = ops[0];
  9021. uint32_t id = ops[1];
  9022. uint32_t a = ops[2];
  9023. uint32_t b = ops[3];
  9024. auto &type = get<SPIRType>(result_type);
  9025. string expr = type_to_glsl_constructor(type);
  9026. expr += "(";
  9027. for (uint32_t col = 0; col < type.columns; col++)
  9028. {
  9029. expr += to_enclosed_unpacked_expression(a);
  9030. expr += " * ";
  9031. expr += to_extract_component_expression(b, col);
  9032. if (col + 1 < type.columns)
  9033. expr += ", ";
  9034. }
  9035. expr += ")";
  9036. emit_op(result_type, id, expr, should_forward(a) && should_forward(b));
  9037. inherit_expression_dependencies(id, a);
  9038. inherit_expression_dependencies(id, b);
  9039. break;
  9040. }
  9041. case OpVectorTimesMatrix:
  9042. case OpMatrixTimesVector:
  9043. {
  9044. if (!msl_options.invariant_float_math && !has_legacy_nocontract(ops[0], ops[1]))
  9045. {
  9046. CompilerGLSL::emit_instruction(instruction);
  9047. break;
  9048. }
  9049. // If the matrix needs transpose, just flip the multiply order.
  9050. auto *e = maybe_get<SPIRExpression>(ops[opcode == OpMatrixTimesVector ? 2 : 3]);
  9051. if (e && e->need_transpose)
  9052. {
  9053. e->need_transpose = false;
  9054. string expr;
  9055. if (opcode == OpMatrixTimesVector)
  9056. {
  9057. expr = join("spvFMulVectorMatrix(", to_enclosed_unpacked_expression(ops[3]), ", ",
  9058. to_unpacked_row_major_matrix_expression(ops[2]), ")");
  9059. }
  9060. else
  9061. {
  9062. expr = join("spvFMulMatrixVector(", to_unpacked_row_major_matrix_expression(ops[3]), ", ",
  9063. to_enclosed_unpacked_expression(ops[2]), ")");
  9064. }
  9065. bool forward = should_forward(ops[2]) && should_forward(ops[3]);
  9066. emit_op(ops[0], ops[1], expr, forward);
  9067. e->need_transpose = true;
  9068. inherit_expression_dependencies(ops[1], ops[2]);
  9069. inherit_expression_dependencies(ops[1], ops[3]);
  9070. }
  9071. else
  9072. {
  9073. if (opcode == OpMatrixTimesVector)
  9074. MSL_BFOP(spvFMulMatrixVector);
  9075. else
  9076. MSL_BFOP(spvFMulVectorMatrix);
  9077. }
  9078. break;
  9079. }
  9080. case OpMatrixTimesMatrix:
  9081. {
  9082. if (!msl_options.invariant_float_math && !has_legacy_nocontract(ops[0], ops[1]))
  9083. {
  9084. CompilerGLSL::emit_instruction(instruction);
  9085. break;
  9086. }
  9087. auto *a = maybe_get<SPIRExpression>(ops[2]);
  9088. auto *b = maybe_get<SPIRExpression>(ops[3]);
  9089. // If both matrices need transpose, we can multiply in flipped order and tag the expression as transposed.
  9090. // a^T * b^T = (b * a)^T.
  9091. if (a && b && a->need_transpose && b->need_transpose)
  9092. {
  9093. a->need_transpose = false;
  9094. b->need_transpose = false;
  9095. auto expr =
  9096. join("spvFMulMatrixMatrix(", enclose_expression(to_unpacked_row_major_matrix_expression(ops[3])), ", ",
  9097. enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])), ")");
  9098. bool forward = should_forward(ops[2]) && should_forward(ops[3]);
  9099. emit_transposed_op(ops[0], ops[1], expr, forward);
  9100. a->need_transpose = true;
  9101. b->need_transpose = true;
  9102. inherit_expression_dependencies(ops[1], ops[2]);
  9103. inherit_expression_dependencies(ops[1], ops[3]);
  9104. }
  9105. else
  9106. MSL_BFOP(spvFMulMatrixMatrix);
  9107. break;
  9108. }
  9109. case OpIAddCarry:
  9110. case OpISubBorrow:
  9111. {
  9112. uint32_t result_type = ops[0];
  9113. uint32_t result_id = ops[1];
  9114. uint32_t op0 = ops[2];
  9115. uint32_t op1 = ops[3];
  9116. auto &type = get<SPIRType>(result_type);
  9117. emit_uninitialized_temporary_expression(result_type, result_id);
  9118. auto &res_type = get<SPIRType>(type.member_types[1]);
  9119. if (opcode == OpIAddCarry)
  9120. {
  9121. statement(to_expression(result_id), ".", to_member_name(type, 0), " = ",
  9122. to_enclosed_unpacked_expression(op0), " + ", to_enclosed_unpacked_expression(op1), ";");
  9123. statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type),
  9124. "(1), ", type_to_glsl(res_type), "(0), ", to_unpacked_expression(result_id), ".", to_member_name(type, 0),
  9125. " >= max(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), "));");
  9126. }
  9127. else
  9128. {
  9129. statement(to_expression(result_id), ".", to_member_name(type, 0), " = ", to_enclosed_unpacked_expression(op0), " - ",
  9130. to_enclosed_unpacked_expression(op1), ";");
  9131. statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type),
  9132. "(1), ", type_to_glsl(res_type), "(0), ", to_enclosed_unpacked_expression(op0),
  9133. " >= ", to_enclosed_unpacked_expression(op1), ");");
  9134. }
  9135. break;
  9136. }
  9137. case OpUMulExtended:
  9138. case OpSMulExtended:
  9139. {
  9140. uint32_t result_type = ops[0];
  9141. uint32_t result_id = ops[1];
  9142. uint32_t op0 = ops[2];
  9143. uint32_t op1 = ops[3];
  9144. auto &type = get<SPIRType>(result_type);
  9145. auto &op_type = get<SPIRType>(type.member_types[0]);
  9146. auto input_type = opcode == OpSMulExtended ? int_type : uint_type;
  9147. string cast_op0, cast_op1;
  9148. binary_op_bitcast_helper(cast_op0, cast_op1, input_type, op0, op1, false);
  9149. auto expr = join("spvMulExtended<", type_to_glsl(type), ", ", type_to_glsl(op_type), ">(", cast_op0, ", ", cast_op1, ")");
  9150. emit_op(result_type, result_id, expr, true);
  9151. break;
  9152. }
  9153. case OpArrayLength:
  9154. {
  9155. auto &type = expression_type(ops[2]);
  9156. uint32_t offset = type_struct_member_offset(type, ops[3]);
  9157. uint32_t stride = type_struct_member_array_stride(type, ops[3]);
  9158. auto expr = join("(", to_buffer_size_expression(ops[2]), " - ", offset, ") / ", stride);
  9159. emit_op(ops[0], ops[1], expr, true);
  9160. break;
  9161. }
  9162. // Legacy sub-group stuff ...
  9163. case OpSubgroupBallotKHR:
  9164. case OpSubgroupFirstInvocationKHR:
  9165. case OpSubgroupReadInvocationKHR:
  9166. case OpSubgroupAllKHR:
  9167. case OpSubgroupAnyKHR:
  9168. case OpSubgroupAllEqualKHR:
  9169. emit_subgroup_op(instruction);
  9170. break;
  9171. // SPV_INTEL_shader_integer_functions2
  9172. case OpUCountLeadingZerosINTEL:
  9173. MSL_UFOP(clz);
  9174. break;
  9175. case OpUCountTrailingZerosINTEL:
  9176. MSL_UFOP(ctz);
  9177. break;
  9178. case OpAbsISubINTEL:
  9179. case OpAbsUSubINTEL:
  9180. MSL_BFOP(absdiff);
  9181. break;
  9182. case OpIAddSatINTEL:
  9183. case OpUAddSatINTEL:
  9184. MSL_BFOP(addsat);
  9185. break;
  9186. case OpIAverageINTEL:
  9187. case OpUAverageINTEL:
  9188. MSL_BFOP(hadd);
  9189. break;
  9190. case OpIAverageRoundedINTEL:
  9191. case OpUAverageRoundedINTEL:
  9192. MSL_BFOP(rhadd);
  9193. break;
  9194. case OpISubSatINTEL:
  9195. case OpUSubSatINTEL:
  9196. MSL_BFOP(subsat);
  9197. break;
  9198. case OpIMul32x16INTEL:
  9199. {
  9200. uint32_t result_type = ops[0];
  9201. uint32_t id = ops[1];
  9202. uint32_t a = ops[2], b = ops[3];
  9203. bool forward = should_forward(a) && should_forward(b);
  9204. emit_op(result_type, id, join("int(short(", to_unpacked_expression(a), ")) * int(short(", to_unpacked_expression(b), "))"), forward);
  9205. inherit_expression_dependencies(id, a);
  9206. inherit_expression_dependencies(id, b);
  9207. break;
  9208. }
  9209. case OpUMul32x16INTEL:
  9210. {
  9211. uint32_t result_type = ops[0];
  9212. uint32_t id = ops[1];
  9213. uint32_t a = ops[2], b = ops[3];
  9214. bool forward = should_forward(a) && should_forward(b);
  9215. emit_op(result_type, id, join("uint(ushort(", to_unpacked_expression(a), ")) * uint(ushort(", to_unpacked_expression(b), "))"), forward);
  9216. inherit_expression_dependencies(id, a);
  9217. inherit_expression_dependencies(id, b);
  9218. break;
  9219. }
  9220. // SPV_EXT_demote_to_helper_invocation
  9221. case OpDemoteToHelperInvocationEXT:
  9222. if (!msl_options.supports_msl_version(2, 3))
  9223. SPIRV_CROSS_THROW("discard_fragment() does not formally have demote semantics until MSL 2.3.");
  9224. CompilerGLSL::emit_instruction(instruction);
  9225. break;
  9226. case OpIsHelperInvocationEXT:
  9227. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  9228. SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.3 on iOS.");
  9229. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  9230. SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.1 on macOS.");
  9231. emit_op(ops[0], ops[1],
  9232. needs_manual_helper_invocation_updates() ? builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput) :
  9233. "simd_is_helper_thread()",
  9234. false);
  9235. break;
  9236. case OpBeginInvocationInterlockEXT:
  9237. case OpEndInvocationInterlockEXT:
  9238. if (!msl_options.supports_msl_version(2, 0))
  9239. SPIRV_CROSS_THROW("Raster order groups require MSL 2.0.");
  9240. break; // Nothing to do in the body
  9241. case OpConvertUToAccelerationStructureKHR:
  9242. SPIRV_CROSS_THROW("ConvertUToAccelerationStructure is not supported in MSL.");
  9243. case OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR:
  9244. SPIRV_CROSS_THROW("BindingTableRecordOffset is not supported in MSL.");
  9245. case OpRayQueryInitializeKHR:
  9246. {
  9247. flush_variable_declaration(ops[0]);
  9248. register_write(ops[0]);
  9249. add_spv_func_and_recompile(SPVFuncImplRayQueryIntersectionParams);
  9250. statement(to_expression(ops[0]), ".reset(", "ray(", to_expression(ops[4]), ", ", to_expression(ops[6]), ", ",
  9251. to_expression(ops[5]), ", ", to_expression(ops[7]), "), ", to_expression(ops[1]), ", ", to_expression(ops[3]),
  9252. ", spvMakeIntersectionParams(", to_expression(ops[2]), "));");
  9253. break;
  9254. }
  9255. case OpRayQueryProceedKHR:
  9256. {
  9257. flush_variable_declaration(ops[0]);
  9258. register_write(ops[2]);
  9259. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".next()"), false);
  9260. break;
  9261. }
  9262. #define MSL_RAY_QUERY_IS_CANDIDATE get<SPIRConstant>(ops[3]).scalar_i32() == 0
  9263. #define MSL_RAY_QUERY_GET_OP(op, msl_op) \
  9264. case OpRayQueryGet##op##KHR: \
  9265. flush_variable_declaration(ops[2]); \
  9266. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_" #msl_op "()"), false); \
  9267. break
  9268. #define MSL_RAY_QUERY_OP_INNER2(op, msl_prefix, msl_op) \
  9269. case OpRayQueryGet##op##KHR: \
  9270. flush_variable_declaration(ops[2]); \
  9271. if (MSL_RAY_QUERY_IS_CANDIDATE) \
  9272. emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_candidate_" #msl_op "()"), false); \
  9273. else \
  9274. emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_committed_" #msl_op "()"), false); \
  9275. break
  9276. #define MSL_RAY_QUERY_GET_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .get, msl_op)
  9277. #define MSL_RAY_QUERY_IS_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .is, msl_op)
  9278. MSL_RAY_QUERY_GET_OP(RayTMin, ray_min_distance);
  9279. MSL_RAY_QUERY_GET_OP(WorldRayOrigin, world_space_ray_origin);
  9280. MSL_RAY_QUERY_GET_OP(WorldRayDirection, world_space_ray_direction);
  9281. MSL_RAY_QUERY_GET_OP2(IntersectionInstanceId, instance_id);
  9282. MSL_RAY_QUERY_GET_OP2(IntersectionInstanceCustomIndex, user_instance_id);
  9283. MSL_RAY_QUERY_GET_OP2(IntersectionBarycentrics, triangle_barycentric_coord);
  9284. MSL_RAY_QUERY_GET_OP2(IntersectionPrimitiveIndex, primitive_id);
  9285. MSL_RAY_QUERY_GET_OP2(IntersectionGeometryIndex, geometry_id);
  9286. MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayOrigin, ray_origin);
  9287. MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayDirection, ray_direction);
  9288. MSL_RAY_QUERY_GET_OP2(IntersectionObjectToWorld, object_to_world_transform);
  9289. MSL_RAY_QUERY_GET_OP2(IntersectionWorldToObject, world_to_object_transform);
  9290. MSL_RAY_QUERY_IS_OP2(IntersectionFrontFace, triangle_front_facing);
  9291. case OpRayQueryGetIntersectionTypeKHR:
  9292. flush_variable_declaration(ops[2]);
  9293. if (MSL_RAY_QUERY_IS_CANDIDATE)
  9294. emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_candidate_intersection_type()) - 1"),
  9295. false);
  9296. else
  9297. emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_committed_intersection_type())"), false);
  9298. break;
  9299. case OpRayQueryGetIntersectionTKHR:
  9300. flush_variable_declaration(ops[2]);
  9301. if (MSL_RAY_QUERY_IS_CANDIDATE)
  9302. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_candidate_triangle_distance()"), false);
  9303. else
  9304. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_committed_distance()"), false);
  9305. break;
  9306. case OpRayQueryGetIntersectionCandidateAABBOpaqueKHR:
  9307. {
  9308. flush_variable_declaration(ops[0]);
  9309. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".is_candidate_non_opaque_bounding_box()"), false);
  9310. break;
  9311. }
  9312. case OpRayQueryConfirmIntersectionKHR:
  9313. flush_variable_declaration(ops[0]);
  9314. register_write(ops[0]);
  9315. statement(to_expression(ops[0]), ".commit_triangle_intersection();");
  9316. break;
  9317. case OpRayQueryGenerateIntersectionKHR:
  9318. flush_variable_declaration(ops[0]);
  9319. register_write(ops[0]);
  9320. statement(to_expression(ops[0]), ".commit_bounding_box_intersection(", to_expression(ops[1]), ");");
  9321. break;
  9322. case OpRayQueryTerminateKHR:
  9323. flush_variable_declaration(ops[0]);
  9324. register_write(ops[0]);
  9325. statement(to_expression(ops[0]), ".abort();");
  9326. break;
  9327. #undef MSL_RAY_QUERY_GET_OP
  9328. #undef MSL_RAY_QUERY_IS_CANDIDATE
  9329. #undef MSL_RAY_QUERY_IS_OP2
  9330. #undef MSL_RAY_QUERY_GET_OP2
  9331. #undef MSL_RAY_QUERY_OP_INNER2
  9332. case OpConvertPtrToU:
  9333. case OpConvertUToPtr:
  9334. case OpBitcast:
  9335. {
  9336. auto &type = get<SPIRType>(ops[0]);
  9337. auto &input_type = expression_type(ops[2]);
  9338. if (opcode != OpBitcast || is_pointer(type) || is_pointer(input_type))
  9339. {
  9340. string op;
  9341. if ((type.vecsize == 1 || is_pointer(type)) && (input_type.vecsize == 1 || is_pointer(input_type)))
  9342. op = join("reinterpret_cast<", type_to_glsl(type), ">(", to_unpacked_expression(ops[2]), ")");
  9343. else if (input_type.vecsize == 2)
  9344. op = join("reinterpret_cast<", type_to_glsl(type), ">(as_type<ulong>(", to_unpacked_expression(ops[2]), "))");
  9345. else
  9346. op = join("as_type<", type_to_glsl(type), ">(reinterpret_cast<ulong>(", to_unpacked_expression(ops[2]), "))");
  9347. emit_op(ops[0], ops[1], op, should_forward(ops[2]));
  9348. inherit_expression_dependencies(ops[1], ops[2]);
  9349. }
  9350. else
  9351. CompilerGLSL::emit_instruction(instruction);
  9352. break;
  9353. }
  9354. case OpSDot:
  9355. case OpUDot:
  9356. case OpSUDot:
  9357. {
  9358. uint32_t result_type = ops[0];
  9359. uint32_t id = ops[1];
  9360. uint32_t vec1 = ops[2];
  9361. uint32_t vec2 = ops[3];
  9362. auto &input_type1 = expression_type(vec1);
  9363. auto &input_type2 = expression_type(vec2);
  9364. string vec1input, vec2input;
  9365. auto input_size = input_type1.vecsize;
  9366. if (instruction.length == 5)
  9367. {
  9368. if (ops[4] == PackedVectorFormatPackedVectorFormat4x8Bit)
  9369. {
  9370. string type = opcode == OpSDot || opcode == OpSUDot ? "char4" : "uchar4";
  9371. vec1input = join("as_type<", type, ">(", to_expression(vec1), ")");
  9372. type = opcode == OpSDot ? "char4" : "uchar4";
  9373. vec2input = join("as_type<", type, ">(", to_expression(vec2), ")");
  9374. input_size = 4;
  9375. }
  9376. else
  9377. SPIRV_CROSS_THROW("Packed vector formats other than 4x8Bit for integer dot product is not supported.");
  9378. }
  9379. else
  9380. {
  9381. // Inputs are sign or zero-extended to their target width.
  9382. SPIRType::BaseType vec1_expected_type =
  9383. opcode != OpUDot ?
  9384. to_signed_basetype(input_type1.width) :
  9385. to_unsigned_basetype(input_type1.width);
  9386. SPIRType::BaseType vec2_expected_type =
  9387. opcode != OpSDot ?
  9388. to_unsigned_basetype(input_type2.width) :
  9389. to_signed_basetype(input_type2.width);
  9390. vec1input = bitcast_expression(vec1_expected_type, vec1);
  9391. vec2input = bitcast_expression(vec2_expected_type, vec2);
  9392. }
  9393. auto &type = get<SPIRType>(result_type);
  9394. // We'll get the appropriate sign-extend or zero-extend, no matter which type we cast to here.
  9395. // The addition in reduce_add is sign-invariant.
  9396. auto result_type_cast = join(type_to_glsl(type), input_size);
  9397. string exp = join("reduce_add(",
  9398. result_type_cast, "(", vec1input, ") * ",
  9399. result_type_cast, "(", vec2input, "))");
  9400. emit_op(result_type, id, exp, should_forward(vec1) && should_forward(vec2));
  9401. inherit_expression_dependencies(id, vec1);
  9402. inherit_expression_dependencies(id, vec2);
  9403. break;
  9404. }
  9405. case OpSDotAccSat:
  9406. case OpUDotAccSat:
  9407. case OpSUDotAccSat:
  9408. {
  9409. uint32_t result_type = ops[0];
  9410. uint32_t id = ops[1];
  9411. uint32_t vec1 = ops[2];
  9412. uint32_t vec2 = ops[3];
  9413. uint32_t acc = ops[4];
  9414. auto input_type1 = expression_type(vec1);
  9415. auto input_type2 = expression_type(vec2);
  9416. string vec1input, vec2input;
  9417. if (instruction.length == 6)
  9418. {
  9419. if (ops[5] == PackedVectorFormatPackedVectorFormat4x8Bit)
  9420. {
  9421. string type = opcode == OpSDotAccSat || opcode == OpSUDotAccSat ? "char4" : "uchar4";
  9422. vec1input = join("as_type<", type, ">(", to_expression(vec1), ")");
  9423. type = opcode == OpSDotAccSat ? "char4" : "uchar4";
  9424. vec2input = join("as_type<", type, ">(", to_expression(vec2), ")");
  9425. input_type1.vecsize = 4;
  9426. input_type2.vecsize = 4;
  9427. }
  9428. else
  9429. SPIRV_CROSS_THROW("Packed vector formats other than 4x8Bit for integer dot product is not supported.");
  9430. }
  9431. else
  9432. {
  9433. // Inputs are sign or zero-extended to their target width.
  9434. SPIRType::BaseType vec1_expected_type =
  9435. opcode != OpUDotAccSat ?
  9436. to_signed_basetype(input_type1.width) :
  9437. to_unsigned_basetype(input_type1.width);
  9438. SPIRType::BaseType vec2_expected_type =
  9439. opcode != OpSDotAccSat ?
  9440. to_unsigned_basetype(input_type2.width) :
  9441. to_signed_basetype(input_type2.width);
  9442. vec1input = bitcast_expression(vec1_expected_type, vec1);
  9443. vec2input = bitcast_expression(vec2_expected_type, vec2);
  9444. }
  9445. auto &type = get<SPIRType>(result_type);
  9446. SPIRType::BaseType pre_saturate_type =
  9447. opcode != OpUDotAccSat ?
  9448. to_signed_basetype(type.width) :
  9449. to_unsigned_basetype(type.width);
  9450. input_type1.basetype = pre_saturate_type;
  9451. input_type2.basetype = pre_saturate_type;
  9452. string exp = join(type_to_glsl(type), "(addsat(reduce_add(",
  9453. type_to_glsl(input_type1), "(", vec1input, ") * ",
  9454. type_to_glsl(input_type2), "(", vec2input, ")), ",
  9455. bitcast_expression(pre_saturate_type, acc), "))");
  9456. emit_op(result_type, id, exp, should_forward(vec1) && should_forward(vec2));
  9457. inherit_expression_dependencies(id, vec1);
  9458. inherit_expression_dependencies(id, vec2);
  9459. break;
  9460. }
  9461. case OpSetMeshOutputsEXT:
  9462. {
  9463. flush_variable_declaration(builtin_mesh_primitive_indices_id);
  9464. add_spv_func_and_recompile(SPVFuncImplSetMeshOutputsEXT);
  9465. statement("spvSetMeshOutputsEXT(gl_LocalInvocationIndex, spvMeshSizes, ", to_unpacked_expression(ops[0]), ", ", to_unpacked_expression(ops[1]), ");");
  9466. break;
  9467. }
  9468. case OpAssumeTrueKHR:
  9469. {
  9470. auto condition = ops[0];
  9471. statement(join("SPV_ASSUME(", to_unpacked_expression(condition), ")"));
  9472. break;
  9473. }
  9474. case OpExpectKHR:
  9475. {
  9476. auto result_type = ops[0];
  9477. auto ret = ops[1];
  9478. auto value = ops[2];
  9479. auto exp_value = ops[3];
  9480. auto exp = join("SPV_EXPECT(", to_unpacked_expression(value), ", ", to_unpacked_expression(exp_value), ")");
  9481. emit_op(result_type, ret, exp, should_forward(value), should_forward(exp_value));
  9482. inherit_expression_dependencies(ret, value);
  9483. inherit_expression_dependencies(ret, exp_value);
  9484. break;
  9485. }
  9486. default:
  9487. CompilerGLSL::emit_instruction(instruction);
  9488. break;
  9489. }
  9490. previous_instruction_opcode = opcode;
  9491. }
  9492. void CompilerMSL::emit_texture_op(const Instruction &i, bool sparse)
  9493. {
  9494. if (sparse)
  9495. SPIRV_CROSS_THROW("Sparse feedback not yet supported in MSL.");
  9496. if (msl_options.use_framebuffer_fetch_subpasses)
  9497. {
  9498. auto *ops = stream(i);
  9499. uint32_t result_type_id = ops[0];
  9500. uint32_t id = ops[1];
  9501. uint32_t img = ops[2];
  9502. auto &type = expression_type(img);
  9503. auto &imgtype = get<SPIRType>(type.self);
  9504. // Use Metal's native frame-buffer fetch API for subpass inputs.
  9505. if (imgtype.image.dim == DimSubpassData)
  9506. {
  9507. // Subpass inputs cannot be invalidated,
  9508. // so just forward the expression directly.
  9509. string expr = to_expression(img);
  9510. emit_op(result_type_id, id, expr, true);
  9511. return;
  9512. }
  9513. }
  9514. // Fallback to default implementation
  9515. CompilerGLSL::emit_texture_op(i, sparse);
  9516. }
  9517. void CompilerMSL::emit_barrier(uint32_t id_exe_scope, uint32_t id_mem_scope, uint32_t id_mem_sem)
  9518. {
  9519. auto model = get_execution_model();
  9520. if (model != ExecutionModelGLCompute && model != ExecutionModelTaskEXT &&
  9521. model != ExecutionModelMeshEXT && !is_tesc_shader())
  9522. {
  9523. return;
  9524. }
  9525. uint32_t exe_scope = id_exe_scope ? evaluate_constant_u32(id_exe_scope) : uint32_t(ScopeInvocation);
  9526. uint32_t mem_scope = id_mem_scope ? evaluate_constant_u32(id_mem_scope) : uint32_t(ScopeInvocation);
  9527. // Use the wider of the two scopes (smaller value)
  9528. exe_scope = min(exe_scope, mem_scope);
  9529. if (msl_options.emulate_subgroups && exe_scope >= ScopeSubgroup && !id_mem_sem)
  9530. // In this case, we assume a "subgroup" size of 1. The barrier, then, is a noop.
  9531. return;
  9532. string bar_stmt;
  9533. if (!id_exe_scope && msl_options.supports_msl_version(3, 2))
  9534. {
  9535. // Just took 10 years to get a proper barrier, but hey!
  9536. bar_stmt = "atomic_thread_fence";
  9537. }
  9538. else
  9539. {
  9540. if ((msl_options.is_ios() && msl_options.supports_msl_version(1, 2)) || msl_options.supports_msl_version(2))
  9541. bar_stmt = exe_scope < ScopeSubgroup ? "threadgroup_barrier" : "simdgroup_barrier";
  9542. else
  9543. bar_stmt = "threadgroup_barrier";
  9544. }
  9545. bar_stmt += "(";
  9546. uint32_t mem_sem = id_mem_sem ? evaluate_constant_u32(id_mem_sem) : uint32_t(MemorySemanticsMaskNone);
  9547. // Use the | operator to combine flags if we can.
  9548. if (msl_options.supports_msl_version(1, 2))
  9549. {
  9550. string mem_flags;
  9551. // For tesc shaders, this also affects objects in the Output storage class.
  9552. // Since in Metal, these are placed in a device buffer, we have to sync device memory here.
  9553. if (is_tesc_shader() ||
  9554. (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)))
  9555. mem_flags += "mem_flags::mem_device";
  9556. // Fix tessellation patch function processing
  9557. if (is_tesc_shader() || (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)))
  9558. {
  9559. if (!mem_flags.empty())
  9560. mem_flags += " | ";
  9561. mem_flags += "mem_flags::mem_threadgroup";
  9562. }
  9563. if (mem_sem & MemorySemanticsImageMemoryMask)
  9564. {
  9565. if (!mem_flags.empty())
  9566. mem_flags += " | ";
  9567. mem_flags += "mem_flags::mem_texture";
  9568. }
  9569. if (mem_flags.empty())
  9570. mem_flags = "mem_flags::mem_none";
  9571. bar_stmt += mem_flags;
  9572. }
  9573. else
  9574. {
  9575. if ((mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)) &&
  9576. (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)))
  9577. bar_stmt += "mem_flags::mem_device_and_threadgroup";
  9578. else if (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask))
  9579. bar_stmt += "mem_flags::mem_device";
  9580. else if (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask))
  9581. bar_stmt += "mem_flags::mem_threadgroup";
  9582. else if (mem_sem & MemorySemanticsImageMemoryMask)
  9583. bar_stmt += "mem_flags::mem_texture";
  9584. else
  9585. bar_stmt += "mem_flags::mem_none";
  9586. }
  9587. if (!id_exe_scope && msl_options.supports_msl_version(3, 2))
  9588. {
  9589. // If there's no device-related memory in the barrier, demote to workgroup scope.
  9590. // glslang seems to emit device scope even for memoryBarrierShared().
  9591. if (mem_scope == ScopeDevice &&
  9592. (mem_sem & (MemorySemanticsUniformMemoryMask |
  9593. MemorySemanticsImageMemoryMask |
  9594. MemorySemanticsCrossWorkgroupMemoryMask)) == 0)
  9595. {
  9596. mem_scope = ScopeWorkgroup;
  9597. }
  9598. // MSL 3.2 only supports seq_cst or relaxed.
  9599. if (mem_sem & (MemorySemanticsAcquireReleaseMask |
  9600. MemorySemanticsAcquireMask |
  9601. MemorySemanticsReleaseMask |
  9602. MemorySemanticsSequentiallyConsistentMask))
  9603. {
  9604. bar_stmt += ", memory_order_seq_cst";
  9605. }
  9606. else
  9607. {
  9608. bar_stmt += ", memory_order_relaxed";
  9609. }
  9610. switch (mem_scope)
  9611. {
  9612. case ScopeDevice:
  9613. bar_stmt += ", thread_scope_device";
  9614. break;
  9615. case ScopeWorkgroup:
  9616. bar_stmt += ", thread_scope_threadgroup";
  9617. break;
  9618. case ScopeSubgroup:
  9619. bar_stmt += ", thread_scope_subgroup";
  9620. break;
  9621. case ScopeInvocation:
  9622. bar_stmt += ", thread_scope_thread";
  9623. break;
  9624. default:
  9625. // The default argument is device, which is conservative.
  9626. break;
  9627. }
  9628. }
  9629. bar_stmt += ");";
  9630. statement(bar_stmt);
  9631. assert(current_emitting_block);
  9632. flush_control_dependent_expressions(current_emitting_block->self);
  9633. flush_all_active_variables();
  9634. }
  9635. static bool storage_class_array_is_thread(StorageClass storage)
  9636. {
  9637. switch (storage)
  9638. {
  9639. case StorageClassInput:
  9640. case StorageClassOutput:
  9641. case StorageClassGeneric:
  9642. case StorageClassFunction:
  9643. case StorageClassPrivate:
  9644. return true;
  9645. default:
  9646. return false;
  9647. }
  9648. }
  9649. bool CompilerMSL::emit_array_copy(const char *expr, uint32_t lhs_id, uint32_t rhs_id,
  9650. StorageClass lhs_storage, StorageClass rhs_storage)
  9651. {
  9652. // Allow Metal to use the array<T> template to make arrays a value type.
  9653. // This, however, cannot be used for threadgroup address specifiers, so consider the custom array copy as fallback.
  9654. bool lhs_is_thread_storage = storage_class_array_is_thread(lhs_storage);
  9655. bool rhs_is_thread_storage = storage_class_array_is_thread(rhs_storage);
  9656. bool lhs_is_array_template = lhs_is_thread_storage || lhs_storage == StorageClassWorkgroup;
  9657. bool rhs_is_array_template = rhs_is_thread_storage || rhs_storage == StorageClassWorkgroup;
  9658. // Special considerations for stage IO variables.
  9659. // If the variable is actually backed by non-user visible device storage, we use array templates for those.
  9660. //
  9661. // Another special consideration is given to thread local variables which happen to have Offset decorations
  9662. // applied to them. Block-like types do not use array templates, so we need to force POD path if we detect
  9663. // these scenarios. This check isn't perfect since it would be technically possible to mix and match these things,
  9664. // and for a fully correct solution we might have to track array template state through access chains as well,
  9665. // but for all reasonable use cases, this should suffice.
  9666. // This special case should also only apply to Function/Private storage classes.
  9667. // We should not check backing variable for temporaries.
  9668. auto *lhs_var = maybe_get_backing_variable(lhs_id);
  9669. if (lhs_var && lhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(lhs_var->storage))
  9670. lhs_is_array_template = true;
  9671. else if (lhs_var && lhs_storage != StorageClassGeneric && type_is_explicit_layout(get<SPIRType>(lhs_var->basetype)))
  9672. lhs_is_array_template = false;
  9673. auto *rhs_var = maybe_get_backing_variable(rhs_id);
  9674. if (rhs_var && rhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(rhs_var->storage))
  9675. rhs_is_array_template = true;
  9676. else if (rhs_var && rhs_storage != StorageClassGeneric && type_is_explicit_layout(get<SPIRType>(rhs_var->basetype)))
  9677. rhs_is_array_template = false;
  9678. // If threadgroup storage qualifiers are *not* used:
  9679. // Avoid spvCopy* wrapper functions; Otherwise, spvUnsafeArray<> template cannot be used with that storage qualifier.
  9680. if (lhs_is_array_template && rhs_is_array_template && !using_builtin_array())
  9681. {
  9682. // Fall back to normal copy path.
  9683. return false;
  9684. }
  9685. else
  9686. {
  9687. // Ensure the LHS variable has been declared
  9688. if (lhs_var)
  9689. flush_variable_declaration(lhs_var->self);
  9690. string lhs;
  9691. if (expr)
  9692. lhs = expr;
  9693. else
  9694. lhs = to_expression(lhs_id);
  9695. // Assignment from an array initializer is fine.
  9696. auto &type = expression_type(rhs_id);
  9697. auto *var = maybe_get_backing_variable(rhs_id);
  9698. // Unfortunately, we cannot template on address space in MSL,
  9699. // so explicit address space redirection it is ...
  9700. bool is_constant = false;
  9701. if (ir.ids[rhs_id].get_type() == TypeConstant)
  9702. {
  9703. is_constant = true;
  9704. }
  9705. else if (var && var->remapped_variable && var->statically_assigned &&
  9706. ir.ids[var->static_expression].get_type() == TypeConstant)
  9707. {
  9708. is_constant = true;
  9709. }
  9710. else if (rhs_storage == StorageClassUniform || rhs_storage == StorageClassUniformConstant)
  9711. {
  9712. is_constant = true;
  9713. }
  9714. // For the case where we have OpLoad triggering an array copy,
  9715. // we cannot easily detect this case ahead of time since it's
  9716. // context dependent. We might have to force a recompile here
  9717. // if this is the only use of array copies in our shader.
  9718. add_spv_func_and_recompile(type.array.size() > 1 ? SPVFuncImplArrayCopyMultidim : SPVFuncImplArrayCopy);
  9719. const char *tag = nullptr;
  9720. if (lhs_is_thread_storage && is_constant)
  9721. tag = "FromConstantToStack";
  9722. else if (lhs_storage == StorageClassWorkgroup && is_constant)
  9723. tag = "FromConstantToThreadGroup";
  9724. else if (lhs_is_thread_storage && rhs_is_thread_storage)
  9725. tag = "FromStackToStack";
  9726. else if (lhs_storage == StorageClassWorkgroup && rhs_is_thread_storage)
  9727. tag = "FromStackToThreadGroup";
  9728. else if (lhs_is_thread_storage && rhs_storage == StorageClassWorkgroup)
  9729. tag = "FromThreadGroupToStack";
  9730. else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassWorkgroup)
  9731. tag = "FromThreadGroupToThreadGroup";
  9732. else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassStorageBuffer)
  9733. tag = "FromDeviceToDevice";
  9734. else if (lhs_storage == StorageClassStorageBuffer && is_constant)
  9735. tag = "FromConstantToDevice";
  9736. else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassWorkgroup)
  9737. tag = "FromThreadGroupToDevice";
  9738. else if (lhs_storage == StorageClassStorageBuffer && rhs_is_thread_storage)
  9739. tag = "FromStackToDevice";
  9740. else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassStorageBuffer)
  9741. tag = "FromDeviceToThreadGroup";
  9742. else if (lhs_is_thread_storage && rhs_storage == StorageClassStorageBuffer)
  9743. tag = "FromDeviceToStack";
  9744. else
  9745. SPIRV_CROSS_THROW("Unknown storage class used for copying arrays.");
  9746. // Pass internal array of spvUnsafeArray<> into wrapper functions
  9747. if (lhs_is_array_template && rhs_is_array_template && !msl_options.force_native_arrays)
  9748. statement("spvArrayCopy", tag, "(", lhs, ".elements, ", to_expression(rhs_id), ".elements);");
  9749. if (lhs_is_array_template && !msl_options.force_native_arrays)
  9750. statement("spvArrayCopy", tag, "(", lhs, ".elements, ", to_expression(rhs_id), ");");
  9751. else if (rhs_is_array_template && !msl_options.force_native_arrays)
  9752. statement("spvArrayCopy", tag, "(", lhs, ", ", to_expression(rhs_id), ".elements);");
  9753. else
  9754. statement("spvArrayCopy", tag, "(", lhs, ", ", to_expression(rhs_id), ");");
  9755. }
  9756. return true;
  9757. }
  9758. uint32_t CompilerMSL::get_physical_tess_level_array_size(BuiltIn builtin) const
  9759. {
  9760. if (is_tessellating_triangles())
  9761. return builtin == BuiltInTessLevelInner ? 1 : 3;
  9762. else
  9763. return builtin == BuiltInTessLevelInner ? 2 : 4;
  9764. }
  9765. // Since MSL does not allow arrays to be copied via simple variable assignment,
  9766. // if the LHS and RHS represent an assignment of an entire array, it must be
  9767. // implemented by calling an array copy function.
  9768. // Returns whether the struct assignment was emitted.
  9769. bool CompilerMSL::maybe_emit_array_assignment(uint32_t id_lhs, uint32_t id_rhs)
  9770. {
  9771. // We only care about assignments of an entire array
  9772. auto &type = expression_type(id_lhs);
  9773. if (!is_array(get_pointee_type(type)))
  9774. return false;
  9775. auto *var = maybe_get<SPIRVariable>(id_lhs);
  9776. // Is this a remapped, static constant? Don't do anything.
  9777. if (var && var->remapped_variable && var->statically_assigned)
  9778. return true;
  9779. if (ir.ids[id_rhs].get_type() == TypeConstant && var && var->deferred_declaration)
  9780. {
  9781. // Special case, if we end up declaring a variable when assigning the constant array,
  9782. // we can avoid the copy by directly assigning the constant expression.
  9783. // This is likely necessary to be able to use a variable as a true look-up table, as it is unlikely
  9784. // the compiler will be able to optimize the spvArrayCopy() into a constant LUT.
  9785. // After a variable has been declared, we can no longer assign constant arrays in MSL unfortunately.
  9786. statement(to_expression(id_lhs), " = ", constant_expression(get<SPIRConstant>(id_rhs)), ";");
  9787. return true;
  9788. }
  9789. if (is_tesc_shader() && has_decoration(id_lhs, DecorationBuiltIn))
  9790. {
  9791. auto builtin = BuiltIn(get_decoration(id_lhs, DecorationBuiltIn));
  9792. // Need to manually unroll the array store.
  9793. if (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter)
  9794. {
  9795. uint32_t array_size = get_physical_tess_level_array_size(builtin);
  9796. if (array_size == 1)
  9797. statement(to_expression(id_lhs), " = half(", to_expression(id_rhs), "[0]);");
  9798. else
  9799. {
  9800. for (uint32_t i = 0; i < array_size; i++)
  9801. statement(to_expression(id_lhs), "[", i, "] = half(", to_expression(id_rhs), "[", i, "]);");
  9802. }
  9803. return true;
  9804. }
  9805. }
  9806. auto lhs_storage = get_expression_effective_storage_class(id_lhs);
  9807. auto rhs_storage = get_expression_effective_storage_class(id_rhs);
  9808. if (!emit_array_copy(nullptr, id_lhs, id_rhs, lhs_storage, rhs_storage))
  9809. return false;
  9810. register_write(id_lhs);
  9811. return true;
  9812. }
  9813. // Emits one of the atomic functions. In MSL, the atomic functions operate on pointers
  9814. void CompilerMSL::emit_atomic_func_op(uint32_t result_type, uint32_t result_id, const char *op, Op opcode,
  9815. uint32_t mem_order_1, uint32_t mem_order_2, bool has_mem_order_2, uint32_t obj, uint32_t op1,
  9816. bool op1_is_pointer, bool op1_is_literal, uint32_t op2)
  9817. {
  9818. string exp;
  9819. auto &ptr_type = expression_type(obj);
  9820. auto &type = get_pointee_type(ptr_type);
  9821. auto expected_type = type.basetype;
  9822. if (opcode == OpAtomicUMax || opcode == OpAtomicUMin)
  9823. expected_type = to_unsigned_basetype(type.width);
  9824. else if (opcode == OpAtomicSMax || opcode == OpAtomicSMin)
  9825. expected_type = to_signed_basetype(type.width);
  9826. bool use_native_image_atomic;
  9827. if (msl_options.supports_msl_version(3, 1))
  9828. use_native_image_atomic = check_atomic_image(obj);
  9829. else
  9830. use_native_image_atomic = false;
  9831. if (type.width == 64)
  9832. SPIRV_CROSS_THROW("MSL currently does not support 64-bit atomics.");
  9833. auto remapped_type = type;
  9834. remapped_type.basetype = expected_type;
  9835. auto *var = maybe_get_backing_variable(obj);
  9836. const auto *res_type = var ? &get<SPIRType>(var->basetype) : nullptr;
  9837. assert(type.storage != StorageClassImage || res_type);
  9838. bool is_atomic_compare_exchange_strong = op1_is_pointer && op1;
  9839. bool check_discard = opcode != OpAtomicLoad && needs_frag_discard_checks() &&
  9840. ptr_type.storage != StorageClassWorkgroup;
  9841. // Even compare exchange atomics are vec4 on metal for ... reasons :v
  9842. uint32_t vec4_temporary_id = 0;
  9843. if (use_native_image_atomic && is_atomic_compare_exchange_strong)
  9844. {
  9845. uint32_t &tmp_id = extra_sub_expressions[result_id];
  9846. if (!tmp_id)
  9847. {
  9848. tmp_id = ir.increase_bound_by(2);
  9849. auto vec4_type = get<SPIRType>(result_type);
  9850. vec4_type.vecsize = 4;
  9851. set<SPIRType>(tmp_id + 1, vec4_type);
  9852. }
  9853. vec4_temporary_id = tmp_id;
  9854. }
  9855. if (check_discard)
  9856. {
  9857. if (is_atomic_compare_exchange_strong)
  9858. {
  9859. // We're already emitting a CAS loop here; a conditional won't hurt.
  9860. emit_uninitialized_temporary_expression(result_type, result_id);
  9861. if (vec4_temporary_id)
  9862. emit_uninitialized_temporary_expression(vec4_temporary_id + 1, vec4_temporary_id);
  9863. statement("if (!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), ")");
  9864. begin_scope();
  9865. }
  9866. else
  9867. exp = join("(!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), " ? ");
  9868. }
  9869. if (use_native_image_atomic)
  9870. {
  9871. auto obj_expression = to_expression(obj);
  9872. auto split_index = obj_expression.find_first_of('@');
  9873. bool needs_reinterpret = opcode == OpAtomicUMax || opcode == OpAtomicUMin || opcode == OpAtomicSMax || opcode == OpAtomicSMin;
  9874. needs_reinterpret &= type.basetype != expected_type;
  9875. SPIRVariable *backing_var = nullptr;
  9876. // Try to avoid waiting until not force recompile later mode to enable force recompile later
  9877. if (needs_reinterpret && (backing_var = maybe_get_backing_variable(obj)))
  9878. add_spv_func_and_recompile(SPVFuncImplTextureCast);
  9879. // Will only be false if we're in "force recompile later" mode.
  9880. if (split_index != string::npos)
  9881. {
  9882. auto coord = obj_expression.substr(split_index + 1);
  9883. auto image_expr = obj_expression.substr(0, split_index);
  9884. // Handle problem cases with sign where we need signed min/max on a uint image for example.
  9885. // It seems to work to cast the texture type itself, even if it is probably wildly outside of spec,
  9886. // but SPIR-V requires this to work.
  9887. if (needs_reinterpret && backing_var)
  9888. {
  9889. assert(spv_function_implementations.count(SPVFuncImplTextureCast) && "Should have been added above");
  9890. const auto *backing_type = &get<SPIRType>(backing_var->basetype);
  9891. while (backing_type->op != OpTypeImage)
  9892. backing_type = &get<SPIRType>(backing_type->parent_type);
  9893. auto img_type = *backing_type;
  9894. auto tmp_type = type;
  9895. tmp_type.basetype = expected_type;
  9896. img_type.image.type = ir.increase_bound_by(1);
  9897. set<SPIRType>(img_type.image.type, tmp_type);
  9898. image_expr = join("spvTextureCast<", type_to_glsl(img_type, obj), ">(", image_expr, ")");
  9899. }
  9900. exp += join(image_expr, ".", op, "(");
  9901. if (ptr_type.storage == StorageClassImage && (res_type->image.arrayed || res_type->image.dim == DimCube))
  9902. {
  9903. switch (res_type->image.dim)
  9904. {
  9905. case Dim1D:
  9906. if (msl_options.texture_1D_as_2D)
  9907. exp += join("uint2(", coord, ".x, 0), ", coord, ".y");
  9908. else
  9909. exp += join(coord, ".x, ", coord, ".y");
  9910. break;
  9911. case Dim2D:
  9912. exp += join(coord, ".xy, ", coord, ".z");
  9913. break;
  9914. case DimCube:
  9915. if (!msl_options.supports_msl_version(4, 0))
  9916. SPIRV_CROSS_THROW("Cannot do atomics on Cube textures before 4.0.");
  9917. if (res_type->image.arrayed)
  9918. exp += join(coord, ".xy, ", coord, ".z % 6u, ", coord, ".z / 6u");
  9919. else
  9920. exp += join(coord, ".xy, ", coord, ".z");
  9921. break;
  9922. default:
  9923. SPIRV_CROSS_THROW("Cannot do atomics on unknown dimension.");
  9924. }
  9925. }
  9926. else if (ptr_type.storage == StorageClassImage && res_type->image.dim == Dim1D && msl_options.texture_1D_as_2D)
  9927. exp += join("uint2(", coord, ", 0)");
  9928. else
  9929. exp += coord;
  9930. }
  9931. else
  9932. {
  9933. exp += obj_expression;
  9934. }
  9935. }
  9936. else
  9937. {
  9938. exp += string(op) + "_explicit(";
  9939. exp += "(";
  9940. // Emulate texture2D atomic operations
  9941. if (ptr_type.storage == StorageClassImage)
  9942. {
  9943. auto &flags = ir.get_decoration_bitset(var->self);
  9944. if (decoration_flags_signal_volatile(flags))
  9945. exp += "volatile ";
  9946. exp += "device";
  9947. }
  9948. else if (var && ptr_type.storage != StorageClassPhysicalStorageBuffer)
  9949. {
  9950. exp += get_variable_address_space(*var);
  9951. }
  9952. else
  9953. {
  9954. // Fallback scenario, could happen for raw pointers.
  9955. exp += ptr_type.storage == StorageClassWorkgroup ? "threadgroup" : "device";
  9956. }
  9957. exp += " atomic_";
  9958. // For signed and unsigned min/max, we can signal this through the pointer type.
  9959. // There is no other way, since C++ does not have explicit signage for atomics.
  9960. exp += type_to_glsl(remapped_type);
  9961. exp += "*)";
  9962. exp += "&";
  9963. exp += to_enclosed_expression(obj);
  9964. }
  9965. if (is_atomic_compare_exchange_strong)
  9966. {
  9967. assert(strcmp(op, "atomic_compare_exchange_weak") == 0);
  9968. assert(op2);
  9969. assert(has_mem_order_2);
  9970. exp += ", &";
  9971. exp += to_name(vec4_temporary_id ? vec4_temporary_id : result_id);
  9972. exp += ", ";
  9973. exp += to_expression(op2);
  9974. if (!use_native_image_atomic)
  9975. {
  9976. exp += ", ";
  9977. exp += get_memory_order(mem_order_1);
  9978. exp += ", ";
  9979. exp += get_memory_order(mem_order_2);
  9980. }
  9981. exp += ")";
  9982. // MSL only supports the weak atomic compare exchange, so emit a CAS loop here.
  9983. // The MSL function returns false if the atomic write fails OR the comparison test fails,
  9984. // so we must validate that it wasn't the comparison test that failed before continuing
  9985. // the CAS loop, otherwise it will loop infinitely, with the comparison test always failing.
  9986. // The function updates the comparator value from the memory value, so the additional
  9987. // comparison test evaluates the memory value against the expected value.
  9988. if (!check_discard)
  9989. {
  9990. emit_uninitialized_temporary_expression(result_type, result_id);
  9991. if (vec4_temporary_id)
  9992. emit_uninitialized_temporary_expression(vec4_temporary_id + 1, vec4_temporary_id);
  9993. }
  9994. statement("do");
  9995. begin_scope();
  9996. string scalar_expression;
  9997. if (vec4_temporary_id)
  9998. scalar_expression = join(to_expression(vec4_temporary_id), ".x");
  9999. else
  10000. scalar_expression = to_expression(result_id);
  10001. statement(scalar_expression, " = ", to_expression(op1), ";");
  10002. end_scope_decl(join("while (!", exp, " && ", scalar_expression, " == ", to_enclosed_expression(op1), ")"));
  10003. if (vec4_temporary_id)
  10004. statement(to_expression(result_id), " = ", scalar_expression, ";");
  10005. // Vulkan: (section 9.29: ... and values returned by atomic instructions in helper invocations are undefined)
  10006. if (check_discard)
  10007. {
  10008. end_scope();
  10009. statement("else");
  10010. begin_scope();
  10011. statement(to_expression(result_id), " = {};");
  10012. end_scope();
  10013. }
  10014. }
  10015. else
  10016. {
  10017. assert(strcmp(op, "atomic_compare_exchange_weak") != 0);
  10018. if (op1)
  10019. {
  10020. exp += ", ";
  10021. if (op1_is_literal)
  10022. exp += to_string(op1);
  10023. else
  10024. exp += bitcast_expression(expected_type, op1);
  10025. }
  10026. if (op2)
  10027. exp += ", " + to_expression(op2);
  10028. if (!use_native_image_atomic)
  10029. {
  10030. exp += string(", ") + get_memory_order(mem_order_1);
  10031. if (has_mem_order_2)
  10032. exp += string(", ") + get_memory_order(mem_order_2);
  10033. }
  10034. exp += ")";
  10035. // For some particular reason, atomics return vec4 in Metal ...
  10036. if (use_native_image_atomic)
  10037. exp += ".x";
  10038. // Vulkan: (section 9.29: ... and values returned by atomic instructions in helper invocations are undefined)
  10039. if (check_discard)
  10040. {
  10041. exp += " : ";
  10042. if (strcmp(op, "atomic_store") != 0)
  10043. exp += join(type_to_glsl(get<SPIRType>(result_type)), "{}");
  10044. else
  10045. exp += "((void)0)";
  10046. exp += ")";
  10047. }
  10048. if (expected_type != type.basetype)
  10049. exp = bitcast_expression(type, expected_type, exp);
  10050. if (strcmp(op, "atomic_store") != 0)
  10051. emit_op(result_type, result_id, exp, false);
  10052. else
  10053. statement(exp, ";");
  10054. }
  10055. flush_all_atomic_capable_variables();
  10056. }
  10057. // Metal only supports relaxed memory order for now
  10058. const char *CompilerMSL::get_memory_order(uint32_t)
  10059. {
  10060. return "memory_order_relaxed";
  10061. }
  10062. // Override for MSL-specific extension syntax instructions.
  10063. // In some cases, deliberately select either the fast or precise versions of the MSL functions to match Vulkan math precision results.
  10064. void CompilerMSL::emit_glsl_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args, uint32_t count)
  10065. {
  10066. auto op = static_cast<GLSLstd450>(eop);
  10067. // If we need to do implicit bitcasts, make sure we do it with the correct type.
  10068. uint32_t integer_width = get_integer_width_for_glsl_instruction(op, args, count);
  10069. auto int_type = to_signed_basetype(integer_width);
  10070. auto uint_type = to_unsigned_basetype(integer_width);
  10071. op = get_remapped_glsl_op(op);
  10072. auto &restype = get<SPIRType>(result_type);
  10073. // Only precise:: preserves NaN in trancendentals (supposedly, cannot find documentation for this).
  10074. const auto drop_nan_inf = FPFastMathModeNotInfMask | FPFastMathModeNotNaNMask;
  10075. bool preserve_nan = (get_fp_fast_math_flags_for_op(result_type, id) & drop_nan_inf) != drop_nan_inf;
  10076. const char *preserve_str = preserve_nan ? "precise" : "fast";
  10077. // TODO: Emit the default behavior to match existing code. Might need to be revisited.
  10078. // Only fp32 has the precise:: override.
  10079. #define EMIT_PRECISE_OVERRIDE(glsl_op, op) \
  10080. case GLSLstd450##glsl_op: \
  10081. if (restype.basetype == SPIRType::Float && preserve_nan) \
  10082. emit_unary_func_op(result_type, id, args[0], "precise::" op); \
  10083. else \
  10084. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); \
  10085. break
  10086. switch (op)
  10087. {
  10088. EMIT_PRECISE_OVERRIDE(Cos, "cos");
  10089. EMIT_PRECISE_OVERRIDE(Sin, "sin");
  10090. EMIT_PRECISE_OVERRIDE(Tan, "tan");
  10091. EMIT_PRECISE_OVERRIDE(Acos, "acos");
  10092. EMIT_PRECISE_OVERRIDE(Asin, "asin");
  10093. EMIT_PRECISE_OVERRIDE(Atan, "atan");
  10094. EMIT_PRECISE_OVERRIDE(Exp, "exp");
  10095. EMIT_PRECISE_OVERRIDE(Exp2, "exp2");
  10096. EMIT_PRECISE_OVERRIDE(Log, "log");
  10097. EMIT_PRECISE_OVERRIDE(Log2, "log2");
  10098. EMIT_PRECISE_OVERRIDE(Sqrt, "sqrt");
  10099. #undef EMIT_PRECISE_OVERRIDE
  10100. case GLSLstd450Sinh:
  10101. if (restype.basetype == SPIRType::Half)
  10102. {
  10103. auto ftype = restype;
  10104. ftype.basetype = SPIRType::Float;
  10105. // MSL does not have overload for half. Force-cast back to half.
  10106. auto expr = join(type_to_glsl(restype), "(", preserve_str, "::sinh(", type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), ")))");
  10107. emit_op(result_type, id, expr, should_forward(args[0]));
  10108. inherit_expression_dependencies(id, args[0]);
  10109. }
  10110. else if (preserve_nan)
  10111. emit_unary_func_op(result_type, id, args[0], "precise::sinh");
  10112. else
  10113. emit_unary_func_op(result_type, id, args[0], "fast::sinh");
  10114. break;
  10115. case GLSLstd450Cosh:
  10116. if (restype.basetype == SPIRType::Half)
  10117. {
  10118. auto ftype = restype;
  10119. ftype.basetype = SPIRType::Float;
  10120. // MSL does not have overload for half. Force-cast back to half.
  10121. auto expr = join(type_to_glsl(restype), "(", preserve_str, "::cosh(", type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), ")))");
  10122. emit_op(result_type, id, expr, should_forward(args[0]));
  10123. inherit_expression_dependencies(id, args[0]);
  10124. }
  10125. else if (preserve_nan)
  10126. emit_unary_func_op(result_type, id, args[0], "precise::cosh");
  10127. else
  10128. emit_unary_func_op(result_type, id, args[0], "fast::cosh");
  10129. break;
  10130. case GLSLstd450Tanh:
  10131. if (restype.basetype == SPIRType::Half)
  10132. {
  10133. auto ftype = restype;
  10134. ftype.basetype = SPIRType::Float;
  10135. // MSL does not have overload for half. Force-cast back to half.
  10136. auto expr = join(type_to_glsl(restype), "(", preserve_str, "::tanh(", type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), ")))");
  10137. emit_op(result_type, id, expr, should_forward(args[0]));
  10138. inherit_expression_dependencies(id, args[0]);
  10139. }
  10140. else
  10141. emit_unary_func_op(result_type, id, args[0], "precise::tanh");
  10142. break;
  10143. case GLSLstd450Atan2:
  10144. if (restype.basetype == SPIRType::Half)
  10145. {
  10146. // MSL does not have overload for half. Force-cast back to half.
  10147. auto ftype = restype;
  10148. ftype.basetype = SPIRType::Float;
  10149. auto expr = join(type_to_glsl(restype),
  10150. "(", preserve_str, "::atan2(",
  10151. type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), "), ",
  10152. type_to_glsl(ftype), "(", to_unpacked_expression(args[1]), ")))");
  10153. emit_op(result_type, id, expr, should_forward(args[0]) && should_forward(args[1]));
  10154. inherit_expression_dependencies(id, args[0]);
  10155. inherit_expression_dependencies(id, args[1]);
  10156. }
  10157. else
  10158. emit_binary_func_op(result_type, id, args[0], args[1], "precise::atan2");
  10159. break;
  10160. case GLSLstd450InverseSqrt:
  10161. if (restype.basetype == SPIRType::Float && preserve_nan)
  10162. emit_unary_func_op(result_type, id, args[0], "precise::rsqrt");
  10163. else
  10164. emit_unary_func_op(result_type, id, args[0], "rsqrt");
  10165. break;
  10166. case GLSLstd450RoundEven:
  10167. emit_unary_func_op(result_type, id, args[0], "rint");
  10168. break;
  10169. case GLSLstd450FindILsb:
  10170. {
  10171. // In this template version of findLSB, we return T.
  10172. auto basetype = expression_type(args[0]).basetype;
  10173. emit_unary_func_op_cast(result_type, id, args[0], "spvFindLSB", basetype, basetype);
  10174. break;
  10175. }
  10176. case GLSLstd450FindSMsb:
  10177. emit_unary_func_op_cast(result_type, id, args[0], "spvFindSMSB", int_type, int_type);
  10178. break;
  10179. case GLSLstd450FindUMsb:
  10180. emit_unary_func_op_cast(result_type, id, args[0], "spvFindUMSB", uint_type, uint_type);
  10181. break;
  10182. case GLSLstd450PackSnorm4x8:
  10183. emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm4x8");
  10184. break;
  10185. case GLSLstd450PackUnorm4x8:
  10186. emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm4x8");
  10187. break;
  10188. case GLSLstd450PackSnorm2x16:
  10189. emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm2x16");
  10190. break;
  10191. case GLSLstd450PackUnorm2x16:
  10192. emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm2x16");
  10193. break;
  10194. case GLSLstd450PackHalf2x16:
  10195. {
  10196. auto expr = join("as_type<uint>(half2(", to_expression(args[0]), "))");
  10197. emit_op(result_type, id, expr, should_forward(args[0]));
  10198. inherit_expression_dependencies(id, args[0]);
  10199. break;
  10200. }
  10201. case GLSLstd450UnpackSnorm4x8:
  10202. emit_unary_func_op(result_type, id, args[0], "unpack_snorm4x8_to_float");
  10203. break;
  10204. case GLSLstd450UnpackUnorm4x8:
  10205. emit_unary_func_op(result_type, id, args[0], "unpack_unorm4x8_to_float");
  10206. break;
  10207. case GLSLstd450UnpackSnorm2x16:
  10208. emit_unary_func_op(result_type, id, args[0], "unpack_snorm2x16_to_float");
  10209. break;
  10210. case GLSLstd450UnpackUnorm2x16:
  10211. emit_unary_func_op(result_type, id, args[0], "unpack_unorm2x16_to_float");
  10212. break;
  10213. case GLSLstd450UnpackHalf2x16:
  10214. {
  10215. auto expr = join("float2(as_type<half2>(", to_expression(args[0]), "))");
  10216. emit_op(result_type, id, expr, should_forward(args[0]));
  10217. inherit_expression_dependencies(id, args[0]);
  10218. break;
  10219. }
  10220. case GLSLstd450PackDouble2x32:
  10221. emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450PackDouble2x32"); // Currently unsupported
  10222. break;
  10223. case GLSLstd450UnpackDouble2x32:
  10224. emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450UnpackDouble2x32"); // Currently unsupported
  10225. break;
  10226. case GLSLstd450MatrixInverse:
  10227. {
  10228. auto &mat_type = get<SPIRType>(result_type);
  10229. switch (mat_type.columns)
  10230. {
  10231. case 2:
  10232. emit_unary_func_op(result_type, id, args[0], "spvInverse2x2");
  10233. break;
  10234. case 3:
  10235. emit_unary_func_op(result_type, id, args[0], "spvInverse3x3");
  10236. break;
  10237. case 4:
  10238. emit_unary_func_op(result_type, id, args[0], "spvInverse4x4");
  10239. break;
  10240. default:
  10241. break;
  10242. }
  10243. break;
  10244. }
  10245. case GLSLstd450FMin:
  10246. // If the result type isn't float, don't bother calling the specific
  10247. // precise::/fast:: version. Metal doesn't have those for half and
  10248. // double types.
  10249. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10250. emit_binary_func_op(result_type, id, args[0], args[1], "min");
  10251. else
  10252. emit_binary_func_op(result_type, id, args[0], args[1], "fast::min");
  10253. break;
  10254. case GLSLstd450FMax:
  10255. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10256. emit_binary_func_op(result_type, id, args[0], args[1], "max");
  10257. else
  10258. emit_binary_func_op(result_type, id, args[0], args[1], "fast::max");
  10259. break;
  10260. case GLSLstd450FClamp:
  10261. // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call.
  10262. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10263. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
  10264. else
  10265. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "fast::clamp");
  10266. break;
  10267. case GLSLstd450NMin:
  10268. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10269. emit_binary_func_op(result_type, id, args[0], args[1], "min");
  10270. else
  10271. emit_binary_func_op(result_type, id, args[0], args[1], "precise::min");
  10272. break;
  10273. case GLSLstd450NMax:
  10274. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10275. emit_binary_func_op(result_type, id, args[0], args[1], "max");
  10276. else
  10277. emit_binary_func_op(result_type, id, args[0], args[1], "precise::max");
  10278. break;
  10279. case GLSLstd450NClamp:
  10280. // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call.
  10281. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10282. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
  10283. else
  10284. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "precise::clamp");
  10285. break;
  10286. case GLSLstd450InterpolateAtCentroid:
  10287. {
  10288. // We can't just emit the expression normally, because the qualified name contains a call to the default
  10289. // interpolate method, or refers to a local variable. We saved the interface index we need; use it to construct
  10290. // the base for the method call.
  10291. uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
  10292. string component;
  10293. if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
  10294. {
  10295. uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
  10296. auto *c = maybe_get<SPIRConstant>(index_expr);
  10297. if (!c || c->specialization)
  10298. component = join("[", to_expression(index_expr), "]");
  10299. else
  10300. component = join(".", index_to_swizzle(c->scalar()));
  10301. }
  10302. emit_op(result_type, id,
  10303. join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
  10304. ".interpolate_at_centroid()", component),
  10305. should_forward(args[0]));
  10306. break;
  10307. }
  10308. case GLSLstd450InterpolateAtSample:
  10309. {
  10310. uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
  10311. string component;
  10312. if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
  10313. {
  10314. uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
  10315. auto *c = maybe_get<SPIRConstant>(index_expr);
  10316. if (!c || c->specialization)
  10317. component = join("[", to_expression(index_expr), "]");
  10318. else
  10319. component = join(".", index_to_swizzle(c->scalar()));
  10320. }
  10321. emit_op(result_type, id,
  10322. join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
  10323. ".interpolate_at_sample(", to_expression(args[1]), ")", component),
  10324. should_forward(args[0]) && should_forward(args[1]));
  10325. break;
  10326. }
  10327. case GLSLstd450InterpolateAtOffset:
  10328. {
  10329. uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
  10330. string component;
  10331. if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
  10332. {
  10333. uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
  10334. auto *c = maybe_get<SPIRConstant>(index_expr);
  10335. if (!c || c->specialization)
  10336. component = join("[", to_expression(index_expr), "]");
  10337. else
  10338. component = join(".", index_to_swizzle(c->scalar()));
  10339. }
  10340. // Like Direct3D, Metal puts the (0, 0) at the upper-left corner, not the center as SPIR-V and GLSL do.
  10341. // Offset the offset by (1/2 - 1/16), or 0.4375, to compensate for this.
  10342. // It has to be (1/2 - 1/16) and not 1/2, or several CTS tests subtly break on Intel.
  10343. emit_op(result_type, id,
  10344. join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
  10345. ".interpolate_at_offset(", to_expression(args[1]), " + 0.4375)", component),
  10346. should_forward(args[0]) && should_forward(args[1]));
  10347. break;
  10348. }
  10349. case GLSLstd450Distance:
  10350. // MSL does not support scalar versions here.
  10351. if (expression_type(args[0]).vecsize == 1)
  10352. {
  10353. // Equivalent to length(a - b) -> abs(a - b).
  10354. emit_op(result_type, id,
  10355. join("abs(", to_enclosed_unpacked_expression(args[0]), " - ",
  10356. to_enclosed_unpacked_expression(args[1]), ")"),
  10357. should_forward(args[0]) && should_forward(args[1]));
  10358. inherit_expression_dependencies(id, args[0]);
  10359. inherit_expression_dependencies(id, args[1]);
  10360. }
  10361. else
  10362. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10363. break;
  10364. case GLSLstd450Length:
  10365. // MSL does not support scalar versions, so use abs().
  10366. if (expression_type(args[0]).vecsize == 1)
  10367. emit_unary_func_op(result_type, id, args[0], "abs");
  10368. else
  10369. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10370. break;
  10371. case GLSLstd450Normalize:
  10372. {
  10373. auto &exp_type = expression_type(args[0]);
  10374. // MSL does not support scalar versions here.
  10375. // MSL has no implementation for normalize in the fast:: namespace for half
  10376. // Returns -1 or 1 for valid input, sign() does the job.
  10377. // precise::normalize asm looks ridiculous.
  10378. // Don't think this actually matters unless proven otherwise.
  10379. if (exp_type.vecsize == 1)
  10380. emit_unary_func_op(result_type, id, args[0], "sign");
  10381. else if (exp_type.basetype == SPIRType::Half)
  10382. emit_unary_func_op(result_type, id, args[0], "normalize");
  10383. else
  10384. emit_unary_func_op(result_type, id, args[0], "fast::normalize");
  10385. break;
  10386. }
  10387. case GLSLstd450Reflect:
  10388. if (get<SPIRType>(result_type).vecsize == 1)
  10389. emit_binary_func_op(result_type, id, args[0], args[1], "spvReflect");
  10390. else
  10391. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10392. break;
  10393. case GLSLstd450Refract:
  10394. if (get<SPIRType>(result_type).vecsize == 1)
  10395. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvRefract");
  10396. else
  10397. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10398. break;
  10399. case GLSLstd450FaceForward:
  10400. if (get<SPIRType>(result_type).vecsize == 1)
  10401. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvFaceForward");
  10402. else
  10403. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10404. break;
  10405. case GLSLstd450Modf:
  10406. case GLSLstd450Frexp:
  10407. {
  10408. // Special case. If the variable is a scalar access chain, we cannot use it directly. We have to emit a temporary.
  10409. // Another special case is if the variable is in a storage class which is not thread.
  10410. auto *ptr = maybe_get<SPIRExpression>(args[1]);
  10411. auto &type = expression_type(args[1]);
  10412. bool is_thread_storage = storage_class_array_is_thread(type.storage);
  10413. if (type.storage == StorageClassOutput && capture_output_to_buffer)
  10414. is_thread_storage = false;
  10415. if (!is_thread_storage ||
  10416. (ptr && ptr->access_chain && is_scalar(expression_type(args[1]))))
  10417. {
  10418. register_call_out_argument(args[1]);
  10419. forced_temporaries.insert(id);
  10420. // Need to create temporaries and copy over to access chain after.
  10421. // We cannot directly take the reference of a vector swizzle in MSL, even if it's scalar ...
  10422. uint32_t &tmp_id = extra_sub_expressions[id];
  10423. if (!tmp_id)
  10424. tmp_id = ir.increase_bound_by(1);
  10425. uint32_t tmp_type_id = get_pointee_type_id(expression_type_id(args[1]));
  10426. emit_uninitialized_temporary_expression(tmp_type_id, tmp_id);
  10427. emit_binary_func_op(result_type, id, args[0], tmp_id, eop == GLSLstd450Modf ? "modf" : "frexp");
  10428. statement(to_expression(args[1]), " = ", to_expression(tmp_id), ";");
  10429. }
  10430. else
  10431. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10432. break;
  10433. }
  10434. case GLSLstd450Pow:
  10435. // powr makes x < 0.0 undefined, just like SPIR-V.
  10436. if (restype.basetype == SPIRType::Float && preserve_nan)
  10437. emit_binary_func_op(result_type, id, args[0], args[1], "precise::powr");
  10438. else
  10439. emit_binary_func_op(result_type, id, args[0], args[1], "powr");
  10440. break;
  10441. default:
  10442. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10443. break;
  10444. }
  10445. }
  10446. void CompilerMSL::emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t id, uint32_t eop,
  10447. const uint32_t *args, uint32_t count)
  10448. {
  10449. enum AMDShaderTrinaryMinMax
  10450. {
  10451. FMin3AMD = 1,
  10452. UMin3AMD = 2,
  10453. SMin3AMD = 3,
  10454. FMax3AMD = 4,
  10455. UMax3AMD = 5,
  10456. SMax3AMD = 6,
  10457. FMid3AMD = 7,
  10458. UMid3AMD = 8,
  10459. SMid3AMD = 9
  10460. };
  10461. if (!msl_options.supports_msl_version(2, 1))
  10462. SPIRV_CROSS_THROW("Trinary min/max functions require MSL 2.1.");
  10463. auto op = static_cast<AMDShaderTrinaryMinMax>(eop);
  10464. switch (op)
  10465. {
  10466. case FMid3AMD:
  10467. case UMid3AMD:
  10468. case SMid3AMD:
  10469. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "median3");
  10470. break;
  10471. default:
  10472. CompilerGLSL::emit_spv_amd_shader_trinary_minmax_op(result_type, id, eop, args, count);
  10473. break;
  10474. }
  10475. }
  10476. // Emit a structure declaration for the specified interface variable.
  10477. void CompilerMSL::emit_interface_block(uint32_t ib_var_id)
  10478. {
  10479. if (ib_var_id)
  10480. {
  10481. auto &ib_var = get<SPIRVariable>(ib_var_id);
  10482. auto &ib_type = get_variable_data_type(ib_var);
  10483. //assert(ib_type.basetype == SPIRType::Struct && !ib_type.member_types.empty());
  10484. assert(ib_type.basetype == SPIRType::Struct);
  10485. emit_struct(ib_type);
  10486. }
  10487. }
  10488. // Emits the declaration signature of the specified function.
  10489. // If this is the entry point function, Metal-specific return value and function arguments are added.
  10490. void CompilerMSL::emit_function_prototype(SPIRFunction &func, const Bitset &)
  10491. {
  10492. if (func.self != ir.default_entry_point)
  10493. add_function_overload(func);
  10494. local_variable_names = resource_names;
  10495. string decl;
  10496. processing_entry_point = func.self == ir.default_entry_point;
  10497. // Metal helper functions must be static force-inline otherwise they will cause problems when linked together in a single Metallib.
  10498. if (!processing_entry_point)
  10499. statement(force_inline);
  10500. auto &type = get<SPIRType>(func.return_type);
  10501. if (!type.array.empty() && msl_options.force_native_arrays)
  10502. {
  10503. // We cannot return native arrays in MSL, so "return" through an out variable.
  10504. decl += "void";
  10505. }
  10506. else
  10507. {
  10508. decl += func_type_decl(type);
  10509. }
  10510. decl += " ";
  10511. decl += to_name(func.self);
  10512. decl += "(";
  10513. if (!type.array.empty() && msl_options.force_native_arrays)
  10514. {
  10515. // Fake arrays returns by writing to an out array instead.
  10516. decl += "thread ";
  10517. decl += type_to_glsl(type);
  10518. decl += " (&spvReturnValue)";
  10519. decl += type_to_array_glsl(type, 0);
  10520. if (!func.arguments.empty())
  10521. decl += ", ";
  10522. }
  10523. if (processing_entry_point)
  10524. {
  10525. if (msl_options.argument_buffers)
  10526. decl += entry_point_args_argument_buffer(!func.arguments.empty());
  10527. else
  10528. decl += entry_point_args_classic(!func.arguments.empty());
  10529. // append entry point args to avoid conflicts in local variable names.
  10530. local_variable_names.insert(resource_names.begin(), resource_names.end());
  10531. // If entry point function has variables that require early declaration,
  10532. // ensure they each have an empty initializer, creating one if needed.
  10533. // This is done at this late stage because the initialization expression
  10534. // is cleared after each compilation pass.
  10535. for (auto var_id : vars_needing_early_declaration)
  10536. {
  10537. auto &ed_var = get<SPIRVariable>(var_id);
  10538. ID &initializer = ed_var.initializer;
  10539. if (!initializer)
  10540. initializer = ir.increase_bound_by(1);
  10541. // Do not override proper initializers.
  10542. if (ir.ids[initializer].get_type() == TypeNone || ir.ids[initializer].get_type() == TypeExpression)
  10543. set<SPIRExpression>(ed_var.initializer, "{}", ed_var.basetype, true);
  10544. }
  10545. // add `taskPayloadSharedEXT` variable to entry-point arguments
  10546. for (auto &v : func.local_variables)
  10547. {
  10548. auto &var = get<SPIRVariable>(v);
  10549. if (var.storage != StorageClassTaskPayloadWorkgroupEXT)
  10550. continue;
  10551. add_local_variable_name(v);
  10552. SPIRFunction::Parameter arg = {};
  10553. arg.id = v;
  10554. arg.type = var.basetype;
  10555. arg.alias_global_variable = true;
  10556. decl += join(", ", argument_decl(arg), " [[payload]]");
  10557. }
  10558. }
  10559. for (auto &arg : func.arguments)
  10560. {
  10561. uint32_t name_id = arg.id;
  10562. auto *var = maybe_get<SPIRVariable>(arg.id);
  10563. if (var)
  10564. {
  10565. // If we need to modify the name of the variable, make sure we modify the original variable.
  10566. // Our alias is just a shadow variable.
  10567. if (arg.alias_global_variable && var->basevariable)
  10568. name_id = var->basevariable;
  10569. var->parameter = &arg; // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
  10570. }
  10571. add_local_variable_name(name_id);
  10572. decl += argument_decl(arg);
  10573. bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
  10574. auto &arg_type = get<SPIRType>(arg.type);
  10575. if (arg_type.basetype == SPIRType::SampledImage && !is_dynamic_img_sampler)
  10576. {
  10577. // Manufacture automatic plane args for multiplanar texture
  10578. uint32_t planes = 1;
  10579. if (auto *constexpr_sampler = find_constexpr_sampler(name_id))
  10580. if (constexpr_sampler->ycbcr_conversion_enable)
  10581. planes = constexpr_sampler->planes;
  10582. for (uint32_t i = 1; i < planes; i++)
  10583. decl += join(", ", argument_decl(arg), plane_name_suffix, i);
  10584. // Manufacture automatic sampler arg for SampledImage texture
  10585. if (arg_type.image.dim != DimBuffer)
  10586. {
  10587. if (arg_type.array.empty() || (var ? is_var_runtime_size_array(*var) : is_runtime_size_array(arg_type)))
  10588. {
  10589. decl += join(", ", sampler_type(arg_type, arg.id, false), " ", to_sampler_expression(name_id));
  10590. }
  10591. else
  10592. {
  10593. const char *sampler_address_space =
  10594. descriptor_address_space(name_id,
  10595. StorageClassUniformConstant,
  10596. "thread const");
  10597. decl += join(", ", sampler_address_space, " ", sampler_type(arg_type, name_id, false), "& ",
  10598. to_sampler_expression(name_id));
  10599. }
  10600. }
  10601. }
  10602. // Manufacture automatic swizzle arg.
  10603. if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(arg_type) &&
  10604. !is_dynamic_img_sampler)
  10605. {
  10606. bool arg_is_array = !arg_type.array.empty();
  10607. decl += join(", constant uint", arg_is_array ? "* " : "& ", to_swizzle_expression(name_id));
  10608. }
  10609. if (buffer_requires_array_length(name_id))
  10610. {
  10611. bool arg_is_array = !arg_type.array.empty();
  10612. decl += join(", constant uint", arg_is_array ? "* " : "& ", to_buffer_size_expression(name_id));
  10613. }
  10614. if (&arg != &func.arguments.back())
  10615. decl += ", ";
  10616. }
  10617. decl += ")";
  10618. statement(decl);
  10619. }
  10620. static bool needs_chroma_reconstruction(const MSLConstexprSampler *constexpr_sampler)
  10621. {
  10622. // For now, only multiplanar images need explicit reconstruction. GBGR and BGRG images
  10623. // use implicit reconstruction.
  10624. return constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && constexpr_sampler->planes > 1;
  10625. }
  10626. // Returns the texture sampling function string for the specified image and sampling characteristics.
  10627. string CompilerMSL::to_function_name(const TextureFunctionNameArguments &args)
  10628. {
  10629. VariableID img = args.base.img;
  10630. const MSLConstexprSampler *constexpr_sampler = nullptr;
  10631. bool is_dynamic_img_sampler = false;
  10632. if (auto *var = maybe_get_backing_variable(img))
  10633. {
  10634. constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
  10635. is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
  10636. }
  10637. // Special-case gather. We have to alter the component being looked up in the swizzle case.
  10638. if (msl_options.swizzle_texture_samples && args.base.is_gather && !is_dynamic_img_sampler &&
  10639. (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable))
  10640. {
  10641. bool is_compare = comparison_ids.count(img);
  10642. add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareSwizzle : SPVFuncImplGatherSwizzle);
  10643. return is_compare ? "spvGatherCompareSwizzle" : "spvGatherSwizzle";
  10644. }
  10645. // Special-case gather with an array of offsets. We have to lower into 4 separate gathers.
  10646. if (args.has_array_offsets && !is_dynamic_img_sampler &&
  10647. (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable))
  10648. {
  10649. bool is_compare = comparison_ids.count(img);
  10650. add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareConstOffsets : SPVFuncImplGatherConstOffsets);
  10651. return is_compare ? "spvGatherCompareConstOffsets" : "spvGatherConstOffsets";
  10652. }
  10653. auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
  10654. // Texture reference
  10655. string fname;
  10656. if (needs_chroma_reconstruction(constexpr_sampler) && !is_dynamic_img_sampler)
  10657. {
  10658. if (constexpr_sampler->planes != 2 && constexpr_sampler->planes != 3)
  10659. SPIRV_CROSS_THROW("Unhandled number of color image planes!");
  10660. // 444 images aren't downsampled, so we don't need to do linear filtering.
  10661. if (constexpr_sampler->resolution == MSL_FORMAT_RESOLUTION_444 ||
  10662. constexpr_sampler->chroma_filter == MSL_SAMPLER_FILTER_NEAREST)
  10663. {
  10664. if (constexpr_sampler->planes == 2)
  10665. add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest2Plane);
  10666. else
  10667. add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest3Plane);
  10668. fname = "spvChromaReconstructNearest";
  10669. }
  10670. else // Linear with a downsampled format
  10671. {
  10672. fname = "spvChromaReconstructLinear";
  10673. switch (constexpr_sampler->resolution)
  10674. {
  10675. case MSL_FORMAT_RESOLUTION_444:
  10676. assert(false);
  10677. break; // not reached
  10678. case MSL_FORMAT_RESOLUTION_422:
  10679. switch (constexpr_sampler->x_chroma_offset)
  10680. {
  10681. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10682. if (constexpr_sampler->planes == 2)
  10683. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven2Plane);
  10684. else
  10685. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven3Plane);
  10686. fname += "422CositedEven";
  10687. break;
  10688. case MSL_CHROMA_LOCATION_MIDPOINT:
  10689. if (constexpr_sampler->planes == 2)
  10690. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint2Plane);
  10691. else
  10692. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint3Plane);
  10693. fname += "422Midpoint";
  10694. break;
  10695. default:
  10696. SPIRV_CROSS_THROW("Invalid chroma location.");
  10697. }
  10698. break;
  10699. case MSL_FORMAT_RESOLUTION_420:
  10700. fname += "420";
  10701. switch (constexpr_sampler->x_chroma_offset)
  10702. {
  10703. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10704. switch (constexpr_sampler->y_chroma_offset)
  10705. {
  10706. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10707. if (constexpr_sampler->planes == 2)
  10708. add_spv_func_and_recompile(
  10709. SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane);
  10710. else
  10711. add_spv_func_and_recompile(
  10712. SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane);
  10713. fname += "XCositedEvenYCositedEven";
  10714. break;
  10715. case MSL_CHROMA_LOCATION_MIDPOINT:
  10716. if (constexpr_sampler->planes == 2)
  10717. add_spv_func_and_recompile(
  10718. SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane);
  10719. else
  10720. add_spv_func_and_recompile(
  10721. SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane);
  10722. fname += "XCositedEvenYMidpoint";
  10723. break;
  10724. default:
  10725. SPIRV_CROSS_THROW("Invalid Y chroma location.");
  10726. }
  10727. break;
  10728. case MSL_CHROMA_LOCATION_MIDPOINT:
  10729. switch (constexpr_sampler->y_chroma_offset)
  10730. {
  10731. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10732. if (constexpr_sampler->planes == 2)
  10733. add_spv_func_and_recompile(
  10734. SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane);
  10735. else
  10736. add_spv_func_and_recompile(
  10737. SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane);
  10738. fname += "XMidpointYCositedEven";
  10739. break;
  10740. case MSL_CHROMA_LOCATION_MIDPOINT:
  10741. if (constexpr_sampler->planes == 2)
  10742. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane);
  10743. else
  10744. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane);
  10745. fname += "XMidpointYMidpoint";
  10746. break;
  10747. default:
  10748. SPIRV_CROSS_THROW("Invalid Y chroma location.");
  10749. }
  10750. break;
  10751. default:
  10752. SPIRV_CROSS_THROW("Invalid X chroma location.");
  10753. }
  10754. break;
  10755. default:
  10756. SPIRV_CROSS_THROW("Invalid format resolution.");
  10757. }
  10758. }
  10759. }
  10760. else
  10761. {
  10762. fname = to_expression(combined ? combined->image : img) + ".";
  10763. // Texture function and sampler
  10764. if (args.base.is_fetch)
  10765. fname += "read";
  10766. else if (args.base.is_gather)
  10767. fname += "gather";
  10768. else
  10769. fname += "sample";
  10770. if (args.has_dref)
  10771. fname += "_compare";
  10772. }
  10773. return fname;
  10774. }
  10775. string CompilerMSL::convert_to_f32(const string &expr, uint32_t components)
  10776. {
  10777. SPIRType t { components > 1 ? OpTypeVector : OpTypeFloat };
  10778. t.basetype = SPIRType::Float;
  10779. t.vecsize = components;
  10780. t.columns = 1;
  10781. return join(type_to_glsl_constructor(t), "(", expr, ")");
  10782. }
  10783. static inline bool sampling_type_needs_f32_conversion(const SPIRType &type)
  10784. {
  10785. // Double is not supported to begin with, but doesn't hurt to check for completion.
  10786. return type.basetype == SPIRType::Half || type.basetype == SPIRType::Double;
  10787. }
  10788. // Returns the function args for a texture sampling function for the specified image and sampling characteristics.
  10789. string CompilerMSL::to_function_args(const TextureFunctionArguments &args, bool *p_forward)
  10790. {
  10791. VariableID img = args.base.img;
  10792. auto &imgtype = *args.base.imgtype;
  10793. uint32_t lod = args.lod;
  10794. uint32_t grad_x = args.grad_x;
  10795. uint32_t grad_y = args.grad_y;
  10796. uint32_t bias = args.bias;
  10797. const MSLConstexprSampler *constexpr_sampler = nullptr;
  10798. bool is_dynamic_img_sampler = false;
  10799. if (auto *var = maybe_get_backing_variable(img))
  10800. {
  10801. constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
  10802. is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
  10803. }
  10804. string farg_str;
  10805. bool forward = true;
  10806. if (!is_dynamic_img_sampler)
  10807. {
  10808. // Texture reference (for some cases)
  10809. if (needs_chroma_reconstruction(constexpr_sampler))
  10810. {
  10811. // Multiplanar images need two or three textures.
  10812. farg_str += to_expression(img);
  10813. for (uint32_t i = 1; i < constexpr_sampler->planes; i++)
  10814. farg_str += join(", ", to_expression(img), plane_name_suffix, i);
  10815. }
  10816. else if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) &&
  10817. msl_options.swizzle_texture_samples && args.base.is_gather)
  10818. {
  10819. auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
  10820. farg_str += to_expression(combined ? combined->image : img);
  10821. }
  10822. // Gathers with constant offsets call a special function, so include the texture.
  10823. if (args.has_array_offsets)
  10824. farg_str += to_expression(img);
  10825. // Sampler reference
  10826. if (!args.base.is_fetch)
  10827. {
  10828. if (!farg_str.empty())
  10829. farg_str += ", ";
  10830. farg_str += to_sampler_expression(img);
  10831. }
  10832. if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) &&
  10833. msl_options.swizzle_texture_samples && args.base.is_gather)
  10834. {
  10835. // Add the swizzle constant from the swizzle buffer.
  10836. farg_str += ", " + to_swizzle_expression(img);
  10837. used_swizzle_buffer = true;
  10838. }
  10839. // Const offsets gather puts the const offsets before the other args.
  10840. if (args.has_array_offsets)
  10841. {
  10842. forward = forward && should_forward(args.offset);
  10843. farg_str += ", " + to_unpacked_expression(args.offset);
  10844. }
  10845. // Const offsets gather or swizzled gather puts the component before the other args.
  10846. if (args.component && (args.has_array_offsets || msl_options.swizzle_texture_samples))
  10847. {
  10848. forward = forward && should_forward(args.component);
  10849. farg_str += ", " + to_component_argument(args.component);
  10850. }
  10851. }
  10852. // Texture coordinates
  10853. forward = forward && should_forward(args.coord);
  10854. auto coord_expr = to_enclosed_unpacked_expression(args.coord);
  10855. auto &coord_type = expression_type(args.coord);
  10856. bool coord_is_fp = type_is_floating_point(coord_type);
  10857. bool is_cube_fetch = false;
  10858. string tex_coords = coord_expr;
  10859. uint32_t alt_coord_component = 0;
  10860. switch (imgtype.image.dim)
  10861. {
  10862. case Dim1D:
  10863. if (coord_type.vecsize > 1)
  10864. tex_coords = enclose_expression(tex_coords) + ".x";
  10865. if (args.base.is_fetch)
  10866. tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10867. else if (sampling_type_needs_f32_conversion(coord_type))
  10868. tex_coords = convert_to_f32(tex_coords, 1);
  10869. if (msl_options.texture_1D_as_2D)
  10870. {
  10871. if (args.base.is_fetch)
  10872. tex_coords = "uint2(" + tex_coords + ", 0)";
  10873. else
  10874. tex_coords = "float2(" + tex_coords + ", 0.5)";
  10875. }
  10876. alt_coord_component = 1;
  10877. break;
  10878. case DimBuffer:
  10879. if (coord_type.vecsize > 1)
  10880. tex_coords = enclose_expression(tex_coords) + ".x";
  10881. if (msl_options.texture_buffer_native)
  10882. {
  10883. tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10884. }
  10885. else
  10886. {
  10887. // Metal texel buffer textures are 2D, so convert 1D coord to 2D.
  10888. // Support for Metal 2.1's new texture_buffer type.
  10889. if (args.base.is_fetch)
  10890. {
  10891. if (msl_options.texel_buffer_texture_width > 0)
  10892. {
  10893. tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10894. }
  10895. else
  10896. {
  10897. tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ", " +
  10898. to_expression(img) + ")";
  10899. }
  10900. }
  10901. }
  10902. alt_coord_component = 1;
  10903. break;
  10904. case DimSubpassData:
  10905. // If we're using Metal's native frame-buffer fetch API for subpass inputs,
  10906. // this path will not be hit.
  10907. tex_coords = "uint2(gl_FragCoord.xy)";
  10908. alt_coord_component = 2;
  10909. break;
  10910. case Dim2D:
  10911. if (coord_type.vecsize > 2)
  10912. tex_coords = enclose_expression(tex_coords) + ".xy";
  10913. if (args.base.is_fetch)
  10914. tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10915. else if (sampling_type_needs_f32_conversion(coord_type))
  10916. tex_coords = convert_to_f32(tex_coords, 2);
  10917. alt_coord_component = 2;
  10918. break;
  10919. case Dim3D:
  10920. if (coord_type.vecsize > 3)
  10921. tex_coords = enclose_expression(tex_coords) + ".xyz";
  10922. if (args.base.is_fetch)
  10923. tex_coords = "uint3(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10924. else if (sampling_type_needs_f32_conversion(coord_type))
  10925. tex_coords = convert_to_f32(tex_coords, 3);
  10926. alt_coord_component = 3;
  10927. break;
  10928. case DimCube:
  10929. if (args.base.is_fetch)
  10930. {
  10931. is_cube_fetch = true;
  10932. tex_coords += ".xy";
  10933. tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10934. }
  10935. else
  10936. {
  10937. if (coord_type.vecsize > 3)
  10938. tex_coords = enclose_expression(tex_coords) + ".xyz";
  10939. }
  10940. if (sampling_type_needs_f32_conversion(coord_type))
  10941. tex_coords = convert_to_f32(tex_coords, 3);
  10942. alt_coord_component = 3;
  10943. break;
  10944. default:
  10945. break;
  10946. }
  10947. if (args.base.is_fetch && args.offset)
  10948. {
  10949. // Fetch offsets must be applied directly to the coordinate.
  10950. forward = forward && should_forward(args.offset);
  10951. auto &type = expression_type(args.offset);
  10952. if (imgtype.image.dim == Dim1D && msl_options.texture_1D_as_2D)
  10953. {
  10954. if (type.basetype != SPIRType::UInt)
  10955. tex_coords += join(" + uint2(", bitcast_expression(SPIRType::UInt, args.offset), ", 0)");
  10956. else
  10957. tex_coords += join(" + uint2(", to_enclosed_unpacked_expression(args.offset), ", 0)");
  10958. }
  10959. else
  10960. {
  10961. if (type.basetype != SPIRType::UInt)
  10962. tex_coords += " + " + bitcast_expression(SPIRType::UInt, args.offset);
  10963. else
  10964. tex_coords += " + " + to_enclosed_unpacked_expression(args.offset);
  10965. }
  10966. }
  10967. // If projection, use alt coord as divisor
  10968. if (args.base.is_proj)
  10969. {
  10970. if (sampling_type_needs_f32_conversion(coord_type))
  10971. tex_coords += " / " + convert_to_f32(to_extract_component_expression(args.coord, alt_coord_component), 1);
  10972. else
  10973. tex_coords += " / " + to_extract_component_expression(args.coord, alt_coord_component);
  10974. }
  10975. if (!farg_str.empty())
  10976. farg_str += ", ";
  10977. if (imgtype.image.dim == DimCube && imgtype.image.arrayed && msl_options.emulate_cube_array)
  10978. {
  10979. farg_str += "spvCubemapTo2DArrayFace(" + tex_coords + ").xy";
  10980. if (is_cube_fetch)
  10981. farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ")";
  10982. else
  10983. farg_str +=
  10984. ", uint(spvCubemapTo2DArrayFace(" + tex_coords + ").z) + (uint(" +
  10985. round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) +
  10986. ") * 6u)";
  10987. add_spv_func_and_recompile(SPVFuncImplCubemapTo2DArrayFace);
  10988. }
  10989. else
  10990. {
  10991. farg_str += tex_coords;
  10992. // If fetch from cube, add face explicitly
  10993. if (is_cube_fetch)
  10994. {
  10995. // Special case for cube arrays, face and layer are packed in one dimension.
  10996. if (imgtype.image.arrayed)
  10997. farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") % 6u";
  10998. else
  10999. farg_str +=
  11000. ", uint(" + round_fp_tex_coords(to_extract_component_expression(args.coord, 2), coord_is_fp) + ")";
  11001. }
  11002. // If array, use alt coord
  11003. if (imgtype.image.arrayed)
  11004. {
  11005. // Special case for cube arrays, face and layer are packed in one dimension.
  11006. if (imgtype.image.dim == DimCube && args.base.is_fetch)
  11007. {
  11008. farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") / 6u";
  11009. }
  11010. else
  11011. {
  11012. farg_str +=
  11013. ", uint(" +
  11014. round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) +
  11015. ")";
  11016. if (imgtype.image.dim == DimSubpassData)
  11017. {
  11018. if (msl_options.multiview)
  11019. farg_str += " + gl_ViewIndex";
  11020. else if (msl_options.arrayed_subpass_input)
  11021. farg_str += " + gl_Layer";
  11022. }
  11023. }
  11024. }
  11025. else if (imgtype.image.dim == DimSubpassData)
  11026. {
  11027. if (msl_options.multiview)
  11028. farg_str += ", gl_ViewIndex";
  11029. else if (msl_options.arrayed_subpass_input)
  11030. farg_str += ", gl_Layer";
  11031. }
  11032. }
  11033. // Depth compare reference value
  11034. if (args.dref)
  11035. {
  11036. forward = forward && should_forward(args.dref);
  11037. farg_str += ", ";
  11038. auto &dref_type = expression_type(args.dref);
  11039. string dref_expr;
  11040. if (args.base.is_proj)
  11041. dref_expr = join(to_enclosed_unpacked_expression(args.dref), " / ",
  11042. to_extract_component_expression(args.coord, alt_coord_component));
  11043. else
  11044. dref_expr = to_unpacked_expression(args.dref);
  11045. if (sampling_type_needs_f32_conversion(dref_type))
  11046. dref_expr = convert_to_f32(dref_expr, 1);
  11047. farg_str += dref_expr;
  11048. if (msl_options.is_macos() && (grad_x || grad_y))
  11049. {
  11050. // For sample compare, MSL does not support gradient2d for all targets (only iOS apparently according to docs).
  11051. // However, the most common case here is to have a constant gradient of 0, as that is the only way to express
  11052. // LOD == 0 in GLSL with sampler2DArrayShadow (cascaded shadow mapping).
  11053. // We will detect a compile-time constant 0 value for gradient and promote that to level(0) on MSL.
  11054. bool constant_zero_x = !grad_x || expression_is_constant_null(grad_x);
  11055. bool constant_zero_y = !grad_y || expression_is_constant_null(grad_y);
  11056. if (constant_zero_x && constant_zero_y &&
  11057. (!imgtype.image.arrayed || !msl_options.sample_dref_lod_array_as_grad))
  11058. {
  11059. lod = 0;
  11060. grad_x = 0;
  11061. grad_y = 0;
  11062. farg_str += ", level(0)";
  11063. }
  11064. else if (!msl_options.supports_msl_version(2, 3))
  11065. {
  11066. SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not "
  11067. "supported on macOS prior to MSL 2.3.");
  11068. }
  11069. }
  11070. if (msl_options.is_macos() && bias)
  11071. {
  11072. // Bias is not supported either on macOS with sample_compare.
  11073. // Verify it is compile-time zero, and drop the argument.
  11074. if (expression_is_constant_null(bias))
  11075. {
  11076. bias = 0;
  11077. }
  11078. else if (!msl_options.supports_msl_version(2, 3))
  11079. {
  11080. SPIRV_CROSS_THROW("Using non-constant 0.0 bias() qualifier for sample_compare. This is not supported "
  11081. "on macOS prior to MSL 2.3.");
  11082. }
  11083. }
  11084. }
  11085. // LOD Options
  11086. // Metal does not support LOD for 1D textures.
  11087. if (bias && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
  11088. {
  11089. forward = forward && should_forward(bias);
  11090. farg_str += ", bias(" + to_unpacked_expression(bias) + ")";
  11091. }
  11092. // Metal does not support LOD for 1D textures.
  11093. if (lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
  11094. {
  11095. forward = forward && should_forward(lod);
  11096. if (args.base.is_fetch)
  11097. {
  11098. farg_str += ", " + to_unpacked_expression(lod);
  11099. }
  11100. else if (msl_options.sample_dref_lod_array_as_grad && args.dref && imgtype.image.arrayed)
  11101. {
  11102. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
  11103. SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not "
  11104. "supported on macOS prior to MSL 2.3.");
  11105. // Some Metal devices have a bug where the LoD is erroneously biased upward
  11106. // when using a level() argument. Since this doesn't happen as much with gradient2d(),
  11107. // if we perform the LoD calculation in reverse, we can pass a gradient
  11108. // instead.
  11109. // lod = log2(rhoMax/eta) -> exp2(lod) = rhoMax/eta
  11110. // If we make all of the scale factors the same, eta will be 1 and
  11111. // exp2(lod) = rho.
  11112. // rhoX = dP/dx * extent; rhoY = dP/dy * extent
  11113. // Therefore, dP/dx = dP/dy = exp2(lod)/extent.
  11114. // (Subtracting 0.5 before exponentiation gives better results.)
  11115. string grad_opt, extent, grad_coord;
  11116. VariableID base_img = img;
  11117. if (auto *combined = maybe_get<SPIRCombinedImageSampler>(img))
  11118. base_img = combined->image;
  11119. switch (imgtype.image.dim)
  11120. {
  11121. case Dim1D:
  11122. grad_opt = "gradient2d";
  11123. extent = join("float2(", to_expression(base_img), ".get_width(), 1.0)");
  11124. break;
  11125. case Dim2D:
  11126. grad_opt = "gradient2d";
  11127. extent = join("float2(", to_expression(base_img), ".get_width(), ", to_expression(base_img), ".get_height())");
  11128. break;
  11129. case DimCube:
  11130. if (imgtype.image.arrayed && msl_options.emulate_cube_array)
  11131. {
  11132. grad_opt = "gradient2d";
  11133. extent = join("float2(", to_expression(base_img), ".get_width())");
  11134. }
  11135. else
  11136. {
  11137. if (msl_options.agx_manual_cube_grad_fixup)
  11138. {
  11139. add_spv_func_and_recompile(SPVFuncImplGradientCube);
  11140. grad_opt = "spvGradientCube";
  11141. grad_coord = tex_coords + ", ";
  11142. }
  11143. else
  11144. {
  11145. grad_opt = "gradientcube";
  11146. }
  11147. extent = join("float3(", to_expression(base_img), ".get_width())");
  11148. }
  11149. break;
  11150. default:
  11151. grad_opt = "unsupported_gradient_dimension";
  11152. extent = "float3(1.0)";
  11153. break;
  11154. }
  11155. farg_str += join(", ", grad_opt, "(", grad_coord, "exp2(", to_unpacked_expression(lod), " - 0.5) / ", extent,
  11156. ", exp2(", to_unpacked_expression(lod), " - 0.5) / ", extent, ")");
  11157. }
  11158. else
  11159. {
  11160. farg_str += ", level(" + to_unpacked_expression(lod) + ")";
  11161. }
  11162. }
  11163. else if (args.base.is_fetch && !lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D) &&
  11164. imgtype.image.dim != DimBuffer && !imgtype.image.ms && imgtype.image.sampled != 2)
  11165. {
  11166. // Lod argument is optional in OpImageFetch, but we require a LOD value, pick 0 as the default.
  11167. // Check for sampled type as well, because is_fetch is also used for OpImageRead in MSL.
  11168. farg_str += ", 0";
  11169. }
  11170. // Metal does not support LOD for 1D textures.
  11171. if ((grad_x || grad_y) && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
  11172. {
  11173. forward = forward && should_forward(grad_x);
  11174. forward = forward && should_forward(grad_y);
  11175. string grad_opt, grad_coord;
  11176. switch (imgtype.image.dim)
  11177. {
  11178. case Dim1D:
  11179. case Dim2D:
  11180. grad_opt = "gradient2d";
  11181. break;
  11182. case Dim3D:
  11183. grad_opt = "gradient3d";
  11184. break;
  11185. case DimCube:
  11186. if (imgtype.image.arrayed && msl_options.emulate_cube_array)
  11187. {
  11188. grad_opt = "gradient2d";
  11189. }
  11190. else if (msl_options.agx_manual_cube_grad_fixup)
  11191. {
  11192. add_spv_func_and_recompile(SPVFuncImplGradientCube);
  11193. grad_opt = "spvGradientCube";
  11194. grad_coord = tex_coords + ", ";
  11195. }
  11196. else
  11197. {
  11198. grad_opt = "gradientcube";
  11199. }
  11200. break;
  11201. default:
  11202. grad_opt = "unsupported_gradient_dimension";
  11203. break;
  11204. }
  11205. farg_str += join(", ", grad_opt, "(", grad_coord, to_unpacked_expression(grad_x), ", ", to_unpacked_expression(grad_y), ")");
  11206. }
  11207. if (args.min_lod)
  11208. {
  11209. if (!msl_options.supports_msl_version(2, 2))
  11210. SPIRV_CROSS_THROW("min_lod_clamp() is only supported in MSL 2.2+ and up.");
  11211. forward = forward && should_forward(args.min_lod);
  11212. farg_str += ", min_lod_clamp(" + to_unpacked_expression(args.min_lod) + ")";
  11213. }
  11214. // Add offsets
  11215. string offset_expr;
  11216. const SPIRType *offset_type = nullptr;
  11217. if (args.offset && !args.base.is_fetch && !args.has_array_offsets)
  11218. {
  11219. forward = forward && should_forward(args.offset);
  11220. offset_expr = to_unpacked_expression(args.offset);
  11221. offset_type = &expression_type(args.offset);
  11222. }
  11223. if (!offset_expr.empty())
  11224. {
  11225. switch (imgtype.image.dim)
  11226. {
  11227. case Dim1D:
  11228. if (!msl_options.texture_1D_as_2D)
  11229. break;
  11230. if (offset_type->vecsize > 1)
  11231. offset_expr = enclose_expression(offset_expr) + ".x";
  11232. farg_str += join(", int2(", offset_expr, ", 0)");
  11233. break;
  11234. case Dim2D:
  11235. if (offset_type->vecsize > 2)
  11236. offset_expr = enclose_expression(offset_expr) + ".xy";
  11237. farg_str += ", " + offset_expr;
  11238. break;
  11239. case Dim3D:
  11240. if (offset_type->vecsize > 3)
  11241. offset_expr = enclose_expression(offset_expr) + ".xyz";
  11242. farg_str += ", " + offset_expr;
  11243. break;
  11244. default:
  11245. break;
  11246. }
  11247. }
  11248. if (args.component && !args.has_array_offsets)
  11249. {
  11250. // If 2D has gather component, ensure it also has an offset arg
  11251. if (imgtype.image.dim == Dim2D && offset_expr.empty())
  11252. farg_str += ", int2(0)";
  11253. if (!msl_options.swizzle_texture_samples || is_dynamic_img_sampler)
  11254. {
  11255. forward = forward && should_forward(args.component);
  11256. uint32_t image_var = 0;
  11257. if (const auto *combined = maybe_get<SPIRCombinedImageSampler>(img))
  11258. {
  11259. if (const auto *img_var = maybe_get_backing_variable(combined->image))
  11260. image_var = img_var->self;
  11261. }
  11262. else if (const auto *var = maybe_get_backing_variable(img))
  11263. {
  11264. image_var = var->self;
  11265. }
  11266. if (image_var == 0 || !is_depth_image(expression_type(image_var), image_var))
  11267. farg_str += ", " + to_component_argument(args.component);
  11268. }
  11269. }
  11270. if (args.sample)
  11271. {
  11272. forward = forward && should_forward(args.sample);
  11273. farg_str += ", ";
  11274. farg_str += to_unpacked_expression(args.sample);
  11275. }
  11276. *p_forward = forward;
  11277. return farg_str;
  11278. }
  11279. // If the texture coordinates are floating point, invokes MSL round() function to round them.
  11280. string CompilerMSL::round_fp_tex_coords(string tex_coords, bool coord_is_fp)
  11281. {
  11282. return coord_is_fp ? ("rint(" + tex_coords + ")") : tex_coords;
  11283. }
  11284. // Returns a string to use in an image sampling function argument.
  11285. // The ID must be a scalar constant.
  11286. string CompilerMSL::to_component_argument(uint32_t id)
  11287. {
  11288. uint32_t component_index = evaluate_constant_u32(id);
  11289. switch (component_index)
  11290. {
  11291. case 0:
  11292. return "component::x";
  11293. case 1:
  11294. return "component::y";
  11295. case 2:
  11296. return "component::z";
  11297. case 3:
  11298. return "component::w";
  11299. default:
  11300. SPIRV_CROSS_THROW("The value (" + to_string(component_index) + ") of OpConstant ID " + to_string(id) +
  11301. " is not a valid Component index, which must be one of 0, 1, 2, or 3.");
  11302. }
  11303. }
  11304. // Establish sampled image as expression object and assign the sampler to it.
  11305. void CompilerMSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id)
  11306. {
  11307. set<SPIRCombinedImageSampler>(result_id, result_type, image_id, samp_id);
  11308. }
  11309. string CompilerMSL::to_texture_op(const Instruction &i, bool sparse, bool *forward,
  11310. SmallVector<uint32_t> &inherited_expressions)
  11311. {
  11312. auto *ops = stream(i);
  11313. uint32_t result_type_id = ops[0];
  11314. uint32_t img = ops[2];
  11315. auto &result_type = get<SPIRType>(result_type_id);
  11316. auto op = static_cast<Op>(i.op);
  11317. bool is_gather = (op == OpImageGather || op == OpImageDrefGather);
  11318. // Bypass pointers because we need the real image struct
  11319. auto &type = expression_type(img);
  11320. auto &imgtype = get<SPIRType>(type.self);
  11321. const MSLConstexprSampler *constexpr_sampler = nullptr;
  11322. bool is_dynamic_img_sampler = false;
  11323. if (auto *var = maybe_get_backing_variable(img))
  11324. {
  11325. constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
  11326. is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
  11327. }
  11328. string expr;
  11329. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler)
  11330. {
  11331. // If this needs sampler Y'CbCr conversion, we need to do some additional
  11332. // processing.
  11333. switch (constexpr_sampler->ycbcr_model)
  11334. {
  11335. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY:
  11336. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY:
  11337. // Default
  11338. break;
  11339. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709:
  11340. add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT709);
  11341. expr += "spvConvertYCbCrBT709(";
  11342. break;
  11343. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601:
  11344. add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT601);
  11345. expr += "spvConvertYCbCrBT601(";
  11346. break;
  11347. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020:
  11348. add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT2020);
  11349. expr += "spvConvertYCbCrBT2020(";
  11350. break;
  11351. default:
  11352. SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion.");
  11353. }
  11354. if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)
  11355. {
  11356. switch (constexpr_sampler->ycbcr_range)
  11357. {
  11358. case MSL_SAMPLER_YCBCR_RANGE_ITU_FULL:
  11359. add_spv_func_and_recompile(SPVFuncImplExpandITUFullRange);
  11360. expr += "spvExpandITUFullRange(";
  11361. break;
  11362. case MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW:
  11363. add_spv_func_and_recompile(SPVFuncImplExpandITUNarrowRange);
  11364. expr += "spvExpandITUNarrowRange(";
  11365. break;
  11366. default:
  11367. SPIRV_CROSS_THROW("Invalid Y'CbCr range.");
  11368. }
  11369. }
  11370. }
  11371. else if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) &&
  11372. !is_dynamic_img_sampler)
  11373. {
  11374. add_spv_func_and_recompile(SPVFuncImplTextureSwizzle);
  11375. expr += "spvTextureSwizzle(";
  11376. }
  11377. string inner_expr = CompilerGLSL::to_texture_op(i, sparse, forward, inherited_expressions);
  11378. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler)
  11379. {
  11380. if (!constexpr_sampler->swizzle_is_identity())
  11381. {
  11382. static const char swizzle_names[] = "rgba";
  11383. if (!constexpr_sampler->swizzle_has_one_or_zero())
  11384. {
  11385. // If we can, do it inline.
  11386. expr += inner_expr + ".";
  11387. for (uint32_t c = 0; c < 4; c++)
  11388. {
  11389. switch (constexpr_sampler->swizzle[c])
  11390. {
  11391. case MSL_COMPONENT_SWIZZLE_IDENTITY:
  11392. expr += swizzle_names[c];
  11393. break;
  11394. case MSL_COMPONENT_SWIZZLE_R:
  11395. case MSL_COMPONENT_SWIZZLE_G:
  11396. case MSL_COMPONENT_SWIZZLE_B:
  11397. case MSL_COMPONENT_SWIZZLE_A:
  11398. expr += swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R];
  11399. break;
  11400. default:
  11401. SPIRV_CROSS_THROW("Invalid component swizzle.");
  11402. }
  11403. }
  11404. }
  11405. else
  11406. {
  11407. // Otherwise, we need to emit a temporary and swizzle that.
  11408. uint32_t temp_id = ir.increase_bound_by(1);
  11409. emit_op(result_type_id, temp_id, inner_expr, false);
  11410. for (auto &inherit : inherited_expressions)
  11411. inherit_expression_dependencies(temp_id, inherit);
  11412. inherited_expressions.clear();
  11413. inherited_expressions.push_back(temp_id);
  11414. switch (op)
  11415. {
  11416. case OpImageSampleDrefImplicitLod:
  11417. case OpImageSampleImplicitLod:
  11418. case OpImageSampleProjImplicitLod:
  11419. case OpImageSampleProjDrefImplicitLod:
  11420. register_control_dependent_expression(temp_id);
  11421. break;
  11422. default:
  11423. break;
  11424. }
  11425. expr += type_to_glsl(result_type) + "(";
  11426. for (uint32_t c = 0; c < 4; c++)
  11427. {
  11428. switch (constexpr_sampler->swizzle[c])
  11429. {
  11430. case MSL_COMPONENT_SWIZZLE_IDENTITY:
  11431. expr += to_expression(temp_id) + "." + swizzle_names[c];
  11432. break;
  11433. case MSL_COMPONENT_SWIZZLE_ZERO:
  11434. expr += "0";
  11435. break;
  11436. case MSL_COMPONENT_SWIZZLE_ONE:
  11437. expr += "1";
  11438. break;
  11439. case MSL_COMPONENT_SWIZZLE_R:
  11440. case MSL_COMPONENT_SWIZZLE_G:
  11441. case MSL_COMPONENT_SWIZZLE_B:
  11442. case MSL_COMPONENT_SWIZZLE_A:
  11443. expr += to_expression(temp_id) + "." +
  11444. swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R];
  11445. break;
  11446. default:
  11447. SPIRV_CROSS_THROW("Invalid component swizzle.");
  11448. }
  11449. if (c < 3)
  11450. expr += ", ";
  11451. }
  11452. expr += ")";
  11453. }
  11454. }
  11455. else
  11456. expr += inner_expr;
  11457. if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)
  11458. {
  11459. expr += join(", ", constexpr_sampler->bpc, ")");
  11460. if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY)
  11461. expr += ")";
  11462. }
  11463. }
  11464. else
  11465. {
  11466. expr += inner_expr;
  11467. if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) &&
  11468. !is_dynamic_img_sampler)
  11469. {
  11470. // Add the swizzle constant from the swizzle buffer.
  11471. expr += ", " + to_swizzle_expression(img) + ")";
  11472. used_swizzle_buffer = true;
  11473. }
  11474. }
  11475. return expr;
  11476. }
  11477. static string create_swizzle(MSLComponentSwizzle swizzle)
  11478. {
  11479. switch (swizzle)
  11480. {
  11481. case MSL_COMPONENT_SWIZZLE_IDENTITY:
  11482. return "spvSwizzle::none";
  11483. case MSL_COMPONENT_SWIZZLE_ZERO:
  11484. return "spvSwizzle::zero";
  11485. case MSL_COMPONENT_SWIZZLE_ONE:
  11486. return "spvSwizzle::one";
  11487. case MSL_COMPONENT_SWIZZLE_R:
  11488. return "spvSwizzle::red";
  11489. case MSL_COMPONENT_SWIZZLE_G:
  11490. return "spvSwizzle::green";
  11491. case MSL_COMPONENT_SWIZZLE_B:
  11492. return "spvSwizzle::blue";
  11493. case MSL_COMPONENT_SWIZZLE_A:
  11494. return "spvSwizzle::alpha";
  11495. default:
  11496. SPIRV_CROSS_THROW("Invalid component swizzle.");
  11497. }
  11498. }
  11499. // Returns a string representation of the ID, usable as a function arg.
  11500. // Manufacture automatic sampler arg for SampledImage texture.
  11501. string CompilerMSL::to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id)
  11502. {
  11503. string arg_str;
  11504. auto &type = expression_type(id);
  11505. bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
  11506. // If the argument *itself* is a "dynamic" combined-image sampler, then we can just pass that around.
  11507. bool arg_is_dynamic_img_sampler = has_extended_decoration(id, SPIRVCrossDecorationDynamicImageSampler);
  11508. if (is_dynamic_img_sampler && !arg_is_dynamic_img_sampler)
  11509. arg_str = join("spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">(");
  11510. auto *c = maybe_get<SPIRConstant>(id);
  11511. if (msl_options.force_native_arrays && c && !get<SPIRType>(c->constant_type).array.empty())
  11512. {
  11513. // If we are passing a constant array directly to a function for some reason,
  11514. // the callee will expect an argument in thread const address space
  11515. // (since we can only bind to arrays with references in MSL).
  11516. // To resolve this, we must emit a copy in this address space.
  11517. // This kind of code gen should be rare enough that performance is not a real concern.
  11518. // Inline the SPIR-V to avoid this kind of suboptimal codegen.
  11519. //
  11520. // We risk calling this inside a continue block (invalid code),
  11521. // so just create a thread local copy in the current function.
  11522. arg_str = join("_", id, "_array_copy");
  11523. auto &constants = current_function->constant_arrays_needed_on_stack;
  11524. auto itr = find(begin(constants), end(constants), ID(id));
  11525. if (itr == end(constants))
  11526. {
  11527. force_recompile();
  11528. constants.push_back(id);
  11529. }
  11530. }
  11531. // Dereference pointer variables where needed.
  11532. // FIXME: This dereference is actually backwards. We should really just support passing pointer variables between functions.
  11533. else if (should_dereference_caller_param(id))
  11534. arg_str += dereference_expression(type, CompilerGLSL::to_func_call_arg(arg, id));
  11535. else
  11536. arg_str += CompilerGLSL::to_func_call_arg(arg, id);
  11537. // Need to check the base variable in case we need to apply a qualified alias.
  11538. uint32_t var_id = 0;
  11539. auto *var = maybe_get<SPIRVariable>(id);
  11540. if (var)
  11541. var_id = var->basevariable;
  11542. if (!arg_is_dynamic_img_sampler)
  11543. {
  11544. auto *constexpr_sampler = find_constexpr_sampler(var_id ? var_id : id);
  11545. if (type.basetype == SPIRType::SampledImage)
  11546. {
  11547. // Manufacture automatic plane args for multiplanar texture
  11548. uint32_t planes = 1;
  11549. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  11550. {
  11551. planes = constexpr_sampler->planes;
  11552. // If this parameter isn't aliasing a global, then we need to use
  11553. // the special "dynamic image-sampler" class to pass it--and we need
  11554. // to use it for *every* non-alias parameter, in case a combined
  11555. // image-sampler with a Y'CbCr conversion is passed. Hopefully, this
  11556. // pathological case is so rare that it should never be hit in practice.
  11557. if (!arg.alias_global_variable)
  11558. add_spv_func_and_recompile(SPVFuncImplDynamicImageSampler);
  11559. }
  11560. for (uint32_t i = 1; i < planes; i++)
  11561. arg_str += join(", ", CompilerGLSL::to_func_call_arg(arg, id), plane_name_suffix, i);
  11562. // Manufacture automatic sampler arg if the arg is a SampledImage texture.
  11563. if (type.image.dim != DimBuffer)
  11564. arg_str += ", " + to_sampler_expression(var_id ? var_id : id);
  11565. // Add sampler Y'CbCr conversion info if we have it
  11566. if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  11567. {
  11568. SmallVector<string> samp_args;
  11569. switch (constexpr_sampler->resolution)
  11570. {
  11571. case MSL_FORMAT_RESOLUTION_444:
  11572. // Default
  11573. break;
  11574. case MSL_FORMAT_RESOLUTION_422:
  11575. samp_args.push_back("spvFormatResolution::_422");
  11576. break;
  11577. case MSL_FORMAT_RESOLUTION_420:
  11578. samp_args.push_back("spvFormatResolution::_420");
  11579. break;
  11580. default:
  11581. SPIRV_CROSS_THROW("Invalid format resolution.");
  11582. }
  11583. if (constexpr_sampler->chroma_filter != MSL_SAMPLER_FILTER_NEAREST)
  11584. samp_args.push_back("spvChromaFilter::linear");
  11585. if (constexpr_sampler->x_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN)
  11586. samp_args.push_back("spvXChromaLocation::midpoint");
  11587. if (constexpr_sampler->y_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN)
  11588. samp_args.push_back("spvYChromaLocation::midpoint");
  11589. switch (constexpr_sampler->ycbcr_model)
  11590. {
  11591. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY:
  11592. // Default
  11593. break;
  11594. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY:
  11595. samp_args.push_back("spvYCbCrModelConversion::ycbcr_identity");
  11596. break;
  11597. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709:
  11598. samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_709");
  11599. break;
  11600. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601:
  11601. samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_601");
  11602. break;
  11603. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020:
  11604. samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_2020");
  11605. break;
  11606. default:
  11607. SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion.");
  11608. }
  11609. if (constexpr_sampler->ycbcr_range != MSL_SAMPLER_YCBCR_RANGE_ITU_FULL)
  11610. samp_args.push_back("spvYCbCrRange::itu_narrow");
  11611. samp_args.push_back(join("spvComponentBits(", constexpr_sampler->bpc, ")"));
  11612. arg_str += join(", spvYCbCrSampler(", merge(samp_args), ")");
  11613. }
  11614. }
  11615. if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  11616. arg_str += join(", (uint(", create_swizzle(constexpr_sampler->swizzle[3]), ") << 24) | (uint(",
  11617. create_swizzle(constexpr_sampler->swizzle[2]), ") << 16) | (uint(",
  11618. create_swizzle(constexpr_sampler->swizzle[1]), ") << 8) | uint(",
  11619. create_swizzle(constexpr_sampler->swizzle[0]), ")");
  11620. else if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type))
  11621. arg_str += ", " + to_swizzle_expression(var_id ? var_id : id);
  11622. if (buffer_requires_array_length(var_id))
  11623. arg_str += ", " + to_buffer_size_expression(var_id ? var_id : id);
  11624. if (is_dynamic_img_sampler)
  11625. arg_str += ")";
  11626. }
  11627. // Emulate texture2D atomic operations
  11628. auto *backing_var = maybe_get_backing_variable(var_id);
  11629. if (backing_var && atomic_image_vars_emulated.count(backing_var->self))
  11630. {
  11631. arg_str += ", " + to_expression(var_id) + "_atomic";
  11632. }
  11633. return arg_str;
  11634. }
  11635. // If the ID represents a sampled image that has been assigned a sampler already,
  11636. // generate an expression for the sampler, otherwise generate a fake sampler name
  11637. // by appending a suffix to the expression constructed from the ID.
  11638. string CompilerMSL::to_sampler_expression(uint32_t id)
  11639. {
  11640. auto *combined = maybe_get<SPIRCombinedImageSampler>(id);
  11641. if (combined && combined->sampler)
  11642. return to_expression(combined->sampler);
  11643. uint32_t expr_id = combined ? uint32_t(combined->image) : id;
  11644. // Constexpr samplers are declared as local variables,
  11645. // so exclude any qualifier names on the image expression.
  11646. if (auto *var = maybe_get_backing_variable(expr_id))
  11647. {
  11648. uint32_t img_id = var->basevariable ? var->basevariable : VariableID(var->self);
  11649. if (find_constexpr_sampler(img_id))
  11650. return Compiler::to_name(img_id) + sampler_name_suffix;
  11651. }
  11652. auto img_expr = to_expression(expr_id);
  11653. auto index = img_expr.find_first_of('[');
  11654. if (index == string::npos)
  11655. return img_expr + sampler_name_suffix;
  11656. else
  11657. return img_expr.substr(0, index) + sampler_name_suffix + img_expr.substr(index);
  11658. }
  11659. string CompilerMSL::to_swizzle_expression(uint32_t id)
  11660. {
  11661. auto *combined = maybe_get<SPIRCombinedImageSampler>(id);
  11662. auto expr = to_expression(combined ? combined->image : VariableID(id));
  11663. auto index = expr.find_first_of('[');
  11664. // If an image is part of an argument buffer translate this to a legal identifier.
  11665. string::size_type period = 0;
  11666. while ((period = expr.find_first_of('.', period)) != string::npos && period < index)
  11667. expr[period] = '_';
  11668. if (index == string::npos)
  11669. return expr + swizzle_name_suffix;
  11670. else
  11671. {
  11672. auto image_expr = expr.substr(0, index);
  11673. auto array_expr = expr.substr(index);
  11674. return image_expr + swizzle_name_suffix + array_expr;
  11675. }
  11676. }
  11677. string CompilerMSL::to_buffer_size_expression(uint32_t id)
  11678. {
  11679. auto expr = to_expression(id);
  11680. // This is quite crude, but we need to translate the reference name (*spvDescriptorSetN.name) to
  11681. // the pointer expression spvDescriptorSetN.name to make a reasonable expression here.
  11682. // This only happens if we have argument buffers and we are using OpArrayLength on a lone SSBO in that set.
  11683. if (expr.size() >= 3 && expr[0] == '(' && expr[1] == '*')
  11684. expr = address_of_expression(expr);
  11685. auto index = expr.find_first_of('[');
  11686. string buffer_expr, array_expr;
  11687. if (index != string::npos)
  11688. {
  11689. buffer_expr = expr.substr(0, index);
  11690. array_expr = expr.substr(index);
  11691. }
  11692. // If a buffer is part of an argument buffer translate this to a legal identifier.
  11693. for (auto &c : expr)
  11694. if (c == '.')
  11695. c = '_';
  11696. if (index == string::npos)
  11697. {
  11698. return expr + buffer_size_name_suffix;
  11699. }
  11700. else
  11701. {
  11702. if (auto var = maybe_get_backing_variable(id))
  11703. {
  11704. if (is_var_runtime_size_array(*var))
  11705. {
  11706. if (!msl_options.runtime_array_rich_descriptor)
  11707. SPIRV_CROSS_THROW("OpArrayLength requires rich descriptor format");
  11708. auto last_pos = array_expr.find_last_of(']');
  11709. if (last_pos != std::string::npos)
  11710. return buffer_expr + ".length(" + array_expr.substr(1, last_pos - 1) + ")";
  11711. }
  11712. }
  11713. for (auto &c : buffer_expr)
  11714. if (c == '.')
  11715. c = '_';
  11716. return buffer_expr + buffer_size_name_suffix + array_expr;
  11717. }
  11718. }
  11719. // Checks whether the type is a Block all of whose members have DecorationPatch.
  11720. bool CompilerMSL::is_patch_block(const SPIRType &type)
  11721. {
  11722. if (!has_decoration(type.self, DecorationBlock))
  11723. return false;
  11724. for (uint32_t i = 0; i < type.member_types.size(); i++)
  11725. {
  11726. if (!has_member_decoration(type.self, i, DecorationPatch))
  11727. return false;
  11728. }
  11729. return true;
  11730. }
  11731. // Checks whether the ID is a row_major matrix that requires conversion before use
  11732. bool CompilerMSL::is_non_native_row_major_matrix(uint32_t id)
  11733. {
  11734. auto *e = maybe_get<SPIRExpression>(id);
  11735. if (e)
  11736. return e->need_transpose;
  11737. else
  11738. return has_decoration(id, DecorationRowMajor);
  11739. }
  11740. // Checks whether the member is a row_major matrix that requires conversion before use
  11741. bool CompilerMSL::member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index)
  11742. {
  11743. return has_member_decoration(type.self, index, DecorationRowMajor);
  11744. }
  11745. string CompilerMSL::convert_row_major_matrix(string exp_str, const SPIRType &exp_type, uint32_t physical_type_id,
  11746. bool is_packed, bool relaxed)
  11747. {
  11748. if (!is_matrix(exp_type))
  11749. {
  11750. return CompilerGLSL::convert_row_major_matrix(std::move(exp_str), exp_type, physical_type_id, is_packed, relaxed);
  11751. }
  11752. else
  11753. {
  11754. strip_enclosed_expression(exp_str);
  11755. if (physical_type_id != 0 || is_packed)
  11756. exp_str = unpack_expression_type(exp_str, exp_type, physical_type_id, is_packed, true);
  11757. return join("transpose(", exp_str, ")");
  11758. }
  11759. }
  11760. // Called automatically at the end of the entry point function
  11761. void CompilerMSL::emit_fixup()
  11762. {
  11763. if (stage_out_var_id && !capture_output_to_buffer)
  11764. {
  11765. if (needs_point_size_output && !writes_to_point_size)
  11766. statement(builtin_to_glsl(BuiltInPointSize, StorageClassOutput), " = ", format_float(msl_options.default_point_size), ";");
  11767. if (is_vertex_like_shader() && !qual_pos_var_name.empty())
  11768. {
  11769. if (options.vertex.fixup_clipspace)
  11770. statement(qual_pos_var_name, ".z = (", qual_pos_var_name, ".z + ", qual_pos_var_name,
  11771. ".w) * 0.5; // Adjust clip-space for Metal");
  11772. if (options.vertex.flip_vert_y)
  11773. statement(qual_pos_var_name, ".y = -(", qual_pos_var_name, ".y);", " // Invert Y-axis for Metal");
  11774. }
  11775. }
  11776. }
  11777. // Return a string defining a structure member, with padding and packing.
  11778. string CompilerMSL::to_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
  11779. const string &qualifier)
  11780. {
  11781. uint32_t orig_member_type_id = member_type_id;
  11782. if (member_is_remapped_physical_type(type, index))
  11783. member_type_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID);
  11784. auto &physical_type = get<SPIRType>(member_type_id);
  11785. // If this member is packed, mark it as so.
  11786. string pack_pfx;
  11787. // Allow Metal to use the array<T> template to make arrays a value type
  11788. uint32_t orig_id = 0;
  11789. if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID))
  11790. orig_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID);
  11791. bool row_major = false;
  11792. if (is_matrix(physical_type))
  11793. row_major = has_member_decoration(type.self, index, DecorationRowMajor);
  11794. SPIRType row_major_physical_type { OpTypeMatrix };
  11795. const SPIRType *declared_type = &physical_type;
  11796. // If a struct is being declared with physical layout,
  11797. // do not use array<T> wrappers.
  11798. // This avoids a lot of complicated cases with packed vectors and matrices,
  11799. // and generally we cannot copy full arrays in and out of buffers into Function
  11800. // address space.
  11801. // Array of resources should also be declared as builtin arrays.
  11802. if (has_member_decoration(type.self, index, DecorationOffset))
  11803. is_using_builtin_array = true;
  11804. else if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary))
  11805. is_using_builtin_array = true;
  11806. if (member_is_packed_physical_type(type, index))
  11807. {
  11808. // If we're packing a matrix, output an appropriate typedef
  11809. if (physical_type.basetype == SPIRType::Struct)
  11810. {
  11811. SPIRV_CROSS_THROW("Cannot emit a packed struct currently.");
  11812. }
  11813. else if (is_matrix(physical_type))
  11814. {
  11815. uint32_t rows = physical_type.vecsize;
  11816. uint32_t cols = physical_type.columns;
  11817. pack_pfx = "packed_";
  11818. if (row_major)
  11819. {
  11820. // These are stored transposed.
  11821. rows = physical_type.columns;
  11822. cols = physical_type.vecsize;
  11823. pack_pfx = "packed_rm_";
  11824. }
  11825. string base_type = physical_type.width == 16 ? "half" : "float";
  11826. string td_line = "typedef ";
  11827. td_line += "packed_" + base_type + to_string(rows);
  11828. td_line += " " + pack_pfx;
  11829. // Use the actual matrix size here.
  11830. td_line += base_type + to_string(physical_type.columns) + "x" + to_string(physical_type.vecsize);
  11831. td_line += "[" + to_string(cols) + "]";
  11832. td_line += ";";
  11833. add_typedef_line(td_line);
  11834. }
  11835. else if (!is_scalar(physical_type)) // scalar type is already packed.
  11836. pack_pfx = "packed_";
  11837. }
  11838. else if (is_matrix(physical_type))
  11839. {
  11840. if (!msl_options.supports_msl_version(3, 0) &&
  11841. has_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct))
  11842. {
  11843. pack_pfx = "spvStorage_";
  11844. add_spv_func_and_recompile(SPVFuncImplStorageMatrix);
  11845. // The pack prefix causes problems with array<T> wrappers.
  11846. is_using_builtin_array = true;
  11847. }
  11848. if (row_major)
  11849. {
  11850. // Need to declare type with flipped vecsize/columns.
  11851. row_major_physical_type = physical_type;
  11852. swap(row_major_physical_type.vecsize, row_major_physical_type.columns);
  11853. declared_type = &row_major_physical_type;
  11854. }
  11855. }
  11856. // iOS Tier 1 argument buffers do not support writable images.
  11857. if (physical_type.basetype == SPIRType::Image &&
  11858. physical_type.image.sampled == 2 &&
  11859. msl_options.is_ios() &&
  11860. msl_options.argument_buffers_tier <= Options::ArgumentBuffersTier::Tier1 &&
  11861. !has_decoration(orig_id, DecorationNonWritable))
  11862. {
  11863. SPIRV_CROSS_THROW("Writable images are not allowed on Tier1 argument buffers on iOS.");
  11864. }
  11865. // Array information is baked into these types.
  11866. string array_type;
  11867. if (physical_type.basetype != SPIRType::Image && physical_type.basetype != SPIRType::Sampler &&
  11868. physical_type.basetype != SPIRType::SampledImage)
  11869. {
  11870. BuiltIn builtin = BuiltInMax;
  11871. // Special handling. In [[stage_out]] or [[stage_in]] blocks,
  11872. // we need flat arrays, but if we're somehow declaring gl_PerVertex for constant array reasons, we want
  11873. // template array types to be declared.
  11874. bool is_ib_in_out =
  11875. ((stage_out_var_id && get_stage_out_struct_type().self == type.self &&
  11876. variable_storage_requires_stage_io(StorageClassOutput)) ||
  11877. (stage_in_var_id && get_stage_in_struct_type().self == type.self &&
  11878. variable_storage_requires_stage_io(StorageClassInput))) ||
  11879. is_mesh_shader();
  11880. if (is_ib_in_out && is_member_builtin(type, index, &builtin))
  11881. is_using_builtin_array = true;
  11882. array_type = type_to_array_glsl(physical_type, orig_id);
  11883. }
  11884. if (is_mesh_shader())
  11885. {
  11886. BuiltIn builtin = BuiltInMax;
  11887. if (is_member_builtin(type, index, &builtin))
  11888. {
  11889. if (builtin == BuiltInPrimitiveShadingRateKHR)
  11890. {
  11891. // not supported in metal 3.0
  11892. is_using_builtin_array = false;
  11893. return "";
  11894. }
  11895. SPIRType metallic_type = *declared_type;
  11896. if (builtin == BuiltInCullPrimitiveEXT)
  11897. metallic_type.basetype = SPIRType::Boolean;
  11898. else if (builtin == BuiltInPrimitiveId || builtin == BuiltInLayer || builtin == BuiltInViewportIndex)
  11899. metallic_type.basetype = SPIRType::UInt;
  11900. is_using_builtin_array = true;
  11901. std::string result;
  11902. if (has_member_decoration(type.self, orig_id, DecorationBuiltIn))
  11903. {
  11904. // avoid '_RESERVED_IDENTIFIER_FIXUP_' in variable name
  11905. result = join(type_to_glsl(metallic_type, orig_id, false), " ", qualifier,
  11906. builtin_to_glsl(builtin, StorageClassOutput), member_attribute_qualifier(type, index),
  11907. array_type, ";");
  11908. }
  11909. else
  11910. {
  11911. result = join(type_to_glsl(metallic_type, orig_id, false), " ", qualifier,
  11912. to_member_name(type, index), member_attribute_qualifier(type, index), array_type, ";");
  11913. }
  11914. is_using_builtin_array = false;
  11915. return result;
  11916. }
  11917. }
  11918. if (orig_id)
  11919. {
  11920. auto *data_type = declared_type;
  11921. if (is_pointer(*data_type))
  11922. data_type = &get_pointee_type(*data_type);
  11923. if (is_array(*data_type) && get_resource_array_size(*data_type, orig_id) == 0)
  11924. {
  11925. // Hack for declaring unsized array of resources. Need to declare dummy sized array by value inline.
  11926. // This can then be wrapped in spvDescriptorArray as usual.
  11927. array_type = "[1] /* unsized array hack */";
  11928. }
  11929. }
  11930. string decl_type;
  11931. if (declared_type->vecsize > 4)
  11932. {
  11933. auto orig_type = get<SPIRType>(orig_member_type_id);
  11934. if (is_matrix(orig_type) && row_major)
  11935. swap(orig_type.vecsize, orig_type.columns);
  11936. orig_type.columns = 1;
  11937. decl_type = type_to_glsl(orig_type, orig_id, true);
  11938. if (declared_type->columns > 1)
  11939. decl_type = join("spvPaddedStd140Matrix<", decl_type, ", ", declared_type->columns, ">");
  11940. else
  11941. decl_type = join("spvPaddedStd140<", decl_type, ">");
  11942. }
  11943. else
  11944. decl_type = type_to_glsl(*declared_type, orig_id, true);
  11945. const char *overlapping_binding_tag =
  11946. has_extended_member_decoration(type.self, index, SPIRVCrossDecorationOverlappingBinding) ?
  11947. "// Overlapping binding: " : "";
  11948. auto result = join(overlapping_binding_tag, pack_pfx, decl_type, " ", qualifier,
  11949. to_member_name(type, index), member_attribute_qualifier(type, index), array_type, ";");
  11950. is_using_builtin_array = false;
  11951. return result;
  11952. }
  11953. // Emit a structure member, padding and packing to maintain the correct memeber alignments.
  11954. void CompilerMSL::emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
  11955. const string &qualifier, uint32_t)
  11956. {
  11957. // If this member requires padding to maintain its declared offset, emit a dummy padding member before it.
  11958. if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget))
  11959. {
  11960. uint32_t pad_len = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget);
  11961. statement("char _m", index, "_pad", "[", pad_len, "];");
  11962. }
  11963. BuiltIn builtin = BuiltInMax;
  11964. if (is_mesh_shader() && is_member_builtin(type, index, &builtin))
  11965. {
  11966. if (!has_active_builtin(builtin, StorageClassOutput) && !has_active_builtin(builtin, StorageClassInput))
  11967. {
  11968. // Do not emit unused builtins in mesh-output blocks
  11969. return;
  11970. }
  11971. }
  11972. // Handle HLSL-style 0-based vertex/instance index.
  11973. builtin_declaration = true;
  11974. statement(to_struct_member(type, member_type_id, index, qualifier));
  11975. builtin_declaration = false;
  11976. }
  11977. void CompilerMSL::emit_struct_padding_target(const SPIRType &type)
  11978. {
  11979. uint32_t struct_size = get_declared_struct_size_msl(type, true, true);
  11980. uint32_t target_size = get_extended_decoration(type.self, SPIRVCrossDecorationPaddingTarget);
  11981. if (target_size < struct_size)
  11982. SPIRV_CROSS_THROW("Cannot pad with negative bytes.");
  11983. else if (target_size > struct_size)
  11984. statement("char _m0_final_padding[", target_size - struct_size, "];");
  11985. }
  11986. // Return a MSL qualifier for the specified function attribute member
  11987. string CompilerMSL::member_attribute_qualifier(const SPIRType &type, uint32_t index)
  11988. {
  11989. auto &execution = get_entry_point();
  11990. uint32_t mbr_type_id = type.member_types[index];
  11991. auto &mbr_type = get<SPIRType>(mbr_type_id);
  11992. BuiltIn builtin = BuiltInMax;
  11993. bool is_builtin = is_member_builtin(type, index, &builtin);
  11994. if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary))
  11995. {
  11996. string quals = join(
  11997. " [[id(", get_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary), ")");
  11998. if (interlocked_resources.count(
  11999. get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID)))
  12000. quals += ", raster_order_group(0)";
  12001. quals += "]]";
  12002. return quals;
  12003. }
  12004. // Vertex function inputs
  12005. if (execution.model == ExecutionModelVertex && type.storage == StorageClassInput)
  12006. {
  12007. if (is_builtin)
  12008. {
  12009. switch (builtin)
  12010. {
  12011. case BuiltInVertexId:
  12012. case BuiltInVertexIndex:
  12013. case BuiltInBaseVertex:
  12014. case BuiltInInstanceId:
  12015. case BuiltInInstanceIndex:
  12016. case BuiltInBaseInstance:
  12017. if (msl_options.vertex_for_tessellation)
  12018. return "";
  12019. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12020. case BuiltInDrawIndex:
  12021. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  12022. default:
  12023. return "";
  12024. }
  12025. }
  12026. uint32_t locn;
  12027. if (is_builtin)
  12028. locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
  12029. else
  12030. locn = get_member_location(type.self, index);
  12031. if (locn != k_unknown_location)
  12032. return string(" [[attribute(") + convert_to_string(locn) + ")]]";
  12033. }
  12034. bool use_semantic_stage_output = is_mesh_shader() || is_tese_shader() ||
  12035. (execution.model == ExecutionModelVertex && !msl_options.vertex_for_tessellation);
  12036. // Vertex, mesh and tessellation evaluation function outputs
  12037. if ((type.storage == StorageClassOutput || is_mesh_shader()) && use_semantic_stage_output)
  12038. {
  12039. if (is_builtin)
  12040. {
  12041. switch (builtin)
  12042. {
  12043. case BuiltInPointSize:
  12044. // Only mark the PointSize builtin if really rendering points.
  12045. // Some shaders may include a PointSize builtin even when used to render
  12046. // non-point topologies, and Metal will reject this builtin when compiling
  12047. // the shader into a render pipeline that uses a non-point topology.
  12048. return msl_options.enable_point_size_builtin ? (string(" [[") + builtin_qualifier(builtin) + "]]") : "";
  12049. case BuiltInViewportIndex:
  12050. if (!msl_options.supports_msl_version(2, 0))
  12051. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  12052. /* fallthrough */
  12053. case BuiltInPosition:
  12054. case BuiltInLayer:
  12055. case BuiltInCullPrimitiveEXT:
  12056. case BuiltInPrimitiveShadingRateKHR:
  12057. case BuiltInPrimitiveId:
  12058. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12059. case BuiltInClipDistance:
  12060. if (has_member_decoration(type.self, index, DecorationIndex))
  12061. return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12062. else
  12063. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12064. case BuiltInCullDistance:
  12065. if (has_member_decoration(type.self, index, DecorationIndex))
  12066. return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12067. else
  12068. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12069. default:
  12070. return "";
  12071. }
  12072. }
  12073. string loc_qual = member_location_attribute_qualifier(type, index);
  12074. if (!loc_qual.empty())
  12075. return join(" [[", loc_qual, "]]");
  12076. }
  12077. if (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation && type.storage == StorageClassOutput)
  12078. {
  12079. // For this type of shader, we always arrange for it to capture its
  12080. // output to a buffer. For this reason, qualifiers are irrelevant here.
  12081. if (is_builtin)
  12082. // We still have to assign a location so the output struct will sort correctly.
  12083. get_or_allocate_builtin_output_member_location(builtin, type.self, index);
  12084. return "";
  12085. }
  12086. // Tessellation control function inputs
  12087. if (is_tesc_shader() && type.storage == StorageClassInput)
  12088. {
  12089. if (is_builtin)
  12090. {
  12091. switch (builtin)
  12092. {
  12093. case BuiltInInvocationId:
  12094. case BuiltInPrimitiveId:
  12095. if (msl_options.multi_patch_workgroup)
  12096. return "";
  12097. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12098. case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage
  12099. case BuiltInSubgroupSize: // FIXME: Should work in any stage
  12100. if (msl_options.emulate_subgroups)
  12101. return "";
  12102. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12103. case BuiltInPatchVertices:
  12104. return "";
  12105. // Others come from stage input.
  12106. default:
  12107. break;
  12108. }
  12109. }
  12110. if (msl_options.multi_patch_workgroup)
  12111. return "";
  12112. uint32_t locn;
  12113. if (is_builtin)
  12114. locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
  12115. else
  12116. locn = get_member_location(type.self, index);
  12117. if (locn != k_unknown_location)
  12118. return string(" [[attribute(") + convert_to_string(locn) + ")]]";
  12119. }
  12120. // Tessellation control function outputs
  12121. if (is_tesc_shader() && type.storage == StorageClassOutput)
  12122. {
  12123. // For this type of shader, we always arrange for it to capture its
  12124. // output to a buffer. For this reason, qualifiers are irrelevant here.
  12125. if (is_builtin)
  12126. // We still have to assign a location so the output struct will sort correctly.
  12127. get_or_allocate_builtin_output_member_location(builtin, type.self, index);
  12128. return "";
  12129. }
  12130. // Tessellation evaluation function inputs
  12131. if (is_tese_shader() && type.storage == StorageClassInput)
  12132. {
  12133. if (is_builtin)
  12134. {
  12135. switch (builtin)
  12136. {
  12137. case BuiltInPrimitiveId:
  12138. case BuiltInTessCoord:
  12139. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12140. case BuiltInPatchVertices:
  12141. return "";
  12142. // Others come from stage input.
  12143. default:
  12144. break;
  12145. }
  12146. }
  12147. if (msl_options.raw_buffer_tese_input)
  12148. return "";
  12149. // The special control point array must not be marked with an attribute.
  12150. if (get_type(type.member_types[index]).basetype == SPIRType::ControlPointArray)
  12151. return "";
  12152. uint32_t locn;
  12153. if (is_builtin)
  12154. locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
  12155. else
  12156. locn = get_member_location(type.self, index);
  12157. if (locn != k_unknown_location)
  12158. return string(" [[attribute(") + convert_to_string(locn) + ")]]";
  12159. }
  12160. // Tessellation evaluation function outputs were handled above.
  12161. // Fragment function inputs
  12162. if (execution.model == ExecutionModelFragment && type.storage == StorageClassInput)
  12163. {
  12164. string quals;
  12165. if (is_builtin)
  12166. {
  12167. switch (builtin)
  12168. {
  12169. case BuiltInViewIndex:
  12170. if (!msl_options.multiview || !msl_options.multiview_layered_rendering)
  12171. break;
  12172. /* fallthrough */
  12173. case BuiltInFrontFacing:
  12174. case BuiltInPointCoord:
  12175. case BuiltInFragCoord:
  12176. case BuiltInSampleId:
  12177. case BuiltInSampleMask:
  12178. case BuiltInLayer:
  12179. case BuiltInBaryCoordKHR:
  12180. case BuiltInBaryCoordNoPerspKHR:
  12181. quals = builtin_qualifier(builtin);
  12182. break;
  12183. case BuiltInClipDistance:
  12184. return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12185. case BuiltInCullDistance:
  12186. return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12187. default:
  12188. break;
  12189. }
  12190. }
  12191. else
  12192. quals = member_location_attribute_qualifier(type, index);
  12193. if (builtin == BuiltInBaryCoordKHR && has_member_decoration(type.self, index, DecorationNoPerspective))
  12194. {
  12195. // NoPerspective is baked into the builtin type.
  12196. SPIRV_CROSS_THROW("NoPerspective decorations are not supported for BaryCoord inputs.");
  12197. }
  12198. // Don't bother decorating integers with the 'flat' attribute; it's
  12199. // the default (in fact, the only option). Also don't bother with the
  12200. // FragCoord builtin; it's always noperspective on Metal.
  12201. if (!type_is_integral(mbr_type) && (!is_builtin || builtin != BuiltInFragCoord))
  12202. {
  12203. if (has_member_decoration(type.self, index, DecorationFlat))
  12204. {
  12205. if (!quals.empty())
  12206. quals += ", ";
  12207. quals += "flat";
  12208. }
  12209. else if (has_member_decoration(type.self, index, DecorationCentroid))
  12210. {
  12211. if (!quals.empty())
  12212. quals += ", ";
  12213. if (builtin == BuiltInBaryCoordNoPerspKHR || builtin == BuiltInBaryCoordKHR)
  12214. SPIRV_CROSS_THROW("Centroid interpolation not supported for barycentrics in MSL.");
  12215. if (has_member_decoration(type.self, index, DecorationNoPerspective))
  12216. quals += "centroid_no_perspective";
  12217. else
  12218. quals += "centroid_perspective";
  12219. }
  12220. else if (has_member_decoration(type.self, index, DecorationSample))
  12221. {
  12222. if (!quals.empty())
  12223. quals += ", ";
  12224. if (builtin == BuiltInBaryCoordNoPerspKHR || builtin == BuiltInBaryCoordKHR)
  12225. SPIRV_CROSS_THROW("Sample interpolation not supported for barycentrics in MSL.");
  12226. if (has_member_decoration(type.self, index, DecorationNoPerspective))
  12227. quals += "sample_no_perspective";
  12228. else
  12229. quals += "sample_perspective";
  12230. }
  12231. else if (has_member_decoration(type.self, index, DecorationNoPerspective) || builtin == BuiltInBaryCoordNoPerspKHR)
  12232. {
  12233. if (!quals.empty())
  12234. quals += ", ";
  12235. quals += "center_no_perspective";
  12236. }
  12237. else if (builtin == BuiltInBaryCoordKHR)
  12238. {
  12239. if (!quals.empty())
  12240. quals += ", ";
  12241. quals += "center_perspective";
  12242. }
  12243. }
  12244. if (!quals.empty())
  12245. return " [[" + quals + "]]";
  12246. }
  12247. // Fragment function outputs
  12248. if (execution.model == ExecutionModelFragment && type.storage == StorageClassOutput)
  12249. {
  12250. if (is_builtin)
  12251. {
  12252. switch (builtin)
  12253. {
  12254. case BuiltInFragStencilRefEXT:
  12255. // Similar to PointSize, only mark FragStencilRef if there's a stencil buffer.
  12256. // Some shaders may include a FragStencilRef builtin even when used to render
  12257. // without a stencil attachment, and Metal will reject this builtin
  12258. // when compiling the shader into a render pipeline that does not set
  12259. // stencilAttachmentPixelFormat.
  12260. if (!msl_options.enable_frag_stencil_ref_builtin)
  12261. return "";
  12262. if (!msl_options.supports_msl_version(2, 1))
  12263. SPIRV_CROSS_THROW("Stencil export only supported in MSL 2.1 and up.");
  12264. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12265. case BuiltInFragDepth:
  12266. // Ditto FragDepth.
  12267. if (!msl_options.enable_frag_depth_builtin)
  12268. return "";
  12269. /* fallthrough */
  12270. case BuiltInSampleMask:
  12271. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12272. default:
  12273. return "";
  12274. }
  12275. }
  12276. uint32_t locn = get_member_location(type.self, index);
  12277. // Metal will likely complain about missing color attachments, too.
  12278. if (locn != k_unknown_location && !(msl_options.enable_frag_output_mask & (1 << locn)))
  12279. return "";
  12280. if (locn != k_unknown_location && has_member_decoration(type.self, index, DecorationIndex))
  12281. return join(" [[color(", locn, "), index(", get_member_decoration(type.self, index, DecorationIndex),
  12282. ")]]");
  12283. else if (locn != k_unknown_location)
  12284. return join(" [[color(", locn, ")]]");
  12285. else if (has_member_decoration(type.self, index, DecorationIndex))
  12286. return join(" [[index(", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12287. else
  12288. return "";
  12289. }
  12290. // Compute function inputs
  12291. if (execution.model == ExecutionModelGLCompute && type.storage == StorageClassInput)
  12292. {
  12293. if (is_builtin)
  12294. {
  12295. switch (builtin)
  12296. {
  12297. case BuiltInNumSubgroups:
  12298. case BuiltInSubgroupId:
  12299. case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage
  12300. case BuiltInSubgroupSize: // FIXME: Should work in any stage
  12301. if (msl_options.emulate_subgroups)
  12302. break;
  12303. /* fallthrough */
  12304. case BuiltInGlobalInvocationId:
  12305. case BuiltInWorkgroupId:
  12306. case BuiltInNumWorkgroups:
  12307. case BuiltInLocalInvocationId:
  12308. case BuiltInLocalInvocationIndex:
  12309. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12310. default:
  12311. return "";
  12312. }
  12313. }
  12314. }
  12315. return "";
  12316. }
  12317. // A user-defined output variable is considered to match an input variable in the subsequent
  12318. // stage if the two variables are declared with the same Location and Component decoration and
  12319. // match in type and decoration, except that interpolation decorations are not required to match.
  12320. // For the purposes of interface matching, variables declared without a Component decoration are
  12321. // considered to have a Component decoration of zero.
  12322. string CompilerMSL::member_location_attribute_qualifier(const SPIRType &type, uint32_t index)
  12323. {
  12324. string quals;
  12325. uint32_t comp;
  12326. uint32_t locn = get_member_location(type.self, index, &comp);
  12327. if (locn != k_unknown_location)
  12328. {
  12329. quals += "user(locn";
  12330. quals += convert_to_string(locn);
  12331. if (comp != k_unknown_component && comp != 0)
  12332. {
  12333. quals += "_";
  12334. quals += convert_to_string(comp);
  12335. }
  12336. quals += ")";
  12337. }
  12338. return quals;
  12339. }
  12340. // Returns the location decoration of the member with the specified index in the specified type.
  12341. // If the location of the member has been explicitly set, that location is used. If not, this
  12342. // function assumes the members are ordered in their location order, and simply returns the
  12343. // index as the location.
  12344. uint32_t CompilerMSL::get_member_location(uint32_t type_id, uint32_t index, uint32_t *comp) const
  12345. {
  12346. if (comp)
  12347. {
  12348. if (has_member_decoration(type_id, index, DecorationComponent))
  12349. *comp = get_member_decoration(type_id, index, DecorationComponent);
  12350. else
  12351. *comp = k_unknown_component;
  12352. }
  12353. if (has_member_decoration(type_id, index, DecorationLocation))
  12354. return get_member_decoration(type_id, index, DecorationLocation);
  12355. else
  12356. return k_unknown_location;
  12357. }
  12358. uint32_t CompilerMSL::get_or_allocate_builtin_input_member_location(BuiltIn builtin,
  12359. uint32_t type_id, uint32_t index,
  12360. uint32_t *comp)
  12361. {
  12362. uint32_t loc = get_member_location(type_id, index, comp);
  12363. if (loc != k_unknown_location)
  12364. return loc;
  12365. if (comp)
  12366. *comp = k_unknown_component;
  12367. // Late allocation. Find a location which is unused by the application.
  12368. // This can happen for built-in inputs in tessellation which are mixed and matched with user inputs.
  12369. auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]);
  12370. uint32_t count = type_to_location_count(mbr_type);
  12371. loc = 0;
  12372. const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool {
  12373. for (uint32_t i = 0; i < location_count; i++)
  12374. if (location_inputs_in_use.count(location + i) != 0)
  12375. return true;
  12376. return false;
  12377. };
  12378. while (location_range_in_use(loc, count))
  12379. loc++;
  12380. set_member_decoration(type_id, index, DecorationLocation, loc);
  12381. // Triangle tess level inputs are shared in one packed float4,
  12382. // mark both builtins as sharing one location.
  12383. if (!msl_options.raw_buffer_tese_input && is_tessellating_triangles() &&
  12384. (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
  12385. {
  12386. builtin_to_automatic_input_location[BuiltInTessLevelInner] = loc;
  12387. builtin_to_automatic_input_location[BuiltInTessLevelOuter] = loc;
  12388. }
  12389. else
  12390. builtin_to_automatic_input_location[builtin] = loc;
  12391. mark_location_as_used_by_shader(loc, mbr_type, StorageClassInput, true);
  12392. return loc;
  12393. }
  12394. uint32_t CompilerMSL::get_or_allocate_builtin_output_member_location(BuiltIn builtin,
  12395. uint32_t type_id, uint32_t index,
  12396. uint32_t *comp)
  12397. {
  12398. uint32_t loc = get_member_location(type_id, index, comp);
  12399. if (loc != k_unknown_location)
  12400. return loc;
  12401. loc = 0;
  12402. if (comp)
  12403. *comp = k_unknown_component;
  12404. // Late allocation. Find a location which is unused by the application.
  12405. // This can happen for built-in outputs in tessellation which are mixed and matched with user inputs.
  12406. auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]);
  12407. uint32_t count = type_to_location_count(mbr_type);
  12408. const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool {
  12409. for (uint32_t i = 0; i < location_count; i++)
  12410. if (location_outputs_in_use.count(location + i) != 0)
  12411. return true;
  12412. return false;
  12413. };
  12414. while (location_range_in_use(loc, count))
  12415. loc++;
  12416. set_member_decoration(type_id, index, DecorationLocation, loc);
  12417. // Triangle tess level inputs are shared in one packed float4;
  12418. // mark both builtins as sharing one location.
  12419. if (is_tessellating_triangles() && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
  12420. {
  12421. builtin_to_automatic_output_location[BuiltInTessLevelInner] = loc;
  12422. builtin_to_automatic_output_location[BuiltInTessLevelOuter] = loc;
  12423. }
  12424. else
  12425. builtin_to_automatic_output_location[builtin] = loc;
  12426. mark_location_as_used_by_shader(loc, mbr_type, StorageClassOutput, true);
  12427. return loc;
  12428. }
  12429. bool CompilerMSL::entry_point_is_vertex() const
  12430. {
  12431. // MSL vertex entrypoint is used for non-tessellation vertex stage or tessellation evaluation stage.
  12432. return (get_execution_model() == ExecutionModelVertex && !msl_options.vertex_for_tessellation) ||
  12433. get_execution_model() == ExecutionModelTessellationEvaluation;
  12434. }
  12435. bool CompilerMSL::entry_point_returns_stage_output() const
  12436. {
  12437. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
  12438. return false;
  12439. bool ep_should_return_output = !get_is_rasterization_disabled();
  12440. return stage_out_var_id && ep_should_return_output;
  12441. }
  12442. bool CompilerMSL::entry_point_requires_const_device_buffers() const
  12443. {
  12444. return !has_descriptor_side_effects_buffer && !capture_output_to_buffer;
  12445. }
  12446. // Returns the type declaration for a function, including the
  12447. // entry type if the current function is the entry point function
  12448. string CompilerMSL::func_type_decl(SPIRType &type)
  12449. {
  12450. // The regular function return type. If not processing the entry point function, that's all we need
  12451. string return_type = type_to_glsl(type) + type_to_array_glsl(type, 0);
  12452. if (!processing_entry_point)
  12453. return return_type;
  12454. // If an outgoing interface block has been defined, and it should be returned, override the entry point return type
  12455. if (entry_point_returns_stage_output())
  12456. return_type = type_to_glsl(get_stage_out_struct_type()) + type_to_array_glsl(type, 0);
  12457. // Prepend a entry type, based on the execution model
  12458. string entry_type;
  12459. auto &execution = get_entry_point();
  12460. switch (execution.model)
  12461. {
  12462. case ExecutionModelVertex:
  12463. if (msl_options.vertex_for_tessellation && !msl_options.supports_msl_version(1, 2))
  12464. SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
  12465. entry_type = msl_options.vertex_for_tessellation ? "kernel" : "vertex";
  12466. break;
  12467. case ExecutionModelTessellationEvaluation:
  12468. if (!msl_options.supports_msl_version(1, 2))
  12469. SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
  12470. if (execution.flags.get(ExecutionModeIsolines))
  12471. SPIRV_CROSS_THROW("Metal does not support isoline tessellation.");
  12472. if (msl_options.is_ios())
  12473. entry_type = join("[[ patch(", is_tessellating_triangles() ? "triangle" : "quad", ") ]] vertex");
  12474. else
  12475. entry_type = join("[[ patch(", is_tessellating_triangles() ? "triangle" : "quad", ", ",
  12476. execution.output_vertices, ") ]] vertex");
  12477. break;
  12478. case ExecutionModelFragment:
  12479. entry_type = uses_explicit_early_fragment_test() ? "[[ early_fragment_tests ]] fragment" : "fragment";
  12480. break;
  12481. case ExecutionModelTessellationControl:
  12482. if (!msl_options.supports_msl_version(1, 2))
  12483. SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
  12484. if (execution.flags.get(ExecutionModeIsolines))
  12485. SPIRV_CROSS_THROW("Metal does not support isoline tessellation.");
  12486. /* fallthrough */
  12487. case ExecutionModelGLCompute:
  12488. case ExecutionModelKernel:
  12489. entry_type = "kernel";
  12490. break;
  12491. case ExecutionModelMeshEXT:
  12492. entry_type = "[[mesh]]";
  12493. break;
  12494. case ExecutionModelTaskEXT:
  12495. entry_type = "[[object]]";
  12496. break;
  12497. default:
  12498. entry_type = "unknown";
  12499. break;
  12500. }
  12501. return entry_type + " " + return_type;
  12502. }
  12503. bool CompilerMSL::is_tesc_shader() const
  12504. {
  12505. return get_execution_model() == ExecutionModelTessellationControl;
  12506. }
  12507. bool CompilerMSL::is_tese_shader() const
  12508. {
  12509. return get_execution_model() == ExecutionModelTessellationEvaluation;
  12510. }
  12511. bool CompilerMSL::is_mesh_shader() const
  12512. {
  12513. return get_execution_model() == ExecutionModelMeshEXT;
  12514. }
  12515. bool CompilerMSL::uses_explicit_early_fragment_test()
  12516. {
  12517. auto &ep_flags = get_entry_point().flags;
  12518. return ep_flags.get(ExecutionModeEarlyFragmentTests) || ep_flags.get(ExecutionModePostDepthCoverage);
  12519. }
  12520. // In MSL, address space qualifiers are required for all pointer or reference variables
  12521. string CompilerMSL::get_variable_address_space(const SPIRVariable &argument)
  12522. {
  12523. const auto &type = get<SPIRType>(argument.basetype);
  12524. return get_type_address_space(type, argument.self, true);
  12525. }
  12526. string CompilerMSL::get_leaf_argument_address_space(const SPIRVariable &argument)
  12527. {
  12528. const auto &type = get<SPIRType>(argument.basetype);
  12529. // BDA and variable buffer pointer is always passed around by (pointer) value. There is no storage class for the argument itself.
  12530. if (is_physical_or_buffer_pointer(type))
  12531. return "";
  12532. return get_type_address_space(type, argument.self, true);
  12533. }
  12534. bool CompilerMSL::decoration_flags_signal_volatile(const Bitset &flags) const
  12535. {
  12536. // Using volatile for coherent pre-3.2 is definitely not correct, but it's something.
  12537. // MSL 3.2 adds actual coherent qualifiers.
  12538. return flags.get(DecorationVolatile) ||
  12539. (flags.get(DecorationCoherent) && !msl_options.supports_msl_version(3, 2));
  12540. }
  12541. bool CompilerMSL::decoration_flags_signal_coherent(const Bitset &flags) const
  12542. {
  12543. return flags.get(DecorationCoherent) && msl_options.supports_msl_version(3, 2);
  12544. }
  12545. string CompilerMSL::get_type_address_space(const SPIRType &type, uint32_t id, bool argument)
  12546. {
  12547. // This can be called for variable pointer contexts as well, so be very careful about which method we choose.
  12548. Bitset flags;
  12549. auto *var = maybe_get<SPIRVariable>(id);
  12550. if (var && type.basetype == SPIRType::Struct &&
  12551. (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock)))
  12552. flags = get_buffer_block_flags(id);
  12553. else
  12554. {
  12555. flags = get_decoration_bitset(id);
  12556. if (type.basetype == SPIRType::Struct &&
  12557. (has_decoration(type.self, DecorationBlock) ||
  12558. has_decoration(type.self, DecorationBufferBlock)))
  12559. {
  12560. flags.merge_or(ir.get_buffer_block_type_flags(type));
  12561. }
  12562. }
  12563. const char *addr_space = nullptr;
  12564. switch (type.storage)
  12565. {
  12566. case StorageClassWorkgroup:
  12567. addr_space = "threadgroup";
  12568. break;
  12569. case StorageClassStorageBuffer:
  12570. case StorageClassPhysicalStorageBuffer:
  12571. {
  12572. // When dealing with descriptor aliasing, it becomes very problematic to make use of
  12573. // readonly qualifiers.
  12574. // If rasterization is not disabled in vertex/tese, Metal does not allow side effects and refuses to compile "device",
  12575. // even if there are no writes. Just force const device.
  12576. if (entry_point_requires_const_device_buffers() && type.basetype != SPIRType::AtomicCounter)
  12577. addr_space = "const device";
  12578. else
  12579. addr_space = "device";
  12580. break;
  12581. }
  12582. case StorageClassUniform:
  12583. case StorageClassUniformConstant:
  12584. case StorageClassPushConstant:
  12585. if (type.basetype == SPIRType::Struct)
  12586. {
  12587. bool ssbo = has_decoration(type.self, DecorationBufferBlock);
  12588. if (ssbo)
  12589. {
  12590. if (entry_point_requires_const_device_buffers() && type.basetype != SPIRType::AtomicCounter)
  12591. addr_space = "const device";
  12592. else
  12593. addr_space = "device";
  12594. }
  12595. else
  12596. addr_space = "constant";
  12597. }
  12598. else if (!argument)
  12599. {
  12600. // This is used for helper UBOs we insert ourselves.
  12601. addr_space = "constant";
  12602. }
  12603. else if (type_is_msl_framebuffer_fetch(type))
  12604. {
  12605. // Subpass inputs are passed around by value.
  12606. addr_space = "";
  12607. }
  12608. break;
  12609. case StorageClassFunction:
  12610. case StorageClassGeneric:
  12611. break;
  12612. case StorageClassInput:
  12613. if (is_tesc_shader() && var && var->basevariable == stage_in_ptr_var_id)
  12614. addr_space = msl_options.multi_patch_workgroup ? "const device" : "threadgroup";
  12615. // Don't pass tessellation levels in the device AS; we load and convert them
  12616. // to float manually.
  12617. if (is_tese_shader() && msl_options.raw_buffer_tese_input && var)
  12618. {
  12619. bool is_stage_in = var->basevariable == stage_in_ptr_var_id;
  12620. bool is_patch_stage_in = has_decoration(var->self, DecorationPatch);
  12621. bool is_builtin = has_decoration(var->self, DecorationBuiltIn);
  12622. BuiltIn builtin = (BuiltIn)get_decoration(var->self, DecorationBuiltIn);
  12623. bool is_tess_level = is_builtin && (builtin == BuiltInTessLevelOuter || builtin == BuiltInTessLevelInner);
  12624. if (is_stage_in || (is_patch_stage_in && !is_tess_level))
  12625. addr_space = "const device";
  12626. }
  12627. if (get_execution_model() == ExecutionModelFragment && var && var->basevariable == stage_in_var_id)
  12628. addr_space = "thread";
  12629. break;
  12630. case StorageClassOutput:
  12631. if (capture_output_to_buffer)
  12632. {
  12633. if (var && type.storage == StorageClassOutput)
  12634. {
  12635. bool is_masked = is_stage_output_variable_masked(*var);
  12636. if (is_masked)
  12637. {
  12638. if (is_tessellation_shader())
  12639. addr_space = "threadgroup";
  12640. else
  12641. addr_space = "thread";
  12642. }
  12643. else if (variable_decl_is_remapped_storage(*var, StorageClassWorkgroup))
  12644. addr_space = "threadgroup";
  12645. }
  12646. if (!addr_space)
  12647. addr_space = "device";
  12648. }
  12649. if (is_mesh_shader())
  12650. addr_space = "threadgroup";
  12651. break;
  12652. case StorageClassTaskPayloadWorkgroupEXT:
  12653. if (is_mesh_shader())
  12654. addr_space = "const object_data";
  12655. else
  12656. addr_space = "object_data";
  12657. break;
  12658. default:
  12659. break;
  12660. }
  12661. if (!addr_space && var && is_var_runtime_size_array(*var))
  12662. addr_space = "device";
  12663. if (!addr_space)
  12664. {
  12665. // No address space for plain values.
  12666. addr_space = type.pointer || (argument && type.basetype == SPIRType::ControlPointArray) ? "thread" : "";
  12667. }
  12668. if (decoration_flags_signal_coherent(flags) && strcmp(addr_space, "device") == 0)
  12669. return join("coherent device");
  12670. else if (decoration_flags_signal_volatile(flags) && strcmp(addr_space, "thread") != 0)
  12671. return join("volatile ", addr_space);
  12672. else
  12673. return addr_space;
  12674. }
  12675. const char *CompilerMSL::to_restrict(uint32_t id, bool space)
  12676. {
  12677. // This can be called for variable pointer contexts as well, so be very careful about which method we choose.
  12678. Bitset flags;
  12679. if (ir.ids[id].get_type() == TypeVariable)
  12680. {
  12681. uint32_t type_id = expression_type_id(id);
  12682. auto &type = expression_type(id);
  12683. if (type.basetype == SPIRType::Struct &&
  12684. (has_decoration(type_id, DecorationBlock) || has_decoration(type_id, DecorationBufferBlock)))
  12685. flags = get_buffer_block_flags(id);
  12686. else
  12687. flags = get_decoration_bitset(id);
  12688. }
  12689. else
  12690. flags = get_decoration_bitset(id);
  12691. return flags.get(DecorationRestrict) || flags.get(DecorationRestrictPointerEXT) ?
  12692. (space ? "__restrict " : "__restrict") : "";
  12693. }
  12694. string CompilerMSL::entry_point_arg_stage_in()
  12695. {
  12696. string decl;
  12697. if ((is_tesc_shader() && msl_options.multi_patch_workgroup) ||
  12698. (is_tese_shader() && msl_options.raw_buffer_tese_input))
  12699. return decl;
  12700. // Stage-in structure
  12701. uint32_t stage_in_id;
  12702. if (is_tese_shader())
  12703. stage_in_id = patch_stage_in_var_id;
  12704. else
  12705. stage_in_id = stage_in_var_id;
  12706. if (stage_in_id)
  12707. {
  12708. auto &var = get<SPIRVariable>(stage_in_id);
  12709. auto &type = get_variable_data_type(var);
  12710. add_resource_name(var.self);
  12711. decl = join(type_to_glsl(type), " ", to_name(var.self), " [[stage_in]]");
  12712. }
  12713. return decl;
  12714. }
  12715. // Returns true if this input builtin should be a direct parameter on a shader function parameter list,
  12716. // and false for builtins that should be passed or calculated some other way.
  12717. bool CompilerMSL::is_direct_input_builtin(BuiltIn bi_type)
  12718. {
  12719. switch (bi_type)
  12720. {
  12721. // Vertex function in
  12722. case BuiltInVertexId:
  12723. case BuiltInVertexIndex:
  12724. case BuiltInBaseVertex:
  12725. case BuiltInInstanceId:
  12726. case BuiltInInstanceIndex:
  12727. case BuiltInBaseInstance:
  12728. return get_execution_model() != ExecutionModelVertex || !msl_options.vertex_for_tessellation;
  12729. // Tess. control function in
  12730. case BuiltInPosition:
  12731. case BuiltInPointSize:
  12732. case BuiltInClipDistance:
  12733. case BuiltInCullDistance:
  12734. case BuiltInPatchVertices:
  12735. return false;
  12736. case BuiltInInvocationId:
  12737. case BuiltInPrimitiveId:
  12738. return !is_tesc_shader() || !msl_options.multi_patch_workgroup;
  12739. // Tess. evaluation function in
  12740. case BuiltInTessLevelInner:
  12741. case BuiltInTessLevelOuter:
  12742. return false;
  12743. // Fragment function in
  12744. case BuiltInSamplePosition:
  12745. case BuiltInHelperInvocation:
  12746. case BuiltInBaryCoordKHR:
  12747. case BuiltInBaryCoordNoPerspKHR:
  12748. return false;
  12749. case BuiltInViewIndex:
  12750. return get_execution_model() == ExecutionModelFragment && msl_options.multiview &&
  12751. msl_options.multiview_layered_rendering;
  12752. // Compute function in
  12753. case BuiltInSubgroupId:
  12754. case BuiltInNumSubgroups:
  12755. return !msl_options.emulate_subgroups;
  12756. // Any stage function in
  12757. case BuiltInDeviceIndex:
  12758. case BuiltInSubgroupEqMask:
  12759. case BuiltInSubgroupGeMask:
  12760. case BuiltInSubgroupGtMask:
  12761. case BuiltInSubgroupLeMask:
  12762. case BuiltInSubgroupLtMask:
  12763. return false;
  12764. case BuiltInSubgroupSize:
  12765. if (msl_options.fixed_subgroup_size != 0)
  12766. return false;
  12767. /* fallthrough */
  12768. case BuiltInSubgroupLocalInvocationId:
  12769. return !msl_options.emulate_subgroups;
  12770. default:
  12771. return true;
  12772. }
  12773. }
  12774. // Returns true if this is a fragment shader that runs per sample, and false otherwise.
  12775. bool CompilerMSL::is_sample_rate() const
  12776. {
  12777. auto &caps = get_declared_capabilities();
  12778. return get_execution_model() == ExecutionModelFragment &&
  12779. (msl_options.force_sample_rate_shading ||
  12780. std::find(caps.begin(), caps.end(), CapabilitySampleRateShading) != caps.end() ||
  12781. (msl_options.use_framebuffer_fetch_subpasses && need_subpass_input_ms));
  12782. }
  12783. bool CompilerMSL::is_intersection_query() const
  12784. {
  12785. auto &caps = get_declared_capabilities();
  12786. return std::find(caps.begin(), caps.end(), CapabilityRayQueryKHR) != caps.end();
  12787. }
  12788. void CompilerMSL::entry_point_args_builtin(string &ep_args)
  12789. {
  12790. // Builtin variables
  12791. SmallVector<pair<SPIRVariable *, BuiltIn>, 8> active_builtins;
  12792. ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
  12793. if (var.storage != StorageClassInput)
  12794. return;
  12795. auto bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn));
  12796. // Don't emit SamplePosition as a separate parameter. In the entry
  12797. // point, we get that by calling get_sample_position() on the sample ID.
  12798. if (is_builtin_variable(var) &&
  12799. get_variable_data_type(var).basetype != SPIRType::Struct &&
  12800. get_variable_data_type(var).basetype != SPIRType::ControlPointArray)
  12801. {
  12802. // If the builtin is not part of the active input builtin set, don't emit it.
  12803. // Relevant for multiple entry-point modules which might declare unused builtins.
  12804. if (!active_input_builtins.get(bi_type) || !interface_variable_exists_in_entry_point(var_id))
  12805. return;
  12806. // Remember this variable. We may need to correct its type.
  12807. active_builtins.push_back(make_pair(&var, bi_type));
  12808. if (is_direct_input_builtin(bi_type))
  12809. {
  12810. if (!ep_args.empty())
  12811. ep_args += ", ";
  12812. // Handle HLSL-style 0-based vertex/instance index.
  12813. builtin_declaration = true;
  12814. // Handle different MSL gl_TessCoord types. (float2, float3)
  12815. if (bi_type == BuiltInTessCoord && get_entry_point().flags.get(ExecutionModeQuads))
  12816. ep_args += "float2 " + to_expression(var_id) + "In";
  12817. else
  12818. ep_args += builtin_type_decl(bi_type, var_id) + " " + to_expression(var_id);
  12819. ep_args += string(" [[") + builtin_qualifier(bi_type);
  12820. if (bi_type == BuiltInSampleMask && get_entry_point().flags.get(ExecutionModePostDepthCoverage))
  12821. {
  12822. if (!msl_options.supports_msl_version(2))
  12823. SPIRV_CROSS_THROW("Post-depth coverage requires MSL 2.0.");
  12824. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
  12825. SPIRV_CROSS_THROW("Post-depth coverage on Mac requires MSL 2.3.");
  12826. ep_args += ", post_depth_coverage";
  12827. }
  12828. ep_args += "]]";
  12829. builtin_declaration = false;
  12830. }
  12831. }
  12832. if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase))
  12833. {
  12834. // This is a special implicit builtin, not corresponding to any SPIR-V builtin,
  12835. // which holds the base that was passed to vkCmdDispatchBase() or vkCmdDrawIndexed(). If it's present,
  12836. // assume we emitted it for a good reason.
  12837. assert(msl_options.supports_msl_version(1, 2));
  12838. if (!ep_args.empty())
  12839. ep_args += ", ";
  12840. ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_origin]]";
  12841. }
  12842. if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize))
  12843. {
  12844. // This is another special implicit builtin, not corresponding to any SPIR-V builtin,
  12845. // which holds the number of vertices and instances to draw. If it's present,
  12846. // assume we emitted it for a good reason.
  12847. assert(msl_options.supports_msl_version(1, 2));
  12848. if (!ep_args.empty())
  12849. ep_args += ", ";
  12850. ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_size]]";
  12851. }
  12852. });
  12853. // Correct the types of all encountered active builtins. We couldn't do this before
  12854. // because ensure_correct_builtin_type() may increase the bound, which isn't allowed
  12855. // while iterating over IDs.
  12856. for (auto &var : active_builtins)
  12857. var.first->basetype = ensure_correct_builtin_type(var.first->basetype, var.second);
  12858. // Handle HLSL-style 0-based vertex/instance index.
  12859. if (needs_base_vertex_arg == TriState::Yes)
  12860. ep_args += built_in_func_arg(BuiltInBaseVertex, !ep_args.empty());
  12861. if (needs_base_instance_arg == TriState::Yes)
  12862. ep_args += built_in_func_arg(BuiltInBaseInstance, !ep_args.empty());
  12863. if (capture_output_to_buffer)
  12864. {
  12865. // Add parameters to hold the indirect draw parameters and the shader output. This has to be handled
  12866. // specially because it needs to be a pointer, not a reference.
  12867. if (stage_out_var_id)
  12868. {
  12869. if (!ep_args.empty())
  12870. ep_args += ", ";
  12871. ep_args += join("device ", type_to_glsl(get_stage_out_struct_type()), "* ", output_buffer_var_name,
  12872. " [[buffer(", msl_options.shader_output_buffer_index, ")]]");
  12873. }
  12874. if (is_tesc_shader())
  12875. {
  12876. if (!ep_args.empty())
  12877. ep_args += ", ";
  12878. ep_args +=
  12879. join("constant uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]");
  12880. }
  12881. else if (stage_out_var_id &&
  12882. !(get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation))
  12883. {
  12884. if (!ep_args.empty())
  12885. ep_args += ", ";
  12886. ep_args +=
  12887. join("device uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]");
  12888. }
  12889. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation &&
  12890. (active_input_builtins.get(BuiltInVertexIndex) || active_input_builtins.get(BuiltInVertexId)) &&
  12891. msl_options.vertex_index_type != Options::IndexType::None)
  12892. {
  12893. // Add the index buffer so we can set gl_VertexIndex correctly.
  12894. if (!ep_args.empty())
  12895. ep_args += ", ";
  12896. switch (msl_options.vertex_index_type)
  12897. {
  12898. case Options::IndexType::None:
  12899. break;
  12900. case Options::IndexType::UInt16:
  12901. ep_args += join("const device ushort* ", index_buffer_var_name, " [[buffer(",
  12902. msl_options.shader_index_buffer_index, ")]]");
  12903. break;
  12904. case Options::IndexType::UInt32:
  12905. ep_args += join("const device uint* ", index_buffer_var_name, " [[buffer(",
  12906. msl_options.shader_index_buffer_index, ")]]");
  12907. break;
  12908. }
  12909. }
  12910. // Tessellation control shaders get three additional parameters:
  12911. // a buffer to hold the per-patch data, a buffer to hold the per-patch
  12912. // tessellation levels, and a block of workgroup memory to hold the
  12913. // input control point data.
  12914. if (is_tesc_shader())
  12915. {
  12916. if (patch_stage_out_var_id)
  12917. {
  12918. if (!ep_args.empty())
  12919. ep_args += ", ";
  12920. ep_args +=
  12921. join("device ", type_to_glsl(get_patch_stage_out_struct_type()), "* ", patch_output_buffer_var_name,
  12922. " [[buffer(", convert_to_string(msl_options.shader_patch_output_buffer_index), ")]]");
  12923. }
  12924. if (!ep_args.empty())
  12925. ep_args += ", ";
  12926. ep_args += join("device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name, " [[buffer(",
  12927. convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]");
  12928. // Initializer for tess factors must be handled specially since it's never declared as a normal variable.
  12929. uint32_t outer_factor_initializer_id = 0;
  12930. uint32_t inner_factor_initializer_id = 0;
  12931. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  12932. if (!has_decoration(var.self, DecorationBuiltIn) || var.storage != StorageClassOutput || !var.initializer)
  12933. return;
  12934. BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  12935. if (builtin == BuiltInTessLevelInner)
  12936. inner_factor_initializer_id = var.initializer;
  12937. else if (builtin == BuiltInTessLevelOuter)
  12938. outer_factor_initializer_id = var.initializer;
  12939. });
  12940. const SPIRConstant *c = nullptr;
  12941. if (outer_factor_initializer_id && (c = maybe_get<SPIRConstant>(outer_factor_initializer_id)))
  12942. {
  12943. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  12944. entry_func.fixup_hooks_in.push_back(
  12945. [=]()
  12946. {
  12947. uint32_t components = is_tessellating_triangles() ? 3 : 4;
  12948. for (uint32_t i = 0; i < components; i++)
  12949. {
  12950. statement(builtin_to_glsl(BuiltInTessLevelOuter, StorageClassOutput), "[", i,
  12951. "] = ", "half(", to_expression(c->subconstants[i]), ");");
  12952. }
  12953. });
  12954. }
  12955. if (inner_factor_initializer_id && (c = maybe_get<SPIRConstant>(inner_factor_initializer_id)))
  12956. {
  12957. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  12958. if (is_tessellating_triangles())
  12959. {
  12960. entry_func.fixup_hooks_in.push_back([=]() {
  12961. statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), " = ", "half(",
  12962. to_expression(c->subconstants[0]), ");");
  12963. });
  12964. }
  12965. else
  12966. {
  12967. entry_func.fixup_hooks_in.push_back([=]() {
  12968. for (uint32_t i = 0; i < 2; i++)
  12969. {
  12970. statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), "[", i, "] = ",
  12971. "half(", to_expression(c->subconstants[i]), ");");
  12972. }
  12973. });
  12974. }
  12975. }
  12976. if (stage_in_var_id)
  12977. {
  12978. if (!ep_args.empty())
  12979. ep_args += ", ";
  12980. if (msl_options.multi_patch_workgroup)
  12981. {
  12982. ep_args += join("device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name,
  12983. " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]");
  12984. }
  12985. else
  12986. {
  12987. ep_args += join("threadgroup ", type_to_glsl(get_stage_in_struct_type()), "* ", input_wg_var_name,
  12988. " [[threadgroup(", convert_to_string(msl_options.shader_input_wg_index), ")]]");
  12989. }
  12990. }
  12991. }
  12992. }
  12993. // Tessellation evaluation shaders get three additional parameters:
  12994. // a buffer for the per-patch data, a buffer for the per-patch
  12995. // tessellation levels, and a buffer for the control point data.
  12996. if (is_tese_shader() && msl_options.raw_buffer_tese_input)
  12997. {
  12998. if (patch_stage_in_var_id)
  12999. {
  13000. if (!ep_args.empty())
  13001. ep_args += ", ";
  13002. ep_args +=
  13003. join("const device ", type_to_glsl(get_patch_stage_in_struct_type()), "* ", patch_input_buffer_var_name,
  13004. " [[buffer(", convert_to_string(msl_options.shader_patch_input_buffer_index), ")]]");
  13005. }
  13006. if (tess_level_inner_var_id || tess_level_outer_var_id)
  13007. {
  13008. if (!ep_args.empty())
  13009. ep_args += ", ";
  13010. ep_args += join("const device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name,
  13011. " [[buffer(", convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]");
  13012. }
  13013. if (stage_in_var_id)
  13014. {
  13015. if (!ep_args.empty())
  13016. ep_args += ", ";
  13017. ep_args += join("const device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name,
  13018. " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]");
  13019. }
  13020. }
  13021. if (is_mesh_shader())
  13022. {
  13023. if (!ep_args.empty())
  13024. ep_args += ", ";
  13025. ep_args += join("spvMesh_t spvMesh");
  13026. }
  13027. if (get_execution_model() == ExecutionModelTaskEXT)
  13028. {
  13029. if (!ep_args.empty())
  13030. ep_args += ", ";
  13031. ep_args += join("mesh_grid_properties spvMgp");
  13032. }
  13033. }
  13034. string CompilerMSL::entry_point_args_argument_buffer(bool append_comma)
  13035. {
  13036. string ep_args = entry_point_arg_stage_in();
  13037. Bitset claimed_bindings;
  13038. for (uint32_t i = 0; i < kMaxArgumentBuffers; i++)
  13039. {
  13040. uint32_t id = argument_buffer_ids[i];
  13041. if (id == 0)
  13042. continue;
  13043. add_resource_name(id);
  13044. auto &var = get<SPIRVariable>(id);
  13045. auto &type = get_variable_data_type(var);
  13046. if (!ep_args.empty())
  13047. ep_args += ", ";
  13048. // Check if the argument buffer binding itself has been remapped.
  13049. uint32_t buffer_binding;
  13050. auto itr = resource_bindings.find({ get_entry_point().model, i, kArgumentBufferBinding });
  13051. if (itr != end(resource_bindings))
  13052. {
  13053. buffer_binding = itr->second.first.msl_buffer;
  13054. itr->second.second = true;
  13055. }
  13056. else
  13057. {
  13058. // As a fallback, directly map desc set <-> binding.
  13059. // If that was taken, take the next buffer binding.
  13060. if (claimed_bindings.get(i))
  13061. buffer_binding = next_metal_resource_index_buffer;
  13062. else
  13063. buffer_binding = i;
  13064. }
  13065. claimed_bindings.set(buffer_binding);
  13066. ep_args += get_variable_address_space(var) + " ";
  13067. if (recursive_inputs.count(type.self))
  13068. ep_args += string("void* ") + to_restrict(id, true) + to_name(id) + "_vp";
  13069. else
  13070. ep_args += type_to_glsl(type) + "& " + to_restrict(id, true) + to_name(id);
  13071. ep_args += " [[buffer(" + convert_to_string(buffer_binding) + ")]]";
  13072. next_metal_resource_index_buffer = max(next_metal_resource_index_buffer, buffer_binding + 1);
  13073. }
  13074. entry_point_args_discrete_descriptors(ep_args);
  13075. entry_point_args_builtin(ep_args);
  13076. if (!ep_args.empty() && append_comma)
  13077. ep_args += ", ";
  13078. return ep_args;
  13079. }
  13080. const MSLConstexprSampler *CompilerMSL::find_constexpr_sampler(uint32_t id) const
  13081. {
  13082. // Try by ID.
  13083. {
  13084. auto itr = constexpr_samplers_by_id.find(id);
  13085. if (itr != end(constexpr_samplers_by_id))
  13086. return &itr->second;
  13087. }
  13088. // Try by binding.
  13089. {
  13090. uint32_t desc_set = get_decoration(id, DecorationDescriptorSet);
  13091. uint32_t binding = get_decoration(id, DecorationBinding);
  13092. auto itr = constexpr_samplers_by_binding.find({ desc_set, binding });
  13093. if (itr != end(constexpr_samplers_by_binding))
  13094. return &itr->second;
  13095. }
  13096. return nullptr;
  13097. }
  13098. void CompilerMSL::entry_point_args_discrete_descriptors(string &ep_args)
  13099. {
  13100. // Output resources, sorted by resource index & type
  13101. // We need to sort to work around a bug on macOS 10.13 with NVidia drivers where switching between shaders
  13102. // with different order of buffers can result in issues with buffer assignments inside the driver.
  13103. struct Resource
  13104. {
  13105. SPIRVariable *var;
  13106. SPIRVariable *discrete_descriptor_alias;
  13107. string name;
  13108. SPIRType::BaseType basetype;
  13109. uint32_t index;
  13110. uint32_t plane;
  13111. uint32_t secondary_index;
  13112. };
  13113. SmallVector<Resource> resources;
  13114. entry_point_bindings.clear();
  13115. ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
  13116. if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  13117. var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer) &&
  13118. !is_hidden_variable(var))
  13119. {
  13120. auto &type = get_variable_data_type(var);
  13121. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13122. if (is_supported_argument_buffer_type(type) && var.storage != StorageClassPushConstant)
  13123. {
  13124. if (descriptor_set_is_argument_buffer(desc_set))
  13125. {
  13126. if (is_var_runtime_size_array(var))
  13127. {
  13128. // Runtime arrays need to be wrapped in spvDescriptorArray from argument buffer payload.
  13129. entry_point_bindings.push_back(&var);
  13130. // We'll wrap this, so to_name() will always use non-qualified name.
  13131. // We'll need the qualified name to create temporary variable instead.
  13132. ir.meta[var_id].decoration.qualified_alias_explicit_override = true;
  13133. }
  13134. return;
  13135. }
  13136. }
  13137. // Handle descriptor aliasing of simple discrete cases.
  13138. // We can handle aliasing of buffers by casting pointers.
  13139. // The amount of aliasing we can perform for discrete descriptors is very limited.
  13140. // For fully mutable-style aliasing, we need argument buffers where we can exploit the fact
  13141. // that descriptors are all 8 bytes.
  13142. SPIRVariable *discrete_descriptor_alias = nullptr;
  13143. const auto resource_is_aliasing_candidate = [this](const SPIRVariable &var_) {
  13144. return is_var_runtime_size_array(var_) || var_.storage == StorageClassUniform ||
  13145. var_.storage == StorageClassStorageBuffer;
  13146. };
  13147. if (resource_is_aliasing_candidate(var))
  13148. {
  13149. for (auto &resource : resources)
  13150. {
  13151. if (resource_is_aliasing_candidate(*resource.var) &&
  13152. get_decoration(resource.var->self, DecorationDescriptorSet) ==
  13153. get_decoration(var_id, DecorationDescriptorSet) &&
  13154. get_decoration(resource.var->self, DecorationBinding) ==
  13155. get_decoration(var_id, DecorationBinding))
  13156. {
  13157. discrete_descriptor_alias = resource.var;
  13158. // Self-reference marks that we should declare the resource,
  13159. // and it's being used as an alias (so we can emit void* instead).
  13160. resource.discrete_descriptor_alias = resource.var;
  13161. // Need to promote interlocked usage so that the primary declaration is correct.
  13162. if (interlocked_resources.count(var_id))
  13163. interlocked_resources.insert(resource.var->self);
  13164. // Aliasing with unroll just gets too messy to deal with. I sure hope this never comes up ...
  13165. if ((is_array(get_variable_data_type(*resource.var)) && !is_var_runtime_size_array(*resource.var)) ||
  13166. (is_array(get_variable_data_type(var)) && !is_var_runtime_size_array(var)))
  13167. {
  13168. SPIRV_CROSS_THROW("Attempting to alias same binding with a descriptor array which is not implemented through argument buffers. This is unsupported.");
  13169. }
  13170. break;
  13171. }
  13172. }
  13173. }
  13174. const MSLConstexprSampler *constexpr_sampler = nullptr;
  13175. if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler)
  13176. {
  13177. constexpr_sampler = find_constexpr_sampler(var_id);
  13178. if (constexpr_sampler)
  13179. {
  13180. // Mark this ID as a constexpr sampler for later in case it came from set/bindings.
  13181. constexpr_samplers_by_id[var_id] = *constexpr_sampler;
  13182. }
  13183. }
  13184. // Emulate texture2D atomic operations
  13185. uint32_t secondary_index = 0;
  13186. if (atomic_image_vars_emulated.count(var.self))
  13187. {
  13188. secondary_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0);
  13189. }
  13190. if (type.basetype == SPIRType::SampledImage)
  13191. {
  13192. add_resource_name(var_id);
  13193. uint32_t plane_count = 1;
  13194. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  13195. plane_count = constexpr_sampler->planes;
  13196. entry_point_bindings.push_back(&var);
  13197. for (uint32_t i = 0; i < plane_count; i++)
  13198. resources.push_back({&var, discrete_descriptor_alias, to_name(var_id), SPIRType::Image,
  13199. get_metal_resource_index(var, SPIRType::Image, i), i, secondary_index });
  13200. if (type.image.dim != DimBuffer && !constexpr_sampler)
  13201. {
  13202. resources.push_back({&var, discrete_descriptor_alias, to_sampler_expression(var_id), SPIRType::Sampler,
  13203. get_metal_resource_index(var, SPIRType::Sampler), 0, 0 });
  13204. }
  13205. }
  13206. else if (!constexpr_sampler)
  13207. {
  13208. // constexpr samplers are not declared as resources.
  13209. add_resource_name(var_id);
  13210. // Don't allocate resource indices for aliases.
  13211. uint32_t resource_index = ~0u;
  13212. if (!discrete_descriptor_alias)
  13213. resource_index = get_metal_resource_index(var, type.basetype);
  13214. entry_point_bindings.push_back(&var);
  13215. resources.push_back({&var, discrete_descriptor_alias, to_name(var_id), type.basetype,
  13216. resource_index, 0, secondary_index });
  13217. }
  13218. }
  13219. });
  13220. stable_sort(resources.begin(), resources.end(),
  13221. [](const Resource &lhs, const Resource &rhs)
  13222. { return tie(lhs.basetype, lhs.index) < tie(rhs.basetype, rhs.index); });
  13223. for (auto &r : resources)
  13224. {
  13225. auto &var = *r.var;
  13226. auto &type = get_variable_data_type(var);
  13227. uint32_t var_id = var.self;
  13228. if (is_var_runtime_size_array(var))
  13229. {
  13230. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  13231. const bool ssbo = has_decoration(type.self, DecorationBufferBlock);
  13232. if ((var.storage == StorageClassStorageBuffer || ssbo) && msl_options.runtime_array_rich_descriptor)
  13233. add_spv_func_and_recompile(SPVFuncImplVariableSizedDescriptor);
  13234. else
  13235. add_spv_func_and_recompile(SPVFuncImplVariableDescriptor);
  13236. }
  13237. if (r.discrete_descriptor_alias)
  13238. {
  13239. if (r.var == r.discrete_descriptor_alias)
  13240. {
  13241. auto primary_name = join("spvBufferAliasSet",
  13242. get_decoration(var_id, DecorationDescriptorSet),
  13243. "Binding",
  13244. get_decoration(var_id, DecorationBinding));
  13245. // Declare the primary alias as void*
  13246. if (!ep_args.empty())
  13247. ep_args += ", ";
  13248. ep_args += get_variable_address_space(var) + " void* " + primary_name;
  13249. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13250. if (interlocked_resources.count(var_id))
  13251. ep_args += ", raster_order_group(0)";
  13252. ep_args += "]]";
  13253. }
  13254. buffer_aliases_discrete.push_back(r.var->self);
  13255. continue;
  13256. }
  13257. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13258. uint32_t desc_binding = get_decoration(var_id, DecorationBinding);
  13259. if (is_var_runtime_size_array(var))
  13260. {
  13261. // This must be implemented as an argument buffer. Cast to intended descriptor array type on-demand.
  13262. if (!ep_args.empty())
  13263. ep_args += ", ";
  13264. ep_args += join("device const void* spvDescriptorSet", desc_set, "Binding", desc_binding);
  13265. if (type.basetype == SPIRType::SampledImage && r.basetype == SPIRType::Sampler)
  13266. ep_args += "Smplr";
  13267. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13268. if (interlocked_resources.count(var_id))
  13269. ep_args += ", raster_order_group(0)";
  13270. ep_args += "]]";
  13271. continue;
  13272. }
  13273. switch (r.basetype)
  13274. {
  13275. case SPIRType::Struct:
  13276. {
  13277. auto &m = ir.meta[type.self];
  13278. if (m.members.size() == 0)
  13279. break;
  13280. if (!type.array.empty())
  13281. {
  13282. if (type.array.size() > 1)
  13283. SPIRV_CROSS_THROW("Arrays of arrays of buffers are not supported.");
  13284. is_using_builtin_array = true;
  13285. uint32_t array_size = get_resource_array_size(type, var_id);
  13286. for (uint32_t i = 0; i < array_size; ++i)
  13287. {
  13288. if (!ep_args.empty())
  13289. ep_args += ", ";
  13290. ep_args += get_variable_address_space(var) + " " + type_to_glsl(type) + "* " +
  13291. to_restrict(var_id, true) + r.name + "_" + convert_to_string(i);
  13292. ep_args += " [[buffer(" + convert_to_string(r.index + i) + ")";
  13293. if (interlocked_resources.count(var_id))
  13294. ep_args += ", raster_order_group(0)";
  13295. ep_args += "]]";
  13296. }
  13297. is_using_builtin_array = false;
  13298. }
  13299. else
  13300. {
  13301. if (!ep_args.empty())
  13302. ep_args += ", ";
  13303. ep_args += get_variable_address_space(var) + " ";
  13304. if (recursive_inputs.count(type.self))
  13305. ep_args += string("void* ") + to_restrict(var_id, true) + r.name + "_vp";
  13306. else
  13307. ep_args += type_to_glsl(type) + "& " + to_restrict(var_id, true) + r.name;
  13308. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13309. if (interlocked_resources.count(var_id))
  13310. ep_args += ", raster_order_group(0)";
  13311. ep_args += "]]";
  13312. }
  13313. break;
  13314. }
  13315. case SPIRType::Sampler:
  13316. if (!ep_args.empty())
  13317. ep_args += ", ";
  13318. ep_args += sampler_type(type, var_id, false) + " " + r.name;
  13319. ep_args += " [[sampler(" + convert_to_string(r.index) + ")]]";
  13320. break;
  13321. case SPIRType::Image:
  13322. {
  13323. if (!ep_args.empty())
  13324. ep_args += ", ";
  13325. // Use Metal's native frame-buffer fetch API for subpass inputs.
  13326. const auto &basetype = get<SPIRType>(var.basetype);
  13327. if (!type_is_msl_framebuffer_fetch(basetype))
  13328. {
  13329. ep_args += image_type_glsl(type, var_id, false) + " " + r.name;
  13330. if (r.plane > 0)
  13331. ep_args += join(plane_name_suffix, r.plane);
  13332. ep_args += " [[texture(" + convert_to_string(r.index) + ")";
  13333. if (interlocked_resources.count(var_id))
  13334. ep_args += ", raster_order_group(0)";
  13335. ep_args += "]]";
  13336. }
  13337. else
  13338. {
  13339. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
  13340. SPIRV_CROSS_THROW("Framebuffer fetch on Mac is not supported before MSL 2.3.");
  13341. ep_args += image_type_glsl(type, var_id, false) + " " + r.name;
  13342. ep_args += " [[color(" + convert_to_string(r.index) + ")]]";
  13343. }
  13344. // Emulate texture2D atomic operations
  13345. if (atomic_image_vars_emulated.count(var.self))
  13346. {
  13347. auto &flags = ir.get_decoration_bitset(var.self);
  13348. const char *cv_flags = decoration_flags_signal_volatile(flags) ? "volatile " : "";
  13349. ep_args += join(", ", cv_flags, "device atomic_", type_to_glsl(get<SPIRType>(basetype.image.type), 0));
  13350. ep_args += "* " + r.name + "_atomic";
  13351. ep_args += " [[buffer(" + convert_to_string(r.secondary_index) + ")";
  13352. if (interlocked_resources.count(var_id))
  13353. ep_args += ", raster_order_group(0)";
  13354. ep_args += "]]";
  13355. }
  13356. break;
  13357. }
  13358. case SPIRType::AccelerationStructure:
  13359. {
  13360. if (!ep_args.empty())
  13361. ep_args += ", ";
  13362. ep_args += type_to_glsl(type, var_id) + " " + r.name;
  13363. ep_args += " [[buffer(" + convert_to_string(r.index) + ")]]";
  13364. break;
  13365. }
  13366. default:
  13367. if (!ep_args.empty())
  13368. ep_args += ", ";
  13369. if (!type.pointer)
  13370. ep_args += get_type_address_space(get<SPIRType>(var.basetype), var_id) + " " +
  13371. type_to_glsl(type, var_id) + "& " + r.name;
  13372. else
  13373. ep_args += type_to_glsl(type, var_id) + " " + r.name;
  13374. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13375. if (interlocked_resources.count(var_id))
  13376. ep_args += ", raster_order_group(0)";
  13377. ep_args += "]]";
  13378. break;
  13379. }
  13380. }
  13381. }
  13382. // Returns a string containing a comma-delimited list of args for the entry point function
  13383. // This is the "classic" method of MSL 1 when we don't have argument buffer support.
  13384. string CompilerMSL::entry_point_args_classic(bool append_comma)
  13385. {
  13386. string ep_args = entry_point_arg_stage_in();
  13387. entry_point_args_discrete_descriptors(ep_args);
  13388. entry_point_args_builtin(ep_args);
  13389. if (!ep_args.empty() && append_comma)
  13390. ep_args += ", ";
  13391. return ep_args;
  13392. }
  13393. void CompilerMSL::fix_up_shader_inputs_outputs()
  13394. {
  13395. auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
  13396. // Emit a guard to ensure we don't execute beyond the last vertex.
  13397. // Vertex shaders shouldn't have the problems with barriers in non-uniform control flow that
  13398. // tessellation control shaders do, so early returns should be OK. We may need to revisit this
  13399. // if it ever becomes possible to use barriers from a vertex shader.
  13400. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
  13401. {
  13402. entry_func.fixup_hooks_in.push_back([this]() {
  13403. statement("if (any(", to_expression(builtin_invocation_id_id),
  13404. " >= ", to_expression(builtin_stage_input_size_id), "))");
  13405. statement(" return;");
  13406. });
  13407. }
  13408. if (is_mesh_shader())
  13409. {
  13410. // If shader doesn't call SetMeshOutputsEXT, nothing should be rendered.
  13411. // No need to barrier after this, because only thread 0 writes to this later.
  13412. entry_func.fixup_hooks_in.push_back([this]() { statement("if (gl_LocalInvocationIndex == 0) spvMeshSizes.y = 0u;"); });
  13413. entry_func.fixup_hooks_out.push_back([this]() { emit_mesh_outputs(); });
  13414. }
  13415. // Look for sampled images and buffer. Add hooks to set up the swizzle constants or array lengths.
  13416. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  13417. auto &type = get_variable_data_type(var);
  13418. uint32_t var_id = var.self;
  13419. bool ssbo = has_decoration(type.self, DecorationBufferBlock);
  13420. if (var.storage == StorageClassUniformConstant && !is_hidden_variable(var))
  13421. {
  13422. if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type))
  13423. {
  13424. entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() {
  13425. bool is_array_type = !type.array.empty();
  13426. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13427. if (descriptor_set_is_argument_buffer(desc_set))
  13428. {
  13429. statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id),
  13430. is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]),
  13431. ".spvSwizzleConstants", "[",
  13432. convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
  13433. }
  13434. else
  13435. {
  13436. // If we have an array of images, we need to be able to index into it, so take a pointer instead.
  13437. statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id),
  13438. is_array_type ? " = &" : " = ", to_name(swizzle_buffer_id), "[",
  13439. convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
  13440. }
  13441. });
  13442. }
  13443. }
  13444. else if ((var.storage == StorageClassStorageBuffer || (var.storage == StorageClassUniform && ssbo)) &&
  13445. !is_hidden_variable(var))
  13446. {
  13447. if (buffer_requires_array_length(var.self))
  13448. {
  13449. entry_func.fixup_hooks_in.push_back(
  13450. [this, &type, &var, var_id]()
  13451. {
  13452. bool is_array_type = !type.array.empty() && !is_var_runtime_size_array(var);
  13453. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13454. if (descriptor_set_is_argument_buffer(desc_set))
  13455. {
  13456. statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id),
  13457. is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]),
  13458. ".spvBufferSizeConstants", "[",
  13459. convert_to_string(get_metal_resource_index(var, SPIRType::UInt)), "];");
  13460. }
  13461. else
  13462. {
  13463. // If we have an array of images, we need to be able to index into it, so take a pointer instead.
  13464. statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id),
  13465. is_array_type ? " = &" : " = ", to_name(buffer_size_buffer_id), "[",
  13466. convert_to_string(get_metal_resource_index(var, type.basetype)), "];");
  13467. }
  13468. });
  13469. }
  13470. }
  13471. if (!msl_options.argument_buffers &&
  13472. msl_options.replace_recursive_inputs && type_contains_recursion(type) &&
  13473. (var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  13474. var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer))
  13475. {
  13476. recursive_inputs.insert(type.self);
  13477. entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() {
  13478. auto addr_space = get_variable_address_space(var);
  13479. auto var_name = to_name(var_id);
  13480. statement(addr_space, " auto& ", to_restrict(var_id, true), var_name,
  13481. " = *(", addr_space, " ", type_to_glsl(type), "*)", var_name, "_vp;");
  13482. });
  13483. }
  13484. });
  13485. // Builtin variables
  13486. ir.for_each_typed_id<SPIRVariable>([this, &entry_func](uint32_t, SPIRVariable &var) {
  13487. uint32_t var_id = var.self;
  13488. BuiltIn bi_type = ir.meta[var_id].decoration.builtin_type;
  13489. if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
  13490. return;
  13491. if (!interface_variable_exists_in_entry_point(var.self))
  13492. return;
  13493. if (var.storage == StorageClassInput && is_builtin_variable(var) && active_input_builtins.get(bi_type))
  13494. {
  13495. switch (bi_type)
  13496. {
  13497. case BuiltInSamplePosition:
  13498. entry_func.fixup_hooks_in.push_back([=]() {
  13499. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = get_sample_position(",
  13500. to_expression(builtin_sample_id_id), ");");
  13501. });
  13502. break;
  13503. case BuiltInFragCoord:
  13504. if (is_sample_rate())
  13505. {
  13506. entry_func.fixup_hooks_in.push_back([=]() {
  13507. statement(to_expression(var_id), ".xy += get_sample_position(",
  13508. to_expression(builtin_sample_id_id), ") - 0.5;");
  13509. });
  13510. }
  13511. break;
  13512. case BuiltInInvocationId:
  13513. // This is direct-mapped without multi-patch workgroups.
  13514. if (!is_tesc_shader() || !msl_options.multi_patch_workgroup)
  13515. break;
  13516. entry_func.fixup_hooks_in.push_back([=]() {
  13517. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13518. to_expression(builtin_invocation_id_id), ".x % ", this->get_entry_point().output_vertices,
  13519. ";");
  13520. });
  13521. break;
  13522. case BuiltInPrimitiveId:
  13523. // This is natively supported by fragment and tessellation evaluation shaders.
  13524. // In tessellation control shaders, this is direct-mapped without multi-patch workgroups.
  13525. if (!is_tesc_shader() || !msl_options.multi_patch_workgroup)
  13526. break;
  13527. entry_func.fixup_hooks_in.push_back([=]() {
  13528. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = min(",
  13529. to_expression(builtin_invocation_id_id), ".x / ", this->get_entry_point().output_vertices,
  13530. ", spvIndirectParams[1] - 1);");
  13531. });
  13532. break;
  13533. case BuiltInPatchVertices:
  13534. if (is_tese_shader())
  13535. {
  13536. if (msl_options.raw_buffer_tese_input)
  13537. {
  13538. entry_func.fixup_hooks_in.push_back(
  13539. [=]() {
  13540. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13541. get_entry_point().output_vertices, ";");
  13542. });
  13543. }
  13544. else
  13545. {
  13546. entry_func.fixup_hooks_in.push_back(
  13547. [=]()
  13548. {
  13549. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13550. to_expression(patch_stage_in_var_id), ".gl_in.size();");
  13551. });
  13552. }
  13553. }
  13554. else
  13555. {
  13556. entry_func.fixup_hooks_in.push_back([=]() {
  13557. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = spvIndirectParams[0];");
  13558. });
  13559. }
  13560. break;
  13561. case BuiltInTessCoord:
  13562. if (get_entry_point().flags.get(ExecutionModeQuads))
  13563. {
  13564. // The entry point will only have a float2 TessCoord variable.
  13565. // Pad to float3.
  13566. entry_func.fixup_hooks_in.push_back([=]() {
  13567. auto name = builtin_to_glsl(BuiltInTessCoord, StorageClassInput);
  13568. statement("float3 " + name + " = float3(" + name + "In.x, " + name + "In.y, 0.0);");
  13569. });
  13570. }
  13571. // Emit a fixup to account for the shifted domain. Don't do this for triangles;
  13572. // MoltenVK will just reverse the winding order instead.
  13573. if (msl_options.tess_domain_origin_lower_left && !is_tessellating_triangles())
  13574. {
  13575. string tc = to_expression(var_id);
  13576. entry_func.fixup_hooks_in.push_back([=]() { statement(tc, ".y = 1.0 - ", tc, ".y;"); });
  13577. }
  13578. break;
  13579. case BuiltInSubgroupId:
  13580. if (!msl_options.emulate_subgroups)
  13581. break;
  13582. // For subgroup emulation, this is the same as the local invocation index.
  13583. entry_func.fixup_hooks_in.push_back([=]() {
  13584. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13585. to_expression(builtin_local_invocation_index_id), ";");
  13586. });
  13587. break;
  13588. case BuiltInNumSubgroups:
  13589. if (!msl_options.emulate_subgroups)
  13590. break;
  13591. // For subgroup emulation, this is the same as the workgroup size.
  13592. entry_func.fixup_hooks_in.push_back([=]() {
  13593. auto &type = expression_type(builtin_workgroup_size_id);
  13594. string size_expr = to_expression(builtin_workgroup_size_id);
  13595. if (type.vecsize >= 3)
  13596. size_expr = join(size_expr, ".x * ", size_expr, ".y * ", size_expr, ".z");
  13597. else if (type.vecsize == 2)
  13598. size_expr = join(size_expr, ".x * ", size_expr, ".y");
  13599. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", size_expr, ";");
  13600. });
  13601. break;
  13602. case BuiltInSubgroupLocalInvocationId:
  13603. if (!msl_options.emulate_subgroups)
  13604. break;
  13605. // For subgroup emulation, assume subgroups of size 1.
  13606. entry_func.fixup_hooks_in.push_back(
  13607. [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;"); });
  13608. break;
  13609. case BuiltInSubgroupSize:
  13610. if (msl_options.emulate_subgroups)
  13611. {
  13612. // For subgroup emulation, assume subgroups of size 1.
  13613. entry_func.fixup_hooks_in.push_back(
  13614. [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 1;"); });
  13615. }
  13616. else if (msl_options.fixed_subgroup_size != 0)
  13617. {
  13618. entry_func.fixup_hooks_in.push_back([=]() {
  13619. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13620. msl_options.fixed_subgroup_size, ";");
  13621. });
  13622. }
  13623. break;
  13624. case BuiltInSubgroupEqMask:
  13625. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13626. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13627. if (!msl_options.supports_msl_version(2, 1))
  13628. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13629. entry_func.fixup_hooks_in.push_back([=]() {
  13630. if (msl_options.is_ios())
  13631. {
  13632. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", "uint4(1 << ",
  13633. to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));");
  13634. }
  13635. else
  13636. {
  13637. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13638. to_expression(builtin_subgroup_invocation_id_id), " >= 32 ? uint4(0, (1 << (",
  13639. to_expression(builtin_subgroup_invocation_id_id), " - 32)), uint2(0)) : uint4(1 << ",
  13640. to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));");
  13641. }
  13642. });
  13643. break;
  13644. case BuiltInSubgroupGeMask:
  13645. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13646. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13647. if (!msl_options.supports_msl_version(2, 1))
  13648. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13649. if (msl_options.fixed_subgroup_size != 0)
  13650. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13651. entry_func.fixup_hooks_in.push_back([=]() {
  13652. // Case where index < 32, size < 32:
  13653. // mask0 = bfi(0, 0xFFFFFFFF, index, size - index);
  13654. // mask1 = bfi(0, 0xFFFFFFFF, 0, 0); // Gives 0
  13655. // Case where index < 32 but size >= 32:
  13656. // mask0 = bfi(0, 0xFFFFFFFF, index, 32 - index);
  13657. // mask1 = bfi(0, 0xFFFFFFFF, 0, size - 32);
  13658. // Case where index >= 32:
  13659. // mask0 = bfi(0, 0xFFFFFFFF, 32, 0); // Gives 0
  13660. // mask1 = bfi(0, 0xFFFFFFFF, index - 32, size - index);
  13661. // This is expressed without branches to avoid divergent
  13662. // control flow--hence the complicated min/max expressions.
  13663. // This is further complicated by the fact that if you attempt
  13664. // to bfi/bfe out-of-bounds on Metal, undefined behavior is the
  13665. // result.
  13666. if (msl_options.fixed_subgroup_size > 32)
  13667. {
  13668. // Don't use the subgroup size variable with fixed subgroup sizes,
  13669. // since the variables could be defined in the wrong order.
  13670. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13671. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13672. to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(32 - (int)",
  13673. to_expression(builtin_subgroup_invocation_id_id),
  13674. ", 0)), insert_bits(0u, 0xFFFFFFFF,"
  13675. " (uint)max((int)",
  13676. to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), ",
  13677. msl_options.fixed_subgroup_size, " - max(",
  13678. to_expression(builtin_subgroup_invocation_id_id),
  13679. ", 32u)), uint2(0));");
  13680. }
  13681. else if (msl_options.fixed_subgroup_size != 0)
  13682. {
  13683. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13684. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13685. to_expression(builtin_subgroup_invocation_id_id), ", ",
  13686. msl_options.fixed_subgroup_size, " - ",
  13687. to_expression(builtin_subgroup_invocation_id_id),
  13688. "), uint3(0));");
  13689. }
  13690. else if (msl_options.is_ios())
  13691. {
  13692. // On iOS, the SIMD-group size will currently never exceed 32.
  13693. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13694. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13695. to_expression(builtin_subgroup_invocation_id_id), ", ",
  13696. to_expression(builtin_subgroup_size_id), " - ",
  13697. to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));");
  13698. }
  13699. else
  13700. {
  13701. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13702. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13703. to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(min((int)",
  13704. to_expression(builtin_subgroup_size_id), ", 32) - (int)",
  13705. to_expression(builtin_subgroup_invocation_id_id),
  13706. ", 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
  13707. to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), (uint)max((int)",
  13708. to_expression(builtin_subgroup_size_id), " - (int)max(",
  13709. to_expression(builtin_subgroup_invocation_id_id), ", 32u), 0)), uint2(0));");
  13710. }
  13711. });
  13712. break;
  13713. case BuiltInSubgroupGtMask:
  13714. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13715. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13716. if (!msl_options.supports_msl_version(2, 1))
  13717. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13718. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13719. entry_func.fixup_hooks_in.push_back([=]() {
  13720. // The same logic applies here, except now the index is one
  13721. // more than the subgroup invocation ID.
  13722. if (msl_options.fixed_subgroup_size > 32)
  13723. {
  13724. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13725. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13726. to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(32 - (int)",
  13727. to_expression(builtin_subgroup_invocation_id_id),
  13728. " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
  13729. to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), ",
  13730. msl_options.fixed_subgroup_size, " - max(",
  13731. to_expression(builtin_subgroup_invocation_id_id),
  13732. " + 1, 32u)), uint2(0));");
  13733. }
  13734. else if (msl_options.fixed_subgroup_size != 0)
  13735. {
  13736. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13737. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13738. to_expression(builtin_subgroup_invocation_id_id), " + 1, ",
  13739. msl_options.fixed_subgroup_size, " - ",
  13740. to_expression(builtin_subgroup_invocation_id_id),
  13741. " - 1), uint3(0));");
  13742. }
  13743. else if (msl_options.is_ios())
  13744. {
  13745. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13746. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13747. to_expression(builtin_subgroup_invocation_id_id), " + 1, ",
  13748. to_expression(builtin_subgroup_size_id), " - ",
  13749. to_expression(builtin_subgroup_invocation_id_id), " - 1), uint3(0));");
  13750. }
  13751. else
  13752. {
  13753. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13754. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13755. to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(min((int)",
  13756. to_expression(builtin_subgroup_size_id), ", 32) - (int)",
  13757. to_expression(builtin_subgroup_invocation_id_id),
  13758. " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
  13759. to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), (uint)max((int)",
  13760. to_expression(builtin_subgroup_size_id), " - (int)max(",
  13761. to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), 0)), uint2(0));");
  13762. }
  13763. });
  13764. break;
  13765. case BuiltInSubgroupLeMask:
  13766. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13767. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13768. if (!msl_options.supports_msl_version(2, 1))
  13769. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13770. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13771. entry_func.fixup_hooks_in.push_back([=]() {
  13772. if (msl_options.is_ios())
  13773. {
  13774. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13775. " = uint4(extract_bits(0xFFFFFFFF, 0, ",
  13776. to_expression(builtin_subgroup_invocation_id_id), " + 1), uint3(0));");
  13777. }
  13778. else
  13779. {
  13780. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13781. " = uint4(extract_bits(0xFFFFFFFF, 0, min(",
  13782. to_expression(builtin_subgroup_invocation_id_id),
  13783. " + 1, 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)",
  13784. to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0)), uint2(0));");
  13785. }
  13786. });
  13787. break;
  13788. case BuiltInSubgroupLtMask:
  13789. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13790. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13791. if (!msl_options.supports_msl_version(2, 1))
  13792. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13793. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13794. entry_func.fixup_hooks_in.push_back([=]() {
  13795. if (msl_options.is_ios())
  13796. {
  13797. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13798. " = uint4(extract_bits(0xFFFFFFFF, 0, ",
  13799. to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));");
  13800. }
  13801. else
  13802. {
  13803. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13804. " = uint4(extract_bits(0xFFFFFFFF, 0, min(",
  13805. to_expression(builtin_subgroup_invocation_id_id),
  13806. ", 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)",
  13807. to_expression(builtin_subgroup_invocation_id_id), " - 32, 0)), uint2(0));");
  13808. }
  13809. });
  13810. break;
  13811. case BuiltInViewIndex:
  13812. if (!msl_options.multiview)
  13813. {
  13814. // According to the Vulkan spec, when not running under a multiview
  13815. // render pass, ViewIndex is 0.
  13816. entry_func.fixup_hooks_in.push_back([=]() {
  13817. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;");
  13818. });
  13819. }
  13820. else if (msl_options.view_index_from_device_index)
  13821. {
  13822. // In this case, we take the view index from that of the device we're running on.
  13823. entry_func.fixup_hooks_in.push_back([=]() {
  13824. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13825. msl_options.device_index, ";");
  13826. });
  13827. // We actually don't want to set the render_target_array_index here.
  13828. // Since every physical device is rendering a different view,
  13829. // there's no need for layered rendering here.
  13830. }
  13831. else if (!msl_options.multiview_layered_rendering)
  13832. {
  13833. // In this case, the views are rendered one at a time. The view index, then,
  13834. // is just the first part of the "view mask".
  13835. entry_func.fixup_hooks_in.push_back([=]() {
  13836. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13837. to_expression(view_mask_buffer_id), "[0];");
  13838. });
  13839. }
  13840. else if (get_execution_model() == ExecutionModelFragment)
  13841. {
  13842. // Because we adjusted the view index in the vertex shader, we have to
  13843. // adjust it back here.
  13844. entry_func.fixup_hooks_in.push_back([=]() {
  13845. statement(to_expression(var_id), " += ", to_expression(view_mask_buffer_id), "[0];");
  13846. });
  13847. }
  13848. else if (get_execution_model() == ExecutionModelVertex)
  13849. {
  13850. // Metal provides no special support for multiview, so we smuggle
  13851. // the view index in the instance index.
  13852. entry_func.fixup_hooks_in.push_back([=]() {
  13853. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13854. to_expression(view_mask_buffer_id), "[0] + (", to_expression(builtin_instance_idx_id),
  13855. " - ", to_expression(builtin_base_instance_id), ") % ",
  13856. to_expression(view_mask_buffer_id), "[1];");
  13857. statement(to_expression(builtin_instance_idx_id), " = (",
  13858. to_expression(builtin_instance_idx_id), " - ",
  13859. to_expression(builtin_base_instance_id), ") / ", to_expression(view_mask_buffer_id),
  13860. "[1] + ", to_expression(builtin_base_instance_id), ";");
  13861. });
  13862. // In addition to setting the variable itself, we also need to
  13863. // set the render_target_array_index with it on output. We have to
  13864. // offset this by the base view index, because Metal isn't in on
  13865. // our little game here.
  13866. entry_func.fixup_hooks_out.push_back([=]() {
  13867. statement(to_expression(builtin_layer_id), " = ", to_expression(var_id), " - ",
  13868. to_expression(view_mask_buffer_id), "[0];");
  13869. });
  13870. }
  13871. break;
  13872. case BuiltInDeviceIndex:
  13873. // Metal pipelines belong to the devices which create them, so we'll
  13874. // need to create a MTLPipelineState for every MTLDevice in a grouped
  13875. // VkDevice. We can assume, then, that the device index is constant.
  13876. entry_func.fixup_hooks_in.push_back([=]() {
  13877. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13878. msl_options.device_index, ";");
  13879. });
  13880. break;
  13881. case BuiltInWorkgroupId:
  13882. if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInWorkgroupId))
  13883. break;
  13884. // The vkCmdDispatchBase() command lets the client set the base value
  13885. // of WorkgroupId. Metal has no direct equivalent; we must make this
  13886. // adjustment ourselves.
  13887. entry_func.fixup_hooks_in.push_back([=]() {
  13888. statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id), ";");
  13889. });
  13890. break;
  13891. case BuiltInGlobalInvocationId:
  13892. if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInGlobalInvocationId))
  13893. break;
  13894. // GlobalInvocationId is defined as LocalInvocationId + WorkgroupId * WorkgroupSize.
  13895. // This needs to be adjusted too.
  13896. entry_func.fixup_hooks_in.push_back([=]() {
  13897. auto &execution = this->get_entry_point();
  13898. uint32_t workgroup_size_id = execution.workgroup_size.constant;
  13899. if (workgroup_size_id)
  13900. statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id),
  13901. " * ", to_expression(workgroup_size_id), ";");
  13902. else
  13903. statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id),
  13904. " * uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ",
  13905. execution.workgroup_size.z, ");");
  13906. });
  13907. break;
  13908. case BuiltInVertexId:
  13909. case BuiltInVertexIndex:
  13910. // This is direct-mapped normally.
  13911. if (!msl_options.vertex_for_tessellation)
  13912. break;
  13913. entry_func.fixup_hooks_in.push_back([=]() {
  13914. builtin_declaration = true;
  13915. switch (msl_options.vertex_index_type)
  13916. {
  13917. case Options::IndexType::None:
  13918. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13919. to_expression(builtin_invocation_id_id), ".x + ",
  13920. to_expression(builtin_dispatch_base_id), ".x;");
  13921. break;
  13922. case Options::IndexType::UInt16:
  13923. case Options::IndexType::UInt32:
  13924. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", index_buffer_var_name,
  13925. "[", to_expression(builtin_invocation_id_id), ".x] + ",
  13926. to_expression(builtin_dispatch_base_id), ".x;");
  13927. break;
  13928. }
  13929. builtin_declaration = false;
  13930. });
  13931. break;
  13932. case BuiltInBaseVertex:
  13933. // This is direct-mapped normally.
  13934. if (!msl_options.vertex_for_tessellation)
  13935. break;
  13936. entry_func.fixup_hooks_in.push_back([=]() {
  13937. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13938. to_expression(builtin_dispatch_base_id), ".x;");
  13939. });
  13940. break;
  13941. case BuiltInInstanceId:
  13942. case BuiltInInstanceIndex:
  13943. // This is direct-mapped normally.
  13944. if (!msl_options.vertex_for_tessellation)
  13945. break;
  13946. entry_func.fixup_hooks_in.push_back([=]() {
  13947. builtin_declaration = true;
  13948. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13949. to_expression(builtin_invocation_id_id), ".y + ", to_expression(builtin_dispatch_base_id),
  13950. ".y;");
  13951. builtin_declaration = false;
  13952. });
  13953. break;
  13954. case BuiltInBaseInstance:
  13955. // This is direct-mapped normally.
  13956. if (!msl_options.vertex_for_tessellation)
  13957. break;
  13958. entry_func.fixup_hooks_in.push_back([=]() {
  13959. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13960. to_expression(builtin_dispatch_base_id), ".y;");
  13961. });
  13962. break;
  13963. default:
  13964. break;
  13965. }
  13966. }
  13967. else if (var.storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment &&
  13968. is_builtin_variable(var) && active_output_builtins.get(bi_type))
  13969. {
  13970. switch (bi_type)
  13971. {
  13972. case BuiltInSampleMask:
  13973. if (has_additional_fixed_sample_mask())
  13974. {
  13975. // If the additional fixed sample mask was set, we need to adjust the sample_mask
  13976. // output to reflect that. If the shader outputs the sample_mask itself too, we need
  13977. // to AND the two masks to get the final one.
  13978. string op_str = does_shader_write_sample_mask ? " &= " : " = ";
  13979. entry_func.fixup_hooks_out.push_back([=]() {
  13980. statement(to_expression(builtin_sample_mask_id), op_str, additional_fixed_sample_mask_str(), ";");
  13981. });
  13982. }
  13983. break;
  13984. case BuiltInFragDepth:
  13985. if (msl_options.input_attachment_is_ds_attachment && !writes_to_depth)
  13986. {
  13987. entry_func.fixup_hooks_out.push_back([=]() {
  13988. statement(to_expression(builtin_frag_depth_id), " = ", to_expression(builtin_frag_coord_id), ".z;");
  13989. });
  13990. }
  13991. break;
  13992. default:
  13993. break;
  13994. }
  13995. }
  13996. });
  13997. }
  13998. // Returns the Metal index of the resource of the specified type as used by the specified variable.
  13999. uint32_t CompilerMSL::get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype, uint32_t plane)
  14000. {
  14001. auto &execution = get_entry_point();
  14002. auto &var_dec = ir.meta[var.self].decoration;
  14003. auto &var_type = get<SPIRType>(var.basetype);
  14004. uint32_t var_desc_set = (var.storage == StorageClassPushConstant) ? kPushConstDescSet : var_dec.set;
  14005. uint32_t var_binding = (var.storage == StorageClassPushConstant) ? kPushConstBinding : var_dec.binding;
  14006. // If a matching binding has been specified, find and use it.
  14007. auto itr = resource_bindings.find({ execution.model, var_desc_set, var_binding });
  14008. // Atomic helper buffers for image atomics need to use secondary bindings as well.
  14009. bool use_secondary_binding = (var_type.basetype == SPIRType::SampledImage && basetype == SPIRType::Sampler) ||
  14010. basetype == SPIRType::AtomicCounter;
  14011. auto resource_decoration =
  14012. use_secondary_binding ? SPIRVCrossDecorationResourceIndexSecondary : SPIRVCrossDecorationResourceIndexPrimary;
  14013. if (plane == 1)
  14014. resource_decoration = SPIRVCrossDecorationResourceIndexTertiary;
  14015. if (plane == 2)
  14016. resource_decoration = SPIRVCrossDecorationResourceIndexQuaternary;
  14017. if (itr != end(resource_bindings))
  14018. {
  14019. auto &remap = itr->second;
  14020. remap.second = true;
  14021. switch (basetype)
  14022. {
  14023. case SPIRType::Image:
  14024. set_extended_decoration(var.self, resource_decoration, remap.first.msl_texture + plane);
  14025. return remap.first.msl_texture + plane;
  14026. case SPIRType::Sampler:
  14027. set_extended_decoration(var.self, resource_decoration, remap.first.msl_sampler);
  14028. return remap.first.msl_sampler;
  14029. default:
  14030. set_extended_decoration(var.self, resource_decoration, remap.first.msl_buffer);
  14031. return remap.first.msl_buffer;
  14032. }
  14033. }
  14034. // If we have already allocated an index, keep using it.
  14035. if (has_extended_decoration(var.self, resource_decoration))
  14036. return get_extended_decoration(var.self, resource_decoration);
  14037. auto &type = get<SPIRType>(var.basetype);
  14038. if (type_is_msl_framebuffer_fetch(type))
  14039. {
  14040. // Frame-buffer fetch gets its fallback resource index from the input attachment index,
  14041. // which is then treated as color index.
  14042. return get_decoration(var.self, DecorationInputAttachmentIndex);
  14043. }
  14044. else if (msl_options.enable_decoration_binding)
  14045. {
  14046. // Allow user to enable decoration binding.
  14047. // If there is no explicit mapping of bindings to MSL, use the declared binding as a fallback.
  14048. if (has_decoration(var.self, DecorationBinding))
  14049. {
  14050. var_binding = get_decoration(var.self, DecorationBinding);
  14051. // Avoid emitting sentinel bindings.
  14052. if (var_binding < 0x80000000u)
  14053. return var_binding;
  14054. }
  14055. }
  14056. // If we did not explicitly remap, allocate bindings on demand.
  14057. // We cannot reliably use Binding decorations since SPIR-V and MSL's binding models are very different.
  14058. bool allocate_argument_buffer_ids = false;
  14059. if (var.storage != StorageClassPushConstant)
  14060. allocate_argument_buffer_ids = descriptor_set_is_argument_buffer(var_desc_set);
  14061. uint32_t binding_stride = 1;
  14062. for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
  14063. binding_stride *= to_array_size_literal(type, i);
  14064. // If a binding has not been specified, revert to incrementing resource indices.
  14065. uint32_t resource_index;
  14066. if (allocate_argument_buffer_ids)
  14067. {
  14068. // Allocate from a flat ID binding space.
  14069. resource_index = next_metal_resource_ids[var_desc_set];
  14070. next_metal_resource_ids[var_desc_set] += binding_stride;
  14071. }
  14072. else
  14073. {
  14074. if (is_var_runtime_size_array(var))
  14075. {
  14076. basetype = SPIRType::Struct;
  14077. binding_stride = 1;
  14078. }
  14079. // Allocate from plain bindings which are allocated per resource type.
  14080. switch (basetype)
  14081. {
  14082. case SPIRType::Image:
  14083. resource_index = next_metal_resource_index_texture;
  14084. next_metal_resource_index_texture += binding_stride;
  14085. break;
  14086. case SPIRType::Sampler:
  14087. resource_index = next_metal_resource_index_sampler;
  14088. next_metal_resource_index_sampler += binding_stride;
  14089. break;
  14090. default:
  14091. resource_index = next_metal_resource_index_buffer;
  14092. next_metal_resource_index_buffer += binding_stride;
  14093. break;
  14094. }
  14095. }
  14096. set_extended_decoration(var.self, resource_decoration, resource_index);
  14097. return resource_index;
  14098. }
  14099. bool CompilerMSL::type_is_msl_framebuffer_fetch(const SPIRType &type) const
  14100. {
  14101. return type.basetype == SPIRType::Image && type.image.dim == DimSubpassData &&
  14102. msl_options.use_framebuffer_fetch_subpasses;
  14103. }
  14104. const char *CompilerMSL::descriptor_address_space(uint32_t id, StorageClass storage, const char *plain_address_space) const
  14105. {
  14106. if (msl_options.argument_buffers)
  14107. {
  14108. bool storage_class_is_descriptor = storage == StorageClassUniform ||
  14109. storage == StorageClassStorageBuffer ||
  14110. storage == StorageClassUniformConstant;
  14111. uint32_t desc_set = get_decoration(id, DecorationDescriptorSet);
  14112. if (storage_class_is_descriptor && descriptor_set_is_argument_buffer(desc_set))
  14113. {
  14114. // An awkward case where we need to emit *more* address space declarations (yay!).
  14115. // An example is where we pass down an array of buffer pointers to leaf functions.
  14116. // It's a constant array containing pointers to constants.
  14117. // The pointer array is always constant however. E.g.
  14118. // device SSBO * constant (&array)[N].
  14119. // const device SSBO * constant (&array)[N].
  14120. // constant SSBO * constant (&array)[N].
  14121. // However, this only matters for argument buffers, since for MSL 1.0 style codegen,
  14122. // we emit the buffer array on stack instead, and that seems to work just fine apparently.
  14123. // If the argument was marked as being in device address space, any pointer to member would
  14124. // be const device, not constant.
  14125. if (argument_buffer_device_storage_mask & (1u << desc_set))
  14126. return "const device";
  14127. else
  14128. return "constant";
  14129. }
  14130. }
  14131. return plain_address_space;
  14132. }
  14133. string CompilerMSL::argument_decl(const SPIRFunction::Parameter &arg)
  14134. {
  14135. auto &var = get<SPIRVariable>(arg.id);
  14136. auto &var_type = get<SPIRType>(arg.type);
  14137. StorageClass type_storage = var_type.storage;
  14138. // Physical pointer types are passed by pointer, not reference.
  14139. auto &data_type = get_variable_data_type(var);
  14140. bool passed_by_value = arg.alias_global_variable ? false : is_physical_or_buffer_pointer(var_type);
  14141. auto &type = passed_by_value ? var_type : data_type;
  14142. // If we need to modify the name of the variable, make sure we use the original variable.
  14143. // Our alias is just a shadow variable.
  14144. uint32_t name_id = var.self;
  14145. if (arg.alias_global_variable && var.basevariable)
  14146. name_id = var.basevariable;
  14147. bool constref = !arg.alias_global_variable && !passed_by_value && is_pointer(var_type) && arg.write_count == 0;
  14148. // Framebuffer fetch is plain value, const looks out of place, but it is not wrong.
  14149. // readonly coming from glslang is not reliable in all cases.
  14150. // For UBOs, readonly is implied, and for SSBOs we use global check.
  14151. if (type_is_msl_framebuffer_fetch(type) ||
  14152. type_storage == StorageClassStorageBuffer ||
  14153. type_storage == StorageClassUniform ||
  14154. type_storage == StorageClassPhysicalStorageBuffer)
  14155. {
  14156. constref = false;
  14157. }
  14158. else if (type_storage == StorageClassUniformConstant)
  14159. {
  14160. constref = true;
  14161. }
  14162. bool type_is_image = type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage ||
  14163. type.basetype == SPIRType::Sampler;
  14164. bool type_is_tlas = type.basetype == SPIRType::AccelerationStructure;
  14165. // For opaque types we handle const later due to descriptor address spaces.
  14166. const char *cv_qualifier = (constref && !type_is_image) ? "const " : "";
  14167. string decl;
  14168. // If this is a combined image-sampler for a 2D image with floating-point type,
  14169. // we emitted the 'spvDynamicImageSampler' type, and this is *not* an alias parameter
  14170. // for a global, then we need to emit a "dynamic" combined image-sampler.
  14171. // Unfortunately, this is necessary to properly support passing around
  14172. // combined image-samplers with Y'CbCr conversions on them.
  14173. bool is_dynamic_img_sampler = !arg.alias_global_variable && type.basetype == SPIRType::SampledImage &&
  14174. type.image.dim == Dim2D && type_is_floating_point(get<SPIRType>(type.image.type)) &&
  14175. spv_function_implementations.count(SPVFuncImplDynamicImageSampler);
  14176. // Allow Metal to use the array<T> template to make arrays a value type
  14177. string address_space = arg.alias_global_variable ? get_variable_address_space(var) : get_leaf_argument_address_space(var);
  14178. bool builtin = has_decoration(var.self, DecorationBuiltIn);
  14179. auto builtin_type = BuiltIn(get_decoration(arg.id, DecorationBuiltIn));
  14180. if (var.basevariable && (var.basevariable == stage_in_ptr_var_id || var.basevariable == stage_out_ptr_var_id))
  14181. decl = join(cv_qualifier, type_to_glsl(type, arg.id));
  14182. else if (builtin && !is_mesh_shader())
  14183. {
  14184. // Only use templated array for Clip/Cull distance when feasible.
  14185. // In other scenarios, we need need to override array length for tess levels (if used as outputs),
  14186. // or we need to emit the expected type for builtins (uint vs int).
  14187. auto storage = get<SPIRType>(var.basetype).storage;
  14188. if (storage == StorageClassInput &&
  14189. (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter))
  14190. {
  14191. is_using_builtin_array = false;
  14192. }
  14193. else if (builtin_type != BuiltInClipDistance && builtin_type != BuiltInCullDistance)
  14194. {
  14195. is_using_builtin_array = true;
  14196. }
  14197. if (storage == StorageClassOutput && variable_storage_requires_stage_io(storage) &&
  14198. !is_stage_output_builtin_masked(builtin_type))
  14199. is_using_builtin_array = true;
  14200. if (is_using_builtin_array)
  14201. decl = join(cv_qualifier, builtin_type_decl(builtin_type, arg.id));
  14202. else
  14203. decl = join(cv_qualifier, type_to_glsl(type, arg.id));
  14204. }
  14205. else if (is_var_runtime_size_array(var))
  14206. {
  14207. const auto *parent_type = &get<SPIRType>(type.parent_type);
  14208. auto type_name = type_to_glsl(*parent_type, arg.id);
  14209. if (type.basetype == SPIRType::AccelerationStructure)
  14210. decl = join("spvDescriptorArray<", type_name, ">");
  14211. else if (type_is_image)
  14212. decl = join("spvDescriptorArray<", cv_qualifier, type_name, ">");
  14213. else
  14214. decl = join("spvDescriptorArray<", address_space, " ", type_name, "*>");
  14215. address_space = "const";
  14216. }
  14217. else if ((type_storage == StorageClassUniform || type_storage == StorageClassStorageBuffer) && is_array(type))
  14218. {
  14219. is_using_builtin_array = true;
  14220. decl += join(cv_qualifier, type_to_glsl(type, arg.id), "*");
  14221. }
  14222. else if (is_dynamic_img_sampler)
  14223. {
  14224. decl = join(cv_qualifier, "spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">");
  14225. // Mark the variable so that we can handle passing it to another function.
  14226. set_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
  14227. }
  14228. else
  14229. {
  14230. // The type is a pointer type we need to emit cv_qualifier late.
  14231. if (is_pointer(data_type))
  14232. {
  14233. decl = type_to_glsl(type, arg.id);
  14234. if (*cv_qualifier != '\0')
  14235. decl += join(" ", cv_qualifier);
  14236. }
  14237. else
  14238. {
  14239. decl = join(cv_qualifier, type_to_glsl(type, arg.id));
  14240. }
  14241. }
  14242. if (passed_by_value || (!builtin && !is_pointer(var_type) &&
  14243. (type_storage == StorageClassFunction || type_storage == StorageClassGeneric)))
  14244. {
  14245. // If the argument is a pure value and not an opaque type, we will pass by value.
  14246. if (msl_options.force_native_arrays && is_array(type))
  14247. {
  14248. // We are receiving an array by value. This is problematic.
  14249. // We cannot be sure of the target address space since we are supposed to receive a copy,
  14250. // but this is not possible with MSL without some extra work.
  14251. // We will have to assume we're getting a reference in thread address space.
  14252. // If we happen to get a reference in constant address space, the caller must emit a copy and pass that.
  14253. // Thread const therefore becomes the only logical choice, since we cannot "create" a constant array from
  14254. // non-constant arrays, but we can create thread const from constant.
  14255. decl = string("thread const ") + decl;
  14256. decl += " (&";
  14257. const char *restrict_kw = to_restrict(name_id, true);
  14258. if (*restrict_kw)
  14259. {
  14260. decl += " ";
  14261. decl += restrict_kw;
  14262. }
  14263. decl += to_expression(name_id);
  14264. decl += ")";
  14265. decl += type_to_array_glsl(type, name_id);
  14266. }
  14267. else
  14268. {
  14269. // Variable pointer to array is kinda awkward ...
  14270. bool pointer_to_logical_buffer_array =
  14271. !is_physical_pointer(type) && is_pointer(type) &&
  14272. has_decoration(type.parent_type, DecorationArrayStride);
  14273. if (pointer_to_logical_buffer_array)
  14274. {
  14275. decl.pop_back();
  14276. decl += " (*";
  14277. decl += to_expression(name_id);
  14278. decl += ")";
  14279. bool old_is_using_builtin_array = is_using_builtin_array;
  14280. is_using_builtin_array = true;
  14281. decl += type_to_array_glsl(type, name_id);
  14282. is_using_builtin_array = old_is_using_builtin_array;
  14283. }
  14284. else
  14285. {
  14286. if (!address_space.empty())
  14287. decl = join(address_space, " ", decl);
  14288. decl += " ";
  14289. decl += to_expression(name_id);
  14290. }
  14291. }
  14292. }
  14293. else if (is_array(type) && !type_is_image)
  14294. {
  14295. // Arrays of opaque types are special cased.
  14296. if (!address_space.empty())
  14297. decl = join(address_space, " ", decl);
  14298. // spvDescriptorArray absorbs the address space inside the template.
  14299. if (!is_var_runtime_size_array(var))
  14300. {
  14301. const char *argument_buffer_space = descriptor_address_space(name_id, type_storage, nullptr);
  14302. if (argument_buffer_space)
  14303. {
  14304. decl += " ";
  14305. decl += argument_buffer_space;
  14306. }
  14307. }
  14308. // Special case, need to override the array size here if we're using tess level as an argument.
  14309. if (is_tesc_shader() && builtin &&
  14310. (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter))
  14311. {
  14312. uint32_t array_size = get_physical_tess_level_array_size(builtin_type);
  14313. if (array_size == 1)
  14314. {
  14315. decl += " &";
  14316. decl += to_expression(name_id);
  14317. }
  14318. else
  14319. {
  14320. decl += " (&";
  14321. decl += to_expression(name_id);
  14322. decl += ")";
  14323. decl += join("[", array_size, "]");
  14324. }
  14325. }
  14326. else if (is_var_runtime_size_array(var))
  14327. {
  14328. decl += " " + to_expression(name_id);
  14329. }
  14330. else
  14331. {
  14332. auto array_size_decl = type_to_array_glsl(type, name_id);
  14333. if (array_size_decl.empty())
  14334. decl += "& ";
  14335. else
  14336. decl += " (&";
  14337. const char *restrict_kw = to_restrict(name_id, true);
  14338. if (*restrict_kw)
  14339. {
  14340. decl += " ";
  14341. decl += restrict_kw;
  14342. }
  14343. decl += to_expression(name_id);
  14344. if (!array_size_decl.empty())
  14345. {
  14346. decl += ")";
  14347. decl += array_size_decl;
  14348. }
  14349. }
  14350. }
  14351. else if (!type_is_image && !type_is_tlas &&
  14352. (!pull_model_inputs.count(var.basevariable) || type.basetype == SPIRType::Struct))
  14353. {
  14354. // If this is going to be a reference to a variable pointer, the address space
  14355. // for the reference has to go before the '&', but after the '*'.
  14356. if (!address_space.empty())
  14357. {
  14358. if (is_pointer(data_type))
  14359. {
  14360. if (*cv_qualifier == '\0')
  14361. decl += ' ';
  14362. decl += join(address_space, " ");
  14363. }
  14364. else
  14365. decl = join(address_space, " ", decl);
  14366. }
  14367. decl += "&";
  14368. decl += " ";
  14369. decl += to_restrict(name_id, true);
  14370. decl += to_expression(name_id);
  14371. }
  14372. else if (type_is_image || type_is_tlas)
  14373. {
  14374. if (is_var_runtime_size_array(var))
  14375. {
  14376. decl = address_space + " " + decl + " " + to_expression(name_id);
  14377. }
  14378. else if (type.array.empty())
  14379. {
  14380. // For non-arrayed types we can just pass opaque descriptors by value.
  14381. // This fixes problems if descriptors are passed by value from argument buffers and plain descriptors
  14382. // in same shader.
  14383. // There is no address space we can actually use, but value will work.
  14384. // This will break if applications attempt to pass down descriptor arrays as arguments, but
  14385. // fortunately that is extremely unlikely ...
  14386. decl += " ";
  14387. decl += to_expression(name_id);
  14388. }
  14389. else
  14390. {
  14391. const char *img_address_space = descriptor_address_space(name_id, type_storage, "thread const");
  14392. decl = join(img_address_space, " ", decl);
  14393. decl += "& ";
  14394. decl += to_expression(name_id);
  14395. }
  14396. }
  14397. else
  14398. {
  14399. if (!address_space.empty())
  14400. decl = join(address_space, " ", decl);
  14401. decl += " ";
  14402. decl += to_expression(name_id);
  14403. }
  14404. // Emulate texture2D atomic operations
  14405. auto *backing_var = maybe_get_backing_variable(name_id);
  14406. if (backing_var && atomic_image_vars_emulated.count(backing_var->self))
  14407. {
  14408. auto &flags = ir.get_decoration_bitset(backing_var->self);
  14409. const char *cv_flags = decoration_flags_signal_volatile(flags) ? "volatile " : "";
  14410. decl += join(", ", cv_flags, "device atomic_", type_to_glsl(get<SPIRType>(var_type.image.type), 0));
  14411. decl += "* " + to_expression(name_id) + "_atomic";
  14412. }
  14413. is_using_builtin_array = false;
  14414. return decl;
  14415. }
  14416. // If we're currently in the entry point function, and the object
  14417. // has a qualified name, use it, otherwise use the standard name.
  14418. string CompilerMSL::to_name(uint32_t id, bool allow_alias) const
  14419. {
  14420. if (current_function && (current_function->self == ir.default_entry_point))
  14421. {
  14422. auto *m = ir.find_meta(id);
  14423. if (m && !m->decoration.qualified_alias_explicit_override && !m->decoration.qualified_alias.empty())
  14424. return m->decoration.qualified_alias;
  14425. }
  14426. return Compiler::to_name(id, allow_alias);
  14427. }
  14428. // Appends the name of the member to the variable qualifier string, except for Builtins.
  14429. string CompilerMSL::append_member_name(const string &qualifier, const SPIRType &type, uint32_t index)
  14430. {
  14431. // Don't qualify Builtin names because they are unique and are treated as such when building expressions
  14432. BuiltIn builtin = BuiltInMax;
  14433. if (is_member_builtin(type, index, &builtin))
  14434. return builtin_to_glsl(builtin, type.storage);
  14435. // Strip any underscore prefix from member name
  14436. string mbr_name = to_member_name(type, index);
  14437. size_t startPos = mbr_name.find_first_not_of("_");
  14438. mbr_name = (startPos != string::npos) ? mbr_name.substr(startPos) : "";
  14439. return join(qualifier, "_", mbr_name);
  14440. }
  14441. // Ensures that the specified name is permanently usable by prepending a prefix
  14442. // if the first chars are _ and a digit, which indicate a transient name.
  14443. string CompilerMSL::ensure_valid_name(string name, string pfx)
  14444. {
  14445. return (name.size() >= 2 && name[0] == '_' && isdigit(name[1])) ? (pfx + name) : name;
  14446. }
  14447. const std::unordered_set<std::string> &CompilerMSL::get_reserved_keyword_set()
  14448. {
  14449. static const unordered_set<string> keywords = {
  14450. "kernel",
  14451. "vertex",
  14452. "fragment",
  14453. "compute",
  14454. "constant",
  14455. "device",
  14456. "bias",
  14457. "level",
  14458. "gradient2d",
  14459. "gradientcube",
  14460. "gradient3d",
  14461. "min_lod_clamp",
  14462. "assert",
  14463. "VARIABLE_TRACEPOINT",
  14464. "STATIC_DATA_TRACEPOINT",
  14465. "STATIC_DATA_TRACEPOINT_V",
  14466. "METAL_ALIGN",
  14467. "METAL_ASM",
  14468. "METAL_CONST",
  14469. "METAL_DEPRECATED",
  14470. "METAL_ENABLE_IF",
  14471. "METAL_FUNC",
  14472. "METAL_INTERNAL",
  14473. "METAL_NON_NULL_RETURN",
  14474. "METAL_NORETURN",
  14475. "METAL_NOTHROW",
  14476. "METAL_PURE",
  14477. "METAL_UNAVAILABLE",
  14478. "METAL_IMPLICIT",
  14479. "METAL_EXPLICIT",
  14480. "METAL_CONST_ARG",
  14481. "METAL_ARG_UNIFORM",
  14482. "METAL_ZERO_ARG",
  14483. "METAL_VALID_LOD_ARG",
  14484. "METAL_VALID_LEVEL_ARG",
  14485. "METAL_VALID_STORE_ORDER",
  14486. "METAL_VALID_LOAD_ORDER",
  14487. "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER",
  14488. "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS",
  14489. "METAL_VALID_RENDER_TARGET",
  14490. "is_function_constant_defined",
  14491. "CHAR_BIT",
  14492. "SCHAR_MAX",
  14493. "SCHAR_MIN",
  14494. "UCHAR_MAX",
  14495. "CHAR_MAX",
  14496. "CHAR_MIN",
  14497. "USHRT_MAX",
  14498. "SHRT_MAX",
  14499. "SHRT_MIN",
  14500. "UINT_MAX",
  14501. "INT_MAX",
  14502. "INT_MIN",
  14503. "FLT_DIG",
  14504. "FLT_MANT_DIG",
  14505. "FLT_MAX_10_EXP",
  14506. "FLT_MAX_EXP",
  14507. "FLT_MIN_10_EXP",
  14508. "FLT_MIN_EXP",
  14509. "FLT_RADIX",
  14510. "FLT_MAX",
  14511. "FLT_MIN",
  14512. "FLT_EPSILON",
  14513. "FP_ILOGB0",
  14514. "FP_ILOGBNAN",
  14515. "MAXFLOAT",
  14516. "HUGE_VALF",
  14517. "INFINITY",
  14518. "NAN",
  14519. "M_E_F",
  14520. "M_LOG2E_F",
  14521. "M_LOG10E_F",
  14522. "M_LN2_F",
  14523. "M_LN10_F",
  14524. "M_PI_F",
  14525. "M_PI_2_F",
  14526. "M_PI_4_F",
  14527. "M_1_PI_F",
  14528. "M_2_PI_F",
  14529. "M_2_SQRTPI_F",
  14530. "M_SQRT2_F",
  14531. "M_SQRT1_2_F",
  14532. "HALF_DIG",
  14533. "HALF_MANT_DIG",
  14534. "HALF_MAX_10_EXP",
  14535. "HALF_MAX_EXP",
  14536. "HALF_MIN_10_EXP",
  14537. "HALF_MIN_EXP",
  14538. "HALF_RADIX",
  14539. "HALF_MAX",
  14540. "HALF_MIN",
  14541. "HALF_EPSILON",
  14542. "MAXHALF",
  14543. "HUGE_VALH",
  14544. "M_E_H",
  14545. "M_LOG2E_H",
  14546. "M_LOG10E_H",
  14547. "M_LN2_H",
  14548. "M_LN10_H",
  14549. "M_PI_H",
  14550. "M_PI_2_H",
  14551. "M_PI_4_H",
  14552. "M_1_PI_H",
  14553. "M_2_PI_H",
  14554. "M_2_SQRTPI_H",
  14555. "M_SQRT2_H",
  14556. "M_SQRT1_2_H",
  14557. "DBL_DIG",
  14558. "DBL_MANT_DIG",
  14559. "DBL_MAX_10_EXP",
  14560. "DBL_MAX_EXP",
  14561. "DBL_MIN_10_EXP",
  14562. "DBL_MIN_EXP",
  14563. "DBL_RADIX",
  14564. "DBL_MAX",
  14565. "DBL_MIN",
  14566. "DBL_EPSILON",
  14567. "HUGE_VAL",
  14568. "M_E",
  14569. "M_LOG2E",
  14570. "M_LOG10E",
  14571. "M_LN2",
  14572. "M_LN10",
  14573. "M_PI",
  14574. "M_PI_2",
  14575. "M_PI_4",
  14576. "M_1_PI",
  14577. "M_2_PI",
  14578. "M_2_SQRTPI",
  14579. "M_SQRT2",
  14580. "M_SQRT1_2",
  14581. "quad_broadcast",
  14582. "thread",
  14583. "threadgroup",
  14584. "signed",
  14585. };
  14586. return keywords;
  14587. }
  14588. const std::unordered_set<std::string> &CompilerMSL::get_illegal_func_names()
  14589. {
  14590. static const unordered_set<string> illegal_func_names = {
  14591. "main",
  14592. "fragment",
  14593. "vertex",
  14594. "kernel",
  14595. "saturate",
  14596. "assert",
  14597. "fmin3",
  14598. "fmax3",
  14599. "divide",
  14600. "fmod",
  14601. "median3",
  14602. "VARIABLE_TRACEPOINT",
  14603. "STATIC_DATA_TRACEPOINT",
  14604. "STATIC_DATA_TRACEPOINT_V",
  14605. "METAL_ALIGN",
  14606. "METAL_ASM",
  14607. "METAL_CONST",
  14608. "METAL_DEPRECATED",
  14609. "METAL_ENABLE_IF",
  14610. "METAL_FUNC",
  14611. "METAL_INTERNAL",
  14612. "METAL_NON_NULL_RETURN",
  14613. "METAL_NORETURN",
  14614. "METAL_NOTHROW",
  14615. "METAL_PURE",
  14616. "METAL_UNAVAILABLE",
  14617. "METAL_IMPLICIT",
  14618. "METAL_EXPLICIT",
  14619. "METAL_CONST_ARG",
  14620. "METAL_ARG_UNIFORM",
  14621. "METAL_ZERO_ARG",
  14622. "METAL_VALID_LOD_ARG",
  14623. "METAL_VALID_LEVEL_ARG",
  14624. "METAL_VALID_STORE_ORDER",
  14625. "METAL_VALID_LOAD_ORDER",
  14626. "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER",
  14627. "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS",
  14628. "METAL_VALID_RENDER_TARGET",
  14629. "is_function_constant_defined",
  14630. "CHAR_BIT",
  14631. "SCHAR_MAX",
  14632. "SCHAR_MIN",
  14633. "UCHAR_MAX",
  14634. "CHAR_MAX",
  14635. "CHAR_MIN",
  14636. "USHRT_MAX",
  14637. "SHRT_MAX",
  14638. "SHRT_MIN",
  14639. "UINT_MAX",
  14640. "INT_MAX",
  14641. "INT_MIN",
  14642. "FLT_DIG",
  14643. "FLT_MANT_DIG",
  14644. "FLT_MAX_10_EXP",
  14645. "FLT_MAX_EXP",
  14646. "FLT_MIN_10_EXP",
  14647. "FLT_MIN_EXP",
  14648. "FLT_RADIX",
  14649. "FLT_MAX",
  14650. "FLT_MIN",
  14651. "FLT_EPSILON",
  14652. "FP_ILOGB0",
  14653. "FP_ILOGBNAN",
  14654. "MAXFLOAT",
  14655. "HUGE_VALF",
  14656. "INFINITY",
  14657. "NAN",
  14658. "M_E_F",
  14659. "M_LOG2E_F",
  14660. "M_LOG10E_F",
  14661. "M_LN2_F",
  14662. "M_LN10_F",
  14663. "M_PI_F",
  14664. "M_PI_2_F",
  14665. "M_PI_4_F",
  14666. "M_1_PI_F",
  14667. "M_2_PI_F",
  14668. "M_2_SQRTPI_F",
  14669. "M_SQRT2_F",
  14670. "M_SQRT1_2_F",
  14671. "HALF_DIG",
  14672. "HALF_MANT_DIG",
  14673. "HALF_MAX_10_EXP",
  14674. "HALF_MAX_EXP",
  14675. "HALF_MIN_10_EXP",
  14676. "HALF_MIN_EXP",
  14677. "HALF_RADIX",
  14678. "HALF_MAX",
  14679. "HALF_MIN",
  14680. "HALF_EPSILON",
  14681. "MAXHALF",
  14682. "HUGE_VALH",
  14683. "M_E_H",
  14684. "M_LOG2E_H",
  14685. "M_LOG10E_H",
  14686. "M_LN2_H",
  14687. "M_LN10_H",
  14688. "M_PI_H",
  14689. "M_PI_2_H",
  14690. "M_PI_4_H",
  14691. "M_1_PI_H",
  14692. "M_2_PI_H",
  14693. "M_2_SQRTPI_H",
  14694. "M_SQRT2_H",
  14695. "M_SQRT1_2_H",
  14696. "DBL_DIG",
  14697. "DBL_MANT_DIG",
  14698. "DBL_MAX_10_EXP",
  14699. "DBL_MAX_EXP",
  14700. "DBL_MIN_10_EXP",
  14701. "DBL_MIN_EXP",
  14702. "DBL_RADIX",
  14703. "DBL_MAX",
  14704. "DBL_MIN",
  14705. "DBL_EPSILON",
  14706. "HUGE_VAL",
  14707. "M_E",
  14708. "M_LOG2E",
  14709. "M_LOG10E",
  14710. "M_LN2",
  14711. "M_LN10",
  14712. "M_PI",
  14713. "M_PI_2",
  14714. "M_PI_4",
  14715. "M_1_PI",
  14716. "M_2_PI",
  14717. "M_2_SQRTPI",
  14718. "M_SQRT2",
  14719. "M_SQRT1_2",
  14720. "int8",
  14721. "uint8",
  14722. "int16",
  14723. "uint16",
  14724. "float8",
  14725. "float16",
  14726. "signed",
  14727. };
  14728. return illegal_func_names;
  14729. }
  14730. // Replace all names that match MSL keywords or Metal Standard Library functions.
  14731. void CompilerMSL::replace_illegal_names()
  14732. {
  14733. // FIXME: MSL and GLSL are doing two different things here.
  14734. // Agree on convention and remove this override.
  14735. auto &keywords = get_reserved_keyword_set();
  14736. auto &illegal_func_names = get_illegal_func_names();
  14737. ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &) {
  14738. auto *meta = ir.find_meta(self);
  14739. if (!meta)
  14740. return;
  14741. auto &dec = meta->decoration;
  14742. if (keywords.find(dec.alias) != end(keywords))
  14743. dec.alias += "0";
  14744. });
  14745. ir.for_each_typed_id<SPIRFunction>([&](uint32_t self, SPIRFunction &) {
  14746. auto *meta = ir.find_meta(self);
  14747. if (!meta)
  14748. return;
  14749. auto &dec = meta->decoration;
  14750. if (illegal_func_names.find(dec.alias) != end(illegal_func_names))
  14751. dec.alias += "0";
  14752. });
  14753. ir.for_each_typed_id<SPIRType>([&](uint32_t self, SPIRType &) {
  14754. auto *meta = ir.find_meta(self);
  14755. if (!meta)
  14756. return;
  14757. for (auto &mbr_dec : meta->members)
  14758. if (keywords.find(mbr_dec.alias) != end(keywords))
  14759. mbr_dec.alias += "0";
  14760. });
  14761. CompilerGLSL::replace_illegal_names();
  14762. }
  14763. void CompilerMSL::replace_illegal_entry_point_names()
  14764. {
  14765. auto &illegal_func_names = get_illegal_func_names();
  14766. // It is important to this before we fixup identifiers,
  14767. // since if ep_name is reserved, we will need to fix that up,
  14768. // and then copy alias back into entry.name after the fixup.
  14769. for (auto &entry : ir.entry_points)
  14770. {
  14771. // Change both the entry point name and the alias, to keep them synced.
  14772. string &ep_name = entry.second.name;
  14773. if (illegal_func_names.find(ep_name) != end(illegal_func_names))
  14774. ep_name += "0";
  14775. ir.meta[entry.first].decoration.alias = ep_name;
  14776. }
  14777. }
  14778. void CompilerMSL::sync_entry_point_aliases_and_names()
  14779. {
  14780. for (auto &entry : ir.entry_points)
  14781. entry.second.name = ir.meta[entry.first].decoration.alias;
  14782. }
  14783. string CompilerMSL::to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain_is_resolved)
  14784. {
  14785. auto *var = maybe_get_backing_variable(base);
  14786. // If this is a buffer array, we have to dereference the buffer pointers.
  14787. // Otherwise, if this is a pointer expression, dereference it.
  14788. bool declared_as_pointer = false;
  14789. if (var)
  14790. {
  14791. // Only allow -> dereference for block types. This is so we get expressions like
  14792. // buffer[i]->first_member.second_member, rather than buffer[i]->first->second.
  14793. const bool is_block =
  14794. has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
  14795. bool is_buffer_variable =
  14796. is_block && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer);
  14797. declared_as_pointer = is_buffer_variable && is_array(get_pointee_type(var->basetype));
  14798. }
  14799. if (declared_as_pointer || (!ptr_chain_is_resolved && should_dereference(base)))
  14800. return join("->", to_member_name(type, index));
  14801. else
  14802. return join(".", to_member_name(type, index));
  14803. }
  14804. string CompilerMSL::to_qualifiers_glsl(uint32_t id)
  14805. {
  14806. string quals;
  14807. auto *var = maybe_get<SPIRVariable>(id);
  14808. auto &type = expression_type(id);
  14809. if (type.storage == StorageClassTaskPayloadWorkgroupEXT)
  14810. quals += "object_data ";
  14811. if (type.storage == StorageClassWorkgroup || (var && variable_decl_is_remapped_storage(*var, StorageClassWorkgroup)))
  14812. quals += "threadgroup ";
  14813. return quals;
  14814. }
  14815. // The optional id parameter indicates the object whose type we are trying
  14816. // to find the description for. It is optional. Most type descriptions do not
  14817. // depend on a specific object's use of that type.
  14818. string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id, bool member)
  14819. {
  14820. string type_name;
  14821. // Pointer?
  14822. if (is_pointer(type) || type_is_array_of_pointers(type))
  14823. {
  14824. assert(type.pointer_depth > 0);
  14825. const char *restrict_kw;
  14826. auto type_address_space = get_type_address_space(type, id);
  14827. const auto *p_parent_type = &get<SPIRType>(type.parent_type);
  14828. // If we're wrapping buffer descriptors in a spvDescriptorArray, we'll have to handle it as a special case.
  14829. if (member && id)
  14830. {
  14831. auto &var = get<SPIRVariable>(id);
  14832. if (is_var_runtime_size_array(var) && is_runtime_size_array(*p_parent_type))
  14833. {
  14834. const bool ssbo = has_decoration(p_parent_type->self, DecorationBufferBlock);
  14835. bool buffer_desc =
  14836. (var.storage == StorageClassStorageBuffer || ssbo) &&
  14837. msl_options.runtime_array_rich_descriptor;
  14838. const char *wrapper_type = buffer_desc ? "spvBufferDescriptor" : "spvDescriptor";
  14839. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  14840. add_spv_func_and_recompile(buffer_desc ? SPVFuncImplVariableSizedDescriptor : SPVFuncImplVariableDescriptor);
  14841. type_name = join(wrapper_type, "<", type_address_space, " ", type_to_glsl(*p_parent_type, id), " *>");
  14842. return type_name;
  14843. }
  14844. }
  14845. // Work around C pointer qualifier rules. If glsl_type is a pointer type as well
  14846. // we'll need to emit the address space to the right.
  14847. // We could always go this route, but it makes the code unnatural.
  14848. // Prefer emitting thread T *foo over T thread* foo since it's more readable,
  14849. // but we'll have to emit thread T * thread * T constant bar; for example.
  14850. if (is_pointer(type) && is_pointer(*p_parent_type))
  14851. type_name = join(type_to_glsl(*p_parent_type, id), " ", type_address_space, " ");
  14852. else
  14853. {
  14854. // Since this is not a pointer-to-pointer, ensure we've dug down to the base type.
  14855. // Some situations chain pointers even though they are not formally pointers-of-pointers.
  14856. while (is_pointer(*p_parent_type))
  14857. p_parent_type = &get<SPIRType>(p_parent_type->parent_type);
  14858. // If we're emitting BDA, just use the templated type.
  14859. // Emitting builtin arrays need a lot of cooperation with other code to ensure
  14860. // the C-style nesting works right.
  14861. // FIXME: This is somewhat of a hack.
  14862. bool old_is_using_builtin_array = is_using_builtin_array;
  14863. bool pointer_to_buffer_array = is_pointer(type) && has_decoration(type.parent_type, DecorationArrayStride);
  14864. if (is_physical_pointer(type))
  14865. is_using_builtin_array = false;
  14866. else if (pointer_to_buffer_array)
  14867. is_using_builtin_array = true;
  14868. type_name = join(type_address_space, " ", type_to_glsl(*p_parent_type, id));
  14869. is_using_builtin_array = old_is_using_builtin_array;
  14870. }
  14871. switch (type.basetype)
  14872. {
  14873. case SPIRType::Image:
  14874. case SPIRType::SampledImage:
  14875. case SPIRType::Sampler:
  14876. // These are handles.
  14877. break;
  14878. default:
  14879. // Anything else can be a raw pointer.
  14880. type_name += "*";
  14881. restrict_kw = to_restrict(id, false);
  14882. if (*restrict_kw)
  14883. {
  14884. type_name += " ";
  14885. type_name += restrict_kw;
  14886. }
  14887. break;
  14888. }
  14889. return type_name;
  14890. }
  14891. switch (type.basetype)
  14892. {
  14893. case SPIRType::Struct:
  14894. // Need OpName lookup here to get a "sensible" name for a struct.
  14895. // Allow Metal to use the array<T> template to make arrays a value type
  14896. type_name = to_name(type.self);
  14897. break;
  14898. case SPIRType::Image:
  14899. case SPIRType::SampledImage:
  14900. return image_type_glsl(type, id, member);
  14901. case SPIRType::Sampler:
  14902. return sampler_type(type, id, member);
  14903. case SPIRType::Void:
  14904. return "void";
  14905. case SPIRType::AtomicCounter:
  14906. return "atomic_uint";
  14907. case SPIRType::ControlPointArray:
  14908. return join("patch_control_point<", type_to_glsl(get<SPIRType>(type.parent_type), id), ">");
  14909. case SPIRType::Interpolant:
  14910. return join("interpolant<", type_to_glsl(get<SPIRType>(type.parent_type), id), ", interpolation::",
  14911. has_decoration(type.self, DecorationNoPerspective) ? "no_perspective" : "perspective", ">");
  14912. // Scalars
  14913. case SPIRType::Boolean:
  14914. {
  14915. auto *var = maybe_get_backing_variable(id);
  14916. if (var && var->basevariable)
  14917. var = &get<SPIRVariable>(var->basevariable);
  14918. // Need to special-case threadgroup booleans. They are supposed to be logical
  14919. // storage, but MSL compilers will sometimes crash if you use threadgroup bool.
  14920. // Workaround this by using 16-bit types instead and fixup on load-store to this data.
  14921. if ((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup || member)
  14922. type_name = "short";
  14923. else
  14924. type_name = "bool";
  14925. break;
  14926. }
  14927. case SPIRType::Char:
  14928. case SPIRType::SByte:
  14929. type_name = "char";
  14930. break;
  14931. case SPIRType::UByte:
  14932. type_name = "uchar";
  14933. break;
  14934. case SPIRType::Short:
  14935. type_name = "short";
  14936. break;
  14937. case SPIRType::UShort:
  14938. type_name = "ushort";
  14939. break;
  14940. case SPIRType::Int:
  14941. type_name = "int";
  14942. break;
  14943. case SPIRType::UInt:
  14944. type_name = "uint";
  14945. break;
  14946. case SPIRType::Int64:
  14947. if (!msl_options.supports_msl_version(2, 2))
  14948. SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above.");
  14949. type_name = "long";
  14950. break;
  14951. case SPIRType::UInt64:
  14952. if (!msl_options.supports_msl_version(2, 2))
  14953. SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above.");
  14954. type_name = "ulong";
  14955. break;
  14956. case SPIRType::Half:
  14957. type_name = "half";
  14958. break;
  14959. case SPIRType::Float:
  14960. type_name = "float";
  14961. break;
  14962. case SPIRType::Double:
  14963. type_name = "double"; // Currently unsupported
  14964. break;
  14965. case SPIRType::AccelerationStructure:
  14966. if (msl_options.supports_msl_version(2, 4))
  14967. type_name = "raytracing::acceleration_structure<raytracing::instancing>";
  14968. else if (msl_options.supports_msl_version(2, 3))
  14969. type_name = "raytracing::instance_acceleration_structure";
  14970. else
  14971. SPIRV_CROSS_THROW("Acceleration Structure Type is supported in MSL 2.3 and above.");
  14972. break;
  14973. case SPIRType::RayQuery:
  14974. return "raytracing::intersection_query<raytracing::instancing, raytracing::triangle_data>";
  14975. case SPIRType::MeshGridProperties:
  14976. return "mesh_grid_properties";
  14977. default:
  14978. return "unknown_type";
  14979. }
  14980. // Matrix?
  14981. if (type.columns > 1)
  14982. {
  14983. auto *var = maybe_get_backing_variable(id);
  14984. if (var && var->basevariable)
  14985. var = &get<SPIRVariable>(var->basevariable);
  14986. // Need to special-case threadgroup matrices. Due to an oversight, Metal's
  14987. // matrix struct prior to Metal 3 lacks constructors in the threadgroup AS,
  14988. // preventing us from default-constructing or initializing matrices in threadgroup storage.
  14989. // Work around this by using our own type as storage.
  14990. if (((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup) &&
  14991. !msl_options.supports_msl_version(3, 0))
  14992. {
  14993. add_spv_func_and_recompile(SPVFuncImplStorageMatrix);
  14994. type_name = "spvStorage_" + type_name;
  14995. }
  14996. type_name += to_string(type.columns) + "x";
  14997. }
  14998. // Vector or Matrix?
  14999. if (type.vecsize > 1)
  15000. type_name += to_string(type.vecsize);
  15001. if (type.array.empty() || using_builtin_array())
  15002. {
  15003. return type_name;
  15004. }
  15005. else
  15006. {
  15007. // Allow Metal to use the array<T> template to make arrays a value type
  15008. add_spv_func_and_recompile(SPVFuncImplUnsafeArray);
  15009. string res;
  15010. string sizes;
  15011. for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
  15012. {
  15013. res += "spvUnsafeArray<";
  15014. sizes += ", ";
  15015. sizes += to_array_size(type, i);
  15016. sizes += ">";
  15017. }
  15018. res += type_name + sizes;
  15019. return res;
  15020. }
  15021. }
  15022. string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id)
  15023. {
  15024. return type_to_glsl(type, id, false);
  15025. }
  15026. string CompilerMSL::type_to_array_glsl(const SPIRType &type, uint32_t variable_id)
  15027. {
  15028. // Allow Metal to use the array<T> template to make arrays a value type
  15029. switch (type.basetype)
  15030. {
  15031. case SPIRType::AtomicCounter:
  15032. case SPIRType::ControlPointArray:
  15033. case SPIRType::RayQuery:
  15034. return CompilerGLSL::type_to_array_glsl(type, variable_id);
  15035. default:
  15036. if (type_is_array_of_pointers(type) || using_builtin_array())
  15037. {
  15038. const SPIRVariable *var = variable_id ? maybe_get<SPIRVariable>(variable_id) : nullptr;
  15039. if (var && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer) &&
  15040. is_array(get_variable_data_type(*var)))
  15041. {
  15042. return join("[", get_resource_array_size(type, variable_id), "]");
  15043. }
  15044. else
  15045. return CompilerGLSL::type_to_array_glsl(type, variable_id);
  15046. }
  15047. else
  15048. return "";
  15049. }
  15050. }
  15051. string CompilerMSL::constant_op_expression(const SPIRConstantOp &cop)
  15052. {
  15053. switch (cop.opcode)
  15054. {
  15055. case OpSMod:
  15056. add_spv_func_and_recompile(SPVFuncImplSMod);
  15057. return join("spvSMod(", to_expression(cop.arguments[0]), ", ", to_expression(cop.arguments[1]), ")");
  15058. case OpQuantizeToF16:
  15059. add_spv_func_and_recompile(SPVFuncImplQuantizeToF16);
  15060. return join("spvQuantizeToF16(", to_expression(cop.arguments[0]), ")");
  15061. default:
  15062. return CompilerGLSL::constant_op_expression(cop);
  15063. }
  15064. }
  15065. bool CompilerMSL::variable_decl_is_remapped_storage(const SPIRVariable &variable, StorageClass storage) const
  15066. {
  15067. if (variable.storage == storage)
  15068. return true;
  15069. if (storage == StorageClassWorkgroup)
  15070. {
  15071. // Specially masked IO block variable.
  15072. // Normally, we will never access IO blocks directly here.
  15073. // The only scenario which that should occur is with a masked IO block.
  15074. if (is_tesc_shader() && variable.storage == StorageClassOutput &&
  15075. has_decoration(get<SPIRType>(variable.basetype).self, DecorationBlock))
  15076. {
  15077. return true;
  15078. }
  15079. if (is_mesh_shader())
  15080. return variable.storage == StorageClassOutput;
  15081. return variable.storage == StorageClassOutput && is_tesc_shader() && is_stage_output_variable_masked(variable);
  15082. }
  15083. else if (storage == StorageClassStorageBuffer)
  15084. {
  15085. // These builtins are passed directly; we don't want to use remapping
  15086. // for them.
  15087. auto builtin = (BuiltIn)get_decoration(variable.self, DecorationBuiltIn);
  15088. if (is_tese_shader() && is_builtin_variable(variable) && (builtin == BuiltInTessCoord || builtin == BuiltInPrimitiveId))
  15089. return false;
  15090. // We won't be able to catch writes to control point outputs here since variable
  15091. // refers to a function local pointer.
  15092. // This is fine, as there cannot be concurrent writers to that memory anyways,
  15093. // so we just ignore that case.
  15094. return (variable.storage == StorageClassOutput || variable.storage == StorageClassInput) &&
  15095. !variable_storage_requires_stage_io(variable.storage) &&
  15096. (variable.storage != StorageClassOutput || !is_stage_output_variable_masked(variable));
  15097. }
  15098. else
  15099. {
  15100. return false;
  15101. }
  15102. }
  15103. // GCC workaround of lambdas calling protected funcs
  15104. std::string CompilerMSL::variable_decl(const SPIRType &type, const std::string &name, uint32_t id)
  15105. {
  15106. return CompilerGLSL::variable_decl(type, name, id);
  15107. }
  15108. std::string CompilerMSL::sampler_type(const SPIRType &type, uint32_t id, bool member)
  15109. {
  15110. auto *var = maybe_get<SPIRVariable>(id);
  15111. if (var && var->basevariable)
  15112. {
  15113. // Check against the base variable, and not a fake ID which might have been generated for this variable.
  15114. id = var->basevariable;
  15115. }
  15116. if (!type.array.empty())
  15117. {
  15118. if (!msl_options.supports_msl_version(2))
  15119. SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of samplers.");
  15120. if (type.array.size() > 1)
  15121. SPIRV_CROSS_THROW("Arrays of arrays of samplers are not supported in MSL.");
  15122. // Arrays of samplers in MSL must be declared with a special array<T, N> syntax ala C++11 std::array.
  15123. // If we have a runtime array, it could be a variable-count descriptor set binding.
  15124. auto &parent = get<SPIRType>(get_pointee_type(type).parent_type);
  15125. uint32_t array_size = get_resource_array_size(type, id);
  15126. if (array_size == 0)
  15127. {
  15128. add_spv_func_and_recompile(SPVFuncImplVariableDescriptor);
  15129. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  15130. const char *descriptor_wrapper = processing_entry_point ? "const device spvDescriptor" : "const spvDescriptorArray";
  15131. if (member)
  15132. descriptor_wrapper = "spvDescriptor";
  15133. return join(descriptor_wrapper, "<", sampler_type(parent, id, false), ">",
  15134. processing_entry_point ? "*" : "");
  15135. }
  15136. else
  15137. {
  15138. return join("array<", sampler_type(parent, id, false), ", ", array_size, ">");
  15139. }
  15140. }
  15141. else
  15142. return "sampler";
  15143. }
  15144. // Returns an MSL string describing the SPIR-V image type
  15145. string CompilerMSL::image_type_glsl(const SPIRType &type, uint32_t id, bool member)
  15146. {
  15147. auto *var = maybe_get<SPIRVariable>(id);
  15148. if (var && var->basevariable)
  15149. {
  15150. // For comparison images, check against the base variable,
  15151. // and not the fake ID which might have been generated for this variable.
  15152. id = var->basevariable;
  15153. }
  15154. if (!type.array.empty())
  15155. {
  15156. uint32_t major = 2, minor = 0;
  15157. if (msl_options.is_ios())
  15158. {
  15159. major = 1;
  15160. minor = 2;
  15161. }
  15162. if (!msl_options.supports_msl_version(major, minor))
  15163. {
  15164. if (msl_options.is_ios())
  15165. SPIRV_CROSS_THROW("MSL 1.2 or greater is required for arrays of textures.");
  15166. else
  15167. SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of textures.");
  15168. }
  15169. if (type.array.size() > 1)
  15170. SPIRV_CROSS_THROW("Arrays of arrays of textures are not supported in MSL.");
  15171. // Arrays of images in MSL must be declared with a special array<T, N> syntax ala C++11 std::array.
  15172. // If we have a runtime array, it could be a variable-count descriptor set binding.
  15173. auto &parent = get<SPIRType>(get_pointee_type(type).parent_type);
  15174. uint32_t array_size = get_resource_array_size(type, id);
  15175. if (array_size == 0)
  15176. {
  15177. add_spv_func_and_recompile(SPVFuncImplVariableDescriptor);
  15178. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  15179. const char *descriptor_wrapper = processing_entry_point ? "const device spvDescriptor" : "const spvDescriptorArray";
  15180. if (member)
  15181. {
  15182. descriptor_wrapper = "spvDescriptor";
  15183. // This requires a specialized wrapper type that packs image and sampler side by side.
  15184. // It is possible in theory.
  15185. if (type.basetype == SPIRType::SampledImage)
  15186. SPIRV_CROSS_THROW("Argument buffer runtime array currently not supported for combined image sampler.");
  15187. }
  15188. return join(descriptor_wrapper, "<", image_type_glsl(parent, id, false), ">",
  15189. processing_entry_point ? "*" : "");
  15190. }
  15191. else
  15192. {
  15193. return join("array<", image_type_glsl(parent, id, false), ", ", array_size, ">");
  15194. }
  15195. }
  15196. string img_type_name;
  15197. auto &img_type = type.image;
  15198. if (is_depth_image(type, id))
  15199. {
  15200. switch (img_type.dim)
  15201. {
  15202. case Dim1D:
  15203. case Dim2D:
  15204. if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D)
  15205. {
  15206. // Use a native Metal 1D texture
  15207. img_type_name += "depth1d_unsupported_by_metal";
  15208. break;
  15209. }
  15210. if (img_type.ms && img_type.arrayed)
  15211. {
  15212. if (!msl_options.supports_msl_version(2, 1))
  15213. SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1.");
  15214. img_type_name += "depth2d_ms_array";
  15215. }
  15216. else if (img_type.ms)
  15217. img_type_name += "depth2d_ms";
  15218. else if (img_type.arrayed)
  15219. img_type_name += "depth2d_array";
  15220. else
  15221. img_type_name += "depth2d";
  15222. break;
  15223. case Dim3D:
  15224. img_type_name += "depth3d_unsupported_by_metal";
  15225. break;
  15226. case DimCube:
  15227. if (!msl_options.emulate_cube_array)
  15228. img_type_name += (img_type.arrayed ? "depthcube_array" : "depthcube");
  15229. else
  15230. img_type_name += (img_type.arrayed ? "depth2d_array" : "depthcube");
  15231. break;
  15232. default:
  15233. img_type_name += "unknown_depth_texture_type";
  15234. break;
  15235. }
  15236. }
  15237. else
  15238. {
  15239. switch (img_type.dim)
  15240. {
  15241. case DimBuffer:
  15242. if (img_type.ms || img_type.arrayed)
  15243. SPIRV_CROSS_THROW("Cannot use texel buffers with multisampling or array layers.");
  15244. if (msl_options.texture_buffer_native)
  15245. {
  15246. if (!msl_options.supports_msl_version(2, 1))
  15247. SPIRV_CROSS_THROW("Native texture_buffer type is only supported in MSL 2.1.");
  15248. img_type_name = "texture_buffer";
  15249. }
  15250. else
  15251. img_type_name += "texture2d";
  15252. break;
  15253. case Dim1D:
  15254. case Dim2D:
  15255. case DimSubpassData:
  15256. {
  15257. bool subpass_array =
  15258. img_type.dim == DimSubpassData && (msl_options.multiview || msl_options.arrayed_subpass_input);
  15259. if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D)
  15260. {
  15261. // Use a native Metal 1D texture
  15262. img_type_name += (img_type.arrayed ? "texture1d_array" : "texture1d");
  15263. break;
  15264. }
  15265. // Use Metal's native frame-buffer fetch API for subpass inputs.
  15266. if (type_is_msl_framebuffer_fetch(type))
  15267. {
  15268. auto img_type_4 = get<SPIRType>(img_type.type);
  15269. img_type_4.vecsize = 4;
  15270. return type_to_glsl(img_type_4);
  15271. }
  15272. if (img_type.ms && (img_type.arrayed || subpass_array))
  15273. {
  15274. if (!msl_options.supports_msl_version(2, 1))
  15275. SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1.");
  15276. img_type_name += "texture2d_ms_array";
  15277. }
  15278. else if (img_type.ms)
  15279. img_type_name += "texture2d_ms";
  15280. else if (img_type.arrayed || subpass_array)
  15281. img_type_name += "texture2d_array";
  15282. else
  15283. img_type_name += "texture2d";
  15284. break;
  15285. }
  15286. case Dim3D:
  15287. img_type_name += "texture3d";
  15288. break;
  15289. case DimCube:
  15290. if (!msl_options.emulate_cube_array)
  15291. img_type_name += (img_type.arrayed ? "texturecube_array" : "texturecube");
  15292. else
  15293. img_type_name += (img_type.arrayed ? "texture2d_array" : "texturecube");
  15294. break;
  15295. default:
  15296. img_type_name += "unknown_texture_type";
  15297. break;
  15298. }
  15299. }
  15300. // Append the pixel type
  15301. img_type_name += "<";
  15302. img_type_name += type_to_glsl(get<SPIRType>(img_type.type));
  15303. // For unsampled images, append the sample/read/write access qualifier.
  15304. // For kernel images, the access qualifier my be supplied directly by SPIR-V.
  15305. // Otherwise it may be set based on whether the image is read from or written to within the shader.
  15306. if (type.basetype == SPIRType::Image && type.image.sampled == 2 && type.image.dim != DimSubpassData)
  15307. {
  15308. auto *p_var = maybe_get_backing_variable(id);
  15309. if (p_var && p_var->basevariable)
  15310. p_var = maybe_get<SPIRVariable>(p_var->basevariable);
  15311. bool has_access_qualifier = true;
  15312. switch (img_type.access)
  15313. {
  15314. case AccessQualifierReadOnly:
  15315. img_type_name += ", access::read";
  15316. break;
  15317. case AccessQualifierWriteOnly:
  15318. img_type_name += ", access::write";
  15319. break;
  15320. case AccessQualifierReadWrite:
  15321. img_type_name += ", access::read_write";
  15322. break;
  15323. default:
  15324. {
  15325. if (p_var && !has_decoration(p_var->self, DecorationNonWritable))
  15326. {
  15327. img_type_name += ", access::";
  15328. if (!has_decoration(p_var->self, DecorationNonReadable))
  15329. img_type_name += "read_";
  15330. img_type_name += "write";
  15331. }
  15332. else
  15333. {
  15334. has_access_qualifier = false;
  15335. }
  15336. break;
  15337. }
  15338. }
  15339. if (p_var && has_decoration(p_var->self, DecorationCoherent) && msl_options.supports_msl_version(3, 2))
  15340. {
  15341. // Cannot declare memory_coherence_device without access qualifier.
  15342. if (!has_access_qualifier)
  15343. img_type_name += ", access::read";
  15344. img_type_name += ", memory_coherence_device";
  15345. }
  15346. }
  15347. img_type_name += ">";
  15348. return img_type_name;
  15349. }
  15350. void CompilerMSL::emit_subgroup_op(const Instruction &i)
  15351. {
  15352. const uint32_t *ops = stream(i);
  15353. auto op = static_cast<Op>(i.op);
  15354. if (msl_options.emulate_subgroups)
  15355. {
  15356. // In this mode, only the GroupNonUniform cap is supported. The only op
  15357. // we need to handle, then, is OpGroupNonUniformElect.
  15358. if (op != OpGroupNonUniformElect)
  15359. SPIRV_CROSS_THROW("Subgroup emulation does not support operations other than Elect.");
  15360. // In this mode, the subgroup size is assumed to be one, so every invocation
  15361. // is elected.
  15362. emit_op(ops[0], ops[1], "true", true);
  15363. return;
  15364. }
  15365. // Metal 2.0 is required. iOS only supports quad ops on 11.0 (2.0), with
  15366. // full support in 13.0 (2.2). macOS only supports broadcast and shuffle on
  15367. // 10.13 (2.0), with full support in 10.14 (2.1).
  15368. // Note that Apple GPUs before A13 make no distinction between a quad-group
  15369. // and a SIMD-group; all SIMD-groups are quad-groups on those.
  15370. if (!msl_options.supports_msl_version(2))
  15371. SPIRV_CROSS_THROW("Subgroups are only supported in Metal 2.0 and up.");
  15372. // If we need to do implicit bitcasts, make sure we do it with the correct type.
  15373. uint32_t integer_width = get_integer_width_for_instruction(i);
  15374. auto int_type = to_signed_basetype(integer_width);
  15375. auto uint_type = to_unsigned_basetype(integer_width);
  15376. if (msl_options.is_ios() && (!msl_options.supports_msl_version(2, 3) || !msl_options.ios_use_simdgroup_functions))
  15377. {
  15378. switch (op)
  15379. {
  15380. default:
  15381. SPIRV_CROSS_THROW("Subgroup ops beyond broadcast, ballot, and shuffle on iOS require Metal 2.3 and up.");
  15382. case OpGroupNonUniformBroadcastFirst:
  15383. if (!msl_options.supports_msl_version(2, 2))
  15384. SPIRV_CROSS_THROW("BroadcastFirst on iOS requires Metal 2.2 and up.");
  15385. break;
  15386. case OpGroupNonUniformElect:
  15387. if (!msl_options.supports_msl_version(2, 2))
  15388. SPIRV_CROSS_THROW("Elect on iOS requires Metal 2.2 and up.");
  15389. break;
  15390. case OpGroupNonUniformAny:
  15391. case OpGroupNonUniformAll:
  15392. case OpGroupNonUniformAllEqual:
  15393. case OpGroupNonUniformBallot:
  15394. case OpGroupNonUniformInverseBallot:
  15395. case OpGroupNonUniformBallotBitExtract:
  15396. case OpGroupNonUniformBallotFindLSB:
  15397. case OpGroupNonUniformBallotFindMSB:
  15398. case OpGroupNonUniformBallotBitCount:
  15399. case OpSubgroupBallotKHR:
  15400. case OpSubgroupAllKHR:
  15401. case OpSubgroupAnyKHR:
  15402. case OpSubgroupAllEqualKHR:
  15403. if (!msl_options.supports_msl_version(2, 2))
  15404. SPIRV_CROSS_THROW("Ballot ops on iOS requires Metal 2.2 and up.");
  15405. break;
  15406. case OpGroupNonUniformRotateKHR:
  15407. if (!msl_options.supports_msl_version(2, 2))
  15408. SPIRV_CROSS_THROW("Rotate on iOS requires Metal 2.2 and up.");
  15409. break;
  15410. case OpGroupNonUniformBroadcast:
  15411. case OpGroupNonUniformShuffle:
  15412. case OpGroupNonUniformShuffleXor:
  15413. case OpGroupNonUniformShuffleUp:
  15414. case OpGroupNonUniformShuffleDown:
  15415. case OpGroupNonUniformQuadSwap:
  15416. case OpGroupNonUniformQuadBroadcast:
  15417. case OpSubgroupReadInvocationKHR:
  15418. break;
  15419. }
  15420. }
  15421. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  15422. {
  15423. switch (op)
  15424. {
  15425. default:
  15426. SPIRV_CROSS_THROW("Subgroup ops beyond broadcast and shuffle on macOS require Metal 2.1 and up.");
  15427. case OpGroupNonUniformBroadcast:
  15428. case OpGroupNonUniformShuffle:
  15429. case OpGroupNonUniformShuffleXor:
  15430. case OpGroupNonUniformShuffleUp:
  15431. case OpGroupNonUniformShuffleDown:
  15432. case OpSubgroupReadInvocationKHR:
  15433. break;
  15434. }
  15435. }
  15436. uint32_t op_idx = 0;
  15437. uint32_t result_type = ops[op_idx++];
  15438. uint32_t id = ops[op_idx++];
  15439. Scope scope;
  15440. switch (op)
  15441. {
  15442. // These earlier instructions don't have the scope operand.
  15443. case OpSubgroupBallotKHR:
  15444. case OpSubgroupFirstInvocationKHR:
  15445. case OpSubgroupReadInvocationKHR:
  15446. case OpSubgroupAllKHR:
  15447. case OpSubgroupAnyKHR:
  15448. case OpSubgroupAllEqualKHR:
  15449. // These instructions are always quad-scoped and thus do not have a scope operand.
  15450. case OpGroupNonUniformQuadAllKHR:
  15451. case OpGroupNonUniformQuadAnyKHR:
  15452. scope = ScopeSubgroup;
  15453. break;
  15454. default:
  15455. scope = static_cast<Scope>(evaluate_constant_u32(ops[op_idx++]));
  15456. break;
  15457. }
  15458. if (scope != ScopeSubgroup)
  15459. SPIRV_CROSS_THROW("Only subgroup scope is supported.");
  15460. switch (op)
  15461. {
  15462. case OpGroupNonUniformElect:
  15463. if (msl_options.use_quadgroup_operation())
  15464. emit_op(result_type, id, "quad_is_first()", false);
  15465. else
  15466. emit_op(result_type, id, "simd_is_first()", false);
  15467. break;
  15468. case OpGroupNonUniformBroadcast:
  15469. case OpSubgroupReadInvocationKHR:
  15470. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupBroadcast");
  15471. break;
  15472. case OpGroupNonUniformBroadcastFirst:
  15473. case OpSubgroupFirstInvocationKHR:
  15474. emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupBroadcastFirst");
  15475. break;
  15476. case OpGroupNonUniformBallot:
  15477. case OpSubgroupBallotKHR:
  15478. emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupBallot");
  15479. break;
  15480. case OpGroupNonUniformInverseBallot:
  15481. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id, "spvSubgroupBallotBitExtract");
  15482. break;
  15483. case OpGroupNonUniformBallotBitExtract:
  15484. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupBallotBitExtract");
  15485. break;
  15486. case OpGroupNonUniformBallotFindLSB:
  15487. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotFindLSB");
  15488. break;
  15489. case OpGroupNonUniformBallotFindMSB:
  15490. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotFindMSB");
  15491. break;
  15492. case OpGroupNonUniformBallotBitCount:
  15493. {
  15494. auto operation = static_cast<GroupOperation>(ops[op_idx++]);
  15495. switch (operation)
  15496. {
  15497. case GroupOperationReduce:
  15498. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotBitCount");
  15499. break;
  15500. case GroupOperationInclusiveScan:
  15501. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id,
  15502. "spvSubgroupBallotInclusiveBitCount");
  15503. break;
  15504. case GroupOperationExclusiveScan:
  15505. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id,
  15506. "spvSubgroupBallotExclusiveBitCount");
  15507. break;
  15508. default:
  15509. SPIRV_CROSS_THROW("Invalid BitCount operation.");
  15510. }
  15511. break;
  15512. }
  15513. case OpGroupNonUniformShuffle:
  15514. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffle");
  15515. break;
  15516. case OpGroupNonUniformShuffleXor:
  15517. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleXor");
  15518. break;
  15519. case OpGroupNonUniformShuffleUp:
  15520. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleUp");
  15521. break;
  15522. case OpGroupNonUniformShuffleDown:
  15523. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleDown");
  15524. break;
  15525. case OpGroupNonUniformRotateKHR:
  15526. {
  15527. if (i.length > 5)
  15528. {
  15529. // MSL does not have a cluster size parameter, so calculate the invocation ID manually and using a shuffle.
  15530. auto delta_expr = enclose_expression(to_unpacked_expression(ops[op_idx + 1]));
  15531. auto cluster_size_minus_one = evaluate_constant_u32(ops[op_idx + 2]) - 1;
  15532. auto local_id_expr = to_unpacked_expression(scope == ScopeSubgroup
  15533. ? builtin_subgroup_invocation_id_id : builtin_local_invocation_index_id);
  15534. auto shuffle_idx = join("((", local_id_expr, " + ", delta_expr, ")", " & ", std::to_string(cluster_size_minus_one),
  15535. ") + (", local_id_expr, " & ", std::to_string(~cluster_size_minus_one), ")");
  15536. emit_op(result_type, id, join("spvSubgroupShuffle(", to_unpacked_expression(ops[op_idx]), ", ", shuffle_idx, ")"), false);
  15537. } else
  15538. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupRotate");
  15539. break;
  15540. }
  15541. case OpGroupNonUniformAll:
  15542. case OpSubgroupAllKHR:
  15543. if (msl_options.use_quadgroup_operation())
  15544. emit_unary_func_op(result_type, id, ops[op_idx], "quad_all");
  15545. else
  15546. emit_unary_func_op(result_type, id, ops[op_idx], "simd_all");
  15547. break;
  15548. case OpGroupNonUniformAny:
  15549. case OpSubgroupAnyKHR:
  15550. if (msl_options.use_quadgroup_operation())
  15551. emit_unary_func_op(result_type, id, ops[op_idx], "quad_any");
  15552. else
  15553. emit_unary_func_op(result_type, id, ops[op_idx], "simd_any");
  15554. break;
  15555. case OpGroupNonUniformAllEqual:
  15556. case OpSubgroupAllEqualKHR:
  15557. emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupAllEqual");
  15558. break;
  15559. // clang-format off
  15560. #define MSL_GROUP_OP(op, msl_op) \
  15561. case OpGroupNonUniform##op: \
  15562. { \
  15563. auto operation = static_cast<GroupOperation>(ops[op_idx++]); \
  15564. if (operation == GroupOperationReduce) \
  15565. emit_unary_func_op(result_type, id, ops[op_idx], "simd_" #msl_op); \
  15566. else if (operation == GroupOperationInclusiveScan) \
  15567. emit_unary_func_op(result_type, id, ops[op_idx], "simd_prefix_inclusive_" #msl_op); \
  15568. else if (operation == GroupOperationExclusiveScan) \
  15569. emit_unary_func_op(result_type, id, ops[op_idx], "simd_prefix_exclusive_" #msl_op); \
  15570. else if (operation == GroupOperationClusteredReduce) \
  15571. { \
  15572. uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \
  15573. if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \
  15574. add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \
  15575. emit_subgroup_cluster_op(result_type, id, cluster_size, ops[op_idx], #msl_op); \
  15576. } \
  15577. else \
  15578. SPIRV_CROSS_THROW("Invalid group operation."); \
  15579. break; \
  15580. }
  15581. MSL_GROUP_OP(FAdd, sum)
  15582. MSL_GROUP_OP(FMul, product)
  15583. MSL_GROUP_OP(IAdd, sum)
  15584. MSL_GROUP_OP(IMul, product)
  15585. #undef MSL_GROUP_OP
  15586. // The others, unfortunately, don't support InclusiveScan or ExclusiveScan.
  15587. #define MSL_GROUP_OP(op, msl_op) \
  15588. case OpGroupNonUniform##op: \
  15589. { \
  15590. auto operation = static_cast<GroupOperation>(ops[op_idx++]); \
  15591. if (operation == GroupOperationReduce) \
  15592. emit_unary_func_op(result_type, id, ops[op_idx], "simd_" #msl_op); \
  15593. else if (operation == GroupOperationInclusiveScan) \
  15594. SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \
  15595. else if (operation == GroupOperationExclusiveScan) \
  15596. SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \
  15597. else if (operation == GroupOperationClusteredReduce) \
  15598. { \
  15599. uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \
  15600. if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \
  15601. add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \
  15602. emit_subgroup_cluster_op(result_type, id, cluster_size, ops[op_idx], #msl_op); \
  15603. } \
  15604. else \
  15605. SPIRV_CROSS_THROW("Invalid group operation."); \
  15606. break; \
  15607. }
  15608. #define MSL_GROUP_OP_CAST(op, msl_op, type) \
  15609. case OpGroupNonUniform##op: \
  15610. { \
  15611. auto operation = static_cast<GroupOperation>(ops[op_idx++]); \
  15612. if (operation == GroupOperationReduce) \
  15613. emit_unary_func_op_cast(result_type, id, ops[op_idx], "simd_" #msl_op, type, type); \
  15614. else if (operation == GroupOperationInclusiveScan) \
  15615. SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \
  15616. else if (operation == GroupOperationExclusiveScan) \
  15617. SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \
  15618. else if (operation == GroupOperationClusteredReduce) \
  15619. { \
  15620. uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \
  15621. if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \
  15622. add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \
  15623. emit_subgroup_cluster_op_cast(result_type, id, cluster_size, ops[op_idx], #msl_op, type, type); \
  15624. } \
  15625. else \
  15626. SPIRV_CROSS_THROW("Invalid group operation."); \
  15627. break; \
  15628. }
  15629. MSL_GROUP_OP(FMin, min)
  15630. MSL_GROUP_OP(FMax, max)
  15631. MSL_GROUP_OP_CAST(SMin, min, int_type)
  15632. MSL_GROUP_OP_CAST(SMax, max, int_type)
  15633. MSL_GROUP_OP_CAST(UMin, min, uint_type)
  15634. MSL_GROUP_OP_CAST(UMax, max, uint_type)
  15635. MSL_GROUP_OP(BitwiseAnd, and)
  15636. MSL_GROUP_OP(BitwiseOr, or)
  15637. MSL_GROUP_OP(BitwiseXor, xor)
  15638. // Metal doesn't support boolean types in SIMD-group operations, so we
  15639. // have to emit some casts.
  15640. MSL_GROUP_OP_CAST(LogicalAnd, and, SPIRType::UShort)
  15641. MSL_GROUP_OP_CAST(LogicalOr, or, SPIRType::UShort)
  15642. MSL_GROUP_OP_CAST(LogicalXor, xor, SPIRType::UShort)
  15643. // clang-format on
  15644. #undef MSL_GROUP_OP
  15645. #undef MSL_GROUP_OP_CAST
  15646. case OpGroupNonUniformQuadSwap:
  15647. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvQuadSwap");
  15648. break;
  15649. case OpGroupNonUniformQuadBroadcast:
  15650. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvQuadBroadcast");
  15651. break;
  15652. case OpGroupNonUniformQuadAllKHR:
  15653. emit_unary_func_op(result_type, id, ops[op_idx], "quad_all");
  15654. break;
  15655. case OpGroupNonUniformQuadAnyKHR:
  15656. emit_unary_func_op(result_type, id, ops[op_idx], "quad_any");
  15657. break;
  15658. default:
  15659. SPIRV_CROSS_THROW("Invalid opcode for subgroup.");
  15660. }
  15661. register_control_dependent_expression(id);
  15662. }
  15663. void CompilerMSL::emit_subgroup_cluster_op(uint32_t result_type, uint32_t result_id, uint32_t cluster_size,
  15664. uint32_t op0, const char *op)
  15665. {
  15666. if (get_execution_model() == ExecutionModelFragment && !msl_options.supports_msl_version(2, 2))
  15667. {
  15668. if (cluster_size == 4)
  15669. {
  15670. emit_unary_func_op(result_type, result_id, op0, join("quad_", op).c_str());
  15671. return;
  15672. }
  15673. SPIRV_CROSS_THROW("Cluster sizes other than 4 in fragment shaders require MSL 2.2.");
  15674. }
  15675. bool forward = should_forward(op0);
  15676. emit_op(result_type, result_id,
  15677. join("spvClustered_", op, "<", cluster_size, ">(", to_unpacked_expression(op0), ", ",
  15678. to_expression(builtin_subgroup_invocation_id_id), ")"),
  15679. forward);
  15680. inherit_expression_dependencies(result_id, op0);
  15681. }
  15682. void CompilerMSL::emit_subgroup_cluster_op_cast(uint32_t result_type, uint32_t result_id, uint32_t cluster_size,
  15683. uint32_t op0, const char *op, SPIRType::BaseType input_type,
  15684. SPIRType::BaseType expected_result_type)
  15685. {
  15686. if (get_execution_model() == ExecutionModelFragment && !msl_options.supports_msl_version(2, 2))
  15687. {
  15688. if (cluster_size == 4)
  15689. {
  15690. emit_unary_func_op_cast(result_type, result_id, op0, join("quad_", op).c_str(), input_type,
  15691. expected_result_type);
  15692. return;
  15693. }
  15694. SPIRV_CROSS_THROW("Cluster sizes other than 4 in fragment shaders require MSL 2.2.");
  15695. }
  15696. auto &out_type = get<SPIRType>(result_type);
  15697. auto &expr_type = expression_type(op0);
  15698. auto expected_type = out_type;
  15699. // Bit-widths might be different in unary cases because we use it for SConvert/UConvert and friends.
  15700. expected_type.basetype = input_type;
  15701. expected_type.width = expr_type.width;
  15702. string cast_op;
  15703. if (expr_type.basetype != input_type)
  15704. {
  15705. if (expr_type.basetype == SPIRType::Boolean)
  15706. cast_op = join(type_to_glsl(expected_type), "(", to_unpacked_expression(op0), ")");
  15707. else
  15708. cast_op = bitcast_glsl(expected_type, op0);
  15709. }
  15710. else
  15711. cast_op = to_unpacked_expression(op0);
  15712. string sg_op = join("spvClustered_", op, "<", cluster_size, ">");
  15713. string expr;
  15714. if (out_type.basetype != expected_result_type)
  15715. {
  15716. expected_type.basetype = expected_result_type;
  15717. expected_type.width = out_type.width;
  15718. if (out_type.basetype == SPIRType::Boolean)
  15719. expr = type_to_glsl(out_type);
  15720. else
  15721. expr = bitcast_glsl_op(out_type, expected_type);
  15722. expr += '(';
  15723. expr += join(sg_op, "(", cast_op, ", ", to_expression(builtin_subgroup_invocation_id_id), ")");
  15724. expr += ')';
  15725. }
  15726. else
  15727. {
  15728. expr += join(sg_op, "(", cast_op, ", ", to_expression(builtin_subgroup_invocation_id_id), ")");
  15729. }
  15730. emit_op(result_type, result_id, expr, should_forward(op0));
  15731. inherit_expression_dependencies(result_id, op0);
  15732. }
  15733. // Note: Metal forbids bitcasting to/from 'bool' using as_type. This function is used widely
  15734. // for generating casts in the backend. To avoid generating illegal MSL when the canonical
  15735. // function constant type (from deduplicated SpecId) is Boolean, fall back to value-cast in
  15736. // that case by returning type_to_glsl(out_type) instead of as_type<...>.
  15737. string CompilerMSL::bitcast_glsl_op(const SPIRType &out_type, const SPIRType &in_type)
  15738. {
  15739. if (out_type.basetype == in_type.basetype)
  15740. return "";
  15741. // Avoid bitcasting to/from booleans in MSL; use value cast instead.
  15742. if (out_type.basetype == SPIRType::Boolean || in_type.basetype == SPIRType::Boolean)
  15743. return type_to_glsl(out_type);
  15744. bool integral_cast = type_is_integral(out_type) && type_is_integral(in_type) && (out_type.vecsize == in_type.vecsize);
  15745. bool same_size_cast = (out_type.width * out_type.vecsize) == (in_type.width * in_type.vecsize);
  15746. // Bitcasting can only be used between types of the same overall size.
  15747. // And always formally cast between integers, because it's trivial, and also
  15748. // because Metal can internally cast the results of some integer ops to a larger
  15749. // size (eg. short shift right becomes int), which means chaining integer ops
  15750. // together may introduce size variations that SPIR-V doesn't know about.
  15751. if (same_size_cast && !integral_cast)
  15752. return "as_type<" + type_to_glsl(out_type) + ">";
  15753. else
  15754. return type_to_glsl(out_type);
  15755. }
  15756. bool CompilerMSL::emit_complex_bitcast(uint32_t, uint32_t, uint32_t)
  15757. {
  15758. // This is handled from the outside where we deal with PtrToU/UToPtr and friends.
  15759. return false;
  15760. }
  15761. // Returns an MSL string identifying the name of a SPIR-V builtin.
  15762. // Output builtins are qualified with the name of the stage out structure.
  15763. string CompilerMSL::builtin_to_glsl(BuiltIn builtin, StorageClass storage)
  15764. {
  15765. switch (builtin)
  15766. {
  15767. // Handle HLSL-style 0-based vertex/instance index.
  15768. // Override GLSL compiler strictness
  15769. case BuiltInVertexId:
  15770. ensure_builtin(StorageClassInput, BuiltInVertexId);
  15771. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15772. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15773. {
  15774. if (builtin_declaration)
  15775. {
  15776. if (needs_base_vertex_arg != TriState::No)
  15777. needs_base_vertex_arg = TriState::Yes;
  15778. return "gl_VertexID";
  15779. }
  15780. else
  15781. {
  15782. ensure_builtin(StorageClassInput, BuiltInBaseVertex);
  15783. return "(gl_VertexID - gl_BaseVertex)";
  15784. }
  15785. }
  15786. else
  15787. {
  15788. return "gl_VertexID";
  15789. }
  15790. case BuiltInInstanceId:
  15791. ensure_builtin(StorageClassInput, BuiltInInstanceId);
  15792. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15793. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15794. {
  15795. if (builtin_declaration)
  15796. {
  15797. if (needs_base_instance_arg != TriState::No)
  15798. needs_base_instance_arg = TriState::Yes;
  15799. return "gl_InstanceID";
  15800. }
  15801. else
  15802. {
  15803. ensure_builtin(StorageClassInput, BuiltInBaseInstance);
  15804. return "(gl_InstanceID - gl_BaseInstance)";
  15805. }
  15806. }
  15807. else
  15808. {
  15809. return "gl_InstanceID";
  15810. }
  15811. case BuiltInVertexIndex:
  15812. ensure_builtin(StorageClassInput, BuiltInVertexIndex);
  15813. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15814. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15815. {
  15816. if (builtin_declaration)
  15817. {
  15818. if (needs_base_vertex_arg != TriState::No)
  15819. needs_base_vertex_arg = TriState::Yes;
  15820. return "gl_VertexIndex";
  15821. }
  15822. else
  15823. {
  15824. ensure_builtin(StorageClassInput, BuiltInBaseVertex);
  15825. return "(gl_VertexIndex - gl_BaseVertex)";
  15826. }
  15827. }
  15828. else
  15829. {
  15830. return "gl_VertexIndex";
  15831. }
  15832. case BuiltInInstanceIndex:
  15833. ensure_builtin(StorageClassInput, BuiltInInstanceIndex);
  15834. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15835. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15836. {
  15837. if (builtin_declaration)
  15838. {
  15839. if (needs_base_instance_arg != TriState::No)
  15840. needs_base_instance_arg = TriState::Yes;
  15841. return "gl_InstanceIndex";
  15842. }
  15843. else
  15844. {
  15845. ensure_builtin(StorageClassInput, BuiltInBaseInstance);
  15846. return "(gl_InstanceIndex - gl_BaseInstance)";
  15847. }
  15848. }
  15849. else
  15850. {
  15851. return "gl_InstanceIndex";
  15852. }
  15853. case BuiltInBaseVertex:
  15854. if (msl_options.supports_msl_version(1, 1) &&
  15855. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15856. {
  15857. needs_base_vertex_arg = TriState::No;
  15858. return "gl_BaseVertex";
  15859. }
  15860. else
  15861. {
  15862. SPIRV_CROSS_THROW("BaseVertex requires Metal 1.1 and Mac or Apple A9+ hardware.");
  15863. }
  15864. case BuiltInBaseInstance:
  15865. if (msl_options.supports_msl_version(1, 1) &&
  15866. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15867. {
  15868. needs_base_instance_arg = TriState::No;
  15869. return "gl_BaseInstance";
  15870. }
  15871. else
  15872. {
  15873. SPIRV_CROSS_THROW("BaseInstance requires Metal 1.1 and Mac or Apple A9+ hardware.");
  15874. }
  15875. case BuiltInDrawIndex:
  15876. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  15877. // When used in the entry function, output builtins are qualified with output struct name.
  15878. // Test storage class as NOT Input, as output builtins might be part of generic type.
  15879. // Also don't do this for tessellation control shaders.
  15880. case BuiltInViewportIndex:
  15881. if (!msl_options.supports_msl_version(2, 0))
  15882. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  15883. /* fallthrough */
  15884. case BuiltInFragDepth:
  15885. case BuiltInFragStencilRefEXT:
  15886. if ((builtin == BuiltInFragDepth && !msl_options.enable_frag_depth_builtin) ||
  15887. (builtin == BuiltInFragStencilRefEXT && !msl_options.enable_frag_stencil_ref_builtin))
  15888. break;
  15889. /* fallthrough */
  15890. case BuiltInPosition:
  15891. case BuiltInPointSize:
  15892. case BuiltInClipDistance:
  15893. case BuiltInCullDistance:
  15894. case BuiltInLayer:
  15895. if (is_tesc_shader())
  15896. break;
  15897. if (is_mesh_shader())
  15898. break;
  15899. if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
  15900. !is_stage_output_builtin_masked(builtin))
  15901. return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
  15902. break;
  15903. case BuiltInSampleMask:
  15904. if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
  15905. (has_additional_fixed_sample_mask() || needs_sample_id))
  15906. {
  15907. string samp_mask_in;
  15908. samp_mask_in += "(" + CompilerGLSL::builtin_to_glsl(builtin, storage);
  15909. if (has_additional_fixed_sample_mask())
  15910. samp_mask_in += " & " + additional_fixed_sample_mask_str();
  15911. if (needs_sample_id)
  15912. samp_mask_in += " & (1 << gl_SampleID)";
  15913. samp_mask_in += ")";
  15914. return samp_mask_in;
  15915. }
  15916. if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
  15917. !is_stage_output_builtin_masked(builtin))
  15918. return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
  15919. break;
  15920. case BuiltInBaryCoordKHR:
  15921. case BuiltInBaryCoordNoPerspKHR:
  15922. if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point))
  15923. return stage_in_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
  15924. break;
  15925. case BuiltInTessLevelOuter:
  15926. if (is_tesc_shader() && storage != StorageClassInput && current_function &&
  15927. (current_function->self == ir.default_entry_point))
  15928. {
  15929. return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
  15930. "].edgeTessellationFactor");
  15931. }
  15932. break;
  15933. case BuiltInTessLevelInner:
  15934. if (is_tesc_shader() && storage != StorageClassInput && current_function &&
  15935. (current_function->self == ir.default_entry_point))
  15936. {
  15937. return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
  15938. "].insideTessellationFactor");
  15939. }
  15940. break;
  15941. case BuiltInHelperInvocation:
  15942. if (needs_manual_helper_invocation_updates())
  15943. break;
  15944. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  15945. SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.3 on iOS.");
  15946. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  15947. SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.1 on macOS.");
  15948. // In SPIR-V 1.6 with Volatile HelperInvocation, we cannot emit a fixup early.
  15949. return "simd_is_helper_thread()";
  15950. case BuiltInPrimitiveId:
  15951. return "gl_PrimitiveID";
  15952. default:
  15953. break;
  15954. }
  15955. return CompilerGLSL::builtin_to_glsl(builtin, storage);
  15956. }
  15957. // Returns an MSL string attribute qualifer for a SPIR-V builtin
  15958. string CompilerMSL::builtin_qualifier(BuiltIn builtin)
  15959. {
  15960. auto &execution = get_entry_point();
  15961. switch (builtin)
  15962. {
  15963. // Vertex function in
  15964. case BuiltInVertexId:
  15965. return "vertex_id";
  15966. case BuiltInVertexIndex:
  15967. return "vertex_id";
  15968. case BuiltInBaseVertex:
  15969. return "base_vertex";
  15970. case BuiltInInstanceId:
  15971. return "instance_id";
  15972. case BuiltInInstanceIndex:
  15973. return "instance_id";
  15974. case BuiltInBaseInstance:
  15975. return "base_instance";
  15976. case BuiltInDrawIndex:
  15977. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  15978. // Vertex function out
  15979. case BuiltInClipDistance:
  15980. return "clip_distance";
  15981. case BuiltInCullDistance:
  15982. return "cull_distance";
  15983. case BuiltInPointSize:
  15984. return "point_size";
  15985. case BuiltInPosition:
  15986. if (position_invariant)
  15987. {
  15988. if (!msl_options.supports_msl_version(2, 1))
  15989. SPIRV_CROSS_THROW("Invariant position is only supported on MSL 2.1 and up.");
  15990. return "position, invariant";
  15991. }
  15992. else
  15993. return "position";
  15994. case BuiltInLayer:
  15995. return "render_target_array_index";
  15996. case BuiltInViewportIndex:
  15997. if (!msl_options.supports_msl_version(2, 0))
  15998. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  15999. return "viewport_array_index";
  16000. // Tess. control function in
  16001. case BuiltInInvocationId:
  16002. if (msl_options.multi_patch_workgroup)
  16003. {
  16004. // Shouldn't be reached.
  16005. SPIRV_CROSS_THROW("InvocationId is computed manually with multi-patch workgroups in MSL.");
  16006. }
  16007. return "thread_index_in_threadgroup";
  16008. case BuiltInPatchVertices:
  16009. // Shouldn't be reached.
  16010. SPIRV_CROSS_THROW("PatchVertices is derived from the auxiliary buffer in MSL.");
  16011. case BuiltInPrimitiveId:
  16012. switch (execution.model)
  16013. {
  16014. case ExecutionModelTessellationControl:
  16015. if (msl_options.multi_patch_workgroup)
  16016. {
  16017. // Shouldn't be reached.
  16018. SPIRV_CROSS_THROW("PrimitiveId is computed manually with multi-patch workgroups in MSL.");
  16019. }
  16020. return "threadgroup_position_in_grid";
  16021. case ExecutionModelTessellationEvaluation:
  16022. return "patch_id";
  16023. case ExecutionModelFragment:
  16024. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  16025. SPIRV_CROSS_THROW("PrimitiveId on iOS requires MSL 2.3.");
  16026. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 2))
  16027. SPIRV_CROSS_THROW("PrimitiveId on macOS requires MSL 2.2.");
  16028. return "primitive_id";
  16029. case ExecutionModelMeshEXT:
  16030. return "primitive_id";
  16031. default:
  16032. SPIRV_CROSS_THROW("PrimitiveId is not supported in this execution model.");
  16033. }
  16034. // Tess. control function out
  16035. case BuiltInTessLevelOuter:
  16036. case BuiltInTessLevelInner:
  16037. // Shouldn't be reached.
  16038. SPIRV_CROSS_THROW("Tessellation levels are handled specially in MSL.");
  16039. // Tess. evaluation function in
  16040. case BuiltInTessCoord:
  16041. return "position_in_patch";
  16042. // Fragment function in
  16043. case BuiltInFrontFacing:
  16044. return "front_facing";
  16045. case BuiltInPointCoord:
  16046. return "point_coord";
  16047. case BuiltInFragCoord:
  16048. return "position";
  16049. case BuiltInSampleId:
  16050. return "sample_id";
  16051. case BuiltInSampleMask:
  16052. return "sample_mask";
  16053. case BuiltInSamplePosition:
  16054. // Shouldn't be reached.
  16055. SPIRV_CROSS_THROW("Sample position is retrieved by a function in MSL.");
  16056. case BuiltInViewIndex:
  16057. if (execution.model != ExecutionModelFragment && execution.model != ExecutionModelMeshEXT)
  16058. SPIRV_CROSS_THROW("ViewIndex is handled specially outside fragment shaders.");
  16059. // The ViewIndex was implicitly used in the prior stages to set the render_target_array_index,
  16060. // so we can get it from there.
  16061. return "render_target_array_index";
  16062. // Fragment function out
  16063. case BuiltInFragDepth:
  16064. if (execution.flags.get(ExecutionModeDepthGreater))
  16065. return "depth(greater)";
  16066. else if (execution.flags.get(ExecutionModeDepthLess))
  16067. return "depth(less)";
  16068. else
  16069. return "depth(any)";
  16070. case BuiltInFragStencilRefEXT:
  16071. return "stencil";
  16072. // Compute function in
  16073. case BuiltInGlobalInvocationId:
  16074. return "thread_position_in_grid";
  16075. case BuiltInWorkgroupSize:
  16076. return "threads_per_threadgroup";
  16077. case BuiltInWorkgroupId:
  16078. return "threadgroup_position_in_grid";
  16079. case BuiltInNumWorkgroups:
  16080. return "threadgroups_per_grid";
  16081. case BuiltInLocalInvocationId:
  16082. return "thread_position_in_threadgroup";
  16083. case BuiltInLocalInvocationIndex:
  16084. return "thread_index_in_threadgroup";
  16085. case BuiltInSubgroupSize:
  16086. if (msl_options.emulate_subgroups || msl_options.fixed_subgroup_size != 0)
  16087. // Shouldn't be reached.
  16088. SPIRV_CROSS_THROW("Emitting threads_per_simdgroup attribute with fixed subgroup size??");
  16089. if (execution.model == ExecutionModelFragment)
  16090. {
  16091. if (!msl_options.supports_msl_version(2, 2))
  16092. SPIRV_CROSS_THROW("threads_per_simdgroup requires Metal 2.2 in fragment shaders.");
  16093. return "threads_per_simdgroup";
  16094. }
  16095. else
  16096. {
  16097. // thread_execution_width is an alias for threads_per_simdgroup, and it's only available since 1.0,
  16098. // but not in fragment.
  16099. if (msl_options.supports_msl_version(3, 0))
  16100. return "threads_per_simdgroup";
  16101. else
  16102. return "thread_execution_width";
  16103. }
  16104. case BuiltInNumSubgroups:
  16105. if (msl_options.emulate_subgroups)
  16106. // Shouldn't be reached.
  16107. SPIRV_CROSS_THROW("NumSubgroups is handled specially with emulation.");
  16108. if (!msl_options.supports_msl_version(2))
  16109. SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0.");
  16110. return msl_options.use_quadgroup_operation() ? "quadgroups_per_threadgroup" : "simdgroups_per_threadgroup";
  16111. case BuiltInSubgroupId:
  16112. if (msl_options.emulate_subgroups)
  16113. // Shouldn't be reached.
  16114. SPIRV_CROSS_THROW("SubgroupId is handled specially with emulation.");
  16115. if (!msl_options.supports_msl_version(2))
  16116. SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0.");
  16117. return msl_options.use_quadgroup_operation() ? "quadgroup_index_in_threadgroup" : "simdgroup_index_in_threadgroup";
  16118. case BuiltInSubgroupLocalInvocationId:
  16119. if (msl_options.emulate_subgroups)
  16120. // Shouldn't be reached.
  16121. SPIRV_CROSS_THROW("SubgroupLocalInvocationId is handled specially with emulation.");
  16122. if (execution.model == ExecutionModelFragment)
  16123. {
  16124. if (!msl_options.supports_msl_version(2, 2))
  16125. SPIRV_CROSS_THROW("thread_index_in_simdgroup requires Metal 2.2 in fragment shaders.");
  16126. return "thread_index_in_simdgroup";
  16127. }
  16128. else if (execution.model == ExecutionModelKernel || execution.model == ExecutionModelGLCompute ||
  16129. execution.model == ExecutionModelTaskEXT || execution.model == ExecutionModelMeshEXT ||
  16130. execution.model == ExecutionModelTessellationControl ||
  16131. (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation))
  16132. {
  16133. // We are generating a Metal kernel function.
  16134. if (!msl_options.supports_msl_version(2))
  16135. SPIRV_CROSS_THROW("Subgroup builtins in kernel functions require Metal 2.0.");
  16136. return msl_options.use_quadgroup_operation() ? "thread_index_in_quadgroup" : "thread_index_in_simdgroup";
  16137. }
  16138. else
  16139. SPIRV_CROSS_THROW("Subgroup builtins are not available in this type of function.");
  16140. case BuiltInSubgroupEqMask:
  16141. case BuiltInSubgroupGeMask:
  16142. case BuiltInSubgroupGtMask:
  16143. case BuiltInSubgroupLeMask:
  16144. case BuiltInSubgroupLtMask:
  16145. // Shouldn't be reached.
  16146. SPIRV_CROSS_THROW("Subgroup ballot masks are handled specially in MSL.");
  16147. case BuiltInBaryCoordKHR:
  16148. case BuiltInBaryCoordNoPerspKHR:
  16149. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  16150. SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.3 and above on iOS.");
  16151. else if (!msl_options.supports_msl_version(2, 2))
  16152. SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.2 and above on macOS.");
  16153. return "barycentric_coord";
  16154. case BuiltInCullPrimitiveEXT:
  16155. return "primitive_culled";
  16156. default:
  16157. return "unsupported-built-in";
  16158. }
  16159. }
  16160. // Returns an MSL string type declaration for a SPIR-V builtin
  16161. string CompilerMSL::builtin_type_decl(BuiltIn builtin, uint32_t id)
  16162. {
  16163. switch (builtin)
  16164. {
  16165. // Vertex function in
  16166. case BuiltInVertexId:
  16167. return "uint";
  16168. case BuiltInVertexIndex:
  16169. return "uint";
  16170. case BuiltInBaseVertex:
  16171. return "uint";
  16172. case BuiltInInstanceId:
  16173. return "uint";
  16174. case BuiltInInstanceIndex:
  16175. return "uint";
  16176. case BuiltInBaseInstance:
  16177. return "uint";
  16178. case BuiltInDrawIndex:
  16179. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  16180. // Vertex function out
  16181. case BuiltInClipDistance:
  16182. case BuiltInCullDistance:
  16183. return "float";
  16184. case BuiltInPointSize:
  16185. return "float";
  16186. case BuiltInPosition:
  16187. return "float4";
  16188. case BuiltInLayer:
  16189. return "uint";
  16190. case BuiltInViewportIndex:
  16191. if (!msl_options.supports_msl_version(2, 0))
  16192. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  16193. return "uint";
  16194. // Tess. control function in
  16195. case BuiltInInvocationId:
  16196. return "uint";
  16197. case BuiltInPatchVertices:
  16198. return "uint";
  16199. case BuiltInPrimitiveId:
  16200. return "uint";
  16201. // Tess. control function out
  16202. case BuiltInTessLevelInner:
  16203. if (is_tese_shader())
  16204. return (msl_options.raw_buffer_tese_input || is_tessellating_triangles()) ? "float" : "float2";
  16205. return "half";
  16206. case BuiltInTessLevelOuter:
  16207. if (is_tese_shader())
  16208. return (msl_options.raw_buffer_tese_input || is_tessellating_triangles()) ? "float" : "float4";
  16209. return "half";
  16210. // Tess. evaluation function in
  16211. case BuiltInTessCoord:
  16212. return "float3";
  16213. // Fragment function in
  16214. case BuiltInFrontFacing:
  16215. return "bool";
  16216. case BuiltInPointCoord:
  16217. return "float2";
  16218. case BuiltInFragCoord:
  16219. return "float4";
  16220. case BuiltInSampleId:
  16221. return "uint";
  16222. case BuiltInSampleMask:
  16223. return "uint";
  16224. case BuiltInSamplePosition:
  16225. return "float2";
  16226. case BuiltInViewIndex:
  16227. return "uint";
  16228. case BuiltInHelperInvocation:
  16229. return "bool";
  16230. case BuiltInBaryCoordKHR:
  16231. case BuiltInBaryCoordNoPerspKHR:
  16232. // Use the type as declared, can be 1, 2 or 3 components.
  16233. return type_to_glsl(get_variable_data_type(get<SPIRVariable>(id)));
  16234. // Fragment function out
  16235. case BuiltInFragDepth:
  16236. return "float";
  16237. case BuiltInFragStencilRefEXT:
  16238. return "uint";
  16239. // Compute function in
  16240. case BuiltInGlobalInvocationId:
  16241. case BuiltInLocalInvocationId:
  16242. case BuiltInNumWorkgroups:
  16243. case BuiltInWorkgroupId:
  16244. case BuiltInWorkgroupSize:
  16245. return "uint3";
  16246. case BuiltInLocalInvocationIndex:
  16247. case BuiltInNumSubgroups:
  16248. case BuiltInSubgroupId:
  16249. case BuiltInSubgroupSize:
  16250. case BuiltInSubgroupLocalInvocationId:
  16251. return "uint";
  16252. case BuiltInSubgroupEqMask:
  16253. case BuiltInSubgroupGeMask:
  16254. case BuiltInSubgroupGtMask:
  16255. case BuiltInSubgroupLeMask:
  16256. case BuiltInSubgroupLtMask:
  16257. return "uint4";
  16258. case BuiltInDeviceIndex:
  16259. return "int";
  16260. case BuiltInPrimitivePointIndicesEXT:
  16261. return "uint";
  16262. case BuiltInPrimitiveLineIndicesEXT:
  16263. return "uint2";
  16264. case BuiltInPrimitiveTriangleIndicesEXT:
  16265. return "uint3";
  16266. default:
  16267. return "unsupported-built-in-type";
  16268. }
  16269. }
  16270. // Returns the declaration of a built-in argument to a function
  16271. string CompilerMSL::built_in_func_arg(BuiltIn builtin, bool prefix_comma)
  16272. {
  16273. string bi_arg;
  16274. if (prefix_comma)
  16275. bi_arg += ", ";
  16276. // Handle HLSL-style 0-based vertex/instance index.
  16277. builtin_declaration = true;
  16278. bi_arg += builtin_type_decl(builtin);
  16279. bi_arg += string(" ") + builtin_to_glsl(builtin, StorageClassInput);
  16280. bi_arg += string(" [[") + builtin_qualifier(builtin) + string("]]");
  16281. builtin_declaration = false;
  16282. return bi_arg;
  16283. }
  16284. const SPIRType &CompilerMSL::get_physical_member_type(const SPIRType &type, uint32_t index) const
  16285. {
  16286. if (member_is_remapped_physical_type(type, index))
  16287. return get<SPIRType>(get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID));
  16288. else
  16289. return get<SPIRType>(type.member_types[index]);
  16290. }
  16291. SPIRType CompilerMSL::get_presumed_input_type(const SPIRType &ib_type, uint32_t index) const
  16292. {
  16293. SPIRType type = get_physical_member_type(ib_type, index);
  16294. uint32_t loc = get_member_decoration(ib_type.self, index, DecorationLocation);
  16295. uint32_t cmp = get_member_decoration(ib_type.self, index, DecorationComponent);
  16296. auto p_va = inputs_by_location.find({loc, cmp});
  16297. if (p_va != end(inputs_by_location) && p_va->second.vecsize > type.vecsize)
  16298. type.vecsize = p_va->second.vecsize;
  16299. return type;
  16300. }
  16301. uint32_t CompilerMSL::get_declared_type_array_stride_msl(const SPIRType &type, bool is_packed, bool row_major) const
  16302. {
  16303. // Array stride in MSL is always size * array_size. sizeof(float3) == 16,
  16304. // unlike GLSL and HLSL where array stride would be 16 and size 12.
  16305. // We could use parent type here and recurse, but that makes creating physical type remappings
  16306. // far more complicated. We'd rather just create the final type, and ignore having to create the entire type
  16307. // hierarchy in order to compute this value, so make a temporary type on the stack.
  16308. auto basic_type = type;
  16309. basic_type.array.clear();
  16310. basic_type.array_size_literal.clear();
  16311. uint32_t value_size = get_declared_type_size_msl(basic_type, is_packed, row_major);
  16312. uint32_t dimensions = uint32_t(type.array.size());
  16313. assert(dimensions > 0);
  16314. dimensions--;
  16315. // Multiply together every dimension, except the last one.
  16316. for (uint32_t dim = 0; dim < dimensions; dim++)
  16317. {
  16318. uint32_t array_size = to_array_size_literal(type, dim);
  16319. value_size *= max<uint32_t>(array_size, 1u);
  16320. }
  16321. return value_size;
  16322. }
  16323. uint32_t CompilerMSL::get_declared_struct_member_array_stride_msl(const SPIRType &type, uint32_t index) const
  16324. {
  16325. return get_declared_type_array_stride_msl(get_physical_member_type(type, index),
  16326. member_is_packed_physical_type(type, index),
  16327. has_member_decoration(type.self, index, DecorationRowMajor));
  16328. }
  16329. uint32_t CompilerMSL::get_declared_input_array_stride_msl(const SPIRType &type, uint32_t index) const
  16330. {
  16331. return get_declared_type_array_stride_msl(get_presumed_input_type(type, index), false,
  16332. has_member_decoration(type.self, index, DecorationRowMajor));
  16333. }
  16334. uint32_t CompilerMSL::get_declared_type_matrix_stride_msl(const SPIRType &type, bool packed, bool row_major) const
  16335. {
  16336. // For packed matrices, we just use the size of the vector type.
  16337. // Otherwise, MatrixStride == alignment, which is the size of the underlying vector type.
  16338. if (packed)
  16339. return (type.width / 8) * ((row_major && type.columns > 1) ? type.columns : type.vecsize);
  16340. else
  16341. return get_declared_type_alignment_msl(type, false, row_major);
  16342. }
  16343. uint32_t CompilerMSL::get_declared_struct_member_matrix_stride_msl(const SPIRType &type, uint32_t index) const
  16344. {
  16345. return get_declared_type_matrix_stride_msl(get_physical_member_type(type, index),
  16346. member_is_packed_physical_type(type, index),
  16347. has_member_decoration(type.self, index, DecorationRowMajor));
  16348. }
  16349. uint32_t CompilerMSL::get_declared_input_matrix_stride_msl(const SPIRType &type, uint32_t index) const
  16350. {
  16351. return get_declared_type_matrix_stride_msl(get_presumed_input_type(type, index), false,
  16352. has_member_decoration(type.self, index, DecorationRowMajor));
  16353. }
  16354. uint32_t CompilerMSL::get_declared_struct_size_msl(const SPIRType &struct_type, bool ignore_alignment,
  16355. bool ignore_padding) const
  16356. {
  16357. // If we have a target size, that is the declared size as well.
  16358. if (!ignore_padding && has_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget))
  16359. return get_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget);
  16360. if (struct_type.member_types.empty())
  16361. return 0;
  16362. uint32_t mbr_cnt = uint32_t(struct_type.member_types.size());
  16363. // In MSL, a struct's alignment is equal to the maximum alignment of any of its members.
  16364. uint32_t alignment = 1;
  16365. if (!ignore_alignment)
  16366. {
  16367. for (uint32_t i = 0; i < mbr_cnt; i++)
  16368. {
  16369. uint32_t mbr_alignment = get_declared_struct_member_alignment_msl(struct_type, i);
  16370. alignment = max(alignment, mbr_alignment);
  16371. }
  16372. }
  16373. // Last member will always be matched to the final Offset decoration, but size of struct in MSL now depends
  16374. // on physical size in MSL, and the size of the struct itself is then aligned to struct alignment.
  16375. uint32_t spirv_offset = type_struct_member_offset(struct_type, mbr_cnt - 1);
  16376. uint32_t msl_size = spirv_offset + get_declared_struct_member_size_msl(struct_type, mbr_cnt - 1);
  16377. msl_size = (msl_size + alignment - 1) & ~(alignment - 1);
  16378. return msl_size;
  16379. }
  16380. uint32_t CompilerMSL::get_physical_type_stride(const SPIRType &type) const
  16381. {
  16382. // This should only be relevant for plain types such as scalars and vectors?
  16383. // If we're pointing to a struct, it will recursively pick up packed/row-major state.
  16384. return get_declared_type_size_msl(type, false, false);
  16385. }
  16386. // Returns the byte size of a struct member.
  16387. uint32_t CompilerMSL::get_declared_type_size_msl(const SPIRType &type, bool is_packed, bool row_major) const
  16388. {
  16389. // Pointers take 8 bytes each
  16390. // Match both pointer and array-of-pointer here.
  16391. if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  16392. {
  16393. uint32_t type_size = 8;
  16394. // Work our way through potentially layered arrays,
  16395. // stopping when we hit a pointer that is not also an array.
  16396. int32_t dim_idx = (int32_t)type.array.size() - 1;
  16397. auto *p_type = &type;
  16398. while (!is_pointer(*p_type) && dim_idx >= 0)
  16399. {
  16400. type_size *= to_array_size_literal(*p_type, dim_idx);
  16401. p_type = &get<SPIRType>(p_type->parent_type);
  16402. dim_idx--;
  16403. }
  16404. return type_size;
  16405. }
  16406. switch (type.basetype)
  16407. {
  16408. case SPIRType::Unknown:
  16409. case SPIRType::Void:
  16410. case SPIRType::AtomicCounter:
  16411. case SPIRType::Image:
  16412. case SPIRType::SampledImage:
  16413. case SPIRType::Sampler:
  16414. SPIRV_CROSS_THROW("Querying size of opaque object.");
  16415. default:
  16416. {
  16417. if (!type.array.empty())
  16418. {
  16419. uint32_t array_size = to_array_size_literal(type);
  16420. return get_declared_type_array_stride_msl(type, is_packed, row_major) * max<uint32_t>(array_size, 1u);
  16421. }
  16422. if (type.basetype == SPIRType::Struct)
  16423. return get_declared_struct_size_msl(type);
  16424. if (is_packed)
  16425. {
  16426. return type.vecsize * type.columns * (type.width / 8);
  16427. }
  16428. else
  16429. {
  16430. // An unpacked 3-element vector or matrix column is the same memory size as a 4-element.
  16431. uint32_t vecsize = type.vecsize;
  16432. uint32_t columns = type.columns;
  16433. if (row_major && columns > 1)
  16434. swap(vecsize, columns);
  16435. if (vecsize == 3)
  16436. vecsize = 4;
  16437. return vecsize * columns * (type.width / 8);
  16438. }
  16439. }
  16440. }
  16441. }
  16442. uint32_t CompilerMSL::get_declared_struct_member_size_msl(const SPIRType &type, uint32_t index) const
  16443. {
  16444. return get_declared_type_size_msl(get_physical_member_type(type, index),
  16445. member_is_packed_physical_type(type, index),
  16446. has_member_decoration(type.self, index, DecorationRowMajor));
  16447. }
  16448. uint32_t CompilerMSL::get_declared_input_size_msl(const SPIRType &type, uint32_t index) const
  16449. {
  16450. return get_declared_type_size_msl(get_presumed_input_type(type, index), false,
  16451. has_member_decoration(type.self, index, DecorationRowMajor));
  16452. }
  16453. // Returns the byte alignment of a type.
  16454. uint32_t CompilerMSL::get_declared_type_alignment_msl(const SPIRType &type, bool is_packed, bool row_major) const
  16455. {
  16456. // Pointers align on multiples of 8 bytes.
  16457. // Deliberately ignore array-ness here. It's not relevant for alignment.
  16458. if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  16459. return 8;
  16460. switch (type.basetype)
  16461. {
  16462. case SPIRType::Unknown:
  16463. case SPIRType::Void:
  16464. case SPIRType::AtomicCounter:
  16465. case SPIRType::Image:
  16466. case SPIRType::SampledImage:
  16467. case SPIRType::Sampler:
  16468. SPIRV_CROSS_THROW("Querying alignment of opaque object.");
  16469. case SPIRType::Double:
  16470. SPIRV_CROSS_THROW("double types are not supported in buffers in MSL.");
  16471. case SPIRType::Struct:
  16472. {
  16473. // In MSL, a struct's alignment is equal to the maximum alignment of any of its members.
  16474. uint32_t alignment = 1;
  16475. for (uint32_t i = 0; i < type.member_types.size(); i++)
  16476. alignment = max(alignment, uint32_t(get_declared_struct_member_alignment_msl(type, i)));
  16477. return alignment;
  16478. }
  16479. default:
  16480. {
  16481. if (type.basetype == SPIRType::Int64 && !msl_options.supports_msl_version(2, 3))
  16482. SPIRV_CROSS_THROW("long types in buffers are only supported in MSL 2.3 and above.");
  16483. if (type.basetype == SPIRType::UInt64 && !msl_options.supports_msl_version(2, 3))
  16484. SPIRV_CROSS_THROW("ulong types in buffers are only supported in MSL 2.3 and above.");
  16485. // Alignment of packed type is the same as the underlying component or column size.
  16486. // Alignment of unpacked type is the same as the vector size.
  16487. // Alignment of 3-elements vector is the same as 4-elements (including packed using column).
  16488. if (is_packed)
  16489. {
  16490. // If we have packed_T and friends, the alignment is always scalar.
  16491. return type.width / 8;
  16492. }
  16493. else
  16494. {
  16495. // This is the general rule for MSL. Size == alignment.
  16496. uint32_t vecsize = (row_major && type.columns > 1) ? type.columns : type.vecsize;
  16497. return (type.width / 8) * (vecsize == 3 ? 4 : vecsize);
  16498. }
  16499. }
  16500. }
  16501. }
  16502. uint32_t CompilerMSL::get_declared_struct_member_alignment_msl(const SPIRType &type, uint32_t index) const
  16503. {
  16504. return get_declared_type_alignment_msl(get_physical_member_type(type, index),
  16505. member_is_packed_physical_type(type, index),
  16506. has_member_decoration(type.self, index, DecorationRowMajor));
  16507. }
  16508. uint32_t CompilerMSL::get_declared_input_alignment_msl(const SPIRType &type, uint32_t index) const
  16509. {
  16510. return get_declared_type_alignment_msl(get_presumed_input_type(type, index), false,
  16511. has_member_decoration(type.self, index, DecorationRowMajor));
  16512. }
  16513. bool CompilerMSL::skip_argument(uint32_t) const
  16514. {
  16515. return false;
  16516. }
  16517. void CompilerMSL::analyze_sampled_image_usage()
  16518. {
  16519. if (msl_options.swizzle_texture_samples)
  16520. {
  16521. SampledImageScanner scanner(*this);
  16522. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), scanner);
  16523. }
  16524. }
  16525. void CompilerMSL::analyze_workgroup_variables()
  16526. {
  16527. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  16528. // If workgroup variables have initializer, it can only be ConstantNull (zero init)
  16529. if (var.storage == StorageClassWorkgroup && var.initializer)
  16530. {
  16531. needs_workgroup_zero_init = true;
  16532. // MSL compiler does not like the routine to initialize simple threadgroup variables,
  16533. // falsely claiming it is "sometimes uninitialized". Suppress it.
  16534. auto &type = get_variable_data_type(var);
  16535. if (type.array.empty() && type.member_types.empty())
  16536. suppress_sometimes_unitialized = true;
  16537. }
  16538. });
  16539. }
  16540. bool CompilerMSL::SampledImageScanner::handle(Op opcode, const uint32_t *args, uint32_t length)
  16541. {
  16542. switch (opcode)
  16543. {
  16544. case OpLoad:
  16545. case OpImage:
  16546. case OpSampledImage:
  16547. {
  16548. if (length < 3)
  16549. return false;
  16550. uint32_t result_type = args[0];
  16551. auto &type = get<SPIRType>(result_type);
  16552. if ((type.basetype != SPIRType::Image && type.basetype != SPIRType::SampledImage) || type.image.sampled != 1)
  16553. return true;
  16554. uint32_t id = args[1];
  16555. set<SPIRExpression>(id, "", result_type, true);
  16556. break;
  16557. }
  16558. case OpImageSampleExplicitLod:
  16559. case OpImageSampleProjExplicitLod:
  16560. case OpImageSampleDrefExplicitLod:
  16561. case OpImageSampleProjDrefExplicitLod:
  16562. case OpImageSampleImplicitLod:
  16563. case OpImageSampleProjImplicitLod:
  16564. case OpImageSampleDrefImplicitLod:
  16565. case OpImageSampleProjDrefImplicitLod:
  16566. case OpImageFetch:
  16567. case OpImageGather:
  16568. case OpImageDrefGather:
  16569. self.has_sampled_images =
  16570. self.has_sampled_images || self.is_sampled_image_type(self.expression_type(args[2]));
  16571. self.needs_swizzle_buffer_def = self.needs_swizzle_buffer_def || self.has_sampled_images;
  16572. break;
  16573. default:
  16574. break;
  16575. }
  16576. return true;
  16577. }
  16578. // If a needed custom function wasn't added before, add it and force a recompile.
  16579. void CompilerMSL::add_spv_func_and_recompile(SPVFuncImpl spv_func)
  16580. {
  16581. if (spv_function_implementations.count(spv_func) == 0)
  16582. {
  16583. spv_function_implementations.insert(spv_func);
  16584. suppress_missing_prototypes = true;
  16585. force_recompile();
  16586. }
  16587. }
  16588. bool CompilerMSL::OpCodePreprocessor::handle(Op opcode, const uint32_t *args, uint32_t length)
  16589. {
  16590. // Since MSL exists in a single execution scope, function prototype declarations are not
  16591. // needed, and clutter the output. If secondary functions are output (either as a SPIR-V
  16592. // function implementation or as indicated by the presence of OpFunctionCall), then set
  16593. // suppress_missing_prototypes to suppress compiler warnings of missing function prototypes.
  16594. // Mark if the input requires the implementation of an SPIR-V function that does not exist in Metal.
  16595. SPVFuncImpl spv_func = get_spv_func_impl(opcode, args, length);
  16596. if (spv_func != SPVFuncImplNone)
  16597. {
  16598. self.spv_function_implementations.insert(spv_func);
  16599. suppress_missing_prototypes = true;
  16600. }
  16601. switch (opcode)
  16602. {
  16603. case OpFunctionCall:
  16604. suppress_missing_prototypes = true;
  16605. break;
  16606. case OpDemoteToHelperInvocationEXT:
  16607. uses_discard = true;
  16608. break;
  16609. // Emulate texture2D atomic operations
  16610. case OpImageTexelPointer:
  16611. {
  16612. if (!self.msl_options.supports_msl_version(3, 1))
  16613. {
  16614. auto *var = self.maybe_get_backing_variable(args[2]);
  16615. image_pointers_emulated[args[1]] = var ? var->self : ID(0);
  16616. }
  16617. break;
  16618. }
  16619. case OpImageWrite:
  16620. uses_image_write = true;
  16621. break;
  16622. case OpStore:
  16623. check_resource_write(args[0]);
  16624. break;
  16625. // Emulate texture2D atomic operations
  16626. case OpAtomicExchange:
  16627. case OpAtomicCompareExchange:
  16628. case OpAtomicCompareExchangeWeak:
  16629. case OpAtomicIIncrement:
  16630. case OpAtomicIDecrement:
  16631. case OpAtomicIAdd:
  16632. case OpAtomicFAddEXT:
  16633. case OpAtomicISub:
  16634. case OpAtomicSMin:
  16635. case OpAtomicUMin:
  16636. case OpAtomicSMax:
  16637. case OpAtomicUMax:
  16638. case OpAtomicAnd:
  16639. case OpAtomicOr:
  16640. case OpAtomicXor:
  16641. {
  16642. uses_atomics = true;
  16643. auto it = image_pointers_emulated.find(args[2]);
  16644. if (it != image_pointers_emulated.end())
  16645. {
  16646. uses_image_write = true;
  16647. self.atomic_image_vars_emulated.insert(it->second);
  16648. }
  16649. else
  16650. check_resource_write(args[2]);
  16651. break;
  16652. }
  16653. case OpAtomicStore:
  16654. {
  16655. uses_atomics = true;
  16656. auto it = image_pointers_emulated.find(args[0]);
  16657. if (it != image_pointers_emulated.end())
  16658. {
  16659. self.atomic_image_vars_emulated.insert(it->second);
  16660. uses_image_write = true;
  16661. }
  16662. else
  16663. check_resource_write(args[0]);
  16664. break;
  16665. }
  16666. case OpAtomicLoad:
  16667. {
  16668. uses_atomics = true;
  16669. auto it = image_pointers_emulated.find(args[2]);
  16670. if (it != image_pointers_emulated.end())
  16671. {
  16672. self.atomic_image_vars_emulated.insert(it->second);
  16673. }
  16674. break;
  16675. }
  16676. case OpGroupNonUniformInverseBallot:
  16677. needs_subgroup_invocation_id = true;
  16678. break;
  16679. case OpGroupNonUniformBallotFindLSB:
  16680. case OpGroupNonUniformBallotFindMSB:
  16681. needs_subgroup_size = true;
  16682. break;
  16683. case OpGroupNonUniformBallotBitCount:
  16684. if (args[3] == GroupOperationReduce)
  16685. needs_subgroup_size = true;
  16686. else
  16687. needs_subgroup_invocation_id = true;
  16688. break;
  16689. case OpGroupNonUniformRotateKHR:
  16690. // Add the correct invocation ID for calculating clustered rotate case.
  16691. if (length > 5)
  16692. {
  16693. if (static_cast<Scope>(self.evaluate_constant_u32(args[2])) == ScopeSubgroup)
  16694. needs_subgroup_invocation_id = true;
  16695. else
  16696. needs_local_invocation_index = true;
  16697. }
  16698. break;
  16699. case OpGroupNonUniformFAdd:
  16700. case OpGroupNonUniformFMul:
  16701. case OpGroupNonUniformFMin:
  16702. case OpGroupNonUniformFMax:
  16703. case OpGroupNonUniformIAdd:
  16704. case OpGroupNonUniformIMul:
  16705. case OpGroupNonUniformSMin:
  16706. case OpGroupNonUniformSMax:
  16707. case OpGroupNonUniformUMin:
  16708. case OpGroupNonUniformUMax:
  16709. case OpGroupNonUniformBitwiseAnd:
  16710. case OpGroupNonUniformBitwiseOr:
  16711. case OpGroupNonUniformBitwiseXor:
  16712. case OpGroupNonUniformLogicalAnd:
  16713. case OpGroupNonUniformLogicalOr:
  16714. case OpGroupNonUniformLogicalXor:
  16715. if ((compiler.get_execution_model() != ExecutionModelFragment ||
  16716. self.msl_options.supports_msl_version(2, 2)) &&
  16717. args[3] == GroupOperationClusteredReduce)
  16718. needs_subgroup_invocation_id = true;
  16719. break;
  16720. case OpArrayLength:
  16721. {
  16722. auto *var = self.maybe_get_backing_variable(args[2]);
  16723. if (var != nullptr)
  16724. {
  16725. if (!self.is_var_runtime_size_array(*var))
  16726. self.buffers_requiring_array_length.insert(var->self);
  16727. }
  16728. break;
  16729. }
  16730. case OpInBoundsAccessChain:
  16731. case OpAccessChain:
  16732. case OpPtrAccessChain:
  16733. {
  16734. // OpArrayLength might want to know if taking ArrayLength of an array of SSBOs.
  16735. uint32_t result_type = args[0];
  16736. uint32_t id = args[1];
  16737. uint32_t ptr = args[2];
  16738. set<SPIRExpression>(id, "", result_type, true);
  16739. self.register_read(id, ptr, true);
  16740. self.ir.ids[id].set_allow_type_rewrite();
  16741. break;
  16742. }
  16743. case OpExtInst:
  16744. {
  16745. uint32_t extension_set = args[2];
  16746. SPIRExtension::Extension ext = get<SPIRExtension>(extension_set).ext;
  16747. if (ext == SPIRExtension::GLSL)
  16748. {
  16749. auto op_450 = static_cast<GLSLstd450>(args[3]);
  16750. switch (op_450)
  16751. {
  16752. case GLSLstd450InterpolateAtCentroid:
  16753. case GLSLstd450InterpolateAtSample:
  16754. case GLSLstd450InterpolateAtOffset:
  16755. {
  16756. if (!self.msl_options.supports_msl_version(2, 3))
  16757. SPIRV_CROSS_THROW("Pull-model interpolation requires MSL 2.3.");
  16758. // Fragment varyings used with pull-model interpolation need special handling,
  16759. // due to the way pull-model interpolation works in Metal.
  16760. auto *var = self.maybe_get_backing_variable(args[4]);
  16761. if (var)
  16762. {
  16763. self.pull_model_inputs.insert(var->self);
  16764. auto &var_type = self.get_variable_element_type(*var);
  16765. // In addition, if this variable has a 'Sample' decoration, we need the sample ID
  16766. // in order to do default interpolation.
  16767. if (compiler.has_decoration(var->self, DecorationSample))
  16768. {
  16769. needs_sample_id = true;
  16770. }
  16771. else if (var_type.basetype == SPIRType::Struct)
  16772. {
  16773. // Now we need to check each member and see if it has this decoration.
  16774. for (uint32_t i = 0; i < var_type.member_types.size(); ++i)
  16775. {
  16776. if (compiler.has_member_decoration(var_type.self, i, DecorationSample))
  16777. {
  16778. needs_sample_id = true;
  16779. break;
  16780. }
  16781. }
  16782. }
  16783. }
  16784. break;
  16785. }
  16786. default:
  16787. break;
  16788. }
  16789. }
  16790. else if (ext == SPIRExtension::NonSemanticDebugPrintf)
  16791. {
  16792. // Operation 1 is printf.
  16793. if (args[3] == 1 && !self.msl_options.supports_msl_version(3, 2))
  16794. SPIRV_CROSS_THROW("Debug printf requires MSL 3.2.");
  16795. }
  16796. break;
  16797. }
  16798. case OpIsHelperInvocationEXT:
  16799. if (self.needs_manual_helper_invocation_updates())
  16800. needs_helper_invocation = true;
  16801. break;
  16802. default:
  16803. break;
  16804. }
  16805. return true;
  16806. }
  16807. // If the variable is a Uniform or StorageBuffer, mark that a resource has been written to.
  16808. void CompilerMSL::OpCodePreprocessor::check_resource_write(uint32_t var_id)
  16809. {
  16810. auto *type = get_expression_result_type(var_id);
  16811. auto sc = StorageClassMax;
  16812. if (type)
  16813. {
  16814. sc = type->storage;
  16815. }
  16816. else
  16817. {
  16818. auto *var = self.maybe_get_backing_variable(var_id);
  16819. if (var)
  16820. sc = var->storage;
  16821. }
  16822. if (sc == StorageClassUniform || sc == StorageClassStorageBuffer || sc == StorageClassPhysicalStorageBuffer)
  16823. uses_buffer_write = true;
  16824. }
  16825. // Returns an enumeration of a SPIR-V function that needs to be output for certain Op codes.
  16826. CompilerMSL::SPVFuncImpl CompilerMSL::OpCodePreprocessor::get_spv_func_impl(Op opcode, const uint32_t *args, uint32_t length)
  16827. {
  16828. switch (opcode)
  16829. {
  16830. case OpSMod:
  16831. return SPVFuncImplSMod;
  16832. case OpFMod:
  16833. return SPVFuncImplMod;
  16834. case OpFAdd:
  16835. case OpFSub:
  16836. if (self.msl_options.invariant_float_math || self.has_legacy_nocontract(args[0], args[1]))
  16837. return opcode == OpFAdd ? SPVFuncImplFAdd : SPVFuncImplFSub;
  16838. break;
  16839. case OpFMul:
  16840. case OpOuterProduct:
  16841. case OpMatrixTimesVector:
  16842. case OpVectorTimesMatrix:
  16843. case OpMatrixTimesMatrix:
  16844. if (self.msl_options.invariant_float_math || self.has_legacy_nocontract(args[0], args[1]))
  16845. return SPVFuncImplFMul;
  16846. break;
  16847. case OpQuantizeToF16:
  16848. return SPVFuncImplQuantizeToF16;
  16849. case OpTypeArray:
  16850. {
  16851. // Allow Metal to use the array<T> template to make arrays a value type
  16852. return SPVFuncImplUnsafeArray;
  16853. }
  16854. // Emulate texture2D atomic operations
  16855. case OpAtomicExchange:
  16856. case OpAtomicCompareExchange:
  16857. case OpAtomicCompareExchangeWeak:
  16858. case OpAtomicIIncrement:
  16859. case OpAtomicIDecrement:
  16860. case OpAtomicIAdd:
  16861. case OpAtomicFAddEXT:
  16862. case OpAtomicISub:
  16863. case OpAtomicSMin:
  16864. case OpAtomicUMin:
  16865. case OpAtomicSMax:
  16866. case OpAtomicUMax:
  16867. case OpAtomicAnd:
  16868. case OpAtomicOr:
  16869. case OpAtomicXor:
  16870. case OpAtomicLoad:
  16871. case OpAtomicStore:
  16872. {
  16873. auto it = image_pointers_emulated.find(args[opcode == OpAtomicStore ? 0 : 2]);
  16874. if (it != image_pointers_emulated.end())
  16875. {
  16876. uint32_t tid = get<SPIRVariable>(it->second).basetype;
  16877. if (tid && get<SPIRType>(tid).image.dim == Dim2D)
  16878. return SPVFuncImplImage2DAtomicCoords;
  16879. }
  16880. break;
  16881. }
  16882. case OpImageFetch:
  16883. case OpImageRead:
  16884. case OpImageWrite:
  16885. {
  16886. // Retrieve the image type, and if it's a Buffer, emit a texel coordinate function
  16887. uint32_t tid = result_types[args[opcode == OpImageWrite ? 0 : 2]];
  16888. if (tid && get<SPIRType>(tid).image.dim == DimBuffer && !self.msl_options.texture_buffer_native)
  16889. return SPVFuncImplTexelBufferCoords;
  16890. break;
  16891. }
  16892. case OpExtInst:
  16893. {
  16894. uint32_t extension_set = args[2];
  16895. if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  16896. {
  16897. auto op_450 = static_cast<GLSLstd450>(args[3]);
  16898. switch (op_450)
  16899. {
  16900. case GLSLstd450Radians:
  16901. return SPVFuncImplRadians;
  16902. case GLSLstd450Degrees:
  16903. return SPVFuncImplDegrees;
  16904. case GLSLstd450FindILsb:
  16905. return SPVFuncImplFindILsb;
  16906. case GLSLstd450FindSMsb:
  16907. return SPVFuncImplFindSMsb;
  16908. case GLSLstd450FindUMsb:
  16909. return SPVFuncImplFindUMsb;
  16910. case GLSLstd450SSign:
  16911. return SPVFuncImplSSign;
  16912. case GLSLstd450Reflect:
  16913. {
  16914. auto &type = get<SPIRType>(args[0]);
  16915. if (type.vecsize == 1)
  16916. return SPVFuncImplReflectScalar;
  16917. break;
  16918. }
  16919. case GLSLstd450Refract:
  16920. {
  16921. auto &type = get<SPIRType>(args[0]);
  16922. if (type.vecsize == 1)
  16923. return SPVFuncImplRefractScalar;
  16924. break;
  16925. }
  16926. case GLSLstd450FaceForward:
  16927. {
  16928. auto &type = get<SPIRType>(args[0]);
  16929. if (type.vecsize == 1)
  16930. return SPVFuncImplFaceForwardScalar;
  16931. break;
  16932. }
  16933. case GLSLstd450MatrixInverse:
  16934. {
  16935. auto &mat_type = get<SPIRType>(args[0]);
  16936. switch (mat_type.columns)
  16937. {
  16938. case 2:
  16939. return SPVFuncImplInverse2x2;
  16940. case 3:
  16941. return SPVFuncImplInverse3x3;
  16942. case 4:
  16943. return SPVFuncImplInverse4x4;
  16944. default:
  16945. break;
  16946. }
  16947. break;
  16948. }
  16949. default:
  16950. break;
  16951. }
  16952. }
  16953. break;
  16954. }
  16955. case OpGroupNonUniformBroadcast:
  16956. case OpSubgroupReadInvocationKHR:
  16957. return SPVFuncImplSubgroupBroadcast;
  16958. case OpGroupNonUniformBroadcastFirst:
  16959. case OpSubgroupFirstInvocationKHR:
  16960. return SPVFuncImplSubgroupBroadcastFirst;
  16961. case OpGroupNonUniformBallot:
  16962. case OpSubgroupBallotKHR:
  16963. return SPVFuncImplSubgroupBallot;
  16964. case OpGroupNonUniformInverseBallot:
  16965. case OpGroupNonUniformBallotBitExtract:
  16966. return SPVFuncImplSubgroupBallotBitExtract;
  16967. case OpGroupNonUniformBallotFindLSB:
  16968. return SPVFuncImplSubgroupBallotFindLSB;
  16969. case OpGroupNonUniformBallotFindMSB:
  16970. return SPVFuncImplSubgroupBallotFindMSB;
  16971. case OpGroupNonUniformBallotBitCount:
  16972. return SPVFuncImplSubgroupBallotBitCount;
  16973. case OpGroupNonUniformAllEqual:
  16974. case OpSubgroupAllEqualKHR:
  16975. return SPVFuncImplSubgroupAllEqual;
  16976. case OpGroupNonUniformShuffle:
  16977. return SPVFuncImplSubgroupShuffle;
  16978. case OpGroupNonUniformShuffleXor:
  16979. return SPVFuncImplSubgroupShuffleXor;
  16980. case OpGroupNonUniformShuffleUp:
  16981. return SPVFuncImplSubgroupShuffleUp;
  16982. case OpGroupNonUniformShuffleDown:
  16983. return SPVFuncImplSubgroupShuffleDown;
  16984. case OpGroupNonUniformRotateKHR:
  16985. // Clustered rotate is performed using shuffle.
  16986. if (length > 5)
  16987. return SPVFuncImplSubgroupShuffle;
  16988. return SPVFuncImplSubgroupRotate;
  16989. case OpGroupNonUniformQuadBroadcast:
  16990. return SPVFuncImplQuadBroadcast;
  16991. case OpGroupNonUniformQuadSwap:
  16992. return SPVFuncImplQuadSwap;
  16993. case OpSDot:
  16994. case OpUDot:
  16995. case OpSUDot:
  16996. case OpSDotAccSat:
  16997. case OpUDotAccSat:
  16998. case OpSUDotAccSat:
  16999. return SPVFuncImplReduceAdd;
  17000. case OpSMulExtended:
  17001. case OpUMulExtended:
  17002. return SPVFuncImplMulExtended;
  17003. case OpAssumeTrueKHR:
  17004. case OpExpectKHR:
  17005. return SPVFuncImplAssume;
  17006. default:
  17007. break;
  17008. }
  17009. return SPVFuncImplNone;
  17010. }
  17011. // Sort both type and meta member content based on builtin status (put builtins at end),
  17012. // then by the required sorting aspect.
  17013. void CompilerMSL::MemberSorter::sort()
  17014. {
  17015. // Create a temporary array of consecutive member indices and sort it based on how
  17016. // the members should be reordered, based on builtin and sorting aspect meta info.
  17017. size_t mbr_cnt = type.member_types.size();
  17018. SmallVector<uint32_t> mbr_idxs(mbr_cnt);
  17019. std::iota(mbr_idxs.begin(), mbr_idxs.end(), 0); // Fill with consecutive indices
  17020. std::stable_sort(mbr_idxs.begin(), mbr_idxs.end(), *this); // Sort member indices based on sorting aspect
  17021. bool sort_is_identity = true;
  17022. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  17023. {
  17024. if (mbr_idx != mbr_idxs[mbr_idx])
  17025. {
  17026. sort_is_identity = false;
  17027. break;
  17028. }
  17029. }
  17030. if (sort_is_identity)
  17031. return;
  17032. if (meta.members.size() < type.member_types.size())
  17033. {
  17034. // This should never trigger in normal circumstances, but to be safe.
  17035. meta.members.resize(type.member_types.size());
  17036. }
  17037. // Move type and meta member info to the order defined by the sorted member indices.
  17038. // This is done by creating temporary copies of both member types and meta, and then
  17039. // copying back to the original content at the sorted indices.
  17040. auto mbr_types_cpy = type.member_types;
  17041. auto mbr_meta_cpy = meta.members;
  17042. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  17043. {
  17044. type.member_types[mbr_idx] = mbr_types_cpy[mbr_idxs[mbr_idx]];
  17045. meta.members[mbr_idx] = mbr_meta_cpy[mbr_idxs[mbr_idx]];
  17046. }
  17047. // If we're sorting by Offset, this might affect user code which accesses a buffer block.
  17048. // We will need to redirect member indices from defined index to sorted index using reverse lookup.
  17049. if (sort_aspect == SortAspect::Offset)
  17050. {
  17051. type.member_type_index_redirection.resize(mbr_cnt);
  17052. for (uint32_t map_idx = 0; map_idx < mbr_cnt; map_idx++)
  17053. type.member_type_index_redirection[mbr_idxs[map_idx]] = map_idx;
  17054. }
  17055. }
  17056. bool CompilerMSL::MemberSorter::operator()(uint32_t mbr_idx1, uint32_t mbr_idx2)
  17057. {
  17058. auto &mbr_meta1 = meta.members[mbr_idx1];
  17059. auto &mbr_meta2 = meta.members[mbr_idx2];
  17060. if (sort_aspect == LocationThenBuiltInType)
  17061. {
  17062. // Sort first by builtin status (put builtins at end), then by the sorting aspect.
  17063. if (mbr_meta1.builtin != mbr_meta2.builtin)
  17064. return mbr_meta2.builtin;
  17065. else if (mbr_meta1.builtin)
  17066. return mbr_meta1.builtin_type < mbr_meta2.builtin_type;
  17067. else if (mbr_meta1.location == mbr_meta2.location)
  17068. return mbr_meta1.component < mbr_meta2.component;
  17069. else
  17070. return mbr_meta1.location < mbr_meta2.location;
  17071. }
  17072. else
  17073. return mbr_meta1.offset < mbr_meta2.offset;
  17074. }
  17075. CompilerMSL::MemberSorter::MemberSorter(SPIRType &t, Meta &m, SortAspect sa)
  17076. : type(t)
  17077. , meta(m)
  17078. , sort_aspect(sa)
  17079. {
  17080. // Ensure enough meta info is available
  17081. meta.members.resize(max(type.member_types.size(), meta.members.size()));
  17082. }
  17083. void CompilerMSL::remap_constexpr_sampler(VariableID id, const MSLConstexprSampler &sampler)
  17084. {
  17085. auto &type = get<SPIRType>(get<SPIRVariable>(id).basetype);
  17086. if (type.basetype != SPIRType::SampledImage && type.basetype != SPIRType::Sampler)
  17087. SPIRV_CROSS_THROW("Can only remap SampledImage and Sampler type.");
  17088. if (!type.array.empty())
  17089. SPIRV_CROSS_THROW("Can not remap array of samplers.");
  17090. constexpr_samplers_by_id[id] = sampler;
  17091. }
  17092. void CompilerMSL::remap_constexpr_sampler_by_binding(uint32_t desc_set, uint32_t binding,
  17093. const MSLConstexprSampler &sampler)
  17094. {
  17095. constexpr_samplers_by_binding[{ desc_set, binding }] = sampler;
  17096. }
  17097. void CompilerMSL::cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type)
  17098. {
  17099. bool is_packed = has_extended_decoration(source_id, SPIRVCrossDecorationPhysicalTypePacked);
  17100. auto *source_expr = maybe_get<SPIRExpression>(source_id);
  17101. auto *var = maybe_get_backing_variable(source_id);
  17102. const SPIRType *var_type = nullptr, *phys_type = nullptr;
  17103. if (uint32_t phys_id = get_extended_decoration(source_id, SPIRVCrossDecorationPhysicalTypeID))
  17104. phys_type = &get<SPIRType>(phys_id);
  17105. else
  17106. phys_type = &expr_type;
  17107. if (var)
  17108. {
  17109. source_id = var->self;
  17110. var_type = &get_variable_data_type(*var);
  17111. }
  17112. bool rewrite_boolean_load =
  17113. expr_type.basetype == SPIRType::Boolean &&
  17114. (var && (var->storage == StorageClassWorkgroup || var_type->basetype == SPIRType::Struct));
  17115. // Type fixups for workgroup variables if they are booleans.
  17116. if (rewrite_boolean_load)
  17117. {
  17118. if (is_array(expr_type))
  17119. expr = to_rerolled_array_expression(expr_type, expr, expr_type);
  17120. else
  17121. expr = join(type_to_glsl(expr_type), "(", expr, ")");
  17122. }
  17123. // Type fixups for workgroup variables if they are matrices.
  17124. // Don't do fixup for packed types; those are handled specially.
  17125. // FIXME: Maybe use a type like spvStorageMatrix for packed matrices?
  17126. if (!msl_options.supports_msl_version(3, 0) && var &&
  17127. (var->storage == StorageClassWorkgroup ||
  17128. (var_type->basetype == SPIRType::Struct &&
  17129. has_extended_decoration(var_type->self, SPIRVCrossDecorationWorkgroupStruct) && !is_packed)) &&
  17130. expr_type.columns > 1)
  17131. {
  17132. SPIRType matrix_type = *phys_type;
  17133. if (source_expr && source_expr->need_transpose)
  17134. swap(matrix_type.vecsize, matrix_type.columns);
  17135. matrix_type.array.clear();
  17136. matrix_type.array_size_literal.clear();
  17137. expr = join(type_to_glsl(matrix_type), "(", expr, ")");
  17138. }
  17139. // Only interested in standalone builtin variables in the switch below.
  17140. if (!has_decoration(source_id, DecorationBuiltIn))
  17141. {
  17142. // If the backing variable does not match our expected sign, we can fix it up here.
  17143. // See ensure_correct_input_type().
  17144. if (var && var->storage == StorageClassInput)
  17145. {
  17146. auto &base_type = get<SPIRType>(var->basetype);
  17147. if (base_type.basetype != SPIRType::Struct && expr_type.basetype != base_type.basetype)
  17148. expr = join(type_to_glsl(expr_type), "(", expr, ")");
  17149. }
  17150. return;
  17151. }
  17152. auto builtin = static_cast<BuiltIn>(get_decoration(source_id, DecorationBuiltIn));
  17153. auto expected_type = expr_type.basetype;
  17154. auto expected_width = expr_type.width;
  17155. switch (builtin)
  17156. {
  17157. case BuiltInGlobalInvocationId:
  17158. case BuiltInLocalInvocationId:
  17159. case BuiltInWorkgroupId:
  17160. case BuiltInLocalInvocationIndex:
  17161. case BuiltInWorkgroupSize:
  17162. case BuiltInNumWorkgroups:
  17163. case BuiltInLayer:
  17164. case BuiltInViewportIndex:
  17165. case BuiltInFragStencilRefEXT:
  17166. case BuiltInPrimitiveId:
  17167. case BuiltInSubgroupSize:
  17168. case BuiltInSubgroupLocalInvocationId:
  17169. case BuiltInViewIndex:
  17170. case BuiltInVertexIndex:
  17171. case BuiltInInstanceIndex:
  17172. case BuiltInBaseInstance:
  17173. case BuiltInBaseVertex:
  17174. case BuiltInSampleMask:
  17175. expected_type = SPIRType::UInt;
  17176. expected_width = 32;
  17177. break;
  17178. case BuiltInTessLevelInner:
  17179. case BuiltInTessLevelOuter:
  17180. if (is_tesc_shader())
  17181. {
  17182. expected_type = SPIRType::Half;
  17183. expected_width = 16;
  17184. }
  17185. break;
  17186. default:
  17187. break;
  17188. }
  17189. if (is_array(expr_type) && builtin == BuiltInSampleMask)
  17190. {
  17191. // Needs special handling.
  17192. auto wrap_expr = join(type_to_glsl(expr_type), "({ ");
  17193. wrap_expr += join(type_to_glsl(get<SPIRType>(expr_type.parent_type)), "(", expr, ")");
  17194. wrap_expr += " })";
  17195. expr = std::move(wrap_expr);
  17196. }
  17197. else if (expected_type != expr_type.basetype)
  17198. {
  17199. if (is_array(expr_type) && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
  17200. {
  17201. // Triggers when loading TessLevel directly as an array.
  17202. // Need explicit padding + cast.
  17203. auto wrap_expr = join(type_to_glsl(expr_type), "({ ");
  17204. uint32_t array_size = get_physical_tess_level_array_size(builtin);
  17205. for (uint32_t i = 0; i < array_size; i++)
  17206. {
  17207. if (array_size > 1)
  17208. wrap_expr += join("float(", expr, "[", i, "])");
  17209. else
  17210. wrap_expr += join("float(", expr, ")");
  17211. if (i + 1 < array_size)
  17212. wrap_expr += ", ";
  17213. }
  17214. if (is_tessellating_triangles())
  17215. wrap_expr += ", 0.0";
  17216. wrap_expr += " })";
  17217. expr = std::move(wrap_expr);
  17218. }
  17219. else
  17220. {
  17221. // These are of different widths, so we cannot do a straight bitcast.
  17222. if (expected_width != expr_type.width)
  17223. expr = join(type_to_glsl(expr_type), "(", expr, ")");
  17224. else
  17225. expr = bitcast_expression(expr_type, expected_type, expr);
  17226. }
  17227. }
  17228. }
  17229. void CompilerMSL::cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type)
  17230. {
  17231. bool is_packed = has_extended_decoration(target_id, SPIRVCrossDecorationPhysicalTypePacked);
  17232. auto *target_expr = maybe_get<SPIRExpression>(target_id);
  17233. auto *var = maybe_get_backing_variable(target_id);
  17234. const SPIRType *var_type = nullptr, *phys_type = nullptr;
  17235. if (uint32_t phys_id = get_extended_decoration(target_id, SPIRVCrossDecorationPhysicalTypeID))
  17236. phys_type = &get<SPIRType>(phys_id);
  17237. else
  17238. phys_type = &expr_type;
  17239. if (var)
  17240. {
  17241. target_id = var->self;
  17242. var_type = &get_variable_data_type(*var);
  17243. }
  17244. bool rewrite_boolean_store =
  17245. expr_type.basetype == SPIRType::Boolean &&
  17246. (var && (var->storage == StorageClassWorkgroup || var_type->basetype == SPIRType::Struct));
  17247. // Type fixups for workgroup variables or struct members if they are booleans.
  17248. if (rewrite_boolean_store)
  17249. {
  17250. if (is_array(expr_type))
  17251. {
  17252. expr = to_rerolled_array_expression(*var_type, expr, expr_type);
  17253. }
  17254. else
  17255. {
  17256. auto short_type = expr_type;
  17257. short_type.basetype = SPIRType::Short;
  17258. expr = join(type_to_glsl(short_type), "(", expr, ")");
  17259. }
  17260. }
  17261. // Type fixups for workgroup variables if they are matrices.
  17262. // Don't do fixup for packed types; those are handled specially.
  17263. // FIXME: Maybe use a type like spvStorageMatrix for packed matrices?
  17264. if (!msl_options.supports_msl_version(3, 0) && var &&
  17265. (var->storage == StorageClassWorkgroup ||
  17266. (var_type->basetype == SPIRType::Struct &&
  17267. has_extended_decoration(var_type->self, SPIRVCrossDecorationWorkgroupStruct) && !is_packed)) &&
  17268. expr_type.columns > 1)
  17269. {
  17270. SPIRType matrix_type = *phys_type;
  17271. if (target_expr && target_expr->need_transpose)
  17272. swap(matrix_type.vecsize, matrix_type.columns);
  17273. expr = join("spvStorage_", type_to_glsl(matrix_type), "(", expr, ")");
  17274. }
  17275. // Only interested in standalone builtin variables.
  17276. if (!has_decoration(target_id, DecorationBuiltIn))
  17277. return;
  17278. auto builtin = static_cast<BuiltIn>(get_decoration(target_id, DecorationBuiltIn));
  17279. auto expected_type = expr_type.basetype;
  17280. auto expected_width = expr_type.width;
  17281. switch (builtin)
  17282. {
  17283. case BuiltInLayer:
  17284. case BuiltInViewportIndex:
  17285. case BuiltInFragStencilRefEXT:
  17286. case BuiltInPrimitiveId:
  17287. case BuiltInViewIndex:
  17288. expected_type = SPIRType::UInt;
  17289. expected_width = 32;
  17290. break;
  17291. case BuiltInTessLevelInner:
  17292. case BuiltInTessLevelOuter:
  17293. expected_type = SPIRType::Half;
  17294. expected_width = 16;
  17295. break;
  17296. default:
  17297. break;
  17298. }
  17299. if (expected_type != expr_type.basetype)
  17300. {
  17301. if (expected_width != expr_type.width)
  17302. {
  17303. // These are of different widths, so we cannot do a straight bitcast.
  17304. auto type = expr_type;
  17305. type.basetype = expected_type;
  17306. type.width = expected_width;
  17307. expr = join(type_to_glsl(type), "(", expr, ")");
  17308. }
  17309. else
  17310. {
  17311. auto type = expr_type;
  17312. type.basetype = expected_type;
  17313. expr = bitcast_expression(type, expr_type.basetype, expr);
  17314. }
  17315. }
  17316. }
  17317. string CompilerMSL::to_initializer_expression(const SPIRVariable &var)
  17318. {
  17319. // We risk getting an array initializer here with MSL. If we have an array.
  17320. // FIXME: We cannot handle non-constant arrays being initialized.
  17321. // We will need to inject spvArrayCopy here somehow ...
  17322. auto &type = get<SPIRType>(var.basetype);
  17323. string expr;
  17324. if (ir.ids[var.initializer].get_type() == TypeConstant &&
  17325. (!type.array.empty() || type.basetype == SPIRType::Struct))
  17326. expr = constant_expression(get<SPIRConstant>(var.initializer));
  17327. else
  17328. expr = CompilerGLSL::to_initializer_expression(var);
  17329. // If the initializer has more vector components than the variable, add a swizzle.
  17330. // FIXME: This can't handle arrays or structs.
  17331. auto &init_type = expression_type(var.initializer);
  17332. if (type.array.empty() && type.basetype != SPIRType::Struct && init_type.vecsize > type.vecsize)
  17333. expr = enclose_expression(expr + vector_swizzle(type.vecsize, 0));
  17334. return expr;
  17335. }
  17336. string CompilerMSL::to_zero_initialized_expression(uint32_t)
  17337. {
  17338. return "{}";
  17339. }
  17340. bool CompilerMSL::descriptor_set_is_argument_buffer(uint32_t desc_set) const
  17341. {
  17342. if (!msl_options.argument_buffers)
  17343. return false;
  17344. if (desc_set >= kMaxArgumentBuffers)
  17345. return false;
  17346. return (argument_buffer_discrete_mask & (1u << desc_set)) == 0;
  17347. }
  17348. bool CompilerMSL::is_supported_argument_buffer_type(const SPIRType &type) const
  17349. {
  17350. // iOS Tier 1 argument buffers do not support writable images.
  17351. // When the argument buffer is encoded, we don't know whether this image will have a
  17352. // NonWritable decoration, so just use discrete arguments for all storage images on iOS.
  17353. bool is_supported_type = !(type.basetype == SPIRType::Image &&
  17354. type.image.sampled == 2 &&
  17355. msl_options.is_ios() &&
  17356. msl_options.argument_buffers_tier <= Options::ArgumentBuffersTier::Tier1);
  17357. return is_supported_type && !type_is_msl_framebuffer_fetch(type);
  17358. }
  17359. void CompilerMSL::emit_argument_buffer_aliased_descriptor(const SPIRVariable &aliased_var,
  17360. const SPIRVariable &base_var)
  17361. {
  17362. // To deal with buffer <-> image aliasing, we need to perform an unholy UB ritual.
  17363. // A texture type in Metal 3.0 is a pointer. However, we cannot simply cast a pointer to texture.
  17364. // What we *can* do is to cast pointer-to-pointer to pointer-to-texture.
  17365. // We need to explicitly reach into the descriptor buffer lvalue, not any spvDescriptorArray wrapper.
  17366. auto *var_meta = ir.find_meta(base_var.self);
  17367. bool old_explicit_qualifier = var_meta && var_meta->decoration.qualified_alias_explicit_override;
  17368. if (var_meta)
  17369. var_meta->decoration.qualified_alias_explicit_override = false;
  17370. auto unqualified_name = to_name(base_var.self, false);
  17371. if (var_meta)
  17372. var_meta->decoration.qualified_alias_explicit_override = old_explicit_qualifier;
  17373. // For non-arrayed buffers, we have already performed a de-reference.
  17374. // We need a proper lvalue to cast, so strip away the de-reference.
  17375. if (unqualified_name.size() > 2 && unqualified_name[0] == '(' && unqualified_name[1] == '*')
  17376. {
  17377. unqualified_name.erase(unqualified_name.begin(), unqualified_name.begin() + 2);
  17378. unqualified_name.pop_back();
  17379. }
  17380. string name;
  17381. auto &var_type = get<SPIRType>(aliased_var.basetype);
  17382. auto &data_type = get_variable_data_type(aliased_var);
  17383. string descriptor_storage = descriptor_address_space(aliased_var.self, aliased_var.storage, "");
  17384. if (aliased_var.storage == StorageClassUniformConstant)
  17385. {
  17386. if (is_var_runtime_size_array(aliased_var))
  17387. {
  17388. // This becomes a plain pointer to spvDescriptor.
  17389. name = join("reinterpret_cast<", descriptor_storage, " ",
  17390. type_to_glsl(get_variable_data_type(aliased_var), aliased_var.self, true), ">(&",
  17391. unqualified_name, ")");
  17392. }
  17393. else
  17394. {
  17395. name = join("reinterpret_cast<", descriptor_storage, " ",
  17396. type_to_glsl(get_variable_data_type(aliased_var), aliased_var.self, true), " &>(",
  17397. unqualified_name, ");");
  17398. }
  17399. }
  17400. else
  17401. {
  17402. // Buffer types.
  17403. bool old_is_using_builtin_array = is_using_builtin_array;
  17404. is_using_builtin_array = true;
  17405. bool needs_post_cast_deref = !is_array(data_type);
  17406. string ref_type = needs_post_cast_deref ? "&" : join("(&)", type_to_array_glsl(var_type, aliased_var.self));
  17407. if (is_var_runtime_size_array(aliased_var))
  17408. {
  17409. name = join("reinterpret_cast<",
  17410. type_to_glsl(var_type, aliased_var.self, true), " ", descriptor_storage, " *>(&",
  17411. unqualified_name, ")");
  17412. }
  17413. else
  17414. {
  17415. name = join(needs_post_cast_deref ? "*" : "", "reinterpret_cast<",
  17416. type_to_glsl(var_type, aliased_var.self, true), " ", descriptor_storage, " ",
  17417. ref_type,
  17418. ">(", unqualified_name, ");");
  17419. }
  17420. if (needs_post_cast_deref)
  17421. descriptor_storage = get_type_address_space(var_type, aliased_var.self, false);
  17422. // These kinds of ridiculous casts trigger warnings in compiler. Just ignore them.
  17423. if (!suppress_incompatible_pointer_types_discard_qualifiers)
  17424. {
  17425. suppress_incompatible_pointer_types_discard_qualifiers = true;
  17426. force_recompile_guarantee_forward_progress();
  17427. }
  17428. is_using_builtin_array = old_is_using_builtin_array;
  17429. }
  17430. if (!is_var_runtime_size_array(aliased_var))
  17431. {
  17432. // Lower to temporary, so drop the qualification.
  17433. set_qualified_name(aliased_var.self, "");
  17434. statement(descriptor_storage, " auto &", to_name(aliased_var.self), " = ", name);
  17435. }
  17436. else
  17437. {
  17438. // This alias may have already been used to emit an entry point declaration. If there is a mismatch, we need a recompile.
  17439. // Moving this code to be run earlier will also conflict,
  17440. // because we need the qualified alias for the base resource,
  17441. // so forcing recompile until things sync up is the least invasive method for now.
  17442. if (ir.meta[aliased_var.self].decoration.qualified_alias != name)
  17443. force_recompile();
  17444. // This will get wrapped in a separate temporary when a spvDescriptorArray wrapper is emitted.
  17445. set_qualified_name(aliased_var.self, name);
  17446. }
  17447. }
  17448. void CompilerMSL::analyze_argument_buffers()
  17449. {
  17450. // Gather all used resources and sort them out into argument buffers.
  17451. // Each argument buffer corresponds to a descriptor set in SPIR-V.
  17452. // The [[id(N)]] values used correspond to the resource mapping we have for MSL.
  17453. // Otherwise, the binding number is used, but this is generally not safe some types like
  17454. // combined image samplers and arrays of resources. Metal needs different indices here,
  17455. // while SPIR-V can have one descriptor set binding. To use argument buffers in practice,
  17456. // you will need to use the remapping from the API.
  17457. for (auto &id : argument_buffer_ids)
  17458. id = 0;
  17459. // Output resources, sorted by resource index & type.
  17460. struct Resource
  17461. {
  17462. SPIRVariable *var;
  17463. string name;
  17464. SPIRType::BaseType basetype;
  17465. uint32_t index;
  17466. uint32_t plane_count;
  17467. uint32_t plane;
  17468. uint32_t overlapping_var_id;
  17469. };
  17470. SmallVector<Resource> resources_in_set[kMaxArgumentBuffers];
  17471. SmallVector<uint32_t> inline_block_vars;
  17472. bool set_needs_swizzle_buffer[kMaxArgumentBuffers] = {};
  17473. bool set_needs_buffer_sizes[kMaxArgumentBuffers] = {};
  17474. bool needs_buffer_sizes = false;
  17475. ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &var) {
  17476. if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  17477. var.storage == StorageClassStorageBuffer) &&
  17478. !is_hidden_variable(var))
  17479. {
  17480. uint32_t desc_set = get_decoration(self, DecorationDescriptorSet);
  17481. // Ignore if it's part of a push descriptor set.
  17482. if (!descriptor_set_is_argument_buffer(desc_set))
  17483. return;
  17484. uint32_t var_id = var.self;
  17485. auto &type = get_variable_data_type(var);
  17486. if (desc_set >= kMaxArgumentBuffers)
  17487. SPIRV_CROSS_THROW("Descriptor set index is out of range.");
  17488. const MSLConstexprSampler *constexpr_sampler = nullptr;
  17489. if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler)
  17490. {
  17491. constexpr_sampler = find_constexpr_sampler(var_id);
  17492. if (constexpr_sampler)
  17493. {
  17494. // Mark this ID as a constexpr sampler for later in case it came from set/bindings.
  17495. constexpr_samplers_by_id[var_id] = *constexpr_sampler;
  17496. }
  17497. }
  17498. uint32_t binding = get_decoration(var_id, DecorationBinding);
  17499. if (type.basetype == SPIRType::SampledImage)
  17500. {
  17501. add_resource_name(var_id);
  17502. uint32_t plane_count = 1;
  17503. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  17504. plane_count = constexpr_sampler->planes;
  17505. for (uint32_t i = 0; i < plane_count; i++)
  17506. {
  17507. uint32_t image_resource_index = get_metal_resource_index(var, SPIRType::Image, i);
  17508. resources_in_set[desc_set].push_back(
  17509. { &var, to_name(var_id), SPIRType::Image, image_resource_index, plane_count, i, 0 });
  17510. }
  17511. if (type.image.dim != DimBuffer && !constexpr_sampler)
  17512. {
  17513. uint32_t sampler_resource_index = get_metal_resource_index(var, SPIRType::Sampler);
  17514. resources_in_set[desc_set].push_back(
  17515. { &var, to_sampler_expression(var_id), SPIRType::Sampler, sampler_resource_index, 1, 0, 0 });
  17516. }
  17517. }
  17518. else if (inline_uniform_blocks.count(SetBindingPair{ desc_set, binding }))
  17519. {
  17520. inline_block_vars.push_back(var_id);
  17521. }
  17522. else if (!constexpr_sampler && is_supported_argument_buffer_type(type))
  17523. {
  17524. // constexpr samplers are not declared as resources.
  17525. // Inline uniform blocks are always emitted at the end.
  17526. add_resource_name(var_id);
  17527. uint32_t resource_index = get_metal_resource_index(var, type.basetype);
  17528. resources_in_set[desc_set].push_back(
  17529. { &var, to_name(var_id), type.basetype, resource_index, 1, 0, 0 });
  17530. // Emulate texture2D atomic operations
  17531. if (atomic_image_vars_emulated.count(var.self))
  17532. {
  17533. uint32_t buffer_resource_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0);
  17534. resources_in_set[desc_set].push_back(
  17535. { &var, to_name(var_id) + "_atomic", SPIRType::Struct, buffer_resource_index, 1, 0, 0 });
  17536. }
  17537. }
  17538. // Check if this descriptor set needs a swizzle buffer.
  17539. if (needs_swizzle_buffer_def && is_sampled_image_type(type))
  17540. set_needs_swizzle_buffer[desc_set] = true;
  17541. else if (buffer_requires_array_length(var_id))
  17542. {
  17543. set_needs_buffer_sizes[desc_set] = true;
  17544. needs_buffer_sizes = true;
  17545. }
  17546. }
  17547. });
  17548. if (needs_swizzle_buffer_def || needs_buffer_sizes)
  17549. {
  17550. uint32_t uint_ptr_type_id = 0;
  17551. // We might have to add a swizzle buffer resource to the set.
  17552. for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++)
  17553. {
  17554. if (!set_needs_swizzle_buffer[desc_set] && !set_needs_buffer_sizes[desc_set])
  17555. continue;
  17556. if (uint_ptr_type_id == 0)
  17557. {
  17558. uint_ptr_type_id = ir.increase_bound_by(1);
  17559. // Create a buffer to hold extra data, including the swizzle constants.
  17560. SPIRType uint_type_pointer = get_uint_type();
  17561. uint_type_pointer.op = OpTypePointer;
  17562. uint_type_pointer.pointer = true;
  17563. uint_type_pointer.pointer_depth++;
  17564. uint_type_pointer.parent_type = get_uint_type_id();
  17565. uint_type_pointer.storage = StorageClassUniform;
  17566. set<SPIRType>(uint_ptr_type_id, uint_type_pointer);
  17567. set_decoration(uint_ptr_type_id, DecorationArrayStride, 4);
  17568. }
  17569. if (set_needs_swizzle_buffer[desc_set])
  17570. {
  17571. uint32_t var_id = ir.increase_bound_by(1);
  17572. auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant);
  17573. set_name(var_id, "spvSwizzleConstants");
  17574. set_decoration(var_id, DecorationDescriptorSet, desc_set);
  17575. set_decoration(var_id, DecorationBinding, kSwizzleBufferBinding);
  17576. resources_in_set[desc_set].push_back(
  17577. { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 1, 0, 0 });
  17578. }
  17579. if (set_needs_buffer_sizes[desc_set])
  17580. {
  17581. uint32_t var_id = ir.increase_bound_by(1);
  17582. auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant);
  17583. set_name(var_id, "spvBufferSizeConstants");
  17584. set_decoration(var_id, DecorationDescriptorSet, desc_set);
  17585. set_decoration(var_id, DecorationBinding, kBufferSizeBufferBinding);
  17586. resources_in_set[desc_set].push_back(
  17587. { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 1, 0, 0 });
  17588. }
  17589. }
  17590. }
  17591. // Now add inline uniform blocks.
  17592. for (uint32_t var_id : inline_block_vars)
  17593. {
  17594. auto &var = get<SPIRVariable>(var_id);
  17595. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  17596. add_resource_name(var_id);
  17597. resources_in_set[desc_set].push_back(
  17598. { &var, to_name(var_id), SPIRType::Struct, get_metal_resource_index(var, SPIRType::Struct), 1, 0, 0 });
  17599. }
  17600. for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++)
  17601. {
  17602. auto &resources = resources_in_set[desc_set];
  17603. if (resources.empty())
  17604. continue;
  17605. assert(descriptor_set_is_argument_buffer(desc_set));
  17606. uint32_t next_id = ir.increase_bound_by(3);
  17607. uint32_t type_id = next_id + 1;
  17608. uint32_t ptr_type_id = next_id + 2;
  17609. argument_buffer_ids[desc_set] = next_id;
  17610. auto &buffer_type = set<SPIRType>(type_id, OpTypeStruct);
  17611. buffer_type.basetype = SPIRType::Struct;
  17612. if ((argument_buffer_device_storage_mask & (1u << desc_set)) != 0)
  17613. {
  17614. buffer_type.storage = StorageClassStorageBuffer;
  17615. // Make sure the argument buffer gets marked as const device.
  17616. set_decoration(next_id, DecorationNonWritable);
  17617. // Need to mark the type as a Block to enable this.
  17618. set_decoration(type_id, DecorationBlock);
  17619. }
  17620. else
  17621. buffer_type.storage = StorageClassUniform;
  17622. auto buffer_type_name = join("spvDescriptorSetBuffer", desc_set);
  17623. set_name(type_id, buffer_type_name);
  17624. auto &ptr_type = set<SPIRType>(ptr_type_id, OpTypePointer);
  17625. ptr_type = buffer_type;
  17626. ptr_type.op = OpTypePointer;
  17627. ptr_type.pointer = true;
  17628. ptr_type.pointer_depth++;
  17629. ptr_type.parent_type = type_id;
  17630. uint32_t buffer_variable_id = next_id;
  17631. auto &buffer_var = set<SPIRVariable>(buffer_variable_id, ptr_type_id, StorageClassUniform);
  17632. auto buffer_name = join("spvDescriptorSet", desc_set);
  17633. set_name(buffer_variable_id, buffer_name);
  17634. // Ids must be emitted in ID order.
  17635. stable_sort(begin(resources), end(resources), [&](const Resource &lhs, const Resource &rhs) -> bool {
  17636. return tie(lhs.index, lhs.basetype) < tie(rhs.index, rhs.basetype);
  17637. });
  17638. for (size_t i = 0; i < resources.size() - 1; i++)
  17639. {
  17640. auto &r1 = resources[i];
  17641. auto &r2 = resources[i + 1];
  17642. if (r1.index == r2.index)
  17643. {
  17644. if (r1.overlapping_var_id)
  17645. r2.overlapping_var_id = r1.overlapping_var_id;
  17646. else
  17647. r2.overlapping_var_id = r1.var->self;
  17648. set_extended_decoration(r2.var->self, SPIRVCrossDecorationOverlappingBinding, r2.overlapping_var_id);
  17649. }
  17650. }
  17651. uint32_t member_index = 0;
  17652. uint32_t next_arg_buff_index = 0;
  17653. uint32_t prev_was_scalar_on_array_offset = 0;
  17654. for (auto &resource : resources)
  17655. {
  17656. auto &var = *resource.var;
  17657. auto &type = get_variable_data_type(var);
  17658. if (is_var_runtime_size_array(var) && (argument_buffer_device_storage_mask & (1u << desc_set)) == 0)
  17659. SPIRV_CROSS_THROW("Runtime sized variables must be in device storage argument buffers.");
  17660. // If needed, synthesize and add padding members.
  17661. // member_index and next_arg_buff_index are incremented when padding members are added.
  17662. if (msl_options.pad_argument_buffer_resources && resource.plane == 0 && resource.overlapping_var_id == 0)
  17663. {
  17664. auto rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index - prev_was_scalar_on_array_offset);
  17665. rez_bind.count -= prev_was_scalar_on_array_offset;
  17666. while (resource.index > next_arg_buff_index)
  17667. {
  17668. switch (rez_bind.basetype)
  17669. {
  17670. case SPIRType::Void:
  17671. case SPIRType::Boolean:
  17672. case SPIRType::SByte:
  17673. case SPIRType::UByte:
  17674. case SPIRType::Short:
  17675. case SPIRType::UShort:
  17676. case SPIRType::Int:
  17677. case SPIRType::UInt:
  17678. case SPIRType::Int64:
  17679. case SPIRType::UInt64:
  17680. case SPIRType::AtomicCounter:
  17681. case SPIRType::Half:
  17682. case SPIRType::Float:
  17683. case SPIRType::Double:
  17684. add_argument_buffer_padding_buffer_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17685. break;
  17686. case SPIRType::Image:
  17687. add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17688. break;
  17689. case SPIRType::Sampler:
  17690. add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17691. break;
  17692. case SPIRType::SampledImage:
  17693. if (next_arg_buff_index == rez_bind.msl_sampler)
  17694. add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17695. else
  17696. add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17697. break;
  17698. default:
  17699. break;
  17700. }
  17701. // After padding, retrieve the resource again. It will either be more padding, or the actual resource.
  17702. rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index);
  17703. prev_was_scalar_on_array_offset = 0;
  17704. }
  17705. uint32_t count = rez_bind.count;
  17706. // If the current resource is an array in the descriptor, but is a scalar
  17707. // in the shader, only the first element will be consumed. The next pass
  17708. // will add a padding member to consume the remaining array elements.
  17709. if (count > 1 && type.array.empty())
  17710. count = prev_was_scalar_on_array_offset = 1;
  17711. // Adjust the number of slots consumed by current member itself.
  17712. next_arg_buff_index += resource.plane_count * count;
  17713. }
  17714. // Here we're locking down the member name early before compilation loops, so ensure that
  17715. // the resource name is not reused, even through a reset().
  17716. string mbr_name = ensure_valid_name(resource.name, "m");
  17717. if (resource.plane > 0)
  17718. mbr_name += join(plane_name_suffix, resource.plane);
  17719. set_member_name(buffer_type.self, member_index, mbr_name);
  17720. if (resource.basetype == SPIRType::Sampler && type.basetype != SPIRType::Sampler)
  17721. {
  17722. // Have to synthesize a sampler type here.
  17723. bool type_is_array = !type.array.empty();
  17724. uint32_t sampler_type_id = ir.increase_bound_by(type_is_array ? 2 : 1);
  17725. auto &new_sampler_type = set<SPIRType>(sampler_type_id, OpTypeSampler);
  17726. new_sampler_type.basetype = SPIRType::Sampler;
  17727. new_sampler_type.storage = StorageClassUniformConstant;
  17728. if (type_is_array)
  17729. {
  17730. uint32_t sampler_type_array_id = sampler_type_id + 1;
  17731. auto &sampler_type_array = set<SPIRType>(sampler_type_array_id, OpTypeArray);
  17732. sampler_type_array = new_sampler_type;
  17733. sampler_type_array.array = type.array;
  17734. sampler_type_array.array_size_literal = type.array_size_literal;
  17735. sampler_type_array.parent_type = sampler_type_id;
  17736. buffer_type.member_types.push_back(sampler_type_array_id);
  17737. }
  17738. else
  17739. buffer_type.member_types.push_back(sampler_type_id);
  17740. }
  17741. else
  17742. {
  17743. uint32_t binding = get_decoration(var.self, DecorationBinding);
  17744. SetBindingPair pair = { desc_set, binding };
  17745. if (resource.basetype == SPIRType::Image || resource.basetype == SPIRType::Sampler ||
  17746. resource.basetype == SPIRType::SampledImage || resource.basetype == SPIRType::AccelerationStructure)
  17747. {
  17748. // Drop pointer information when we emit the resources into a struct.
  17749. buffer_type.member_types.push_back(get_variable_data_type_id(var));
  17750. if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding))
  17751. {
  17752. if (!msl_options.supports_msl_version(3, 0))
  17753. SPIRV_CROSS_THROW("Full mutable aliasing of argument buffer descriptors only works on Metal 3+.");
  17754. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  17755. entry_func.fixup_hooks_in.push_back([this, resource]() {
  17756. emit_argument_buffer_aliased_descriptor(*resource.var, this->get<SPIRVariable>(resource.overlapping_var_id));
  17757. });
  17758. }
  17759. else if (resource.plane == 0)
  17760. {
  17761. set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
  17762. }
  17763. }
  17764. else if (buffers_requiring_dynamic_offset.count(pair))
  17765. {
  17766. // Don't set the qualified name here; we'll define a variable holding the corrected buffer address later.
  17767. buffer_type.member_types.push_back(var.basetype);
  17768. auto &dynamic_buffer = buffers_requiring_dynamic_offset[pair];
  17769. dynamic_buffer.var_id = var.self;
  17770. dynamic_buffer.mbr_name = mbr_name;
  17771. }
  17772. else if (inline_uniform_blocks.count(pair))
  17773. {
  17774. // Put the buffer block itself into the argument buffer.
  17775. buffer_type.member_types.push_back(get_variable_data_type_id(var));
  17776. set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
  17777. }
  17778. else if (atomic_image_vars_emulated.count(var.self))
  17779. {
  17780. // Emulate texture2D atomic operations.
  17781. // Don't set the qualified name: it's already set for this variable,
  17782. // and the code that references the buffer manually appends "_atomic"
  17783. // to the name.
  17784. uint32_t offset = ir.increase_bound_by(2);
  17785. uint32_t atomic_type_id = offset;
  17786. uint32_t type_ptr_id = offset + 1;
  17787. SPIRType atomic_type { OpTypeInt };
  17788. atomic_type.basetype = SPIRType::AtomicCounter;
  17789. atomic_type.width = 32;
  17790. atomic_type.vecsize = 1;
  17791. set<SPIRType>(atomic_type_id, atomic_type);
  17792. atomic_type.op = OpTypePointer;
  17793. atomic_type.pointer = true;
  17794. atomic_type.pointer_depth++;
  17795. atomic_type.parent_type = atomic_type_id;
  17796. atomic_type.storage = StorageClassStorageBuffer;
  17797. auto &atomic_ptr_type = set<SPIRType>(type_ptr_id, atomic_type);
  17798. atomic_ptr_type.self = atomic_type_id;
  17799. buffer_type.member_types.push_back(type_ptr_id);
  17800. }
  17801. else
  17802. {
  17803. buffer_type.member_types.push_back(var.basetype);
  17804. if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding))
  17805. {
  17806. // Casting raw pointers is fine since their ABI is fixed, but anything opaque is deeply questionable on Metal 2.
  17807. if (get<SPIRVariable>(resource.overlapping_var_id).storage == StorageClassUniformConstant &&
  17808. !msl_options.supports_msl_version(3, 0))
  17809. {
  17810. SPIRV_CROSS_THROW("Full mutable aliasing of argument buffer descriptors only works on Metal 3+.");
  17811. }
  17812. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  17813. entry_func.fixup_hooks_in.push_back([this, resource]() {
  17814. emit_argument_buffer_aliased_descriptor(*resource.var, this->get<SPIRVariable>(resource.overlapping_var_id));
  17815. });
  17816. }
  17817. else if (type.array.empty())
  17818. set_qualified_name(var.self, join("(*", to_name(buffer_variable_id), ".", mbr_name, ")"));
  17819. else
  17820. set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
  17821. }
  17822. }
  17823. set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationResourceIndexPrimary,
  17824. resource.index);
  17825. set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationInterfaceOrigID,
  17826. var.self);
  17827. if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding))
  17828. set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationOverlappingBinding);
  17829. member_index++;
  17830. }
  17831. if (msl_options.replace_recursive_inputs && type_contains_recursion(buffer_type))
  17832. {
  17833. recursive_inputs.insert(type_id);
  17834. auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
  17835. auto addr_space = get_variable_address_space(buffer_var);
  17836. entry_func.fixup_hooks_in.push_back([this, addr_space, buffer_name, buffer_type_name]() {
  17837. statement(addr_space, " auto& ", buffer_name, " = *(", addr_space, " ", buffer_type_name, "*)", buffer_name, "_vp;");
  17838. });
  17839. }
  17840. }
  17841. }
  17842. // Return the resource type of the app-provided resources for the descriptor set,
  17843. // that matches the resource index of the argument buffer index.
  17844. // This is a two-step lookup, first lookup the resource binding number from the argument buffer index,
  17845. // then lookup the resource binding using the binding number.
  17846. const MSLResourceBinding &CompilerMSL::get_argument_buffer_resource(uint32_t desc_set, uint32_t arg_idx) const
  17847. {
  17848. auto stage = get_entry_point().model;
  17849. StageSetBinding arg_idx_tuple = { stage, desc_set, arg_idx };
  17850. auto arg_itr = resource_arg_buff_idx_to_binding_number.find(arg_idx_tuple);
  17851. if (arg_itr != end(resource_arg_buff_idx_to_binding_number))
  17852. {
  17853. StageSetBinding bind_tuple = { stage, desc_set, arg_itr->second };
  17854. auto bind_itr = resource_bindings.find(bind_tuple);
  17855. if (bind_itr != end(resource_bindings))
  17856. return bind_itr->second.first;
  17857. }
  17858. SPIRV_CROSS_THROW("Argument buffer resource base type could not be determined. When padding argument buffer "
  17859. "elements, all descriptor set resources must be supplied with a base type by the app.");
  17860. }
  17861. // Adds an argument buffer padding argument buffer type as one or more members of the struct type at the member index.
  17862. // Metal does not support arrays of buffers, so these are emitted as multiple struct members.
  17863. void CompilerMSL::add_argument_buffer_padding_buffer_type(SPIRType &struct_type, uint32_t &mbr_idx,
  17864. uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
  17865. {
  17866. if (!argument_buffer_padding_buffer_type_id)
  17867. {
  17868. uint32_t buff_type_id = ir.increase_bound_by(2);
  17869. auto &buff_type = set<SPIRType>(buff_type_id, OpNop);
  17870. buff_type.basetype = rez_bind.basetype;
  17871. buff_type.storage = StorageClassUniformConstant;
  17872. uint32_t ptr_type_id = buff_type_id + 1;
  17873. auto &ptr_type = set<SPIRType>(ptr_type_id, OpTypePointer);
  17874. ptr_type = buff_type;
  17875. ptr_type.op = OpTypePointer;
  17876. ptr_type.pointer = true;
  17877. ptr_type.pointer_depth++;
  17878. ptr_type.parent_type = buff_type_id;
  17879. argument_buffer_padding_buffer_type_id = ptr_type_id;
  17880. }
  17881. add_argument_buffer_padding_type(argument_buffer_padding_buffer_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
  17882. }
  17883. // Adds an argument buffer padding argument image type as a member of the struct type at the member index.
  17884. void CompilerMSL::add_argument_buffer_padding_image_type(SPIRType &struct_type, uint32_t &mbr_idx,
  17885. uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
  17886. {
  17887. if (!argument_buffer_padding_image_type_id)
  17888. {
  17889. uint32_t base_type_id = ir.increase_bound_by(2);
  17890. auto &base_type = set<SPIRType>(base_type_id, OpTypeFloat);
  17891. base_type.basetype = SPIRType::Float;
  17892. base_type.width = 32;
  17893. uint32_t img_type_id = base_type_id + 1;
  17894. auto &img_type = set<SPIRType>(img_type_id, OpTypeImage);
  17895. img_type.basetype = SPIRType::Image;
  17896. img_type.storage = StorageClassUniformConstant;
  17897. img_type.image.type = base_type_id;
  17898. img_type.image.dim = Dim2D;
  17899. img_type.image.depth = false;
  17900. img_type.image.arrayed = false;
  17901. img_type.image.ms = false;
  17902. img_type.image.sampled = 1;
  17903. img_type.image.format = ImageFormatUnknown;
  17904. img_type.image.access = AccessQualifierMax;
  17905. argument_buffer_padding_image_type_id = img_type_id;
  17906. }
  17907. add_argument_buffer_padding_type(argument_buffer_padding_image_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
  17908. }
  17909. // Adds an argument buffer padding argument sampler type as a member of the struct type at the member index.
  17910. void CompilerMSL::add_argument_buffer_padding_sampler_type(SPIRType &struct_type, uint32_t &mbr_idx,
  17911. uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
  17912. {
  17913. if (!argument_buffer_padding_sampler_type_id)
  17914. {
  17915. uint32_t samp_type_id = ir.increase_bound_by(1);
  17916. auto &samp_type = set<SPIRType>(samp_type_id, OpTypeSampler);
  17917. samp_type.basetype = SPIRType::Sampler;
  17918. samp_type.storage = StorageClassUniformConstant;
  17919. argument_buffer_padding_sampler_type_id = samp_type_id;
  17920. }
  17921. add_argument_buffer_padding_type(argument_buffer_padding_sampler_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
  17922. }
  17923. // Adds the argument buffer padding argument type as a member of the struct type at the member index.
  17924. // Advances both arg_buff_index and mbr_idx to next argument slots.
  17925. void CompilerMSL::add_argument_buffer_padding_type(uint32_t mbr_type_id, SPIRType &struct_type, uint32_t &mbr_idx,
  17926. uint32_t &arg_buff_index, uint32_t count)
  17927. {
  17928. uint32_t type_id = mbr_type_id;
  17929. if (count > 1)
  17930. {
  17931. uint32_t ary_type_id = ir.increase_bound_by(1);
  17932. auto &ary_type = set<SPIRType>(ary_type_id, get<SPIRType>(type_id));
  17933. ary_type.op = OpTypeArray;
  17934. ary_type.array.push_back(count);
  17935. ary_type.array_size_literal.push_back(true);
  17936. ary_type.parent_type = type_id;
  17937. type_id = ary_type_id;
  17938. }
  17939. set_member_name(struct_type.self, mbr_idx, join("_m", arg_buff_index, "_pad"));
  17940. set_extended_member_decoration(struct_type.self, mbr_idx, SPIRVCrossDecorationResourceIndexPrimary, arg_buff_index);
  17941. struct_type.member_types.push_back(type_id);
  17942. arg_buff_index += count;
  17943. mbr_idx++;
  17944. }
  17945. void CompilerMSL::activate_argument_buffer_resources()
  17946. {
  17947. // For ABI compatibility, force-enable all resources which are part of argument buffers.
  17948. ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, const SPIRVariable &) {
  17949. if (!has_decoration(self, DecorationDescriptorSet))
  17950. return;
  17951. uint32_t desc_set = get_decoration(self, DecorationDescriptorSet);
  17952. if (descriptor_set_is_argument_buffer(desc_set))
  17953. add_active_interface_variable(self);
  17954. });
  17955. }
  17956. bool CompilerMSL::using_builtin_array() const
  17957. {
  17958. return msl_options.force_native_arrays || is_using_builtin_array;
  17959. }
  17960. void CompilerMSL::set_combined_sampler_suffix(const char *suffix)
  17961. {
  17962. sampler_name_suffix = suffix;
  17963. }
  17964. const char *CompilerMSL::get_combined_sampler_suffix() const
  17965. {
  17966. return sampler_name_suffix.c_str();
  17967. }
  17968. bool CompilerMSL::specialization_constant_is_macro(uint32_t const_id) const
  17969. {
  17970. return constant_macro_ids.find(const_id) != constant_macro_ids.end();
  17971. }
  17972. // Start with all fast math flags enabled, and selectively disable based execution modes and float controls
  17973. uint32_t CompilerMSL::get_fp_fast_math_flags(bool incl_ops) const
  17974. {
  17975. uint32_t fp_flags = ~0;
  17976. auto &ep = get_entry_point();
  17977. if (ep.flags.get(ExecutionModeSignedZeroInfNanPreserve))
  17978. fp_flags &= ~(FPFastMathModeNSZMask | FPFastMathModeNotInfMask | FPFastMathModeNotNaNMask);
  17979. if (ep.flags.get(ExecutionModeContractionOff))
  17980. fp_flags &= ~(FPFastMathModeAllowContractMask);
  17981. for (auto &fp_pair : ep.fp_fast_math_defaults)
  17982. if (fp_pair.second)
  17983. fp_flags &= get<SPIRConstant>(fp_pair.second).scalar();
  17984. if (incl_ops)
  17985. for (auto &p_m : ir.meta)
  17986. if (p_m.second.decoration.decoration_flags.get(DecorationFPFastMathMode))
  17987. fp_flags &= p_m.second.decoration.fp_fast_math_mode;
  17988. return fp_flags;
  17989. }
  17990. void CompilerMSL::emit_block_hints(const SPIRBlock &)
  17991. {
  17992. }
  17993. void CompilerMSL::emit_mesh_entry_point()
  17994. {
  17995. auto &ep = get_entry_point();
  17996. auto &f = get<SPIRFunction>(ir.default_entry_point);
  17997. const uint32_t func_id = ir.increase_bound_by(3);
  17998. const uint32_t block_id = func_id + 1;
  17999. const uint32_t ret_id = func_id + 2;
  18000. auto &wrapped_main = set<SPIRFunction>(func_id, f.return_type, f.function_type);
  18001. wrapped_main.blocks.push_back(block_id);
  18002. wrapped_main.entry_block = block_id;
  18003. auto &wrapped_entry = set<SPIRBlock>(block_id);
  18004. wrapped_entry.terminator = SPIRBlock::Return;
  18005. // Push call to original 'main'
  18006. Instruction ix = {};
  18007. ix.op = OpFunctionCall;
  18008. ix.offset = uint32_t(ir.spirv.size());
  18009. ix.length = 3;
  18010. ir.spirv.push_back(f.return_type);
  18011. ir.spirv.push_back(ret_id);
  18012. ir.spirv.push_back(ep.self);
  18013. wrapped_entry.ops.push_back(ix);
  18014. // relace entry-point for new one
  18015. SPIREntryPoint proxy_ep = ep;
  18016. proxy_ep.self = func_id;
  18017. ir.entry_points.insert(std::make_pair(func_id, proxy_ep));
  18018. ir.meta[func_id] = ir.meta[ir.default_entry_point];
  18019. ir.meta[ir.default_entry_point].decoration.alias.clear();
  18020. ir.default_entry_point = func_id;
  18021. }
  18022. void CompilerMSL::emit_mesh_outputs()
  18023. {
  18024. auto &mode = get_entry_point();
  18025. // predefined thread count or zero, if specialization constant is in use
  18026. uint32_t num_invocations = 0;
  18027. if (mode.workgroup_size.id_x == 0 && mode.workgroup_size.id_y == 0 && mode.workgroup_size.id_z == 0)
  18028. num_invocations = mode.workgroup_size.x * mode.workgroup_size.y * mode.workgroup_size.z;
  18029. statement("threadgroup_barrier(mem_flags::mem_threadgroup);");
  18030. statement("if (spvMeshSizes.y == 0)");
  18031. begin_scope();
  18032. statement("return;");
  18033. end_scope();
  18034. statement("spvMesh.set_primitive_count(spvMeshSizes.y);");
  18035. statement("const uint spvThreadCount [[maybe_unused]] = (gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z);");
  18036. if (mesh_out_per_vertex != 0)
  18037. {
  18038. auto &type_vert = get<SPIRType>(mesh_out_per_vertex);
  18039. if (num_invocations < mode.output_vertices)
  18040. {
  18041. statement("for (uint spvVI = gl_LocalInvocationIndex; spvVI < spvMeshSizes.x; spvVI += spvThreadCount)");
  18042. }
  18043. else
  18044. {
  18045. statement("const uint spvVI = gl_LocalInvocationIndex;");
  18046. statement("if (gl_LocalInvocationIndex < spvMeshSizes.x)");
  18047. }
  18048. begin_scope();
  18049. statement("spvPerVertex spvV = {};");
  18050. for (uint32_t index = 0; index < uint32_t(type_vert.member_types.size()); ++index)
  18051. {
  18052. uint32_t orig_var = get_extended_member_decoration(type_vert.self, index, SPIRVCrossDecorationInterfaceOrigID);
  18053. uint32_t orig_id = get_extended_member_decoration(type_vert.self, index, SPIRVCrossDecorationInterfaceMemberIndex);
  18054. // Clip/cull distances are special-case
  18055. if (orig_var == 0 && orig_id == (~0u))
  18056. continue;
  18057. auto &orig = get<SPIRVariable>(orig_var);
  18058. auto &orig_type = get<SPIRType>(orig.basetype);
  18059. // FIXME: Need to deal with complex composite IO types. These may need extra unroll, etc.
  18060. BuiltIn builtin = BuiltInMax;
  18061. std::string access;
  18062. if (orig_type.basetype == SPIRType::Struct)
  18063. {
  18064. if (has_member_decoration(orig_type.self, orig_id, DecorationBuiltIn))
  18065. builtin = BuiltIn(get_member_decoration(orig_type.self, orig_id, DecorationBuiltIn));
  18066. switch (builtin)
  18067. {
  18068. case BuiltInPosition:
  18069. case BuiltInPointSize:
  18070. case BuiltInClipDistance:
  18071. case BuiltInCullDistance:
  18072. access = "." + builtin_to_glsl(builtin, StorageClassOutput);
  18073. break;
  18074. default:
  18075. access = "." + to_member_name(orig_type, orig_id);
  18076. break;
  18077. }
  18078. if (has_member_decoration(type_vert.self, index, DecorationIndex))
  18079. {
  18080. // Declare the Clip/CullDistance as [[user(clip/cullN)]].
  18081. const uint32_t orig_index = get_member_decoration(type_vert.self, index, DecorationIndex);
  18082. access += "[" + to_string(orig_index) + "]";
  18083. statement("spvV.", builtin_to_glsl(builtin, StorageClassOutput), "[", orig_index, "] = ", to_name(orig_var), "[spvVI]", access, ";");
  18084. }
  18085. }
  18086. statement("spvV.", to_member_name(type_vert, index), " = ", to_name(orig_var), "[spvVI]", access, ";");
  18087. if (options.vertex.flip_vert_y && builtin == BuiltInPosition)
  18088. {
  18089. statement("spvV.", to_member_name(type_vert, index), ".y = -(", "spvV.",
  18090. to_member_name(type_vert, index), ".y);", " // Invert Y-axis for Metal");
  18091. }
  18092. }
  18093. statement("spvMesh.set_vertex(spvVI, spvV);");
  18094. end_scope();
  18095. }
  18096. if (mesh_out_per_primitive != 0 || builtin_mesh_primitive_indices_id != 0)
  18097. {
  18098. if (num_invocations < mode.output_primitives)
  18099. {
  18100. statement("for (uint spvPI = gl_LocalInvocationIndex; spvPI < spvMeshSizes.y; spvPI += spvThreadCount)");
  18101. }
  18102. else
  18103. {
  18104. statement("const uint spvPI = gl_LocalInvocationIndex;");
  18105. statement("if (gl_LocalInvocationIndex < spvMeshSizes.y)");
  18106. }
  18107. // FIXME: Need to deal with complex composite IO types. These may need extra unroll, etc.
  18108. begin_scope();
  18109. if (builtin_mesh_primitive_indices_id != 0)
  18110. {
  18111. if (mode.flags.get(ExecutionModeOutputTrianglesEXT))
  18112. {
  18113. statement("spvMesh.set_index(spvPI * 3u + 0u, gl_PrimitiveTriangleIndicesEXT[spvPI].x);");
  18114. statement("spvMesh.set_index(spvPI * 3u + 1u, gl_PrimitiveTriangleIndicesEXT[spvPI].y);");
  18115. statement("spvMesh.set_index(spvPI * 3u + 2u, gl_PrimitiveTriangleIndicesEXT[spvPI].z);");
  18116. }
  18117. else if (mode.flags.get(ExecutionModeOutputLinesEXT))
  18118. {
  18119. statement("spvMesh.set_index(spvPI * 2u + 0u, gl_PrimitiveLineIndicesEXT[spvPI].x);");
  18120. statement("spvMesh.set_index(spvPI * 2u + 1u, gl_PrimitiveLineIndicesEXT[spvPI].y);");
  18121. }
  18122. else
  18123. {
  18124. statement("spvMesh.set_index(spvPI, gl_PrimitivePointIndicesEXT[spvPI]);");
  18125. }
  18126. }
  18127. if (mesh_out_per_primitive != 0)
  18128. {
  18129. auto &type_prim = get<SPIRType>(mesh_out_per_primitive);
  18130. statement("spvPerPrimitive spvP = {};");
  18131. for (uint32_t index = 0; index < uint32_t(type_prim.member_types.size()); ++index)
  18132. {
  18133. uint32_t orig_var =
  18134. get_extended_member_decoration(type_prim.self, index, SPIRVCrossDecorationInterfaceOrigID);
  18135. uint32_t orig_id =
  18136. get_extended_member_decoration(type_prim.self, index, SPIRVCrossDecorationInterfaceMemberIndex);
  18137. auto &orig = get<SPIRVariable>(orig_var);
  18138. auto &orig_type = get<SPIRType>(orig.basetype);
  18139. BuiltIn builtin = BuiltInMax;
  18140. std::string access;
  18141. if (orig_type.basetype == SPIRType::Struct)
  18142. {
  18143. if (has_member_decoration(orig_type.self, orig_id, DecorationBuiltIn))
  18144. builtin = BuiltIn(get_member_decoration(orig_type.self, orig_id, DecorationBuiltIn));
  18145. switch (builtin)
  18146. {
  18147. case BuiltInPrimitiveId:
  18148. case BuiltInLayer:
  18149. case BuiltInViewportIndex:
  18150. case BuiltInCullPrimitiveEXT:
  18151. case BuiltInPrimitiveShadingRateKHR:
  18152. access = "." + builtin_to_glsl(builtin, StorageClassOutput);
  18153. break;
  18154. default:
  18155. access = "." + to_member_name(orig_type, orig_id);
  18156. }
  18157. }
  18158. statement("spvP.", to_member_name(type_prim, index), " = ", to_name(orig_var), "[spvPI]", access, ";");
  18159. }
  18160. statement("spvMesh.set_primitive(spvPI, spvP);");
  18161. }
  18162. end_scope();
  18163. }
  18164. }
  18165. void CompilerMSL::emit_mesh_tasks(SPIRBlock &block)
  18166. {
  18167. // GLSL: Once this instruction is called, the workgroup must be terminated immediately, and the mesh shaders are launched.
  18168. // TODO: find relieble and clean of terminating shader.
  18169. flush_variable_declaration(builtin_task_grid_id);
  18170. statement("spvMgp.set_threadgroups_per_grid(uint3(", to_unpacked_expression(block.mesh.groups[0]), ", ",
  18171. to_unpacked_expression(block.mesh.groups[1]), ", ", to_unpacked_expression(block.mesh.groups[2]), "));");
  18172. // This is correct if EmitMeshTasks is called in the entry function for shader.
  18173. // Only viable solutions would be:
  18174. // - Caller ensures the SPIR-V is inlined, then this always holds true.
  18175. // - Pass down a "should terminate" bool to leaf functions and chain return (horrible and disgusting, let's not).
  18176. statement("return;");
  18177. }
  18178. void CompilerMSL::emit_workgroup_initialization(const SPIRVariable &var)
  18179. {
  18180. auto &type = get_variable_data_type(var);
  18181. begin_scope();
  18182. if (type.array.empty() && type.member_types.empty())
  18183. {
  18184. // For simple shared variables, we just initialize it in thread 0 of the block
  18185. // We use short to represent bool for threadgroup variable to workaround compiler bug,
  18186. // so we do a temporary fixup here. Alas. (see the type_to_glsl method)
  18187. bool is_boolean = type.basetype == SPIRType::Boolean;
  18188. if (is_boolean)
  18189. type.basetype = SPIRType::Short;
  18190. statement("if (gl_LocalInvocationIndex == 0)");
  18191. begin_scope();
  18192. statement(to_name(var.self), " = ", to_initializer_expression(var), ";");
  18193. end_scope();
  18194. if (is_boolean)
  18195. type.basetype = SPIRType::Boolean;
  18196. }
  18197. else
  18198. {
  18199. // Otherwise, we use a loop to cooperatively initialize the memory within the group
  18200. // First, we define a few variable names;
  18201. string var_name = to_name(var.self);
  18202. string var_ptr_name = join(var_name, "_ptr");
  18203. string var_size_name = join(var_name, "_sz");
  18204. string var_pos_name = join(var_name, "_pos");
  18205. string var_stride_name = join(var_name, "_stride");
  18206. string var_ptr2_name = join(var_name, "_ptr2");
  18207. statement("threadgroup uint *", var_ptr_name, " = (threadgroup uint *)&", var_name, ";");
  18208. statement("uint ", var_size_name, " = ", "sizeof(", var_name, ");");
  18209. statement("uint ", var_pos_name, " = gl_LocalInvocationIndex;");
  18210. statement("uint ", var_stride_name, " = gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z;");
  18211. statement("while (sizeof(uint) * ", var_pos_name, " < ", var_size_name, ")");
  18212. begin_scope();
  18213. statement(var_ptr_name, "[", var_pos_name, "] = 0u;");
  18214. statement(var_pos_name, " += ", var_stride_name, ";");
  18215. end_scope();
  18216. statement("if (gl_LocalInvocationIndex == 0)");
  18217. begin_scope();
  18218. statement(var_pos_name, " = (", var_size_name, " / sizeof(uint)) * sizeof(uint);");
  18219. statement("threadgroup uchar *", var_ptr2_name, " = (threadgroup uchar *)&", var_name, ";");
  18220. statement("while (", var_pos_name, " < ", var_size_name, ")");
  18221. begin_scope();
  18222. statement(var_ptr2_name, "[", var_pos_name, "] = '\\0';");
  18223. statement(var_pos_name, "++;");
  18224. end_scope();
  18225. end_scope();
  18226. }
  18227. statement("threadgroup_barrier(mem_flags::mem_threadgroup);");
  18228. end_scope();
  18229. }
  18230. string CompilerMSL::additional_fixed_sample_mask_str() const
  18231. {
  18232. char print_buffer[32];
  18233. #ifdef _MSC_VER
  18234. // snprintf does not exist or is buggy on older MSVC versions, some of
  18235. // them being used by MinGW. Use sprintf instead and disable
  18236. // corresponding warning.
  18237. #pragma warning(push)
  18238. #pragma warning(disable : 4996)
  18239. #endif
  18240. #if defined(_WIN32)
  18241. sprintf(print_buffer, "0x%x", msl_options.additional_fixed_sample_mask);
  18242. #else
  18243. snprintf(print_buffer, sizeof(print_buffer), "0x%x", msl_options.additional_fixed_sample_mask);
  18244. #endif
  18245. #ifdef _MSC_VER
  18246. #pragma warning(pop)
  18247. #endif
  18248. return print_buffer;
  18249. }