spirv_cross.cpp 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807
  1. /*
  2. * Copyright 2015-2021 Arm Limited
  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_cross.hpp"
  23. #include "GLSL.std.450.h"
  24. #include "spirv_cfg.hpp"
  25. #include "spirv_common.hpp"
  26. #include "spirv_parser.hpp"
  27. #include <algorithm>
  28. #include <cstring>
  29. #include <utility>
  30. using namespace std;
  31. using namespace SPIRV_CROSS_SPV_HEADER_NAMESPACE;
  32. using namespace SPIRV_CROSS_NAMESPACE;
  33. Compiler::Compiler(vector<uint32_t> ir_)
  34. {
  35. Parser parser(std::move(ir_));
  36. parser.parse();
  37. set_ir(std::move(parser.get_parsed_ir()));
  38. }
  39. Compiler::Compiler(const uint32_t *ir_, size_t word_count)
  40. {
  41. Parser parser(ir_, word_count);
  42. parser.parse();
  43. set_ir(std::move(parser.get_parsed_ir()));
  44. }
  45. Compiler::Compiler(const ParsedIR &ir_)
  46. {
  47. set_ir(ir_);
  48. }
  49. Compiler::Compiler(ParsedIR &&ir_)
  50. {
  51. set_ir(std::move(ir_));
  52. }
  53. void Compiler::set_ir(ParsedIR &&ir_)
  54. {
  55. ir = std::move(ir_);
  56. parse_fixup();
  57. }
  58. void Compiler::set_ir(const ParsedIR &ir_)
  59. {
  60. ir = ir_;
  61. parse_fixup();
  62. }
  63. string Compiler::compile()
  64. {
  65. return "";
  66. }
  67. bool Compiler::variable_storage_is_aliased(const SPIRVariable &v)
  68. {
  69. auto &type = get<SPIRType>(v.basetype);
  70. bool ssbo = v.storage == StorageClassStorageBuffer ||
  71. ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
  72. bool image = type.basetype == SPIRType::Image;
  73. bool counter = type.basetype == SPIRType::AtomicCounter;
  74. bool buffer_reference = type.storage == StorageClassPhysicalStorageBuffer;
  75. bool is_restrict;
  76. if (ssbo)
  77. is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
  78. else
  79. is_restrict = has_decoration(v.self, DecorationRestrict);
  80. return !is_restrict && (ssbo || image || counter || buffer_reference);
  81. }
  82. bool Compiler::block_is_control_dependent(const SPIRBlock &block)
  83. {
  84. for (auto &i : block.ops)
  85. {
  86. auto ops = stream(i);
  87. auto op = static_cast<Op>(i.op);
  88. switch (op)
  89. {
  90. case OpFunctionCall:
  91. {
  92. uint32_t func = ops[2];
  93. if (function_is_control_dependent(get<SPIRFunction>(func)))
  94. return true;
  95. break;
  96. }
  97. // Derivatives
  98. case OpDPdx:
  99. case OpDPdxCoarse:
  100. case OpDPdxFine:
  101. case OpDPdy:
  102. case OpDPdyCoarse:
  103. case OpDPdyFine:
  104. case OpFwidth:
  105. case OpFwidthCoarse:
  106. case OpFwidthFine:
  107. // Anything implicit LOD
  108. case OpImageSampleImplicitLod:
  109. case OpImageSampleDrefImplicitLod:
  110. case OpImageSampleProjImplicitLod:
  111. case OpImageSampleProjDrefImplicitLod:
  112. case OpImageSparseSampleImplicitLod:
  113. case OpImageSparseSampleDrefImplicitLod:
  114. case OpImageSparseSampleProjImplicitLod:
  115. case OpImageSparseSampleProjDrefImplicitLod:
  116. case OpImageQueryLod:
  117. case OpImageDrefGather:
  118. case OpImageGather:
  119. case OpImageSparseDrefGather:
  120. case OpImageSparseGather:
  121. // Anything subgroups
  122. case OpGroupNonUniformElect:
  123. case OpGroupNonUniformAll:
  124. case OpGroupNonUniformAny:
  125. case OpGroupNonUniformAllEqual:
  126. case OpGroupNonUniformBroadcast:
  127. case OpGroupNonUniformBroadcastFirst:
  128. case OpGroupNonUniformBallot:
  129. case OpGroupNonUniformInverseBallot:
  130. case OpGroupNonUniformBallotBitExtract:
  131. case OpGroupNonUniformBallotBitCount:
  132. case OpGroupNonUniformBallotFindLSB:
  133. case OpGroupNonUniformBallotFindMSB:
  134. case OpGroupNonUniformShuffle:
  135. case OpGroupNonUniformShuffleXor:
  136. case OpGroupNonUniformShuffleUp:
  137. case OpGroupNonUniformShuffleDown:
  138. case OpGroupNonUniformIAdd:
  139. case OpGroupNonUniformFAdd:
  140. case OpGroupNonUniformIMul:
  141. case OpGroupNonUniformFMul:
  142. case OpGroupNonUniformSMin:
  143. case OpGroupNonUniformUMin:
  144. case OpGroupNonUniformFMin:
  145. case OpGroupNonUniformSMax:
  146. case OpGroupNonUniformUMax:
  147. case OpGroupNonUniformFMax:
  148. case OpGroupNonUniformBitwiseAnd:
  149. case OpGroupNonUniformBitwiseOr:
  150. case OpGroupNonUniformBitwiseXor:
  151. case OpGroupNonUniformLogicalAnd:
  152. case OpGroupNonUniformLogicalOr:
  153. case OpGroupNonUniformLogicalXor:
  154. case OpGroupNonUniformQuadBroadcast:
  155. case OpGroupNonUniformQuadSwap:
  156. case OpGroupNonUniformRotateKHR:
  157. // Control barriers
  158. case OpControlBarrier:
  159. return true;
  160. default:
  161. break;
  162. }
  163. }
  164. return false;
  165. }
  166. bool Compiler::block_is_pure(const SPIRBlock &block)
  167. {
  168. // This is a global side effect of the function.
  169. if (block.terminator == SPIRBlock::Kill ||
  170. block.terminator == SPIRBlock::TerminateRay ||
  171. block.terminator == SPIRBlock::IgnoreIntersection ||
  172. block.terminator == SPIRBlock::EmitMeshTasks)
  173. return false;
  174. for (auto &i : block.ops)
  175. {
  176. auto ops = stream(i);
  177. auto op = static_cast<Op>(i.op);
  178. switch (op)
  179. {
  180. case OpFunctionCall:
  181. {
  182. uint32_t func = ops[2];
  183. if (!function_is_pure(get<SPIRFunction>(func)))
  184. return false;
  185. break;
  186. }
  187. case OpCopyMemory:
  188. case OpStore:
  189. case OpCooperativeMatrixStoreKHR:
  190. {
  191. auto &type = expression_type(ops[0]);
  192. if (type.storage != StorageClassFunction)
  193. return false;
  194. break;
  195. }
  196. case OpImageWrite:
  197. return false;
  198. // Atomics are impure.
  199. case OpAtomicLoad:
  200. case OpAtomicStore:
  201. case OpAtomicExchange:
  202. case OpAtomicCompareExchange:
  203. case OpAtomicCompareExchangeWeak:
  204. case OpAtomicIIncrement:
  205. case OpAtomicIDecrement:
  206. case OpAtomicIAdd:
  207. case OpAtomicISub:
  208. case OpAtomicSMin:
  209. case OpAtomicUMin:
  210. case OpAtomicSMax:
  211. case OpAtomicUMax:
  212. case OpAtomicAnd:
  213. case OpAtomicOr:
  214. case OpAtomicXor:
  215. return false;
  216. // Geometry shader builtins modify global state.
  217. case OpEndPrimitive:
  218. case OpEmitStreamVertex:
  219. case OpEndStreamPrimitive:
  220. case OpEmitVertex:
  221. return false;
  222. // Mesh shader functions modify global state.
  223. // (EmitMeshTasks is a terminator).
  224. case OpSetMeshOutputsEXT:
  225. return false;
  226. // Barriers disallow any reordering, so we should treat blocks with barrier as writing.
  227. case OpControlBarrier:
  228. case OpMemoryBarrier:
  229. return false;
  230. // Ray tracing builtins are impure.
  231. case OpReportIntersectionKHR:
  232. case OpIgnoreIntersectionNV:
  233. case OpTerminateRayNV:
  234. case OpTraceNV:
  235. case OpTraceRayKHR:
  236. case OpExecuteCallableNV:
  237. case OpExecuteCallableKHR:
  238. case OpRayQueryInitializeKHR:
  239. case OpRayQueryTerminateKHR:
  240. case OpRayQueryGenerateIntersectionKHR:
  241. case OpRayQueryConfirmIntersectionKHR:
  242. case OpRayQueryProceedKHR:
  243. // There are various getters in ray query, but they are considered pure.
  244. return false;
  245. // OpExtInst is potentially impure depending on extension, but GLSL builtins are at least pure.
  246. case OpDemoteToHelperInvocationEXT:
  247. // This is a global side effect of the function.
  248. return false;
  249. case OpTensorReadARM:
  250. return false;
  251. case OpExtInst:
  252. {
  253. uint32_t extension_set = ops[2];
  254. if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  255. {
  256. auto op_450 = static_cast<GLSLstd450>(ops[3]);
  257. switch (op_450)
  258. {
  259. case GLSLstd450Modf:
  260. case GLSLstd450Frexp:
  261. {
  262. auto &type = expression_type(ops[5]);
  263. if (type.storage != StorageClassFunction)
  264. return false;
  265. break;
  266. }
  267. default:
  268. break;
  269. }
  270. }
  271. break;
  272. }
  273. default:
  274. break;
  275. }
  276. }
  277. return true;
  278. }
  279. string Compiler::to_name(uint32_t id, bool allow_alias) const
  280. {
  281. if (allow_alias && ir.ids[id].get_type() == TypeType)
  282. {
  283. // If this type is a simple alias, emit the
  284. // name of the original type instead.
  285. // We don't want to override the meta alias
  286. // as that can be overridden by the reflection APIs after parse.
  287. auto &type = get<SPIRType>(id);
  288. if (type.type_alias)
  289. {
  290. // If the alias master has been specially packed, we will have emitted a clean variant as well,
  291. // so skip the name aliasing here.
  292. if (!has_extended_decoration(type.type_alias, SPIRVCrossDecorationBufferBlockRepacked))
  293. return to_name(type.type_alias);
  294. }
  295. }
  296. auto &alias = ir.get_name(id);
  297. if (alias.empty())
  298. return join("_", id);
  299. else
  300. return alias;
  301. }
  302. bool Compiler::function_is_pure(const SPIRFunction &func)
  303. {
  304. for (auto block : func.blocks)
  305. if (!block_is_pure(get<SPIRBlock>(block)))
  306. return false;
  307. return true;
  308. }
  309. bool Compiler::function_is_control_dependent(const SPIRFunction &func)
  310. {
  311. for (auto block : func.blocks)
  312. if (block_is_control_dependent(get<SPIRBlock>(block)))
  313. return true;
  314. return false;
  315. }
  316. void Compiler::register_global_read_dependencies(const SPIRBlock &block, uint32_t id)
  317. {
  318. for (auto &i : block.ops)
  319. {
  320. auto ops = stream(i);
  321. auto op = static_cast<Op>(i.op);
  322. switch (op)
  323. {
  324. case OpFunctionCall:
  325. {
  326. uint32_t func = ops[2];
  327. register_global_read_dependencies(get<SPIRFunction>(func), id);
  328. break;
  329. }
  330. case OpLoad:
  331. case OpCooperativeMatrixLoadKHR:
  332. case OpCooperativeVectorLoadNV:
  333. case OpImageRead:
  334. {
  335. // If we're in a storage class which does not get invalidated, adding dependencies here is no big deal.
  336. auto *var = maybe_get_backing_variable(ops[2]);
  337. if (var && var->storage != StorageClassFunction)
  338. {
  339. auto &type = get<SPIRType>(var->basetype);
  340. // InputTargets are immutable.
  341. if (type.basetype != SPIRType::Image && type.image.dim != DimSubpassData)
  342. var->dependees.push_back(id);
  343. }
  344. break;
  345. }
  346. default:
  347. break;
  348. }
  349. }
  350. }
  351. void Compiler::register_global_read_dependencies(const SPIRFunction &func, uint32_t id)
  352. {
  353. for (auto block : func.blocks)
  354. register_global_read_dependencies(get<SPIRBlock>(block), id);
  355. }
  356. SPIRVariable *Compiler::maybe_get_backing_variable(uint32_t chain)
  357. {
  358. auto *var = maybe_get<SPIRVariable>(chain);
  359. if (!var)
  360. {
  361. auto *cexpr = maybe_get<SPIRExpression>(chain);
  362. if (cexpr)
  363. var = maybe_get<SPIRVariable>(cexpr->loaded_from);
  364. auto *access_chain = maybe_get<SPIRAccessChain>(chain);
  365. if (access_chain)
  366. var = maybe_get<SPIRVariable>(access_chain->loaded_from);
  367. }
  368. return var;
  369. }
  370. void Compiler::register_read(uint32_t expr, uint32_t chain, bool forwarded)
  371. {
  372. auto &e = get<SPIRExpression>(expr);
  373. auto *var = maybe_get_backing_variable(chain);
  374. if (var)
  375. {
  376. e.loaded_from = var->self;
  377. // If the backing variable is immutable, we do not need to depend on the variable.
  378. if (forwarded && !is_immutable(var->self))
  379. var->dependees.push_back(e.self);
  380. // If we load from a parameter, make sure we create "inout" if we also write to the parameter.
  381. // The default is "in" however, so we never invalidate our compilation by reading.
  382. if (var && var->parameter)
  383. var->parameter->read_count++;
  384. }
  385. }
  386. void Compiler::register_write(uint32_t chain)
  387. {
  388. auto *var = maybe_get<SPIRVariable>(chain);
  389. if (!var)
  390. {
  391. // If we're storing through an access chain, invalidate the backing variable instead.
  392. auto *expr = maybe_get<SPIRExpression>(chain);
  393. if (expr && expr->loaded_from)
  394. var = maybe_get<SPIRVariable>(expr->loaded_from);
  395. auto *access_chain = maybe_get<SPIRAccessChain>(chain);
  396. if (access_chain && access_chain->loaded_from)
  397. var = maybe_get<SPIRVariable>(access_chain->loaded_from);
  398. }
  399. auto &chain_type = expression_type(chain);
  400. if (var)
  401. {
  402. bool check_argument_storage_qualifier = true;
  403. auto &type = expression_type(chain);
  404. // If our variable is in a storage class which can alias with other buffers,
  405. // invalidate all variables which depend on aliased variables. And if this is a
  406. // variable pointer, then invalidate all variables regardless.
  407. if (get_variable_data_type(*var).pointer)
  408. {
  409. flush_all_active_variables();
  410. if (type.pointer_depth == 1)
  411. {
  412. // We have a backing variable which is a pointer-to-pointer type.
  413. // We are storing some data through a pointer acquired through that variable,
  414. // but we are not writing to the value of the variable itself,
  415. // i.e., we are not modifying the pointer directly.
  416. // If we are storing a non-pointer type (pointer_depth == 1),
  417. // we know that we are storing some unrelated data.
  418. // A case here would be
  419. // void foo(Foo * const *arg) {
  420. // Foo *bar = *arg;
  421. // bar->unrelated = 42;
  422. // }
  423. // arg, the argument is constant.
  424. check_argument_storage_qualifier = false;
  425. }
  426. }
  427. if (type.storage == StorageClassPhysicalStorageBuffer || variable_storage_is_aliased(*var))
  428. flush_all_aliased_variables();
  429. else if (var)
  430. flush_dependees(*var);
  431. // We tried to write to a parameter which is not marked with out qualifier, force a recompile.
  432. if (check_argument_storage_qualifier && var->parameter && var->parameter->write_count == 0)
  433. {
  434. var->parameter->write_count++;
  435. force_recompile();
  436. }
  437. }
  438. else if (chain_type.pointer)
  439. {
  440. // If we stored through a variable pointer, then we don't know which
  441. // variable we stored to. So *all* expressions after this point need to
  442. // be invalidated.
  443. // FIXME: If we can prove that the variable pointer will point to
  444. // only certain variables, we can invalidate only those.
  445. flush_all_active_variables();
  446. }
  447. // If chain_type.pointer is false, we're not writing to memory backed variables, but temporaries instead.
  448. // This can happen in copy_logical_type where we unroll complex reads and writes to temporaries.
  449. }
  450. void Compiler::flush_dependees(SPIRVariable &var)
  451. {
  452. for (auto expr : var.dependees)
  453. invalid_expressions.insert(expr);
  454. var.dependees.clear();
  455. }
  456. void Compiler::flush_all_aliased_variables()
  457. {
  458. for (auto aliased : aliased_variables)
  459. flush_dependees(get<SPIRVariable>(aliased));
  460. }
  461. void Compiler::flush_all_atomic_capable_variables()
  462. {
  463. for (auto global : global_variables)
  464. flush_dependees(get<SPIRVariable>(global));
  465. flush_all_aliased_variables();
  466. }
  467. void Compiler::flush_control_dependent_expressions(uint32_t block_id)
  468. {
  469. auto &block = get<SPIRBlock>(block_id);
  470. for (auto &expr : block.invalidate_expressions)
  471. invalid_expressions.insert(expr);
  472. block.invalidate_expressions.clear();
  473. }
  474. void Compiler::flush_all_active_variables()
  475. {
  476. // Invalidate all temporaries we read from variables in this block since they were forwarded.
  477. // Invalidate all temporaries we read from globals.
  478. for (auto &v : current_function->local_variables)
  479. flush_dependees(get<SPIRVariable>(v));
  480. for (auto &arg : current_function->arguments)
  481. flush_dependees(get<SPIRVariable>(arg.id));
  482. for (auto global : global_variables)
  483. flush_dependees(get<SPIRVariable>(global));
  484. flush_all_aliased_variables();
  485. }
  486. uint32_t Compiler::expression_type_id(uint32_t id) const
  487. {
  488. switch (ir.ids[id].get_type())
  489. {
  490. case TypeVariable:
  491. return get<SPIRVariable>(id).basetype;
  492. case TypeExpression:
  493. return get<SPIRExpression>(id).expression_type;
  494. case TypeConstant:
  495. return get<SPIRConstant>(id).constant_type;
  496. case TypeConstantOp:
  497. return get<SPIRConstantOp>(id).basetype;
  498. case TypeUndef:
  499. return get<SPIRUndef>(id).basetype;
  500. case TypeCombinedImageSampler:
  501. return get<SPIRCombinedImageSampler>(id).combined_type;
  502. case TypeAccessChain:
  503. return get<SPIRAccessChain>(id).basetype;
  504. default:
  505. SPIRV_CROSS_THROW("Cannot resolve expression type.");
  506. }
  507. }
  508. const SPIRType &Compiler::expression_type(uint32_t id) const
  509. {
  510. return get<SPIRType>(expression_type_id(id));
  511. }
  512. bool Compiler::expression_is_lvalue(uint32_t id) const
  513. {
  514. auto &type = expression_type(id);
  515. switch (type.basetype)
  516. {
  517. case SPIRType::SampledImage:
  518. case SPIRType::Image:
  519. case SPIRType::Sampler:
  520. return false;
  521. default:
  522. return true;
  523. }
  524. }
  525. bool Compiler::is_immutable(uint32_t id) const
  526. {
  527. if (ir.ids[id].get_type() == TypeVariable)
  528. {
  529. auto &var = get<SPIRVariable>(id);
  530. // Anything we load from the UniformConstant address space is guaranteed to be immutable.
  531. bool pointer_to_const = var.storage == StorageClassUniformConstant;
  532. return pointer_to_const || var.phi_variable || !expression_is_lvalue(id);
  533. }
  534. else if (ir.ids[id].get_type() == TypeAccessChain)
  535. return get<SPIRAccessChain>(id).immutable;
  536. else if (ir.ids[id].get_type() == TypeExpression)
  537. return get<SPIRExpression>(id).immutable;
  538. else if (ir.ids[id].get_type() == TypeConstant || ir.ids[id].get_type() == TypeConstantOp ||
  539. ir.ids[id].get_type() == TypeUndef)
  540. return true;
  541. else
  542. return false;
  543. }
  544. static inline bool storage_class_is_interface(StorageClass storage)
  545. {
  546. switch (storage)
  547. {
  548. case StorageClassInput:
  549. case StorageClassOutput:
  550. case StorageClassUniform:
  551. case StorageClassUniformConstant:
  552. case StorageClassAtomicCounter:
  553. case StorageClassPushConstant:
  554. case StorageClassStorageBuffer:
  555. return true;
  556. default:
  557. return false;
  558. }
  559. }
  560. bool Compiler::is_hidden_variable(const SPIRVariable &var, bool include_builtins) const
  561. {
  562. if ((is_builtin_variable(var) && !include_builtins) || var.remapped_variable)
  563. return true;
  564. // Combined image samplers are always considered active as they are "magic" variables.
  565. if (find_if(begin(combined_image_samplers), end(combined_image_samplers), [&var](const CombinedImageSampler &samp) {
  566. return samp.combined_id == var.self;
  567. }) != end(combined_image_samplers))
  568. {
  569. return false;
  570. }
  571. // In SPIR-V 1.4 and up we must also use the active variable interface to disable global variables
  572. // which are not part of the entry point.
  573. if (ir.get_spirv_version() >= 0x10400 && var.storage != StorageClassGeneric &&
  574. var.storage != StorageClassFunction && !interface_variable_exists_in_entry_point(var.self))
  575. {
  576. return true;
  577. }
  578. return check_active_interface_variables && storage_class_is_interface(var.storage) &&
  579. active_interface_variables.find(var.self) == end(active_interface_variables);
  580. }
  581. bool Compiler::is_builtin_type(const SPIRType &type) const
  582. {
  583. auto *type_meta = ir.find_meta(type.self);
  584. // We can have builtin structs as well. If one member of a struct is builtin, the struct must also be builtin.
  585. if (type_meta)
  586. for (auto &m : type_meta->members)
  587. if (m.builtin)
  588. return true;
  589. return false;
  590. }
  591. bool Compiler::is_builtin_variable(const SPIRVariable &var) const
  592. {
  593. auto *m = ir.find_meta(var.self);
  594. if (var.compat_builtin || (m && m->decoration.builtin))
  595. return true;
  596. else
  597. return is_builtin_type(get<SPIRType>(var.basetype));
  598. }
  599. bool Compiler::is_member_builtin(const SPIRType &type, uint32_t index, BuiltIn *builtin) const
  600. {
  601. auto *type_meta = ir.find_meta(type.self);
  602. if (type_meta)
  603. {
  604. auto &memb = type_meta->members;
  605. if (index < memb.size() && memb[index].builtin)
  606. {
  607. if (builtin)
  608. *builtin = memb[index].builtin_type;
  609. return true;
  610. }
  611. }
  612. return false;
  613. }
  614. bool Compiler::is_scalar(const SPIRType &type) const
  615. {
  616. return type.basetype != SPIRType::Struct && type.vecsize == 1 && type.columns == 1;
  617. }
  618. bool Compiler::is_vector(const SPIRType &type) const
  619. {
  620. return type.vecsize > 1 && type.columns == 1;
  621. }
  622. bool Compiler::is_matrix(const SPIRType &type) const
  623. {
  624. return type.vecsize > 1 && type.columns > 1;
  625. }
  626. bool Compiler::is_array(const SPIRType &type) const
  627. {
  628. return type.op == OpTypeArray || type.op == OpTypeRuntimeArray;
  629. }
  630. bool Compiler::is_pointer(const SPIRType &type) const
  631. {
  632. return type.op == OpTypePointer && type.basetype != SPIRType::Unknown; // Ignore function pointers.
  633. }
  634. bool Compiler::is_physical_pointer(const SPIRType &type) const
  635. {
  636. return type.op == OpTypePointer && type.storage == StorageClassPhysicalStorageBuffer;
  637. }
  638. bool Compiler::is_physical_or_buffer_pointer(const SPIRType &type) const
  639. {
  640. return type.op == OpTypePointer &&
  641. (type.storage == StorageClassPhysicalStorageBuffer || type.storage == StorageClassUniform ||
  642. type.storage == StorageClassStorageBuffer || type.storage == StorageClassWorkgroup ||
  643. type.storage == StorageClassPushConstant);
  644. }
  645. bool Compiler::is_physical_pointer_to_buffer_block(const SPIRType &type) const
  646. {
  647. return is_physical_pointer(type) && get_pointee_type(type).self == type.parent_type &&
  648. (has_decoration(type.self, DecorationBlock) ||
  649. has_decoration(type.self, DecorationBufferBlock));
  650. }
  651. bool Compiler::is_runtime_size_array(const SPIRType &type)
  652. {
  653. return type.op == OpTypeRuntimeArray;
  654. }
  655. ShaderResources Compiler::get_shader_resources() const
  656. {
  657. return get_shader_resources(nullptr);
  658. }
  659. ShaderResources Compiler::get_shader_resources(const unordered_set<VariableID> &active_variables) const
  660. {
  661. return get_shader_resources(&active_variables);
  662. }
  663. bool Compiler::InterfaceVariableAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  664. {
  665. uint32_t variable = 0;
  666. switch (opcode)
  667. {
  668. // Need this first, otherwise, GCC complains about unhandled switch statements.
  669. default:
  670. break;
  671. case OpFunctionCall:
  672. {
  673. // Invalid SPIR-V.
  674. if (length < 3)
  675. return false;
  676. uint32_t count = length - 3;
  677. args += 3;
  678. for (uint32_t i = 0; i < count; i++)
  679. {
  680. auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
  681. if (var && storage_class_is_interface(var->storage))
  682. variables.insert(args[i]);
  683. }
  684. break;
  685. }
  686. case OpSelect:
  687. {
  688. // Invalid SPIR-V.
  689. if (length < 5)
  690. return false;
  691. uint32_t count = length - 3;
  692. args += 3;
  693. for (uint32_t i = 0; i < count; i++)
  694. {
  695. auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
  696. if (var && storage_class_is_interface(var->storage))
  697. variables.insert(args[i]);
  698. }
  699. break;
  700. }
  701. case OpPhi:
  702. {
  703. // Invalid SPIR-V.
  704. if (length < 2)
  705. return false;
  706. uint32_t count = length - 2;
  707. args += 2;
  708. for (uint32_t i = 0; i < count; i += 2)
  709. {
  710. auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
  711. if (var && storage_class_is_interface(var->storage))
  712. variables.insert(args[i]);
  713. }
  714. break;
  715. }
  716. case OpAtomicStore:
  717. case OpStore:
  718. case OpCooperativeMatrixStoreKHR:
  719. // Invalid SPIR-V.
  720. if (length < 1)
  721. return false;
  722. variable = args[0];
  723. break;
  724. case OpCopyMemory:
  725. {
  726. if (length < 2)
  727. return false;
  728. auto *var = compiler.maybe_get<SPIRVariable>(args[0]);
  729. if (var && storage_class_is_interface(var->storage))
  730. variables.insert(args[0]);
  731. var = compiler.maybe_get<SPIRVariable>(args[1]);
  732. if (var && storage_class_is_interface(var->storage))
  733. variables.insert(args[1]);
  734. break;
  735. }
  736. case OpExtInst:
  737. {
  738. if (length < 3)
  739. return false;
  740. auto &extension_set = compiler.get<SPIRExtension>(args[2]);
  741. switch (extension_set.ext)
  742. {
  743. case SPIRExtension::GLSL:
  744. {
  745. auto op = static_cast<GLSLstd450>(args[3]);
  746. switch (op)
  747. {
  748. case GLSLstd450InterpolateAtCentroid:
  749. case GLSLstd450InterpolateAtSample:
  750. case GLSLstd450InterpolateAtOffset:
  751. {
  752. auto *var = compiler.maybe_get<SPIRVariable>(args[4]);
  753. if (var && storage_class_is_interface(var->storage))
  754. variables.insert(args[4]);
  755. break;
  756. }
  757. case GLSLstd450Modf:
  758. case GLSLstd450Fract:
  759. {
  760. auto *var = compiler.maybe_get<SPIRVariable>(args[5]);
  761. if (var && storage_class_is_interface(var->storage))
  762. variables.insert(args[5]);
  763. break;
  764. }
  765. default:
  766. break;
  767. }
  768. break;
  769. }
  770. case SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter:
  771. {
  772. enum AMDShaderExplicitVertexParameter
  773. {
  774. InterpolateAtVertexAMD = 1
  775. };
  776. auto op = static_cast<AMDShaderExplicitVertexParameter>(args[3]);
  777. switch (op)
  778. {
  779. case InterpolateAtVertexAMD:
  780. {
  781. auto *var = compiler.maybe_get<SPIRVariable>(args[4]);
  782. if (var && storage_class_is_interface(var->storage))
  783. variables.insert(args[4]);
  784. break;
  785. }
  786. default:
  787. break;
  788. }
  789. break;
  790. }
  791. default:
  792. break;
  793. }
  794. break;
  795. }
  796. case OpAccessChain:
  797. case OpInBoundsAccessChain:
  798. case OpPtrAccessChain:
  799. case OpLoad:
  800. case OpCooperativeMatrixLoadKHR:
  801. case OpCopyObject:
  802. case OpImageTexelPointer:
  803. case OpAtomicLoad:
  804. case OpAtomicExchange:
  805. case OpAtomicCompareExchange:
  806. case OpAtomicCompareExchangeWeak:
  807. case OpAtomicIIncrement:
  808. case OpAtomicIDecrement:
  809. case OpAtomicIAdd:
  810. case OpAtomicISub:
  811. case OpAtomicSMin:
  812. case OpAtomicUMin:
  813. case OpAtomicSMax:
  814. case OpAtomicUMax:
  815. case OpAtomicAnd:
  816. case OpAtomicOr:
  817. case OpAtomicXor:
  818. case OpArrayLength:
  819. // Invalid SPIR-V.
  820. if (length < 3)
  821. return false;
  822. variable = args[2];
  823. break;
  824. }
  825. if (variable)
  826. {
  827. auto *var = compiler.maybe_get<SPIRVariable>(variable);
  828. if (var && storage_class_is_interface(var->storage))
  829. variables.insert(variable);
  830. }
  831. return true;
  832. }
  833. unordered_set<VariableID> Compiler::get_active_interface_variables() const
  834. {
  835. // Traverse the call graph and find all interface variables which are in use.
  836. unordered_set<VariableID> variables;
  837. InterfaceVariableAccessHandler handler(*this, variables);
  838. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  839. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  840. if (var.storage != StorageClassOutput)
  841. return;
  842. if (!interface_variable_exists_in_entry_point(var.self))
  843. return;
  844. // An output variable which is just declared (but uninitialized) might be read by subsequent stages
  845. // so we should force-enable these outputs,
  846. // since compilation will fail if a subsequent stage attempts to read from the variable in question.
  847. // Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
  848. if (var.initializer != ID(0) || get_execution_model() != ExecutionModelFragment)
  849. variables.insert(var.self);
  850. });
  851. // If we needed to create one, we'll need it.
  852. if (dummy_sampler_id)
  853. variables.insert(dummy_sampler_id);
  854. return variables;
  855. }
  856. void Compiler::set_enabled_interface_variables(std::unordered_set<VariableID> active_variables)
  857. {
  858. active_interface_variables = std::move(active_variables);
  859. check_active_interface_variables = true;
  860. }
  861. ShaderResources Compiler::get_shader_resources(const unordered_set<VariableID> *active_variables) const
  862. {
  863. ShaderResources res;
  864. bool ssbo_instance_name = reflection_ssbo_instance_name_is_significant();
  865. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  866. auto &type = this->get<SPIRType>(var.basetype);
  867. // It is possible for uniform storage classes to be passed as function parameters, so detect
  868. // that. To detect function parameters, check of StorageClass of variable is function scope.
  869. if (var.storage == StorageClassFunction || !type.pointer)
  870. return;
  871. if (active_variables && active_variables->find(var.self) == end(*active_variables))
  872. return;
  873. // In SPIR-V 1.4 and up, every global must be present in the entry point interface list,
  874. // not just IO variables.
  875. bool active_in_entry_point = true;
  876. if (ir.get_spirv_version() < 0x10400)
  877. {
  878. if (var.storage == StorageClassInput || var.storage == StorageClassOutput)
  879. active_in_entry_point = interface_variable_exists_in_entry_point(var.self);
  880. }
  881. else
  882. active_in_entry_point = interface_variable_exists_in_entry_point(var.self);
  883. if (!active_in_entry_point)
  884. return;
  885. bool is_builtin = is_builtin_variable(var);
  886. if (is_builtin)
  887. {
  888. if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
  889. return;
  890. auto &list = var.storage == StorageClassInput ? res.builtin_inputs : res.builtin_outputs;
  891. BuiltInResource resource;
  892. if (has_decoration(type.self, DecorationBlock))
  893. {
  894. resource.resource = { var.self, var.basetype, type.self,
  895. get_remapped_declared_block_name(var.self, false) };
  896. for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
  897. {
  898. resource.value_type_id = type.member_types[i];
  899. resource.builtin = BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn));
  900. list.push_back(resource);
  901. }
  902. }
  903. else
  904. {
  905. bool strip_array =
  906. !has_decoration(var.self, DecorationPatch) && (
  907. get_execution_model() == ExecutionModelTessellationControl ||
  908. (get_execution_model() == ExecutionModelTessellationEvaluation &&
  909. var.storage == StorageClassInput));
  910. resource.resource = { var.self, var.basetype, type.self, get_name(var.self) };
  911. if (strip_array && !type.array.empty())
  912. resource.value_type_id = get_variable_data_type(var).parent_type;
  913. else
  914. resource.value_type_id = get_variable_data_type_id(var);
  915. assert(resource.value_type_id);
  916. resource.builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  917. list.push_back(std::move(resource));
  918. }
  919. return;
  920. }
  921. // Input
  922. if (var.storage == StorageClassInput)
  923. {
  924. if (has_decoration(type.self, DecorationBlock))
  925. {
  926. res.stage_inputs.push_back(
  927. { var.self, var.basetype, type.self,
  928. get_remapped_declared_block_name(var.self, false) });
  929. }
  930. else
  931. res.stage_inputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  932. }
  933. // Subpass inputs
  934. else if (var.storage == StorageClassUniformConstant && type.image.dim == DimSubpassData)
  935. {
  936. res.subpass_inputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  937. }
  938. // Outputs
  939. else if (var.storage == StorageClassOutput)
  940. {
  941. if (has_decoration(type.self, DecorationBlock))
  942. {
  943. res.stage_outputs.push_back(
  944. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, false) });
  945. }
  946. else
  947. res.stage_outputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  948. }
  949. // UBOs
  950. else if (type.storage == StorageClassUniform && has_decoration(type.self, DecorationBlock))
  951. {
  952. res.uniform_buffers.push_back(
  953. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, false) });
  954. }
  955. // Old way to declare SSBOs.
  956. else if (type.storage == StorageClassUniform && has_decoration(type.self, DecorationBufferBlock))
  957. {
  958. res.storage_buffers.push_back(
  959. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
  960. }
  961. // Modern way to declare SSBOs.
  962. else if (type.storage == StorageClassStorageBuffer)
  963. {
  964. res.storage_buffers.push_back(
  965. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
  966. }
  967. // Push constant blocks
  968. else if (type.storage == StorageClassPushConstant)
  969. {
  970. // There can only be one push constant block, but keep the vector in case this restriction is lifted
  971. // in the future.
  972. res.push_constant_buffers.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  973. }
  974. else if (type.storage == StorageClassShaderRecordBufferKHR)
  975. {
  976. res.shader_record_buffers.push_back({ var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
  977. }
  978. // Atomic counters
  979. else if (type.storage == StorageClassAtomicCounter)
  980. {
  981. res.atomic_counters.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  982. }
  983. else if (type.storage == StorageClassUniformConstant)
  984. {
  985. if (type.basetype == SPIRType::Image)
  986. {
  987. // Images
  988. if (type.image.sampled == 2)
  989. {
  990. res.storage_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  991. }
  992. // Separate images
  993. else if (type.image.sampled == 1)
  994. {
  995. res.separate_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  996. }
  997. }
  998. // Separate samplers
  999. else if (type.basetype == SPIRType::Sampler)
  1000. {
  1001. res.separate_samplers.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1002. }
  1003. // Textures
  1004. else if (type.basetype == SPIRType::SampledImage)
  1005. {
  1006. res.sampled_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1007. }
  1008. // Acceleration structures
  1009. else if (type.basetype == SPIRType::AccelerationStructure)
  1010. {
  1011. res.acceleration_structures.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1012. }
  1013. // Tensors
  1014. else if (type.basetype == SPIRType::Tensor)
  1015. {
  1016. res.tensors.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1017. }
  1018. else
  1019. {
  1020. res.gl_plain_uniforms.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1021. }
  1022. }
  1023. });
  1024. return res;
  1025. }
  1026. bool Compiler::type_is_top_level_block(const SPIRType &type) const
  1027. {
  1028. if (type.basetype != SPIRType::Struct)
  1029. return false;
  1030. return has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
  1031. }
  1032. bool Compiler::type_is_explicit_layout(const SPIRType &type) const
  1033. {
  1034. if (type.basetype == SPIRType::Struct)
  1035. {
  1036. // Block-like types may have Offset decorations.
  1037. for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
  1038. if (has_member_decoration(type.self, i, DecorationOffset))
  1039. return true;
  1040. }
  1041. return false;
  1042. }
  1043. bool Compiler::type_is_block_like(const SPIRType &type) const
  1044. {
  1045. if (type_is_top_level_block(type))
  1046. return true;
  1047. else
  1048. return type_is_explicit_layout(type);
  1049. }
  1050. void Compiler::parse_fixup()
  1051. {
  1052. // Figure out specialization constants for work group sizes.
  1053. for (auto id_ : ir.ids_for_constant_or_variable)
  1054. {
  1055. auto &id = ir.ids[id_];
  1056. if (id.get_type() == TypeConstant)
  1057. {
  1058. auto &c = id.get<SPIRConstant>();
  1059. if (has_decoration(c.self, DecorationBuiltIn) &&
  1060. BuiltIn(get_decoration(c.self, DecorationBuiltIn)) == BuiltInWorkgroupSize)
  1061. {
  1062. // In current SPIR-V, there can be just one constant like this.
  1063. // All entry points will receive the constant value.
  1064. // WorkgroupSize take precedence over LocalSizeId.
  1065. for (auto &entry : ir.entry_points)
  1066. {
  1067. entry.second.workgroup_size.constant = c.self;
  1068. entry.second.workgroup_size.x = c.scalar(0, 0);
  1069. entry.second.workgroup_size.y = c.scalar(0, 1);
  1070. entry.second.workgroup_size.z = c.scalar(0, 2);
  1071. }
  1072. }
  1073. }
  1074. else if (id.get_type() == TypeVariable)
  1075. {
  1076. auto &var = id.get<SPIRVariable>();
  1077. if (var.storage == StorageClassPrivate || var.storage == StorageClassWorkgroup ||
  1078. var.storage == StorageClassTaskPayloadWorkgroupEXT ||
  1079. var.storage == StorageClassOutput)
  1080. {
  1081. global_variables.push_back(var.self);
  1082. }
  1083. if (variable_storage_is_aliased(var))
  1084. aliased_variables.push_back(var.self);
  1085. }
  1086. }
  1087. }
  1088. void Compiler::update_name_cache(unordered_set<string> &cache_primary, const unordered_set<string> &cache_secondary,
  1089. string &name)
  1090. {
  1091. if (name.empty())
  1092. return;
  1093. const auto find_name = [&](const string &n) -> bool {
  1094. if (cache_primary.find(n) != end(cache_primary))
  1095. return true;
  1096. if (&cache_primary != &cache_secondary)
  1097. if (cache_secondary.find(n) != end(cache_secondary))
  1098. return true;
  1099. return false;
  1100. };
  1101. const auto insert_name = [&](const string &n) { cache_primary.insert(n); };
  1102. if (!find_name(name))
  1103. {
  1104. insert_name(name);
  1105. return;
  1106. }
  1107. uint32_t counter = 0;
  1108. auto tmpname = name;
  1109. bool use_linked_underscore = true;
  1110. if (tmpname == "_")
  1111. {
  1112. // We cannot just append numbers, as we will end up creating internally reserved names.
  1113. // Make it like _0_<counter> instead.
  1114. tmpname += "0";
  1115. }
  1116. else if (tmpname.back() == '_')
  1117. {
  1118. // The last_character is an underscore, so we don't need to link in underscore.
  1119. // This would violate double underscore rules.
  1120. use_linked_underscore = false;
  1121. }
  1122. // If there is a collision (very rare),
  1123. // keep tacking on extra identifier until it's unique.
  1124. do
  1125. {
  1126. counter++;
  1127. name = tmpname + (use_linked_underscore ? "_" : "") + convert_to_string(counter);
  1128. } while (find_name(name));
  1129. insert_name(name);
  1130. }
  1131. void Compiler::update_name_cache(unordered_set<string> &cache, string &name)
  1132. {
  1133. update_name_cache(cache, cache, name);
  1134. }
  1135. void Compiler::set_name(ID id, const std::string &name)
  1136. {
  1137. ir.set_name(id, name);
  1138. }
  1139. const SPIRType &Compiler::get_type(TypeID id) const
  1140. {
  1141. return get<SPIRType>(id);
  1142. }
  1143. const SPIRType &Compiler::get_type_from_variable(VariableID id) const
  1144. {
  1145. return get<SPIRType>(get<SPIRVariable>(id).basetype);
  1146. }
  1147. uint32_t Compiler::get_pointee_type_id(uint32_t type_id) const
  1148. {
  1149. auto *p_type = &get<SPIRType>(type_id);
  1150. if (p_type->pointer)
  1151. {
  1152. assert(p_type->parent_type);
  1153. type_id = p_type->parent_type;
  1154. }
  1155. return type_id;
  1156. }
  1157. const SPIRType &Compiler::get_pointee_type(const SPIRType &type) const
  1158. {
  1159. auto *p_type = &type;
  1160. if (p_type->pointer)
  1161. {
  1162. assert(p_type->parent_type);
  1163. p_type = &get<SPIRType>(p_type->parent_type);
  1164. }
  1165. return *p_type;
  1166. }
  1167. const SPIRType &Compiler::get_pointee_type(uint32_t type_id) const
  1168. {
  1169. return get_pointee_type(get<SPIRType>(type_id));
  1170. }
  1171. uint32_t Compiler::get_variable_data_type_id(const SPIRVariable &var) const
  1172. {
  1173. if (var.phi_variable || var.storage == StorageClassAtomicCounter)
  1174. return var.basetype;
  1175. return get_pointee_type_id(var.basetype);
  1176. }
  1177. SPIRType &Compiler::get_variable_data_type(const SPIRVariable &var)
  1178. {
  1179. return get<SPIRType>(get_variable_data_type_id(var));
  1180. }
  1181. const SPIRType &Compiler::get_variable_data_type(const SPIRVariable &var) const
  1182. {
  1183. return get<SPIRType>(get_variable_data_type_id(var));
  1184. }
  1185. SPIRType &Compiler::get_variable_element_type(const SPIRVariable &var)
  1186. {
  1187. SPIRType *type = &get_variable_data_type(var);
  1188. if (is_array(*type))
  1189. type = &get<SPIRType>(type->parent_type);
  1190. return *type;
  1191. }
  1192. const SPIRType &Compiler::get_variable_element_type(const SPIRVariable &var) const
  1193. {
  1194. const SPIRType *type = &get_variable_data_type(var);
  1195. if (is_array(*type))
  1196. type = &get<SPIRType>(type->parent_type);
  1197. return *type;
  1198. }
  1199. bool Compiler::is_sampled_image_type(const SPIRType &type)
  1200. {
  1201. return (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage) && type.image.sampled == 1 &&
  1202. type.image.dim != DimBuffer;
  1203. }
  1204. void Compiler::set_member_decoration_string(TypeID id, uint32_t index, Decoration decoration,
  1205. const std::string &argument)
  1206. {
  1207. ir.set_member_decoration_string(id, index, decoration, argument);
  1208. }
  1209. void Compiler::set_member_decoration(TypeID id, uint32_t index, Decoration decoration, uint32_t argument)
  1210. {
  1211. ir.set_member_decoration(id, index, decoration, argument);
  1212. }
  1213. void Compiler::set_member_name(TypeID id, uint32_t index, const std::string &name)
  1214. {
  1215. ir.set_member_name(id, index, name);
  1216. }
  1217. const std::string &Compiler::get_member_name(TypeID id, uint32_t index) const
  1218. {
  1219. return ir.get_member_name(id, index);
  1220. }
  1221. void Compiler::set_qualified_name(uint32_t id, const string &name)
  1222. {
  1223. ir.meta[id].decoration.qualified_alias = name;
  1224. }
  1225. void Compiler::set_member_qualified_name(uint32_t type_id, uint32_t index, const std::string &name)
  1226. {
  1227. ir.meta[type_id].members.resize(max(ir.meta[type_id].members.size(), size_t(index) + 1));
  1228. ir.meta[type_id].members[index].qualified_alias = name;
  1229. }
  1230. const string &Compiler::get_member_qualified_name(TypeID type_id, uint32_t index) const
  1231. {
  1232. auto *m = ir.find_meta(type_id);
  1233. if (m && index < m->members.size())
  1234. return m->members[index].qualified_alias;
  1235. else
  1236. return ir.get_empty_string();
  1237. }
  1238. uint32_t Compiler::get_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
  1239. {
  1240. return ir.get_member_decoration(id, index, decoration);
  1241. }
  1242. const Bitset &Compiler::get_member_decoration_bitset(TypeID id, uint32_t index) const
  1243. {
  1244. return ir.get_member_decoration_bitset(id, index);
  1245. }
  1246. bool Compiler::has_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
  1247. {
  1248. return ir.has_member_decoration(id, index, decoration);
  1249. }
  1250. void Compiler::unset_member_decoration(TypeID id, uint32_t index, Decoration decoration)
  1251. {
  1252. ir.unset_member_decoration(id, index, decoration);
  1253. }
  1254. void Compiler::set_decoration_string(ID id, Decoration decoration, const std::string &argument)
  1255. {
  1256. ir.set_decoration_string(id, decoration, argument);
  1257. }
  1258. void Compiler::set_decoration(ID id, Decoration decoration, uint32_t argument)
  1259. {
  1260. ir.set_decoration(id, decoration, argument);
  1261. }
  1262. void Compiler::set_extended_decoration(uint32_t id, ExtendedDecorations decoration, uint32_t value)
  1263. {
  1264. auto &dec = ir.meta[id].decoration;
  1265. dec.extended.flags.set(decoration);
  1266. dec.extended.values[decoration] = value;
  1267. }
  1268. void Compiler::set_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration,
  1269. uint32_t value)
  1270. {
  1271. ir.meta[type].members.resize(max(ir.meta[type].members.size(), size_t(index) + 1));
  1272. auto &dec = ir.meta[type].members[index];
  1273. dec.extended.flags.set(decoration);
  1274. dec.extended.values[decoration] = value;
  1275. }
  1276. static uint32_t get_default_extended_decoration(ExtendedDecorations decoration)
  1277. {
  1278. switch (decoration)
  1279. {
  1280. case SPIRVCrossDecorationResourceIndexPrimary:
  1281. case SPIRVCrossDecorationResourceIndexSecondary:
  1282. case SPIRVCrossDecorationResourceIndexTertiary:
  1283. case SPIRVCrossDecorationResourceIndexQuaternary:
  1284. case SPIRVCrossDecorationInterfaceMemberIndex:
  1285. return ~(0u);
  1286. default:
  1287. return 0;
  1288. }
  1289. }
  1290. uint32_t Compiler::get_extended_decoration(uint32_t id, ExtendedDecorations decoration) const
  1291. {
  1292. auto *m = ir.find_meta(id);
  1293. if (!m)
  1294. return 0;
  1295. auto &dec = m->decoration;
  1296. if (!dec.extended.flags.get(decoration))
  1297. return get_default_extended_decoration(decoration);
  1298. return dec.extended.values[decoration];
  1299. }
  1300. uint32_t Compiler::get_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const
  1301. {
  1302. auto *m = ir.find_meta(type);
  1303. if (!m)
  1304. return 0;
  1305. if (index >= m->members.size())
  1306. return 0;
  1307. auto &dec = m->members[index];
  1308. if (!dec.extended.flags.get(decoration))
  1309. return get_default_extended_decoration(decoration);
  1310. return dec.extended.values[decoration];
  1311. }
  1312. bool Compiler::has_extended_decoration(uint32_t id, ExtendedDecorations decoration) const
  1313. {
  1314. auto *m = ir.find_meta(id);
  1315. if (!m)
  1316. return false;
  1317. auto &dec = m->decoration;
  1318. return dec.extended.flags.get(decoration);
  1319. }
  1320. bool Compiler::has_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const
  1321. {
  1322. auto *m = ir.find_meta(type);
  1323. if (!m)
  1324. return false;
  1325. if (index >= m->members.size())
  1326. return false;
  1327. auto &dec = m->members[index];
  1328. return dec.extended.flags.get(decoration);
  1329. }
  1330. void Compiler::unset_extended_decoration(uint32_t id, ExtendedDecorations decoration)
  1331. {
  1332. auto &dec = ir.meta[id].decoration;
  1333. dec.extended.flags.clear(decoration);
  1334. dec.extended.values[decoration] = 0;
  1335. }
  1336. void Compiler::unset_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration)
  1337. {
  1338. ir.meta[type].members.resize(max(ir.meta[type].members.size(), size_t(index) + 1));
  1339. auto &dec = ir.meta[type].members[index];
  1340. dec.extended.flags.clear(decoration);
  1341. dec.extended.values[decoration] = 0;
  1342. }
  1343. StorageClass Compiler::get_storage_class(VariableID id) const
  1344. {
  1345. return get<SPIRVariable>(id).storage;
  1346. }
  1347. const std::string &Compiler::get_name(ID id) const
  1348. {
  1349. return ir.get_name(id);
  1350. }
  1351. const std::string Compiler::get_fallback_name(ID id) const
  1352. {
  1353. return join("_", id);
  1354. }
  1355. const std::string Compiler::get_block_fallback_name(VariableID id) const
  1356. {
  1357. auto &var = get<SPIRVariable>(id);
  1358. if (get_name(id).empty())
  1359. return join("_", get<SPIRType>(var.basetype).self, "_", id);
  1360. else
  1361. return get_name(id);
  1362. }
  1363. const Bitset &Compiler::get_decoration_bitset(ID id) const
  1364. {
  1365. return ir.get_decoration_bitset(id);
  1366. }
  1367. bool Compiler::has_decoration(ID id, Decoration decoration) const
  1368. {
  1369. return ir.has_decoration(id, decoration);
  1370. }
  1371. const string &Compiler::get_decoration_string(ID id, Decoration decoration) const
  1372. {
  1373. return ir.get_decoration_string(id, decoration);
  1374. }
  1375. const string &Compiler::get_member_decoration_string(TypeID id, uint32_t index, Decoration decoration) const
  1376. {
  1377. return ir.get_member_decoration_string(id, index, decoration);
  1378. }
  1379. uint32_t Compiler::get_decoration(ID id, Decoration decoration) const
  1380. {
  1381. return ir.get_decoration(id, decoration);
  1382. }
  1383. void Compiler::unset_decoration(ID id, Decoration decoration)
  1384. {
  1385. ir.unset_decoration(id, decoration);
  1386. }
  1387. bool Compiler::get_binary_offset_for_decoration(VariableID id, Decoration decoration, uint32_t &word_offset) const
  1388. {
  1389. auto *m = ir.find_meta(id);
  1390. if (!m)
  1391. return false;
  1392. auto &word_offsets = m->decoration_word_offset;
  1393. auto itr = word_offsets.find(decoration);
  1394. if (itr == end(word_offsets))
  1395. return false;
  1396. word_offset = itr->second;
  1397. return true;
  1398. }
  1399. bool Compiler::block_is_noop(const SPIRBlock &block) const
  1400. {
  1401. if (block.terminator != SPIRBlock::Direct)
  1402. return false;
  1403. auto &child = get<SPIRBlock>(block.next_block);
  1404. // If this block participates in PHI, the block isn't really noop.
  1405. for (auto &phi : block.phi_variables)
  1406. if (phi.parent == block.self || phi.parent == child.self)
  1407. return false;
  1408. for (auto &phi : child.phi_variables)
  1409. if (phi.parent == block.self)
  1410. return false;
  1411. // Verify all instructions have no semantic impact.
  1412. for (auto &i : block.ops)
  1413. {
  1414. auto op = static_cast<Op>(i.op);
  1415. switch (op)
  1416. {
  1417. // Non-Semantic instructions.
  1418. case OpLine:
  1419. case OpNoLine:
  1420. break;
  1421. case OpExtInst:
  1422. {
  1423. auto *ops = stream(i);
  1424. auto ext = get<SPIRExtension>(ops[2]).ext;
  1425. bool ext_is_nonsemantic_only =
  1426. ext == SPIRExtension::NonSemanticShaderDebugInfo ||
  1427. ext == SPIRExtension::SPV_debug_info ||
  1428. ext == SPIRExtension::NonSemanticGeneric;
  1429. if (!ext_is_nonsemantic_only)
  1430. return false;
  1431. break;
  1432. }
  1433. default:
  1434. return false;
  1435. }
  1436. }
  1437. return true;
  1438. }
  1439. bool Compiler::block_is_loop_candidate(const SPIRBlock &block, SPIRBlock::Method method) const
  1440. {
  1441. // Tried and failed.
  1442. if (block.disable_block_optimization || block.complex_continue)
  1443. return false;
  1444. if (method == SPIRBlock::MergeToSelectForLoop || method == SPIRBlock::MergeToSelectContinueForLoop)
  1445. {
  1446. // Try to detect common for loop pattern
  1447. // which the code backend can use to create cleaner code.
  1448. // for(;;) { if (cond) { some_body; } else { break; } }
  1449. // is the pattern we're looking for.
  1450. const auto *false_block = maybe_get<SPIRBlock>(block.false_block);
  1451. const auto *true_block = maybe_get<SPIRBlock>(block.true_block);
  1452. const auto *merge_block = maybe_get<SPIRBlock>(block.merge_block);
  1453. bool false_block_is_merge = block.false_block == block.merge_block ||
  1454. (false_block && merge_block && execution_is_noop(*false_block, *merge_block));
  1455. bool true_block_is_merge = block.true_block == block.merge_block ||
  1456. (true_block && merge_block && execution_is_noop(*true_block, *merge_block));
  1457. bool positive_candidate =
  1458. block.true_block != block.merge_block && block.true_block != block.self && false_block_is_merge;
  1459. bool negative_candidate =
  1460. block.false_block != block.merge_block && block.false_block != block.self && true_block_is_merge;
  1461. bool ret = block.terminator == SPIRBlock::Select && block.merge == SPIRBlock::MergeLoop &&
  1462. (positive_candidate || negative_candidate);
  1463. if (ret && positive_candidate && method == SPIRBlock::MergeToSelectContinueForLoop)
  1464. ret = block.true_block == block.continue_block;
  1465. else if (ret && negative_candidate && method == SPIRBlock::MergeToSelectContinueForLoop)
  1466. ret = block.false_block == block.continue_block;
  1467. // If we have OpPhi which depends on branches which came from our own block,
  1468. // we need to flush phi variables in else block instead of a trivial break,
  1469. // so we cannot assume this is a for loop candidate.
  1470. if (ret)
  1471. {
  1472. for (auto &phi : block.phi_variables)
  1473. if (phi.parent == block.self)
  1474. return false;
  1475. auto *merge = maybe_get<SPIRBlock>(block.merge_block);
  1476. if (merge)
  1477. for (auto &phi : merge->phi_variables)
  1478. if (phi.parent == block.self)
  1479. return false;
  1480. }
  1481. return ret;
  1482. }
  1483. else if (method == SPIRBlock::MergeToDirectForLoop)
  1484. {
  1485. // Empty loop header that just sets up merge target
  1486. // and branches to loop body.
  1487. bool ret = block.terminator == SPIRBlock::Direct && block.merge == SPIRBlock::MergeLoop && block_is_noop(block);
  1488. if (!ret)
  1489. return false;
  1490. auto &child = get<SPIRBlock>(block.next_block);
  1491. const auto *false_block = maybe_get<SPIRBlock>(child.false_block);
  1492. const auto *true_block = maybe_get<SPIRBlock>(child.true_block);
  1493. const auto *merge_block = maybe_get<SPIRBlock>(block.merge_block);
  1494. bool false_block_is_merge = child.false_block == block.merge_block ||
  1495. (false_block && merge_block && execution_is_noop(*false_block, *merge_block));
  1496. bool true_block_is_merge = child.true_block == block.merge_block ||
  1497. (true_block && merge_block && execution_is_noop(*true_block, *merge_block));
  1498. bool positive_candidate =
  1499. child.true_block != block.merge_block && child.true_block != block.self && false_block_is_merge;
  1500. bool negative_candidate =
  1501. child.false_block != block.merge_block && child.false_block != block.self && true_block_is_merge;
  1502. ret = child.terminator == SPIRBlock::Select && child.merge == SPIRBlock::MergeNone &&
  1503. (positive_candidate || negative_candidate);
  1504. if (ret)
  1505. {
  1506. auto *merge = maybe_get<SPIRBlock>(block.merge_block);
  1507. if (merge)
  1508. for (auto &phi : merge->phi_variables)
  1509. if (phi.parent == block.self || phi.parent == child.false_block)
  1510. return false;
  1511. }
  1512. return ret;
  1513. }
  1514. else
  1515. return false;
  1516. }
  1517. bool Compiler::execution_is_noop(const SPIRBlock &from, const SPIRBlock &to) const
  1518. {
  1519. if (!execution_is_branchless(from, to))
  1520. return false;
  1521. auto *start = &from;
  1522. for (;;)
  1523. {
  1524. if (start->self == to.self)
  1525. return true;
  1526. if (!block_is_noop(*start))
  1527. return false;
  1528. auto &next = get<SPIRBlock>(start->next_block);
  1529. start = &next;
  1530. }
  1531. }
  1532. bool Compiler::execution_is_branchless(const SPIRBlock &from, const SPIRBlock &to) const
  1533. {
  1534. auto *start = &from;
  1535. for (;;)
  1536. {
  1537. if (start->self == to.self)
  1538. return true;
  1539. if (start->terminator == SPIRBlock::Direct && start->merge == SPIRBlock::MergeNone)
  1540. start = &get<SPIRBlock>(start->next_block);
  1541. else
  1542. return false;
  1543. }
  1544. }
  1545. bool Compiler::execution_is_direct_branch(const SPIRBlock &from, const SPIRBlock &to) const
  1546. {
  1547. return from.terminator == SPIRBlock::Direct && from.merge == SPIRBlock::MergeNone && from.next_block == to.self;
  1548. }
  1549. SPIRBlock::ContinueBlockType Compiler::continue_block_type(const SPIRBlock &block) const
  1550. {
  1551. // The block was deemed too complex during code emit, pick conservative fallback paths.
  1552. if (block.complex_continue)
  1553. return SPIRBlock::ComplexLoop;
  1554. // In older glslang output continue block can be equal to the loop header.
  1555. // In this case, execution is clearly branchless, so just assume a while loop header here.
  1556. if (block.merge == SPIRBlock::MergeLoop)
  1557. return SPIRBlock::WhileLoop;
  1558. if (block.loop_dominator == BlockID(SPIRBlock::NoDominator))
  1559. {
  1560. // Continue block is never reached from CFG.
  1561. return SPIRBlock::ComplexLoop;
  1562. }
  1563. auto &dominator = get<SPIRBlock>(block.loop_dominator);
  1564. if (execution_is_noop(block, dominator))
  1565. return SPIRBlock::WhileLoop;
  1566. else if (execution_is_branchless(block, dominator))
  1567. return SPIRBlock::ForLoop;
  1568. else
  1569. {
  1570. const auto *false_block = maybe_get<SPIRBlock>(block.false_block);
  1571. const auto *true_block = maybe_get<SPIRBlock>(block.true_block);
  1572. const auto *merge_block = maybe_get<SPIRBlock>(dominator.merge_block);
  1573. // If we need to flush Phi in this block, we cannot have a DoWhile loop.
  1574. bool flush_phi_to_false = false_block && flush_phi_required(block.self, block.false_block);
  1575. bool flush_phi_to_true = true_block && flush_phi_required(block.self, block.true_block);
  1576. if (flush_phi_to_false || flush_phi_to_true)
  1577. return SPIRBlock::ComplexLoop;
  1578. bool positive_do_while = block.true_block == dominator.self &&
  1579. (block.false_block == dominator.merge_block ||
  1580. (false_block && merge_block && execution_is_noop(*false_block, *merge_block)));
  1581. bool negative_do_while = block.false_block == dominator.self &&
  1582. (block.true_block == dominator.merge_block ||
  1583. (true_block && merge_block && execution_is_noop(*true_block, *merge_block)));
  1584. if (block.merge == SPIRBlock::MergeNone && block.terminator == SPIRBlock::Select &&
  1585. (positive_do_while || negative_do_while))
  1586. {
  1587. return SPIRBlock::DoWhileLoop;
  1588. }
  1589. else
  1590. return SPIRBlock::ComplexLoop;
  1591. }
  1592. }
  1593. const SmallVector<SPIRBlock::Case> &Compiler::get_case_list(const SPIRBlock &block) const
  1594. {
  1595. uint32_t width = 0;
  1596. // First we check if we can get the type directly from the block.condition
  1597. // since it can be a SPIRConstant or a SPIRVariable.
  1598. if (const auto *constant = maybe_get<SPIRConstant>(block.condition))
  1599. {
  1600. const auto &type = get<SPIRType>(constant->constant_type);
  1601. width = type.width;
  1602. }
  1603. else if (const auto *op = maybe_get<SPIRConstantOp>(block.condition))
  1604. {
  1605. const auto &type = get<SPIRType>(op->basetype);
  1606. width = type.width;
  1607. }
  1608. else if (const auto *var = maybe_get<SPIRVariable>(block.condition))
  1609. {
  1610. const auto &type = get<SPIRType>(var->basetype);
  1611. width = type.width;
  1612. }
  1613. else if (const auto *undef = maybe_get<SPIRUndef>(block.condition))
  1614. {
  1615. const auto &type = get<SPIRType>(undef->basetype);
  1616. width = type.width;
  1617. }
  1618. else
  1619. {
  1620. auto search = ir.load_type_width.find(block.condition);
  1621. if (search == ir.load_type_width.end())
  1622. {
  1623. SPIRV_CROSS_THROW("Use of undeclared variable on a switch statement.");
  1624. }
  1625. width = search->second;
  1626. }
  1627. if (width > 32)
  1628. return block.cases_64bit;
  1629. return block.cases_32bit;
  1630. }
  1631. bool Compiler::traverse_all_reachable_opcodes(const SPIRBlock &block, OpcodeHandler &handler) const
  1632. {
  1633. handler.set_current_block(block);
  1634. handler.rearm_current_block(block);
  1635. if (handler.enable_result_types)
  1636. {
  1637. for (auto &phi: block.phi_variables)
  1638. {
  1639. auto &v = get<SPIRVariable>(phi.function_variable);
  1640. handler.result_types[phi.function_variable] = v.basetype;
  1641. }
  1642. }
  1643. // Ideally, perhaps traverse the CFG instead of all blocks in order to eliminate dead blocks,
  1644. // but this shouldn't be a problem in practice unless the SPIR-V is doing insane things like recursing
  1645. // inside dead blocks ...
  1646. for (auto &i : block.ops)
  1647. {
  1648. auto ops = stream(i);
  1649. auto op = static_cast<Op>(i.op);
  1650. if (!handler.handle(op, ops, i.length))
  1651. return false;
  1652. if (handler.enable_result_types)
  1653. {
  1654. // If it has one, keep track of the instruction's result type, mapped by ID
  1655. uint32_t result_type, result_id;
  1656. if (instruction_to_result_type(result_type, result_id, op, ops, i.length))
  1657. handler.result_types[result_id] = result_type;
  1658. }
  1659. if (op == OpFunctionCall)
  1660. {
  1661. auto &func = get<SPIRFunction>(ops[2]);
  1662. if (handler.follow_function_call(func))
  1663. {
  1664. if (handler.enable_result_types)
  1665. for (auto &arg : func.arguments)
  1666. if (!arg.alias_global_variable)
  1667. handler.result_types[arg.id] = arg.type;
  1668. if (!handler.begin_function_scope(ops, i.length))
  1669. return false;
  1670. if (!traverse_all_reachable_opcodes(get<SPIRFunction>(ops[2]), handler))
  1671. return false;
  1672. if (!handler.end_function_scope(ops, i.length))
  1673. return false;
  1674. handler.rearm_current_block(block);
  1675. }
  1676. }
  1677. }
  1678. if (!handler.handle_terminator(block))
  1679. return false;
  1680. return true;
  1681. }
  1682. bool Compiler::traverse_all_reachable_opcodes(const SPIRFunction &func, OpcodeHandler &handler) const
  1683. {
  1684. for (auto block : func.blocks)
  1685. if (!traverse_all_reachable_opcodes(get<SPIRBlock>(block), handler))
  1686. return false;
  1687. return true;
  1688. }
  1689. uint32_t Compiler::type_struct_member_offset(const SPIRType &type, uint32_t index) const
  1690. {
  1691. auto *type_meta = ir.find_meta(type.self);
  1692. if (type_meta)
  1693. {
  1694. // Decoration must be set in valid SPIR-V, otherwise throw.
  1695. auto &dec = type_meta->members[index];
  1696. if (dec.decoration_flags.get(DecorationOffset))
  1697. return dec.offset;
  1698. else
  1699. SPIRV_CROSS_THROW("Struct member does not have Offset set.");
  1700. }
  1701. else
  1702. SPIRV_CROSS_THROW("Struct member does not have Offset set.");
  1703. }
  1704. uint32_t Compiler::type_struct_member_array_stride(const SPIRType &type, uint32_t index) const
  1705. {
  1706. auto *type_meta = ir.find_meta(type.member_types[index]);
  1707. if (type_meta)
  1708. {
  1709. // Decoration must be set in valid SPIR-V, otherwise throw.
  1710. // ArrayStride is part of the array type not OpMemberDecorate.
  1711. auto &dec = type_meta->decoration;
  1712. if (dec.decoration_flags.get(DecorationArrayStride))
  1713. return dec.array_stride;
  1714. else
  1715. SPIRV_CROSS_THROW("Struct member does not have ArrayStride set.");
  1716. }
  1717. else
  1718. SPIRV_CROSS_THROW("Struct member does not have ArrayStride set.");
  1719. }
  1720. uint32_t Compiler::type_struct_member_matrix_stride(const SPIRType &type, uint32_t index) const
  1721. {
  1722. auto *type_meta = ir.find_meta(type.self);
  1723. if (type_meta)
  1724. {
  1725. // Decoration must be set in valid SPIR-V, otherwise throw.
  1726. // MatrixStride is part of OpMemberDecorate.
  1727. auto &dec = type_meta->members[index];
  1728. if (dec.decoration_flags.get(DecorationMatrixStride))
  1729. return dec.matrix_stride;
  1730. else
  1731. SPIRV_CROSS_THROW("Struct member does not have MatrixStride set.");
  1732. }
  1733. else
  1734. SPIRV_CROSS_THROW("Struct member does not have MatrixStride set.");
  1735. }
  1736. size_t Compiler::get_declared_struct_size(const SPIRType &type) const
  1737. {
  1738. if (type.member_types.empty())
  1739. SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
  1740. // Offsets can be declared out of order, so we need to deduce the actual size
  1741. // based on last member instead.
  1742. uint32_t member_index = 0;
  1743. size_t highest_offset = 0;
  1744. for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
  1745. {
  1746. size_t offset = type_struct_member_offset(type, i);
  1747. if (offset > highest_offset)
  1748. {
  1749. highest_offset = offset;
  1750. member_index = i;
  1751. }
  1752. }
  1753. size_t size = get_declared_struct_member_size(type, member_index);
  1754. return highest_offset + size;
  1755. }
  1756. size_t Compiler::get_declared_struct_size_runtime_array(const SPIRType &type, size_t array_size) const
  1757. {
  1758. if (type.member_types.empty())
  1759. SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
  1760. size_t size = get_declared_struct_size(type);
  1761. auto &last_type = get<SPIRType>(type.member_types.back());
  1762. if (!last_type.array.empty() && last_type.array_size_literal[0] && last_type.array[0] == 0) // Runtime array
  1763. size += array_size * type_struct_member_array_stride(type, uint32_t(type.member_types.size() - 1));
  1764. return size;
  1765. }
  1766. uint32_t Compiler::evaluate_spec_constant_u32(const SPIRConstantOp &spec) const
  1767. {
  1768. auto &result_type = get<SPIRType>(spec.basetype);
  1769. if (result_type.basetype != SPIRType::UInt && result_type.basetype != SPIRType::Int &&
  1770. result_type.basetype != SPIRType::Boolean)
  1771. {
  1772. SPIRV_CROSS_THROW(
  1773. "Only 32-bit integers and booleans are currently supported when evaluating specialization constants.\n");
  1774. }
  1775. if (!is_scalar(result_type))
  1776. SPIRV_CROSS_THROW("Spec constant evaluation must be a scalar.\n");
  1777. uint32_t value = 0;
  1778. const auto eval_u32 = [&](uint32_t id) -> uint32_t {
  1779. auto &type = expression_type(id);
  1780. if (type.basetype != SPIRType::UInt && type.basetype != SPIRType::Int && type.basetype != SPIRType::Boolean)
  1781. {
  1782. SPIRV_CROSS_THROW("Only 32-bit integers and booleans are currently supported when evaluating "
  1783. "specialization constants.\n");
  1784. }
  1785. if (!is_scalar(type))
  1786. SPIRV_CROSS_THROW("Spec constant evaluation must be a scalar.\n");
  1787. if (const auto *c = this->maybe_get<SPIRConstant>(id))
  1788. return c->scalar();
  1789. else
  1790. return evaluate_spec_constant_u32(this->get<SPIRConstantOp>(id));
  1791. };
  1792. #define binary_spec_op(op, binary_op) \
  1793. case Op##op: \
  1794. value = eval_u32(spec.arguments[0]) binary_op eval_u32(spec.arguments[1]); \
  1795. break
  1796. #define binary_spec_op_cast(op, binary_op, type) \
  1797. case Op##op: \
  1798. value = uint32_t(type(eval_u32(spec.arguments[0])) binary_op type(eval_u32(spec.arguments[1]))); \
  1799. break
  1800. // Support the basic opcodes which are typically used when computing array sizes.
  1801. switch (spec.opcode)
  1802. {
  1803. binary_spec_op(IAdd, +);
  1804. binary_spec_op(ISub, -);
  1805. binary_spec_op(IMul, *);
  1806. binary_spec_op(BitwiseAnd, &);
  1807. binary_spec_op(BitwiseOr, |);
  1808. binary_spec_op(BitwiseXor, ^);
  1809. binary_spec_op(LogicalAnd, &);
  1810. binary_spec_op(LogicalOr, |);
  1811. binary_spec_op(ShiftLeftLogical, <<);
  1812. binary_spec_op(ShiftRightLogical, >>);
  1813. binary_spec_op_cast(ShiftRightArithmetic, >>, int32_t);
  1814. binary_spec_op(LogicalEqual, ==);
  1815. binary_spec_op(LogicalNotEqual, !=);
  1816. binary_spec_op(IEqual, ==);
  1817. binary_spec_op(INotEqual, !=);
  1818. binary_spec_op(ULessThan, <);
  1819. binary_spec_op(ULessThanEqual, <=);
  1820. binary_spec_op(UGreaterThan, >);
  1821. binary_spec_op(UGreaterThanEqual, >=);
  1822. binary_spec_op_cast(SLessThan, <, int32_t);
  1823. binary_spec_op_cast(SLessThanEqual, <=, int32_t);
  1824. binary_spec_op_cast(SGreaterThan, >, int32_t);
  1825. binary_spec_op_cast(SGreaterThanEqual, >=, int32_t);
  1826. #undef binary_spec_op
  1827. #undef binary_spec_op_cast
  1828. case OpLogicalNot:
  1829. value = uint32_t(!eval_u32(spec.arguments[0]));
  1830. break;
  1831. case OpNot:
  1832. value = ~eval_u32(spec.arguments[0]);
  1833. break;
  1834. case OpSNegate:
  1835. value = uint32_t(-int32_t(eval_u32(spec.arguments[0])));
  1836. break;
  1837. case OpSelect:
  1838. value = eval_u32(spec.arguments[0]) ? eval_u32(spec.arguments[1]) : eval_u32(spec.arguments[2]);
  1839. break;
  1840. case OpUMod:
  1841. {
  1842. uint32_t a = eval_u32(spec.arguments[0]);
  1843. uint32_t b = eval_u32(spec.arguments[1]);
  1844. if (b == 0)
  1845. SPIRV_CROSS_THROW("Undefined behavior in UMod, b == 0.\n");
  1846. value = a % b;
  1847. break;
  1848. }
  1849. case OpSRem:
  1850. {
  1851. auto a = int32_t(eval_u32(spec.arguments[0]));
  1852. auto b = int32_t(eval_u32(spec.arguments[1]));
  1853. if (b == 0)
  1854. SPIRV_CROSS_THROW("Undefined behavior in SRem, b == 0.\n");
  1855. value = a % b;
  1856. break;
  1857. }
  1858. case OpSMod:
  1859. {
  1860. auto a = int32_t(eval_u32(spec.arguments[0]));
  1861. auto b = int32_t(eval_u32(spec.arguments[1]));
  1862. if (b == 0)
  1863. SPIRV_CROSS_THROW("Undefined behavior in SMod, b == 0.\n");
  1864. auto v = a % b;
  1865. // Makes sure we match the sign of b, not a.
  1866. if ((b < 0 && v > 0) || (b > 0 && v < 0))
  1867. v += b;
  1868. value = v;
  1869. break;
  1870. }
  1871. case OpUDiv:
  1872. {
  1873. uint32_t a = eval_u32(spec.arguments[0]);
  1874. uint32_t b = eval_u32(spec.arguments[1]);
  1875. if (b == 0)
  1876. SPIRV_CROSS_THROW("Undefined behavior in UDiv, b == 0.\n");
  1877. value = a / b;
  1878. break;
  1879. }
  1880. case OpSDiv:
  1881. {
  1882. auto a = int32_t(eval_u32(spec.arguments[0]));
  1883. auto b = int32_t(eval_u32(spec.arguments[1]));
  1884. if (b == 0)
  1885. SPIRV_CROSS_THROW("Undefined behavior in SDiv, b == 0.\n");
  1886. value = a / b;
  1887. break;
  1888. }
  1889. default:
  1890. SPIRV_CROSS_THROW("Unsupported spec constant opcode for evaluation.\n");
  1891. }
  1892. return value;
  1893. }
  1894. uint32_t Compiler::evaluate_constant_u32(uint32_t id) const
  1895. {
  1896. if (const auto *c = maybe_get<SPIRConstant>(id))
  1897. return c->scalar();
  1898. else
  1899. return evaluate_spec_constant_u32(get<SPIRConstantOp>(id));
  1900. }
  1901. size_t Compiler::get_declared_struct_member_size(const SPIRType &struct_type, uint32_t index) const
  1902. {
  1903. if (struct_type.member_types.empty())
  1904. SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
  1905. auto &flags = get_member_decoration_bitset(struct_type.self, index);
  1906. auto &type = get<SPIRType>(struct_type.member_types[index]);
  1907. switch (type.basetype)
  1908. {
  1909. case SPIRType::Unknown:
  1910. case SPIRType::Void:
  1911. case SPIRType::Boolean: // Bools are purely logical, and cannot be used for externally visible types.
  1912. case SPIRType::AtomicCounter:
  1913. case SPIRType::Image:
  1914. case SPIRType::SampledImage:
  1915. case SPIRType::Sampler:
  1916. SPIRV_CROSS_THROW("Querying size for object with opaque size.");
  1917. default:
  1918. break;
  1919. }
  1920. if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  1921. {
  1922. // Check if this is a top-level pointer type, and not an array of pointers.
  1923. if (type.pointer_depth > get<SPIRType>(type.parent_type).pointer_depth)
  1924. return 8;
  1925. }
  1926. if (!type.array.empty())
  1927. {
  1928. // For arrays, we can use ArrayStride to get an easy check.
  1929. bool array_size_literal = type.array_size_literal.back();
  1930. uint32_t array_size = array_size_literal ? type.array.back() : evaluate_constant_u32(type.array.back());
  1931. return type_struct_member_array_stride(struct_type, index) * array_size;
  1932. }
  1933. else if (type.basetype == SPIRType::Struct)
  1934. {
  1935. return get_declared_struct_size(type);
  1936. }
  1937. else
  1938. {
  1939. unsigned vecsize = type.vecsize;
  1940. unsigned columns = type.columns;
  1941. // Vectors.
  1942. if (columns == 1)
  1943. {
  1944. size_t component_size = type.width / 8;
  1945. return vecsize * component_size;
  1946. }
  1947. else
  1948. {
  1949. uint32_t matrix_stride = type_struct_member_matrix_stride(struct_type, index);
  1950. // Per SPIR-V spec, matrices must be tightly packed and aligned up for vec3 accesses.
  1951. if (flags.get(DecorationRowMajor))
  1952. return matrix_stride * vecsize;
  1953. else if (flags.get(DecorationColMajor))
  1954. return matrix_stride * columns;
  1955. else
  1956. SPIRV_CROSS_THROW("Either row-major or column-major must be declared for matrices.");
  1957. }
  1958. }
  1959. }
  1960. bool Compiler::BufferAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  1961. {
  1962. if (opcode != OpAccessChain && opcode != OpInBoundsAccessChain && opcode != OpPtrAccessChain)
  1963. return true;
  1964. bool ptr_chain = (opcode == OpPtrAccessChain);
  1965. // Invalid SPIR-V.
  1966. if (length < (ptr_chain ? 5u : 4u))
  1967. return false;
  1968. if (args[2] != id)
  1969. return true;
  1970. // Don't bother traversing the entire access chain tree yet.
  1971. // If we access a struct member, assume we access the entire member.
  1972. uint32_t index = compiler.get<SPIRConstant>(args[ptr_chain ? 4 : 3]).scalar();
  1973. // Seen this index already.
  1974. if (seen.find(index) != end(seen))
  1975. return true;
  1976. seen.insert(index);
  1977. auto &type = compiler.expression_type(id);
  1978. uint32_t offset = compiler.type_struct_member_offset(type, index);
  1979. size_t range;
  1980. // If we have another member in the struct, deduce the range by looking at the next member.
  1981. // This is okay since structs in SPIR-V can have padding, but Offset decoration must be
  1982. // monotonically increasing.
  1983. // Of course, this doesn't take into account if the SPIR-V for some reason decided to add
  1984. // very large amounts of padding, but that's not really a big deal.
  1985. if (index + 1 < type.member_types.size())
  1986. {
  1987. range = compiler.type_struct_member_offset(type, index + 1) - offset;
  1988. }
  1989. else
  1990. {
  1991. // No padding, so just deduce it from the size of the member directly.
  1992. range = compiler.get_declared_struct_member_size(type, index);
  1993. }
  1994. ranges.push_back({ index, offset, range });
  1995. return true;
  1996. }
  1997. SmallVector<BufferRange> Compiler::get_active_buffer_ranges(VariableID id) const
  1998. {
  1999. SmallVector<BufferRange> ranges;
  2000. BufferAccessHandler handler(*this, ranges, id);
  2001. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  2002. return ranges;
  2003. }
  2004. bool Compiler::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
  2005. {
  2006. if (a.basetype != b.basetype)
  2007. return false;
  2008. if (a.width != b.width)
  2009. return false;
  2010. if (a.vecsize != b.vecsize)
  2011. return false;
  2012. if (a.columns != b.columns)
  2013. return false;
  2014. if (a.array.size() != b.array.size())
  2015. return false;
  2016. size_t array_count = a.array.size();
  2017. if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
  2018. return false;
  2019. if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
  2020. {
  2021. if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
  2022. return false;
  2023. }
  2024. if (a.member_types.size() != b.member_types.size())
  2025. return false;
  2026. size_t member_types = a.member_types.size();
  2027. for (size_t i = 0; i < member_types; i++)
  2028. {
  2029. if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
  2030. return false;
  2031. }
  2032. return true;
  2033. }
  2034. const Bitset &Compiler::get_execution_mode_bitset() const
  2035. {
  2036. return get_entry_point().flags;
  2037. }
  2038. void Compiler::set_execution_mode(ExecutionMode mode, uint32_t arg0, uint32_t arg1, uint32_t arg2)
  2039. {
  2040. auto &execution = get_entry_point();
  2041. execution.flags.set(mode);
  2042. switch (mode)
  2043. {
  2044. case ExecutionModeLocalSize:
  2045. execution.workgroup_size.x = arg0;
  2046. execution.workgroup_size.y = arg1;
  2047. execution.workgroup_size.z = arg2;
  2048. break;
  2049. case ExecutionModeLocalSizeId:
  2050. execution.workgroup_size.id_x = arg0;
  2051. execution.workgroup_size.id_y = arg1;
  2052. execution.workgroup_size.id_z = arg2;
  2053. break;
  2054. case ExecutionModeInvocations:
  2055. execution.invocations = arg0;
  2056. break;
  2057. case ExecutionModeOutputVertices:
  2058. execution.output_vertices = arg0;
  2059. break;
  2060. case ExecutionModeOutputPrimitivesEXT:
  2061. execution.output_primitives = arg0;
  2062. break;
  2063. case ExecutionModeFPFastMathDefault:
  2064. execution.fp_fast_math_defaults[arg0] = arg1;
  2065. break;
  2066. default:
  2067. break;
  2068. }
  2069. }
  2070. void Compiler::unset_execution_mode(ExecutionMode mode)
  2071. {
  2072. auto &execution = get_entry_point();
  2073. execution.flags.clear(mode);
  2074. }
  2075. uint32_t Compiler::get_work_group_size_specialization_constants(SpecializationConstant &x, SpecializationConstant &y,
  2076. SpecializationConstant &z) const
  2077. {
  2078. auto &execution = get_entry_point();
  2079. x = { 0, 0 };
  2080. y = { 0, 0 };
  2081. z = { 0, 0 };
  2082. // WorkgroupSize builtin takes precedence over LocalSize / LocalSizeId.
  2083. if (execution.workgroup_size.constant != 0)
  2084. {
  2085. auto &c = get<SPIRConstant>(execution.workgroup_size.constant);
  2086. if (c.m.c[0].id[0] != ID(0))
  2087. {
  2088. x.id = c.m.c[0].id[0];
  2089. x.constant_id = get_decoration(c.m.c[0].id[0], DecorationSpecId);
  2090. }
  2091. if (c.m.c[0].id[1] != ID(0))
  2092. {
  2093. y.id = c.m.c[0].id[1];
  2094. y.constant_id = get_decoration(c.m.c[0].id[1], DecorationSpecId);
  2095. }
  2096. if (c.m.c[0].id[2] != ID(0))
  2097. {
  2098. z.id = c.m.c[0].id[2];
  2099. z.constant_id = get_decoration(c.m.c[0].id[2], DecorationSpecId);
  2100. }
  2101. }
  2102. else if (execution.flags.get(ExecutionModeLocalSizeId))
  2103. {
  2104. auto &cx = get<SPIRConstant>(execution.workgroup_size.id_x);
  2105. if (cx.specialization)
  2106. {
  2107. x.id = execution.workgroup_size.id_x;
  2108. x.constant_id = get_decoration(execution.workgroup_size.id_x, DecorationSpecId);
  2109. }
  2110. auto &cy = get<SPIRConstant>(execution.workgroup_size.id_y);
  2111. if (cy.specialization)
  2112. {
  2113. y.id = execution.workgroup_size.id_y;
  2114. y.constant_id = get_decoration(execution.workgroup_size.id_y, DecorationSpecId);
  2115. }
  2116. auto &cz = get<SPIRConstant>(execution.workgroup_size.id_z);
  2117. if (cz.specialization)
  2118. {
  2119. z.id = execution.workgroup_size.id_z;
  2120. z.constant_id = get_decoration(execution.workgroup_size.id_z, DecorationSpecId);
  2121. }
  2122. }
  2123. return execution.workgroup_size.constant;
  2124. }
  2125. uint32_t Compiler::get_execution_mode_argument(ExecutionMode mode, uint32_t index) const
  2126. {
  2127. auto &execution = get_entry_point();
  2128. switch (mode)
  2129. {
  2130. case ExecutionModeLocalSizeId:
  2131. if (execution.flags.get(ExecutionModeLocalSizeId))
  2132. {
  2133. switch (index)
  2134. {
  2135. case 0:
  2136. return execution.workgroup_size.id_x;
  2137. case 1:
  2138. return execution.workgroup_size.id_y;
  2139. case 2:
  2140. return execution.workgroup_size.id_z;
  2141. default:
  2142. return 0;
  2143. }
  2144. }
  2145. else
  2146. return 0;
  2147. case ExecutionModeLocalSize:
  2148. switch (index)
  2149. {
  2150. case 0:
  2151. if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_x != 0)
  2152. return get<SPIRConstant>(execution.workgroup_size.id_x).scalar();
  2153. else
  2154. return execution.workgroup_size.x;
  2155. case 1:
  2156. if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_y != 0)
  2157. return get<SPIRConstant>(execution.workgroup_size.id_y).scalar();
  2158. else
  2159. return execution.workgroup_size.y;
  2160. case 2:
  2161. if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_z != 0)
  2162. return get<SPIRConstant>(execution.workgroup_size.id_z).scalar();
  2163. else
  2164. return execution.workgroup_size.z;
  2165. default:
  2166. return 0;
  2167. }
  2168. case ExecutionModeInvocations:
  2169. return execution.invocations;
  2170. case ExecutionModeOutputVertices:
  2171. return execution.output_vertices;
  2172. case ExecutionModeOutputPrimitivesEXT:
  2173. return execution.output_primitives;
  2174. default:
  2175. return 0;
  2176. }
  2177. }
  2178. ExecutionModel Compiler::get_execution_model() const
  2179. {
  2180. auto &execution = get_entry_point();
  2181. return execution.model;
  2182. }
  2183. bool Compiler::is_tessellation_shader(ExecutionModel model)
  2184. {
  2185. return model == ExecutionModelTessellationControl || model == ExecutionModelTessellationEvaluation;
  2186. }
  2187. bool Compiler::is_vertex_like_shader() const
  2188. {
  2189. auto model = get_execution_model();
  2190. return model == ExecutionModelVertex || model == ExecutionModelGeometry ||
  2191. model == ExecutionModelTessellationControl || model == ExecutionModelTessellationEvaluation;
  2192. }
  2193. bool Compiler::is_tessellation_shader() const
  2194. {
  2195. return is_tessellation_shader(get_execution_model());
  2196. }
  2197. bool Compiler::is_tessellating_triangles() const
  2198. {
  2199. return get_execution_mode_bitset().get(ExecutionModeTriangles);
  2200. }
  2201. void Compiler::set_remapped_variable_state(VariableID id, bool remap_enable)
  2202. {
  2203. get<SPIRVariable>(id).remapped_variable = remap_enable;
  2204. }
  2205. bool Compiler::get_remapped_variable_state(VariableID id) const
  2206. {
  2207. return get<SPIRVariable>(id).remapped_variable;
  2208. }
  2209. void Compiler::set_subpass_input_remapped_components(VariableID id, uint32_t components)
  2210. {
  2211. get<SPIRVariable>(id).remapped_components = components;
  2212. }
  2213. uint32_t Compiler::get_subpass_input_remapped_components(VariableID id) const
  2214. {
  2215. return get<SPIRVariable>(id).remapped_components;
  2216. }
  2217. void Compiler::add_implied_read_expression(SPIRExpression &e, uint32_t source)
  2218. {
  2219. auto itr = find(begin(e.implied_read_expressions), end(e.implied_read_expressions), ID(source));
  2220. if (itr == end(e.implied_read_expressions))
  2221. e.implied_read_expressions.push_back(source);
  2222. }
  2223. void Compiler::add_implied_read_expression(SPIRAccessChain &e, uint32_t source)
  2224. {
  2225. auto itr = find(begin(e.implied_read_expressions), end(e.implied_read_expressions), ID(source));
  2226. if (itr == end(e.implied_read_expressions))
  2227. e.implied_read_expressions.push_back(source);
  2228. }
  2229. void Compiler::add_active_interface_variable(uint32_t var_id)
  2230. {
  2231. active_interface_variables.insert(var_id);
  2232. // In SPIR-V 1.4 and up we must also track the interface variable in the entry point.
  2233. if (ir.get_spirv_version() >= 0x10400)
  2234. {
  2235. auto &vars = get_entry_point().interface_variables;
  2236. if (find(begin(vars), end(vars), VariableID(var_id)) == end(vars))
  2237. vars.push_back(var_id);
  2238. }
  2239. }
  2240. void Compiler::inherit_expression_dependencies(uint32_t dst, uint32_t source_expression)
  2241. {
  2242. auto *ptr_e = maybe_get<SPIRExpression>(dst);
  2243. if (is_position_invariant() && ptr_e && maybe_get<SPIRExpression>(source_expression))
  2244. {
  2245. auto &deps = ptr_e->invariance_dependencies;
  2246. if (std::find(deps.begin(), deps.end(), source_expression) == deps.end())
  2247. deps.push_back(source_expression);
  2248. }
  2249. // Don't inherit any expression dependencies if the expression in dst
  2250. // is not a forwarded temporary.
  2251. if (forwarded_temporaries.find(dst) == end(forwarded_temporaries) ||
  2252. forced_temporaries.find(dst) != end(forced_temporaries))
  2253. {
  2254. return;
  2255. }
  2256. auto &e = *ptr_e;
  2257. auto *phi = maybe_get<SPIRVariable>(source_expression);
  2258. if (phi && phi->phi_variable)
  2259. {
  2260. // We have used a phi variable, which can change at the end of the block,
  2261. // so make sure we take a dependency on this phi variable.
  2262. phi->dependees.push_back(dst);
  2263. }
  2264. auto *s = maybe_get<SPIRExpression>(source_expression);
  2265. if (!s)
  2266. return;
  2267. auto &e_deps = e.expression_dependencies;
  2268. auto &s_deps = s->expression_dependencies;
  2269. // If we depend on a expression, we also depend on all sub-dependencies from source.
  2270. e_deps.push_back(source_expression);
  2271. e_deps.insert(end(e_deps), begin(s_deps), end(s_deps));
  2272. // Eliminate duplicated dependencies.
  2273. sort(begin(e_deps), end(e_deps));
  2274. e_deps.erase(unique(begin(e_deps), end(e_deps)), end(e_deps));
  2275. }
  2276. SmallVector<EntryPoint> Compiler::get_entry_points_and_stages() const
  2277. {
  2278. SmallVector<EntryPoint> entries;
  2279. for (auto &entry : ir.entry_points)
  2280. entries.push_back({ entry.second.orig_name, entry.second.model });
  2281. return entries;
  2282. }
  2283. void Compiler::rename_entry_point(const std::string &old_name, const std::string &new_name, ExecutionModel model)
  2284. {
  2285. auto &entry = get_entry_point(old_name, model);
  2286. entry.orig_name = new_name;
  2287. entry.name = new_name;
  2288. }
  2289. void Compiler::set_entry_point(const std::string &name, ExecutionModel model)
  2290. {
  2291. auto &entry = get_entry_point(name, model);
  2292. ir.default_entry_point = entry.self;
  2293. }
  2294. SPIREntryPoint &Compiler::get_first_entry_point(const std::string &name)
  2295. {
  2296. auto itr = find_if(
  2297. begin(ir.entry_points), end(ir.entry_points),
  2298. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool { return entry.second.orig_name == name; });
  2299. if (itr == end(ir.entry_points))
  2300. SPIRV_CROSS_THROW("Entry point does not exist.");
  2301. return itr->second;
  2302. }
  2303. const SPIREntryPoint &Compiler::get_first_entry_point(const std::string &name) const
  2304. {
  2305. auto itr = find_if(
  2306. begin(ir.entry_points), end(ir.entry_points),
  2307. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool { return entry.second.orig_name == name; });
  2308. if (itr == end(ir.entry_points))
  2309. SPIRV_CROSS_THROW("Entry point does not exist.");
  2310. return itr->second;
  2311. }
  2312. SPIREntryPoint &Compiler::get_entry_point(const std::string &name, ExecutionModel model)
  2313. {
  2314. auto itr = find_if(begin(ir.entry_points), end(ir.entry_points),
  2315. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool {
  2316. return entry.second.orig_name == name && entry.second.model == model;
  2317. });
  2318. if (itr == end(ir.entry_points))
  2319. SPIRV_CROSS_THROW("Entry point does not exist.");
  2320. return itr->second;
  2321. }
  2322. const SPIREntryPoint &Compiler::get_entry_point(const std::string &name, ExecutionModel model) const
  2323. {
  2324. auto itr = find_if(begin(ir.entry_points), end(ir.entry_points),
  2325. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool {
  2326. return entry.second.orig_name == name && entry.second.model == model;
  2327. });
  2328. if (itr == end(ir.entry_points))
  2329. SPIRV_CROSS_THROW("Entry point does not exist.");
  2330. return itr->second;
  2331. }
  2332. const string &Compiler::get_cleansed_entry_point_name(const std::string &name, ExecutionModel model) const
  2333. {
  2334. return get_entry_point(name, model).name;
  2335. }
  2336. const SPIREntryPoint &Compiler::get_entry_point() const
  2337. {
  2338. return ir.entry_points.find(ir.default_entry_point)->second;
  2339. }
  2340. SPIREntryPoint &Compiler::get_entry_point()
  2341. {
  2342. return ir.entry_points.find(ir.default_entry_point)->second;
  2343. }
  2344. bool Compiler::interface_variable_exists_in_entry_point(uint32_t id) const
  2345. {
  2346. auto &var = get<SPIRVariable>(id);
  2347. if (ir.get_spirv_version() < 0x10400)
  2348. {
  2349. if (var.storage != StorageClassInput && var.storage != StorageClassOutput &&
  2350. var.storage != StorageClassUniformConstant)
  2351. SPIRV_CROSS_THROW("Only Input, Output variables and Uniform constants are part of a shader linking interface.");
  2352. // This is to avoid potential problems with very old glslang versions which did
  2353. // not emit input/output interfaces properly.
  2354. // We can assume they only had a single entry point, and single entry point
  2355. // shaders could easily be assumed to use every interface variable anyways.
  2356. if (ir.entry_points.size() <= 1)
  2357. return true;
  2358. }
  2359. // In SPIR-V 1.4 and later, all global resource variables must be present.
  2360. auto &execution = get_entry_point();
  2361. return find(begin(execution.interface_variables), end(execution.interface_variables), VariableID(id)) !=
  2362. end(execution.interface_variables);
  2363. }
  2364. void Compiler::CombinedImageSamplerHandler::push_remap_parameters(const SPIRFunction &func, const uint32_t *args,
  2365. uint32_t length)
  2366. {
  2367. // If possible, pipe through a remapping table so that parameters know
  2368. // which variables they actually bind to in this scope.
  2369. unordered_map<uint32_t, uint32_t> remapping;
  2370. for (uint32_t i = 0; i < length; i++)
  2371. remapping[func.arguments[i].id] = remap_parameter(args[i]);
  2372. parameter_remapping.push(std::move(remapping));
  2373. }
  2374. void Compiler::CombinedImageSamplerHandler::pop_remap_parameters()
  2375. {
  2376. parameter_remapping.pop();
  2377. }
  2378. uint32_t Compiler::CombinedImageSamplerHandler::remap_parameter(uint32_t id)
  2379. {
  2380. auto *var = compiler.maybe_get_backing_variable(id);
  2381. if (var)
  2382. id = var->self;
  2383. if (parameter_remapping.empty())
  2384. return id;
  2385. auto &remapping = parameter_remapping.top();
  2386. auto itr = remapping.find(id);
  2387. if (itr != end(remapping))
  2388. return itr->second;
  2389. else
  2390. return id;
  2391. }
  2392. bool Compiler::CombinedImageSamplerHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  2393. {
  2394. if (length < 3)
  2395. return false;
  2396. auto &callee = compiler.get<SPIRFunction>(args[2]);
  2397. args += 3;
  2398. length -= 3;
  2399. push_remap_parameters(callee, args, length);
  2400. functions.push(&callee);
  2401. return true;
  2402. }
  2403. bool Compiler::CombinedImageSamplerHandler::end_function_scope(const uint32_t *args, uint32_t length)
  2404. {
  2405. if (length < 3)
  2406. return false;
  2407. auto &callee = compiler.get<SPIRFunction>(args[2]);
  2408. args += 3;
  2409. // There are two types of cases we have to handle,
  2410. // a callee might call sampler2D(texture2D, sampler) directly where
  2411. // one or more parameters originate from parameters.
  2412. // Alternatively, we need to provide combined image samplers to our callees,
  2413. // and in this case we need to add those as well.
  2414. pop_remap_parameters();
  2415. // Our callee has now been processed at least once.
  2416. // No point in doing it again.
  2417. callee.do_combined_parameters = false;
  2418. auto &params = functions.top()->combined_parameters;
  2419. functions.pop();
  2420. if (functions.empty())
  2421. return true;
  2422. auto &caller = *functions.top();
  2423. if (caller.do_combined_parameters)
  2424. {
  2425. for (auto &param : params)
  2426. {
  2427. VariableID image_id = param.global_image ? param.image_id : VariableID(args[param.image_id]);
  2428. VariableID sampler_id = param.global_sampler ? param.sampler_id : VariableID(args[param.sampler_id]);
  2429. auto *i = compiler.maybe_get_backing_variable(image_id);
  2430. auto *s = compiler.maybe_get_backing_variable(sampler_id);
  2431. if (i)
  2432. image_id = i->self;
  2433. if (s)
  2434. sampler_id = s->self;
  2435. register_combined_image_sampler(caller, 0, image_id, sampler_id, param.depth);
  2436. }
  2437. }
  2438. return true;
  2439. }
  2440. void Compiler::CombinedImageSamplerHandler::register_combined_image_sampler(SPIRFunction &caller,
  2441. VariableID combined_module_id,
  2442. VariableID image_id, VariableID sampler_id,
  2443. bool depth)
  2444. {
  2445. // We now have a texture ID and a sampler ID which will either be found as a global
  2446. // or a parameter in our own function. If both are global, they will not need a parameter,
  2447. // otherwise, add it to our list.
  2448. SPIRFunction::CombinedImageSamplerParameter param = {
  2449. 0u, image_id, sampler_id, true, true, depth,
  2450. };
  2451. auto texture_itr = find_if(begin(caller.arguments), end(caller.arguments),
  2452. [image_id](const SPIRFunction::Parameter &p) { return p.id == image_id; });
  2453. auto sampler_itr = find_if(begin(caller.arguments), end(caller.arguments),
  2454. [sampler_id](const SPIRFunction::Parameter &p) { return p.id == sampler_id; });
  2455. if (texture_itr != end(caller.arguments))
  2456. {
  2457. param.global_image = false;
  2458. param.image_id = uint32_t(texture_itr - begin(caller.arguments));
  2459. }
  2460. if (sampler_itr != end(caller.arguments))
  2461. {
  2462. param.global_sampler = false;
  2463. param.sampler_id = uint32_t(sampler_itr - begin(caller.arguments));
  2464. }
  2465. if (param.global_image && param.global_sampler)
  2466. return;
  2467. auto itr = find_if(begin(caller.combined_parameters), end(caller.combined_parameters),
  2468. [&param](const SPIRFunction::CombinedImageSamplerParameter &p) {
  2469. return param.image_id == p.image_id && param.sampler_id == p.sampler_id &&
  2470. param.global_image == p.global_image && param.global_sampler == p.global_sampler;
  2471. });
  2472. if (itr == end(caller.combined_parameters))
  2473. {
  2474. uint32_t id = compiler.ir.increase_bound_by(3);
  2475. auto type_id = id + 0;
  2476. auto ptr_type_id = id + 1;
  2477. auto combined_id = id + 2;
  2478. auto &base = compiler.expression_type(image_id);
  2479. auto &type = compiler.set<SPIRType>(type_id, OpTypeSampledImage);
  2480. auto &ptr_type = compiler.set<SPIRType>(ptr_type_id, OpTypePointer);
  2481. type = base;
  2482. type.self = type_id;
  2483. type.basetype = SPIRType::SampledImage;
  2484. type.pointer = false;
  2485. type.storage = StorageClassGeneric;
  2486. type.image.depth = depth;
  2487. ptr_type = type;
  2488. ptr_type.pointer = true;
  2489. ptr_type.storage = StorageClassUniformConstant;
  2490. ptr_type.parent_type = type_id;
  2491. // Build new variable.
  2492. compiler.set<SPIRVariable>(combined_id, ptr_type_id, StorageClassFunction, 0);
  2493. // Inherit RelaxedPrecision.
  2494. // If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
  2495. bool relaxed_precision =
  2496. compiler.has_decoration(sampler_id, DecorationRelaxedPrecision) ||
  2497. compiler.has_decoration(image_id, DecorationRelaxedPrecision) ||
  2498. (combined_module_id && compiler.has_decoration(combined_module_id, DecorationRelaxedPrecision));
  2499. if (relaxed_precision)
  2500. compiler.set_decoration(combined_id, DecorationRelaxedPrecision);
  2501. param.id = combined_id;
  2502. compiler.set_name(combined_id,
  2503. join("SPIRV_Cross_Combined", compiler.to_name(image_id), compiler.to_name(sampler_id)));
  2504. caller.combined_parameters.push_back(param);
  2505. caller.shadow_arguments.push_back({ ptr_type_id, combined_id, 0u, 0u, true });
  2506. }
  2507. }
  2508. bool Compiler::DummySamplerForCombinedImageHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  2509. {
  2510. if (need_dummy_sampler)
  2511. {
  2512. // No need to traverse further, we know the result.
  2513. return false;
  2514. }
  2515. switch (opcode)
  2516. {
  2517. case OpLoad:
  2518. {
  2519. if (length < 3)
  2520. return false;
  2521. uint32_t result_type = args[0];
  2522. auto &type = compiler.get<SPIRType>(result_type);
  2523. bool separate_image =
  2524. type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer;
  2525. // If not separate image, don't bother.
  2526. if (!separate_image)
  2527. return true;
  2528. uint32_t id = args[1];
  2529. uint32_t ptr = args[2];
  2530. compiler.set<SPIRExpression>(id, "", result_type, true);
  2531. compiler.register_read(id, ptr, true);
  2532. break;
  2533. }
  2534. case OpImageFetch:
  2535. case OpImageQuerySizeLod:
  2536. case OpImageQuerySize:
  2537. case OpImageQueryLevels:
  2538. case OpImageQuerySamples:
  2539. {
  2540. // If we are fetching or querying LOD from a plain OpTypeImage, we must pre-combine with our dummy sampler.
  2541. auto *var = compiler.maybe_get_backing_variable(args[2]);
  2542. if (var)
  2543. {
  2544. auto &type = compiler.get<SPIRType>(var->basetype);
  2545. if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
  2546. need_dummy_sampler = true;
  2547. }
  2548. break;
  2549. }
  2550. case OpInBoundsAccessChain:
  2551. case OpAccessChain:
  2552. case OpPtrAccessChain:
  2553. {
  2554. if (length < 3)
  2555. return false;
  2556. uint32_t result_type = args[0];
  2557. auto &type = compiler.get<SPIRType>(result_type);
  2558. bool separate_image =
  2559. type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer;
  2560. if (!separate_image)
  2561. return true;
  2562. uint32_t id = args[1];
  2563. uint32_t ptr = args[2];
  2564. compiler.set<SPIRExpression>(id, "", result_type, true);
  2565. compiler.register_read(id, ptr, true);
  2566. // Other backends might use SPIRAccessChain for this later.
  2567. compiler.ir.ids[id].set_allow_type_rewrite();
  2568. break;
  2569. }
  2570. default:
  2571. break;
  2572. }
  2573. return true;
  2574. }
  2575. bool Compiler::CombinedImageSamplerHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  2576. {
  2577. // We need to figure out where samplers and images are loaded from, so do only the bare bones compilation we need.
  2578. bool is_fetch = false;
  2579. switch (opcode)
  2580. {
  2581. case OpLoad:
  2582. {
  2583. if (length < 3)
  2584. return false;
  2585. uint32_t result_type = args[0];
  2586. auto &type = compiler.get<SPIRType>(result_type);
  2587. bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
  2588. bool separate_sampler = type.basetype == SPIRType::Sampler;
  2589. // If not separate image or sampler, don't bother.
  2590. if (!separate_image && !separate_sampler)
  2591. return true;
  2592. uint32_t id = args[1];
  2593. uint32_t ptr = args[2];
  2594. compiler.set<SPIRExpression>(id, "", result_type, true);
  2595. compiler.register_read(id, ptr, true);
  2596. return true;
  2597. }
  2598. case OpInBoundsAccessChain:
  2599. case OpAccessChain:
  2600. case OpPtrAccessChain:
  2601. {
  2602. if (length < 3)
  2603. return false;
  2604. // Technically, it is possible to have arrays of textures and arrays of samplers and combine them, but this becomes essentially
  2605. // impossible to implement, since we don't know which concrete sampler we are accessing.
  2606. // One potential way is to create a combinatorial explosion where N textures and M samplers are combined into N * M sampler2Ds,
  2607. // but this seems ridiculously complicated for a problem which is easy to work around.
  2608. // Checking access chains like this assumes we don't have samplers or textures inside uniform structs, but this makes no sense.
  2609. uint32_t result_type = args[0];
  2610. auto &type = compiler.get<SPIRType>(result_type);
  2611. bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
  2612. bool separate_sampler = type.basetype == SPIRType::Sampler;
  2613. if (separate_sampler)
  2614. SPIRV_CROSS_THROW(
  2615. "Attempting to use arrays or structs of separate samplers. This is not possible to statically "
  2616. "remap to plain GLSL.");
  2617. if (separate_image)
  2618. {
  2619. uint32_t id = args[1];
  2620. uint32_t ptr = args[2];
  2621. compiler.set<SPIRExpression>(id, "", result_type, true);
  2622. compiler.register_read(id, ptr, true);
  2623. }
  2624. return true;
  2625. }
  2626. case OpImageFetch:
  2627. case OpImageQuerySizeLod:
  2628. case OpImageQuerySize:
  2629. case OpImageQueryLevels:
  2630. case OpImageQuerySamples:
  2631. {
  2632. // If we are fetching from a plain OpTypeImage or querying LOD, we must pre-combine with our dummy sampler.
  2633. auto *var = compiler.maybe_get_backing_variable(args[2]);
  2634. if (!var)
  2635. return true;
  2636. auto &type = compiler.get<SPIRType>(var->basetype);
  2637. if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
  2638. {
  2639. if (compiler.dummy_sampler_id == 0)
  2640. SPIRV_CROSS_THROW("texelFetch without sampler was found, but no dummy sampler has been created with "
  2641. "build_dummy_sampler_for_combined_images().");
  2642. // Do it outside.
  2643. is_fetch = true;
  2644. break;
  2645. }
  2646. return true;
  2647. }
  2648. case OpSampledImage:
  2649. // Do it outside.
  2650. break;
  2651. default:
  2652. return true;
  2653. }
  2654. // Registers sampler2D calls used in case they are parameters so
  2655. // that their callees know which combined image samplers to propagate down the call stack.
  2656. if (!functions.empty())
  2657. {
  2658. auto &callee = *functions.top();
  2659. if (callee.do_combined_parameters)
  2660. {
  2661. uint32_t image_id = args[2];
  2662. auto *image = compiler.maybe_get_backing_variable(image_id);
  2663. if (image)
  2664. image_id = image->self;
  2665. uint32_t sampler_id = is_fetch ? compiler.dummy_sampler_id : args[3];
  2666. auto *sampler = compiler.maybe_get_backing_variable(sampler_id);
  2667. if (sampler)
  2668. sampler_id = sampler->self;
  2669. uint32_t combined_id = args[1];
  2670. auto &combined_type = compiler.get<SPIRType>(args[0]);
  2671. register_combined_image_sampler(callee, combined_id, image_id, sampler_id, combined_type.image.depth);
  2672. }
  2673. }
  2674. // For function calls, we need to remap IDs which are function parameters into global variables.
  2675. // This information is statically known from the current place in the call stack.
  2676. // Function parameters are not necessarily pointers, so if we don't have a backing variable, remapping will know
  2677. // which backing variable the image/sample came from.
  2678. VariableID image_id = remap_parameter(args[2]);
  2679. VariableID sampler_id = is_fetch ? compiler.dummy_sampler_id : remap_parameter(args[3]);
  2680. auto itr = find_if(begin(compiler.combined_image_samplers), end(compiler.combined_image_samplers),
  2681. [image_id, sampler_id](const CombinedImageSampler &combined) {
  2682. return combined.image_id == image_id && combined.sampler_id == sampler_id;
  2683. });
  2684. if (itr == end(compiler.combined_image_samplers))
  2685. {
  2686. uint32_t sampled_type;
  2687. uint32_t combined_module_id;
  2688. if (is_fetch)
  2689. {
  2690. // Have to invent the sampled image type.
  2691. sampled_type = compiler.ir.increase_bound_by(1);
  2692. auto &type = compiler.set<SPIRType>(sampled_type, OpTypeSampledImage);
  2693. type = compiler.expression_type(args[2]);
  2694. type.self = sampled_type;
  2695. type.basetype = SPIRType::SampledImage;
  2696. type.image.depth = false;
  2697. combined_module_id = 0;
  2698. }
  2699. else
  2700. {
  2701. sampled_type = args[0];
  2702. combined_module_id = args[1];
  2703. }
  2704. auto id = compiler.ir.increase_bound_by(2);
  2705. auto type_id = id + 0;
  2706. auto combined_id = id + 1;
  2707. // Make a new type, pointer to OpTypeSampledImage, so we can make a variable of this type.
  2708. // We will probably have this type lying around, but it doesn't hurt to make duplicates for internal purposes.
  2709. auto &type = compiler.set<SPIRType>(type_id, OpTypePointer);
  2710. auto &base = compiler.get<SPIRType>(sampled_type);
  2711. type = base;
  2712. type.pointer = true;
  2713. type.storage = StorageClassUniformConstant;
  2714. type.parent_type = type_id;
  2715. // Build new variable.
  2716. compiler.set<SPIRVariable>(combined_id, type_id, StorageClassUniformConstant, 0);
  2717. // Inherit RelaxedPrecision (and potentially other useful flags if deemed relevant).
  2718. // If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
  2719. bool relaxed_precision =
  2720. (sampler_id && compiler.has_decoration(sampler_id, DecorationRelaxedPrecision)) ||
  2721. (image_id && compiler.has_decoration(image_id, DecorationRelaxedPrecision)) ||
  2722. (combined_module_id && compiler.has_decoration(combined_module_id, DecorationRelaxedPrecision));
  2723. if (relaxed_precision)
  2724. compiler.set_decoration(combined_id, DecorationRelaxedPrecision);
  2725. // Propagate the array type for the original image as well.
  2726. auto *var = compiler.maybe_get_backing_variable(image_id);
  2727. if (var)
  2728. {
  2729. auto &parent_type = compiler.get<SPIRType>(var->basetype);
  2730. type.array = parent_type.array;
  2731. type.array_size_literal = parent_type.array_size_literal;
  2732. }
  2733. compiler.combined_image_samplers.push_back({ combined_id, image_id, sampler_id });
  2734. }
  2735. return true;
  2736. }
  2737. VariableID Compiler::build_dummy_sampler_for_combined_images()
  2738. {
  2739. DummySamplerForCombinedImageHandler handler(*this);
  2740. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  2741. if (handler.need_dummy_sampler)
  2742. {
  2743. uint32_t offset = ir.increase_bound_by(3);
  2744. auto type_id = offset + 0;
  2745. auto ptr_type_id = offset + 1;
  2746. auto var_id = offset + 2;
  2747. auto &sampler = set<SPIRType>(type_id, OpTypeSampler);
  2748. sampler.basetype = SPIRType::Sampler;
  2749. auto &ptr_sampler = set<SPIRType>(ptr_type_id, OpTypePointer);
  2750. ptr_sampler = sampler;
  2751. ptr_sampler.self = type_id;
  2752. ptr_sampler.storage = StorageClassUniformConstant;
  2753. ptr_sampler.pointer = true;
  2754. ptr_sampler.parent_type = type_id;
  2755. set<SPIRVariable>(var_id, ptr_type_id, StorageClassUniformConstant, 0);
  2756. set_name(var_id, "SPIRV_Cross_DummySampler");
  2757. dummy_sampler_id = var_id;
  2758. return var_id;
  2759. }
  2760. else
  2761. return 0;
  2762. }
  2763. void Compiler::build_combined_image_samplers()
  2764. {
  2765. ir.for_each_typed_id<SPIRFunction>([&](uint32_t, SPIRFunction &func) {
  2766. func.combined_parameters.clear();
  2767. func.shadow_arguments.clear();
  2768. func.do_combined_parameters = true;
  2769. });
  2770. combined_image_samplers.clear();
  2771. CombinedImageSamplerHandler handler(*this);
  2772. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  2773. }
  2774. SmallVector<SpecializationConstant> Compiler::get_specialization_constants() const
  2775. {
  2776. SmallVector<SpecializationConstant> spec_consts;
  2777. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, const SPIRConstant &c) {
  2778. if (c.specialization && has_decoration(c.self, DecorationSpecId))
  2779. spec_consts.push_back({ c.self, get_decoration(c.self, DecorationSpecId) });
  2780. });
  2781. return spec_consts;
  2782. }
  2783. SPIRConstant &Compiler::get_constant(ConstantID id)
  2784. {
  2785. return get<SPIRConstant>(id);
  2786. }
  2787. const SPIRConstant &Compiler::get_constant(ConstantID id) const
  2788. {
  2789. return get<SPIRConstant>(id);
  2790. }
  2791. static bool exists_unaccessed_path_to_return(const CFG &cfg, uint32_t block, const unordered_set<uint32_t> &blocks,
  2792. unordered_set<uint32_t> &visit_cache)
  2793. {
  2794. // This block accesses the variable.
  2795. if (blocks.find(block) != end(blocks))
  2796. return false;
  2797. // We are at the end of the CFG.
  2798. if (cfg.get_succeeding_edges(block).empty())
  2799. return true;
  2800. // If any of our successors have a path to the end, there exists a path from block.
  2801. for (auto &succ : cfg.get_succeeding_edges(block))
  2802. {
  2803. if (visit_cache.count(succ) == 0)
  2804. {
  2805. if (exists_unaccessed_path_to_return(cfg, succ, blocks, visit_cache))
  2806. return true;
  2807. visit_cache.insert(succ);
  2808. }
  2809. }
  2810. return false;
  2811. }
  2812. void Compiler::analyze_parameter_preservation(
  2813. SPIRFunction &entry, const CFG &cfg, const unordered_map<uint32_t, unordered_set<uint32_t>> &variable_to_blocks,
  2814. const unordered_map<uint32_t, unordered_set<uint32_t>> &complete_write_blocks)
  2815. {
  2816. for (auto &arg : entry.arguments)
  2817. {
  2818. // Non-pointers are always inputs.
  2819. auto &type = get<SPIRType>(arg.type);
  2820. if (!type.pointer)
  2821. continue;
  2822. // Opaque argument types are always in
  2823. bool potential_preserve;
  2824. switch (type.basetype)
  2825. {
  2826. case SPIRType::Sampler:
  2827. case SPIRType::Image:
  2828. case SPIRType::SampledImage:
  2829. case SPIRType::AtomicCounter:
  2830. potential_preserve = false;
  2831. break;
  2832. default:
  2833. potential_preserve = true;
  2834. break;
  2835. }
  2836. if (!potential_preserve)
  2837. continue;
  2838. auto itr = variable_to_blocks.find(arg.id);
  2839. if (itr == end(variable_to_blocks))
  2840. {
  2841. // Variable is never accessed.
  2842. continue;
  2843. }
  2844. // We have accessed a variable, but there was no complete writes to that variable.
  2845. // We deduce that we must preserve the argument.
  2846. itr = complete_write_blocks.find(arg.id);
  2847. if (itr == end(complete_write_blocks))
  2848. {
  2849. arg.read_count++;
  2850. continue;
  2851. }
  2852. // If there is a path through the CFG where no block completely writes to the variable, the variable will be in an undefined state
  2853. // when the function returns. We therefore need to implicitly preserve the variable in case there are writers in the function.
  2854. // Major case here is if a function is
  2855. // void foo(int &var) { if (cond) var = 10; }
  2856. // Using read/write counts, we will think it's just an out variable, but it really needs to be inout,
  2857. // because if we don't write anything whatever we put into the function must return back to the caller.
  2858. unordered_set<uint32_t> visit_cache;
  2859. if (exists_unaccessed_path_to_return(cfg, entry.entry_block, itr->second, visit_cache))
  2860. arg.read_count++;
  2861. }
  2862. }
  2863. Compiler::AnalyzeVariableScopeAccessHandler::AnalyzeVariableScopeAccessHandler(Compiler &compiler_,
  2864. SPIRFunction &entry_)
  2865. : OpcodeHandler(compiler_)
  2866. , entry(entry_)
  2867. {
  2868. }
  2869. bool Compiler::AnalyzeVariableScopeAccessHandler::follow_function_call(const SPIRFunction &)
  2870. {
  2871. // Only analyze within this function.
  2872. return false;
  2873. }
  2874. void Compiler::AnalyzeVariableScopeAccessHandler::set_current_block(const SPIRBlock &block)
  2875. {
  2876. current_block = &block;
  2877. // If we're branching to a block which uses OpPhi, in GLSL
  2878. // this will be a variable write when we branch,
  2879. // so we need to track access to these variables as well to
  2880. // have a complete picture.
  2881. const auto test_phi = [this, &block](uint32_t to) {
  2882. auto &next = compiler.get<SPIRBlock>(to);
  2883. for (auto &phi : next.phi_variables)
  2884. {
  2885. if (phi.parent == block.self)
  2886. {
  2887. accessed_variables_to_block[phi.function_variable].insert(block.self);
  2888. // Phi variables are also accessed in our target branch block.
  2889. accessed_variables_to_block[phi.function_variable].insert(next.self);
  2890. notify_variable_access(phi.local_variable, block.self);
  2891. }
  2892. }
  2893. };
  2894. switch (block.terminator)
  2895. {
  2896. case SPIRBlock::Direct:
  2897. notify_variable_access(block.condition, block.self);
  2898. test_phi(block.next_block);
  2899. break;
  2900. case SPIRBlock::Select:
  2901. notify_variable_access(block.condition, block.self);
  2902. test_phi(block.true_block);
  2903. test_phi(block.false_block);
  2904. break;
  2905. case SPIRBlock::MultiSelect:
  2906. {
  2907. notify_variable_access(block.condition, block.self);
  2908. auto &cases = compiler.get_case_list(block);
  2909. for (auto &target : cases)
  2910. test_phi(target.block);
  2911. if (block.default_block)
  2912. test_phi(block.default_block);
  2913. break;
  2914. }
  2915. default:
  2916. break;
  2917. }
  2918. }
  2919. void Compiler::AnalyzeVariableScopeAccessHandler::notify_variable_access(uint32_t id, uint32_t block)
  2920. {
  2921. if (id == 0)
  2922. return;
  2923. // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
  2924. auto itr = rvalue_forward_children.find(id);
  2925. if (itr != end(rvalue_forward_children))
  2926. for (auto child_id : itr->second)
  2927. notify_variable_access(child_id, block);
  2928. if (id_is_phi_variable(id))
  2929. accessed_variables_to_block[id].insert(block);
  2930. else if (id_is_potential_temporary(id))
  2931. accessed_temporaries_to_block[id].insert(block);
  2932. }
  2933. bool Compiler::AnalyzeVariableScopeAccessHandler::id_is_phi_variable(uint32_t id) const
  2934. {
  2935. if (id >= compiler.get_current_id_bound())
  2936. return false;
  2937. auto *var = compiler.maybe_get<SPIRVariable>(id);
  2938. return var && var->phi_variable;
  2939. }
  2940. bool Compiler::AnalyzeVariableScopeAccessHandler::id_is_potential_temporary(uint32_t id) const
  2941. {
  2942. if (id >= compiler.get_current_id_bound())
  2943. return false;
  2944. // Temporaries are not created before we start emitting code.
  2945. return compiler.ir.ids[id].empty() || (compiler.ir.ids[id].get_type() == TypeExpression);
  2946. }
  2947. bool Compiler::AnalyzeVariableScopeAccessHandler::handle_terminator(const SPIRBlock &block)
  2948. {
  2949. switch (block.terminator)
  2950. {
  2951. case SPIRBlock::Return:
  2952. if (block.return_value)
  2953. notify_variable_access(block.return_value, block.self);
  2954. break;
  2955. case SPIRBlock::Select:
  2956. case SPIRBlock::MultiSelect:
  2957. notify_variable_access(block.condition, block.self);
  2958. break;
  2959. default:
  2960. break;
  2961. }
  2962. return true;
  2963. }
  2964. bool Compiler::AnalyzeVariableScopeAccessHandler::handle(Op op, const uint32_t *args, uint32_t length)
  2965. {
  2966. // Keep track of the types of temporaries, so we can hoist them out as necessary.
  2967. uint32_t result_type = 0, result_id = 0;
  2968. if (instruction_to_result_type(result_type, result_id, op, args, length))
  2969. {
  2970. // For some opcodes, we will need to override the result id.
  2971. // If we need to hoist the temporary, the temporary type is the input, not the result.
  2972. if (op == OpConvertUToAccelerationStructureKHR)
  2973. {
  2974. auto itr = result_id_to_type.find(args[2]);
  2975. if (itr != result_id_to_type.end())
  2976. result_type = itr->second;
  2977. }
  2978. result_id_to_type[result_id] = result_type;
  2979. }
  2980. switch (op)
  2981. {
  2982. case OpStore:
  2983. case OpCooperativeMatrixStoreKHR:
  2984. {
  2985. if (length < 2)
  2986. return false;
  2987. ID ptr = args[0];
  2988. auto *var = compiler.maybe_get_backing_variable(ptr);
  2989. // If we store through an access chain, we have a partial write.
  2990. if (var)
  2991. {
  2992. accessed_variables_to_block[var->self].insert(current_block->self);
  2993. if (var->self == ptr)
  2994. complete_write_variables_to_block[var->self].insert(current_block->self);
  2995. else
  2996. partial_write_variables_to_block[var->self].insert(current_block->self);
  2997. }
  2998. // args[0] might be an access chain we have to track use of.
  2999. notify_variable_access(args[0], current_block->self);
  3000. // Might try to store a Phi variable here.
  3001. notify_variable_access(args[1], current_block->self);
  3002. break;
  3003. }
  3004. case OpAccessChain:
  3005. case OpInBoundsAccessChain:
  3006. case OpPtrAccessChain:
  3007. {
  3008. if (length < 3)
  3009. return false;
  3010. // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
  3011. uint32_t ptr = args[2];
  3012. auto *var = compiler.maybe_get<SPIRVariable>(ptr);
  3013. if (var)
  3014. {
  3015. accessed_variables_to_block[var->self].insert(current_block->self);
  3016. rvalue_forward_children[args[1]].insert(var->self);
  3017. }
  3018. // args[2] might be another access chain we have to track use of.
  3019. for (uint32_t i = 2; i < length; i++)
  3020. {
  3021. notify_variable_access(args[i], current_block->self);
  3022. rvalue_forward_children[args[1]].insert(args[i]);
  3023. }
  3024. // Also keep track of the access chain pointer itself.
  3025. // In exceptionally rare cases, we can end up with a case where
  3026. // the access chain is generated in the loop body, but is consumed in continue block.
  3027. // This means we need complex loop workarounds, and we must detect this via CFG analysis.
  3028. notify_variable_access(args[1], current_block->self);
  3029. // The result of an access chain is a fixed expression and is not really considered a temporary.
  3030. auto &e = compiler.set<SPIRExpression>(args[1], "", args[0], true);
  3031. auto *backing_variable = compiler.maybe_get_backing_variable(ptr);
  3032. e.loaded_from = backing_variable ? VariableID(backing_variable->self) : VariableID(0);
  3033. // Other backends might use SPIRAccessChain for this later.
  3034. compiler.ir.ids[args[1]].set_allow_type_rewrite();
  3035. access_chain_expressions.insert(args[1]);
  3036. break;
  3037. }
  3038. case OpCopyMemory:
  3039. {
  3040. if (length < 2)
  3041. return false;
  3042. ID lhs = args[0];
  3043. ID rhs = args[1];
  3044. auto *var = compiler.maybe_get_backing_variable(lhs);
  3045. // If we store through an access chain, we have a partial write.
  3046. if (var)
  3047. {
  3048. accessed_variables_to_block[var->self].insert(current_block->self);
  3049. if (var->self == lhs)
  3050. complete_write_variables_to_block[var->self].insert(current_block->self);
  3051. else
  3052. partial_write_variables_to_block[var->self].insert(current_block->self);
  3053. }
  3054. // args[0:1] might be access chains we have to track use of.
  3055. for (uint32_t i = 0; i < 2; i++)
  3056. notify_variable_access(args[i], current_block->self);
  3057. var = compiler.maybe_get_backing_variable(rhs);
  3058. if (var)
  3059. accessed_variables_to_block[var->self].insert(current_block->self);
  3060. break;
  3061. }
  3062. case OpCopyObject:
  3063. {
  3064. // OpCopyObject copies the underlying non-pointer type,
  3065. // so any temp variable should be declared using the underlying type.
  3066. // If the type is a pointer, get its base type and overwrite the result type mapping.
  3067. auto &type = compiler.get<SPIRType>(result_type);
  3068. if (type.pointer)
  3069. result_id_to_type[result_id] = type.parent_type;
  3070. if (length < 3)
  3071. return false;
  3072. auto *var = compiler.maybe_get_backing_variable(args[2]);
  3073. if (var)
  3074. accessed_variables_to_block[var->self].insert(current_block->self);
  3075. // Might be an access chain which we have to keep track of.
  3076. notify_variable_access(args[1], current_block->self);
  3077. if (access_chain_expressions.count(args[2]))
  3078. access_chain_expressions.insert(args[1]);
  3079. // Might try to copy a Phi variable here.
  3080. notify_variable_access(args[2], current_block->self);
  3081. break;
  3082. }
  3083. case OpLoad:
  3084. case OpCooperativeMatrixLoadKHR:
  3085. {
  3086. if (length < 3)
  3087. return false;
  3088. uint32_t ptr = args[2];
  3089. auto *var = compiler.maybe_get_backing_variable(ptr);
  3090. if (var)
  3091. accessed_variables_to_block[var->self].insert(current_block->self);
  3092. // Loaded value is a temporary.
  3093. notify_variable_access(args[1], current_block->self);
  3094. // Might be an access chain we have to track use of.
  3095. notify_variable_access(args[2], current_block->self);
  3096. // If we're loading an opaque type we cannot lower it to a temporary,
  3097. // we must defer access of args[2] until it's used.
  3098. auto &type = compiler.get<SPIRType>(args[0]);
  3099. if (compiler.type_is_opaque_value(type))
  3100. rvalue_forward_children[args[1]].insert(args[2]);
  3101. break;
  3102. }
  3103. case OpFunctionCall:
  3104. {
  3105. if (length < 3)
  3106. return false;
  3107. // Return value may be a temporary.
  3108. if (compiler.get_type(args[0]).basetype != SPIRType::Void)
  3109. notify_variable_access(args[1], current_block->self);
  3110. length -= 3;
  3111. args += 3;
  3112. for (uint32_t i = 0; i < length; i++)
  3113. {
  3114. auto *var = compiler.maybe_get_backing_variable(args[i]);
  3115. if (var)
  3116. {
  3117. accessed_variables_to_block[var->self].insert(current_block->self);
  3118. // Assume we can get partial writes to this variable.
  3119. partial_write_variables_to_block[var->self].insert(current_block->self);
  3120. }
  3121. // Cannot easily prove if argument we pass to a function is completely written.
  3122. // Usually, functions write to a dummy variable,
  3123. // which is then copied to in full to the real argument.
  3124. // Might try to copy a Phi variable here.
  3125. notify_variable_access(args[i], current_block->self);
  3126. }
  3127. break;
  3128. }
  3129. case OpSelect:
  3130. {
  3131. // In case of variable pointers, we might access a variable here.
  3132. // We cannot prove anything about these accesses however.
  3133. for (uint32_t i = 1; i < length; i++)
  3134. {
  3135. if (i >= 3)
  3136. {
  3137. auto *var = compiler.maybe_get_backing_variable(args[i]);
  3138. if (var)
  3139. {
  3140. accessed_variables_to_block[var->self].insert(current_block->self);
  3141. // Assume we can get partial writes to this variable.
  3142. partial_write_variables_to_block[var->self].insert(current_block->self);
  3143. }
  3144. }
  3145. // Might try to copy a Phi variable here.
  3146. notify_variable_access(args[i], current_block->self);
  3147. }
  3148. break;
  3149. }
  3150. case OpExtInst:
  3151. {
  3152. for (uint32_t i = 4; i < length; i++)
  3153. notify_variable_access(args[i], current_block->self);
  3154. notify_variable_access(args[1], current_block->self);
  3155. uint32_t extension_set = args[2];
  3156. if (compiler.get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  3157. {
  3158. auto op_450 = static_cast<GLSLstd450>(args[3]);
  3159. switch (op_450)
  3160. {
  3161. case GLSLstd450Modf:
  3162. case GLSLstd450Frexp:
  3163. {
  3164. uint32_t ptr = args[5];
  3165. auto *var = compiler.maybe_get_backing_variable(ptr);
  3166. if (var)
  3167. {
  3168. accessed_variables_to_block[var->self].insert(current_block->self);
  3169. if (var->self == ptr)
  3170. complete_write_variables_to_block[var->self].insert(current_block->self);
  3171. else
  3172. partial_write_variables_to_block[var->self].insert(current_block->self);
  3173. }
  3174. break;
  3175. }
  3176. default:
  3177. break;
  3178. }
  3179. }
  3180. break;
  3181. }
  3182. case OpArrayLength:
  3183. // Only result is a temporary.
  3184. notify_variable_access(args[1], current_block->self);
  3185. break;
  3186. case OpLine:
  3187. case OpNoLine:
  3188. // Uses literals, but cannot be a phi variable or temporary, so ignore.
  3189. break;
  3190. // Atomics shouldn't be able to access function-local variables.
  3191. // Some GLSL builtins access a pointer.
  3192. case OpCompositeInsert:
  3193. case OpVectorShuffle:
  3194. // Specialize for opcode which contains literals.
  3195. for (uint32_t i = 1; i < 4; i++)
  3196. notify_variable_access(args[i], current_block->self);
  3197. break;
  3198. case OpCompositeExtract:
  3199. // Specialize for opcode which contains literals.
  3200. for (uint32_t i = 1; i < 3; i++)
  3201. notify_variable_access(args[i], current_block->self);
  3202. break;
  3203. case OpImageWrite:
  3204. for (uint32_t i = 0; i < length; i++)
  3205. {
  3206. // Argument 3 is a literal.
  3207. if (i != 3)
  3208. notify_variable_access(args[i], current_block->self);
  3209. }
  3210. break;
  3211. case OpImageSampleImplicitLod:
  3212. case OpImageSampleExplicitLod:
  3213. case OpImageSparseSampleImplicitLod:
  3214. case OpImageSparseSampleExplicitLod:
  3215. case OpImageSampleProjImplicitLod:
  3216. case OpImageSampleProjExplicitLod:
  3217. case OpImageSparseSampleProjImplicitLod:
  3218. case OpImageSparseSampleProjExplicitLod:
  3219. case OpImageFetch:
  3220. case OpImageSparseFetch:
  3221. case OpImageRead:
  3222. case OpImageSparseRead:
  3223. for (uint32_t i = 1; i < length; i++)
  3224. {
  3225. // Argument 4 is a literal.
  3226. if (i != 4)
  3227. notify_variable_access(args[i], current_block->self);
  3228. }
  3229. break;
  3230. case OpImageSampleDrefImplicitLod:
  3231. case OpImageSampleDrefExplicitLod:
  3232. case OpImageSparseSampleDrefImplicitLod:
  3233. case OpImageSparseSampleDrefExplicitLod:
  3234. case OpImageSampleProjDrefImplicitLod:
  3235. case OpImageSampleProjDrefExplicitLod:
  3236. case OpImageSparseSampleProjDrefImplicitLod:
  3237. case OpImageSparseSampleProjDrefExplicitLod:
  3238. case OpImageGather:
  3239. case OpImageSparseGather:
  3240. case OpImageDrefGather:
  3241. case OpImageSparseDrefGather:
  3242. for (uint32_t i = 1; i < length; i++)
  3243. {
  3244. // Argument 5 is a literal.
  3245. if (i != 5)
  3246. notify_variable_access(args[i], current_block->self);
  3247. }
  3248. break;
  3249. default:
  3250. {
  3251. // Rather dirty way of figuring out where Phi variables are used.
  3252. // As long as only IDs are used, we can scan through instructions and try to find any evidence that
  3253. // the ID of a variable has been used.
  3254. // There are potential false positives here where a literal is used in-place of an ID,
  3255. // but worst case, it does not affect the correctness of the compile.
  3256. // Exhaustive analysis would be better here, but it's not worth it for now.
  3257. for (uint32_t i = 0; i < length; i++)
  3258. notify_variable_access(args[i], current_block->self);
  3259. break;
  3260. }
  3261. }
  3262. return true;
  3263. }
  3264. Compiler::StaticExpressionAccessHandler::StaticExpressionAccessHandler(Compiler &compiler_, uint32_t variable_id_)
  3265. : OpcodeHandler(compiler_)
  3266. , variable_id(variable_id_)
  3267. {
  3268. }
  3269. bool Compiler::StaticExpressionAccessHandler::follow_function_call(const SPIRFunction &)
  3270. {
  3271. return false;
  3272. }
  3273. bool Compiler::StaticExpressionAccessHandler::handle(Op op, const uint32_t *args, uint32_t length)
  3274. {
  3275. switch (op)
  3276. {
  3277. case OpStore:
  3278. case OpCooperativeMatrixStoreKHR:
  3279. if (length < 2)
  3280. return false;
  3281. if (args[0] == variable_id)
  3282. {
  3283. static_expression = args[1];
  3284. write_count++;
  3285. }
  3286. break;
  3287. case OpLoad:
  3288. case OpCooperativeMatrixLoadKHR:
  3289. if (length < 3)
  3290. return false;
  3291. if (args[2] == variable_id && static_expression == 0) // Tried to read from variable before it was initialized.
  3292. return false;
  3293. break;
  3294. case OpAccessChain:
  3295. case OpInBoundsAccessChain:
  3296. case OpPtrAccessChain:
  3297. if (length < 3)
  3298. return false;
  3299. if (args[2] == variable_id) // If we try to access chain our candidate variable before we store to it, bail.
  3300. return false;
  3301. break;
  3302. default:
  3303. break;
  3304. }
  3305. return true;
  3306. }
  3307. void Compiler::find_function_local_luts(SPIRFunction &entry, const AnalyzeVariableScopeAccessHandler &handler,
  3308. bool single_function)
  3309. {
  3310. auto &cfg = *function_cfgs.find(entry.self)->second;
  3311. // For each variable which is statically accessed.
  3312. for (auto &accessed_var : handler.accessed_variables_to_block)
  3313. {
  3314. auto &blocks = accessed_var.second;
  3315. auto &var = get<SPIRVariable>(accessed_var.first);
  3316. auto &type = expression_type(accessed_var.first);
  3317. // First check if there are writes to the variable. Later, if there are none, we'll
  3318. // reconsider it as globally accessed LUT.
  3319. if (!var.is_written_to)
  3320. {
  3321. var.is_written_to = handler.complete_write_variables_to_block.count(var.self) != 0 ||
  3322. handler.partial_write_variables_to_block.count(var.self) != 0;
  3323. }
  3324. // Only consider function local variables here.
  3325. // If we only have a single function in our CFG, private storage is also fine,
  3326. // since it behaves like a function local variable.
  3327. bool allow_lut = var.storage == StorageClassFunction || (single_function && var.storage == StorageClassPrivate);
  3328. if (!allow_lut)
  3329. continue;
  3330. // We cannot be a phi variable.
  3331. if (var.phi_variable)
  3332. continue;
  3333. // Only consider arrays here.
  3334. if (type.array.empty())
  3335. continue;
  3336. // If the variable has an initializer, make sure it is a constant expression.
  3337. uint32_t static_constant_expression = 0;
  3338. if (var.initializer)
  3339. {
  3340. if (ir.ids[var.initializer].get_type() != TypeConstant)
  3341. continue;
  3342. static_constant_expression = var.initializer;
  3343. // There can be no stores to this variable, we have now proved we have a LUT.
  3344. if (var.is_written_to)
  3345. continue;
  3346. }
  3347. else
  3348. {
  3349. // We can have one, and only one write to the variable, and that write needs to be a constant.
  3350. // No partial writes allowed.
  3351. if (handler.partial_write_variables_to_block.count(var.self) != 0)
  3352. continue;
  3353. auto itr = handler.complete_write_variables_to_block.find(var.self);
  3354. // No writes?
  3355. if (itr == end(handler.complete_write_variables_to_block))
  3356. continue;
  3357. // We write to the variable in more than one block.
  3358. auto &write_blocks = itr->second;
  3359. if (write_blocks.size() != 1)
  3360. continue;
  3361. // The write needs to happen in the dominating block.
  3362. DominatorBuilder builder(cfg);
  3363. for (auto &block : blocks)
  3364. builder.add_block(block);
  3365. uint32_t dominator = builder.get_dominator();
  3366. // The complete write happened in a branch or similar, cannot deduce static expression.
  3367. if (write_blocks.count(dominator) == 0)
  3368. continue;
  3369. // Find the static expression for this variable.
  3370. StaticExpressionAccessHandler static_expression_handler(*this, var.self);
  3371. traverse_all_reachable_opcodes(get<SPIRBlock>(dominator), static_expression_handler);
  3372. // We want one, and exactly one write
  3373. if (static_expression_handler.write_count != 1 || static_expression_handler.static_expression == 0)
  3374. continue;
  3375. // Is it a constant expression?
  3376. if (ir.ids[static_expression_handler.static_expression].get_type() != TypeConstant)
  3377. continue;
  3378. // We found a LUT!
  3379. static_constant_expression = static_expression_handler.static_expression;
  3380. }
  3381. get<SPIRConstant>(static_constant_expression).is_used_as_lut = true;
  3382. var.static_expression = static_constant_expression;
  3383. var.statically_assigned = true;
  3384. var.remapped_variable = true;
  3385. }
  3386. }
  3387. void Compiler::analyze_variable_scope(SPIRFunction &entry, AnalyzeVariableScopeAccessHandler &handler)
  3388. {
  3389. // First, we map out all variable access within a function.
  3390. // Essentially a map of block -> { variables accessed in the basic block }
  3391. traverse_all_reachable_opcodes(entry, handler);
  3392. auto &cfg = *function_cfgs.find(entry.self)->second;
  3393. // Analyze if there are parameters which need to be implicitly preserved with an "in" qualifier.
  3394. analyze_parameter_preservation(entry, cfg, handler.accessed_variables_to_block,
  3395. handler.complete_write_variables_to_block);
  3396. unordered_map<uint32_t, uint32_t> potential_loop_variables;
  3397. // Find the loop dominator block for each block.
  3398. for (auto &block_id : entry.blocks)
  3399. {
  3400. auto &block = get<SPIRBlock>(block_id);
  3401. auto itr = ir.continue_block_to_loop_header.find(block_id);
  3402. if (itr != end(ir.continue_block_to_loop_header) && itr->second != block_id)
  3403. {
  3404. // Continue block might be unreachable in the CFG, but we still like to know the loop dominator.
  3405. // Edge case is when continue block is also the loop header, don't set the dominator in this case.
  3406. block.loop_dominator = itr->second;
  3407. }
  3408. else
  3409. {
  3410. uint32_t loop_dominator = cfg.find_loop_dominator(block_id);
  3411. if (loop_dominator != block_id)
  3412. block.loop_dominator = loop_dominator;
  3413. else
  3414. block.loop_dominator = SPIRBlock::NoDominator;
  3415. }
  3416. }
  3417. // For each variable which is statically accessed.
  3418. for (auto &var : handler.accessed_variables_to_block)
  3419. {
  3420. // Only deal with variables which are considered local variables in this function.
  3421. if (find(begin(entry.local_variables), end(entry.local_variables), VariableID(var.first)) ==
  3422. end(entry.local_variables))
  3423. continue;
  3424. DominatorBuilder builder(cfg);
  3425. auto &blocks = var.second;
  3426. auto &type = expression_type(var.first);
  3427. BlockID potential_continue_block = 0;
  3428. // Figure out which block is dominating all accesses of those variables.
  3429. for (auto &block : blocks)
  3430. {
  3431. // If we're accessing a variable inside a continue block, this variable might be a loop variable.
  3432. // We can only use loop variables with scalars, as we cannot track static expressions for vectors.
  3433. if (is_continue(block))
  3434. {
  3435. // Potentially awkward case to check for.
  3436. // We might have a variable inside a loop, which is touched by the continue block,
  3437. // but is not actually a loop variable.
  3438. // The continue block is dominated by the inner part of the loop, which does not make sense in high-level
  3439. // language output because it will be declared before the body,
  3440. // so we will have to lift the dominator up to the relevant loop header instead.
  3441. builder.add_block(ir.continue_block_to_loop_header[block]);
  3442. // Arrays or structs cannot be loop variables.
  3443. if (type.vecsize == 1 && type.columns == 1 && type.basetype != SPIRType::Struct && type.array.empty())
  3444. {
  3445. // The variable is used in multiple continue blocks, this is not a loop
  3446. // candidate, signal that by setting block to -1u.
  3447. if (potential_continue_block == 0)
  3448. potential_continue_block = block;
  3449. else
  3450. potential_continue_block = ~(0u);
  3451. }
  3452. }
  3453. builder.add_block(block);
  3454. }
  3455. builder.lift_continue_block_dominator();
  3456. // Add it to a per-block list of variables.
  3457. BlockID dominating_block = builder.get_dominator();
  3458. if (dominating_block && potential_continue_block != 0 && potential_continue_block != ~0u)
  3459. {
  3460. auto &inner_block = get<SPIRBlock>(dominating_block);
  3461. BlockID merge_candidate = 0;
  3462. // Analyze the dominator. If it lives in a different loop scope than the candidate continue
  3463. // block, reject the loop variable candidate.
  3464. if (inner_block.merge == SPIRBlock::MergeLoop)
  3465. merge_candidate = inner_block.merge_block;
  3466. else if (inner_block.loop_dominator != SPIRBlock::NoDominator)
  3467. merge_candidate = get<SPIRBlock>(inner_block.loop_dominator).merge_block;
  3468. if (merge_candidate != 0 && cfg.is_reachable(merge_candidate))
  3469. {
  3470. // If the merge block has a higher post-visit order, we know that continue candidate
  3471. // cannot reach the merge block, and we have two separate scopes.
  3472. if (!cfg.is_reachable(potential_continue_block) ||
  3473. cfg.get_visit_order(merge_candidate) > cfg.get_visit_order(potential_continue_block))
  3474. {
  3475. potential_continue_block = 0;
  3476. }
  3477. }
  3478. }
  3479. if (potential_continue_block != 0 && potential_continue_block != ~0u)
  3480. potential_loop_variables[var.first] = potential_continue_block;
  3481. // For variables whose dominating block is inside a loop, there is a risk that these variables
  3482. // actually need to be preserved across loop iterations. We can express this by adding
  3483. // a "read" access to the loop header.
  3484. // In the dominating block, we must see an OpStore or equivalent as the first access of an OpVariable.
  3485. // Should that fail, we look for the outermost loop header and tack on an access there.
  3486. // Phi nodes cannot have this problem.
  3487. if (dominating_block)
  3488. {
  3489. auto &variable = get<SPIRVariable>(var.first);
  3490. if (!variable.phi_variable)
  3491. {
  3492. auto *block = &get<SPIRBlock>(dominating_block);
  3493. bool preserve = may_read_undefined_variable_in_block(*block, var.first);
  3494. if (preserve)
  3495. {
  3496. // Find the outermost loop scope.
  3497. while (block->loop_dominator != BlockID(SPIRBlock::NoDominator))
  3498. block = &get<SPIRBlock>(block->loop_dominator);
  3499. if (block->self != dominating_block)
  3500. {
  3501. builder.add_block(block->self);
  3502. dominating_block = builder.get_dominator();
  3503. }
  3504. }
  3505. }
  3506. }
  3507. // If all blocks here are dead code, this will be 0, so the variable in question
  3508. // will be completely eliminated.
  3509. if (dominating_block)
  3510. {
  3511. auto &block = get<SPIRBlock>(dominating_block);
  3512. block.dominated_variables.push_back(var.first);
  3513. get<SPIRVariable>(var.first).dominator = dominating_block;
  3514. }
  3515. }
  3516. for (auto &var : handler.accessed_temporaries_to_block)
  3517. {
  3518. auto itr = handler.result_id_to_type.find(var.first);
  3519. if (itr == end(handler.result_id_to_type))
  3520. {
  3521. // We found a false positive ID being used, ignore.
  3522. // This should probably be an assert.
  3523. continue;
  3524. }
  3525. // There is no point in doing domination analysis for opaque types.
  3526. auto &type = get<SPIRType>(itr->second);
  3527. if (type_is_opaque_value(type))
  3528. continue;
  3529. DominatorBuilder builder(cfg);
  3530. bool force_temporary = false;
  3531. bool used_in_header_hoisted_continue_block = false;
  3532. // Figure out which block is dominating all accesses of those temporaries.
  3533. auto &blocks = var.second;
  3534. for (auto &block : blocks)
  3535. {
  3536. builder.add_block(block);
  3537. if (blocks.size() != 1 && is_continue(block))
  3538. {
  3539. // The risk here is that inner loop can dominate the continue block.
  3540. // Any temporary we access in the continue block must be declared before the loop.
  3541. // This is moot for complex loops however.
  3542. auto &loop_header_block = get<SPIRBlock>(ir.continue_block_to_loop_header[block]);
  3543. assert(loop_header_block.merge == SPIRBlock::MergeLoop);
  3544. builder.add_block(loop_header_block.self);
  3545. used_in_header_hoisted_continue_block = true;
  3546. }
  3547. }
  3548. uint32_t dominating_block = builder.get_dominator();
  3549. if (blocks.size() != 1 && is_single_block_loop(dominating_block))
  3550. {
  3551. // Awkward case, because the loop header is also the continue block,
  3552. // so hoisting to loop header does not help.
  3553. force_temporary = true;
  3554. }
  3555. if (dominating_block)
  3556. {
  3557. // If we touch a variable in the dominating block, this is the expected setup.
  3558. // SPIR-V normally mandates this, but we have extra cases for temporary use inside loops.
  3559. bool first_use_is_dominator = blocks.count(dominating_block) != 0;
  3560. if (!first_use_is_dominator || force_temporary)
  3561. {
  3562. if (handler.access_chain_expressions.count(var.first))
  3563. {
  3564. // Exceptionally rare case.
  3565. // We cannot declare temporaries of access chains (except on MSL perhaps with pointers).
  3566. // Rather than do that, we force the indexing expressions to be declared in the right scope by
  3567. // tracking their usage to that end. There is no temporary to hoist.
  3568. // However, we still need to observe declaration order of the access chain.
  3569. if (used_in_header_hoisted_continue_block)
  3570. {
  3571. // For this scenario, we used an access chain inside a continue block where we also registered an access to header block.
  3572. // This is a problem as we need to declare an access chain properly first with full definition.
  3573. // We cannot use temporaries for these expressions,
  3574. // so we must make sure the access chain is declared ahead of time.
  3575. // Force a complex for loop to deal with this.
  3576. // TODO: Out-of-order declaring for loops where continue blocks are emitted last might be another option.
  3577. auto &loop_header_block = get<SPIRBlock>(dominating_block);
  3578. assert(loop_header_block.merge == SPIRBlock::MergeLoop);
  3579. loop_header_block.complex_continue = true;
  3580. }
  3581. }
  3582. else
  3583. {
  3584. // This should be very rare, but if we try to declare a temporary inside a loop,
  3585. // and that temporary is used outside the loop as well (spirv-opt inliner likes this)
  3586. // we should actually emit the temporary outside the loop.
  3587. hoisted_temporaries.insert(var.first);
  3588. forced_temporaries.insert(var.first);
  3589. auto &block_temporaries = get<SPIRBlock>(dominating_block).declare_temporary;
  3590. block_temporaries.emplace_back(handler.result_id_to_type[var.first], var.first);
  3591. }
  3592. }
  3593. else if (blocks.size() > 1)
  3594. {
  3595. // Keep track of the temporary as we might have to declare this temporary.
  3596. // This can happen if the loop header dominates a temporary, but we have a complex fallback loop.
  3597. // In this case, the header is actually inside the for (;;) {} block, and we have problems.
  3598. // What we need to do is hoist the temporaries outside the for (;;) {} block in case the header block
  3599. // declares the temporary.
  3600. auto &block_temporaries = get<SPIRBlock>(dominating_block).potential_declare_temporary;
  3601. block_temporaries.emplace_back(handler.result_id_to_type[var.first], var.first);
  3602. }
  3603. }
  3604. }
  3605. unordered_set<uint32_t> seen_blocks;
  3606. // Now, try to analyze whether or not these variables are actually loop variables.
  3607. for (auto &loop_variable : potential_loop_variables)
  3608. {
  3609. auto &var = get<SPIRVariable>(loop_variable.first);
  3610. auto dominator = var.dominator;
  3611. BlockID block = loop_variable.second;
  3612. // The variable was accessed in multiple continue blocks, ignore.
  3613. if (block == BlockID(~(0u)) || block == BlockID(0))
  3614. continue;
  3615. // Dead code.
  3616. if (dominator == ID(0))
  3617. continue;
  3618. BlockID header = 0;
  3619. // Find the loop header for this block if we are a continue block.
  3620. {
  3621. auto itr = ir.continue_block_to_loop_header.find(block);
  3622. if (itr != end(ir.continue_block_to_loop_header))
  3623. {
  3624. header = itr->second;
  3625. }
  3626. else if (get<SPIRBlock>(block).continue_block == block)
  3627. {
  3628. // Also check for self-referential continue block.
  3629. header = block;
  3630. }
  3631. }
  3632. assert(header);
  3633. auto &header_block = get<SPIRBlock>(header);
  3634. auto &blocks = handler.accessed_variables_to_block[loop_variable.first];
  3635. // If a loop variable is not used before the loop, it's probably not a loop variable.
  3636. bool has_accessed_variable = blocks.count(header) != 0;
  3637. // Now, there are two conditions we need to meet for the variable to be a loop variable.
  3638. // 1. The dominating block must have a branch-free path to the loop header,
  3639. // this way we statically know which expression should be part of the loop variable initializer.
  3640. // Walk from the dominator, if there is one straight edge connecting
  3641. // dominator and loop header, we statically know the loop initializer.
  3642. bool static_loop_init = true;
  3643. while (dominator != header)
  3644. {
  3645. if (blocks.count(dominator) != 0)
  3646. has_accessed_variable = true;
  3647. auto &succ = cfg.get_succeeding_edges(dominator);
  3648. if (succ.size() != 1)
  3649. {
  3650. static_loop_init = false;
  3651. break;
  3652. }
  3653. auto &pred = cfg.get_preceding_edges(succ.front());
  3654. if (pred.size() != 1 || pred.front() != dominator)
  3655. {
  3656. static_loop_init = false;
  3657. break;
  3658. }
  3659. dominator = succ.front();
  3660. }
  3661. if (!static_loop_init || !has_accessed_variable)
  3662. continue;
  3663. // The second condition we need to meet is that no access after the loop
  3664. // merge can occur. Walk the CFG to see if we find anything.
  3665. seen_blocks.clear();
  3666. cfg.walk_from(seen_blocks, header_block.merge_block, [&](uint32_t walk_block) -> bool {
  3667. // We found a block which accesses the variable outside the loop.
  3668. if (blocks.find(walk_block) != end(blocks))
  3669. static_loop_init = false;
  3670. return true;
  3671. });
  3672. if (!static_loop_init)
  3673. continue;
  3674. // We have a loop variable.
  3675. header_block.loop_variables.push_back(loop_variable.first);
  3676. // Need to sort here as variables come from an unordered container, and pushing stuff in wrong order
  3677. // will break reproducability in regression runs.
  3678. sort(begin(header_block.loop_variables), end(header_block.loop_variables));
  3679. get<SPIRVariable>(loop_variable.first).loop_variable = true;
  3680. }
  3681. }
  3682. bool Compiler::may_read_undefined_variable_in_block(const SPIRBlock &block, uint32_t var)
  3683. {
  3684. for (auto &op : block.ops)
  3685. {
  3686. auto *ops = stream(op);
  3687. switch (op.op)
  3688. {
  3689. case OpStore:
  3690. case OpCooperativeMatrixStoreKHR:
  3691. case OpCopyMemory:
  3692. if (ops[0] == var)
  3693. return false;
  3694. break;
  3695. case OpAccessChain:
  3696. case OpInBoundsAccessChain:
  3697. case OpPtrAccessChain:
  3698. // Access chains are generally used to partially read and write. It's too hard to analyze
  3699. // if all constituents are written fully before continuing, so just assume it's preserved.
  3700. // This is the same as the parameter preservation analysis.
  3701. if (ops[2] == var)
  3702. return true;
  3703. break;
  3704. case OpSelect:
  3705. // Variable pointers.
  3706. // We might read before writing.
  3707. if (ops[3] == var || ops[4] == var)
  3708. return true;
  3709. break;
  3710. case OpPhi:
  3711. {
  3712. // Variable pointers.
  3713. // We might read before writing.
  3714. if (op.length < 2)
  3715. break;
  3716. uint32_t count = op.length - 2;
  3717. for (uint32_t i = 0; i < count; i += 2)
  3718. if (ops[i + 2] == var)
  3719. return true;
  3720. break;
  3721. }
  3722. case OpCopyObject:
  3723. case OpLoad:
  3724. case OpCooperativeVectorLoadNV:
  3725. case OpCooperativeMatrixLoadKHR:
  3726. if (ops[2] == var)
  3727. return true;
  3728. break;
  3729. case OpFunctionCall:
  3730. {
  3731. if (op.length < 3)
  3732. break;
  3733. // May read before writing.
  3734. uint32_t count = op.length - 3;
  3735. for (uint32_t i = 0; i < count; i++)
  3736. if (ops[i + 3] == var)
  3737. return true;
  3738. break;
  3739. }
  3740. default:
  3741. break;
  3742. }
  3743. }
  3744. // Not accessed somehow, at least not in a usual fashion.
  3745. // It's likely accessed in a branch, so assume we must preserve.
  3746. return true;
  3747. }
  3748. bool Compiler::GeometryEmitDisocveryHandler::handle(Op opcode, const uint32_t *, uint32_t)
  3749. {
  3750. if (opcode == OpEmitVertex || opcode == OpEndPrimitive)
  3751. {
  3752. for (auto *func : function_stack)
  3753. func->emits_geometry = true;
  3754. }
  3755. return true;
  3756. }
  3757. bool Compiler::GeometryEmitDisocveryHandler::begin_function_scope(const uint32_t *stream, uint32_t)
  3758. {
  3759. auto &callee = compiler.get<SPIRFunction>(stream[2]);
  3760. function_stack.push_back(&callee);
  3761. return true;
  3762. }
  3763. bool Compiler::GeometryEmitDisocveryHandler::end_function_scope(const uint32_t *stream, uint32_t)
  3764. {
  3765. (void)stream;
  3766. assert(function_stack.back() == &compiler.get<SPIRFunction>(stream[2]));
  3767. function_stack.pop_back();
  3768. return true;
  3769. }
  3770. void Compiler::discover_geometry_emitters()
  3771. {
  3772. GeometryEmitDisocveryHandler handler(*this);
  3773. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  3774. }
  3775. Bitset Compiler::get_buffer_block_flags(VariableID id) const
  3776. {
  3777. return ir.get_buffer_block_flags(get<SPIRVariable>(id));
  3778. }
  3779. bool Compiler::get_common_basic_type(const SPIRType &type, SPIRType::BaseType &base_type)
  3780. {
  3781. if (type.basetype == SPIRType::Struct)
  3782. {
  3783. base_type = SPIRType::Unknown;
  3784. for (auto &member_type : type.member_types)
  3785. {
  3786. SPIRType::BaseType member_base;
  3787. if (!get_common_basic_type(get<SPIRType>(member_type), member_base))
  3788. return false;
  3789. if (base_type == SPIRType::Unknown)
  3790. base_type = member_base;
  3791. else if (base_type != member_base)
  3792. return false;
  3793. }
  3794. return true;
  3795. }
  3796. else
  3797. {
  3798. base_type = type.basetype;
  3799. return true;
  3800. }
  3801. }
  3802. void Compiler::ActiveBuiltinHandler::handle_builtin(const SPIRType &type, BuiltIn builtin,
  3803. const Bitset &decoration_flags)
  3804. {
  3805. // If used, we will need to explicitly declare a new array size for these builtins.
  3806. if (builtin == BuiltInClipDistance)
  3807. {
  3808. if (!type.array_size_literal[0])
  3809. SPIRV_CROSS_THROW("Array size for ClipDistance must be a literal.");
  3810. uint32_t array_size = type.array[0];
  3811. if (array_size == 0)
  3812. SPIRV_CROSS_THROW("Array size for ClipDistance must not be unsized.");
  3813. compiler.clip_distance_count = array_size;
  3814. }
  3815. else if (builtin == BuiltInCullDistance)
  3816. {
  3817. if (!type.array_size_literal[0])
  3818. SPIRV_CROSS_THROW("Array size for CullDistance must be a literal.");
  3819. uint32_t array_size = type.array[0];
  3820. if (array_size == 0)
  3821. SPIRV_CROSS_THROW("Array size for CullDistance must not be unsized.");
  3822. compiler.cull_distance_count = array_size;
  3823. }
  3824. else if (builtin == BuiltInPosition)
  3825. {
  3826. if (decoration_flags.get(DecorationInvariant))
  3827. compiler.position_invariant = true;
  3828. }
  3829. }
  3830. void Compiler::ActiveBuiltinHandler::add_if_builtin(uint32_t id, bool allow_blocks)
  3831. {
  3832. // Only handle plain variables here.
  3833. // Builtins which are part of a block are handled in AccessChain.
  3834. // If allow_blocks is used however, this is to handle initializers of blocks,
  3835. // which implies that all members are written to.
  3836. auto *var = compiler.maybe_get<SPIRVariable>(id);
  3837. auto *m = compiler.ir.find_meta(id);
  3838. if (var && m)
  3839. {
  3840. auto &type = compiler.get<SPIRType>(var->basetype);
  3841. auto &decorations = m->decoration;
  3842. auto &flags = type.storage == StorageClassInput ?
  3843. compiler.active_input_builtins : compiler.active_output_builtins;
  3844. if (decorations.builtin)
  3845. {
  3846. flags.set(decorations.builtin_type);
  3847. handle_builtin(type, decorations.builtin_type, decorations.decoration_flags);
  3848. }
  3849. else if (allow_blocks && compiler.has_decoration(type.self, DecorationBlock))
  3850. {
  3851. uint32_t member_count = uint32_t(type.member_types.size());
  3852. for (uint32_t i = 0; i < member_count; i++)
  3853. {
  3854. if (compiler.has_member_decoration(type.self, i, DecorationBuiltIn))
  3855. {
  3856. auto &member_type = compiler.get<SPIRType>(type.member_types[i]);
  3857. BuiltIn builtin = BuiltIn(compiler.get_member_decoration(type.self, i, DecorationBuiltIn));
  3858. flags.set(builtin);
  3859. handle_builtin(member_type, builtin, compiler.get_member_decoration_bitset(type.self, i));
  3860. }
  3861. }
  3862. }
  3863. }
  3864. }
  3865. void Compiler::ActiveBuiltinHandler::add_if_builtin(uint32_t id)
  3866. {
  3867. add_if_builtin(id, false);
  3868. }
  3869. void Compiler::ActiveBuiltinHandler::add_if_builtin_or_block(uint32_t id)
  3870. {
  3871. add_if_builtin(id, true);
  3872. }
  3873. bool Compiler::ActiveBuiltinHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  3874. {
  3875. switch (opcode)
  3876. {
  3877. case OpStore:
  3878. case OpCooperativeMatrixStoreKHR:
  3879. if (length < 1)
  3880. return false;
  3881. add_if_builtin(args[0]);
  3882. break;
  3883. case OpCopyMemory:
  3884. if (length < 2)
  3885. return false;
  3886. add_if_builtin(args[0]);
  3887. add_if_builtin(args[1]);
  3888. break;
  3889. case OpCopyObject:
  3890. case OpLoad:
  3891. case OpCooperativeMatrixLoadKHR:
  3892. if (length < 3)
  3893. return false;
  3894. add_if_builtin(args[2]);
  3895. break;
  3896. case OpSelect:
  3897. if (length < 5)
  3898. return false;
  3899. add_if_builtin(args[3]);
  3900. add_if_builtin(args[4]);
  3901. break;
  3902. case OpPhi:
  3903. {
  3904. if (length < 2)
  3905. return false;
  3906. uint32_t count = length - 2;
  3907. args += 2;
  3908. for (uint32_t i = 0; i < count; i += 2)
  3909. add_if_builtin(args[i]);
  3910. break;
  3911. }
  3912. case OpFunctionCall:
  3913. {
  3914. if (length < 3)
  3915. return false;
  3916. uint32_t count = length - 3;
  3917. args += 3;
  3918. for (uint32_t i = 0; i < count; i++)
  3919. add_if_builtin(args[i]);
  3920. break;
  3921. }
  3922. case OpAccessChain:
  3923. case OpInBoundsAccessChain:
  3924. case OpPtrAccessChain:
  3925. {
  3926. if (length < 4)
  3927. return false;
  3928. // Only consider global variables, cannot consider variables in functions yet, or other
  3929. // access chains as they have not been created yet.
  3930. auto *var = compiler.maybe_get<SPIRVariable>(args[2]);
  3931. if (!var)
  3932. break;
  3933. // Required if we access chain into builtins like gl_GlobalInvocationID.
  3934. add_if_builtin(args[2]);
  3935. // Start traversing type hierarchy at the proper non-pointer types.
  3936. auto *type = &compiler.get_variable_data_type(*var);
  3937. auto &flags =
  3938. var->storage == StorageClassInput ? compiler.active_input_builtins : compiler.active_output_builtins;
  3939. uint32_t count = length - 3;
  3940. args += 3;
  3941. for (uint32_t i = 0; i < count; i++)
  3942. {
  3943. // Pointers
  3944. // PtrAccessChain functions more like a pointer offset. Type remains the same.
  3945. if (opcode == OpPtrAccessChain && i == 0)
  3946. continue;
  3947. // Arrays
  3948. if (!type->array.empty())
  3949. {
  3950. type = &compiler.get<SPIRType>(type->parent_type);
  3951. }
  3952. // Structs
  3953. else if (type->basetype == SPIRType::Struct)
  3954. {
  3955. uint32_t index = compiler.get<SPIRConstant>(args[i]).scalar();
  3956. if (index < uint32_t(compiler.ir.meta[type->self].members.size()))
  3957. {
  3958. auto &decorations = compiler.ir.meta[type->self].members[index];
  3959. if (decorations.builtin)
  3960. {
  3961. flags.set(decorations.builtin_type);
  3962. handle_builtin(compiler.get<SPIRType>(type->member_types[index]), decorations.builtin_type,
  3963. decorations.decoration_flags);
  3964. }
  3965. }
  3966. type = &compiler.get<SPIRType>(type->member_types[index]);
  3967. }
  3968. else
  3969. {
  3970. // No point in traversing further. We won't find any extra builtins.
  3971. break;
  3972. }
  3973. }
  3974. break;
  3975. }
  3976. default:
  3977. break;
  3978. }
  3979. return true;
  3980. }
  3981. void Compiler::update_active_builtins()
  3982. {
  3983. active_input_builtins.reset();
  3984. active_output_builtins.reset();
  3985. cull_distance_count = 0;
  3986. clip_distance_count = 0;
  3987. ActiveBuiltinHandler handler(*this);
  3988. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  3989. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  3990. if (var.storage != StorageClassOutput)
  3991. return;
  3992. if (!interface_variable_exists_in_entry_point(var.self))
  3993. return;
  3994. // Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
  3995. if (var.initializer != ID(0))
  3996. handler.add_if_builtin_or_block(var.self);
  3997. });
  3998. }
  3999. // Returns whether this shader uses a builtin of the storage class
  4000. bool Compiler::has_active_builtin(BuiltIn builtin, StorageClass storage) const
  4001. {
  4002. const Bitset *flags;
  4003. switch (storage)
  4004. {
  4005. case StorageClassInput:
  4006. flags = &active_input_builtins;
  4007. break;
  4008. case StorageClassOutput:
  4009. flags = &active_output_builtins;
  4010. break;
  4011. default:
  4012. return false;
  4013. }
  4014. return flags->get(builtin);
  4015. }
  4016. void Compiler::analyze_image_and_sampler_usage()
  4017. {
  4018. CombinedImageSamplerDrefHandler dref_handler(*this);
  4019. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), dref_handler);
  4020. CombinedImageSamplerUsageHandler handler(*this, dref_handler.dref_combined_samplers);
  4021. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4022. // Need to run this traversal twice. First time, we propagate any comparison sampler usage from leaf functions
  4023. // down to main().
  4024. // In the second pass, we can propagate up forced depth state coming from main() up into leaf functions.
  4025. handler.dependency_hierarchy.clear();
  4026. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4027. comparison_ids = std::move(handler.comparison_ids);
  4028. need_subpass_input = handler.need_subpass_input;
  4029. need_subpass_input_ms = handler.need_subpass_input_ms;
  4030. // Forward information from separate images and samplers into combined image samplers.
  4031. for (auto &combined : combined_image_samplers)
  4032. if (comparison_ids.count(combined.sampler_id))
  4033. comparison_ids.insert(combined.combined_id);
  4034. }
  4035. bool Compiler::CombinedImageSamplerDrefHandler::handle(Op opcode, const uint32_t *args, uint32_t)
  4036. {
  4037. // Mark all sampled images which are used with Dref.
  4038. switch (opcode)
  4039. {
  4040. case OpImageSampleDrefExplicitLod:
  4041. case OpImageSampleDrefImplicitLod:
  4042. case OpImageSampleProjDrefExplicitLod:
  4043. case OpImageSampleProjDrefImplicitLod:
  4044. case OpImageSparseSampleProjDrefImplicitLod:
  4045. case OpImageSparseSampleDrefImplicitLod:
  4046. case OpImageSparseSampleProjDrefExplicitLod:
  4047. case OpImageSparseSampleDrefExplicitLod:
  4048. case OpImageDrefGather:
  4049. case OpImageSparseDrefGather:
  4050. dref_combined_samplers.insert(args[2]);
  4051. return true;
  4052. default:
  4053. break;
  4054. }
  4055. return true;
  4056. }
  4057. const CFG &Compiler::get_cfg_for_current_function() const
  4058. {
  4059. assert(current_function);
  4060. return get_cfg_for_function(current_function->self);
  4061. }
  4062. const CFG &Compiler::get_cfg_for_function(uint32_t id) const
  4063. {
  4064. auto cfg_itr = function_cfgs.find(id);
  4065. assert(cfg_itr != end(function_cfgs));
  4066. assert(cfg_itr->second);
  4067. return *cfg_itr->second;
  4068. }
  4069. void Compiler::build_function_control_flow_graphs_and_analyze()
  4070. {
  4071. CFGBuilder handler(*this);
  4072. handler.function_cfgs[ir.default_entry_point].reset(new CFG(*this, get<SPIRFunction>(ir.default_entry_point)));
  4073. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4074. function_cfgs = std::move(handler.function_cfgs);
  4075. bool single_function = function_cfgs.size() <= 1;
  4076. for (auto &f : function_cfgs)
  4077. {
  4078. auto &func = get<SPIRFunction>(f.first);
  4079. AnalyzeVariableScopeAccessHandler scope_handler(*this, func);
  4080. analyze_variable_scope(func, scope_handler);
  4081. find_function_local_luts(func, scope_handler, single_function);
  4082. // Check if we can actually use the loop variables we found in analyze_variable_scope.
  4083. // To use multiple initializers, we need the same type and qualifiers.
  4084. for (auto block : func.blocks)
  4085. {
  4086. auto &b = get<SPIRBlock>(block);
  4087. if (b.loop_variables.size() < 2)
  4088. continue;
  4089. auto &flags = get_decoration_bitset(b.loop_variables.front());
  4090. uint32_t type = get<SPIRVariable>(b.loop_variables.front()).basetype;
  4091. bool invalid_initializers = false;
  4092. for (auto loop_variable : b.loop_variables)
  4093. {
  4094. if (flags != get_decoration_bitset(loop_variable) ||
  4095. type != get<SPIRVariable>(b.loop_variables.front()).basetype)
  4096. {
  4097. invalid_initializers = true;
  4098. break;
  4099. }
  4100. }
  4101. if (invalid_initializers)
  4102. {
  4103. for (auto loop_variable : b.loop_variables)
  4104. get<SPIRVariable>(loop_variable).loop_variable = false;
  4105. b.loop_variables.clear();
  4106. }
  4107. }
  4108. }
  4109. // Find LUTs which are not function local. Only consider this case if the CFG is multi-function,
  4110. // otherwise we treat Private as Function trivially.
  4111. // Needs to be analyzed from the outside since we have to block the LUT optimization if at least
  4112. // one function writes to it.
  4113. if (!single_function)
  4114. {
  4115. for (auto &id : global_variables)
  4116. {
  4117. auto &var = get<SPIRVariable>(id);
  4118. auto &type = get_variable_data_type(var);
  4119. if (is_array(type) && var.storage == StorageClassPrivate &&
  4120. var.initializer && !var.is_written_to &&
  4121. ir.ids[var.initializer].get_type() == TypeConstant)
  4122. {
  4123. get<SPIRConstant>(var.initializer).is_used_as_lut = true;
  4124. var.static_expression = var.initializer;
  4125. var.statically_assigned = true;
  4126. var.remapped_variable = true;
  4127. }
  4128. }
  4129. }
  4130. }
  4131. Compiler::CFGBuilder::CFGBuilder(Compiler &compiler_)
  4132. : OpcodeHandler(compiler_)
  4133. {
  4134. }
  4135. bool Compiler::CFGBuilder::handle(Op, const uint32_t *, uint32_t)
  4136. {
  4137. return true;
  4138. }
  4139. bool Compiler::CFGBuilder::follow_function_call(const SPIRFunction &func)
  4140. {
  4141. if (function_cfgs.find(func.self) == end(function_cfgs))
  4142. {
  4143. function_cfgs[func.self].reset(new CFG(compiler, func));
  4144. return true;
  4145. }
  4146. else
  4147. return false;
  4148. }
  4149. void Compiler::CombinedImageSamplerUsageHandler::add_dependency(uint32_t dst, uint32_t src)
  4150. {
  4151. dependency_hierarchy[dst].insert(src);
  4152. // Propagate up any comparison state if we're loading from one such variable.
  4153. if (comparison_ids.count(src))
  4154. comparison_ids.insert(dst);
  4155. }
  4156. bool Compiler::CombinedImageSamplerUsageHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  4157. {
  4158. if (length < 3)
  4159. return false;
  4160. auto &func = compiler.get<SPIRFunction>(args[2]);
  4161. const auto *arg = &args[3];
  4162. length -= 3;
  4163. for (uint32_t i = 0; i < length; i++)
  4164. {
  4165. auto &argument = func.arguments[i];
  4166. add_dependency(argument.id, arg[i]);
  4167. }
  4168. return true;
  4169. }
  4170. void Compiler::CombinedImageSamplerUsageHandler::add_hierarchy_to_comparison_ids(uint32_t id)
  4171. {
  4172. // Traverse the variable dependency hierarchy and tag everything in its path with comparison ids.
  4173. comparison_ids.insert(id);
  4174. for (auto &dep_id : dependency_hierarchy[id])
  4175. add_hierarchy_to_comparison_ids(dep_id);
  4176. }
  4177. bool Compiler::CombinedImageSamplerUsageHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  4178. {
  4179. switch (opcode)
  4180. {
  4181. case OpAccessChain:
  4182. case OpInBoundsAccessChain:
  4183. case OpPtrAccessChain:
  4184. case OpLoad:
  4185. {
  4186. if (length < 3)
  4187. return false;
  4188. add_dependency(args[1], args[2]);
  4189. // Ideally defer this to OpImageRead, but then we'd need to track loaded IDs.
  4190. // If we load an image, we're going to use it and there is little harm in declaring an unused gl_FragCoord.
  4191. auto &type = compiler.get<SPIRType>(args[0]);
  4192. if (type.image.dim == DimSubpassData)
  4193. {
  4194. need_subpass_input = true;
  4195. if (type.image.ms)
  4196. need_subpass_input_ms = true;
  4197. }
  4198. // If we load a SampledImage and it will be used with Dref, propagate the state up.
  4199. if (dref_combined_samplers.count(args[1]) != 0)
  4200. add_hierarchy_to_comparison_ids(args[1]);
  4201. break;
  4202. }
  4203. case OpSampledImage:
  4204. {
  4205. if (length < 4)
  4206. return false;
  4207. // If the underlying resource has been used for comparison then duplicate loads of that resource must be too.
  4208. // This image must be a depth image.
  4209. uint32_t result_id = args[1];
  4210. uint32_t image = args[2];
  4211. uint32_t sampler = args[3];
  4212. if (dref_combined_samplers.count(result_id) != 0)
  4213. {
  4214. add_hierarchy_to_comparison_ids(image);
  4215. // This sampler must be a SamplerComparisonState, and not a regular SamplerState.
  4216. add_hierarchy_to_comparison_ids(sampler);
  4217. // Mark the OpSampledImage itself as being comparison state.
  4218. comparison_ids.insert(result_id);
  4219. }
  4220. return true;
  4221. }
  4222. default:
  4223. break;
  4224. }
  4225. return true;
  4226. }
  4227. bool Compiler::buffer_is_hlsl_counter_buffer(VariableID id) const
  4228. {
  4229. auto *m = ir.find_meta(id);
  4230. return m && m->hlsl_is_magic_counter_buffer;
  4231. }
  4232. bool Compiler::buffer_get_hlsl_counter_buffer(VariableID id, uint32_t &counter_id) const
  4233. {
  4234. auto *m = ir.find_meta(id);
  4235. // First, check for the proper decoration.
  4236. if (m && m->hlsl_magic_counter_buffer != 0)
  4237. {
  4238. counter_id = m->hlsl_magic_counter_buffer;
  4239. return true;
  4240. }
  4241. else
  4242. return false;
  4243. }
  4244. void Compiler::make_constant_null(uint32_t id, uint32_t type)
  4245. {
  4246. auto &constant_type = get<SPIRType>(type);
  4247. if (constant_type.pointer)
  4248. {
  4249. auto &constant = set<SPIRConstant>(id, type);
  4250. constant.make_null(constant_type);
  4251. }
  4252. else if (!constant_type.array.empty())
  4253. {
  4254. assert(constant_type.parent_type);
  4255. uint32_t parent_id = ir.increase_bound_by(1);
  4256. make_constant_null(parent_id, constant_type.parent_type);
  4257. // The array size of OpConstantNull can be either literal or specialization constant.
  4258. // In the latter case, we cannot take the value as-is, as it can be changed to anything.
  4259. // Rather, we assume it to be *one* for the sake of initializer.
  4260. bool is_literal_array_size = constant_type.array_size_literal.back();
  4261. uint32_t count = is_literal_array_size ? constant_type.array.back() : 1;
  4262. SmallVector<uint32_t> elements(count);
  4263. for (uint32_t i = 0; i < count; i++)
  4264. elements[i] = parent_id;
  4265. auto &constant = set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
  4266. constant.is_null_array_specialized_length = !is_literal_array_size;
  4267. }
  4268. else if (!constant_type.member_types.empty())
  4269. {
  4270. uint32_t member_ids = ir.increase_bound_by(uint32_t(constant_type.member_types.size()));
  4271. SmallVector<uint32_t> elements(constant_type.member_types.size());
  4272. for (uint32_t i = 0; i < constant_type.member_types.size(); i++)
  4273. {
  4274. make_constant_null(member_ids + i, constant_type.member_types[i]);
  4275. elements[i] = member_ids + i;
  4276. }
  4277. set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
  4278. }
  4279. else
  4280. {
  4281. auto &constant = set<SPIRConstant>(id, type);
  4282. constant.make_null(constant_type);
  4283. }
  4284. }
  4285. const SmallVector<Capability> &Compiler::get_declared_capabilities() const
  4286. {
  4287. return ir.declared_capabilities;
  4288. }
  4289. const SmallVector<std::string> &Compiler::get_declared_extensions() const
  4290. {
  4291. return ir.declared_extensions;
  4292. }
  4293. std::string Compiler::get_remapped_declared_block_name(VariableID id) const
  4294. {
  4295. return get_remapped_declared_block_name(id, false);
  4296. }
  4297. std::string Compiler::get_remapped_declared_block_name(uint32_t id, bool fallback_prefer_instance_name) const
  4298. {
  4299. auto itr = declared_block_names.find(id);
  4300. if (itr != end(declared_block_names))
  4301. {
  4302. return itr->second;
  4303. }
  4304. else
  4305. {
  4306. auto &var = get<SPIRVariable>(id);
  4307. if (fallback_prefer_instance_name)
  4308. {
  4309. return to_name(var.self);
  4310. }
  4311. else
  4312. {
  4313. auto &type = get<SPIRType>(var.basetype);
  4314. auto *type_meta = ir.find_meta(type.self);
  4315. auto *block_name = type_meta ? &type_meta->decoration.alias : nullptr;
  4316. return (!block_name || block_name->empty()) ? get_block_fallback_name(id) : *block_name;
  4317. }
  4318. }
  4319. }
  4320. bool Compiler::reflection_ssbo_instance_name_is_significant() const
  4321. {
  4322. if (ir.source.known)
  4323. {
  4324. // UAVs from HLSL source tend to be declared in a way where the type is reused
  4325. // but the instance name is significant, and that's the name we should report.
  4326. // For GLSL, SSBOs each have their own block type as that's how GLSL is written.
  4327. return ir.source.hlsl;
  4328. }
  4329. unordered_set<uint32_t> ssbo_type_ids;
  4330. bool aliased_ssbo_types = false;
  4331. // If we don't have any OpSource information, we need to perform some shaky heuristics.
  4332. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  4333. auto &type = this->get<SPIRType>(var.basetype);
  4334. if (!type.pointer || var.storage == StorageClassFunction)
  4335. return;
  4336. bool ssbo = var.storage == StorageClassStorageBuffer ||
  4337. (var.storage == StorageClassUniform && has_decoration(type.self, DecorationBufferBlock));
  4338. if (ssbo)
  4339. {
  4340. if (ssbo_type_ids.count(type.self))
  4341. aliased_ssbo_types = true;
  4342. else
  4343. ssbo_type_ids.insert(type.self);
  4344. }
  4345. });
  4346. // If the block name is aliased, assume we have HLSL-style UAV declarations.
  4347. return aliased_ssbo_types;
  4348. }
  4349. bool Compiler::instruction_to_result_type(uint32_t &result_type, uint32_t &result_id, Op op,
  4350. const uint32_t *args, uint32_t length)
  4351. {
  4352. if (length < 2)
  4353. return false;
  4354. bool has_result_id = false, has_result_type = false;
  4355. HasResultAndType(op, &has_result_id, &has_result_type);
  4356. if (has_result_id && has_result_type)
  4357. {
  4358. result_type = args[0];
  4359. result_id = args[1];
  4360. return true;
  4361. }
  4362. else
  4363. return false;
  4364. }
  4365. Bitset Compiler::combined_decoration_for_member(const SPIRType &type, uint32_t index) const
  4366. {
  4367. Bitset flags;
  4368. auto *type_meta = ir.find_meta(type.self);
  4369. if (type_meta)
  4370. {
  4371. auto &members = type_meta->members;
  4372. if (index >= members.size())
  4373. return flags;
  4374. auto &dec = members[index];
  4375. flags.merge_or(dec.decoration_flags);
  4376. auto &member_type = get<SPIRType>(type.member_types[index]);
  4377. // If our member type is a struct, traverse all the child members as well recursively.
  4378. auto &member_childs = member_type.member_types;
  4379. for (uint32_t i = 0; i < member_childs.size(); i++)
  4380. {
  4381. auto &child_member_type = get<SPIRType>(member_childs[i]);
  4382. if (!child_member_type.pointer)
  4383. flags.merge_or(combined_decoration_for_member(member_type, i));
  4384. }
  4385. }
  4386. return flags;
  4387. }
  4388. bool Compiler::is_desktop_only_format(ImageFormat format)
  4389. {
  4390. switch (format)
  4391. {
  4392. // Desktop-only formats
  4393. case ImageFormatR11fG11fB10f:
  4394. case ImageFormatR16f:
  4395. case ImageFormatRgb10A2:
  4396. case ImageFormatR8:
  4397. case ImageFormatRg8:
  4398. case ImageFormatR16:
  4399. case ImageFormatRg16:
  4400. case ImageFormatRgba16:
  4401. case ImageFormatR16Snorm:
  4402. case ImageFormatRg16Snorm:
  4403. case ImageFormatRgba16Snorm:
  4404. case ImageFormatR8Snorm:
  4405. case ImageFormatRg8Snorm:
  4406. case ImageFormatR8ui:
  4407. case ImageFormatRg8ui:
  4408. case ImageFormatR16ui:
  4409. case ImageFormatRgb10a2ui:
  4410. case ImageFormatR8i:
  4411. case ImageFormatRg8i:
  4412. case ImageFormatR16i:
  4413. return true;
  4414. default:
  4415. break;
  4416. }
  4417. return false;
  4418. }
  4419. // An image is determined to be a depth image if it is marked as a depth image and is not also
  4420. // explicitly marked with a color format, or if there are any sample/gather compare operations on it.
  4421. bool Compiler::is_depth_image(const SPIRType &type, uint32_t id) const
  4422. {
  4423. return (type.image.depth && type.image.format == ImageFormatUnknown) || comparison_ids.count(id);
  4424. }
  4425. bool Compiler::type_is_opaque_value(const SPIRType &type) const
  4426. {
  4427. return !type.pointer && (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Image ||
  4428. type.basetype == SPIRType::Sampler || type.basetype == SPIRType::Tensor);
  4429. }
  4430. // Make these member functions so we can easily break on any force_recompile events.
  4431. void Compiler::force_recompile()
  4432. {
  4433. is_force_recompile = true;
  4434. }
  4435. void Compiler::force_recompile_guarantee_forward_progress()
  4436. {
  4437. force_recompile();
  4438. is_force_recompile_forward_progress = true;
  4439. }
  4440. bool Compiler::is_forcing_recompilation() const
  4441. {
  4442. return is_force_recompile;
  4443. }
  4444. void Compiler::clear_force_recompile()
  4445. {
  4446. is_force_recompile = false;
  4447. is_force_recompile_forward_progress = false;
  4448. }
  4449. Compiler::PhysicalStorageBufferPointerHandler::PhysicalStorageBufferPointerHandler(Compiler &compiler_)
  4450. : OpcodeHandler(compiler_)
  4451. {
  4452. }
  4453. Compiler::PhysicalBlockMeta *Compiler::PhysicalStorageBufferPointerHandler::find_block_meta(uint32_t id) const
  4454. {
  4455. auto chain_itr = access_chain_to_physical_block.find(id);
  4456. if (chain_itr != access_chain_to_physical_block.end())
  4457. return chain_itr->second;
  4458. else
  4459. return nullptr;
  4460. }
  4461. void Compiler::PhysicalStorageBufferPointerHandler::mark_aligned_access(uint32_t id, const uint32_t *args, uint32_t length)
  4462. {
  4463. uint32_t mask = *args;
  4464. args++;
  4465. length--;
  4466. if (length && (mask & MemoryAccessVolatileMask) != 0)
  4467. {
  4468. args++;
  4469. length--;
  4470. }
  4471. if (length && (mask & MemoryAccessAlignedMask) != 0)
  4472. {
  4473. uint32_t alignment = *args;
  4474. auto *meta = find_block_meta(id);
  4475. // This makes the assumption that the application does not rely on insane edge cases like:
  4476. // Bind buffer with ADDR = 8, use block offset of 8 bytes, load/store with 16 byte alignment.
  4477. // If we emit the buffer with alignment = 16 here, the first element at offset = 0 should
  4478. // actually have alignment of 8 bytes, but this is too theoretical and awkward to support.
  4479. // We could potentially keep track of any offset in the access chain, but it's
  4480. // practically impossible for high level compilers to emit code like that,
  4481. // so deducing overall alignment requirement based on maximum observed Alignment value is probably fine.
  4482. if (meta && alignment > meta->alignment)
  4483. meta->alignment = alignment;
  4484. }
  4485. }
  4486. bool Compiler::PhysicalStorageBufferPointerHandler::type_is_bda_block_entry(uint32_t type_id) const
  4487. {
  4488. auto &type = compiler.get<SPIRType>(type_id);
  4489. return compiler.is_physical_pointer(type);
  4490. }
  4491. uint32_t Compiler::PhysicalStorageBufferPointerHandler::get_minimum_scalar_alignment(const SPIRType &type) const
  4492. {
  4493. if (type.storage == StorageClassPhysicalStorageBuffer)
  4494. return 8;
  4495. else if (type.basetype == SPIRType::Struct)
  4496. {
  4497. uint32_t alignment = 0;
  4498. for (auto &member_type : type.member_types)
  4499. {
  4500. uint32_t member_align = get_minimum_scalar_alignment(compiler.get<SPIRType>(member_type));
  4501. if (member_align > alignment)
  4502. alignment = member_align;
  4503. }
  4504. return alignment;
  4505. }
  4506. else
  4507. return type.width / 8;
  4508. }
  4509. void Compiler::PhysicalStorageBufferPointerHandler::setup_meta_chain(uint32_t type_id, uint32_t var_id)
  4510. {
  4511. if (type_is_bda_block_entry(type_id))
  4512. {
  4513. auto &meta = physical_block_type_meta[type_id];
  4514. access_chain_to_physical_block[var_id] = &meta;
  4515. auto &type = compiler.get<SPIRType>(type_id);
  4516. if (!compiler.is_physical_pointer_to_buffer_block(type))
  4517. non_block_types.insert(type_id);
  4518. if (meta.alignment == 0)
  4519. meta.alignment = get_minimum_scalar_alignment(compiler.get_pointee_type(type));
  4520. }
  4521. }
  4522. bool Compiler::PhysicalStorageBufferPointerHandler::handle(Op op, const uint32_t *args, uint32_t length)
  4523. {
  4524. // When a BDA pointer comes to life, we need to keep a mapping of SSA ID -> type ID for the pointer type.
  4525. // For every load and store, we'll need to be able to look up the type ID being accessed and mark any alignment
  4526. // requirements.
  4527. switch (op)
  4528. {
  4529. case OpConvertUToPtr:
  4530. case OpBitcast:
  4531. case OpCompositeExtract:
  4532. // Extract can begin a new chain if we had a struct or array of pointers as input.
  4533. // We don't begin chains before we have a pure scalar pointer.
  4534. setup_meta_chain(args[0], args[1]);
  4535. break;
  4536. case OpAccessChain:
  4537. case OpInBoundsAccessChain:
  4538. case OpPtrAccessChain:
  4539. case OpCopyObject:
  4540. {
  4541. auto itr = access_chain_to_physical_block.find(args[2]);
  4542. if (itr != access_chain_to_physical_block.end())
  4543. access_chain_to_physical_block[args[1]] = itr->second;
  4544. break;
  4545. }
  4546. case OpLoad:
  4547. {
  4548. setup_meta_chain(args[0], args[1]);
  4549. if (length >= 4)
  4550. mark_aligned_access(args[2], args + 3, length - 3);
  4551. break;
  4552. }
  4553. case OpStore:
  4554. {
  4555. if (length >= 3)
  4556. mark_aligned_access(args[0], args + 2, length - 2);
  4557. break;
  4558. }
  4559. case OpCooperativeMatrixLoadKHR:
  4560. case OpCooperativeMatrixStoreKHR:
  4561. {
  4562. // TODO: Can we meaningfully deal with this?
  4563. break;
  4564. }
  4565. default:
  4566. break;
  4567. }
  4568. return true;
  4569. }
  4570. uint32_t Compiler::PhysicalStorageBufferPointerHandler::get_base_non_block_type_id(uint32_t type_id) const
  4571. {
  4572. auto *type = &compiler.get<SPIRType>(type_id);
  4573. while (compiler.is_physical_pointer(*type) && !type_is_bda_block_entry(type_id))
  4574. {
  4575. type_id = type->parent_type;
  4576. type = &compiler.get<SPIRType>(type_id);
  4577. }
  4578. assert(type_is_bda_block_entry(type_id));
  4579. return type_id;
  4580. }
  4581. void Compiler::PhysicalStorageBufferPointerHandler::analyze_non_block_types_from_block(const SPIRType &type)
  4582. {
  4583. if (analyzed_type_ids.count(type.self))
  4584. return;
  4585. analyzed_type_ids.insert(type.self);
  4586. for (auto &member : type.member_types)
  4587. {
  4588. auto &subtype = compiler.get<SPIRType>(member);
  4589. if (compiler.is_physical_pointer(subtype) && !compiler.is_physical_pointer_to_buffer_block(subtype))
  4590. non_block_types.insert(get_base_non_block_type_id(member));
  4591. else if (subtype.basetype == SPIRType::Struct && !compiler.is_pointer(subtype))
  4592. analyze_non_block_types_from_block(subtype);
  4593. }
  4594. }
  4595. void Compiler::analyze_non_block_pointer_types()
  4596. {
  4597. PhysicalStorageBufferPointerHandler handler(*this);
  4598. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4599. // Analyze any block declaration we have to make. It might contain
  4600. // physical pointers to POD types which we never used, and thus never added to the list.
  4601. // We'll need to add those pointer types to the set of types we declare.
  4602. ir.for_each_typed_id<SPIRType>([&](uint32_t id, SPIRType &type) {
  4603. // Only analyze the raw block struct, not any pointer-to-struct, since that's just redundant.
  4604. if (type.self == id &&
  4605. (has_decoration(type.self, DecorationBlock) ||
  4606. has_decoration(type.self, DecorationBufferBlock)))
  4607. {
  4608. handler.analyze_non_block_types_from_block(type);
  4609. }
  4610. });
  4611. physical_storage_non_block_pointer_types.reserve(handler.non_block_types.size());
  4612. for (auto type : handler.non_block_types)
  4613. physical_storage_non_block_pointer_types.push_back(type);
  4614. sort(begin(physical_storage_non_block_pointer_types), end(physical_storage_non_block_pointer_types));
  4615. physical_storage_type_to_alignment = std::move(handler.physical_block_type_meta);
  4616. }
  4617. bool Compiler::InterlockedResourceAccessPrepassHandler::handle(Op op, const uint32_t *, uint32_t)
  4618. {
  4619. if (op == OpBeginInvocationInterlockEXT || op == OpEndInvocationInterlockEXT)
  4620. {
  4621. if (interlock_function_id != 0 && interlock_function_id != call_stack.back())
  4622. {
  4623. // Most complex case, we have no sensible way of dealing with this
  4624. // other than taking the 100% conservative approach, exit early.
  4625. split_function_case = true;
  4626. return false;
  4627. }
  4628. else
  4629. {
  4630. interlock_function_id = call_stack.back();
  4631. // If this call is performed inside control flow we have a problem.
  4632. auto &cfg = compiler.get_cfg_for_function(interlock_function_id);
  4633. uint32_t from_block_id = compiler.get<SPIRFunction>(interlock_function_id).entry_block;
  4634. bool outside_control_flow = cfg.node_terminates_control_flow_in_sub_graph(from_block_id, current_block_id);
  4635. if (!outside_control_flow)
  4636. control_flow_interlock = true;
  4637. }
  4638. }
  4639. return true;
  4640. }
  4641. void Compiler::InterlockedResourceAccessPrepassHandler::rearm_current_block(const SPIRBlock &block)
  4642. {
  4643. current_block_id = block.self;
  4644. }
  4645. bool Compiler::InterlockedResourceAccessPrepassHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  4646. {
  4647. if (length < 3)
  4648. return false;
  4649. call_stack.push_back(args[2]);
  4650. return true;
  4651. }
  4652. bool Compiler::InterlockedResourceAccessPrepassHandler::end_function_scope(const uint32_t *, uint32_t)
  4653. {
  4654. call_stack.pop_back();
  4655. return true;
  4656. }
  4657. bool Compiler::InterlockedResourceAccessHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  4658. {
  4659. if (length < 3)
  4660. return false;
  4661. if (args[2] == interlock_function_id)
  4662. call_stack_is_interlocked = true;
  4663. call_stack.push_back(args[2]);
  4664. return true;
  4665. }
  4666. bool Compiler::InterlockedResourceAccessHandler::end_function_scope(const uint32_t *, uint32_t)
  4667. {
  4668. if (call_stack.back() == interlock_function_id)
  4669. call_stack_is_interlocked = false;
  4670. call_stack.pop_back();
  4671. return true;
  4672. }
  4673. void Compiler::InterlockedResourceAccessHandler::access_potential_resource(uint32_t id)
  4674. {
  4675. if ((use_critical_section && in_crit_sec) || (control_flow_interlock && call_stack_is_interlocked) ||
  4676. split_function_case)
  4677. {
  4678. compiler.interlocked_resources.insert(id);
  4679. }
  4680. }
  4681. bool Compiler::InterlockedResourceAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  4682. {
  4683. // Only care about critical section analysis if we have simple case.
  4684. if (use_critical_section)
  4685. {
  4686. if (opcode == OpBeginInvocationInterlockEXT)
  4687. {
  4688. in_crit_sec = true;
  4689. return true;
  4690. }
  4691. if (opcode == OpEndInvocationInterlockEXT)
  4692. {
  4693. // End critical section--nothing more to do.
  4694. return false;
  4695. }
  4696. }
  4697. // We need to figure out where images and buffers are loaded from, so do only the bare bones compilation we need.
  4698. switch (opcode)
  4699. {
  4700. case OpLoad:
  4701. case OpCooperativeMatrixLoadKHR:
  4702. case OpCooperativeVectorLoadNV:
  4703. {
  4704. if (length < 3)
  4705. return false;
  4706. uint32_t ptr = args[2];
  4707. auto *var = compiler.maybe_get_backing_variable(ptr);
  4708. // We're only concerned with buffer and image memory here.
  4709. if (!var)
  4710. break;
  4711. switch (var->storage)
  4712. {
  4713. default:
  4714. break;
  4715. case StorageClassUniformConstant:
  4716. {
  4717. uint32_t result_type = args[0];
  4718. uint32_t id = args[1];
  4719. compiler.set<SPIRExpression>(id, "", result_type, true);
  4720. compiler.register_read(id, ptr, true);
  4721. break;
  4722. }
  4723. case StorageClassUniform:
  4724. // Must have BufferBlock; we only care about SSBOs.
  4725. if (!compiler.has_decoration(compiler.get<SPIRType>(var->basetype).self, DecorationBufferBlock))
  4726. break;
  4727. // fallthrough
  4728. case StorageClassStorageBuffer:
  4729. access_potential_resource(var->self);
  4730. break;
  4731. }
  4732. break;
  4733. }
  4734. case OpInBoundsAccessChain:
  4735. case OpAccessChain:
  4736. case OpPtrAccessChain:
  4737. {
  4738. if (length < 3)
  4739. return false;
  4740. uint32_t result_type = args[0];
  4741. auto &type = compiler.get<SPIRType>(result_type);
  4742. if (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant ||
  4743. type.storage == StorageClassStorageBuffer)
  4744. {
  4745. uint32_t id = args[1];
  4746. uint32_t ptr = args[2];
  4747. compiler.set<SPIRExpression>(id, "", result_type, true);
  4748. compiler.register_read(id, ptr, true);
  4749. compiler.ir.ids[id].set_allow_type_rewrite();
  4750. }
  4751. break;
  4752. }
  4753. case OpImageTexelPointer:
  4754. {
  4755. if (length < 3)
  4756. return false;
  4757. uint32_t result_type = args[0];
  4758. uint32_t id = args[1];
  4759. uint32_t ptr = args[2];
  4760. auto &e = compiler.set<SPIRExpression>(id, "", result_type, true);
  4761. auto *var = compiler.maybe_get_backing_variable(ptr);
  4762. if (var)
  4763. e.loaded_from = var->self;
  4764. break;
  4765. }
  4766. case OpStore:
  4767. case OpImageWrite:
  4768. case OpAtomicStore:
  4769. case OpCooperativeMatrixStoreKHR:
  4770. case OpCooperativeVectorStoreNV:
  4771. {
  4772. if (length < 1)
  4773. return false;
  4774. uint32_t ptr = args[0];
  4775. auto *var = compiler.maybe_get_backing_variable(ptr);
  4776. if (var && (var->storage == StorageClassUniform || var->storage == StorageClassUniformConstant ||
  4777. var->storage == StorageClassStorageBuffer))
  4778. {
  4779. access_potential_resource(var->self);
  4780. }
  4781. break;
  4782. }
  4783. case OpCopyMemory:
  4784. {
  4785. if (length < 2)
  4786. return false;
  4787. uint32_t dst = args[0];
  4788. uint32_t src = args[1];
  4789. auto *dst_var = compiler.maybe_get_backing_variable(dst);
  4790. auto *src_var = compiler.maybe_get_backing_variable(src);
  4791. if (dst_var && (dst_var->storage == StorageClassUniform || dst_var->storage == StorageClassStorageBuffer))
  4792. access_potential_resource(dst_var->self);
  4793. if (src_var)
  4794. {
  4795. if (src_var->storage != StorageClassUniform && src_var->storage != StorageClassStorageBuffer)
  4796. break;
  4797. if (src_var->storage == StorageClassUniform &&
  4798. !compiler.has_decoration(compiler.get<SPIRType>(src_var->basetype).self, DecorationBufferBlock))
  4799. {
  4800. break;
  4801. }
  4802. access_potential_resource(src_var->self);
  4803. }
  4804. break;
  4805. }
  4806. case OpImageRead:
  4807. case OpAtomicLoad:
  4808. {
  4809. if (length < 3)
  4810. return false;
  4811. uint32_t ptr = args[2];
  4812. auto *var = compiler.maybe_get_backing_variable(ptr);
  4813. // We're only concerned with buffer and image memory here.
  4814. if (!var)
  4815. break;
  4816. switch (var->storage)
  4817. {
  4818. default:
  4819. break;
  4820. case StorageClassUniform:
  4821. // Must have BufferBlock; we only care about SSBOs.
  4822. if (!compiler.has_decoration(compiler.get<SPIRType>(var->basetype).self, DecorationBufferBlock))
  4823. break;
  4824. // fallthrough
  4825. case StorageClassUniformConstant:
  4826. case StorageClassStorageBuffer:
  4827. access_potential_resource(var->self);
  4828. break;
  4829. }
  4830. break;
  4831. }
  4832. case OpAtomicExchange:
  4833. case OpAtomicCompareExchange:
  4834. case OpAtomicIIncrement:
  4835. case OpAtomicIDecrement:
  4836. case OpAtomicIAdd:
  4837. case OpAtomicISub:
  4838. case OpAtomicSMin:
  4839. case OpAtomicUMin:
  4840. case OpAtomicSMax:
  4841. case OpAtomicUMax:
  4842. case OpAtomicAnd:
  4843. case OpAtomicOr:
  4844. case OpAtomicXor:
  4845. {
  4846. if (length < 3)
  4847. return false;
  4848. uint32_t ptr = args[2];
  4849. auto *var = compiler.maybe_get_backing_variable(ptr);
  4850. if (var && (var->storage == StorageClassUniform || var->storage == StorageClassUniformConstant ||
  4851. var->storage == StorageClassStorageBuffer))
  4852. {
  4853. access_potential_resource(var->self);
  4854. }
  4855. break;
  4856. }
  4857. default:
  4858. break;
  4859. }
  4860. return true;
  4861. }
  4862. void Compiler::analyze_interlocked_resource_usage()
  4863. {
  4864. if (get_execution_model() == ExecutionModelFragment &&
  4865. (get_entry_point().flags.get(ExecutionModePixelInterlockOrderedEXT) ||
  4866. get_entry_point().flags.get(ExecutionModePixelInterlockUnorderedEXT) ||
  4867. get_entry_point().flags.get(ExecutionModeSampleInterlockOrderedEXT) ||
  4868. get_entry_point().flags.get(ExecutionModeSampleInterlockUnorderedEXT)))
  4869. {
  4870. InterlockedResourceAccessPrepassHandler prepass_handler(*this, ir.default_entry_point);
  4871. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), prepass_handler);
  4872. InterlockedResourceAccessHandler handler(*this, ir.default_entry_point);
  4873. handler.interlock_function_id = prepass_handler.interlock_function_id;
  4874. handler.split_function_case = prepass_handler.split_function_case;
  4875. handler.control_flow_interlock = prepass_handler.control_flow_interlock;
  4876. handler.use_critical_section = !handler.split_function_case && !handler.control_flow_interlock;
  4877. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4878. // For GLSL. If we hit any of these cases, we have to fall back to conservative approach.
  4879. interlocked_is_complex =
  4880. !handler.use_critical_section || handler.interlock_function_id != ir.default_entry_point;
  4881. }
  4882. }
  4883. // Helper function
  4884. bool Compiler::check_internal_recursion(const SPIRType &type, std::unordered_set<uint32_t> &checked_ids)
  4885. {
  4886. if (type.basetype != SPIRType::Struct)
  4887. return false;
  4888. if (checked_ids.count(type.self))
  4889. return true;
  4890. // Recurse into struct members
  4891. bool is_recursive = false;
  4892. checked_ids.insert(type.self);
  4893. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  4894. for (uint32_t mbr_idx = 0; !is_recursive && mbr_idx < mbr_cnt; mbr_idx++)
  4895. {
  4896. uint32_t mbr_type_id = type.member_types[mbr_idx];
  4897. auto &mbr_type = get<SPIRType>(mbr_type_id);
  4898. is_recursive |= check_internal_recursion(mbr_type, checked_ids);
  4899. }
  4900. checked_ids.erase(type.self);
  4901. return is_recursive;
  4902. }
  4903. // Return whether the struct type contains a structural recursion nested somewhere within its content.
  4904. bool Compiler::type_contains_recursion(const SPIRType &type)
  4905. {
  4906. std::unordered_set<uint32_t> checked_ids;
  4907. return check_internal_recursion(type, checked_ids);
  4908. }
  4909. bool Compiler::type_is_array_of_pointers(const SPIRType &type) const
  4910. {
  4911. if (!is_array(type))
  4912. return false;
  4913. // BDA types must have parent type hierarchy.
  4914. if (!type.parent_type)
  4915. return false;
  4916. // Punch through all array layers.
  4917. auto *parent = &get<SPIRType>(type.parent_type);
  4918. while (is_array(*parent))
  4919. parent = &get<SPIRType>(parent->parent_type);
  4920. return is_pointer(*parent);
  4921. }
  4922. bool Compiler::flush_phi_required(BlockID from, BlockID to) const
  4923. {
  4924. auto &child = get<SPIRBlock>(to);
  4925. for (auto &phi : child.phi_variables)
  4926. if (phi.parent == from)
  4927. return true;
  4928. return false;
  4929. }
  4930. void Compiler::add_loop_level()
  4931. {
  4932. current_loop_level++;
  4933. }
  4934. const SPIRType *Compiler::OpcodeHandler::get_expression_result_type(uint32_t id) const
  4935. {
  4936. auto itr = result_types.find(id);
  4937. if (itr == result_types.end())
  4938. return nullptr;
  4939. return &compiler.get<SPIRType>(itr->second);
  4940. }