spirv_cross.cpp 162 KB

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