hlslParseHelper.cpp 415 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965
  1. //
  2. // Copyright (C) 2017-2018 Google, Inc.
  3. // Copyright (C) 2017 LunarG, Inc.
  4. //
  5. // All rights reserved.
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions
  9. // are met:
  10. //
  11. // Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. //
  14. // Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following
  16. // disclaimer in the documentation and/or other materials provided
  17. // with the distribution.
  18. //
  19. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  20. // contributors may be used to endorse or promote products derived
  21. // from this software without specific prior written permission.
  22. //
  23. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  26. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  27. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  28. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  29. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  30. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  31. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  33. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. // POSSIBILITY OF SUCH DAMAGE.
  35. //
  36. #include "hlslParseHelper.h"
  37. #include "hlslScanContext.h"
  38. #include "hlslGrammar.h"
  39. #include "hlslAttributes.h"
  40. #include "../glslang/MachineIndependent/Scan.h"
  41. #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
  42. #include "../glslang/OSDependent/osinclude.h"
  43. #include <algorithm>
  44. #include <functional>
  45. #include <cctype>
  46. #include <array>
  47. #include <set>
  48. namespace glslang {
  49. HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
  50. int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
  51. TInfoSink& infoSink,
  52. const TString sourceEntryPointName,
  53. bool forwardCompatible, EShMessages messages) :
  54. TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
  55. forwardCompatible, messages, &sourceEntryPointName),
  56. annotationNestingLevel(0),
  57. inputPatch(nullptr),
  58. nextInLocation(0), nextOutLocation(0),
  59. entryPointFunction(nullptr),
  60. entryPointFunctionBody(nullptr),
  61. gsStreamOutput(nullptr),
  62. clipDistanceOutput(nullptr),
  63. cullDistanceOutput(nullptr),
  64. clipDistanceInput(nullptr),
  65. cullDistanceInput(nullptr)
  66. {
  67. globalUniformDefaults.clear();
  68. globalUniformDefaults.layoutMatrix = ElmRowMajor;
  69. globalUniformDefaults.layoutPacking = ElpStd140;
  70. globalBufferDefaults.clear();
  71. globalBufferDefaults.layoutMatrix = ElmRowMajor;
  72. globalBufferDefaults.layoutPacking = ElpStd430;
  73. globalInputDefaults.clear();
  74. globalOutputDefaults.clear();
  75. clipSemanticNSizeIn.fill(0);
  76. cullSemanticNSizeIn.fill(0);
  77. clipSemanticNSizeOut.fill(0);
  78. cullSemanticNSizeOut.fill(0);
  79. // "Shaders in the transform
  80. // feedback capturing mode have an initial global default of
  81. // layout(xfb_buffer = 0) out;"
  82. if (language == EShLangVertex ||
  83. language == EShLangTessControl ||
  84. language == EShLangTessEvaluation ||
  85. language == EShLangGeometry)
  86. globalOutputDefaults.layoutXfbBuffer = 0;
  87. if (language == EShLangGeometry)
  88. globalOutputDefaults.layoutStream = 0;
  89. }
  90. HlslParseContext::~HlslParseContext()
  91. {
  92. }
  93. void HlslParseContext::initializeExtensionBehavior()
  94. {
  95. TParseContextBase::initializeExtensionBehavior();
  96. // HLSL allows #line by default.
  97. extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
  98. }
  99. void HlslParseContext::setLimits(const TBuiltInResource& r)
  100. {
  101. resources = r;
  102. intermediate.setLimits(resources);
  103. }
  104. //
  105. // Parse an array of strings using the parser in HlslRules.
  106. //
  107. // Returns true for successful acceptance of the shader, false if any errors.
  108. //
  109. bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  110. {
  111. currentScanner = &input;
  112. ppContext.setInput(input, versionWillBeError);
  113. HlslScanContext scanContext(*this, ppContext);
  114. HlslGrammar grammar(scanContext, *this);
  115. if (!grammar.parse()) {
  116. // Print a message formated such that if you click on the message it will take you right to
  117. // the line through most UIs.
  118. const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
  119. infoSink.info << sourceLoc.name->c_str() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
  120. << ", HLSL parsing failed.\n";
  121. ++numErrors;
  122. return false;
  123. }
  124. finish();
  125. return numErrors == 0;
  126. }
  127. //
  128. // Return true if this l-value node should be converted in some manner.
  129. // For instance: turning a load aggregate into a store in an l-value.
  130. //
  131. bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
  132. {
  133. if (node == nullptr || node->getAsTyped() == nullptr)
  134. return false;
  135. const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  136. const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
  137. // If it's a swizzled/indexed aggregate, look at the left node instead.
  138. if (lhsAsBinary != nullptr &&
  139. (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
  140. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  141. if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
  142. return true;
  143. return false;
  144. }
  145. void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
  146. TTypeList* newTypeList)
  147. {
  148. newTypeList = nullptr;
  149. correctUniform(memberType.getQualifier());
  150. if (memberType.isStruct()) {
  151. auto it = ioTypeMap.find(memberType.getStruct());
  152. if (it != ioTypeMap.end() && it->second.uniform)
  153. newTypeList = it->second.uniform;
  154. }
  155. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
  156. }
  157. //
  158. // Return a TLayoutFormat corresponding to the given texture type.
  159. //
  160. TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
  161. {
  162. if (txType.isStruct()) {
  163. // TODO: implement.
  164. error(loc, "unimplemented: structure type in image or buffer", "", "");
  165. return ElfNone;
  166. }
  167. const int components = txType.getVectorSize();
  168. const TBasicType txBasicType = txType.getBasicType();
  169. const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
  170. if (intermediate.getNoStorageFormat())
  171. return ElfNone;
  172. return components == 1 ? v1 :
  173. components == 2 ? v2 : v4;
  174. };
  175. switch (txBasicType) {
  176. case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
  177. case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
  178. case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
  179. default:
  180. error(loc, "unknown basic type in image format", "", "");
  181. return ElfNone;
  182. }
  183. }
  184. //
  185. // Both test and if necessary, spit out an error, to see if the node is really
  186. // an l-value that can be operated on this way.
  187. //
  188. // Returns true if there was an error.
  189. //
  190. bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  191. {
  192. if (shouldConvertLValue(node)) {
  193. // if we're writing to a texture, it must be an RW form.
  194. TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  195. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  196. if (!object->getType().getSampler().isImage()) {
  197. error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
  198. return true;
  199. }
  200. }
  201. // We tolerate samplers as l-values, even though they are nominally
  202. // illegal, because we expect a later optimization to eliminate them.
  203. if (node->getType().getBasicType() == EbtSampler) {
  204. intermediate.setNeedsLegalization();
  205. return false;
  206. }
  207. // Let the base class check errors
  208. return TParseContextBase::lValueErrorCheck(loc, op, node);
  209. }
  210. //
  211. // This function handles l-value conversions and verifications. It uses, but is not synonymous
  212. // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
  213. // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
  214. // series of other image operations.
  215. //
  216. // Most things are passed through unmodified, except for error checking.
  217. //
  218. TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
  219. {
  220. if (node == nullptr)
  221. return nullptr;
  222. TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
  223. TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
  224. TIntermAggregate* sequence = nullptr;
  225. TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
  226. nodeAsBinary ? nodeAsBinary->getLeft() :
  227. nullptr;
  228. // Early bail out if there is no conversion to apply
  229. if (!shouldConvertLValue(lhs)) {
  230. if (lhs != nullptr)
  231. if (lValueErrorCheck(loc, op, lhs))
  232. return nullptr;
  233. return node;
  234. }
  235. // *** If we get here, we're going to apply some conversion to an l-value.
  236. // Helper to create a load.
  237. const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
  238. TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
  239. loadOp->setLoc(loc);
  240. loadOp->getSequence().push_back(object);
  241. loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
  242. loadOp->setType(derefType);
  243. sequence = intermediate.growAggregate(sequence,
  244. intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
  245. loc);
  246. };
  247. // Helper to create a store.
  248. const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
  249. TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
  250. storeOp->getSequence().push_back(object);
  251. storeOp->getSequence().push_back(coord);
  252. storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
  253. storeOp->setLoc(loc);
  254. storeOp->setType(TType(EbtVoid));
  255. sequence = intermediate.growAggregate(sequence, storeOp);
  256. };
  257. // Helper to create an assign.
  258. const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
  259. sequence = intermediate.growAggregate(sequence,
  260. intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
  261. loc);
  262. };
  263. // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
  264. const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
  265. // Add a trailing use of the temp, so the sequence returns the proper value.
  266. sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
  267. sequence->setOperator(EOpSequence);
  268. sequence->setLoc(loc);
  269. sequence->setType(derefType);
  270. return sequence;
  271. };
  272. // Helper to add unary op
  273. const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
  274. sequence = intermediate.growAggregate(sequence,
  275. intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
  276. rhsTmp->getType()),
  277. loc);
  278. };
  279. // Return true if swizzle or index writes all components of the given variable.
  280. const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
  281. if (swizzle == nullptr) // not a swizzle or index
  282. return true;
  283. // Track which components are being set.
  284. std::array<bool, 4> compIsSet;
  285. compIsSet.fill(false);
  286. const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
  287. const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
  288. // This could be either a direct index, or a swizzle.
  289. if (asConst) {
  290. compIsSet[asConst->getConstArray()[0].getIConst()] = true;
  291. } else if (asAggregate) {
  292. const TIntermSequence& seq = asAggregate->getSequence();
  293. for (int comp=0; comp<int(seq.size()); ++comp)
  294. compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
  295. } else {
  296. assert(0);
  297. }
  298. // Return true if all components are being set by the index or swizzle
  299. return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
  300. [](bool isSet) { return isSet; } );
  301. };
  302. // Create swizzle matching input swizzle
  303. const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
  304. if (swizzle)
  305. return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
  306. else
  307. return var;
  308. };
  309. TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
  310. TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
  311. bool lhsIsSwizzle = false;
  312. // If it's a swizzled L-value, remember the swizzle, and use the LHS.
  313. if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
  314. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  315. lhsIsSwizzle = true;
  316. }
  317. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  318. TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
  319. const TSampler& texSampler = object->getType().getSampler();
  320. TType objDerefType;
  321. getTextureReturnType(texSampler, objDerefType);
  322. if (nodeAsBinary) {
  323. TIntermTyped* rhs = nodeAsBinary->getRight();
  324. const TOperator assignOp = nodeAsBinary->getOp();
  325. bool isModifyOp = false;
  326. switch (assignOp) {
  327. case EOpAddAssign:
  328. case EOpSubAssign:
  329. case EOpMulAssign:
  330. case EOpVectorTimesMatrixAssign:
  331. case EOpVectorTimesScalarAssign:
  332. case EOpMatrixTimesScalarAssign:
  333. case EOpMatrixTimesMatrixAssign:
  334. case EOpDivAssign:
  335. case EOpModAssign:
  336. case EOpAndAssign:
  337. case EOpInclusiveOrAssign:
  338. case EOpExclusiveOrAssign:
  339. case EOpLeftShiftAssign:
  340. case EOpRightShiftAssign:
  341. isModifyOp = true;
  342. // fall through...
  343. case EOpAssign:
  344. {
  345. // Since this is an lvalue, we'll convert an image load to a sequence like this
  346. // (to still provide the value):
  347. // OpSequence
  348. // OpImageStore(object, lhs, rhs)
  349. // rhs
  350. // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
  351. // so we'll convert instead to this:
  352. // OpSequence
  353. // rhsTmp = rhs
  354. // OpImageStore(object, coord, rhsTmp)
  355. // rhsTmp
  356. // If this is a read-modify-write op, like +=, we issue:
  357. // OpSequence
  358. // coordtmp = load's param1
  359. // rhsTmp = OpImageLoad(object, coordTmp)
  360. // rhsTmp op= rhs
  361. // OpImageStore(object, coordTmp, rhsTmp)
  362. // rhsTmp
  363. //
  364. // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
  365. // ...
  366. // rhsTmp.some_swizzle = ...
  367. // For partial writes, an error is generated.
  368. TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
  369. TIntermTyped* coordTmp = coord;
  370. if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
  371. rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  372. // Partial updates not yet supported
  373. if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
  374. error(loc, "unimplemented: partial image updates", "", "");
  375. }
  376. // Assign storeTemp = rhs
  377. if (isModifyOp) {
  378. // We have to make a temp var for the coordinate, to avoid evaluating it twice.
  379. coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  380. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  381. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  382. }
  383. // rhsTmp op= rhs.
  384. makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
  385. }
  386. makeStore(object, coordTmp, rhsTmp); // add a store
  387. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  388. }
  389. default:
  390. break;
  391. }
  392. }
  393. if (nodeAsUnary) {
  394. const TOperator assignOp = nodeAsUnary->getOp();
  395. switch (assignOp) {
  396. case EOpPreIncrement:
  397. case EOpPreDecrement:
  398. {
  399. // We turn this into:
  400. // OpSequence
  401. // coordtmp = load's param1
  402. // rhsTmp = OpImageLoad(object, coordTmp)
  403. // rhsTmp op
  404. // OpImageStore(object, coordTmp, rhsTmp)
  405. // rhsTmp
  406. TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  407. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  408. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  409. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  410. makeUnary(assignOp, rhsTmp); // op rhsTmp
  411. makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
  412. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  413. }
  414. case EOpPostIncrement:
  415. case EOpPostDecrement:
  416. {
  417. // We turn this into:
  418. // OpSequence
  419. // coordtmp = load's param1
  420. // rhsTmp1 = OpImageLoad(object, coordTmp)
  421. // rhsTmp2 = rhsTmp1
  422. // rhsTmp2 op
  423. // OpImageStore(object, coordTmp, rhsTmp2)
  424. // rhsTmp1 (pre-op value)
  425. TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
  426. TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
  427. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  428. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  429. makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
  430. makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
  431. makeUnary(assignOp, rhsTmp2); // rhsTmp op
  432. makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
  433. return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
  434. }
  435. default:
  436. break;
  437. }
  438. }
  439. if (lhs)
  440. if (lValueErrorCheck(loc, op, lhs))
  441. return nullptr;
  442. return node;
  443. }
  444. void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  445. {
  446. if (pragmaCallback)
  447. pragmaCallback(loc.line, tokens);
  448. if (tokens.size() == 0)
  449. return;
  450. // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
  451. TVector<TString> lowerTokens = tokens;
  452. for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
  453. std::transform(it->begin(), it->end(), it->begin(), ::tolower);
  454. // Handle pack_matrix
  455. if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
  456. // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
  457. // Row major becomes column major and vice versa.
  458. if (lowerTokens[2] == "row_major") {
  459. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  460. } else if (lowerTokens[2] == "column_major") {
  461. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  462. } else {
  463. // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
  464. warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
  465. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  466. }
  467. return;
  468. }
  469. // Handle once
  470. if (lowerTokens[0] == "once") {
  471. warn(loc, "not implemented", "#pragma once", "");
  472. return;
  473. }
  474. }
  475. //
  476. // Look at a '.' matrix selector string and change it into components
  477. // for a matrix. There are two types:
  478. //
  479. // _21 second row, first column (one based)
  480. // _m21 third row, second column (zero based)
  481. //
  482. // Returns true if there is no error.
  483. //
  484. bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
  485. TSwizzleSelectors<TMatrixSelector>& components)
  486. {
  487. int startPos[MaxSwizzleSelectors];
  488. int numComps = 0;
  489. TString compString = fields;
  490. // Find where each component starts,
  491. // recording the first character position after the '_'.
  492. for (size_t c = 0; c < compString.size(); ++c) {
  493. if (compString[c] == '_') {
  494. if (numComps >= MaxSwizzleSelectors) {
  495. error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
  496. return false;
  497. }
  498. if (c > compString.size() - 3 ||
  499. ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
  500. error(loc, "matrix component swizzle missing", compString.c_str(), "");
  501. return false;
  502. }
  503. startPos[numComps++] = (int)c + 1;
  504. }
  505. }
  506. // Process each component
  507. for (int i = 0; i < numComps; ++i) {
  508. int pos = startPos[i];
  509. int bias = -1;
  510. if (compString[pos] == 'm' || compString[pos] == 'M') {
  511. bias = 0;
  512. ++pos;
  513. }
  514. TMatrixSelector comp;
  515. comp.coord1 = compString[pos+0] - '0' + bias;
  516. comp.coord2 = compString[pos+1] - '0' + bias;
  517. if (comp.coord1 < 0 || comp.coord1 >= cols) {
  518. error(loc, "matrix row component out of range", compString.c_str(), "");
  519. return false;
  520. }
  521. if (comp.coord2 < 0 || comp.coord2 >= rows) {
  522. error(loc, "matrix column component out of range", compString.c_str(), "");
  523. return false;
  524. }
  525. components.push_back(comp);
  526. }
  527. return true;
  528. }
  529. // If the 'comps' express a column of a matrix,
  530. // return the column. Column means the first coords all match.
  531. //
  532. // Otherwise, return -1.
  533. //
  534. int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
  535. {
  536. int col = -1;
  537. // right number of comps?
  538. if (selector.size() != rows)
  539. return -1;
  540. // all comps in the same column?
  541. // rows in order?
  542. col = selector[0].coord1;
  543. for (int i = 0; i < rows; ++i) {
  544. if (col != selector[i].coord1)
  545. return -1;
  546. if (i != selector[i].coord2)
  547. return -1;
  548. }
  549. return col;
  550. }
  551. //
  552. // Handle seeing a variable identifier in the grammar.
  553. //
  554. TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
  555. {
  556. int thisDepth;
  557. TSymbol* symbol = symbolTable.find(*string, thisDepth);
  558. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  559. error(loc, "expected symbol, not user-defined type", string->c_str(), "");
  560. return nullptr;
  561. }
  562. const TVariable* variable = nullptr;
  563. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  564. TIntermTyped* node = nullptr;
  565. if (anon) {
  566. // It was a member of an anonymous container, which could be a 'this' structure.
  567. // Create a subtree for its dereference.
  568. if (thisDepth > 0) {
  569. variable = getImplicitThis(thisDepth);
  570. if (variable == nullptr)
  571. error(loc, "cannot access member variables (static member function?)", "this", "");
  572. }
  573. if (variable == nullptr)
  574. variable = anon->getAnonContainer().getAsVariable();
  575. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  576. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  577. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  578. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  579. if (node->getType().hiddenMember())
  580. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  581. } else {
  582. // Not a member of an anonymous container.
  583. // The symbol table search was done in the lexical phase.
  584. // See if it was a variable.
  585. variable = symbol ? symbol->getAsVariable() : nullptr;
  586. if (variable) {
  587. if ((variable->getType().getBasicType() == EbtBlock ||
  588. variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
  589. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  590. variable = nullptr;
  591. }
  592. } else {
  593. if (symbol)
  594. error(loc, "variable name expected", string->c_str(), "");
  595. }
  596. // Recovery, if it wasn't found or was not a variable.
  597. if (variable == nullptr) {
  598. error(loc, "unknown variable", string->c_str(), "");
  599. variable = new TVariable(string, TType(EbtVoid));
  600. }
  601. if (variable->getType().getQualifier().isFrontEndConstant())
  602. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  603. else
  604. node = intermediate.addSymbol(*variable, loc);
  605. }
  606. if (variable->getType().getQualifier().isIo())
  607. intermediate.addIoAccessed(*string);
  608. return node;
  609. }
  610. //
  611. // Handle operator[] on any objects it applies to. Currently:
  612. // Textures
  613. // Buffers
  614. //
  615. TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  616. {
  617. // handle r-value operator[] on textures and images. l-values will be processed later.
  618. if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
  619. const TSampler& sampler = base->getType().getSampler();
  620. if (sampler.isImage() || sampler.isTexture()) {
  621. if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
  622. // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
  623. mipsOperatorMipArg.back().mipLevel = index;
  624. return base; // next [] index is to the same base.
  625. } else {
  626. TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
  627. TType sampReturnType;
  628. getTextureReturnType(sampler, sampReturnType);
  629. load->setType(sampReturnType);
  630. load->setLoc(loc);
  631. load->getSequence().push_back(base);
  632. load->getSequence().push_back(index);
  633. // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
  634. if (sampler.isTexture()) {
  635. if (! mipsOperatorMipArg.empty()) {
  636. load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
  637. mipsOperatorMipArg.pop_back();
  638. } else {
  639. load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
  640. }
  641. }
  642. return load;
  643. }
  644. }
  645. }
  646. // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
  647. // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
  648. TIntermTyped* sbArray = indexStructBufferContent(loc, base);
  649. if (sbArray != nullptr) {
  650. if (sbArray == nullptr)
  651. return nullptr;
  652. // Now we'll apply the [] index to that array
  653. const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  654. TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
  655. const TType derefType(sbArray->getType(), 0);
  656. element->setType(derefType);
  657. return element;
  658. }
  659. return nullptr;
  660. }
  661. //
  662. // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
  663. TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
  664. {
  665. const TBasicType indexBasicType = index->getType().getBasicType();
  666. const int vecSize = index->getType().getVectorSize();
  667. // We can use int types directly as the index
  668. if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
  669. indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
  670. return index;
  671. // Cast index to unsigned integer if it isn't one.
  672. return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
  673. }
  674. //
  675. // Handle seeing a base[index] dereference in the grammar.
  676. //
  677. TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  678. {
  679. index = makeIntegerIndex(index);
  680. if (index == nullptr) {
  681. error(loc, " unknown index type ", "", "");
  682. return nullptr;
  683. }
  684. TIntermTyped* result = handleBracketOperator(loc, base, index);
  685. if (result != nullptr)
  686. return result; // it was handled as an operator[]
  687. bool flattened = false;
  688. int indexValue = 0;
  689. if (index->getQualifier().isFrontEndConstant())
  690. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  691. variableCheck(base);
  692. if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
  693. if (base->getAsSymbolNode())
  694. error(loc, " left of '[' is not of type array, matrix, or vector ",
  695. base->getAsSymbolNode()->getName().c_str(), "");
  696. else
  697. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  698. } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) {
  699. // both base and index are front-end constants
  700. checkIndex(loc, base->getType(), indexValue);
  701. return intermediate.foldDereference(base, indexValue, loc);
  702. } else {
  703. // at least one of base and index is variable...
  704. if (index->getQualifier().isFrontEndConstant())
  705. checkIndex(loc, base->getType(), indexValue);
  706. if (base->getType().isScalarOrVec1())
  707. result = base;
  708. else if (base->getAsSymbolNode() && wasFlattened(base)) {
  709. if (index->getQualifier().storage != EvqConst)
  710. error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
  711. result = flattenAccess(base, indexValue);
  712. flattened = (result != base);
  713. } else {
  714. if (index->getQualifier().isFrontEndConstant()) {
  715. if (base->getType().isUnsizedArray())
  716. base->getWritableType().updateImplicitArraySize(indexValue + 1);
  717. else
  718. checkIndex(loc, base->getType(), indexValue);
  719. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  720. } else
  721. result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
  722. }
  723. }
  724. if (result == nullptr) {
  725. // Insert dummy error-recovery result
  726. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  727. } else {
  728. // If the array reference was flattened, it has the correct type. E.g, if it was
  729. // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
  730. // In that case, we preserve the qualifiers.
  731. if (!flattened) {
  732. // Insert valid dereferenced result
  733. TType newType(base->getType(), 0); // dereferenced type
  734. if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
  735. newType.getQualifier().storage = EvqConst;
  736. else
  737. newType.getQualifier().storage = EvqTemporary;
  738. result->setType(newType);
  739. }
  740. }
  741. return result;
  742. }
  743. // Handle seeing a binary node with a math operation.
  744. TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  745. TIntermTyped* left, TIntermTyped* right)
  746. {
  747. TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
  748. if (result == nullptr)
  749. binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
  750. return result;
  751. }
  752. // Handle seeing a unary node with a math operation.
  753. TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  754. TIntermTyped* childNode)
  755. {
  756. TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
  757. if (result)
  758. return result;
  759. else
  760. unaryOpError(loc, str, childNode->getCompleteString());
  761. return childNode;
  762. }
  763. //
  764. // Return true if the name is a struct buffer method
  765. //
  766. bool HlslParseContext::isStructBufferMethod(const TString& name) const
  767. {
  768. return
  769. name == "GetDimensions" ||
  770. name == "Load" ||
  771. name == "Load2" ||
  772. name == "Load3" ||
  773. name == "Load4" ||
  774. name == "Store" ||
  775. name == "Store2" ||
  776. name == "Store3" ||
  777. name == "Store4" ||
  778. name == "InterlockedAdd" ||
  779. name == "InterlockedAnd" ||
  780. name == "InterlockedCompareExchange" ||
  781. name == "InterlockedCompareStore" ||
  782. name == "InterlockedExchange" ||
  783. name == "InterlockedMax" ||
  784. name == "InterlockedMin" ||
  785. name == "InterlockedOr" ||
  786. name == "InterlockedXor" ||
  787. name == "IncrementCounter" ||
  788. name == "DecrementCounter" ||
  789. name == "Append" ||
  790. name == "Consume";
  791. }
  792. //
  793. // Handle seeing a base.field dereference in the grammar, where 'field' is a
  794. // swizzle or member variable.
  795. //
  796. TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  797. {
  798. variableCheck(base);
  799. if (base->isArray()) {
  800. error(loc, "cannot apply to an array:", ".", field.c_str());
  801. return base;
  802. }
  803. TIntermTyped* result = base;
  804. if (base->getType().getBasicType() == EbtSampler) {
  805. // Handle .mips[mipid][pos] operation on textures
  806. const TSampler& sampler = base->getType().getSampler();
  807. if (sampler.isTexture() && field == "mips") {
  808. // Push a null to signify that we expect a mip level under operator[] next.
  809. mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
  810. // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
  811. } else {
  812. if (field == "mips")
  813. error(loc, "unexpected texture type for .mips[][] operator:",
  814. base->getType().getCompleteString().c_str(), "");
  815. else
  816. error(loc, "unexpected operator on texture type:", field.c_str(),
  817. base->getType().getCompleteString().c_str());
  818. }
  819. } else if (base->isVector() || base->isScalar()) {
  820. TSwizzleSelectors<TVectorSelector> selectors;
  821. parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
  822. if (base->isScalar()) {
  823. if (selectors.size() == 1)
  824. return result;
  825. else {
  826. TType type(base->getBasicType(), EvqTemporary, selectors.size());
  827. return addConstructor(loc, base, type);
  828. }
  829. }
  830. if (base->getVectorSize() == 1) {
  831. TType scalarType(base->getBasicType(), EvqTemporary, 1);
  832. if (selectors.size() == 1)
  833. return addConstructor(loc, base, scalarType);
  834. else {
  835. TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
  836. return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
  837. }
  838. }
  839. if (base->getType().getQualifier().isFrontEndConstant())
  840. result = intermediate.foldSwizzle(base, selectors, loc);
  841. else {
  842. if (selectors.size() == 1) {
  843. TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
  844. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  845. result->setType(TType(base->getBasicType(), EvqTemporary));
  846. } else {
  847. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  848. result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
  849. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  850. selectors.size()));
  851. }
  852. }
  853. } else if (base->isMatrix()) {
  854. TSwizzleSelectors<TMatrixSelector> selectors;
  855. if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
  856. return result;
  857. if (selectors.size() == 1) {
  858. // Representable by m[c][r]
  859. if (base->getType().getQualifier().isFrontEndConstant()) {
  860. result = intermediate.foldDereference(base, selectors[0].coord1, loc);
  861. result = intermediate.foldDereference(result, selectors[0].coord2, loc);
  862. } else {
  863. result = intermediate.addIndex(EOpIndexDirect, base,
  864. intermediate.addConstantUnion(selectors[0].coord1, loc),
  865. loc);
  866. TType dereferencedCol(base->getType(), 0);
  867. result->setType(dereferencedCol);
  868. result = intermediate.addIndex(EOpIndexDirect, result,
  869. intermediate.addConstantUnion(selectors[0].coord2, loc),
  870. loc);
  871. TType dereferenced(dereferencedCol, 0);
  872. result->setType(dereferenced);
  873. }
  874. } else {
  875. int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
  876. if (column >= 0) {
  877. // Representable by m[c]
  878. if (base->getType().getQualifier().isFrontEndConstant())
  879. result = intermediate.foldDereference(base, column, loc);
  880. else {
  881. result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
  882. loc);
  883. TType dereferenced(base->getType(), 0);
  884. result->setType(dereferenced);
  885. }
  886. } else {
  887. // general case, not a column, not a single component
  888. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  889. result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
  890. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  891. selectors.size()));
  892. }
  893. }
  894. } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
  895. const TTypeList* fields = base->getType().getStruct();
  896. bool fieldFound = false;
  897. int member;
  898. for (member = 0; member < (int)fields->size(); ++member) {
  899. if ((*fields)[member].type->getFieldName() == field) {
  900. fieldFound = true;
  901. break;
  902. }
  903. }
  904. if (fieldFound) {
  905. if (base->getAsSymbolNode() && wasFlattened(base)) {
  906. result = flattenAccess(base, member);
  907. } else {
  908. if (base->getType().getQualifier().storage == EvqConst)
  909. result = intermediate.foldDereference(base, member, loc);
  910. else {
  911. TIntermTyped* index = intermediate.addConstantUnion(member, loc);
  912. result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
  913. result->setType(*(*fields)[member].type);
  914. }
  915. }
  916. } else
  917. error(loc, "no such field in structure", field.c_str(), "");
  918. } else
  919. error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
  920. return result;
  921. }
  922. //
  923. // Return true if the field should be treated as a built-in method.
  924. // Return false otherwise.
  925. //
  926. bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
  927. {
  928. if (base == nullptr)
  929. return false;
  930. variableCheck(base);
  931. if (base->getType().getBasicType() == EbtSampler) {
  932. return true;
  933. } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
  934. return true;
  935. } else if (field == "Append" ||
  936. field == "RestartStrip") {
  937. // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
  938. // the code is around in the shader source.
  939. return true;
  940. } else
  941. return false;
  942. }
  943. // Independently establish a built-in that is a member of a structure.
  944. // 'arraySizes' are what's desired for the independent built-in, whatever
  945. // the higher-level source/expression of them was.
  946. void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
  947. const TQualifier& outerQualifier)
  948. {
  949. // Because of arrays of structs, we might be asked more than once,
  950. // but the arraySizes passed in should have captured the whole thing
  951. // the first time.
  952. // However, clip/cull rely on multiple updates.
  953. if (!isClipOrCullDistance(memberType))
  954. if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
  955. splitBuiltIns.end())
  956. return;
  957. TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
  958. if (arraySizes != nullptr && !memberType.isArray())
  959. ioVar->getWritableType().copyArraySizes(*arraySizes);
  960. splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
  961. if (!isClipOrCullDistance(ioVar->getType()))
  962. trackLinkage(*ioVar);
  963. // Merge qualifier from the user structure
  964. mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
  965. // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
  966. // shader declared them). This is done after mergeQualifiers(), in case fixBuiltInIoType looks
  967. // at the qualifier to determine e.g, in or out qualifications.
  968. fixBuiltInIoType(ioVar->getWritableType());
  969. // But, not location, we're losing that
  970. ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  971. }
  972. // Split a type into
  973. // 1. a struct of non-I/O members
  974. // 2. a collection of independent I/O variables
  975. void HlslParseContext::split(const TVariable& variable)
  976. {
  977. // Create a new variable:
  978. const TType& clonedType = *variable.getType().clone();
  979. const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
  980. splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
  981. }
  982. // Recursive implementation of split().
  983. // Returns reference to the modified type.
  984. const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
  985. {
  986. if (type.isStruct()) {
  987. TTypeList* userStructure = type.getWritableStruct();
  988. for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
  989. if (ioType->type->isBuiltIn()) {
  990. // move out the built-in
  991. splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
  992. ioType = userStructure->erase(ioType);
  993. } else {
  994. split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
  995. ++ioType;
  996. }
  997. }
  998. }
  999. return type;
  1000. }
  1001. // Is this an aggregate that should be flattened?
  1002. // Can be applied to intermediate levels of type in a hierarchy.
  1003. // Some things like flattening uniform arrays are only about the top level
  1004. // of the aggregate, triggered on 'topLevel'.
  1005. bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
  1006. {
  1007. switch (qualifier) {
  1008. case EvqVaryingIn:
  1009. case EvqVaryingOut:
  1010. return type.isStruct() || type.isArray();
  1011. case EvqUniform:
  1012. return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
  1013. (type.isStruct() && type.containsOpaque());
  1014. default:
  1015. return false;
  1016. };
  1017. }
  1018. // Top level variable flattening: construct data
  1019. void HlslParseContext::flatten(const TVariable& variable, bool linkage)
  1020. {
  1021. const TType& type = variable.getType();
  1022. // If it's a standalone built-in, there is nothing to flatten
  1023. if (type.isBuiltIn() && !type.isStruct())
  1024. return;
  1025. auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
  1026. TFlattenData(type.getQualifier().layoutBinding,
  1027. type.getQualifier().layoutLocation)));
  1028. // the item is a map pair, so first->second is the TFlattenData itself.
  1029. flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
  1030. }
  1031. // Recursively flatten the given variable at the provided type, building the flattenData as we go.
  1032. //
  1033. // This is mutually recursive with flattenStruct and flattenArray.
  1034. // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
  1035. // members, and later on, we want to turn a path through the tree structure into a final
  1036. // location in this linear sequence.
  1037. //
  1038. // If the tree was N-ary, that can be directly calculated. However, we are dealing with
  1039. // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
  1040. // build a data structure to allow the sequence of bracket and dot operators on arrays and
  1041. // structs to arrive at the proper member.
  1042. //
  1043. // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
  1044. // The leaves are the indexes into the flattened member array.
  1045. // Each level will have the next location for the Nth item stored sequentially, so for instance:
  1046. //
  1047. // struct { float2 a[2]; int b; float4 c[3] };
  1048. //
  1049. // This will produce the following flattened tree:
  1050. // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  1051. // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
  1052. //
  1053. // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
  1054. // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
  1055. //
  1056. // so the 4th flattened member in traversal order is ours.
  1057. //
  1058. int HlslParseContext::flatten(const TVariable& variable, const TType& type,
  1059. TFlattenData& flattenData, TString name, bool linkage,
  1060. const TQualifier& outerQualifier,
  1061. const TArraySizes* builtInArraySizes)
  1062. {
  1063. // If something is an arrayed struct, the array flattener will recursively call flatten()
  1064. // to then flatten the struct, so this is an "if else": we don't do both.
  1065. if (type.isArray())
  1066. return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
  1067. else if (type.isStruct())
  1068. return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
  1069. else {
  1070. assert(0); // should never happen
  1071. return -1;
  1072. }
  1073. }
  1074. // Add a single flattened member to the flattened data being tracked for the composite
  1075. // Returns true for the final flattening level.
  1076. int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
  1077. const TString& memberName, bool linkage,
  1078. const TQualifier& outerQualifier,
  1079. const TArraySizes* builtInArraySizes)
  1080. {
  1081. if (!shouldFlatten(type, outerQualifier.storage, false)) {
  1082. // This is as far as we flatten. Insert the variable.
  1083. TVariable* memberVariable = makeInternalVariable(memberName, type);
  1084. mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
  1085. if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
  1086. memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
  1087. if (memberVariable->getType().isBuiltIn()) {
  1088. // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
  1089. memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  1090. } else {
  1091. // inherited locations must be auto bumped, not replicated
  1092. if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
  1093. memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
  1094. flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
  1095. nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
  1096. }
  1097. }
  1098. flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
  1099. flattenData.members.push_back(memberVariable);
  1100. if (linkage)
  1101. trackLinkage(*memberVariable);
  1102. return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
  1103. } else {
  1104. // Further recursion required
  1105. return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
  1106. }
  1107. }
  1108. // Figure out the mapping between an aggregate's top members and an
  1109. // equivalent set of individual variables.
  1110. //
  1111. // Assumes shouldFlatten() or equivalent was called first.
  1112. int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
  1113. TFlattenData& flattenData, TString name, bool linkage,
  1114. const TQualifier& outerQualifier,
  1115. const TArraySizes* builtInArraySizes)
  1116. {
  1117. assert(type.isStruct());
  1118. auto members = *type.getStruct();
  1119. // Reserve space for this tree level.
  1120. int start = static_cast<int>(flattenData.offsets.size());
  1121. int pos = start;
  1122. flattenData.offsets.resize(int(pos + members.size()), -1);
  1123. for (int member = 0; member < (int)members.size(); ++member) {
  1124. TType& dereferencedType = *members[member].type;
  1125. if (dereferencedType.isBuiltIn())
  1126. splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
  1127. else {
  1128. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1129. name + "." + dereferencedType.getFieldName(),
  1130. linkage, outerQualifier,
  1131. builtInArraySizes == nullptr && dereferencedType.isArray()
  1132. ? dereferencedType.getArraySizes()
  1133. : builtInArraySizes);
  1134. flattenData.offsets[pos++] = mpos;
  1135. }
  1136. }
  1137. return start;
  1138. }
  1139. // Figure out mapping between an array's members and an
  1140. // equivalent set of individual variables.
  1141. //
  1142. // Assumes shouldFlatten() or equivalent was called first.
  1143. int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
  1144. TFlattenData& flattenData, TString name, bool linkage,
  1145. const TQualifier& outerQualifier)
  1146. {
  1147. assert(type.isSizedArray());
  1148. const int size = type.getOuterArraySize();
  1149. const TType dereferencedType(type, 0);
  1150. if (name.empty())
  1151. name = variable.getName();
  1152. // Reserve space for this tree level.
  1153. int start = static_cast<int>(flattenData.offsets.size());
  1154. int pos = start;
  1155. flattenData.offsets.resize(int(pos + size), -1);
  1156. for (int element=0; element < size; ++element) {
  1157. char elementNumBuf[20]; // sufficient for MAXINT
  1158. snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
  1159. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1160. name + elementNumBuf, linkage, outerQualifier,
  1161. type.getArraySizes());
  1162. flattenData.offsets[pos++] = mpos;
  1163. }
  1164. return start;
  1165. }
  1166. // Return true if we have flattened this node.
  1167. bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
  1168. {
  1169. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1170. wasFlattened(node->getAsSymbolNode()->getId());
  1171. }
  1172. // Return true if we have split this structure
  1173. bool HlslParseContext::wasSplit(const TIntermTyped* node) const
  1174. {
  1175. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1176. wasSplit(node->getAsSymbolNode()->getId());
  1177. }
  1178. // Turn an access into an aggregate that was flattened to instead be
  1179. // an access to the individual variable the member was flattened to.
  1180. // Assumes wasFlattened() or equivalent was called first.
  1181. TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
  1182. {
  1183. const TType dereferencedType(base->getType(), member); // dereferenced type
  1184. const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
  1185. TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
  1186. dereferencedType, symbolNode.getFlattenSubset());
  1187. return flattened ? flattened : base;
  1188. }
  1189. TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
  1190. const TType& dereferencedType, int subset)
  1191. {
  1192. const auto flattenData = flattenMap.find(uniqueId);
  1193. if (flattenData == flattenMap.end())
  1194. return nullptr;
  1195. // Calculate new cumulative offset from the packed tree
  1196. int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
  1197. TIntermSymbol* subsetSymbol;
  1198. if (!shouldFlatten(dereferencedType, outerStorage, false)) {
  1199. // Finished flattening: create symbol for variable
  1200. member = flattenData->second.offsets[newSubset];
  1201. const TVariable* memberVariable = flattenData->second.members[member];
  1202. subsetSymbol = intermediate.addSymbol(*memberVariable);
  1203. subsetSymbol->setFlattenSubset(-1);
  1204. } else {
  1205. // If this is not the final flattening, accumulate the position and return
  1206. // an object of the partially dereferenced type.
  1207. subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
  1208. subsetSymbol->setFlattenSubset(newSubset);
  1209. }
  1210. return subsetSymbol;
  1211. }
  1212. // For finding where the first leaf is in a subtree of a multi-level aggregate
  1213. // that is just getting a subset assigned. Follows the same logic as flattenAccess,
  1214. // but logically going down the "left-most" tree branch each step of the way.
  1215. //
  1216. // Returns the offset into the first leaf of the subset.
  1217. int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
  1218. {
  1219. const TIntermSymbol* sym = node.getAsSymbolNode();
  1220. if (sym == nullptr)
  1221. return 0;
  1222. if (!sym->isArray() && !sym->isStruct())
  1223. return 0;
  1224. int subset = sym->getFlattenSubset();
  1225. if (subset == -1)
  1226. return 0;
  1227. // Getting this far means a partial aggregate is identified by the flatten subset.
  1228. // Find the first leaf of the subset.
  1229. const auto flattenData = flattenMap.find(sym->getId());
  1230. if (flattenData == flattenMap.end())
  1231. return 0;
  1232. return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
  1233. do {
  1234. subset = flattenData->second.offsets[subset];
  1235. } while (true);
  1236. }
  1237. // Recursively do the desent
  1238. int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
  1239. {
  1240. if (!type.isArray() && !type.isStruct())
  1241. return offsets[subset];
  1242. TType derefType(type, 0);
  1243. return findSubtreeOffset(derefType, offsets[subset], offsets);
  1244. };
  1245. // Find and return the split IO TVariable for id, or nullptr if none.
  1246. TVariable* HlslParseContext::getSplitNonIoVar(int id) const
  1247. {
  1248. const auto splitNonIoVar = splitNonIoVars.find(id);
  1249. if (splitNonIoVar == splitNonIoVars.end())
  1250. return nullptr;
  1251. return splitNonIoVar->second;
  1252. }
  1253. // Pass through to base class after remembering built-in mappings.
  1254. void HlslParseContext::trackLinkage(TSymbol& symbol)
  1255. {
  1256. TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
  1257. if (biType != EbvNone)
  1258. builtInTessLinkageSymbols[biType] = symbol.clone();
  1259. TParseContextBase::trackLinkage(symbol);
  1260. }
  1261. // Returns true if the built-in is a clip or cull distance variable.
  1262. bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
  1263. {
  1264. return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
  1265. }
  1266. // Some types require fixed array sizes in SPIR-V, but can be scalars or
  1267. // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
  1268. // This creates the right size. A conversion is performed when the internal
  1269. // type is copied to or from the external type. This corrects the externally
  1270. // facing input or output type to abide downstream semantics.
  1271. void HlslParseContext::fixBuiltInIoType(TType& type)
  1272. {
  1273. int requiredArraySize = 0;
  1274. int requiredVectorSize = 0;
  1275. switch (type.getQualifier().builtIn) {
  1276. case EbvTessLevelOuter: requiredArraySize = 4; break;
  1277. case EbvTessLevelInner: requiredArraySize = 2; break;
  1278. case EbvSampleMask:
  1279. {
  1280. // Promote scalar to array of size 1. Leave existing arrays alone.
  1281. if (!type.isArray())
  1282. requiredArraySize = 1;
  1283. break;
  1284. }
  1285. case EbvWorkGroupId: requiredVectorSize = 3; break;
  1286. case EbvGlobalInvocationId: requiredVectorSize = 3; break;
  1287. case EbvLocalInvocationId: requiredVectorSize = 3; break;
  1288. case EbvTessCoord: requiredVectorSize = 3; break;
  1289. default:
  1290. if (isClipOrCullDistance(type)) {
  1291. const int loc = type.getQualifier().layoutLocation;
  1292. if (type.getQualifier().builtIn == EbvClipDistance) {
  1293. if (type.getQualifier().storage == EvqVaryingIn)
  1294. clipSemanticNSizeIn[loc] = type.getVectorSize();
  1295. else
  1296. clipSemanticNSizeOut[loc] = type.getVectorSize();
  1297. } else {
  1298. if (type.getQualifier().storage == EvqVaryingIn)
  1299. cullSemanticNSizeIn[loc] = type.getVectorSize();
  1300. else
  1301. cullSemanticNSizeOut[loc] = type.getVectorSize();
  1302. }
  1303. }
  1304. return;
  1305. }
  1306. // Alter or set vector size as needed.
  1307. if (requiredVectorSize > 0) {
  1308. TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
  1309. newType.getQualifier() = type.getQualifier();
  1310. type.shallowCopy(newType);
  1311. }
  1312. // Alter or set array size as needed.
  1313. if (requiredArraySize > 0) {
  1314. if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
  1315. TArraySizes* arraySizes = new TArraySizes;
  1316. arraySizes->addInnerSize(requiredArraySize);
  1317. type.transferArraySizes(arraySizes);
  1318. }
  1319. }
  1320. }
  1321. // Variables that correspond to the user-interface in and out of a stage
  1322. // (not the built-in interface) are
  1323. // - assigned locations
  1324. // - registered as a linkage node (part of the stage's external interface).
  1325. // Assumes it is called in the order in which locations should be assigned.
  1326. void HlslParseContext::assignToInterface(TVariable& variable)
  1327. {
  1328. const auto assignLocation = [&](TVariable& variable) {
  1329. TType& type = variable.getWritableType();
  1330. if (!type.isStruct() || type.getStruct()->size() > 0) {
  1331. TQualifier& qualifier = type.getQualifier();
  1332. if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
  1333. if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
  1334. // Strip off the outer array dimension for those having an extra one.
  1335. int size;
  1336. if (type.isArray() && qualifier.isArrayedIo(language)) {
  1337. TType elementType(type, 0);
  1338. size = intermediate.computeTypeLocationSize(elementType, language);
  1339. } else
  1340. size = intermediate.computeTypeLocationSize(type, language);
  1341. if (qualifier.storage == EvqVaryingIn) {
  1342. variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
  1343. nextInLocation += size;
  1344. } else {
  1345. variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
  1346. nextOutLocation += size;
  1347. }
  1348. }
  1349. trackLinkage(variable);
  1350. }
  1351. }
  1352. };
  1353. if (wasFlattened(variable.getUniqueId())) {
  1354. auto& memberList = flattenMap[variable.getUniqueId()].members;
  1355. for (auto member = memberList.begin(); member != memberList.end(); ++member)
  1356. assignLocation(**member);
  1357. } else if (wasSplit(variable.getUniqueId())) {
  1358. TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
  1359. assignLocation(*splitIoVar);
  1360. } else {
  1361. assignLocation(variable);
  1362. }
  1363. }
  1364. //
  1365. // Handle seeing a function declarator in the grammar. This is the precursor
  1366. // to recognizing a function prototype or function definition.
  1367. //
  1368. void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  1369. {
  1370. //
  1371. // Multiple declarations of the same function name are allowed.
  1372. //
  1373. // If this is a definition, the definition production code will check for redefinitions
  1374. // (we don't know at this point if it's a definition or not).
  1375. //
  1376. bool builtIn;
  1377. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1378. const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
  1379. if (prototype) {
  1380. // All built-in functions are defined, even though they don't have a body.
  1381. // Count their prototype as a definition instead.
  1382. if (symbolTable.atBuiltInLevel())
  1383. function.setDefined();
  1384. else {
  1385. if (prevDec && ! builtIn)
  1386. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1387. function.setPrototyped();
  1388. }
  1389. }
  1390. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1391. // other forms of name collisions.
  1392. if (! symbolTable.insert(function))
  1393. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1394. }
  1395. // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
  1396. // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
  1397. // Otherwise, it's a no-op
  1398. void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
  1399. TIntermAggregate*& paramNodes)
  1400. {
  1401. if (! hasStructBuffCounter(*param.type))
  1402. return;
  1403. const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
  1404. TType counterType;
  1405. counterBufferType(loc, counterType);
  1406. TVariable *variable = makeInternalVariable(counterBlockName, counterType);
  1407. if (! symbolTable.insert(*variable))
  1408. error(loc, "redefinition", variable->getName().c_str(), "");
  1409. paramNodes = intermediate.growAggregate(paramNodes,
  1410. intermediate.addSymbol(*variable, loc),
  1411. loc);
  1412. }
  1413. //
  1414. // Handle seeing the function prototype in front of a function definition in the grammar.
  1415. // The body is handled after this function returns.
  1416. //
  1417. // Returns an aggregate of parameter-symbol nodes.
  1418. //
  1419. TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
  1420. const TAttributes& attributes,
  1421. TIntermNode*& entryPointTree)
  1422. {
  1423. currentCaller = function.getMangledName();
  1424. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1425. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1426. if (prevDec == nullptr)
  1427. error(loc, "can't find function", function.getName().c_str(), "");
  1428. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1429. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1430. // an earlier occurrence.
  1431. if (prevDec && prevDec->isDefined()) {
  1432. // Then this function already has a body.
  1433. error(loc, "function already has a body", function.getName().c_str(), "");
  1434. }
  1435. if (prevDec && ! prevDec->isDefined()) {
  1436. prevDec->setDefined();
  1437. // Remember the return type for later checking for RETURN statements.
  1438. currentFunctionType = &(prevDec->getType());
  1439. } else
  1440. currentFunctionType = new TType(EbtVoid);
  1441. functionReturnsValue = false;
  1442. // Entry points need different I/O and other handling, transform it so the
  1443. // rest of this function doesn't care.
  1444. entryPointTree = transformEntryPoint(loc, function, attributes);
  1445. //
  1446. // New symbol table scope for body of function plus its arguments
  1447. //
  1448. pushScope();
  1449. //
  1450. // Insert parameters into the symbol table.
  1451. // If the parameter has no name, it's not an error, just don't insert it
  1452. // (could be used for unused args).
  1453. //
  1454. // Also, accumulate the list of parameters into the AST, so lower level code
  1455. // knows where to find parameters.
  1456. //
  1457. TIntermAggregate* paramNodes = new TIntermAggregate;
  1458. for (int i = 0; i < function.getParamCount(); i++) {
  1459. TParameter& param = function[i];
  1460. if (param.name != nullptr) {
  1461. TVariable *variable = new TVariable(param.name, *param.type);
  1462. if (i == 0 && function.hasImplicitThis()) {
  1463. // Anonymous 'this' members are already in a symbol-table level,
  1464. // and we need to know what function parameter to map them to.
  1465. symbolTable.makeInternalVariable(*variable);
  1466. pushImplicitThis(variable);
  1467. }
  1468. // Insert the parameters with name in the symbol table.
  1469. if (! symbolTable.insert(*variable))
  1470. error(loc, "redefinition", variable->getName().c_str(), "");
  1471. // Add parameters to the AST list.
  1472. if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
  1473. // Expand the AST parameter nodes (but not the name mangling or symbol table view)
  1474. // for structures that need to be flattened.
  1475. flatten(*variable, false);
  1476. const TTypeList* structure = variable->getType().getStruct();
  1477. for (int mem = 0; mem < (int)structure->size(); ++mem) {
  1478. paramNodes = intermediate.growAggregate(paramNodes,
  1479. flattenAccess(variable->getUniqueId(), mem,
  1480. variable->getType().getQualifier().storage,
  1481. *(*structure)[mem].type),
  1482. loc);
  1483. }
  1484. } else {
  1485. // Add the parameter to the AST
  1486. paramNodes = intermediate.growAggregate(paramNodes,
  1487. intermediate.addSymbol(*variable, loc),
  1488. loc);
  1489. }
  1490. // Add hidden AST parameter for struct buffer counters, if needed.
  1491. addStructBufferHiddenCounterParam(loc, param, paramNodes);
  1492. } else
  1493. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1494. }
  1495. if (function.hasIllegalImplicitThis())
  1496. pushImplicitThis(nullptr);
  1497. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1498. loopNestingLevel = 0;
  1499. controlFlowNestingLevel = 0;
  1500. postEntryPointReturn = false;
  1501. return paramNodes;
  1502. }
  1503. // Handle all [attrib] attribute for the shader entry point
  1504. void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
  1505. {
  1506. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1507. switch (it->name) {
  1508. case EatNumThreads:
  1509. {
  1510. const TIntermSequence& sequence = it->args->getSequence();
  1511. for (int lid = 0; lid < int(sequence.size()); ++lid)
  1512. intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
  1513. break;
  1514. }
  1515. case EatMaxVertexCount:
  1516. {
  1517. int maxVertexCount;
  1518. if (! it->getInt(maxVertexCount)) {
  1519. error(loc, "invalid maxvertexcount", "", "");
  1520. } else {
  1521. if (! intermediate.setVertices(maxVertexCount))
  1522. error(loc, "cannot change previously set maxvertexcount attribute", "", "");
  1523. }
  1524. break;
  1525. }
  1526. case EatPatchConstantFunc:
  1527. {
  1528. TString pcfName;
  1529. if (! it->getString(pcfName, 0, false)) {
  1530. error(loc, "invalid patch constant function", "", "");
  1531. } else {
  1532. patchConstantFunctionName = pcfName;
  1533. }
  1534. break;
  1535. }
  1536. case EatDomain:
  1537. {
  1538. // Handle [domain("...")]
  1539. TString domainStr;
  1540. if (! it->getString(domainStr)) {
  1541. error(loc, "invalid domain", "", "");
  1542. } else {
  1543. TLayoutGeometry domain = ElgNone;
  1544. if (domainStr == "tri") {
  1545. domain = ElgTriangles;
  1546. } else if (domainStr == "quad") {
  1547. domain = ElgQuads;
  1548. } else if (domainStr == "isoline") {
  1549. domain = ElgIsolines;
  1550. } else {
  1551. error(loc, "unsupported domain type", domainStr.c_str(), "");
  1552. }
  1553. if (language == EShLangTessEvaluation) {
  1554. if (! intermediate.setInputPrimitive(domain))
  1555. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1556. } else {
  1557. if (! intermediate.setOutputPrimitive(domain))
  1558. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1559. }
  1560. }
  1561. break;
  1562. }
  1563. case EatOutputTopology:
  1564. {
  1565. // Handle [outputtopology("...")]
  1566. TString topologyStr;
  1567. if (! it->getString(topologyStr)) {
  1568. error(loc, "invalid outputtopology", "", "");
  1569. } else {
  1570. TVertexOrder vertexOrder = EvoNone;
  1571. TLayoutGeometry primitive = ElgNone;
  1572. if (topologyStr == "point") {
  1573. intermediate.setPointMode();
  1574. } else if (topologyStr == "line") {
  1575. primitive = ElgIsolines;
  1576. } else if (topologyStr == "triangle_cw") {
  1577. vertexOrder = EvoCw;
  1578. primitive = ElgTriangles;
  1579. } else if (topologyStr == "triangle_ccw") {
  1580. vertexOrder = EvoCcw;
  1581. primitive = ElgTriangles;
  1582. } else {
  1583. error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
  1584. }
  1585. if (vertexOrder != EvoNone) {
  1586. if (! intermediate.setVertexOrder(vertexOrder)) {
  1587. error(loc, "cannot change previously set outputtopology",
  1588. TQualifier::getVertexOrderString(vertexOrder), "");
  1589. }
  1590. }
  1591. if (primitive != ElgNone)
  1592. intermediate.setOutputPrimitive(primitive);
  1593. }
  1594. break;
  1595. }
  1596. case EatPartitioning:
  1597. {
  1598. // Handle [partitioning("...")]
  1599. TString partitionStr;
  1600. if (! it->getString(partitionStr)) {
  1601. error(loc, "invalid partitioning", "", "");
  1602. } else {
  1603. TVertexSpacing partitioning = EvsNone;
  1604. if (partitionStr == "integer") {
  1605. partitioning = EvsEqual;
  1606. } else if (partitionStr == "fractional_even") {
  1607. partitioning = EvsFractionalEven;
  1608. } else if (partitionStr == "fractional_odd") {
  1609. partitioning = EvsFractionalOdd;
  1610. //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
  1611. } else {
  1612. error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
  1613. }
  1614. if (! intermediate.setVertexSpacing(partitioning))
  1615. error(loc, "cannot change previously set partitioning",
  1616. TQualifier::getVertexSpacingString(partitioning), "");
  1617. }
  1618. break;
  1619. }
  1620. case EatOutputControlPoints:
  1621. {
  1622. // Handle [outputcontrolpoints("...")]
  1623. int ctrlPoints;
  1624. if (! it->getInt(ctrlPoints)) {
  1625. error(loc, "invalid outputcontrolpoints", "", "");
  1626. } else {
  1627. if (! intermediate.setVertices(ctrlPoints)) {
  1628. error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
  1629. }
  1630. }
  1631. break;
  1632. }
  1633. case EatBuiltIn:
  1634. case EatLocation:
  1635. // tolerate these because of dual use of entrypoint and type attributes
  1636. break;
  1637. default:
  1638. warn(loc, "attribute does not apply to entry point", "", "");
  1639. break;
  1640. }
  1641. }
  1642. }
  1643. // Update the given type with any type-like attribute information in the
  1644. // attributes.
  1645. void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
  1646. bool allowEntry)
  1647. {
  1648. if (attributes.size() == 0)
  1649. return;
  1650. int value;
  1651. TString builtInString;
  1652. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1653. switch (it->name) {
  1654. case EatLocation:
  1655. // location
  1656. if (it->getInt(value))
  1657. type.getQualifier().layoutLocation = value;
  1658. break;
  1659. case EatBinding:
  1660. // binding
  1661. if (it->getInt(value)) {
  1662. type.getQualifier().layoutBinding = value;
  1663. type.getQualifier().layoutSet = 0;
  1664. }
  1665. // set
  1666. if (it->getInt(value, 1))
  1667. type.getQualifier().layoutSet = value;
  1668. break;
  1669. case EatGlobalBinding:
  1670. // global cbuffer binding
  1671. if (it->getInt(value))
  1672. globalUniformBinding = value;
  1673. // global cbuffer binding
  1674. if (it->getInt(value, 1))
  1675. globalUniformSet = value;
  1676. break;
  1677. case EatInputAttachment:
  1678. // input attachment
  1679. if (it->getInt(value))
  1680. type.getQualifier().layoutAttachment = value;
  1681. break;
  1682. case EatBuiltIn:
  1683. // PointSize built-in
  1684. if (it->getString(builtInString, 0, false)) {
  1685. if (builtInString == "PointSize")
  1686. type.getQualifier().builtIn = EbvPointSize;
  1687. }
  1688. break;
  1689. case EatPushConstant:
  1690. // push_constant
  1691. type.getQualifier().layoutPushConstant = true;
  1692. break;
  1693. case EatConstantId:
  1694. // specialization constant
  1695. if (it->getInt(value)) {
  1696. TSourceLoc loc;
  1697. loc.init();
  1698. setSpecConstantId(loc, type.getQualifier(), value);
  1699. }
  1700. break;
  1701. default:
  1702. if (! allowEntry)
  1703. warn(loc, "attribute does not apply to a type", "", "");
  1704. break;
  1705. }
  1706. }
  1707. }
  1708. //
  1709. // Do all special handling for the entry point, including wrapping
  1710. // the shader's entry point with the official entry point that will call it.
  1711. //
  1712. // The following:
  1713. //
  1714. // retType shaderEntryPoint(args...) // shader declared entry point
  1715. // { body }
  1716. //
  1717. // Becomes
  1718. //
  1719. // out retType ret;
  1720. // in iargs<that are input>...;
  1721. // out oargs<that are output> ...;
  1722. //
  1723. // void shaderEntryPoint() // synthesized, but official, entry point
  1724. // {
  1725. // args<that are input> = iargs...;
  1726. // ret = @shaderEntryPoint(args...);
  1727. // oargs = args<that are output>...;
  1728. // }
  1729. // retType @shaderEntryPoint(args...)
  1730. // { body }
  1731. //
  1732. // The symbol table will still map the original entry point name to the
  1733. // the modified function and its new name:
  1734. //
  1735. // symbol table: shaderEntryPoint -> @shaderEntryPoint
  1736. //
  1737. // Returns nullptr if no entry-point tree was built, otherwise, returns
  1738. // a subtree that creates the entry point.
  1739. //
  1740. TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
  1741. const TAttributes& attributes)
  1742. {
  1743. // Return true if this is a tessellation patch constant function input to a domain shader.
  1744. const auto isDsPcfInput = [this](const TType& type) {
  1745. return language == EShLangTessEvaluation &&
  1746. type.contains([](const TType* t) {
  1747. return t->getQualifier().builtIn == EbvTessLevelOuter ||
  1748. t->getQualifier().builtIn == EbvTessLevelInner;
  1749. });
  1750. };
  1751. // if we aren't in the entry point, fix the IO as such and exit
  1752. if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
  1753. remapNonEntryPointIO(userFunction);
  1754. return nullptr;
  1755. }
  1756. entryPointFunction = &userFunction; // needed in finish()
  1757. // Handle entry point attributes
  1758. handleEntryPointAttributes(loc, attributes);
  1759. // entry point logic...
  1760. // Move parameters and return value to shader in/out
  1761. TVariable* entryPointOutput; // gets created in remapEntryPointIO
  1762. TVector<TVariable*> inputs;
  1763. TVector<TVariable*> outputs;
  1764. remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
  1765. // Further this return/in/out transform by flattening, splitting, and assigning locations
  1766. const auto makeVariableInOut = [&](TVariable& variable) {
  1767. if (variable.getType().isStruct()) {
  1768. if (variable.getType().getQualifier().isArrayedIo(language)) {
  1769. if (variable.getType().containsBuiltIn())
  1770. split(variable);
  1771. } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
  1772. flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
  1773. }
  1774. // TODO: flatten arrays too
  1775. // TODO: flatten everything in I/O
  1776. // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
  1777. // For clip and cull distance, multiple output variables potentially get merged
  1778. // into one in assignClipCullDistance. That code in assignClipCullDistance
  1779. // handles the interface logic, so we avoid it here in that case.
  1780. if (!isClipOrCullDistance(variable.getType()))
  1781. assignToInterface(variable);
  1782. };
  1783. if (entryPointOutput != nullptr)
  1784. makeVariableInOut(*entryPointOutput);
  1785. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1786. if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
  1787. makeVariableInOut(*(*it));
  1788. for (auto it = outputs.begin(); it != outputs.end(); ++it)
  1789. makeVariableInOut(*(*it));
  1790. // In the domain shader, PCF input must be at the end of the linkage. That's because in the
  1791. // hull shader there is no ordering: the output comes from the separate PCF, which does not
  1792. // participate in the argument list. That is always put at the end of the HS linkage, so the
  1793. // input side of the DS must match. The argument may be in any position in the DS argument list
  1794. // however, so this ensures the linkage is built in the correct order regardless of argument order.
  1795. if (language == EShLangTessEvaluation) {
  1796. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1797. if (isDsPcfInput((*it)->getType()))
  1798. makeVariableInOut(*(*it));
  1799. }
  1800. // Synthesize the call
  1801. pushScope(); // matches the one in handleFunctionBody()
  1802. // new signature
  1803. TType voidType(EbtVoid);
  1804. TFunction synthEntryPoint(&userFunction.getName(), voidType);
  1805. TIntermAggregate* synthParams = new TIntermAggregate();
  1806. intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
  1807. intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
  1808. intermediate.incrementEntryPointCount();
  1809. TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
  1810. // change original name
  1811. userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
  1812. // Copy inputs (shader-in -> calling arg), while building up the call node
  1813. TVector<TVariable*> argVars;
  1814. TIntermAggregate* synthBody = new TIntermAggregate();
  1815. auto inputIt = inputs.begin();
  1816. TIntermTyped* callingArgs = nullptr;
  1817. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1818. TParameter& param = userFunction[i];
  1819. argVars.push_back(makeInternalVariable(*param.name, *param.type));
  1820. argVars.back()->getWritableType().getQualifier().makeTemporary();
  1821. // Track the input patch, which is the only non-builtin supported by hull shader PCF.
  1822. if (param.getDeclaredBuiltIn() == EbvInputPatch)
  1823. inputPatch = argVars.back();
  1824. TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
  1825. handleFunctionArgument(&callee, callingArgs, arg);
  1826. if (param.type->getQualifier().isParamInput()) {
  1827. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1828. intermediate.addSymbol(**inputIt)));
  1829. inputIt++;
  1830. }
  1831. }
  1832. // Call
  1833. currentCaller = synthEntryPoint.getMangledName();
  1834. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  1835. currentCaller = userFunction.getMangledName();
  1836. // Return value
  1837. if (entryPointOutput) {
  1838. TIntermTyped* returnAssign;
  1839. // For hull shaders, the wrapped entry point return value is written to
  1840. // an array element as indexed by invocation ID, which we might have to make up.
  1841. // This is required to match SPIR-V semantics.
  1842. if (language == EShLangTessControl) {
  1843. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  1844. // If there is no user declared invocation ID, we must make one.
  1845. if (invocationIdSym == nullptr) {
  1846. TType invocationIdType(EbtUint, EvqIn, 1);
  1847. TString* invocationIdName = NewPoolTString("InvocationId");
  1848. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  1849. TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
  1850. globalQualifierFix(loc, variable->getWritableType().getQualifier());
  1851. trackLinkage(*variable);
  1852. invocationIdSym = intermediate.addSymbol(*variable);
  1853. }
  1854. TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
  1855. invocationIdSym, loc);
  1856. // Set the type of the array element being dereferenced
  1857. const TType derefElementType(entryPointOutput->getType(), 0);
  1858. element->setType(derefElementType);
  1859. returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
  1860. } else {
  1861. returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
  1862. }
  1863. intermediate.growAggregate(synthBody, returnAssign);
  1864. } else
  1865. intermediate.growAggregate(synthBody, callReturn);
  1866. // Output copies
  1867. auto outputIt = outputs.begin();
  1868. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1869. TParameter& param = userFunction[i];
  1870. // GS outputs are via emit, so we do not copy them here.
  1871. if (param.type->getQualifier().isParamOutput()) {
  1872. if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
  1873. // GS output stream does not assign outputs here: it's the Append() method
  1874. // which writes to the output, probably multiple times separated by Emit.
  1875. // We merely remember the output to use, here.
  1876. gsStreamOutput = *outputIt;
  1877. } else {
  1878. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
  1879. intermediate.addSymbol(**outputIt),
  1880. intermediate.addSymbol(*argVars[i])));
  1881. }
  1882. outputIt++;
  1883. }
  1884. }
  1885. // Put the pieces together to form a full function subtree
  1886. // for the synthesized entry point.
  1887. synthBody->setOperator(EOpSequence);
  1888. TIntermNode* synthFunctionDef = synthParams;
  1889. handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
  1890. entryPointFunctionBody = synthBody;
  1891. return synthFunctionDef;
  1892. }
  1893. void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
  1894. TIntermNode*& node)
  1895. {
  1896. node = intermediate.growAggregate(node, functionBody);
  1897. intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
  1898. node->getAsAggregate()->setName(function.getMangledName().c_str());
  1899. popScope();
  1900. if (function.hasImplicitThis())
  1901. popImplicitThis();
  1902. if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
  1903. error(loc, "function does not return a value:", "", function.getName().c_str());
  1904. }
  1905. // AST I/O is done through shader globals declared in the 'in' or 'out'
  1906. // storage class. An HLSL entry point has a return value, input parameters
  1907. // and output parameters. These need to get remapped to the AST I/O.
  1908. void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
  1909. TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
  1910. {
  1911. // We might have in input structure type with no decorations that caused it
  1912. // to look like an input type, yet it has (e.g.) interpolation types that
  1913. // must be modified that turn it into an input type.
  1914. // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
  1915. const auto synthesizeEditedInput = [this](TType& type) {
  1916. // True if a type needs to be 'flat'
  1917. const auto needsFlat = [](const TType& type) {
  1918. return type.containsBasicType(EbtInt) ||
  1919. type.containsBasicType(EbtUint) ||
  1920. type.containsBasicType(EbtInt64) ||
  1921. type.containsBasicType(EbtUint64) ||
  1922. type.containsBasicType(EbtBool) ||
  1923. type.containsBasicType(EbtDouble);
  1924. };
  1925. if (language == EShLangFragment && needsFlat(type)) {
  1926. if (type.isStruct()) {
  1927. TTypeList* finalList = nullptr;
  1928. auto it = ioTypeMap.find(type.getStruct());
  1929. if (it == ioTypeMap.end() || it->second.input == nullptr) {
  1930. // Getting here means we have no input struct, but we need one.
  1931. auto list = new TTypeList;
  1932. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  1933. TType* newType = new TType;
  1934. newType->shallowCopy(*member->type);
  1935. TTypeLoc typeLoc = { newType, member->loc };
  1936. list->push_back(typeLoc);
  1937. }
  1938. // install the new input type
  1939. if (it == ioTypeMap.end()) {
  1940. tIoKinds newLists = { list, nullptr, nullptr };
  1941. ioTypeMap[type.getStruct()] = newLists;
  1942. } else
  1943. it->second.input = list;
  1944. finalList = list;
  1945. } else
  1946. finalList = it->second.input;
  1947. // edit for 'flat'
  1948. for (auto member = finalList->begin(); member != finalList->end(); ++member) {
  1949. if (needsFlat(*member->type)) {
  1950. member->type->getQualifier().clearInterpolation();
  1951. member->type->getQualifier().flat = true;
  1952. }
  1953. }
  1954. } else {
  1955. type.getQualifier().clearInterpolation();
  1956. type.getQualifier().flat = true;
  1957. }
  1958. }
  1959. };
  1960. // Do the actual work to make a type be a shader input or output variable,
  1961. // and clear the original to be non-IO (for use as a normal function parameter/return).
  1962. const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
  1963. TVariable* ioVariable = makeInternalVariable(name, type);
  1964. clearUniformInputOutput(type.getQualifier());
  1965. if (type.isStruct()) {
  1966. auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
  1967. if (newLists != ioTypeMap.end()) {
  1968. if (storage == EvqVaryingIn && newLists->second.input)
  1969. ioVariable->getWritableType().setStruct(newLists->second.input);
  1970. else if (storage == EvqVaryingOut && newLists->second.output)
  1971. ioVariable->getWritableType().setStruct(newLists->second.output);
  1972. }
  1973. }
  1974. if (storage == EvqVaryingIn) {
  1975. correctInput(ioVariable->getWritableType().getQualifier());
  1976. if (language == EShLangTessEvaluation)
  1977. if (!ioVariable->getType().isArray())
  1978. ioVariable->getWritableType().getQualifier().patch = true;
  1979. } else {
  1980. correctOutput(ioVariable->getWritableType().getQualifier());
  1981. }
  1982. ioVariable->getWritableType().getQualifier().storage = storage;
  1983. fixBuiltInIoType(ioVariable->getWritableType());
  1984. return ioVariable;
  1985. };
  1986. // return value is actually a shader-scoped output (out)
  1987. if (function.getType().getBasicType() == EbtVoid) {
  1988. returnValue = nullptr;
  1989. } else {
  1990. if (language == EShLangTessControl) {
  1991. // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
  1992. // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
  1993. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  1994. TType outputType;
  1995. outputType.shallowCopy(function.getType());
  1996. // vertices has necessarily already been set when handling entry point attributes.
  1997. TArraySizes* arraySizes = new TArraySizes;
  1998. arraySizes->addInnerSize(intermediate.getVertices());
  1999. outputType.transferArraySizes(arraySizes);
  2000. clearUniformInputOutput(function.getWritableType().getQualifier());
  2001. returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
  2002. } else {
  2003. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2004. }
  2005. }
  2006. // parameters are actually shader-scoped inputs and outputs (in or out)
  2007. for (int i = 0; i < function.getParamCount(); i++) {
  2008. TType& paramType = *function[i].type;
  2009. if (paramType.getQualifier().isParamInput()) {
  2010. synthesizeEditedInput(paramType);
  2011. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
  2012. inputs.push_back(argAsGlobal);
  2013. }
  2014. if (paramType.getQualifier().isParamOutput()) {
  2015. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
  2016. outputs.push_back(argAsGlobal);
  2017. }
  2018. }
  2019. }
  2020. // An HLSL function that looks like an entry point, but is not,
  2021. // declares entry point IO built-ins, but these have to be undone.
  2022. void HlslParseContext::remapNonEntryPointIO(TFunction& function)
  2023. {
  2024. // return value
  2025. if (function.getType().getBasicType() != EbtVoid)
  2026. clearUniformInputOutput(function.getWritableType().getQualifier());
  2027. // parameters.
  2028. // References to structuredbuffer types are left unmodified
  2029. for (int i = 0; i < function.getParamCount(); i++)
  2030. if (!isReference(*function[i].type))
  2031. clearUniformInputOutput(function[i].type->getQualifier());
  2032. }
  2033. // Handle function returns, including type conversions to the function return type
  2034. // if necessary.
  2035. TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  2036. {
  2037. functionReturnsValue = true;
  2038. if (currentFunctionType->getBasicType() == EbtVoid) {
  2039. error(loc, "void function cannot return a value", "return", "");
  2040. return intermediate.addBranch(EOpReturn, loc);
  2041. } else if (*currentFunctionType != value->getType()) {
  2042. value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  2043. if (value && *currentFunctionType != value->getType())
  2044. value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
  2045. if (value == nullptr || *currentFunctionType != value->getType()) {
  2046. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  2047. return value;
  2048. }
  2049. }
  2050. return intermediate.addBranch(EOpReturn, value, loc);
  2051. }
  2052. void HlslParseContext::handleFunctionArgument(TFunction* function,
  2053. TIntermTyped*& arguments, TIntermTyped* newArg)
  2054. {
  2055. TParameter param = { 0, new TType, nullptr };
  2056. param.type->shallowCopy(newArg->getType());
  2057. function->addParameter(param);
  2058. if (arguments)
  2059. arguments = intermediate.growAggregate(arguments, newArg);
  2060. else
  2061. arguments = newArg;
  2062. }
  2063. // Position may require special handling: we can optionally invert Y.
  2064. // See: https://github.com/KhronosGroup/glslang/issues/1173
  2065. // https://github.com/KhronosGroup/glslang/issues/494
  2066. TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
  2067. TIntermTyped* left, TIntermTyped* right)
  2068. {
  2069. // If we are not asked for Y inversion, use a plain old assign.
  2070. if (!intermediate.getInvertY())
  2071. return intermediate.addAssign(op, left, right, loc);
  2072. // If we get here, we should invert Y.
  2073. TIntermAggregate* assignList = nullptr;
  2074. // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
  2075. TVariable* rhsTempVar = nullptr;
  2076. rhsTempVar = makeInternalVariable("@position", right->getType());
  2077. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2078. {
  2079. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2080. assignList = intermediate.growAggregate(assignList,
  2081. intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
  2082. }
  2083. // pos.y = -pos.y
  2084. {
  2085. const int Y = 1;
  2086. TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
  2087. TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
  2088. TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
  2089. TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
  2090. TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
  2091. const TType derefType(right->getType(), 0);
  2092. lhsElement->setType(derefType);
  2093. rhsElement->setType(derefType);
  2094. TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
  2095. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
  2096. }
  2097. // Assign the rhs temp (now with Y inversion) to the final output
  2098. {
  2099. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2100. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
  2101. }
  2102. assert(assignList != nullptr);
  2103. assignList->setOperator(EOpSequence);
  2104. return assignList;
  2105. }
  2106. // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
  2107. // these can be float scalar, float vector, or arrays of float scalar or float vector.
  2108. // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
  2109. // (e.g, both x and y components of a float2) out into the destination float array.
  2110. //
  2111. // The values are assigned to sequential members of the output array. The inner dimension
  2112. // is vector components. The outer dimension is array elements.
  2113. TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
  2114. TIntermTyped* left, TIntermTyped* right)
  2115. {
  2116. switch (language) {
  2117. case EShLangFragment:
  2118. case EShLangVertex:
  2119. case EShLangGeometry:
  2120. break;
  2121. default:
  2122. error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
  2123. return nullptr;
  2124. }
  2125. TVariable** clipCullVar = nullptr;
  2126. // Figure out if we are assigning to, or from, clip or cull distance.
  2127. const bool isOutput = isClipOrCullDistance(left->getType());
  2128. // This is the rvalue or lvalue holding the clip or cull distance.
  2129. TIntermTyped* clipCullNode = isOutput ? left : right;
  2130. // This is the value going into or out of the clip or cull distance.
  2131. TIntermTyped* internalNode = isOutput ? right : left;
  2132. const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
  2133. decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
  2134. // Refer to either the clip or the cull distance, depending on semantic.
  2135. switch (builtInType) {
  2136. case EbvClipDistance:
  2137. clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
  2138. semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
  2139. break;
  2140. case EbvCullDistance:
  2141. clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
  2142. semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
  2143. break;
  2144. // called invalidly: we expected a clip or a cull distance.
  2145. // static compile time problem: should not happen.
  2146. default: assert(0); return nullptr;
  2147. }
  2148. // This is the offset in the destination array of a given semantic's data
  2149. std::array<int, maxClipCullRegs> semanticOffset;
  2150. // Calculate offset of variable of semantic N in destination array
  2151. int arrayLoc = 0;
  2152. int vecItems = 0;
  2153. for (int x = 0; x < maxClipCullRegs; ++x) {
  2154. // See if we overflowed the vec4 packing
  2155. if ((vecItems + (*semanticNSize)[x]) > 4) {
  2156. arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
  2157. vecItems = 0;
  2158. }
  2159. semanticOffset[x] = arrayLoc;
  2160. vecItems += (*semanticNSize)[x];
  2161. arrayLoc += (*semanticNSize)[x];
  2162. }
  2163. // It can have up to 2 array dimensions (in the case of geometry shader inputs)
  2164. const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
  2165. const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
  2166. // vector sizes:
  2167. const int internalVectorSize = internalNode->getType().getVectorSize();
  2168. // array sizes, or 1 if it's not an array:
  2169. const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
  2170. const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
  2171. // The created type may be an array of arrays, e.g, for geometry shader inputs.
  2172. const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
  2173. // If we haven't created the output already, create it now.
  2174. if (*clipCullVar == nullptr) {
  2175. // ClipDistance and CullDistance are handled specially in the entry point input/output copy
  2176. // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
  2177. // into a float array, or vice versa. Here, we make the array the right size and type,
  2178. // which depends on the incoming data, which has several potential dimensions:
  2179. // * Semantic ID
  2180. // * vector size
  2181. // * array size
  2182. // Of those, semantic ID and array size cannot appear simultaneously.
  2183. //
  2184. // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
  2185. // array dimensions. The shader's declaration may have one or two array dimensions. One is always
  2186. // the geometry's dimension.
  2187. const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
  2188. const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
  2189. const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
  2190. TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
  2191. clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
  2192. // Create required array dimension
  2193. TArraySizes* arraySizes = new TArraySizes;
  2194. if (isImplicitlyArrayed)
  2195. arraySizes->addInnerSize(requiredOuterArraySize);
  2196. arraySizes->addInnerSize(requiredInnerArraySize);
  2197. clipCullType.transferArraySizes(arraySizes);
  2198. // Obtain symbol name: we'll use that for the symbol we introduce.
  2199. TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
  2200. assert(sym != nullptr);
  2201. // We are moving the semantic ID from the layout location, so it is no longer needed or
  2202. // desired there.
  2203. clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  2204. // Create variable and track its linkage
  2205. *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
  2206. trackLinkage(**clipCullVar);
  2207. }
  2208. // Create symbol for the clip or cull variable.
  2209. TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
  2210. // vector sizes:
  2211. const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
  2212. // array sizes, or 1 if it's not an array:
  2213. const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
  2214. const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
  2215. const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
  2216. // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
  2217. // fixBuiltInIoType() should have handled that upstream.
  2218. assert(clipCullSym->getType().isArray());
  2219. assert(clipCullSym->getType().getVectorSize() == 1);
  2220. assert(clipCullSym->getType().getBasicType() == EbtFloat);
  2221. // We may be creating multiple sub-assignments. This is an aggregate to hold them.
  2222. // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
  2223. TIntermAggregate* assignList = nullptr;
  2224. // Holds individual component assignments as we make them.
  2225. TIntermTyped* clipCullAssign = nullptr;
  2226. // If the types are homomorphic, use a simple assign. No need to mess about with
  2227. // individual components.
  2228. if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
  2229. clipCullInnerArraySize == internalInnerArraySize &&
  2230. clipCullOuterArraySize == internalOuterArraySize &&
  2231. clipCullVectorSize == internalVectorSize) {
  2232. if (isOutput)
  2233. clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
  2234. else
  2235. clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
  2236. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2237. assignList->setOperator(EOpSequence);
  2238. return assignList;
  2239. }
  2240. // We are going to copy each component of the internal (per array element if indicated) to sequential
  2241. // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
  2242. // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
  2243. int clipCullInnerArrayPos = semanticOffset[semanticId];
  2244. int clipCullOuterArrayPos = 0;
  2245. // Lambda to add an index to a node, set the type of the result, and return the new node.
  2246. const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
  2247. const TType derefType(node->getType(), 0);
  2248. node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
  2249. node->setType(derefType);
  2250. return node;
  2251. };
  2252. // Loop through every component of every element of the internal, and copy to or from the matching external.
  2253. for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
  2254. for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
  2255. for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
  2256. // clip/cull array member to read from / write to:
  2257. TIntermTyped* clipCullMember = clipCullSym;
  2258. // If implicitly arrayed, there is an outer array dimension involved
  2259. if (isImplicitlyArrayed)
  2260. clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
  2261. // Index into proper array position for clip cull member
  2262. clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
  2263. // if needed, start over with next outer array slice.
  2264. if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
  2265. clipCullInnerArrayPos = semanticOffset[semanticId];
  2266. ++clipCullOuterArrayPos;
  2267. }
  2268. // internal member to read from / write to:
  2269. TIntermTyped* internalMember = internalNode;
  2270. // If internal node has outer array dimension, index appropriately.
  2271. if (internalArrayDims > 1)
  2272. internalMember = addIndex(internalMember, internalOuterArrayPos);
  2273. // If internal node has inner array dimension, index appropriately.
  2274. if (internalArrayDims > 0)
  2275. internalMember = addIndex(internalMember, internalInnerArrayPos);
  2276. // If internal node is a vector, extract the component of interest.
  2277. if (internalNode->getType().isVector())
  2278. internalMember = addIndex(internalMember, internalComponent);
  2279. // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
  2280. if (isOutput)
  2281. clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
  2282. else
  2283. clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
  2284. // Track assignment in the sequence.
  2285. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2286. }
  2287. }
  2288. }
  2289. assert(assignList != nullptr);
  2290. assignList->setOperator(EOpSequence);
  2291. return assignList;
  2292. }
  2293. // Some simple source assignments need to be flattened to a sequence
  2294. // of AST assignments. Catch these and flatten, otherwise, pass through
  2295. // to intermediate.addAssign().
  2296. //
  2297. // Also, assignment to matrix swizzles requires multiple component assignments,
  2298. // intercept those as well.
  2299. TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2300. TIntermTyped* right)
  2301. {
  2302. if (left == nullptr || right == nullptr)
  2303. return nullptr;
  2304. // writing to opaques will require fixing transforms
  2305. if (left->getType().containsOpaque())
  2306. intermediate.setNeedsLegalization();
  2307. if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
  2308. return handleAssignToMatrixSwizzle(loc, op, left, right);
  2309. // Return true if the given node is an index operation into a split variable.
  2310. const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
  2311. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2312. if (binaryNode == nullptr)
  2313. return false;
  2314. return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
  2315. wasSplit(binaryNode->getLeft());
  2316. };
  2317. // Return true if this stage assigns clip position with potentially inverted Y
  2318. const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
  2319. return node->getType().getQualifier().builtIn == EbvPosition &&
  2320. (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
  2321. };
  2322. const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
  2323. const bool isSplitRight = wasSplit(right) || indexesSplit(right);
  2324. const bool isFlattenLeft = wasFlattened(left);
  2325. const bool isFlattenRight = wasFlattened(right);
  2326. // OK to do a single assign if neither side is split or flattened. Otherwise,
  2327. // fall through to a member-wise copy.
  2328. if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
  2329. // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
  2330. if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
  2331. const bool isOutput = isClipOrCullDistance(left->getType());
  2332. const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
  2333. return assignClipCullDistance(loc, op, semanticId, left, right);
  2334. } else if (assignsClipPos(left)) {
  2335. // Position can require special handling: see comment above assignPosition
  2336. return assignPosition(loc, op, left, right);
  2337. } else if (left->getQualifier().builtIn == EbvSampleMask) {
  2338. // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
  2339. // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
  2340. if (left->isArray() && !right->isArray()) {
  2341. const TType derefType(left->getType(), 0);
  2342. left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
  2343. left->setType(derefType);
  2344. // Fall through to add assign.
  2345. }
  2346. }
  2347. return intermediate.addAssign(op, left, right, loc);
  2348. }
  2349. TIntermAggregate* assignList = nullptr;
  2350. const TVector<TVariable*>* leftVariables = nullptr;
  2351. const TVector<TVariable*>* rightVariables = nullptr;
  2352. // A temporary to store the right node's value, so we don't keep indirecting into it
  2353. // if it's not a simple symbol.
  2354. TVariable* rhsTempVar = nullptr;
  2355. // If the RHS is a simple symbol node, we'll copy it for each member.
  2356. TIntermSymbol* cloneSymNode = nullptr;
  2357. int memberCount = 0;
  2358. // Track how many items there are to copy.
  2359. if (left->getType().isStruct())
  2360. memberCount = (int)left->getType().getStruct()->size();
  2361. if (left->getType().isArray())
  2362. memberCount = left->getType().getCumulativeArraySize();
  2363. if (isFlattenLeft)
  2364. leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
  2365. if (isFlattenRight) {
  2366. rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
  2367. } else {
  2368. // The RHS is not flattened. There are several cases:
  2369. // 1. 1 item to copy: Use the RHS directly.
  2370. // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
  2371. // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
  2372. if (memberCount <= 1) {
  2373. // case 1: we'll use the symbol directly below. Nothing to do.
  2374. } else {
  2375. if (right->getAsSymbolNode() != nullptr) {
  2376. // case 2: we'll copy the symbol per iteration below.
  2377. cloneSymNode = right->getAsSymbolNode();
  2378. } else {
  2379. // case 3: assign to a temp, and indirect into that.
  2380. rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
  2381. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2382. TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
  2383. // Add this to the aggregate being built.
  2384. assignList = intermediate.growAggregate(assignList,
  2385. intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
  2386. }
  2387. }
  2388. }
  2389. // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
  2390. // variables, which is awkward when copying between split and unsplit structures. This variable tracks
  2391. // array indirections so they can be percolated from outer structs to inner variables.
  2392. std::vector <int> arrayElement;
  2393. TStorageQualifier leftStorage = left->getType().getQualifier().storage;
  2394. TStorageQualifier rightStorage = right->getType().getQualifier().storage;
  2395. int leftOffset = findSubtreeOffset(*left);
  2396. int rightOffset = findSubtreeOffset(*right);
  2397. const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
  2398. bool flattened)
  2399. -> TIntermTyped * {
  2400. const bool split = isLeft ? isSplitLeft : isSplitRight;
  2401. TIntermTyped* subTree;
  2402. const TType derefType(type, member);
  2403. const TVariable* builtInVar = nullptr;
  2404. if ((flattened || split) && derefType.isBuiltIn()) {
  2405. auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
  2406. derefType.getQualifier().builtIn,
  2407. isLeft ? leftStorage : rightStorage));
  2408. if (splitPair != splitBuiltIns.end())
  2409. builtInVar = splitPair->second;
  2410. }
  2411. if (builtInVar != nullptr) {
  2412. // copy from interstage IO built-in if needed
  2413. subTree = intermediate.addSymbol(*builtInVar);
  2414. if (subTree->getType().isArray()) {
  2415. // Arrayness of builtIn symbols isn't handled by the normal recursion:
  2416. // it's been extracted and moved to the built-in.
  2417. if (!arrayElement.empty()) {
  2418. const TType splitDerefType(subTree->getType(), arrayElement.back());
  2419. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2420. intermediate.addConstantUnion(arrayElement.back(), loc), loc);
  2421. subTree->setType(splitDerefType);
  2422. } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
  2423. // This might also be a stage with arrayed outputs, in which case there's an index
  2424. // operation we should transfer to the output builtin.
  2425. const TType splitDerefType(subTree->getType(), 0);
  2426. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2427. splitNode->getAsBinaryNode()->getRight(), loc);
  2428. subTree->setType(splitDerefType);
  2429. }
  2430. }
  2431. } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
  2432. if (isLeft)
  2433. subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
  2434. else
  2435. subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
  2436. } else {
  2437. // Index operator if it's an aggregate, else EOpNull
  2438. const TOperator accessOp = type.isArray() ? EOpIndexDirect
  2439. : type.isStruct() ? EOpIndexDirectStruct
  2440. : EOpNull;
  2441. if (accessOp == EOpNull) {
  2442. subTree = splitNode;
  2443. } else {
  2444. subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
  2445. loc);
  2446. const TType splitDerefType(splitNode->getType(), splitMember);
  2447. subTree->setType(splitDerefType);
  2448. }
  2449. }
  2450. return subTree;
  2451. };
  2452. // Use the proper RHS node: a new symbol from a TVariable, copy
  2453. // of an TIntermSymbol node, or sometimes the right node directly.
  2454. right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
  2455. cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
  2456. right;
  2457. // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
  2458. // whole thing. So, we'll resort to an explicit type via std::function.
  2459. const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2460. bool topLevel)>
  2461. traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2462. bool topLevel) -> void {
  2463. // If we get here, we are assigning to or from a whole array or struct that must be
  2464. // flattened, so have to do member-by-member assignment:
  2465. bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
  2466. bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
  2467. if ((left->getType().isArray() || right->getType().isArray()) &&
  2468. (shouldFlattenSubsetLeft || isSplitLeft ||
  2469. shouldFlattenSubsetRight || isSplitRight)) {
  2470. const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
  2471. const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
  2472. // The arrays might not be the same size,
  2473. // e.g., if the size has been forced for EbvTessLevelInner/Outer.
  2474. const int elementsToCopy = std::min(elementsL, elementsR);
  2475. // array case
  2476. for (int element = 0; element < elementsToCopy; ++element) {
  2477. arrayElement.push_back(element);
  2478. // Add a new AST symbol node if we have a temp variable holding a complex RHS.
  2479. TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
  2480. shouldFlattenSubsetLeft);
  2481. TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
  2482. shouldFlattenSubsetRight);
  2483. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
  2484. element, shouldFlattenSubsetLeft)
  2485. : subLeft;
  2486. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
  2487. element, shouldFlattenSubsetRight)
  2488. : subRight;
  2489. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2490. arrayElement.pop_back();
  2491. }
  2492. } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
  2493. shouldFlattenSubsetRight || isSplitRight)) {
  2494. // struct case
  2495. const auto& membersL = *left->getType().getStruct();
  2496. const auto& membersR = *right->getType().getStruct();
  2497. // These track the members in the split structures corresponding to the same in the unsplit structures,
  2498. // which we traverse in parallel.
  2499. int memberL = 0;
  2500. int memberR = 0;
  2501. // Handle empty structure assignment
  2502. if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
  2503. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2504. for (int member = 0; member < int(membersL.size()); ++member) {
  2505. const TType& typeL = *membersL[member].type;
  2506. const TType& typeR = *membersR[member].type;
  2507. TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
  2508. shouldFlattenSubsetLeft);
  2509. TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
  2510. shouldFlattenSubsetRight);
  2511. // If there is no splitting, use the same values to avoid inefficiency.
  2512. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
  2513. memberL, shouldFlattenSubsetLeft)
  2514. : subLeft;
  2515. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
  2516. memberR, shouldFlattenSubsetRight)
  2517. : subRight;
  2518. if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
  2519. // Clip and cull distance built-in assignment is complex in its own right, and is handled in
  2520. // a separate function dedicated to that task. See comment above assignClipCullDistance;
  2521. const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
  2522. // Since all clip/cull semantics boil down to the same built-in type, we need to get the
  2523. // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
  2524. const TType derefType((isOutput ? left : right)->getType(), member);
  2525. const int semanticId = derefType.getQualifier().layoutLocation;
  2526. TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
  2527. subSplitLeft, subSplitRight);
  2528. assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
  2529. } else if (assignsClipPos(subSplitLeft)) {
  2530. // Position can require special handling: see comment above assignPosition
  2531. TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
  2532. assignList = intermediate.growAggregate(assignList, positionAssign, loc);
  2533. } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
  2534. !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
  2535. // If this is the final flattening (no nested types below to flatten)
  2536. // we'll copy the member, else recurse into the type hierarchy.
  2537. // However, if splitting the struct, that means we can copy a whole
  2538. // subtree here IFF it does not itself contain any interstage built-in
  2539. // IO variables, so we only have to recurse into it if there's something
  2540. // for splitting to do. That can save a lot of AST verbosity for
  2541. // a bunch of memberwise copies.
  2542. assignList = intermediate.growAggregate(assignList,
  2543. intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
  2544. loc);
  2545. } else {
  2546. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2547. }
  2548. memberL += (typeL.isBuiltIn() ? 0 : 1);
  2549. memberR += (typeR.isBuiltIn() ? 0 : 1);
  2550. }
  2551. } else {
  2552. // Member copy
  2553. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2554. }
  2555. };
  2556. TIntermTyped* splitLeft = left;
  2557. TIntermTyped* splitRight = right;
  2558. // If either left or right was a split structure, we must read or write it, but still have to
  2559. // parallel-recurse through the unsplit structure to identify the built-in IO vars.
  2560. // The left can be either a symbol, or an index into a symbol (e.g, array reference)
  2561. if (isSplitLeft) {
  2562. if (indexesSplit(left)) {
  2563. // Index case: Refer to the indexed symbol, if the left is an index operator.
  2564. const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2565. TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2566. splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
  2567. left->getAsBinaryNode()->getRight(), loc);
  2568. const TType derefType(splitLeftNonIo->getType(), 0);
  2569. splitLeft->setType(derefType);
  2570. } else {
  2571. // Symbol case: otherwise, if not indexed, we have the symbol directly.
  2572. const TIntermSymbol* symNode = left->getAsSymbolNode();
  2573. splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2574. }
  2575. }
  2576. if (isSplitRight)
  2577. splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
  2578. // This makes the whole assignment, recursing through subtypes as needed.
  2579. traverse(left, right, splitLeft, splitRight, true);
  2580. assert(assignList != nullptr);
  2581. assignList->setOperator(EOpSequence);
  2582. return assignList;
  2583. }
  2584. // An assignment to matrix swizzle must be decomposed into individual assignments.
  2585. // These must be selected component-wise from the RHS and stored component-wise
  2586. // into the LHS.
  2587. TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2588. TIntermTyped* right)
  2589. {
  2590. assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
  2591. if (op != EOpAssign)
  2592. error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
  2593. // isolate the matrix and swizzle nodes
  2594. TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
  2595. const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
  2596. // if the RHS isn't already a simple vector, let's store into one
  2597. TIntermSymbol* vector = right->getAsSymbolNode();
  2598. TIntermTyped* vectorAssign = nullptr;
  2599. if (vector == nullptr) {
  2600. // create a new intermediate vector variable to assign to
  2601. TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
  2602. vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
  2603. // assign the right to the new vector
  2604. vectorAssign = handleAssign(loc, op, vector, right);
  2605. }
  2606. // Assign the vector components to the matrix components.
  2607. // Store this as a sequence, so a single aggregate node represents this
  2608. // entire operation.
  2609. TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
  2610. TType columnType(matrix->getType(), 0);
  2611. TType componentType(columnType, 0);
  2612. TType indexType(EbtInt);
  2613. for (int i = 0; i < (int)swizzle.size(); i += 2) {
  2614. // the right component, single index into the RHS vector
  2615. TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
  2616. intermediate.addConstantUnion(i/2, loc), loc);
  2617. // the left component, double index into the LHS matrix
  2618. TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
  2619. intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
  2620. indexType, loc),
  2621. loc);
  2622. leftComp->setType(columnType);
  2623. leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
  2624. intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
  2625. indexType, loc),
  2626. loc);
  2627. leftComp->setType(componentType);
  2628. // Add the assignment to the aggregate
  2629. result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
  2630. }
  2631. result->setOp(EOpSequence);
  2632. return result;
  2633. }
  2634. //
  2635. // HLSL atomic operations have slightly different arguments than
  2636. // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
  2637. // This provides the post-decomposition equivalent opcode.
  2638. //
  2639. TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
  2640. {
  2641. switch (op) {
  2642. case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
  2643. case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
  2644. case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
  2645. case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
  2646. case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
  2647. case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
  2648. case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
  2649. case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
  2650. case EOpInterlockedCompareStore: // TODO: ...
  2651. default:
  2652. error(loc, "unknown atomic operation", "unknown op", "");
  2653. return EOpNull;
  2654. }
  2655. }
  2656. //
  2657. // Create a combined sampler/texture from separate sampler and texture.
  2658. //
  2659. TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
  2660. TIntermTyped* argSampler)
  2661. {
  2662. TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
  2663. txcombine->getSequence().push_back(argTex);
  2664. txcombine->getSequence().push_back(argSampler);
  2665. TSampler samplerType = argTex->getType().getSampler();
  2666. samplerType.combined = true;
  2667. // TODO:
  2668. // This block exists until the spec no longer requires shadow modes on texture objects.
  2669. // It can be deleted after that, along with the shadowTextureVariant member.
  2670. {
  2671. const bool shadowMode = argSampler->getType().getSampler().shadow;
  2672. TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
  2673. if (texSymbol == nullptr)
  2674. texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2675. if (texSymbol == nullptr) {
  2676. error(loc, "unable to find texture symbol", "", "");
  2677. return nullptr;
  2678. }
  2679. // This forces the texture's shadow state to be the sampler's
  2680. // shadow state. This depends on downstream optimization to
  2681. // DCE one variant in [shadow, nonshadow] if both are present,
  2682. // or the SPIR-V module would be invalid.
  2683. int newId = texSymbol->getId();
  2684. // Check to see if this texture has been given a shadow mode already.
  2685. // If so, look up the one we already have.
  2686. const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
  2687. if (textureShadowEntry != textureShadowVariant.end())
  2688. newId = textureShadowEntry->second->get(shadowMode);
  2689. else
  2690. textureShadowVariant[texSymbol->getId()] = new tShadowTextureSymbols;
  2691. // Sometimes we have to create another symbol (if this texture has been seen before,
  2692. // and we haven't created the form for this shadow mode).
  2693. if (newId == -1) {
  2694. TType texType;
  2695. texType.shallowCopy(argTex->getType());
  2696. texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
  2697. globalQualifierFix(loc, texType.getQualifier());
  2698. TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
  2699. trackLinkage(*newTexture);
  2700. newId = newTexture->getUniqueId();
  2701. }
  2702. assert(newId != -1);
  2703. if (textureShadowVariant.find(newId) == textureShadowVariant.end())
  2704. textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
  2705. textureShadowVariant[newId]->set(shadowMode, newId);
  2706. // Remember this shadow mode in the texture and the merged type.
  2707. argTex->getWritableType().getSampler().shadow = shadowMode;
  2708. samplerType.shadow = shadowMode;
  2709. texSymbol->switchId(newId);
  2710. }
  2711. txcombine->setType(TType(samplerType, EvqTemporary));
  2712. txcombine->setLoc(loc);
  2713. return txcombine;
  2714. }
  2715. // Return true if this a buffer type that has an associated counter buffer.
  2716. bool HlslParseContext::hasStructBuffCounter(const TType& type) const
  2717. {
  2718. switch (type.getQualifier().declaredBuiltIn) {
  2719. case EbvAppendConsume: // fall through...
  2720. case EbvRWStructuredBuffer: // ...
  2721. return true;
  2722. default:
  2723. return false; // the other structuredbuffer types do not have a counter.
  2724. }
  2725. }
  2726. void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
  2727. {
  2728. // Counter type
  2729. TType* counterType = new TType(EbtUint, EvqBuffer);
  2730. counterType->setFieldName(intermediate.implicitCounterName);
  2731. TTypeList* blockStruct = new TTypeList;
  2732. TTypeLoc member = { counterType, loc };
  2733. blockStruct->push_back(member);
  2734. TType blockType(blockStruct, "", counterType->getQualifier());
  2735. blockType.getQualifier().storage = EvqBuffer;
  2736. type.shallowCopy(blockType);
  2737. shareStructBufferType(type);
  2738. }
  2739. // declare counter for a structured buffer type
  2740. void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
  2741. {
  2742. // Bail out if not a struct buffer
  2743. if (! isStructBufferType(bufferType))
  2744. return;
  2745. if (! hasStructBuffCounter(bufferType))
  2746. return;
  2747. TType blockType;
  2748. counterBufferType(loc, blockType);
  2749. TString* blockName = new TString(intermediate.addCounterBufferName(name));
  2750. // Counter buffer is not yet in use
  2751. structBufferCounter[*blockName] = false;
  2752. shareStructBufferType(blockType);
  2753. declareBlock(loc, blockType, blockName);
  2754. }
  2755. // return the counter that goes with a given structuredbuffer
  2756. TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
  2757. {
  2758. // Bail out if not a struct buffer
  2759. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  2760. return nullptr;
  2761. const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
  2762. // Mark the counter as being used
  2763. structBufferCounter[counterBlockName] = true;
  2764. TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
  2765. TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
  2766. TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
  2767. counterMember->setType(TType(EbtUint));
  2768. return counterMember;
  2769. }
  2770. //
  2771. // Decompose structure buffer methods into AST
  2772. //
  2773. void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  2774. {
  2775. if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
  2776. return;
  2777. const TOperator op = node->getAsOperator()->getOp();
  2778. TIntermAggregate* argAggregate = arguments->getAsAggregate();
  2779. // Buffer is the object upon which method is called, so always arg 0
  2780. TIntermTyped* bufferObj = nullptr;
  2781. // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
  2782. if (argAggregate) {
  2783. if (argAggregate->getSequence().empty())
  2784. return;
  2785. bufferObj = argAggregate->getSequence()[0]->getAsTyped();
  2786. } else {
  2787. bufferObj = arguments->getAsSymbolNode();
  2788. }
  2789. if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
  2790. return;
  2791. // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
  2792. // This lambda adds something to it and returns the old value.
  2793. const auto incDecCounter = [&](int incval) -> TIntermTyped* {
  2794. TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
  2795. TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
  2796. if (counter == nullptr)
  2797. return nullptr;
  2798. TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
  2799. counterIncrement->setType(TType(EbtUint, EvqTemporary));
  2800. counterIncrement->setLoc(loc);
  2801. counterIncrement->getSequence().push_back(counter);
  2802. counterIncrement->getSequence().push_back(incrementValue);
  2803. return counterIncrement;
  2804. };
  2805. // Index to obtain the runtime sized array out of the buffer.
  2806. TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
  2807. if (argArray == nullptr)
  2808. return; // It might not be a struct buffer method.
  2809. switch (op) {
  2810. case EOpMethodLoad:
  2811. {
  2812. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2813. const TType& bufferType = bufferObj->getType();
  2814. const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
  2815. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2816. // buffer then, but that's what it calls itself.
  2817. const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
  2818. builtInType == EbvRWByteAddressBuffer);
  2819. if (isByteAddressBuffer)
  2820. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2821. intermediate.addConstantUnion(2, loc, true),
  2822. loc, TType(EbtInt));
  2823. // Index into the array to find the item being loaded.
  2824. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2825. node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2826. const TType derefType(argArray->getType(), 0);
  2827. node->setType(derefType);
  2828. }
  2829. break;
  2830. case EOpMethodLoad2:
  2831. case EOpMethodLoad3:
  2832. case EOpMethodLoad4:
  2833. {
  2834. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2835. TOperator constructOp = EOpNull;
  2836. int size = 0;
  2837. switch (op) {
  2838. case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
  2839. case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
  2840. case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
  2841. default: assert(0);
  2842. }
  2843. TIntermTyped* body = nullptr;
  2844. // First, we'll store the address in a variable to avoid multiple shifts
  2845. // (we must convert the byte address to an item address)
  2846. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2847. intermediate.addConstantUnion(2, loc, true),
  2848. loc, TType(EbtInt));
  2849. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2850. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2851. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2852. TIntermTyped* vec = nullptr;
  2853. // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
  2854. // address conversion.
  2855. for (int idx=0; idx<size; ++idx) {
  2856. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2857. // add index offset
  2858. if (idx != 0)
  2859. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
  2860. intermediate.addConstantUnion(idx, loc, true),
  2861. loc, TType(EbtInt));
  2862. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2863. : EOpIndexIndirect;
  2864. TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2865. TType derefType(argArray->getType(), 0);
  2866. derefType.getQualifier().makeTemporary();
  2867. indexVal->setType(derefType);
  2868. vec = intermediate.growAggregate(vec, indexVal);
  2869. }
  2870. vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
  2871. vec->getAsAggregate()->setOperator(constructOp);
  2872. body = intermediate.growAggregate(body, vec);
  2873. body->setType(vec->getType());
  2874. body->getAsAggregate()->setOperator(EOpSequence);
  2875. node = body;
  2876. }
  2877. break;
  2878. case EOpMethodStore:
  2879. case EOpMethodStore2:
  2880. case EOpMethodStore3:
  2881. case EOpMethodStore4:
  2882. {
  2883. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2884. TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
  2885. // Index into the array to find the item being loaded.
  2886. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2887. // buffer then, but that's what it calls itself).
  2888. int size = 0;
  2889. switch (op) {
  2890. case EOpMethodStore: size = 1; break;
  2891. case EOpMethodStore2: size = 2; break;
  2892. case EOpMethodStore3: size = 3; break;
  2893. case EOpMethodStore4: size = 4; break;
  2894. default: assert(0);
  2895. }
  2896. TIntermAggregate* body = nullptr;
  2897. // First, we'll store the address in a variable to avoid multiple shifts
  2898. // (we must convert the byte address to an item address)
  2899. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2900. intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
  2901. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2902. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2903. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2904. for (int idx=0; idx<size; ++idx) {
  2905. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2906. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  2907. // add index offset
  2908. if (idx != 0)
  2909. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
  2910. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2911. : EOpIndexIndirect;
  2912. TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2913. const TType derefType(argArray->getType(), 0);
  2914. lValue->setType(derefType);
  2915. TIntermTyped* rValue;
  2916. if (size == 1) {
  2917. rValue = argValue;
  2918. } else {
  2919. rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
  2920. const TType indexType(argValue->getType(), 0);
  2921. rValue->setType(indexType);
  2922. }
  2923. TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  2924. body = intermediate.growAggregate(body, assign);
  2925. }
  2926. body->setOperator(EOpSequence);
  2927. node = body;
  2928. }
  2929. break;
  2930. case EOpMethodGetDimensions:
  2931. {
  2932. const int numArgs = (int)argAggregate->getSequence().size();
  2933. TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
  2934. TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
  2935. TIntermAggregate* body = nullptr;
  2936. // Length output:
  2937. if (argArray->getType().isSizedArray()) {
  2938. const int length = argArray->getType().getOuterArraySize();
  2939. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
  2940. intermediate.addConstantUnion(length, loc, true), loc);
  2941. body = intermediate.growAggregate(body, assign, loc);
  2942. } else {
  2943. TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
  2944. argNumItems->getType());
  2945. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
  2946. body = intermediate.growAggregate(body, assign, loc);
  2947. }
  2948. // Stride output:
  2949. if (argStride != nullptr) {
  2950. int size;
  2951. int stride;
  2952. intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
  2953. argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
  2954. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
  2955. intermediate.addConstantUnion(stride, loc, true), loc);
  2956. body = intermediate.growAggregate(body, assign);
  2957. }
  2958. body->setOperator(EOpSequence);
  2959. node = body;
  2960. }
  2961. break;
  2962. case EOpInterlockedAdd:
  2963. case EOpInterlockedAnd:
  2964. case EOpInterlockedExchange:
  2965. case EOpInterlockedMax:
  2966. case EOpInterlockedMin:
  2967. case EOpInterlockedOr:
  2968. case EOpInterlockedXor:
  2969. case EOpInterlockedCompareExchange:
  2970. case EOpInterlockedCompareStore:
  2971. {
  2972. // We'll replace the first argument with the block dereference, and let
  2973. // downstream decomposition handle the rest.
  2974. TIntermSequence& sequence = argAggregate->getSequence();
  2975. TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
  2976. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
  2977. loc, TType(EbtInt));
  2978. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2979. TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2980. const TType derefType(argArray->getType(), 0);
  2981. element->setType(derefType);
  2982. // Replace the numeric byte offset parameter with array reference.
  2983. sequence[1] = element;
  2984. sequence.erase(sequence.begin(), sequence.begin()+1);
  2985. }
  2986. break;
  2987. case EOpMethodIncrementCounter:
  2988. {
  2989. node = incDecCounter(1);
  2990. break;
  2991. }
  2992. case EOpMethodDecrementCounter:
  2993. {
  2994. TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
  2995. node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
  2996. preIncValue->getType());
  2997. break;
  2998. }
  2999. case EOpMethodAppend:
  3000. {
  3001. TIntermTyped* oldCounter = incDecCounter(1);
  3002. TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
  3003. TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
  3004. const TType derefType(argArray->getType(), 0);
  3005. lValue->setType(derefType);
  3006. node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3007. break;
  3008. }
  3009. case EOpMethodConsume:
  3010. {
  3011. TIntermTyped* oldCounter = incDecCounter(-1);
  3012. TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
  3013. intermediate.addConstantUnion(-1, loc, true), loc,
  3014. oldCounter->getType());
  3015. node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
  3016. const TType derefType(argArray->getType(), 0);
  3017. node->setType(derefType);
  3018. break;
  3019. }
  3020. default:
  3021. break; // most pass through unchanged
  3022. }
  3023. }
  3024. // Create array of standard sample positions for given sample count.
  3025. // TODO: remove when a real method to query sample pos exists in SPIR-V.
  3026. TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
  3027. {
  3028. struct tSamplePos { float x, y; };
  3029. static const tSamplePos pos1[] = {
  3030. { 0.0/16.0, 0.0/16.0 },
  3031. };
  3032. // standard sample positions for 2, 4, 8, and 16 samples.
  3033. static const tSamplePos pos2[] = {
  3034. { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
  3035. };
  3036. static const tSamplePos pos4[] = {
  3037. {-2.0/16.0, -6.0/16.0 }, { 6.0/16.0, -2.0/16.0 }, {-6.0/16.0, 2.0/16.0 }, { 2.0/16.0, 6.0/16.0 },
  3038. };
  3039. static const tSamplePos pos8[] = {
  3040. { 1.0/16.0, -3.0/16.0 }, {-1.0/16.0, 3.0/16.0 }, { 5.0/16.0, 1.0/16.0 }, {-3.0/16.0, -5.0/16.0 },
  3041. {-5.0/16.0, 5.0/16.0 }, {-7.0/16.0, -1.0/16.0 }, { 3.0/16.0, 7.0/16.0 }, { 7.0/16.0, -7.0/16.0 },
  3042. };
  3043. static const tSamplePos pos16[] = {
  3044. { 1.0/16.0, 1.0/16.0 }, {-1.0/16.0, -3.0/16.0 }, {-3.0/16.0, 2.0/16.0 }, { 4.0/16.0, -1.0/16.0 },
  3045. {-5.0/16.0, -2.0/16.0 }, { 2.0/16.0, 5.0/16.0 }, { 5.0/16.0, 3.0/16.0 }, { 3.0/16.0, -5.0/16.0 },
  3046. {-2.0/16.0, 6.0/16.0 }, { 0.0/16.0, -7.0/16.0 }, {-4.0/16.0, -6.0/16.0 }, {-6.0/16.0, 4.0/16.0 },
  3047. {-8.0/16.0, 0.0/16.0 }, { 7.0/16.0, -4.0/16.0 }, { 6.0/16.0, 7.0/16.0 }, {-7.0/16.0, -8.0/16.0 },
  3048. };
  3049. const tSamplePos* sampleLoc = nullptr;
  3050. int numSamples = count;
  3051. switch (count) {
  3052. case 2: sampleLoc = pos2; break;
  3053. case 4: sampleLoc = pos4; break;
  3054. case 8: sampleLoc = pos8; break;
  3055. case 16: sampleLoc = pos16; break;
  3056. default:
  3057. sampleLoc = pos1;
  3058. numSamples = 1;
  3059. }
  3060. TConstUnionArray* values = new TConstUnionArray(numSamples*2);
  3061. for (int pos=0; pos<count; ++pos) {
  3062. TConstUnion x, y;
  3063. x.setDConst(sampleLoc[pos].x);
  3064. y.setDConst(sampleLoc[pos].y);
  3065. (*values)[pos*2+0] = x;
  3066. (*values)[pos*2+1] = y;
  3067. }
  3068. TType retType(EbtFloat, EvqConst, 2);
  3069. if (numSamples != 1) {
  3070. TArraySizes* arraySizes = new TArraySizes;
  3071. arraySizes->addInnerSize(numSamples);
  3072. retType.transferArraySizes(arraySizes);
  3073. }
  3074. return new TIntermConstantUnion(*values, retType);
  3075. }
  3076. //
  3077. // Decompose DX9 and DX10 sample intrinsics & object methods into AST
  3078. //
  3079. void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3080. {
  3081. if (node == nullptr || !node->getAsOperator())
  3082. return;
  3083. // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
  3084. const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
  3085. result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
  3086. TIntermTyped* convertedResult = nullptr;
  3087. TType retType;
  3088. getTextureReturnType(sampler, retType);
  3089. if (retType.isStruct()) {
  3090. // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
  3091. TIntermAggregate* conversionAggregate = new TIntermAggregate;
  3092. convertedResult = conversionAggregate;
  3093. // Convert vector output to return structure. We will need a temp symbol to copy the results to.
  3094. TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
  3095. // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
  3096. // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
  3097. TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
  3098. // Initial copy from texture to our sample result shadow.
  3099. TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
  3100. result, loc);
  3101. conversionAggregate->getSequence().push_back(shadowCopy);
  3102. unsigned vec4Pos = 0;
  3103. for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
  3104. const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
  3105. // Check for bad struct members. This should have been caught upstream. Complain, because
  3106. // wwe don't know what to do with it. This algorithm could be generalized to handle
  3107. // other things, e.g, sub-structures, but HLSL doesn't allow them.
  3108. if (!memberType.isVector() && !memberType.isScalar()) {
  3109. error(loc, "expected: scalar or vector type in texture structure", "", "");
  3110. return nullptr;
  3111. }
  3112. // Index into the struct variable to find the member to assign.
  3113. TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
  3114. intermediate.addSymbol(*structVar, loc),
  3115. intermediate.addConstantUnion(m, loc), loc);
  3116. structMember->setType(memberType);
  3117. // Assign each component of (possible) vector in struct member.
  3118. for (int component = 0; component < memberType.getVectorSize(); ++component) {
  3119. TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
  3120. intermediate.addSymbol(*sampleShadow, loc),
  3121. intermediate.addConstantUnion(vec4Pos++, loc), loc);
  3122. vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
  3123. TIntermTyped* memberAssign = nullptr;
  3124. if (memberType.isVector()) {
  3125. // Vector member: we need to create an access chain to the vector component.
  3126. TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
  3127. intermediate.addConstantUnion(component, loc), loc);
  3128. memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
  3129. } else {
  3130. // Scalar member: we can assign to it directly.
  3131. memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
  3132. }
  3133. conversionAggregate->getSequence().push_back(memberAssign);
  3134. }
  3135. }
  3136. // Add completed variable so the expression results in the whole struct value we just built.
  3137. conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
  3138. // Make it a sequence.
  3139. intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
  3140. } else {
  3141. // vector clamp the output if template vector type is smaller than sample result.
  3142. if (retType.getVectorSize() < node->getVectorSize()) {
  3143. // Too many components. Construct shorter vector from it.
  3144. const TOperator op = intermediate.mapTypeToConstructorOp(retType);
  3145. convertedResult = constructBuiltIn(retType, op, result, loc, false);
  3146. } else {
  3147. // Enough components. Use directly.
  3148. convertedResult = result;
  3149. }
  3150. }
  3151. convertedResult->setLoc(loc);
  3152. return convertedResult;
  3153. };
  3154. const TOperator op = node->getAsOperator()->getOp();
  3155. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3156. // Bail out if not a sampler method.
  3157. // Note though this is odd to do before checking the op, because the op
  3158. // could be something that takes the arguments, and the function in question
  3159. // takes the result of the op. So, this is not the final word.
  3160. if (arguments != nullptr) {
  3161. if (argAggregate == nullptr) {
  3162. if (arguments->getAsTyped()->getBasicType() != EbtSampler)
  3163. return;
  3164. } else {
  3165. if (argAggregate->getSequence().size() == 0 ||
  3166. argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
  3167. return;
  3168. }
  3169. }
  3170. switch (op) {
  3171. // **** DX9 intrinsics: ****
  3172. case EOpTexture:
  3173. {
  3174. // Texture with ddx & ddy is really gradient form in HLSL
  3175. if (argAggregate->getSequence().size() == 4)
  3176. node->getAsAggregate()->setOperator(EOpTextureGrad);
  3177. break;
  3178. }
  3179. case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
  3180. {
  3181. TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3182. TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3183. assert(argCoord->getVectorSize() == 4);
  3184. TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
  3185. TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
  3186. TOperator constructOp = EOpNull;
  3187. const TSampler &sampler = argSamp->getType().getSampler();
  3188. int coordSize = 0;
  3189. switch (sampler.dim)
  3190. {
  3191. case Esd1D: constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
  3192. case Esd2D: constructOp = EOpConstructVec2; coordSize = 2; break; // 2D
  3193. case Esd3D: constructOp = EOpConstructVec3; coordSize = 3; break; // 3D
  3194. case EsdCube: constructOp = EOpConstructVec3; coordSize = 3; break; // also 3D
  3195. default:
  3196. break;
  3197. }
  3198. TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
  3199. constructCoord->getSequence().push_back(argCoord);
  3200. constructCoord->setLoc(loc);
  3201. constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
  3202. TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
  3203. tex->getSequence().push_back(argSamp); // sampler
  3204. tex->getSequence().push_back(constructCoord); // coordinate
  3205. tex->getSequence().push_back(argLod); // lod
  3206. node = convertReturn(tex, sampler);
  3207. break;
  3208. }
  3209. case EOpTextureBias:
  3210. {
  3211. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3212. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3213. // HLSL puts bias in W component of coordinate. We extract it and add it to
  3214. // the argument list, instead
  3215. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3216. TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3217. TOperator constructOp = EOpNull;
  3218. const TSampler& sampler = arg0->getType().getSampler();
  3219. switch (sampler.dim) {
  3220. case Esd1D: constructOp = EOpConstructFloat; break; // 1D
  3221. case Esd2D: constructOp = EOpConstructVec2; break; // 2D
  3222. case Esd3D: constructOp = EOpConstructVec3; break; // 3D
  3223. case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
  3224. default: break;
  3225. }
  3226. TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
  3227. constructCoord->getSequence().push_back(arg1);
  3228. constructCoord->setLoc(loc);
  3229. // The input vector should never be less than 2, since there's always a bias.
  3230. // The max is for safety, and should be a no-op.
  3231. constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
  3232. TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
  3233. tex->getSequence().push_back(arg0); // sampler
  3234. tex->getSequence().push_back(constructCoord); // coordinate
  3235. tex->getSequence().push_back(bias); // bias
  3236. node = convertReturn(tex, sampler);
  3237. break;
  3238. }
  3239. // **** DX10 methods: ****
  3240. case EOpMethodSample: // fall through
  3241. case EOpMethodSampleBias: // ...
  3242. {
  3243. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3244. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3245. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3246. TIntermTyped* argBias = nullptr;
  3247. TIntermTyped* argOffset = nullptr;
  3248. const TSampler& sampler = argTex->getType().getSampler();
  3249. int nextArg = 3;
  3250. if (op == EOpMethodSampleBias) // SampleBias has a bias arg
  3251. argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3252. TOperator textureOp = EOpTexture;
  3253. if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
  3254. textureOp = EOpTextureOffset;
  3255. argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3256. }
  3257. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3258. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3259. txsample->getSequence().push_back(txcombine);
  3260. txsample->getSequence().push_back(argCoord);
  3261. if (argBias != nullptr)
  3262. txsample->getSequence().push_back(argBias);
  3263. if (argOffset != nullptr)
  3264. txsample->getSequence().push_back(argOffset);
  3265. node = convertReturn(txsample, sampler);
  3266. break;
  3267. }
  3268. case EOpMethodSampleGrad: // ...
  3269. {
  3270. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3271. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3272. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3273. TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
  3274. TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
  3275. TIntermTyped* argOffset = nullptr;
  3276. const TSampler& sampler = argTex->getType().getSampler();
  3277. TOperator textureOp = EOpTextureGrad;
  3278. if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
  3279. textureOp = EOpTextureGradOffset;
  3280. argOffset = argAggregate->getSequence()[5]->getAsTyped();
  3281. }
  3282. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3283. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3284. txsample->getSequence().push_back(txcombine);
  3285. txsample->getSequence().push_back(argCoord);
  3286. txsample->getSequence().push_back(argDDX);
  3287. txsample->getSequence().push_back(argDDY);
  3288. if (argOffset != nullptr)
  3289. txsample->getSequence().push_back(argOffset);
  3290. node = convertReturn(txsample, sampler);
  3291. break;
  3292. }
  3293. case EOpMethodGetDimensions:
  3294. {
  3295. // AST returns a vector of results, which we break apart component-wise into
  3296. // separate values to assign to the HLSL method's outputs, ala:
  3297. // tx . GetDimensions(width, height);
  3298. // float2 sizeQueryTemp = EOpTextureQuerySize
  3299. // width = sizeQueryTemp.X;
  3300. // height = sizeQueryTemp.Y;
  3301. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3302. const TType& texType = argTex->getType();
  3303. assert(texType.getBasicType() == EbtSampler);
  3304. const TSampler& sampler = texType.getSampler();
  3305. const TSamplerDim dim = sampler.dim;
  3306. const bool isImage = sampler.isImage();
  3307. const bool isMs = sampler.isMultiSample();
  3308. const int numArgs = (int)argAggregate->getSequence().size();
  3309. int numDims = 0;
  3310. switch (dim) {
  3311. case Esd1D: numDims = 1; break; // W
  3312. case Esd2D: numDims = 2; break; // W, H
  3313. case Esd3D: numDims = 3; break; // W, H, D
  3314. case EsdCube: numDims = 2; break; // W, H (cube)
  3315. case EsdBuffer: numDims = 1; break; // W (buffers)
  3316. case EsdRect: numDims = 2; break; // W, H (rect)
  3317. default:
  3318. assert(0 && "unhandled texture dimension");
  3319. }
  3320. // Arrayed adds another dimension for the number of array elements
  3321. if (sampler.isArrayed())
  3322. ++numDims;
  3323. // Establish whether the method itself is querying mip levels. This can be false even
  3324. // if the underlying query requires a MIP level, due to the available HLSL method overloads.
  3325. const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
  3326. // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
  3327. // True if:
  3328. // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
  3329. // or,
  3330. // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
  3331. const bool mipRequired =
  3332. ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
  3333. mipQuery; // 2...
  3334. // AST assumes integer return. Will be converted to float if required.
  3335. TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
  3336. sizeQuery->getSequence().push_back(argTex);
  3337. // If we're building an LOD query, add the LOD.
  3338. if (mipRequired) {
  3339. // If the base HLSL query had no MIP level given, use level 0.
  3340. TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
  3341. intermediate.addConstantUnion(0, loc, true);
  3342. sizeQuery->getSequence().push_back(queryLod);
  3343. }
  3344. sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
  3345. sizeQuery->setLoc(loc);
  3346. // Return value from size query
  3347. TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
  3348. tempArg->getWritableType().getQualifier().makeTemporary();
  3349. TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
  3350. intermediate.addSymbol(*tempArg, loc),
  3351. sizeQuery, loc);
  3352. // Compound statement for assigning outputs
  3353. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
  3354. // Index of first output parameter
  3355. const int outParamBase = mipQuery ? 2 : 1;
  3356. for (int compNum = 0; compNum < numDims; ++compNum) {
  3357. TIntermTyped* indexedOut = nullptr;
  3358. TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
  3359. if (numDims > 1) {
  3360. TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
  3361. indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
  3362. indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
  3363. indexedOut->setLoc(loc);
  3364. } else {
  3365. indexedOut = sizeQueryReturn;
  3366. }
  3367. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
  3368. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
  3369. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3370. }
  3371. // handle mip level parameter
  3372. if (mipQuery) {
  3373. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3374. TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
  3375. levelsQuery->getSequence().push_back(argTex);
  3376. levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3377. levelsQuery->setLoc(loc);
  3378. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
  3379. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3380. }
  3381. // 2DMS formats query # samples, which needs a different query op
  3382. if (sampler.isMultiSample()) {
  3383. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3384. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3385. samplesQuery->getSequence().push_back(argTex);
  3386. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3387. samplesQuery->setLoc(loc);
  3388. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
  3389. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3390. }
  3391. compoundStatement->setOperator(EOpSequence);
  3392. compoundStatement->setLoc(loc);
  3393. compoundStatement->setType(TType(EbtVoid));
  3394. node = compoundStatement;
  3395. break;
  3396. }
  3397. case EOpMethodSampleCmp: // fall through...
  3398. case EOpMethodSampleCmpLevelZero:
  3399. {
  3400. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3401. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3402. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3403. TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
  3404. TIntermTyped* argOffset = nullptr;
  3405. // Sampler argument should be a sampler.
  3406. if (argSamp->getType().getBasicType() != EbtSampler) {
  3407. error(loc, "expected: sampler type", "", "");
  3408. return;
  3409. }
  3410. // Sampler should be a SamplerComparisonState
  3411. if (! argSamp->getType().getSampler().isShadow()) {
  3412. error(loc, "expected: SamplerComparisonState", "", "");
  3413. return;
  3414. }
  3415. // optional offset value
  3416. if (argAggregate->getSequence().size() > 4)
  3417. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3418. const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
  3419. // AST wants comparison value as one of the texture coordinates
  3420. TOperator constructOp = EOpNull;
  3421. switch (coordDimWithCmpVal) {
  3422. // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
  3423. case 2: constructOp = EOpConstructVec2; break;
  3424. case 3: constructOp = EOpConstructVec3; break;
  3425. case 4: constructOp = EOpConstructVec4; break;
  3426. case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
  3427. default: assert(0); break;
  3428. }
  3429. TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
  3430. coordWithCmp->getSequence().push_back(argCoord);
  3431. if (coordDimWithCmpVal != 5) // cube array shadow is special.
  3432. coordWithCmp->getSequence().push_back(argCmpVal);
  3433. coordWithCmp->setLoc(loc);
  3434. coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
  3435. TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
  3436. if (argOffset != nullptr)
  3437. textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
  3438. // Create combined sampler & texture op
  3439. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3440. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3441. txsample->getSequence().push_back(txcombine);
  3442. txsample->getSequence().push_back(coordWithCmp);
  3443. if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
  3444. txsample->getSequence().push_back(argCmpVal);
  3445. // the LevelZero form uses 0 as an explicit LOD
  3446. if (op == EOpMethodSampleCmpLevelZero)
  3447. txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
  3448. // Add offset if present
  3449. if (argOffset != nullptr)
  3450. txsample->getSequence().push_back(argOffset);
  3451. txsample->setType(node->getType());
  3452. txsample->setLoc(loc);
  3453. node = txsample;
  3454. break;
  3455. }
  3456. case EOpMethodLoad:
  3457. {
  3458. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3459. TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
  3460. TIntermTyped* argOffset = nullptr;
  3461. TIntermTyped* lodComponent = nullptr;
  3462. TIntermTyped* coordSwizzle = nullptr;
  3463. const TSampler& sampler = argTex->getType().getSampler();
  3464. const bool isMS = sampler.isMultiSample();
  3465. const bool isBuffer = sampler.dim == EsdBuffer;
  3466. const bool isImage = sampler.isImage();
  3467. const TBasicType coordBaseType = argCoord->getType().getBasicType();
  3468. // Last component of coordinate is the mip level, for non-MS. we separate them here:
  3469. if (isMS || isBuffer || isImage) {
  3470. // MS, Buffer, and Image have no LOD
  3471. coordSwizzle = argCoord;
  3472. } else {
  3473. // Extract coordinate
  3474. int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
  3475. TSwizzleSelectors<TVectorSelector> coordFields;
  3476. for (int i = 0; i < swizzleSize; ++i)
  3477. coordFields.push_back(i);
  3478. TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
  3479. coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
  3480. coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
  3481. // Extract LOD
  3482. TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
  3483. lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
  3484. lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
  3485. }
  3486. const int numArgs = (int)argAggregate->getSequence().size();
  3487. const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
  3488. // Create texel fetch
  3489. const TOperator fetchOp = (isImage ? EOpImageLoad :
  3490. hasOffset ? EOpTextureFetchOffset :
  3491. EOpTextureFetch);
  3492. TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
  3493. // Build up the fetch
  3494. txfetch->getSequence().push_back(argTex);
  3495. txfetch->getSequence().push_back(coordSwizzle);
  3496. if (isMS) {
  3497. // add 2DMS sample index
  3498. TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
  3499. txfetch->getSequence().push_back(argSampleIdx);
  3500. } else if (isBuffer) {
  3501. // Nothing else to do for buffers.
  3502. } else if (isImage) {
  3503. // Nothing else to do for images.
  3504. } else {
  3505. // 2DMS and buffer have no LOD, but everything else does.
  3506. txfetch->getSequence().push_back(lodComponent);
  3507. }
  3508. // Obtain offset arg, if there is one.
  3509. if (hasOffset) {
  3510. const int offsetPos = (isMS ? 3 : 2);
  3511. argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
  3512. txfetch->getSequence().push_back(argOffset);
  3513. }
  3514. node = convertReturn(txfetch, sampler);
  3515. break;
  3516. }
  3517. case EOpMethodSampleLevel:
  3518. {
  3519. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3520. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3521. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3522. TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
  3523. TIntermTyped* argOffset = nullptr;
  3524. const TSampler& sampler = argTex->getType().getSampler();
  3525. const int numArgs = (int)argAggregate->getSequence().size();
  3526. if (numArgs == 5) // offset, if present
  3527. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3528. const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
  3529. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3530. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3531. txsample->getSequence().push_back(txcombine);
  3532. txsample->getSequence().push_back(argCoord);
  3533. txsample->getSequence().push_back(argLod);
  3534. if (argOffset != nullptr)
  3535. txsample->getSequence().push_back(argOffset);
  3536. node = convertReturn(txsample, sampler);
  3537. break;
  3538. }
  3539. case EOpMethodGather:
  3540. {
  3541. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3542. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3543. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3544. TIntermTyped* argOffset = nullptr;
  3545. // Offset is optional
  3546. if (argAggregate->getSequence().size() > 3)
  3547. argOffset = argAggregate->getSequence()[3]->getAsTyped();
  3548. const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
  3549. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3550. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3551. txgather->getSequence().push_back(txcombine);
  3552. txgather->getSequence().push_back(argCoord);
  3553. // Offset if not given is implicitly channel 0 (red)
  3554. if (argOffset != nullptr)
  3555. txgather->getSequence().push_back(argOffset);
  3556. txgather->setType(node->getType());
  3557. txgather->setLoc(loc);
  3558. node = txgather;
  3559. break;
  3560. }
  3561. case EOpMethodGatherRed: // fall through...
  3562. case EOpMethodGatherGreen: // ...
  3563. case EOpMethodGatherBlue: // ...
  3564. case EOpMethodGatherAlpha: // ...
  3565. case EOpMethodGatherCmpRed: // ...
  3566. case EOpMethodGatherCmpGreen: // ...
  3567. case EOpMethodGatherCmpBlue: // ...
  3568. case EOpMethodGatherCmpAlpha: // ...
  3569. {
  3570. int channel = 0; // the channel we are gathering
  3571. int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
  3572. switch (op) {
  3573. case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
  3574. case EOpMethodGatherRed: channel = 0; break;
  3575. case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
  3576. case EOpMethodGatherGreen: channel = 1; break;
  3577. case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
  3578. case EOpMethodGatherBlue: channel = 2; break;
  3579. case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
  3580. case EOpMethodGatherAlpha: channel = 3; break;
  3581. default: assert(0); break;
  3582. }
  3583. // For now, we have nothing to map the component-wise comparison forms
  3584. // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
  3585. // unimplemented error instead. Most of the machinery is here if that
  3586. // should ever become available. However, red can be passed through
  3587. // to OpImageDrefGather. G/B/A cannot, because that opcode does not
  3588. // accept a component.
  3589. if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
  3590. error(loc, "unimplemented: component-level gather compare", "", "");
  3591. return;
  3592. }
  3593. int arg = 0;
  3594. TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
  3595. TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
  3596. TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
  3597. TIntermTyped* argOffset = nullptr;
  3598. TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
  3599. // TIntermTyped* argStatus = nullptr; // TODO: residency
  3600. TIntermTyped* argCmp = nullptr;
  3601. const TSamplerDim dim = argTex->getType().getSampler().dim;
  3602. const int argSize = (int)argAggregate->getSequence().size();
  3603. bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
  3604. bool hasOffset1 = false;
  3605. bool hasOffset4 = false;
  3606. // Sampler argument should be a sampler.
  3607. if (argSamp->getType().getBasicType() != EbtSampler) {
  3608. error(loc, "expected: sampler type", "", "");
  3609. return;
  3610. }
  3611. // Cmp forms require SamplerComparisonState
  3612. if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
  3613. error(loc, "expected: SamplerComparisonState", "", "");
  3614. return;
  3615. }
  3616. // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
  3617. if (dim == Esd2D) {
  3618. hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
  3619. hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
  3620. }
  3621. assert(!(hasOffset1 && hasOffset4));
  3622. TOperator textureOp = EOpTextureGather;
  3623. // Compare forms have compare value
  3624. if (cmpValues != 0)
  3625. argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3626. // Some forms have single offset
  3627. if (hasOffset1) {
  3628. textureOp = EOpTextureGatherOffset; // single offset form
  3629. argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3630. }
  3631. // Some forms have 4 gather offsets
  3632. if (hasOffset4) {
  3633. textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
  3634. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3635. argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
  3636. }
  3637. // Residency status
  3638. if (hasStatus) {
  3639. // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
  3640. error(loc, "unimplemented: residency status", "", "");
  3641. return;
  3642. }
  3643. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3644. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3645. TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
  3646. txgather->getSequence().push_back(txcombine);
  3647. txgather->getSequence().push_back(argCoord);
  3648. // AST wants an array of 4 offsets, where HLSL has separate args. Here
  3649. // we construct an array from the separate args.
  3650. if (hasOffset4) {
  3651. TType arrayType(EbtInt, EvqTemporary, 2);
  3652. TArraySizes* arraySizes = new TArraySizes;
  3653. arraySizes->addInnerSize(4);
  3654. arrayType.transferArraySizes(arraySizes);
  3655. TIntermAggregate* initList = new TIntermAggregate(EOpNull);
  3656. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3657. initList->getSequence().push_back(argOffsets[offsetNum]);
  3658. argOffset = addConstructor(loc, initList, arrayType);
  3659. }
  3660. // Add comparison value if we have one
  3661. if (argCmp != nullptr)
  3662. txgather->getSequence().push_back(argCmp);
  3663. // Add offset (either 1, or an array of 4) if we have one
  3664. if (argOffset != nullptr)
  3665. txgather->getSequence().push_back(argOffset);
  3666. // Add channel value if the sampler is not shadow
  3667. if (! argSamp->getType().getSampler().isShadow())
  3668. txgather->getSequence().push_back(argChannel);
  3669. txgather->setType(node->getType());
  3670. txgather->setLoc(loc);
  3671. node = txgather;
  3672. break;
  3673. }
  3674. case EOpMethodCalculateLevelOfDetail:
  3675. case EOpMethodCalculateLevelOfDetailUnclamped:
  3676. {
  3677. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3678. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3679. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3680. TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
  3681. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3682. txquerylod->getSequence().push_back(txcombine);
  3683. txquerylod->getSequence().push_back(argCoord);
  3684. TIntermTyped* lodComponent = intermediate.addConstantUnion(
  3685. op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
  3686. loc, true);
  3687. TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
  3688. lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
  3689. node = lodComponentIdx;
  3690. break;
  3691. }
  3692. case EOpMethodGetSamplePosition:
  3693. {
  3694. // TODO: this entire decomposition exists because there is not yet a way to query
  3695. // the sample position directly through SPIR-V. Instead, we return fixed sample
  3696. // positions for common cases. *** If the sample positions are set differently,
  3697. // this will be wrong. ***
  3698. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3699. TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
  3700. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3701. samplesQuery->getSequence().push_back(argTex);
  3702. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3703. samplesQuery->setLoc(loc);
  3704. TIntermAggregate* compoundStatement = nullptr;
  3705. TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
  3706. outSampleCount->getWritableType().getQualifier().makeTemporary();
  3707. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
  3708. samplesQuery, loc);
  3709. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3710. TIntermTyped* idxtest[4];
  3711. // Create tests against 2, 4, 8, and 16 sample values
  3712. int count = 0;
  3713. for (int val = 2; val <= 16; val *= 2)
  3714. idxtest[count++] =
  3715. intermediate.addBinaryNode(EOpEqual,
  3716. intermediate.addSymbol(*outSampleCount, loc),
  3717. intermediate.addConstantUnion(val, loc),
  3718. loc, TType(EbtBool));
  3719. const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3720. // Create index ops into position arrays given sample index.
  3721. // TODO: should it be clamped?
  3722. TIntermTyped* index[4];
  3723. count = 0;
  3724. for (int val = 2; val <= 16; val *= 2) {
  3725. index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
  3726. index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
  3727. }
  3728. // Create expression as:
  3729. // (sampleCount == 2) ? pos2[idx] :
  3730. // (sampleCount == 4) ? pos4[idx] :
  3731. // (sampleCount == 8) ? pos8[idx] :
  3732. // (sampleCount == 16) ? pos16[idx] : float2(0,0);
  3733. TIntermTyped* test =
  3734. intermediate.addSelection(idxtest[0], index[0],
  3735. intermediate.addSelection(idxtest[1], index[1],
  3736. intermediate.addSelection(idxtest[2], index[2],
  3737. intermediate.addSelection(idxtest[3], index[3],
  3738. getSamplePosArray(1), loc), loc), loc), loc);
  3739. compoundStatement = intermediate.growAggregate(compoundStatement, test);
  3740. compoundStatement->setOperator(EOpSequence);
  3741. compoundStatement->setLoc(loc);
  3742. compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
  3743. node = compoundStatement;
  3744. break;
  3745. }
  3746. case EOpSubpassLoad:
  3747. {
  3748. const TIntermTyped* argSubpass =
  3749. argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
  3750. arguments->getAsTyped();
  3751. const TSampler& sampler = argSubpass->getType().getSampler();
  3752. // subpass load: the multisample form is overloaded. Here, we convert that to
  3753. // the EOpSubpassLoadMS opcode.
  3754. if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
  3755. node->getAsOperator()->setOp(EOpSubpassLoadMS);
  3756. node = convertReturn(node, sampler);
  3757. break;
  3758. }
  3759. default:
  3760. break; // most pass through unchanged
  3761. }
  3762. }
  3763. //
  3764. // Decompose geometry shader methods
  3765. //
  3766. void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3767. {
  3768. if (node == nullptr || !node->getAsOperator())
  3769. return;
  3770. const TOperator op = node->getAsOperator()->getOp();
  3771. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3772. switch (op) {
  3773. case EOpMethodAppend:
  3774. if (argAggregate) {
  3775. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3776. if (language != EShLangGeometry) {
  3777. node = nullptr;
  3778. return;
  3779. }
  3780. TIntermAggregate* sequence = nullptr;
  3781. TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
  3782. emit->setLoc(loc);
  3783. emit->setType(TType(EbtVoid));
  3784. TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
  3785. // This will be patched in finalization during finalizeAppendMethods()
  3786. sequence = intermediate.growAggregate(sequence, data, loc);
  3787. sequence = intermediate.growAggregate(sequence, emit);
  3788. sequence->setOperator(EOpSequence);
  3789. sequence->setLoc(loc);
  3790. sequence->setType(TType(EbtVoid));
  3791. gsAppends.push_back({sequence, loc});
  3792. node = sequence;
  3793. }
  3794. break;
  3795. case EOpMethodRestartStrip:
  3796. {
  3797. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3798. if (language != EShLangGeometry) {
  3799. node = nullptr;
  3800. return;
  3801. }
  3802. TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
  3803. cut->setLoc(loc);
  3804. cut->setType(TType(EbtVoid));
  3805. node = cut;
  3806. }
  3807. break;
  3808. default:
  3809. break; // most pass through unchanged
  3810. }
  3811. }
  3812. //
  3813. // Optionally decompose intrinsics to AST opcodes.
  3814. //
  3815. void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3816. {
  3817. // Helper to find image data for image atomics:
  3818. // OpImageLoad(image[idx])
  3819. // We take the image load apart and add its params to the atomic op aggregate node
  3820. const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
  3821. TIntermAggregate* loadOp = load->getAsAggregate();
  3822. if (loadOp == nullptr) {
  3823. error(loc, "unknown image type in atomic operation", "", "");
  3824. node = nullptr;
  3825. return;
  3826. }
  3827. atomic->getSequence().push_back(loadOp->getSequence()[0]);
  3828. atomic->getSequence().push_back(loadOp->getSequence()[1]);
  3829. };
  3830. // Return true if this is an imageLoad, which we will change to an image atomic.
  3831. const auto isImageParam = [](TIntermTyped* image) -> bool {
  3832. TIntermAggregate* imageAggregate = image->getAsAggregate();
  3833. return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
  3834. };
  3835. const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
  3836. TSymbol* symbol = symbolTable.find(name);
  3837. if (nullptr == symbol) {
  3838. type.getQualifier().builtIn = builtin;
  3839. TVariable* variable = new TVariable(new TString(name), type);
  3840. symbolTable.insert(*variable);
  3841. symbol = symbolTable.find(name);
  3842. assert(symbol && "Inserted symbol could not be found!");
  3843. }
  3844. return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
  3845. };
  3846. // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
  3847. // opcodes for compatibility with existing software stacks.
  3848. static const bool decomposeHlslIntrinsics = true;
  3849. if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
  3850. return;
  3851. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3852. TIntermUnary* fnUnary = node->getAsUnaryNode();
  3853. const TOperator op = node->getAsOperator()->getOp();
  3854. switch (op) {
  3855. case EOpGenMul:
  3856. {
  3857. // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
  3858. // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
  3859. // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
  3860. TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
  3861. TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
  3862. if (arg0->isVector() && arg1->isVector()) { // vec * vec
  3863. node->getAsAggregate()->setOperator(EOpDot);
  3864. } else {
  3865. node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
  3866. }
  3867. break;
  3868. }
  3869. case EOpRcp:
  3870. {
  3871. // rcp(a) -> 1 / a
  3872. TIntermTyped* arg0 = fnUnary->getOperand();
  3873. TBasicType type0 = arg0->getBasicType();
  3874. TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
  3875. node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
  3876. break;
  3877. }
  3878. case EOpAny: // fall through
  3879. case EOpAll:
  3880. {
  3881. TIntermTyped* typedArg = arguments->getAsTyped();
  3882. // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
  3883. // We'll convert here. Note that for efficiency, we could add a smarter
  3884. // decomposition for some type cases, e.g, maybe by decomposing a dot product.
  3885. if (typedArg->getType().getBasicType() != EbtBool) {
  3886. const TType boolType(EbtBool, EvqTemporary,
  3887. typedArg->getVectorSize(),
  3888. typedArg->getMatrixCols(),
  3889. typedArg->getMatrixRows(),
  3890. typedArg->isVector());
  3891. typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
  3892. node->getAsUnaryNode()->setOperand(typedArg);
  3893. }
  3894. break;
  3895. }
  3896. case EOpSaturate:
  3897. {
  3898. // saturate(a) -> clamp(a,0,1)
  3899. TIntermTyped* arg0 = fnUnary->getOperand();
  3900. TBasicType type0 = arg0->getBasicType();
  3901. TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
  3902. clamp->getSequence().push_back(arg0);
  3903. clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
  3904. clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
  3905. clamp->setLoc(loc);
  3906. clamp->setType(node->getType());
  3907. clamp->getWritableType().getQualifier().makeTemporary();
  3908. node = clamp;
  3909. break;
  3910. }
  3911. case EOpSinCos:
  3912. {
  3913. // sincos(a,b,c) -> b = sin(a), c = cos(a)
  3914. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  3915. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  3916. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
  3917. TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
  3918. TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
  3919. TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
  3920. TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
  3921. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
  3922. compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
  3923. compoundStatement->setOperator(EOpSequence);
  3924. compoundStatement->setLoc(loc);
  3925. compoundStatement->setType(TType(EbtVoid));
  3926. node = compoundStatement;
  3927. break;
  3928. }
  3929. case EOpClip:
  3930. {
  3931. // clip(a) -> if (any(a<0)) discard;
  3932. TIntermTyped* arg0 = fnUnary->getOperand();
  3933. TBasicType type0 = arg0->getBasicType();
  3934. TIntermTyped* compareNode = nullptr;
  3935. // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
  3936. if (!arg0->isScalar()) {
  3937. // component-wise compare: a < 0
  3938. TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
  3939. less->getSequence().push_back(arg0);
  3940. less->setLoc(loc);
  3941. // make vec or mat of bool matching dimensions of input
  3942. less->setType(TType(EbtBool, EvqTemporary,
  3943. arg0->getType().getVectorSize(),
  3944. arg0->getType().getMatrixCols(),
  3945. arg0->getType().getMatrixRows(),
  3946. arg0->getType().isVector()));
  3947. // calculate # of components for comparison const
  3948. const int constComponentCount =
  3949. std::max(arg0->getType().getVectorSize(), 1) *
  3950. std::max(arg0->getType().getMatrixCols(), 1) *
  3951. std::max(arg0->getType().getMatrixRows(), 1);
  3952. TConstUnion zero;
  3953. if (arg0->getType().isIntegerDomain())
  3954. zero.setDConst(0);
  3955. else
  3956. zero.setDConst(0.0);
  3957. TConstUnionArray zeros(constComponentCount, zero);
  3958. less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
  3959. compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
  3960. } else {
  3961. TIntermTyped* zero;
  3962. if (arg0->getType().isIntegerDomain())
  3963. zero = intermediate.addConstantUnion(0, loc, true);
  3964. else
  3965. zero = intermediate.addConstantUnion(0.0, type0, loc, true);
  3966. compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
  3967. }
  3968. TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
  3969. node = new TIntermSelection(compareNode, killNode, nullptr);
  3970. node->setLoc(loc);
  3971. break;
  3972. }
  3973. case EOpLog10:
  3974. {
  3975. // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
  3976. TIntermTyped* arg0 = fnUnary->getOperand();
  3977. TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
  3978. TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
  3979. node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
  3980. break;
  3981. }
  3982. case EOpDst:
  3983. {
  3984. // dest.x = 1;
  3985. // dest.y = src0.y * src1.y;
  3986. // dest.z = src0.z;
  3987. // dest.w = src1.w;
  3988. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  3989. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  3990. TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
  3991. TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
  3992. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3993. TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
  3994. TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
  3995. TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
  3996. TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3997. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  3998. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  3999. dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
  4000. dst->getSequence().push_back(src0z);
  4001. dst->getSequence().push_back(src1w);
  4002. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4003. dst->setLoc(loc);
  4004. node = dst;
  4005. break;
  4006. }
  4007. case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
  4008. case EOpInterlockedMin: // ...
  4009. case EOpInterlockedMax: // ...
  4010. case EOpInterlockedAnd: // ...
  4011. case EOpInterlockedOr: // ...
  4012. case EOpInterlockedXor: // ...
  4013. case EOpInterlockedExchange: // always has output arg
  4014. {
  4015. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4016. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
  4017. TIntermTyped* arg2 = nullptr;
  4018. if (argAggregate->getSequence().size() > 2)
  4019. arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4020. const bool isImage = isImageParam(arg0);
  4021. const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
  4022. TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
  4023. atomic->setType(arg0->getType());
  4024. atomic->getWritableType().getQualifier().makeTemporary();
  4025. atomic->setLoc(loc);
  4026. if (isImage) {
  4027. // orig_value = imageAtomicOp(image, loc, data)
  4028. imageAtomicParams(atomic, arg0);
  4029. atomic->getSequence().push_back(arg1);
  4030. if (argAggregate->getSequence().size() > 2) {
  4031. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4032. } else {
  4033. node = atomic; // no assignment needed, as there was no out var.
  4034. }
  4035. } else {
  4036. // Normal memory variable:
  4037. // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
  4038. if (argAggregate->getSequence().size() > 2) {
  4039. // optional output param is present. return value goes to arg2.
  4040. atomic->getSequence().push_back(arg0);
  4041. atomic->getSequence().push_back(arg1);
  4042. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4043. } else {
  4044. // Set the matching operator. Since output is absent, this is all we need to do.
  4045. node->getAsAggregate()->setOperator(atomicOp);
  4046. node->setType(atomic->getType());
  4047. }
  4048. }
  4049. break;
  4050. }
  4051. case EOpInterlockedCompareExchange:
  4052. {
  4053. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4054. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
  4055. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
  4056. TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
  4057. const bool isImage = isImageParam(arg0);
  4058. TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
  4059. atomic->setLoc(loc);
  4060. atomic->setType(arg2->getType());
  4061. atomic->getWritableType().getQualifier().makeTemporary();
  4062. if (isImage) {
  4063. imageAtomicParams(atomic, arg0);
  4064. } else {
  4065. atomic->getSequence().push_back(arg0);
  4066. }
  4067. atomic->getSequence().push_back(arg1);
  4068. atomic->getSequence().push_back(arg2);
  4069. node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
  4070. break;
  4071. }
  4072. case EOpEvaluateAttributeSnapped:
  4073. {
  4074. // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
  4075. // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
  4076. // iU = (iU<<28)>>28
  4077. // fU = ((float)iU)/16
  4078. // Targets might handle this natively, in which case they can disable
  4079. // decompositions.
  4080. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
  4081. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
  4082. TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
  4083. TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
  4084. handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
  4085. i28);
  4086. TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
  4087. TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
  4088. intermediate.addConversion(EOpConstructFloat,
  4089. TType(EbtFloat, EvqTemporary, 2), iU),
  4090. recip16);
  4091. TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
  4092. interp->getSequence().push_back(arg0);
  4093. interp->getSequence().push_back(floatOffset);
  4094. interp->setLoc(loc);
  4095. interp->setType(arg0->getType());
  4096. interp->getWritableType().getQualifier().makeTemporary();
  4097. node = interp;
  4098. break;
  4099. }
  4100. case EOpLit:
  4101. {
  4102. TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
  4103. TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
  4104. TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
  4105. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4106. // Ambient
  4107. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4108. // Diffuse:
  4109. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4110. TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
  4111. diffuse->getSequence().push_back(n_dot_l);
  4112. diffuse->getSequence().push_back(zero);
  4113. diffuse->setLoc(loc);
  4114. diffuse->setType(TType(EbtFloat));
  4115. dst->getSequence().push_back(diffuse);
  4116. // Specular:
  4117. TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
  4118. min_ndot->getSequence().push_back(n_dot_l);
  4119. min_ndot->getSequence().push_back(n_dot_h);
  4120. min_ndot->setLoc(loc);
  4121. min_ndot->setType(TType(EbtFloat));
  4122. TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
  4123. TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
  4124. dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
  4125. // One:
  4126. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4127. dst->setLoc(loc);
  4128. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4129. node = dst;
  4130. break;
  4131. }
  4132. case EOpAsDouble:
  4133. {
  4134. // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
  4135. // first construct a uint64.
  4136. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4137. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4138. if (arg0->getType().isVector()) { // TODO: ...
  4139. error(loc, "double2 conversion not implemented", "asdouble", "");
  4140. break;
  4141. }
  4142. TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
  4143. uint64->getSequence().push_back(arg0);
  4144. uint64->getSequence().push_back(arg1);
  4145. uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
  4146. uint64->setLoc(loc);
  4147. // bitcast uint2 to a double
  4148. TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
  4149. convert->getAsUnaryNode()->setOperand(uint64);
  4150. convert->setLoc(loc);
  4151. convert->setType(TType(EbtDouble, EvqTemporary));
  4152. node = convert;
  4153. break;
  4154. }
  4155. case EOpF16tof32:
  4156. {
  4157. // input uvecN with low 16 bits of each component holding a float16. convert to float32.
  4158. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4159. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  4160. const int vecSize = argValue->getType().getVectorSize();
  4161. TOperator constructOp = EOpNull;
  4162. switch (vecSize) {
  4163. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4164. case 2: constructOp = EOpConstructVec2; break;
  4165. case 3: constructOp = EOpConstructVec3; break;
  4166. case 4: constructOp = EOpConstructVec4; break;
  4167. default: assert(0); break;
  4168. }
  4169. // For scalar case, we don't need to construct another type.
  4170. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4171. if (result) {
  4172. result->setType(TType(EbtFloat, EvqTemporary, vecSize));
  4173. result->setLoc(loc);
  4174. }
  4175. for (int idx = 0; idx < vecSize; ++idx) {
  4176. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4177. TIntermTyped* component = argValue->getType().isVector() ?
  4178. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4179. if (component != argValue)
  4180. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4181. TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
  4182. unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
  4183. unpackOp->getAsUnaryNode()->setOperand(component);
  4184. unpackOp->setLoc(loc);
  4185. TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
  4186. if (result != nullptr) {
  4187. result->getSequence().push_back(lowOrder);
  4188. node = result;
  4189. } else {
  4190. node = lowOrder;
  4191. }
  4192. }
  4193. break;
  4194. }
  4195. case EOpF32tof16:
  4196. {
  4197. // input floatN converted to 16 bit float in low order bits of each component of uintN
  4198. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4199. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4200. const int vecSize = argValue->getType().getVectorSize();
  4201. TOperator constructOp = EOpNull;
  4202. switch (vecSize) {
  4203. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4204. case 2: constructOp = EOpConstructUVec2; break;
  4205. case 3: constructOp = EOpConstructUVec3; break;
  4206. case 4: constructOp = EOpConstructUVec4; break;
  4207. default: assert(0); break;
  4208. }
  4209. // For scalar case, we don't need to construct another type.
  4210. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4211. if (result) {
  4212. result->setType(TType(EbtUint, EvqTemporary, vecSize));
  4213. result->setLoc(loc);
  4214. }
  4215. for (int idx = 0; idx < vecSize; ++idx) {
  4216. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4217. TIntermTyped* component = argValue->getType().isVector() ?
  4218. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4219. if (component != argValue)
  4220. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4221. TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
  4222. vec2ComponentAndZero->getSequence().push_back(component);
  4223. vec2ComponentAndZero->getSequence().push_back(zero);
  4224. vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
  4225. vec2ComponentAndZero->setLoc(loc);
  4226. TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
  4227. packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
  4228. packOp->setLoc(loc);
  4229. packOp->setType(TType(EbtUint, EvqTemporary));
  4230. if (result != nullptr) {
  4231. result->getSequence().push_back(packOp);
  4232. node = result;
  4233. } else {
  4234. node = packOp;
  4235. }
  4236. }
  4237. break;
  4238. }
  4239. case EOpD3DCOLORtoUBYTE4:
  4240. {
  4241. // ivec4 ( x.zyxw * 255.001953 );
  4242. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4243. TSwizzleSelectors<TVectorSelector> selectors;
  4244. selectors.push_back(2);
  4245. selectors.push_back(1);
  4246. selectors.push_back(0);
  4247. selectors.push_back(3);
  4248. TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
  4249. TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
  4250. swizzled->setType(arg0->getType());
  4251. swizzled->getWritableType().getQualifier().makeTemporary();
  4252. TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
  4253. TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
  4254. rangeConverted->setType(arg0->getType());
  4255. rangeConverted->getWritableType().getQualifier().makeTemporary();
  4256. node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
  4257. node->setLoc(loc);
  4258. node->setType(TType(EbtInt, EvqTemporary, 4));
  4259. break;
  4260. }
  4261. case EOpIsFinite:
  4262. {
  4263. // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
  4264. // it to !isnan && !isinf
  4265. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4266. // We'll make a temporary in case the RHS is cmoplex
  4267. TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
  4268. tempArg->getWritableType().getQualifier().makeTemporary();
  4269. TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
  4270. intermediate.addSymbol(*tempArg, loc),
  4271. arg0, loc);
  4272. TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
  4273. const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
  4274. arg0->getMatrixRows());
  4275. TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
  4276. isnan->setType(boolType);
  4277. TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
  4278. notnan->setType(boolType);
  4279. TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
  4280. isinf->setType(boolType);
  4281. TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
  4282. notinf->setType(boolType);
  4283. TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
  4284. andNode->setType(boolType);
  4285. compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
  4286. compoundStatement->setOperator(EOpSequence);
  4287. compoundStatement->setLoc(loc);
  4288. compoundStatement->setType(boolType);
  4289. node = compoundStatement;
  4290. break;
  4291. }
  4292. case EOpWaveGetLaneCount:
  4293. {
  4294. // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
  4295. // so that it inhabits the symbol table, but has a user-invalid name
  4296. // in-case some source HLSL defined the symbol also).
  4297. TType type(EbtUint, EvqVaryingIn);
  4298. node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
  4299. break;
  4300. }
  4301. case EOpWaveGetLaneIndex:
  4302. {
  4303. // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
  4304. // symbol so that it inhabits the symbol table, but has a
  4305. // user-invalid name in-case some source HLSL defined the symbol
  4306. // also).
  4307. TType type(EbtUint, EvqVaryingIn);
  4308. node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
  4309. break;
  4310. }
  4311. case EOpWaveActiveCountBits:
  4312. {
  4313. // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
  4314. // uvec4 type.
  4315. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4316. // Get the uvec4 return from subgroupBallot().
  4317. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4318. EOpSubgroupBallot, true, arguments, uvec4Type);
  4319. // uint type.
  4320. TType uintType(EbtUint, EvqTemporary);
  4321. node = intermediate.addBuiltInFunctionCall(loc,
  4322. EOpSubgroupBallotBitCount, true, res, uintType);
  4323. break;
  4324. }
  4325. case EOpWavePrefixCountBits:
  4326. {
  4327. // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
  4328. // builtin
  4329. // uvec4 type.
  4330. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4331. // Get the uvec4 return from subgroupBallot().
  4332. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4333. EOpSubgroupBallot, true, arguments, uvec4Type);
  4334. // uint type.
  4335. TType uintType(EbtUint, EvqTemporary);
  4336. node = intermediate.addBuiltInFunctionCall(loc,
  4337. EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
  4338. break;
  4339. }
  4340. default:
  4341. break; // most pass through unchanged
  4342. }
  4343. }
  4344. //
  4345. // Handle seeing function call syntax in the grammar, which could be any of
  4346. // - .length() method
  4347. // - constructor
  4348. // - a call to a built-in function mapped to an operator
  4349. // - a call to a built-in function that will remain a function call (e.g., texturing)
  4350. // - user function
  4351. // - subroutine call (not implemented yet)
  4352. //
  4353. TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
  4354. {
  4355. TIntermTyped* result = nullptr;
  4356. TOperator op = function->getBuiltInOp();
  4357. if (op != EOpNull) {
  4358. //
  4359. // Then this should be a constructor.
  4360. // Don't go through the symbol table for constructors.
  4361. // Their parameters will be verified algorithmically.
  4362. //
  4363. TType type(EbtVoid); // use this to get the type back
  4364. if (! constructorError(loc, arguments, *function, op, type)) {
  4365. //
  4366. // It's a constructor, of type 'type'.
  4367. //
  4368. result = handleConstructor(loc, arguments, type);
  4369. if (result == nullptr) {
  4370. error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
  4371. return nullptr;
  4372. }
  4373. }
  4374. } else {
  4375. //
  4376. // Find it in the symbol table.
  4377. //
  4378. const TFunction* fnCandidate = nullptr;
  4379. bool builtIn = false;
  4380. int thisDepth = 0;
  4381. // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
  4382. // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
  4383. // It doesn't naturally fall out of processing an argument at a time in isolation.
  4384. if (function->getName() == "mul")
  4385. addGenMulArgumentConversion(loc, *function, arguments);
  4386. TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4387. // TODO: this needs improvement: there's no way at present to look up a signature in
  4388. // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
  4389. // It will have false positives, since it doesn't check arg counts or types.
  4390. if (arguments) {
  4391. // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
  4392. // look for either case.
  4393. TIntermTyped* arg0 = nullptr;
  4394. if (aggregate && aggregate->getSequence().size() > 0)
  4395. arg0 = aggregate->getSequence()[0]->getAsTyped();
  4396. else if (arguments->getAsSymbolNode())
  4397. arg0 = arguments->getAsSymbolNode();
  4398. if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
  4399. static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
  4400. if (function->getName().length() > methodPrefixSize &&
  4401. isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
  4402. const TString mangle = function->getName() + "(";
  4403. TSymbol* symbol = symbolTable.find(mangle, &builtIn);
  4404. if (symbol)
  4405. fnCandidate = symbol->getAsFunction();
  4406. }
  4407. }
  4408. }
  4409. if (fnCandidate == nullptr)
  4410. fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
  4411. if (fnCandidate) {
  4412. // This is a declared function that might map to
  4413. // - a built-in operator,
  4414. // - a built-in function not mapped to an operator, or
  4415. // - a user function.
  4416. // turn an implicit member-function resolution into an explicit call
  4417. TString callerName;
  4418. if (thisDepth == 0)
  4419. callerName = fnCandidate->getMangledName();
  4420. else {
  4421. // get the explicit (full) name of the function
  4422. callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
  4423. callerName += fnCandidate->getMangledName();
  4424. // insert the implicit calling argument
  4425. pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
  4426. }
  4427. // Convert 'in' arguments, so that types match.
  4428. // However, skip those that need expansion, that is covered next.
  4429. if (arguments)
  4430. addInputArgumentConversions(*fnCandidate, arguments);
  4431. // Expand arguments. Some arguments must physically expand to a different set
  4432. // than what the shader declared and passes.
  4433. if (arguments && !builtIn)
  4434. expandArguments(loc, *fnCandidate, arguments);
  4435. // Expansion may have changed the form of arguments
  4436. aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4437. op = fnCandidate->getBuiltInOp();
  4438. if (builtIn && op != EOpNull) {
  4439. // A function call mapped to a built-in operation.
  4440. result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
  4441. fnCandidate->getType());
  4442. if (result == nullptr) {
  4443. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  4444. "built in unary operator function. Type: %s",
  4445. static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
  4446. } else if (result->getAsOperator()) {
  4447. builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
  4448. }
  4449. } else {
  4450. // This is a function call not mapped to built-in operator.
  4451. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  4452. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  4453. TIntermAggregate* call = result->getAsAggregate();
  4454. call->setName(callerName);
  4455. // this is how we know whether the given function is a built-in function or a user-defined function
  4456. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  4457. // if builtIn == true, it's definitely a built-in function with EOpNull
  4458. if (! builtIn) {
  4459. call->setUserDefined();
  4460. intermediate.addToCallGraph(infoSink, currentCaller, callerName);
  4461. }
  4462. }
  4463. // for decompositions, since we want to operate on the function node, not the aggregate holding
  4464. // output conversions.
  4465. const TIntermTyped* fnNode = result;
  4466. decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
  4467. decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
  4468. decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
  4469. decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
  4470. // Create the qualifier list, carried in the AST for the call.
  4471. // Because some arguments expand to multiple arguments, the qualifier list will
  4472. // be longer than the formal parameter list.
  4473. if (result == fnNode && result->getAsAggregate()) {
  4474. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  4475. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  4476. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  4477. if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
  4478. // add buffer and counter buffer argument qualifier
  4479. qualifierList.push_back(qual);
  4480. qualifierList.push_back(qual);
  4481. } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
  4482. true)) {
  4483. // add structure member expansion
  4484. for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
  4485. qualifierList.push_back(qual);
  4486. } else {
  4487. // Normal 1:1 case
  4488. qualifierList.push_back(qual);
  4489. }
  4490. }
  4491. }
  4492. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  4493. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  4494. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  4495. // We don't do this is if there has been a decomposition, which will have added its own conversions
  4496. // for output parameters.
  4497. if (result == fnNode && result->getAsAggregate())
  4498. result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
  4499. }
  4500. }
  4501. // generic error recovery
  4502. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
  4503. // reduce cascades
  4504. if (result == nullptr)
  4505. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  4506. return result;
  4507. }
  4508. // An initial argument list is difficult: it can be null, or a single node,
  4509. // or an aggregate if more than one argument. Add one to the front, maintaining
  4510. // this lack of uniformity.
  4511. void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
  4512. {
  4513. if (arguments == nullptr)
  4514. arguments = front;
  4515. else if (arguments->getAsAggregate() != nullptr)
  4516. arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
  4517. else
  4518. arguments = intermediate.growAggregate(front, arguments);
  4519. }
  4520. //
  4521. // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
  4522. // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
  4523. // can look at both arguments insert explicit shape changes if required.
  4524. //
  4525. void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
  4526. {
  4527. TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
  4528. if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
  4529. // It really ought to have two arguments.
  4530. error(loc, "expected: mul arguments", "", "");
  4531. return;
  4532. }
  4533. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4534. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4535. if (arg0->isVector() && arg1->isVector()) {
  4536. // For:
  4537. // vec * vec: it's handled during intrinsic selection, so while we could do it here,
  4538. // we can also ignore it, which is easier.
  4539. } else if (arg0->isVector() && arg1->isMatrix()) {
  4540. // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4541. if (arg0->getVectorSize() < arg1->getMatrixCols()) {
  4542. // vec is smaller, so truncate larger mat dimension
  4543. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4544. 0, arg0->getVectorSize(), arg1->getMatrixRows());
  4545. arg1 = addConstructor(loc, arg1, truncType);
  4546. } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
  4547. // vec is larger, so truncate vec to mat size
  4548. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4549. arg1->getMatrixCols());
  4550. arg0 = addConstructor(loc, arg0, truncType);
  4551. }
  4552. } else if (arg0->isMatrix() && arg1->isVector()) {
  4553. // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4554. if (arg1->getVectorSize() < arg0->getMatrixRows()) {
  4555. // vec is smaller, so truncate larger mat dimension
  4556. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4557. 0, arg0->getMatrixCols(), arg1->getVectorSize());
  4558. arg0 = addConstructor(loc, arg0, truncType);
  4559. } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
  4560. // vec is larger, so truncate vec to mat size
  4561. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4562. arg0->getMatrixRows());
  4563. arg1 = addConstructor(loc, arg1, truncType);
  4564. }
  4565. } else if (arg0->isMatrix() && arg1->isMatrix()) {
  4566. // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
  4567. // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
  4568. if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
  4569. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4570. 0, arg0->getMatrixCols(), arg1->getMatrixCols());
  4571. arg0 = addConstructor(loc, arg0, truncType);
  4572. } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
  4573. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4574. 0, arg0->getMatrixRows(), arg1->getMatrixRows());
  4575. arg1 = addConstructor(loc, arg1, truncType);
  4576. }
  4577. } else {
  4578. // It's something with scalars: we'll just leave it alone. Function selection will handle it
  4579. // downstream.
  4580. }
  4581. // Warn if we altered one of the arguments
  4582. if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
  4583. warn(loc, "mul() matrix size mismatch", "", "");
  4584. // Put arguments back. (They might be unchanged, in which case this is harmless).
  4585. argAggregate->getSequence()[0] = arg0;
  4586. argAggregate->getSequence()[1] = arg1;
  4587. call[0].type = &arg0->getWritableType();
  4588. call[1].type = &arg1->getWritableType();
  4589. }
  4590. //
  4591. // Add any needed implicit conversions for function-call arguments to input parameters.
  4592. //
  4593. void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
  4594. {
  4595. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4596. // Replace a single argument with a single argument.
  4597. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4598. if (function.getParamCount() == 1)
  4599. arguments = arg;
  4600. else {
  4601. if (aggregate == nullptr)
  4602. arguments = arg;
  4603. else
  4604. aggregate->getSequence()[paramNum] = arg;
  4605. }
  4606. };
  4607. // Process each argument's conversion
  4608. for (int param = 0; param < function.getParamCount(); ++param) {
  4609. if (! function[param].type->getQualifier().isParamInput())
  4610. continue;
  4611. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4612. // is the single argument itself or its children are the arguments. Only one argument
  4613. // means take 'arguments' itself as the one argument.
  4614. TIntermTyped* arg = function.getParamCount() == 1
  4615. ? arguments->getAsTyped()
  4616. : (aggregate ?
  4617. aggregate->getSequence()[param]->getAsTyped() :
  4618. arguments->getAsTyped());
  4619. if (*function[param].type != arg->getType()) {
  4620. // In-qualified arguments just need an extra node added above the argument to
  4621. // convert to the correct type.
  4622. TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
  4623. if (convArg != nullptr)
  4624. convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
  4625. if (convArg != nullptr)
  4626. setArg(param, convArg);
  4627. else
  4628. error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
  4629. } else {
  4630. if (wasFlattened(arg)) {
  4631. // If both formal and calling arg are to be flattened, leave that to argument
  4632. // expansion, not conversion.
  4633. if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4634. // Will make a two-level subtree.
  4635. // The deepest will copy member-by-member to build the structure to pass.
  4636. // The level above that will be a two-operand EOpComma sequence that follows the copy by the
  4637. // object itself.
  4638. TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
  4639. internalAggregate->getWritableType().getQualifier().makeTemporary();
  4640. TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
  4641. internalAggregate->getName(),
  4642. internalAggregate->getType());
  4643. internalSymbolNode->setLoc(arg->getLoc());
  4644. // This makes the deepest level, the member-wise copy
  4645. TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
  4646. internalSymbolNode, arg)->getAsAggregate();
  4647. // Now, pair that with the resulting aggregate.
  4648. assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
  4649. assignAgg->setOperator(EOpComma);
  4650. assignAgg->setType(internalAggregate->getType());
  4651. setArg(param, assignAgg);
  4652. }
  4653. }
  4654. }
  4655. }
  4656. }
  4657. //
  4658. // Add any needed implicit expansion of calling arguments from what the shader listed to what's
  4659. // internally needed for the AST (given the constraints downstream).
  4660. //
  4661. void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
  4662. {
  4663. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4664. int functionParamNumberOffset = 0;
  4665. // Replace a single argument with a single argument.
  4666. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4667. if (function.getParamCount() + functionParamNumberOffset == 1)
  4668. arguments = arg;
  4669. else {
  4670. if (aggregate == nullptr)
  4671. arguments = arg;
  4672. else
  4673. aggregate->getSequence()[paramNum] = arg;
  4674. }
  4675. };
  4676. // Replace a single argument with a list of arguments
  4677. const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
  4678. if (args.size() == 1)
  4679. setArg(paramNum, args.front());
  4680. else if (args.size() > 1) {
  4681. if (function.getParamCount() + functionParamNumberOffset == 1) {
  4682. arguments = intermediate.makeAggregate(args.front());
  4683. std::for_each(args.begin() + 1, args.end(),
  4684. [&](TIntermTyped* arg) {
  4685. arguments = intermediate.growAggregate(arguments, arg);
  4686. });
  4687. } else {
  4688. auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
  4689. aggregate->getSequence().insert(it, args.begin(), args.end());
  4690. }
  4691. functionParamNumberOffset += (int)(args.size() - 1);
  4692. }
  4693. };
  4694. // Process each argument's conversion
  4695. for (int param = 0; param < function.getParamCount(); ++param) {
  4696. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4697. // is the single argument itself or its children are the arguments. Only one argument
  4698. // means take 'arguments' itself as the one argument.
  4699. TIntermTyped* arg = function.getParamCount() == 1
  4700. ? arguments->getAsTyped()
  4701. : (aggregate ?
  4702. aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
  4703. arguments->getAsTyped());
  4704. if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4705. // Need to pass the structure members instead of the structure.
  4706. TVector<TIntermTyped*> memberArgs;
  4707. for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
  4708. memberArgs.push_back(flattenAccess(arg, memb));
  4709. setArgList(param + functionParamNumberOffset, memberArgs);
  4710. }
  4711. }
  4712. // TODO: if we need both hidden counter args (below) and struct expansion (above)
  4713. // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
  4714. // parameters and arguments.
  4715. // If any argument is a pass-by-reference struct buffer with an associated counter
  4716. // buffer, we have to add another hidden parameter for that counter.
  4717. if (aggregate)
  4718. addStructBuffArguments(loc, aggregate);
  4719. }
  4720. //
  4721. // Add any needed implicit output conversions for function-call arguments. This
  4722. // can require a new tree topology, complicated further by whether the function
  4723. // has a return value.
  4724. //
  4725. // Returns a node of a subtree that evaluates to the return value of the function.
  4726. //
  4727. TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
  4728. {
  4729. assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
  4730. const TSourceLoc& loc = intermNode.getLoc();
  4731. TIntermSequence argSequence; // temp sequence for unary node args
  4732. if (intermNode.getAsUnaryNode())
  4733. argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
  4734. TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
  4735. const auto needsConversion = [&](int argNum) {
  4736. return function[argNum].type->getQualifier().isParamOutput() &&
  4737. (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
  4738. shouldConvertLValue(arguments[argNum]) ||
  4739. wasFlattened(arguments[argNum]->getAsTyped()));
  4740. };
  4741. // Will there be any output conversions?
  4742. bool outputConversions = false;
  4743. for (int i = 0; i < function.getParamCount(); ++i) {
  4744. if (needsConversion(i)) {
  4745. outputConversions = true;
  4746. break;
  4747. }
  4748. }
  4749. if (! outputConversions)
  4750. return &intermNode;
  4751. // Setup for the new tree, if needed:
  4752. //
  4753. // Output conversions need a different tree topology.
  4754. // Out-qualified arguments need a temporary of the correct type, with the call
  4755. // followed by an assignment of the temporary to the original argument:
  4756. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  4757. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  4758. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  4759. TIntermTyped* conversionTree = nullptr;
  4760. TVariable* tempRet = nullptr;
  4761. if (intermNode.getBasicType() != EbtVoid) {
  4762. // do the "tempRet = function(...), " bit from above
  4763. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  4764. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4765. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
  4766. } else
  4767. conversionTree = &intermNode;
  4768. conversionTree = intermediate.makeAggregate(conversionTree);
  4769. // Process each argument's conversion
  4770. for (int i = 0; i < function.getParamCount(); ++i) {
  4771. if (needsConversion(i)) {
  4772. // Out-qualified arguments needing conversion need to use the topology setup above.
  4773. // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
  4774. // Make a temporary for what the function expects the argument to look like.
  4775. TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
  4776. tempArg->getWritableType().getQualifier().makeTemporary();
  4777. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
  4778. // This makes the deepest level, the member-wise copy
  4779. TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
  4780. tempArgNode);
  4781. tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
  4782. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  4783. // replace the argument with another node for the same tempArg variable
  4784. arguments[i] = intermediate.addSymbol(*tempArg, loc);
  4785. }
  4786. }
  4787. // Finalize the tree topology (see bigger comment above).
  4788. if (tempRet) {
  4789. // do the "..., tempRet" bit from above
  4790. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4791. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
  4792. }
  4793. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
  4794. return conversionTree;
  4795. }
  4796. //
  4797. // Add any needed "hidden" counter buffer arguments for function calls.
  4798. //
  4799. // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
  4800. //
  4801. void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
  4802. {
  4803. // See if there are any SB types with counters.
  4804. const bool hasStructBuffArg =
  4805. std::any_of(aggregate->getSequence().begin(),
  4806. aggregate->getSequence().end(),
  4807. [this](const TIntermNode* node) {
  4808. return (node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
  4809. });
  4810. // Nothing to do, if we didn't find one.
  4811. if (! hasStructBuffArg)
  4812. return;
  4813. TIntermSequence argsWithCounterBuffers;
  4814. for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
  4815. argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
  4816. if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
  4817. const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
  4818. if (blockSym != nullptr) {
  4819. TType counterType;
  4820. counterBufferType(loc, counterType);
  4821. const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
  4822. TVariable* variable = makeInternalVariable(counterBlockName, counterType);
  4823. // Mark this buffer's counter block as being in use
  4824. structBufferCounter[counterBlockName] = true;
  4825. TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
  4826. argsWithCounterBuffers.push_back(sym);
  4827. }
  4828. }
  4829. }
  4830. // Swap with the temp list we've built up.
  4831. aggregate->getSequence().swap(argsWithCounterBuffers);
  4832. }
  4833. //
  4834. // Do additional checking of built-in function calls that is not caught
  4835. // by normal semantic checks on argument type, extension tagging, etc.
  4836. //
  4837. // Assumes there has been a semantically correct match to a built-in function prototype.
  4838. //
  4839. void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  4840. {
  4841. // Set up convenience accessors to the argument(s). There is almost always
  4842. // multiple arguments for the cases below, but when there might be one,
  4843. // check the unaryArg first.
  4844. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  4845. const TIntermTyped* unaryArg = nullptr;
  4846. const TIntermTyped* arg0 = nullptr;
  4847. if (callNode.getAsAggregate()) {
  4848. argp = &callNode.getAsAggregate()->getSequence();
  4849. if (argp->size() > 0)
  4850. arg0 = (*argp)[0]->getAsTyped();
  4851. } else {
  4852. assert(callNode.getAsUnaryNode());
  4853. unaryArg = callNode.getAsUnaryNode()->getOperand();
  4854. arg0 = unaryArg;
  4855. }
  4856. const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
  4857. switch (callNode.getOp()) {
  4858. case EOpTextureGather:
  4859. case EOpTextureGatherOffset:
  4860. case EOpTextureGatherOffsets:
  4861. {
  4862. // Figure out which variants are allowed by what extensions,
  4863. // and what arguments must be constant for which situations.
  4864. TString featureString = fnCandidate.getName() + "(...)";
  4865. const char* feature = featureString.c_str();
  4866. int compArg = -1; // track which argument, if any, is the constant component argument
  4867. switch (callNode.getOp()) {
  4868. case EOpTextureGather:
  4869. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  4870. // otherwise, need GL_ARB_texture_gather.
  4871. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
  4872. fnCandidate[0].type->getSampler().shadow) {
  4873. if (! fnCandidate[0].type->getSampler().shadow)
  4874. compArg = 2;
  4875. }
  4876. break;
  4877. case EOpTextureGatherOffset:
  4878. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  4879. if (! fnCandidate[0].type->getSampler().shadow)
  4880. compArg = 3;
  4881. break;
  4882. case EOpTextureGatherOffsets:
  4883. if (! fnCandidate[0].type->getSampler().shadow)
  4884. compArg = 3;
  4885. break;
  4886. default:
  4887. break;
  4888. }
  4889. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  4890. if (aggArgs[compArg]->getAsConstantUnion()) {
  4891. int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  4892. if (value < 0 || value > 3)
  4893. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  4894. } else
  4895. error(loc, "must be a compile-time constant:", feature, "component argument");
  4896. }
  4897. break;
  4898. }
  4899. case EOpTextureOffset:
  4900. case EOpTextureFetchOffset:
  4901. case EOpTextureProjOffset:
  4902. case EOpTextureLodOffset:
  4903. case EOpTextureProjLodOffset:
  4904. case EOpTextureGradOffset:
  4905. case EOpTextureProjGradOffset:
  4906. {
  4907. // Handle texture-offset limits checking
  4908. // Pick which argument has to hold constant offsets
  4909. int arg = -1;
  4910. switch (callNode.getOp()) {
  4911. case EOpTextureOffset: arg = 2; break;
  4912. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
  4913. case EOpTextureProjOffset: arg = 2; break;
  4914. case EOpTextureLodOffset: arg = 3; break;
  4915. case EOpTextureProjLodOffset: arg = 3; break;
  4916. case EOpTextureGradOffset: arg = 4; break;
  4917. case EOpTextureProjGradOffset: arg = 4; break;
  4918. default:
  4919. assert(0);
  4920. break;
  4921. }
  4922. if (arg > 0) {
  4923. if (aggArgs[arg]->getAsConstantUnion() == nullptr)
  4924. error(loc, "argument must be compile-time constant", "texel offset", "");
  4925. else {
  4926. const TType& type = aggArgs[arg]->getAsTyped()->getType();
  4927. for (int c = 0; c < type.getVectorSize(); ++c) {
  4928. int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  4929. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  4930. error(loc, "value is out of range:", "texel offset",
  4931. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  4932. }
  4933. }
  4934. }
  4935. break;
  4936. }
  4937. case EOpTextureQuerySamples:
  4938. case EOpImageQuerySamples:
  4939. break;
  4940. case EOpImageAtomicAdd:
  4941. case EOpImageAtomicMin:
  4942. case EOpImageAtomicMax:
  4943. case EOpImageAtomicAnd:
  4944. case EOpImageAtomicOr:
  4945. case EOpImageAtomicXor:
  4946. case EOpImageAtomicExchange:
  4947. case EOpImageAtomicCompSwap:
  4948. break;
  4949. case EOpInterpolateAtCentroid:
  4950. case EOpInterpolateAtSample:
  4951. case EOpInterpolateAtOffset:
  4952. // Make sure the first argument is an interpolant, or an array element of an interpolant
  4953. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  4954. // It might still be an array element.
  4955. //
  4956. // We could check more, but the semantics of the first argument are already met; the
  4957. // only way to turn an array into a float/vec* is array dereference and swizzle.
  4958. //
  4959. // ES and desktop 4.3 and earlier: swizzles may not be used
  4960. // desktop 4.4 and later: swizzles may be used
  4961. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
  4962. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  4963. error(loc, "first argument must be an interpolant, or interpolant-array element",
  4964. fnCandidate.getName().c_str(), "");
  4965. }
  4966. break;
  4967. default:
  4968. break;
  4969. }
  4970. }
  4971. //
  4972. // Handle seeing something in a grammar production that can be done by calling
  4973. // a constructor.
  4974. //
  4975. // The constructor still must be "handled" by handleFunctionCall(), which will
  4976. // then call handleConstructor().
  4977. //
  4978. TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
  4979. {
  4980. TOperator op = intermediate.mapTypeToConstructorOp(type);
  4981. if (op == EOpNull) {
  4982. error(loc, "cannot construct this type", type.getBasicString(), "");
  4983. return nullptr;
  4984. }
  4985. TString empty("");
  4986. return new TFunction(&empty, type, op);
  4987. }
  4988. //
  4989. // Handle seeing a "COLON semantic" at the end of a type declaration,
  4990. // by updating the type according to the semantic.
  4991. //
  4992. void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
  4993. const TString& upperCase)
  4994. {
  4995. // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
  4996. // semantic number is >= limit, errorMsg is issued and 0 is returned.
  4997. // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
  4998. // accept those in lambda functions.
  4999. const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
  5000. size_t pos = semantic.find_last_not_of("0123456789");
  5001. if (pos == std::string::npos)
  5002. return 0u;
  5003. unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
  5004. if (limit != 0 && semanticNum >= limit) {
  5005. error(loc, errorMsg, semantic.c_str(), "");
  5006. return 0u;
  5007. }
  5008. return semanticNum;
  5009. };
  5010. switch(builtIn) {
  5011. case EbvNone:
  5012. // Get location numbers from fragment outputs, instead of
  5013. // auto-assigning them.
  5014. if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
  5015. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5016. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5017. } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
  5018. builtIn = EbvClipDistance;
  5019. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
  5020. } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
  5021. builtIn = EbvCullDistance;
  5022. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
  5023. }
  5024. break;
  5025. case EbvPosition:
  5026. // adjust for stage in/out
  5027. if (language == EShLangFragment)
  5028. builtIn = EbvFragCoord;
  5029. break;
  5030. case EbvFragStencilRef:
  5031. error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
  5032. break;
  5033. case EbvTessLevelInner:
  5034. case EbvTessLevelOuter:
  5035. qualifier.patch = true;
  5036. break;
  5037. default:
  5038. break;
  5039. }
  5040. if (qualifier.builtIn == EbvNone)
  5041. qualifier.builtIn = builtIn;
  5042. qualifier.semanticName = intermediate.addSemanticName(upperCase);
  5043. }
  5044. //
  5045. // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
  5046. //
  5047. // 'location' has the "c[Subcomponent]" part.
  5048. // 'component' points to the "component" part, or nullptr if not present.
  5049. //
  5050. void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
  5051. const glslang::TString* component)
  5052. {
  5053. if (location.size() == 0 || location[0] != 'c') {
  5054. error(loc, "expected 'c'", "packoffset", "");
  5055. return;
  5056. }
  5057. if (location.size() == 1)
  5058. return;
  5059. if (! isdigit(location[1])) {
  5060. error(loc, "expected number after 'c'", "packoffset", "");
  5061. return;
  5062. }
  5063. qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
  5064. if (component != nullptr) {
  5065. int componentOffset = 0;
  5066. switch ((*component)[0]) {
  5067. case 'x': componentOffset = 0; break;
  5068. case 'y': componentOffset = 4; break;
  5069. case 'z': componentOffset = 8; break;
  5070. case 'w': componentOffset = 12; break;
  5071. default:
  5072. componentOffset = -1;
  5073. break;
  5074. }
  5075. if (componentOffset < 0 || component->size() > 1) {
  5076. error(loc, "expected {x, y, z, w} for component", "packoffset", "");
  5077. return;
  5078. }
  5079. qualifier.layoutOffset += componentOffset;
  5080. }
  5081. }
  5082. //
  5083. // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
  5084. //
  5085. // 'profile' points to the shader_profile part, or nullptr if not present.
  5086. // 'desc' is the type# part.
  5087. //
  5088. void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
  5089. const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
  5090. {
  5091. if (profile != nullptr)
  5092. warn(loc, "ignoring shader_profile", "register", "");
  5093. if (desc.size() < 1) {
  5094. error(loc, "expected register type", "register", "");
  5095. return;
  5096. }
  5097. int regNumber = 0;
  5098. if (desc.size() > 1) {
  5099. if (isdigit(desc[1]))
  5100. regNumber = atoi(desc.substr(1, desc.size()).c_str());
  5101. else {
  5102. error(loc, "expected register number after register type", "register", "");
  5103. return;
  5104. }
  5105. }
  5106. // more information about register types see
  5107. // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
  5108. const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
  5109. switch (std::tolower(desc[0])) {
  5110. case 'c':
  5111. // c register is the register slot in the global const buffer
  5112. // each slot is a vector of 4 32 bit components
  5113. qualifier.layoutOffset = regNumber * 4 * 4;
  5114. break;
  5115. // const buffer register slot
  5116. case 'b':
  5117. // textrues and structured buffers
  5118. case 't':
  5119. // samplers
  5120. case 's':
  5121. // uav resources
  5122. case 'u':
  5123. // if nothing else has set the binding, do so now
  5124. // (other mechanisms override this one)
  5125. if (!qualifier.hasBinding())
  5126. qualifier.layoutBinding = regNumber + subComponent;
  5127. // This handles per-register layout sets numbers. For the global mode which sets
  5128. // every symbol to the same value, see setLinkageLayoutSets().
  5129. if ((resourceInfo.size() % 3) == 0) {
  5130. // Apply per-symbol resource set and binding.
  5131. for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
  5132. if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
  5133. qualifier.layoutSet = atoi(it[1].c_str());
  5134. qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
  5135. break;
  5136. }
  5137. }
  5138. }
  5139. break;
  5140. default:
  5141. warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
  5142. break;
  5143. }
  5144. // space
  5145. unsigned int setNumber;
  5146. const auto crackSpace = [&]() -> bool {
  5147. const int spaceLen = 5;
  5148. if (spaceDesc->size() < spaceLen + 1)
  5149. return false;
  5150. if (spaceDesc->compare(0, spaceLen, "space") != 0)
  5151. return false;
  5152. if (! isdigit((*spaceDesc)[spaceLen]))
  5153. return false;
  5154. setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
  5155. return true;
  5156. };
  5157. // if nothing else has set the set, do so now
  5158. // (other mechanisms override this one)
  5159. if (spaceDesc && !qualifier.hasSet()) {
  5160. if (! crackSpace()) {
  5161. error(loc, "expected spaceN", "register", "");
  5162. return;
  5163. }
  5164. qualifier.layoutSet = setNumber;
  5165. }
  5166. }
  5167. // Convert to a scalar boolean, or if not allowed by HLSL semantics,
  5168. // report an error and return nullptr.
  5169. TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
  5170. bool mustBeScalar)
  5171. {
  5172. if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
  5173. error(loc, "requires a scalar", "conditional expression", "");
  5174. return nullptr;
  5175. }
  5176. return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
  5177. condition);
  5178. }
  5179. //
  5180. // Same error message for all places assignments don't work.
  5181. //
  5182. void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5183. {
  5184. error(loc, "", op, "cannot convert from '%s' to '%s'",
  5185. right.c_str(), left.c_str());
  5186. }
  5187. //
  5188. // Same error message for all places unary operations don't work.
  5189. //
  5190. void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  5191. {
  5192. error(loc, " wrong operand type", op,
  5193. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  5194. op, operand.c_str());
  5195. }
  5196. //
  5197. // Same error message for all binary operations don't work.
  5198. //
  5199. void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5200. {
  5201. error(loc, " wrong operand types:", op,
  5202. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  5203. "a right operand of type '%s' (or there is no acceptable conversion)",
  5204. op, left.c_str(), right.c_str());
  5205. }
  5206. //
  5207. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  5208. // it was not found as a variable in the symbol table. If so, give the error
  5209. // message and insert a dummy variable in the symbol table to prevent future errors.
  5210. //
  5211. void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
  5212. {
  5213. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  5214. if (! symbol)
  5215. return;
  5216. if (symbol->getType().getBasicType() == EbtVoid) {
  5217. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
  5218. // Add to symbol table to prevent future error messages on the same name
  5219. if (symbol->getName().size() > 0) {
  5220. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  5221. symbolTable.insert(*fakeVariable);
  5222. // substitute a symbol node for this new variable
  5223. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  5224. }
  5225. }
  5226. }
  5227. //
  5228. // Both test, and if necessary spit out an error, to see if the node is really
  5229. // a constant.
  5230. //
  5231. void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  5232. {
  5233. if (node->getQualifier().storage != EvqConst)
  5234. error(node->getLoc(), "constant expression required", token, "");
  5235. }
  5236. //
  5237. // Both test, and if necessary spit out an error, to see if the node is really
  5238. // an integer.
  5239. //
  5240. void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
  5241. {
  5242. if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
  5243. return;
  5244. error(node->getLoc(), "scalar integer expression required", token, "");
  5245. }
  5246. //
  5247. // Both test, and if necessary spit out an error, to see if we are currently
  5248. // globally scoped.
  5249. //
  5250. void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  5251. {
  5252. if (! symbolTable.atGlobalLevel())
  5253. error(loc, "not allowed in nested scope", token, "");
  5254. }
  5255. bool HlslParseContext::builtInName(const TString& /*identifier*/)
  5256. {
  5257. return false;
  5258. }
  5259. //
  5260. // Make sure there is enough data and not too many arguments provided to the
  5261. // constructor to build something of the type of the constructor. Also returns
  5262. // the type of the constructor.
  5263. //
  5264. // Returns true if there was an error in construction.
  5265. //
  5266. bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
  5267. TOperator op, TType& type)
  5268. {
  5269. type.shallowCopy(function.getType());
  5270. bool constructingMatrix = false;
  5271. switch (op) {
  5272. case EOpConstructTextureSampler:
  5273. error(loc, "unhandled texture constructor", "constructor", "");
  5274. return true;
  5275. case EOpConstructMat2x2:
  5276. case EOpConstructMat2x3:
  5277. case EOpConstructMat2x4:
  5278. case EOpConstructMat3x2:
  5279. case EOpConstructMat3x3:
  5280. case EOpConstructMat3x4:
  5281. case EOpConstructMat4x2:
  5282. case EOpConstructMat4x3:
  5283. case EOpConstructMat4x4:
  5284. case EOpConstructDMat2x2:
  5285. case EOpConstructDMat2x3:
  5286. case EOpConstructDMat2x4:
  5287. case EOpConstructDMat3x2:
  5288. case EOpConstructDMat3x3:
  5289. case EOpConstructDMat3x4:
  5290. case EOpConstructDMat4x2:
  5291. case EOpConstructDMat4x3:
  5292. case EOpConstructDMat4x4:
  5293. case EOpConstructIMat2x2:
  5294. case EOpConstructIMat2x3:
  5295. case EOpConstructIMat2x4:
  5296. case EOpConstructIMat3x2:
  5297. case EOpConstructIMat3x3:
  5298. case EOpConstructIMat3x4:
  5299. case EOpConstructIMat4x2:
  5300. case EOpConstructIMat4x3:
  5301. case EOpConstructIMat4x4:
  5302. case EOpConstructUMat2x2:
  5303. case EOpConstructUMat2x3:
  5304. case EOpConstructUMat2x4:
  5305. case EOpConstructUMat3x2:
  5306. case EOpConstructUMat3x3:
  5307. case EOpConstructUMat3x4:
  5308. case EOpConstructUMat4x2:
  5309. case EOpConstructUMat4x3:
  5310. case EOpConstructUMat4x4:
  5311. case EOpConstructBMat2x2:
  5312. case EOpConstructBMat2x3:
  5313. case EOpConstructBMat2x4:
  5314. case EOpConstructBMat3x2:
  5315. case EOpConstructBMat3x3:
  5316. case EOpConstructBMat3x4:
  5317. case EOpConstructBMat4x2:
  5318. case EOpConstructBMat4x3:
  5319. case EOpConstructBMat4x4:
  5320. constructingMatrix = true;
  5321. break;
  5322. default:
  5323. break;
  5324. }
  5325. //
  5326. // Walk the arguments for first-pass checks and collection of information.
  5327. //
  5328. int size = 0;
  5329. bool constType = true;
  5330. bool full = false;
  5331. bool overFull = false;
  5332. bool matrixInMatrix = false;
  5333. bool arrayArg = false;
  5334. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  5335. if (function[arg].type->isArray()) {
  5336. if (function[arg].type->isUnsizedArray()) {
  5337. // Can't construct from an unsized array.
  5338. error(loc, "array argument must be sized", "constructor", "");
  5339. return true;
  5340. }
  5341. arrayArg = true;
  5342. }
  5343. if (constructingMatrix && function[arg].type->isMatrix())
  5344. matrixInMatrix = true;
  5345. // 'full' will go to true when enough args have been seen. If we loop
  5346. // again, there is an extra argument.
  5347. if (full) {
  5348. // For vectors and matrices, it's okay to have too many components
  5349. // available, but not okay to have unused arguments.
  5350. overFull = true;
  5351. }
  5352. size += function[arg].type->computeNumComponents();
  5353. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  5354. full = true;
  5355. if (function[arg].type->getQualifier().storage != EvqConst)
  5356. constType = false;
  5357. }
  5358. if (constType)
  5359. type.getQualifier().storage = EvqConst;
  5360. if (type.isArray()) {
  5361. if (function.getParamCount() == 0) {
  5362. error(loc, "array constructor must have at least one argument", "constructor", "");
  5363. return true;
  5364. }
  5365. if (type.isUnsizedArray()) {
  5366. // auto adapt the constructor type to the number of arguments
  5367. type.changeOuterArraySize(function.getParamCount());
  5368. } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
  5369. error(loc, "array constructor needs one argument per array element", "constructor", "");
  5370. return true;
  5371. }
  5372. if (type.isArrayOfArrays()) {
  5373. // Types have to match, but we're still making the type.
  5374. // Finish making the type, and the comparison is done later
  5375. // when checking for conversion.
  5376. TArraySizes& arraySizes = *type.getArraySizes();
  5377. // At least the dimensionalities have to match.
  5378. if (! function[0].type->isArray() ||
  5379. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  5380. error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
  5381. return true;
  5382. }
  5383. if (arraySizes.isInnerUnsized()) {
  5384. // "Arrays of arrays ..., and the size for any dimension is optional"
  5385. // That means we need to adopt (from the first argument) the other array sizes into the type.
  5386. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  5387. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  5388. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  5389. }
  5390. }
  5391. }
  5392. }
  5393. }
  5394. // Some array -> array type casts are okay
  5395. if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
  5396. !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
  5397. type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
  5398. return false;
  5399. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  5400. error(loc, "constructing non-array constituent from array argument", "constructor", "");
  5401. return true;
  5402. }
  5403. if (matrixInMatrix && ! type.isArray()) {
  5404. return false;
  5405. }
  5406. if (overFull) {
  5407. error(loc, "too many arguments", "constructor", "");
  5408. return true;
  5409. }
  5410. if (op == EOpConstructStruct && ! type.isArray()) {
  5411. if (isScalarConstructor(node))
  5412. return false;
  5413. // Self-type construction: e.g, we can construct a struct from a single identically typed object.
  5414. if (function.getParamCount() == 1 && type == *function[0].type)
  5415. return false;
  5416. if ((int)type.getStruct()->size() != function.getParamCount()) {
  5417. error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
  5418. return true;
  5419. }
  5420. }
  5421. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  5422. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  5423. error(loc, "not enough data provided for construction", "constructor", "");
  5424. return true;
  5425. }
  5426. return false;
  5427. }
  5428. // See if 'node', in the context of constructing aggregates, is a scalar argument
  5429. // to a constructor.
  5430. //
  5431. bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
  5432. {
  5433. // Obviously, it must be a scalar, but an aggregate node might not be fully
  5434. // completed yet: holding a sequence of initializers under an aggregate
  5435. // would not yet be typed, so don't check it's type. This corresponds to
  5436. // the aggregate operator also not being set yet. (An aggregate operation
  5437. // that legitimately yields a scalar will have a getOp() of that operator,
  5438. // not EOpNull.)
  5439. return node->getAsTyped() != nullptr &&
  5440. node->getAsTyped()->isScalar() &&
  5441. (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
  5442. }
  5443. // Checks to see if a void variable has been declared and raise an error message for such a case
  5444. //
  5445. // returns true in case of an error
  5446. //
  5447. bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  5448. {
  5449. if (basicType == EbtVoid) {
  5450. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  5451. return true;
  5452. }
  5453. return false;
  5454. }
  5455. //
  5456. // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  5457. //
  5458. void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
  5459. {
  5460. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  5461. switch (qualifier.storage) {
  5462. case EvqIn:
  5463. qualifier.storage = EvqVaryingIn;
  5464. break;
  5465. case EvqOut:
  5466. qualifier.storage = EvqVaryingOut;
  5467. break;
  5468. default:
  5469. break;
  5470. }
  5471. }
  5472. //
  5473. // Merge characteristics of the 'src' qualifier into the 'dst'.
  5474. // If there is duplication, issue error messages, unless 'force'
  5475. // is specified, which means to just override default settings.
  5476. //
  5477. // Also, when force is false, it will be assumed that 'src' follows
  5478. // 'dst', for the purpose of error checking order for versions
  5479. // that require specific orderings of qualifiers.
  5480. //
  5481. void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
  5482. {
  5483. // Storage qualification
  5484. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  5485. dst.storage = src.storage;
  5486. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  5487. (dst.storage == EvqOut && src.storage == EvqIn))
  5488. dst.storage = EvqInOut;
  5489. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  5490. (dst.storage == EvqConst && src.storage == EvqIn))
  5491. dst.storage = EvqConstReadOnly;
  5492. // Layout qualifiers
  5493. mergeObjectLayoutQualifiers(dst, src, false);
  5494. // individual qualifiers
  5495. bool repeated = false;
  5496. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  5497. MERGE_SINGLETON(invariant);
  5498. MERGE_SINGLETON(noContraction);
  5499. MERGE_SINGLETON(centroid);
  5500. MERGE_SINGLETON(smooth);
  5501. MERGE_SINGLETON(flat);
  5502. MERGE_SINGLETON(nopersp);
  5503. MERGE_SINGLETON(patch);
  5504. MERGE_SINGLETON(sample);
  5505. MERGE_SINGLETON(coherent);
  5506. MERGE_SINGLETON(volatil);
  5507. MERGE_SINGLETON(restrict);
  5508. MERGE_SINGLETON(readonly);
  5509. MERGE_SINGLETON(writeonly);
  5510. MERGE_SINGLETON(specConstant);
  5511. MERGE_SINGLETON(nonUniform);
  5512. }
  5513. // used to flatten the sampler type space into a single dimension
  5514. // correlates with the declaration of defaultSamplerPrecision[]
  5515. int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
  5516. {
  5517. int arrayIndex = sampler.arrayed ? 1 : 0;
  5518. int shadowIndex = sampler.shadow ? 1 : 0;
  5519. int externalIndex = sampler.external ? 1 : 0;
  5520. return EsdNumDims *
  5521. (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
  5522. }
  5523. //
  5524. // Do size checking for an array type's size.
  5525. //
  5526. void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
  5527. {
  5528. bool isConst = false;
  5529. sizePair.size = 1;
  5530. sizePair.node = nullptr;
  5531. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  5532. if (constant) {
  5533. // handle true (non-specialization) constant
  5534. sizePair.size = constant->getConstArray()[0].getIConst();
  5535. isConst = true;
  5536. } else {
  5537. // see if it's a specialization constant instead
  5538. if (expr->getQualifier().isSpecConstant()) {
  5539. isConst = true;
  5540. sizePair.node = expr;
  5541. TIntermSymbol* symbol = expr->getAsSymbolNode();
  5542. if (symbol && symbol->getConstArray().size() > 0)
  5543. sizePair.size = symbol->getConstArray()[0].getIConst();
  5544. }
  5545. }
  5546. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  5547. error(loc, "array size must be a constant integer expression", "", "");
  5548. return;
  5549. }
  5550. if (sizePair.size <= 0) {
  5551. error(loc, "array size must be a positive integer", "", "");
  5552. return;
  5553. }
  5554. }
  5555. //
  5556. // Require array to be completely sized
  5557. //
  5558. void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  5559. {
  5560. if (arraySizes.hasUnsized())
  5561. error(loc, "array size required", "", "");
  5562. }
  5563. void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  5564. {
  5565. const TTypeList& structure = *type.getStruct();
  5566. for (int m = 0; m < (int)structure.size(); ++m) {
  5567. const TType& member = *structure[m].type;
  5568. if (member.isArray())
  5569. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  5570. }
  5571. }
  5572. //
  5573. // Do all the semantic checking for declaring or redeclaring an array, with and
  5574. // without a size, and make the right changes to the symbol table.
  5575. //
  5576. void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  5577. TSymbol*& symbol, bool track)
  5578. {
  5579. if (symbol == nullptr) {
  5580. bool currentScope;
  5581. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  5582. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  5583. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  5584. return;
  5585. }
  5586. if (symbol == nullptr || ! currentScope) {
  5587. //
  5588. // Successfully process a new definition.
  5589. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  5590. //
  5591. symbol = new TVariable(&identifier, type);
  5592. symbolTable.insert(*symbol);
  5593. if (track && symbolTable.atGlobalLevel())
  5594. trackLinkage(*symbol);
  5595. return;
  5596. }
  5597. if (symbol->getAsAnonMember()) {
  5598. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  5599. symbol = nullptr;
  5600. return;
  5601. }
  5602. }
  5603. //
  5604. // Process a redeclaration.
  5605. //
  5606. if (symbol == nullptr) {
  5607. error(loc, "array variable name expected", identifier.c_str(), "");
  5608. return;
  5609. }
  5610. // redeclareBuiltinVariable() should have already done the copyUp()
  5611. TType& existingType = symbol->getWritableType();
  5612. if (existingType.isSizedArray()) {
  5613. // be more lenient for input arrays to geometry shaders and tessellation control outputs,
  5614. // where the redeclaration is the same size
  5615. return;
  5616. }
  5617. existingType.updateArraySizes(type);
  5618. }
  5619. //
  5620. // Enforce non-initializer type/qualifier rules.
  5621. //
  5622. void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
  5623. TIntermTyped*& initializer)
  5624. {
  5625. //
  5626. // Make the qualifier make sense, given that there is an initializer.
  5627. //
  5628. if (initializer == nullptr) {
  5629. if (type.getQualifier().storage == EvqConst ||
  5630. type.getQualifier().storage == EvqConstReadOnly) {
  5631. initializer = intermediate.makeAggregate(loc);
  5632. warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
  5633. }
  5634. }
  5635. }
  5636. //
  5637. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  5638. // copy the symbol table's read-only built-in variable to the current
  5639. // global level, where it can be modified based on the passed in type.
  5640. //
  5641. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  5642. // needs to occur for it, not necessarily an error.
  5643. //
  5644. // Returns a redeclared and type-modified variable if a redeclared occurred.
  5645. //
  5646. TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
  5647. const TQualifier& /*qualifier*/,
  5648. const TShaderQualifiers& /*publicType*/)
  5649. {
  5650. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  5651. return nullptr;
  5652. return nullptr;
  5653. }
  5654. //
  5655. // Generate index to the array element in a structure buffer (SSBO)
  5656. //
  5657. TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
  5658. {
  5659. // Bail out if not a struct buffer
  5660. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  5661. return nullptr;
  5662. // Runtime sized array is always the last element.
  5663. const TTypeList* bufferStruct = buffer->getType().getStruct();
  5664. TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
  5665. TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
  5666. argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
  5667. return argArray;
  5668. }
  5669. //
  5670. // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
  5671. // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
  5672. //
  5673. TType* HlslParseContext::getStructBufferContentType(const TType& type) const
  5674. {
  5675. if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
  5676. return nullptr;
  5677. const int memberCount = (int)type.getStruct()->size();
  5678. assert(memberCount > 0);
  5679. TType* contentType = (*type.getStruct())[memberCount-1].type;
  5680. return contentType->isUnsizedArray() ? contentType : nullptr;
  5681. }
  5682. //
  5683. // If an existing struct buffer has a sharable type, then share it.
  5684. //
  5685. void HlslParseContext::shareStructBufferType(TType& type)
  5686. {
  5687. // PackOffset must be equivalent to share types on a per-member basis.
  5688. // Note: cannot use auto type due to recursion. Thus, this is a std::function.
  5689. const std::function<bool(TType& lhs, TType& rhs)>
  5690. compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
  5691. if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
  5692. return false;
  5693. if (lhs.isStruct() != rhs.isStruct())
  5694. return false;
  5695. if (lhs.isStruct() && rhs.isStruct()) {
  5696. if (lhs.getStruct()->size() != rhs.getStruct()->size())
  5697. return false;
  5698. for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
  5699. if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
  5700. return false;
  5701. }
  5702. return true;
  5703. };
  5704. // We need to compare certain qualifiers in addition to the type.
  5705. const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
  5706. if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
  5707. return false;
  5708. // If both are structures, recursively look for packOffset equality
  5709. // as well as type equality.
  5710. return compareQualifiers(lhs, rhs) && lhs == rhs;
  5711. };
  5712. // This is an exhaustive O(N) search, but real world shaders have
  5713. // only a small number of these.
  5714. for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
  5715. // If the deep structure matches, modulo qualifiers, use it
  5716. if (typeEqual(*structBufferTypes[idx], type)) {
  5717. type.shallowCopy(*structBufferTypes[idx]);
  5718. return;
  5719. }
  5720. }
  5721. // Otherwise, remember it:
  5722. TType* typeCopy = new TType;
  5723. typeCopy->shallowCopy(type);
  5724. structBufferTypes.push_back(typeCopy);
  5725. }
  5726. void HlslParseContext::paramFix(TType& type)
  5727. {
  5728. switch (type.getQualifier().storage) {
  5729. case EvqConst:
  5730. type.getQualifier().storage = EvqConstReadOnly;
  5731. break;
  5732. case EvqGlobal:
  5733. case EvqUniform:
  5734. case EvqTemporary:
  5735. type.getQualifier().storage = EvqIn;
  5736. break;
  5737. case EvqBuffer:
  5738. {
  5739. // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
  5740. correctUniform(type.getQualifier());
  5741. TQualifier bufferQualifier = globalBufferDefaults;
  5742. mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
  5743. bufferQualifier.storage = type.getQualifier().storage;
  5744. bufferQualifier.readonly = type.getQualifier().readonly;
  5745. bufferQualifier.coherent = type.getQualifier().coherent;
  5746. bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
  5747. type.getQualifier() = bufferQualifier;
  5748. break;
  5749. }
  5750. default:
  5751. break;
  5752. }
  5753. }
  5754. void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  5755. {
  5756. if (type.containsSpecializationSize())
  5757. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  5758. }
  5759. //
  5760. // Layout qualifier stuff.
  5761. //
  5762. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  5763. // This is before we know any type information for error checking.
  5764. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
  5765. {
  5766. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5767. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  5768. qualifier.layoutMatrix = ElmRowMajor;
  5769. return;
  5770. }
  5771. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  5772. qualifier.layoutMatrix = ElmColumnMajor;
  5773. return;
  5774. }
  5775. if (id == "push_constant") {
  5776. requireVulkan(loc, "push_constant");
  5777. qualifier.layoutPushConstant = true;
  5778. return;
  5779. }
  5780. if (language == EShLangGeometry || language == EShLangTessEvaluation) {
  5781. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5782. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5783. warn(loc, "ignored", id.c_str(), "");
  5784. return;
  5785. }
  5786. if (language == EShLangGeometry) {
  5787. if (id == TQualifier::getGeometryString(ElgPoints)) {
  5788. // publicType.shaderQualifiers.geometry = ElgPoints;
  5789. warn(loc, "ignored", id.c_str(), "");
  5790. return;
  5791. }
  5792. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  5793. // publicType.shaderQualifiers.geometry = ElgLineStrip;
  5794. warn(loc, "ignored", id.c_str(), "");
  5795. return;
  5796. }
  5797. if (id == TQualifier::getGeometryString(ElgLines)) {
  5798. // publicType.shaderQualifiers.geometry = ElgLines;
  5799. warn(loc, "ignored", id.c_str(), "");
  5800. return;
  5801. }
  5802. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  5803. // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  5804. warn(loc, "ignored", id.c_str(), "");
  5805. return;
  5806. }
  5807. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  5808. // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  5809. warn(loc, "ignored", id.c_str(), "");
  5810. return;
  5811. }
  5812. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  5813. // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  5814. warn(loc, "ignored", id.c_str(), "");
  5815. return;
  5816. }
  5817. } else {
  5818. assert(language == EShLangTessEvaluation);
  5819. // input primitive
  5820. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5821. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5822. warn(loc, "ignored", id.c_str(), "");
  5823. return;
  5824. }
  5825. if (id == TQualifier::getGeometryString(ElgQuads)) {
  5826. // publicType.shaderQualifiers.geometry = ElgQuads;
  5827. warn(loc, "ignored", id.c_str(), "");
  5828. return;
  5829. }
  5830. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  5831. // publicType.shaderQualifiers.geometry = ElgIsolines;
  5832. warn(loc, "ignored", id.c_str(), "");
  5833. return;
  5834. }
  5835. // vertex spacing
  5836. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  5837. // publicType.shaderQualifiers.spacing = EvsEqual;
  5838. warn(loc, "ignored", id.c_str(), "");
  5839. return;
  5840. }
  5841. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  5842. // publicType.shaderQualifiers.spacing = EvsFractionalEven;
  5843. warn(loc, "ignored", id.c_str(), "");
  5844. return;
  5845. }
  5846. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  5847. // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  5848. warn(loc, "ignored", id.c_str(), "");
  5849. return;
  5850. }
  5851. // triangle order
  5852. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  5853. // publicType.shaderQualifiers.order = EvoCw;
  5854. warn(loc, "ignored", id.c_str(), "");
  5855. return;
  5856. }
  5857. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  5858. // publicType.shaderQualifiers.order = EvoCcw;
  5859. warn(loc, "ignored", id.c_str(), "");
  5860. return;
  5861. }
  5862. // point mode
  5863. if (id == "point_mode") {
  5864. // publicType.shaderQualifiers.pointMode = true;
  5865. warn(loc, "ignored", id.c_str(), "");
  5866. return;
  5867. }
  5868. }
  5869. }
  5870. if (language == EShLangFragment) {
  5871. if (id == "origin_upper_left") {
  5872. // publicType.shaderQualifiers.originUpperLeft = true;
  5873. warn(loc, "ignored", id.c_str(), "");
  5874. return;
  5875. }
  5876. if (id == "pixel_center_integer") {
  5877. // publicType.shaderQualifiers.pixelCenterInteger = true;
  5878. warn(loc, "ignored", id.c_str(), "");
  5879. return;
  5880. }
  5881. if (id == "early_fragment_tests") {
  5882. // publicType.shaderQualifiers.earlyFragmentTests = true;
  5883. warn(loc, "ignored", id.c_str(), "");
  5884. return;
  5885. }
  5886. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
  5887. if (id == TQualifier::getLayoutDepthString(depth)) {
  5888. // publicType.shaderQualifiers.layoutDepth = depth;
  5889. warn(loc, "ignored", id.c_str(), "");
  5890. return;
  5891. }
  5892. }
  5893. if (id.compare(0, 13, "blend_support") == 0) {
  5894. bool found = false;
  5895. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  5896. if (id == TQualifier::getBlendEquationString(be)) {
  5897. requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
  5898. intermediate.addBlendEquation(be);
  5899. // publicType.shaderQualifiers.blendEquation = true;
  5900. warn(loc, "ignored", id.c_str(), "");
  5901. found = true;
  5902. break;
  5903. }
  5904. }
  5905. if (! found)
  5906. error(loc, "unknown blend equation", "blend_support", "");
  5907. return;
  5908. }
  5909. }
  5910. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  5911. }
  5912. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  5913. // This is before we know any type information for error checking.
  5914. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
  5915. const TIntermTyped* node)
  5916. {
  5917. const char* feature = "layout-id value";
  5918. // const char* nonLiteralFeature = "non-literal layout-id value";
  5919. integerCheck(node, feature);
  5920. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  5921. int value = 0;
  5922. if (constUnion) {
  5923. value = constUnion->getConstArray()[0].getIConst();
  5924. }
  5925. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5926. if (id == "offset") {
  5927. qualifier.layoutOffset = value;
  5928. return;
  5929. } else if (id == "align") {
  5930. // "The specified alignment must be a power of 2, or a compile-time error results."
  5931. if (! IsPow2(value))
  5932. error(loc, "must be a power of 2", "align", "");
  5933. else
  5934. qualifier.layoutAlign = value;
  5935. return;
  5936. } else if (id == "location") {
  5937. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  5938. error(loc, "location is too large", id.c_str(), "");
  5939. else
  5940. qualifier.layoutLocation = value;
  5941. return;
  5942. } else if (id == "set") {
  5943. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  5944. error(loc, "set is too large", id.c_str(), "");
  5945. else
  5946. qualifier.layoutSet = value;
  5947. return;
  5948. } else if (id == "binding") {
  5949. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  5950. error(loc, "binding is too large", id.c_str(), "");
  5951. else
  5952. qualifier.layoutBinding = value;
  5953. return;
  5954. } else if (id == "component") {
  5955. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  5956. error(loc, "component is too large", id.c_str(), "");
  5957. else
  5958. qualifier.layoutComponent = value;
  5959. return;
  5960. } else if (id.compare(0, 4, "xfb_") == 0) {
  5961. // "Any shader making any static use (after preprocessing) of any of these
  5962. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  5963. // capturing mode and hence responsible for describing the transform feedback
  5964. // setup."
  5965. intermediate.setXfbMode();
  5966. if (id == "xfb_buffer") {
  5967. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  5968. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  5969. if (value >= resources.maxTransformFeedbackBuffers)
  5970. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
  5971. resources.maxTransformFeedbackBuffers);
  5972. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  5973. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
  5974. else
  5975. qualifier.layoutXfbBuffer = value;
  5976. return;
  5977. } else if (id == "xfb_offset") {
  5978. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  5979. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
  5980. else
  5981. qualifier.layoutXfbOffset = value;
  5982. return;
  5983. } else if (id == "xfb_stride") {
  5984. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  5985. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  5986. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
  5987. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  5988. resources.maxTransformFeedbackInterleavedComponents);
  5989. else if (value >= (int)TQualifier::layoutXfbStrideEnd)
  5990. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
  5991. if (value < (int)TQualifier::layoutXfbStrideEnd)
  5992. qualifier.layoutXfbStride = value;
  5993. return;
  5994. }
  5995. }
  5996. if (id == "input_attachment_index") {
  5997. requireVulkan(loc, "input_attachment_index");
  5998. if (value >= (int)TQualifier::layoutAttachmentEnd)
  5999. error(loc, "attachment index is too large", id.c_str(), "");
  6000. else
  6001. qualifier.layoutAttachment = value;
  6002. return;
  6003. }
  6004. if (id == "constant_id") {
  6005. setSpecConstantId(loc, qualifier, value);
  6006. return;
  6007. }
  6008. switch (language) {
  6009. case EShLangVertex:
  6010. break;
  6011. case EShLangTessControl:
  6012. if (id == "vertices") {
  6013. if (value == 0)
  6014. error(loc, "must be greater than 0", "vertices", "");
  6015. else
  6016. // publicType.shaderQualifiers.vertices = value;
  6017. warn(loc, "ignored", id.c_str(), "");
  6018. return;
  6019. }
  6020. break;
  6021. case EShLangTessEvaluation:
  6022. break;
  6023. case EShLangGeometry:
  6024. if (id == "invocations") {
  6025. if (value == 0)
  6026. error(loc, "must be at least 1", "invocations", "");
  6027. else
  6028. // publicType.shaderQualifiers.invocations = value;
  6029. warn(loc, "ignored", id.c_str(), "");
  6030. return;
  6031. }
  6032. if (id == "max_vertices") {
  6033. // publicType.shaderQualifiers.vertices = value;
  6034. warn(loc, "ignored", id.c_str(), "");
  6035. if (value > resources.maxGeometryOutputVertices)
  6036. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  6037. return;
  6038. }
  6039. if (id == "stream") {
  6040. qualifier.layoutStream = value;
  6041. return;
  6042. }
  6043. break;
  6044. case EShLangFragment:
  6045. if (id == "index") {
  6046. qualifier.layoutIndex = value;
  6047. return;
  6048. }
  6049. break;
  6050. case EShLangCompute:
  6051. if (id.compare(0, 11, "local_size_") == 0) {
  6052. if (id == "local_size_x") {
  6053. // publicType.shaderQualifiers.localSize[0] = value;
  6054. warn(loc, "ignored", id.c_str(), "");
  6055. return;
  6056. }
  6057. if (id == "local_size_y") {
  6058. // publicType.shaderQualifiers.localSize[1] = value;
  6059. warn(loc, "ignored", id.c_str(), "");
  6060. return;
  6061. }
  6062. if (id == "local_size_z") {
  6063. // publicType.shaderQualifiers.localSize[2] = value;
  6064. warn(loc, "ignored", id.c_str(), "");
  6065. return;
  6066. }
  6067. if (spvVersion.spv != 0) {
  6068. if (id == "local_size_x_id") {
  6069. // publicType.shaderQualifiers.localSizeSpecId[0] = value;
  6070. warn(loc, "ignored", id.c_str(), "");
  6071. return;
  6072. }
  6073. if (id == "local_size_y_id") {
  6074. // publicType.shaderQualifiers.localSizeSpecId[1] = value;
  6075. warn(loc, "ignored", id.c_str(), "");
  6076. return;
  6077. }
  6078. if (id == "local_size_z_id") {
  6079. // publicType.shaderQualifiers.localSizeSpecId[2] = value;
  6080. warn(loc, "ignored", id.c_str(), "");
  6081. return;
  6082. }
  6083. }
  6084. }
  6085. break;
  6086. default:
  6087. break;
  6088. }
  6089. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  6090. }
  6091. void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
  6092. {
  6093. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  6094. error(loc, "specialization-constant id is too large", "constant_id", "");
  6095. } else {
  6096. qualifier.layoutSpecConstantId = value;
  6097. qualifier.specConstant = true;
  6098. if (! intermediate.addUsedConstantId(value))
  6099. error(loc, "specialization-constant id already used", "constant_id", "");
  6100. }
  6101. return;
  6102. }
  6103. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  6104. //
  6105. // "More than one layout qualifier may appear in a single declaration.
  6106. // Additionally, the same layout-qualifier-name can occur multiple times
  6107. // within a layout qualifier or across multiple layout qualifiers in the
  6108. // same declaration. When the same layout-qualifier-name occurs
  6109. // multiple times, in a single declaration, the last occurrence overrides
  6110. // the former occurrence(s). Further, if such a layout-qualifier-name
  6111. // will effect subsequent declarations or other observable behavior, it
  6112. // is only the last occurrence that will have any effect, behaving as if
  6113. // the earlier occurrence(s) within the declaration are not present.
  6114. // This is also true for overriding layout-qualifier-names, where one
  6115. // overrides the other (e.g., row_major vs. column_major); only the last
  6116. // occurrence has any effect."
  6117. //
  6118. void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  6119. {
  6120. if (src.hasMatrix())
  6121. dst.layoutMatrix = src.layoutMatrix;
  6122. if (src.hasPacking())
  6123. dst.layoutPacking = src.layoutPacking;
  6124. if (src.hasStream())
  6125. dst.layoutStream = src.layoutStream;
  6126. if (src.hasFormat())
  6127. dst.layoutFormat = src.layoutFormat;
  6128. if (src.hasXfbBuffer())
  6129. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  6130. if (src.hasAlign())
  6131. dst.layoutAlign = src.layoutAlign;
  6132. if (! inheritOnly) {
  6133. if (src.hasLocation())
  6134. dst.layoutLocation = src.layoutLocation;
  6135. if (src.hasComponent())
  6136. dst.layoutComponent = src.layoutComponent;
  6137. if (src.hasIndex())
  6138. dst.layoutIndex = src.layoutIndex;
  6139. if (src.hasOffset())
  6140. dst.layoutOffset = src.layoutOffset;
  6141. if (src.hasSet())
  6142. dst.layoutSet = src.layoutSet;
  6143. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  6144. dst.layoutBinding = src.layoutBinding;
  6145. if (src.hasXfbStride())
  6146. dst.layoutXfbStride = src.layoutXfbStride;
  6147. if (src.hasXfbOffset())
  6148. dst.layoutXfbOffset = src.layoutXfbOffset;
  6149. if (src.hasAttachment())
  6150. dst.layoutAttachment = src.layoutAttachment;
  6151. if (src.hasSpecConstantId())
  6152. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  6153. if (src.layoutPushConstant)
  6154. dst.layoutPushConstant = true;
  6155. }
  6156. }
  6157. //
  6158. // Look up a function name in the symbol table, and make sure it is a function.
  6159. //
  6160. // First, look for an exact match. If there is none, use the generic selector
  6161. // TParseContextBase::selectFunction() to find one, parameterized by the
  6162. // convertible() and better() predicates defined below.
  6163. //
  6164. // Return the function symbol if found, otherwise nullptr.
  6165. //
  6166. const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
  6167. TIntermTyped*& args)
  6168. {
  6169. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6170. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6171. return nullptr;
  6172. }
  6173. // first, look for an exact match
  6174. bool dummyScope;
  6175. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
  6176. if (symbol)
  6177. return symbol->getAsFunction();
  6178. // no exact match, use the generic selector, parameterized by the GLSL rules
  6179. // create list of candidates to send
  6180. TVector<const TFunction*> candidateList;
  6181. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6182. // These built-in ops can accept any type, so we bypass the argument selection
  6183. if (candidateList.size() == 1 && builtIn &&
  6184. (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6185. candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
  6186. candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
  6187. candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
  6188. candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6189. candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
  6190. return candidateList[0];
  6191. }
  6192. bool allowOnlyUpConversions = true;
  6193. // can 'from' convert to 'to'?
  6194. const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
  6195. if (from == to)
  6196. return true;
  6197. // no aggregate conversions
  6198. if (from.isArray() || to.isArray() ||
  6199. from.isStruct() || to.isStruct())
  6200. return false;
  6201. switch (op) {
  6202. case EOpInterlockedAdd:
  6203. case EOpInterlockedAnd:
  6204. case EOpInterlockedCompareExchange:
  6205. case EOpInterlockedCompareStore:
  6206. case EOpInterlockedExchange:
  6207. case EOpInterlockedMax:
  6208. case EOpInterlockedMin:
  6209. case EOpInterlockedOr:
  6210. case EOpInterlockedXor:
  6211. // We do not promote the texture or image type for these ocodes. Normally that would not
  6212. // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
  6213. // stage it's merely e.g, a basic integer type.
  6214. //
  6215. // Instead, we want to promote other arguments, but stay within the same family. In other
  6216. // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
  6217. // but it is allowed to promote its other arguments.
  6218. if (arg == 0)
  6219. return false;
  6220. break;
  6221. case EOpMethodSample:
  6222. case EOpMethodSampleBias:
  6223. case EOpMethodSampleCmp:
  6224. case EOpMethodSampleCmpLevelZero:
  6225. case EOpMethodSampleGrad:
  6226. case EOpMethodSampleLevel:
  6227. case EOpMethodLoad:
  6228. case EOpMethodGetDimensions:
  6229. case EOpMethodGetSamplePosition:
  6230. case EOpMethodGather:
  6231. case EOpMethodCalculateLevelOfDetail:
  6232. case EOpMethodCalculateLevelOfDetailUnclamped:
  6233. case EOpMethodGatherRed:
  6234. case EOpMethodGatherGreen:
  6235. case EOpMethodGatherBlue:
  6236. case EOpMethodGatherAlpha:
  6237. case EOpMethodGatherCmp:
  6238. case EOpMethodGatherCmpRed:
  6239. case EOpMethodGatherCmpGreen:
  6240. case EOpMethodGatherCmpBlue:
  6241. case EOpMethodGatherCmpAlpha:
  6242. case EOpMethodAppend:
  6243. case EOpMethodRestartStrip:
  6244. // those are method calls, the object type can not be changed
  6245. // they are equal if the dim and type match (is dim sufficient?)
  6246. if (arg == 0)
  6247. return from.getSampler().type == to.getSampler().type &&
  6248. from.getSampler().arrayed == to.getSampler().arrayed &&
  6249. from.getSampler().shadow == to.getSampler().shadow &&
  6250. from.getSampler().ms == to.getSampler().ms &&
  6251. from.getSampler().dim == to.getSampler().dim;
  6252. break;
  6253. default:
  6254. break;
  6255. }
  6256. // basic types have to be convertible
  6257. if (allowOnlyUpConversions)
  6258. if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
  6259. return false;
  6260. // shapes have to be convertible
  6261. if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
  6262. (from.isScalarOrVec1() && to.isVector()) ||
  6263. (from.isScalarOrVec1() && to.isMatrix()) ||
  6264. (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
  6265. return true;
  6266. // TODO: what are the matrix rules? they go here
  6267. return false;
  6268. };
  6269. // Is 'to2' a better conversion than 'to1'?
  6270. // Ties should not be considered as better.
  6271. // Assumes 'convertible' already said true.
  6272. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6273. // exact match is always better than mismatch
  6274. if (from == to2)
  6275. return from != to1;
  6276. if (from == to1)
  6277. return false;
  6278. // shape changes are always worse
  6279. if (from.isScalar() || from.isVector()) {
  6280. if (from.getVectorSize() == to2.getVectorSize() &&
  6281. from.getVectorSize() != to1.getVectorSize())
  6282. return true;
  6283. if (from.getVectorSize() == to1.getVectorSize() &&
  6284. from.getVectorSize() != to2.getVectorSize())
  6285. return false;
  6286. }
  6287. // Handle sampler betterness: An exact sampler match beats a non-exact match.
  6288. // (If we just looked at basic type, all EbtSamplers would look the same).
  6289. // If any type is not a sampler, just use the linearize function below.
  6290. if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
  6291. // We can ignore the vector size in the comparison.
  6292. TSampler to1Sampler = to1.getSampler();
  6293. TSampler to2Sampler = to2.getSampler();
  6294. to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
  6295. if (from.getSampler() == to2Sampler)
  6296. return from.getSampler() != to1Sampler;
  6297. if (from.getSampler() == to1Sampler)
  6298. return false;
  6299. }
  6300. // Might or might not be changing shape, which means basic type might
  6301. // or might not match, so within that, the question is how big a
  6302. // basic-type conversion is being done.
  6303. //
  6304. // Use a hierarchy of domains, translated to order of magnitude
  6305. // in a linearized view:
  6306. // - floating-point vs. integer
  6307. // - 32 vs. 64 bit (or width in general)
  6308. // - bool vs. non bool
  6309. // - signed vs. not signed
  6310. const auto linearize = [](const TBasicType& basicType) -> int {
  6311. switch (basicType) {
  6312. case EbtBool: return 1;
  6313. case EbtInt: return 10;
  6314. case EbtUint: return 11;
  6315. case EbtInt64: return 20;
  6316. case EbtUint64: return 21;
  6317. case EbtFloat: return 100;
  6318. case EbtDouble: return 110;
  6319. default: return 0;
  6320. }
  6321. };
  6322. return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
  6323. abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
  6324. };
  6325. // for ambiguity reporting
  6326. bool tie = false;
  6327. // send to the generic selector
  6328. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6329. if (bestMatch == nullptr) {
  6330. // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
  6331. // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
  6332. // upconversions possible.
  6333. allowOnlyUpConversions = false;
  6334. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6335. }
  6336. if (bestMatch == nullptr) {
  6337. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6338. return nullptr;
  6339. }
  6340. // For built-ins, we can convert across the arguments. This will happen in several steps:
  6341. // Step 1: If there's an exact match, use it.
  6342. // Step 2a: Otherwise, get the operator from the best match and promote arguments:
  6343. // Step 2b: reconstruct the TFunction based on the new arg types
  6344. // Step 3: Re-select after type promotion is applied, to find proper candidate.
  6345. if (builtIn) {
  6346. // Step 1: If there's an exact match, use it.
  6347. if (call.getMangledName() == bestMatch->getMangledName())
  6348. return bestMatch;
  6349. // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
  6350. // are that kind of operator.
  6351. if (args != nullptr) {
  6352. // The arg list can be a unary node, or an aggregate. We have to handle both.
  6353. // We will use the normal promote() facilities, which require an interm node.
  6354. TIntermOperator* promote = nullptr;
  6355. if (call.getParamCount() == 1) {
  6356. promote = new TIntermUnary(bestMatch->getBuiltInOp());
  6357. promote->getAsUnaryNode()->setOperand(args->getAsTyped());
  6358. } else {
  6359. promote = new TIntermAggregate(bestMatch->getBuiltInOp());
  6360. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6361. }
  6362. if (! intermediate.promote(promote))
  6363. return nullptr;
  6364. // Obtain the promoted arg list.
  6365. if (call.getParamCount() == 1) {
  6366. args = promote->getAsUnaryNode()->getOperand();
  6367. } else {
  6368. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6369. }
  6370. }
  6371. // Step 2b: reconstruct the TFunction based on the new arg types
  6372. TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
  6373. if (args->getAsAggregate()) {
  6374. // Handle aggregates: put all args into the new function call
  6375. for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
  6376. // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
  6377. TParameter param = { 0, new TType, nullptr };
  6378. param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
  6379. convertedCall.addParameter(param);
  6380. }
  6381. } else if (args->getAsUnaryNode()) {
  6382. // Handle unaries: put all args into the new function call
  6383. TParameter param = { 0, new TType, nullptr };
  6384. param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
  6385. convertedCall.addParameter(param);
  6386. } else if (args->getAsTyped()) {
  6387. // Handle bare e.g, floats, not in an aggregate.
  6388. TParameter param = { 0, new TType, nullptr };
  6389. param.type->shallowCopy(args->getAsTyped()->getType());
  6390. convertedCall.addParameter(param);
  6391. } else {
  6392. assert(0); // unknown argument list.
  6393. return nullptr;
  6394. }
  6395. // Step 3: Re-select after type promotion, to find proper candidate
  6396. // send to the generic selector
  6397. bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
  6398. // At this point, there should be no tie.
  6399. }
  6400. if (tie)
  6401. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6402. // Append default parameter values if needed
  6403. if (!tie && bestMatch != nullptr) {
  6404. for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
  6405. handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
  6406. }
  6407. }
  6408. return bestMatch;
  6409. }
  6410. //
  6411. // Do everything necessary to handle a typedef declaration, for a single symbol.
  6412. //
  6413. // 'parseType' is the type part of the declaration (to the left)
  6414. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6415. //
  6416. void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
  6417. {
  6418. TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
  6419. if (! symbolTable.insert(*typeSymbol))
  6420. error(loc, "name already defined", "typedef", identifier.c_str());
  6421. }
  6422. // Do everything necessary to handle a struct declaration, including
  6423. // making IO aliases because HLSL allows mixed IO in a struct that specializes
  6424. // based on the usage (input, output, uniform, none).
  6425. void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
  6426. {
  6427. // If it was named, which means the type can be reused later, add
  6428. // it to the symbol table. (Unless it's a block, in which
  6429. // case the name is not a type.)
  6430. if (type.getBasicType() == EbtBlock || structName.size() == 0)
  6431. return;
  6432. TVariable* userTypeDef = new TVariable(&structName, type, true);
  6433. if (! symbolTable.insert(*userTypeDef)) {
  6434. error(loc, "redefinition", structName.c_str(), "struct");
  6435. return;
  6436. }
  6437. // See if we need IO aliases for the structure typeList
  6438. const auto condAlloc = [](bool pred, TTypeList*& list) {
  6439. if (pred && list == nullptr)
  6440. list = new TTypeList;
  6441. };
  6442. tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
  6443. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6444. condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
  6445. condAlloc( hasInput(member->type->getQualifier()), newLists.input);
  6446. condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
  6447. if (member->type->isStruct()) {
  6448. auto it = ioTypeMap.find(member->type->getStruct());
  6449. if (it != ioTypeMap.end()) {
  6450. condAlloc(it->second.uniform != nullptr, newLists.uniform);
  6451. condAlloc(it->second.input != nullptr, newLists.input);
  6452. condAlloc(it->second.output != nullptr, newLists.output);
  6453. }
  6454. }
  6455. }
  6456. if (newLists.uniform == nullptr &&
  6457. newLists.input == nullptr &&
  6458. newLists.output == nullptr) {
  6459. // Won't do any IO caching, clear up the type and get out now.
  6460. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
  6461. clearUniformInputOutput(member->type->getQualifier());
  6462. return;
  6463. }
  6464. // We have IO involved.
  6465. // Make a pure typeList for the symbol table, and cache side copies of IO versions.
  6466. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6467. const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
  6468. if (s != nullptr) {
  6469. ioMember.type = new TType;
  6470. ioMember.type->shallowCopy(*member->type);
  6471. ioMember.type->setStruct(s);
  6472. }
  6473. };
  6474. const auto newMember = [&](TTypeLoc& m) {
  6475. if (m.type == nullptr) {
  6476. m.type = new TType;
  6477. m.type->shallowCopy(*member->type);
  6478. }
  6479. };
  6480. TTypeLoc newUniformMember = { nullptr, member->loc };
  6481. TTypeLoc newInputMember = { nullptr, member->loc };
  6482. TTypeLoc newOutputMember = { nullptr, member->loc };
  6483. if (member->type->isStruct()) {
  6484. // swap in an IO child if there is one
  6485. auto it = ioTypeMap.find(member->type->getStruct());
  6486. if (it != ioTypeMap.end()) {
  6487. inheritStruct(it->second.uniform, newUniformMember);
  6488. inheritStruct(it->second.input, newInputMember);
  6489. inheritStruct(it->second.output, newOutputMember);
  6490. }
  6491. }
  6492. if (newLists.uniform) {
  6493. newMember(newUniformMember);
  6494. // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
  6495. if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
  6496. newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
  6497. correctUniform(newUniformMember.type->getQualifier());
  6498. newLists.uniform->push_back(newUniformMember);
  6499. }
  6500. if (newLists.input) {
  6501. newMember(newInputMember);
  6502. correctInput(newInputMember.type->getQualifier());
  6503. newLists.input->push_back(newInputMember);
  6504. }
  6505. if (newLists.output) {
  6506. newMember(newOutputMember);
  6507. correctOutput(newOutputMember.type->getQualifier());
  6508. newLists.output->push_back(newOutputMember);
  6509. }
  6510. // make original pure
  6511. clearUniformInputOutput(member->type->getQualifier());
  6512. }
  6513. ioTypeMap[type.getStruct()] = newLists;
  6514. }
  6515. // Lookup a user-type by name.
  6516. // If found, fill in the type and return the defining symbol.
  6517. // If not found, return nullptr.
  6518. TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
  6519. {
  6520. TSymbol* symbol = symbolTable.find(typeName);
  6521. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  6522. type.shallowCopy(symbol->getType());
  6523. return symbol;
  6524. } else
  6525. return nullptr;
  6526. }
  6527. //
  6528. // Do everything necessary to handle a variable (non-block) declaration.
  6529. // Either redeclaring a variable, or making a new one, updating the symbol
  6530. // table, and all error checking.
  6531. //
  6532. // Returns a subtree node that computes an initializer, if needed.
  6533. // Returns nullptr if there is no code to execute for initialization.
  6534. //
  6535. // 'parseType' is the type part of the declaration (to the left)
  6536. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6537. //
  6538. TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
  6539. TIntermTyped* initializer)
  6540. {
  6541. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6542. return nullptr;
  6543. // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
  6544. // This test is implicitly recursive, because initializers propagate constness
  6545. // up the aggregate node tree during creation. E.g, for:
  6546. // { { 1, 2 }, { 3, 4 } }
  6547. // the initializer list is marked EvqConst at the top node, and remains so here. However:
  6548. // { 1, { myvar, 2 }, 3 }
  6549. // is not a const intializer, and still becomes EvqGlobal here.
  6550. const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
  6551. if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
  6552. // Force to global
  6553. type.getQualifier().storage = EvqGlobal;
  6554. }
  6555. // make const and initialization consistent
  6556. fixConstInit(loc, identifier, type, initializer);
  6557. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6558. TSymbol* symbol = nullptr;
  6559. inheritGlobalDefaults(type.getQualifier());
  6560. const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
  6561. // correct IO in the type
  6562. switch (type.getQualifier().storage) {
  6563. case EvqGlobal:
  6564. case EvqTemporary:
  6565. clearUniformInputOutput(type.getQualifier());
  6566. break;
  6567. case EvqUniform:
  6568. case EvqBuffer:
  6569. correctUniform(type.getQualifier());
  6570. if (type.isStruct()) {
  6571. auto it = ioTypeMap.find(type.getStruct());
  6572. if (it != ioTypeMap.end())
  6573. type.setStruct(it->second.uniform);
  6574. }
  6575. break;
  6576. default:
  6577. break;
  6578. }
  6579. // Declare the variable
  6580. if (type.isArray()) {
  6581. // array case
  6582. declareArray(loc, identifier, type, symbol, !flattenVar);
  6583. } else {
  6584. // non-array case
  6585. if (symbol == nullptr)
  6586. symbol = declareNonArray(loc, identifier, type, !flattenVar);
  6587. else if (type != symbol->getType())
  6588. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6589. }
  6590. if (symbol == nullptr)
  6591. return nullptr;
  6592. if (flattenVar)
  6593. flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
  6594. if (initializer == nullptr)
  6595. return nullptr;
  6596. // Deal with initializer
  6597. TVariable* variable = symbol->getAsVariable();
  6598. if (variable == nullptr) {
  6599. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6600. return nullptr;
  6601. }
  6602. return executeInitializer(loc, initializer, variable);
  6603. }
  6604. // Pick up global defaults from the provide global defaults into dst.
  6605. void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6606. {
  6607. if (dst.storage == EvqVaryingOut) {
  6608. if (! dst.hasStream() && language == EShLangGeometry)
  6609. dst.layoutStream = globalOutputDefaults.layoutStream;
  6610. if (! dst.hasXfbBuffer())
  6611. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6612. }
  6613. }
  6614. //
  6615. // Make an internal-only variable whose name is for debug purposes only
  6616. // and won't be searched for. Callers will only use the return value to use
  6617. // the variable, not the name to look it up. It is okay if the name
  6618. // is the same as other names; there won't be any conflict.
  6619. //
  6620. TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
  6621. {
  6622. TString* nameString = NewPoolTString(name);
  6623. TVariable* variable = new TVariable(nameString, type);
  6624. symbolTable.makeInternalVariable(*variable);
  6625. return variable;
  6626. }
  6627. // Make a symbol node holding a new internal temporary variable.
  6628. TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
  6629. const TType& type) const
  6630. {
  6631. TVariable* tmpVar = makeInternalVariable(name, type);
  6632. tmpVar->getWritableType().getQualifier().makeTemporary();
  6633. return intermediate.addSymbol(*tmpVar, loc);
  6634. }
  6635. //
  6636. // Declare a non-array variable, the main point being there is no redeclaration
  6637. // for resizing allowed.
  6638. //
  6639. // Return the successfully declared variable.
  6640. //
  6641. TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  6642. bool track)
  6643. {
  6644. // make a new variable
  6645. TVariable* variable = new TVariable(&identifier, type);
  6646. // add variable to symbol table
  6647. if (symbolTable.insert(*variable)) {
  6648. if (track && symbolTable.atGlobalLevel())
  6649. trackLinkage(*variable);
  6650. return variable;
  6651. }
  6652. error(loc, "redefinition", variable->getName().c_str(), "");
  6653. return nullptr;
  6654. }
  6655. //
  6656. // Handle all types of initializers from the grammar.
  6657. //
  6658. // Returning nullptr just means there is no code to execute to handle the
  6659. // initializer, which will, for example, be the case for constant initializers.
  6660. //
  6661. // Returns a subtree that accomplished the initialization.
  6662. //
  6663. TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6664. {
  6665. //
  6666. // Identifier must be of type constant, a global, or a temporary, and
  6667. // starting at version 120, desktop allows uniforms to have initializers.
  6668. //
  6669. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6670. //
  6671. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6672. // constructor-style subtree, allowing the rest of the code to operate
  6673. // identically for both kinds of initializers.
  6674. //
  6675. //
  6676. // Type can't be deduced from the initializer list, so a skeletal type to
  6677. // follow has to be passed in. Constness and specialization-constness
  6678. // should be deduced bottom up, not dictated by the skeletal type.
  6679. //
  6680. TType skeletalType;
  6681. skeletalType.shallowCopy(variable->getType());
  6682. skeletalType.getQualifier().makeTemporary();
  6683. if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
  6684. initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
  6685. if (initializer == nullptr) {
  6686. // error recovery; don't leave const without constant values
  6687. if (qualifier == EvqConst)
  6688. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6689. return nullptr;
  6690. }
  6691. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6692. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6693. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6694. // Inner arrayness can also get set by an initializer
  6695. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6696. initializer->getType().getArraySizes()->getNumDims() ==
  6697. variable->getType().getArraySizes()->getNumDims()) {
  6698. // adopt unsized sizes from the initializer's sizes
  6699. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6700. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6701. variable->getWritableType().getArraySizes()->setDimSize(d,
  6702. initializer->getType().getArraySizes()->getDimSize(d));
  6703. }
  6704. }
  6705. }
  6706. // Uniform and global consts require a constant initializer
  6707. if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
  6708. error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
  6709. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6710. return nullptr;
  6711. }
  6712. // Const variables require a constant initializer
  6713. if (qualifier == EvqConst) {
  6714. if (initializer->getType().getQualifier().storage != EvqConst) {
  6715. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6716. qualifier = EvqConstReadOnly;
  6717. }
  6718. }
  6719. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6720. // Compile-time tagging of the variable with its constant value...
  6721. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6722. if (initializer != nullptr && variable->getType() != initializer->getType())
  6723. initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
  6724. if (initializer == nullptr || !initializer->getAsConstantUnion() ||
  6725. variable->getType() != initializer->getType()) {
  6726. error(loc, "non-matching or non-convertible constant type for const initializer",
  6727. variable->getType().getStorageQualifierString(), "");
  6728. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6729. return nullptr;
  6730. }
  6731. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6732. } else {
  6733. // normal assigning of a value to a variable...
  6734. specializationCheck(loc, initializer->getType(), "initializer");
  6735. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6736. TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
  6737. if (initNode == nullptr)
  6738. assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
  6739. return initNode;
  6740. }
  6741. return nullptr;
  6742. }
  6743. //
  6744. // Reprocess any initializer-list { ... } parts of the initializer.
  6745. // Need to hierarchically assign correct types and implicit
  6746. // conversions. Will do this mimicking the same process used for
  6747. // creating a constructor-style initializer, ensuring we get the
  6748. // same form.
  6749. //
  6750. // Returns a node representing an expression for the initializer list expressed
  6751. // as the correct type.
  6752. //
  6753. // Returns nullptr if there is an error.
  6754. //
  6755. TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
  6756. TIntermTyped* initializer, TIntermTyped* scalarInit)
  6757. {
  6758. // Will operate recursively. Once a subtree is found that is constructor style,
  6759. // everything below it is already good: Only the "top part" of the initializer
  6760. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6761. // see if we have bottomed out in the tree within the initializer-list part
  6762. TIntermAggregate* initList = initializer->getAsAggregate();
  6763. if (initList == nullptr || initList->getOp() != EOpNull) {
  6764. // We don't have a list, but if it's a scalar and the 'type' is a
  6765. // composite, we need to lengthen below to make it useful.
  6766. // Otherwise, this is an already formed object to initialize with.
  6767. if (type.isScalar() || !initializer->getType().isScalar())
  6768. return initializer;
  6769. else
  6770. initList = intermediate.makeAggregate(initializer);
  6771. }
  6772. // Of the initializer-list set of nodes, need to process bottom up,
  6773. // so recurse deep, then process on the way up.
  6774. // Go down the tree here...
  6775. if (type.isArray()) {
  6776. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6777. // Later on, initializer execution code will deal with array size logic.
  6778. TType arrayType;
  6779. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6780. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6781. // edit array sizes to fill in unsized dimensions
  6782. if (type.isUnsizedArray())
  6783. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6784. // set unsized array dimensions that can be derived from the initializer's first element
  6785. if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
  6786. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6787. if (firstInit->getType().isArray() &&
  6788. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6789. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6790. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6791. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6792. }
  6793. }
  6794. }
  6795. // lengthen list to be long enough
  6796. lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
  6797. // recursively process each element
  6798. TType elementType(arrayType, 0); // dereferenced type
  6799. for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
  6800. initList->getSequence()[i] = convertInitializerList(loc, elementType,
  6801. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6802. if (initList->getSequence()[i] == nullptr)
  6803. return nullptr;
  6804. }
  6805. return addConstructor(loc, initList, arrayType);
  6806. } else if (type.isStruct()) {
  6807. // do we have implicit assignments to opaques?
  6808. for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
  6809. if ((*type.getStruct())[i].type->containsOpaque()) {
  6810. error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
  6811. return nullptr;
  6812. }
  6813. }
  6814. // lengthen list to be long enough
  6815. lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
  6816. if (type.getStruct()->size() != initList->getSequence().size()) {
  6817. error(loc, "wrong number of structure members", "initializer list", "");
  6818. return nullptr;
  6819. }
  6820. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6821. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
  6822. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6823. if (initList->getSequence()[i] == nullptr)
  6824. return nullptr;
  6825. }
  6826. } else if (type.isMatrix()) {
  6827. if (type.computeNumComponents() == (int)initList->getSequence().size()) {
  6828. // This means the matrix is initialized component-wise, rather than as
  6829. // a series of rows and columns. We can just use the list directly as
  6830. // a constructor; no further processing needed.
  6831. } else {
  6832. // lengthen list to be long enough
  6833. lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
  6834. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  6835. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
  6836. return nullptr;
  6837. }
  6838. TType vectorType(type, 0); // dereferenced type
  6839. for (int i = 0; i < type.getMatrixCols(); ++i) {
  6840. initList->getSequence()[i] = convertInitializerList(loc, vectorType,
  6841. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6842. if (initList->getSequence()[i] == nullptr)
  6843. return nullptr;
  6844. }
  6845. }
  6846. } else if (type.isVector()) {
  6847. // lengthen list to be long enough
  6848. lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
  6849. // error check; we're at bottom, so work is finished below
  6850. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  6851. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
  6852. type.getCompleteString().c_str());
  6853. return nullptr;
  6854. }
  6855. } else if (type.isScalar()) {
  6856. // lengthen list to be long enough
  6857. lengthenList(loc, initList->getSequence(), 1, scalarInit);
  6858. if ((int)initList->getSequence().size() != 1) {
  6859. error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
  6860. return nullptr;
  6861. }
  6862. } else {
  6863. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
  6864. return nullptr;
  6865. }
  6866. // Now that the subtree is processed, process this node as if the
  6867. // initializer list is a set of arguments to a constructor.
  6868. TIntermTyped* emulatedConstructorArguments;
  6869. if (initList->getSequence().size() == 1)
  6870. emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
  6871. else
  6872. emulatedConstructorArguments = initList;
  6873. return addConstructor(loc, emulatedConstructorArguments, type);
  6874. }
  6875. // Lengthen list to be long enough to cover any gap from the current list size
  6876. // to 'size'. If the list is longer, do nothing.
  6877. // The value to lengthen with is the default for short lists.
  6878. //
  6879. // By default, lists that are too short due to lack of initializers initialize to zero.
  6880. // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
  6881. // based on whether something is passed in as 'scalarInit'.
  6882. //
  6883. // 'scalarInit' must be safe to use each time this is called (no side effects replication).
  6884. //
  6885. void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
  6886. {
  6887. for (int c = (int)list.size(); c < size; ++c) {
  6888. if (scalarInit == nullptr)
  6889. list.push_back(intermediate.addConstantUnion(0, loc));
  6890. else
  6891. list.push_back(scalarInit);
  6892. }
  6893. }
  6894. //
  6895. // Test for the correctness of the parameters passed to various constructor functions
  6896. // and also convert them to the right data type, if allowed and required.
  6897. //
  6898. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  6899. //
  6900. TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6901. {
  6902. if (node == nullptr)
  6903. return nullptr;
  6904. // Construct identical type
  6905. if (type == node->getType())
  6906. return node;
  6907. // Handle the idiom "(struct type)<scalar value>"
  6908. if (type.isStruct() && isScalarConstructor(node)) {
  6909. // 'node' will almost always get used multiple times, so should not be used directly,
  6910. // it would create a DAG instead of a tree, which might be okay (would
  6911. // like to formalize that for constants and symbols), but if it has
  6912. // side effects, they would get executed multiple times, which is not okay.
  6913. if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
  6914. TIntermAggregate* seq = intermediate.makeAggregate(loc);
  6915. TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
  6916. seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
  6917. seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
  6918. seq->setOp(EOpComma);
  6919. seq->setType(type);
  6920. return seq;
  6921. } else
  6922. return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
  6923. }
  6924. return addConstructor(loc, node, type);
  6925. }
  6926. // Add a constructor, either from the grammar, or other programmatic reasons.
  6927. //
  6928. // 'node' is what to construct from.
  6929. // 'type' is what type to construct.
  6930. //
  6931. // Returns the constructed object.
  6932. // Return nullptr if it can't be done.
  6933. //
  6934. TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6935. {
  6936. TIntermAggregate* aggrNode = node->getAsAggregate();
  6937. TOperator op = intermediate.mapTypeToConstructorOp(type);
  6938. if (op == EOpConstructTextureSampler)
  6939. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  6940. TTypeList::const_iterator memberTypes;
  6941. if (op == EOpConstructStruct)
  6942. memberTypes = type.getStruct()->begin();
  6943. TType elementType;
  6944. if (type.isArray()) {
  6945. TType dereferenced(type, 0);
  6946. elementType.shallowCopy(dereferenced);
  6947. } else
  6948. elementType.shallowCopy(type);
  6949. bool singleArg;
  6950. if (aggrNode != nullptr) {
  6951. if (aggrNode->getOp() != EOpNull)
  6952. singleArg = true;
  6953. else
  6954. singleArg = false;
  6955. } else
  6956. singleArg = true;
  6957. TIntermTyped *newNode;
  6958. if (singleArg) {
  6959. // Handle array -> array conversion
  6960. // Constructing an array of one type from an array of another type is allowed,
  6961. // assuming there are enough components available (semantic-checked earlier).
  6962. if (type.isArray() && node->isArray())
  6963. newNode = convertArray(node, type);
  6964. // If structure constructor or array constructor is being called
  6965. // for only one parameter inside the aggregate, we need to call constructAggregate function once.
  6966. else if (type.isArray())
  6967. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  6968. else if (op == EOpConstructStruct)
  6969. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  6970. else {
  6971. // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
  6972. // is replicated into every element of the matrix (not just the diagnonal), so
  6973. // that is handled specially here.
  6974. if (type.isMatrix() && node->getType().isScalarOrVec1())
  6975. node = intermediate.addShapeConversion(type, node);
  6976. newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
  6977. }
  6978. if (newNode && (type.isArray() || op == EOpConstructStruct))
  6979. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  6980. return newNode;
  6981. }
  6982. //
  6983. // Handle list of arguments.
  6984. //
  6985. TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  6986. // if the structure constructor contains more than one parameter, then construct
  6987. // each parameter
  6988. int paramCount = 0; // keeps a track of the constructor parameter number being checked
  6989. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  6990. // to the right type if possible (and allowed).
  6991. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  6992. for (TIntermSequence::iterator p = sequenceVector.begin();
  6993. p != sequenceVector.end(); p++, paramCount++) {
  6994. if (type.isArray())
  6995. newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
  6996. else if (op == EOpConstructStruct)
  6997. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
  6998. else
  6999. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7000. if (newNode)
  7001. *p = newNode;
  7002. else
  7003. return nullptr;
  7004. }
  7005. TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7006. return constructor;
  7007. }
  7008. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7009. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7010. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7011. // float, then float is converted to int.
  7012. //
  7013. // Returns nullptr for an error or the constructed node.
  7014. //
  7015. TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
  7016. const TSourceLoc& loc, bool subset)
  7017. {
  7018. TIntermTyped* newNode;
  7019. TOperator basicOp;
  7020. //
  7021. // First, convert types as needed.
  7022. //
  7023. switch (op) {
  7024. case EOpConstructF16Vec2:
  7025. case EOpConstructF16Vec3:
  7026. case EOpConstructF16Vec4:
  7027. case EOpConstructF16Mat2x2:
  7028. case EOpConstructF16Mat2x3:
  7029. case EOpConstructF16Mat2x4:
  7030. case EOpConstructF16Mat3x2:
  7031. case EOpConstructF16Mat3x3:
  7032. case EOpConstructF16Mat3x4:
  7033. case EOpConstructF16Mat4x2:
  7034. case EOpConstructF16Mat4x3:
  7035. case EOpConstructF16Mat4x4:
  7036. case EOpConstructFloat16:
  7037. basicOp = EOpConstructFloat16;
  7038. break;
  7039. case EOpConstructVec2:
  7040. case EOpConstructVec3:
  7041. case EOpConstructVec4:
  7042. case EOpConstructMat2x2:
  7043. case EOpConstructMat2x3:
  7044. case EOpConstructMat2x4:
  7045. case EOpConstructMat3x2:
  7046. case EOpConstructMat3x3:
  7047. case EOpConstructMat3x4:
  7048. case EOpConstructMat4x2:
  7049. case EOpConstructMat4x3:
  7050. case EOpConstructMat4x4:
  7051. case EOpConstructFloat:
  7052. basicOp = EOpConstructFloat;
  7053. break;
  7054. case EOpConstructDVec2:
  7055. case EOpConstructDVec3:
  7056. case EOpConstructDVec4:
  7057. case EOpConstructDMat2x2:
  7058. case EOpConstructDMat2x3:
  7059. case EOpConstructDMat2x4:
  7060. case EOpConstructDMat3x2:
  7061. case EOpConstructDMat3x3:
  7062. case EOpConstructDMat3x4:
  7063. case EOpConstructDMat4x2:
  7064. case EOpConstructDMat4x3:
  7065. case EOpConstructDMat4x4:
  7066. case EOpConstructDouble:
  7067. basicOp = EOpConstructDouble;
  7068. break;
  7069. case EOpConstructI16Vec2:
  7070. case EOpConstructI16Vec3:
  7071. case EOpConstructI16Vec4:
  7072. case EOpConstructInt16:
  7073. basicOp = EOpConstructInt16;
  7074. break;
  7075. case EOpConstructIVec2:
  7076. case EOpConstructIVec3:
  7077. case EOpConstructIVec4:
  7078. case EOpConstructIMat2x2:
  7079. case EOpConstructIMat2x3:
  7080. case EOpConstructIMat2x4:
  7081. case EOpConstructIMat3x2:
  7082. case EOpConstructIMat3x3:
  7083. case EOpConstructIMat3x4:
  7084. case EOpConstructIMat4x2:
  7085. case EOpConstructIMat4x3:
  7086. case EOpConstructIMat4x4:
  7087. case EOpConstructInt:
  7088. basicOp = EOpConstructInt;
  7089. break;
  7090. case EOpConstructU16Vec2:
  7091. case EOpConstructU16Vec3:
  7092. case EOpConstructU16Vec4:
  7093. case EOpConstructUint16:
  7094. basicOp = EOpConstructUint16;
  7095. break;
  7096. case EOpConstructUVec2:
  7097. case EOpConstructUVec3:
  7098. case EOpConstructUVec4:
  7099. case EOpConstructUMat2x2:
  7100. case EOpConstructUMat2x3:
  7101. case EOpConstructUMat2x4:
  7102. case EOpConstructUMat3x2:
  7103. case EOpConstructUMat3x3:
  7104. case EOpConstructUMat3x4:
  7105. case EOpConstructUMat4x2:
  7106. case EOpConstructUMat4x3:
  7107. case EOpConstructUMat4x4:
  7108. case EOpConstructUint:
  7109. basicOp = EOpConstructUint;
  7110. break;
  7111. case EOpConstructBVec2:
  7112. case EOpConstructBVec3:
  7113. case EOpConstructBVec4:
  7114. case EOpConstructBMat2x2:
  7115. case EOpConstructBMat2x3:
  7116. case EOpConstructBMat2x4:
  7117. case EOpConstructBMat3x2:
  7118. case EOpConstructBMat3x3:
  7119. case EOpConstructBMat3x4:
  7120. case EOpConstructBMat4x2:
  7121. case EOpConstructBMat4x3:
  7122. case EOpConstructBMat4x4:
  7123. case EOpConstructBool:
  7124. basicOp = EOpConstructBool;
  7125. break;
  7126. default:
  7127. error(loc, "unsupported construction", "", "");
  7128. return nullptr;
  7129. }
  7130. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7131. if (newNode == nullptr) {
  7132. error(loc, "can't convert", "constructor", "");
  7133. return nullptr;
  7134. }
  7135. //
  7136. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7137. //
  7138. // Otherwise, skip out early.
  7139. if (subset || (newNode != node && newNode->getType() == type))
  7140. return newNode;
  7141. // setAggregateOperator will insert a new node for the constructor, as needed.
  7142. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7143. }
  7144. // Convert the array in node to the requested type, which is also an array.
  7145. // Returns nullptr on failure, otherwise returns aggregate holding the list of
  7146. // elements needed to construct the array.
  7147. TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
  7148. {
  7149. assert(node->isArray() && type.isArray());
  7150. if (node->getType().computeNumComponents() < type.computeNumComponents())
  7151. return nullptr;
  7152. // TODO: write an argument replicator, for the case the argument should not be
  7153. // executed multiple times, yet multiple copies are needed.
  7154. TIntermTyped* constructee = node->getAsTyped();
  7155. // track where we are in consuming the argument
  7156. int constructeeElement = 0;
  7157. int constructeeComponent = 0;
  7158. // bump up to the next component to consume
  7159. const auto getNextComponent = [&]() {
  7160. TIntermTyped* component;
  7161. component = handleBracketDereference(node->getLoc(), constructee,
  7162. intermediate.addConstantUnion(constructeeElement, node->getLoc()));
  7163. if (component->isVector())
  7164. component = handleBracketDereference(node->getLoc(), component,
  7165. intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
  7166. // bump component pointer up
  7167. ++constructeeComponent;
  7168. if (constructeeComponent == constructee->getVectorSize()) {
  7169. constructeeComponent = 0;
  7170. ++constructeeElement;
  7171. }
  7172. return component;
  7173. };
  7174. // make one subnode per constructed array element
  7175. TIntermAggregate* constructor = nullptr;
  7176. TType derefType(type, 0);
  7177. TType speculativeComponentType(derefType, 0);
  7178. TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
  7179. TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
  7180. TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
  7181. for (int e = 0; e < type.getOuterArraySize(); ++e) {
  7182. // construct an element
  7183. TIntermTyped* elementArg;
  7184. if (type.getVectorSize() == constructee->getVectorSize()) {
  7185. // same element shape
  7186. elementArg = handleBracketDereference(node->getLoc(), constructee,
  7187. intermediate.addConstantUnion(e, node->getLoc()));
  7188. } else {
  7189. // mismatched element shapes
  7190. if (type.getVectorSize() == 1)
  7191. elementArg = getNextComponent();
  7192. else {
  7193. // make a vector
  7194. TIntermAggregate* elementConstructee = nullptr;
  7195. for (int c = 0; c < type.getVectorSize(); ++c)
  7196. elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
  7197. elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
  7198. }
  7199. }
  7200. // convert basic types
  7201. elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
  7202. if (elementArg == nullptr)
  7203. return nullptr;
  7204. // combine with top-level constructor
  7205. constructor = intermediate.growAggregate(constructor, elementArg);
  7206. }
  7207. return constructor;
  7208. }
  7209. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7210. // an error message if the expected type does not match the parameter passed to the constructor.
  7211. //
  7212. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7213. //
  7214. TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
  7215. const TSourceLoc& loc)
  7216. {
  7217. // Handle cases that map more 1:1 between constructor arguments and constructed.
  7218. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7219. if (converted == nullptr || converted->getType() != type) {
  7220. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7221. node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
  7222. return nullptr;
  7223. }
  7224. return converted;
  7225. }
  7226. //
  7227. // Do everything needed to add an interface block.
  7228. //
  7229. void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
  7230. {
  7231. assert(type.getWritableStruct() != nullptr);
  7232. // Clean up top-level decorations that don't belong.
  7233. switch (type.getQualifier().storage) {
  7234. case EvqUniform:
  7235. case EvqBuffer:
  7236. correctUniform(type.getQualifier());
  7237. break;
  7238. case EvqVaryingIn:
  7239. correctInput(type.getQualifier());
  7240. break;
  7241. case EvqVaryingOut:
  7242. correctOutput(type.getQualifier());
  7243. break;
  7244. default:
  7245. break;
  7246. }
  7247. TTypeList& typeList = *type.getWritableStruct();
  7248. // fix and check for member storage qualifiers and types that don't belong within a block
  7249. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7250. TType& memberType = *typeList[member].type;
  7251. TQualifier& memberQualifier = memberType.getQualifier();
  7252. const TSourceLoc& memberLoc = typeList[member].loc;
  7253. globalQualifierFix(memberLoc, memberQualifier);
  7254. memberQualifier.storage = type.getQualifier().storage;
  7255. if (memberType.isStruct()) {
  7256. // clean up and pick up the right set of decorations
  7257. auto it = ioTypeMap.find(memberType.getStruct());
  7258. switch (type.getQualifier().storage) {
  7259. case EvqUniform:
  7260. case EvqBuffer:
  7261. correctUniform(type.getQualifier());
  7262. if (it != ioTypeMap.end() && it->second.uniform)
  7263. memberType.setStruct(it->second.uniform);
  7264. break;
  7265. case EvqVaryingIn:
  7266. correctInput(type.getQualifier());
  7267. if (it != ioTypeMap.end() && it->second.input)
  7268. memberType.setStruct(it->second.input);
  7269. break;
  7270. case EvqVaryingOut:
  7271. correctOutput(type.getQualifier());
  7272. if (it != ioTypeMap.end() && it->second.output)
  7273. memberType.setStruct(it->second.output);
  7274. break;
  7275. default:
  7276. break;
  7277. }
  7278. }
  7279. }
  7280. // Make default block qualification, and adjust the member qualifications
  7281. TQualifier defaultQualification;
  7282. switch (type.getQualifier().storage) {
  7283. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7284. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7285. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7286. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7287. default: defaultQualification.clear(); break;
  7288. }
  7289. // Special case for "push_constant uniform", which has a default of std430,
  7290. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7291. if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
  7292. type.getQualifier().layoutPacking = ElpStd430;
  7293. // fix and check for member layout qualifiers
  7294. mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
  7295. bool memberWithLocation = false;
  7296. bool memberWithoutLocation = false;
  7297. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7298. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7299. const TSourceLoc& memberLoc = typeList[member].loc;
  7300. if (memberQualifier.hasStream()) {
  7301. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7302. error(memberLoc, "member cannot contradict block", "stream", "");
  7303. }
  7304. // "This includes a block's inheritance of the
  7305. // current global default buffer, a block member's inheritance of the block's
  7306. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7307. // member must match the buffer inherited from the block."
  7308. if (memberQualifier.hasXfbBuffer()) {
  7309. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7310. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7311. }
  7312. if (memberQualifier.hasLocation()) {
  7313. switch (type.getQualifier().storage) {
  7314. case EvqVaryingIn:
  7315. case EvqVaryingOut:
  7316. memberWithLocation = true;
  7317. break;
  7318. default:
  7319. break;
  7320. }
  7321. } else
  7322. memberWithoutLocation = true;
  7323. TQualifier newMemberQualification = defaultQualification;
  7324. mergeQualifiers(newMemberQualification, memberQualifier);
  7325. memberQualifier = newMemberQualification;
  7326. }
  7327. // Process the members
  7328. fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
  7329. fixXfbOffsets(type.getQualifier(), typeList);
  7330. fixBlockUniformOffsets(type.getQualifier(), typeList);
  7331. // reverse merge, so that currentBlockQualifier now has all layout information
  7332. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7333. mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
  7334. //
  7335. // Build and add the interface block as a new type named 'blockName'
  7336. //
  7337. // Use the instance name as the interface name if one exists, else the block name.
  7338. const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
  7339. TType blockType(&typeList, interfaceName, type.getQualifier());
  7340. if (type.isArray())
  7341. blockType.transferArraySizes(type.getArraySizes());
  7342. // Add the variable, as anonymous or named instanceName.
  7343. // Make an anonymous variable if no name was provided.
  7344. if (instanceName == nullptr)
  7345. instanceName = NewPoolTString("");
  7346. TVariable& variable = *new TVariable(instanceName, blockType);
  7347. if (! symbolTable.insert(variable)) {
  7348. if (*instanceName == "")
  7349. error(loc, "nameless block contains a member that already has a name at global scope",
  7350. "" /* blockName->c_str() */, "");
  7351. else
  7352. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7353. return;
  7354. }
  7355. // Save it in the AST for linker use.
  7356. if (symbolTable.atGlobalLevel())
  7357. trackLinkage(variable);
  7358. }
  7359. //
  7360. // "For a block, this process applies to the entire block, or until the first member
  7361. // is reached that has a location layout qualifier. When a block member is declared with a location
  7362. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7363. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7364. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7365. // declared in increasing order."
  7366. void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7367. {
  7368. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7369. // have a location layout qualifier, or a compile-time error results."
  7370. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7371. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7372. else {
  7373. if (memberWithLocation) {
  7374. // remove any block-level location and make it per *every* member
  7375. int nextLocation = 0; // by the rule above, initial value is not relevant
  7376. if (qualifier.hasAnyLocation()) {
  7377. nextLocation = qualifier.layoutLocation;
  7378. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7379. if (qualifier.hasComponent()) {
  7380. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7381. error(loc, "cannot apply to a block", "component", "");
  7382. }
  7383. if (qualifier.hasIndex()) {
  7384. error(loc, "cannot apply to a block", "index", "");
  7385. }
  7386. }
  7387. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7388. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7389. const TSourceLoc& memberLoc = typeList[member].loc;
  7390. if (! memberQualifier.hasLocation()) {
  7391. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7392. error(memberLoc, "location is too large", "location", "");
  7393. memberQualifier.layoutLocation = nextLocation;
  7394. memberQualifier.layoutComponent = 0;
  7395. }
  7396. nextLocation = memberQualifier.layoutLocation +
  7397. intermediate.computeTypeLocationSize(*typeList[member].type, language);
  7398. }
  7399. }
  7400. }
  7401. }
  7402. void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7403. {
  7404. // "If a block is qualified with xfb_offset, all its
  7405. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7406. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7407. // offsets."
  7408. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7409. return;
  7410. int nextOffset = qualifier.layoutXfbOffset;
  7411. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7412. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7413. bool containsDouble = false;
  7414. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
  7415. // see if we need to auto-assign an offset to this member
  7416. if (! memberQualifier.hasXfbOffset()) {
  7417. // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
  7418. if (containsDouble)
  7419. RoundToPow2(nextOffset, 8);
  7420. memberQualifier.layoutXfbOffset = nextOffset;
  7421. } else
  7422. nextOffset = memberQualifier.layoutXfbOffset;
  7423. nextOffset += memberSize;
  7424. }
  7425. // The above gave all block members an offset, so we can take it off the block now,
  7426. // which will avoid double counting the offset usage.
  7427. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7428. }
  7429. // Calculate and save the offset of each block member, using the recursively
  7430. // defined block offset rules and the user-provided offset and align.
  7431. //
  7432. // Also, compute and save the total size of the block. For the block's size, arrayness
  7433. // is not taken into account, as each element is backed by a separate buffer.
  7434. //
  7435. void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
  7436. {
  7437. if (! qualifier.isUniformOrBuffer())
  7438. return;
  7439. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7440. return;
  7441. int offset = 0;
  7442. int memberSize;
  7443. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7444. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7445. const TSourceLoc& memberLoc = typeList[member].loc;
  7446. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7447. // modify just the children's view of matrix layout, if there is one for this member
  7448. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7449. int dummyStride;
  7450. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
  7451. qualifier.layoutPacking,
  7452. subMatrixLayout != ElmNone
  7453. ? subMatrixLayout == ElmRowMajor
  7454. : qualifier.layoutMatrix == ElmRowMajor);
  7455. if (memberQualifier.hasOffset()) {
  7456. // "The specified offset must be a multiple
  7457. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7458. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7459. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7460. // "The offset qualifier forces the qualified member to start at or after the specified
  7461. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7462. // "The actual offset of a member is computed as
  7463. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7464. offset = std::max(offset, memberQualifier.layoutOffset);
  7465. }
  7466. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7467. // (e.g., std140) base alignment for the member's type."
  7468. if (memberQualifier.hasAlign())
  7469. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7470. // "If the resulting offset is not a multiple of the actual alignment,
  7471. // increase it to the first offset that is a multiple of
  7472. // the actual alignment."
  7473. RoundToPow2(offset, memberAlignment);
  7474. typeList[member].type->getQualifier().layoutOffset = offset;
  7475. offset += memberSize;
  7476. }
  7477. }
  7478. // For an identifier that is already declared, add more qualification to it.
  7479. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  7480. {
  7481. TSymbol* symbol = symbolTable.find(identifier);
  7482. if (symbol == nullptr) {
  7483. error(loc, "identifier not previously declared", identifier.c_str(), "");
  7484. return;
  7485. }
  7486. if (symbol->getAsFunction()) {
  7487. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  7488. return;
  7489. }
  7490. if (qualifier.isAuxiliary() ||
  7491. qualifier.isMemory() ||
  7492. qualifier.isInterpolation() ||
  7493. qualifier.hasLayout() ||
  7494. qualifier.storage != EvqTemporary ||
  7495. qualifier.precision != EpqNone) {
  7496. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  7497. return;
  7498. }
  7499. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  7500. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  7501. if (symbol->isReadOnly())
  7502. symbol = symbolTable.copyUp(symbol);
  7503. if (qualifier.invariant) {
  7504. if (intermediate.inIoAccessed(identifier))
  7505. error(loc, "cannot change qualification after use", "invariant", "");
  7506. symbol->getWritableType().getQualifier().invariant = true;
  7507. } else if (qualifier.noContraction) {
  7508. if (intermediate.inIoAccessed(identifier))
  7509. error(loc, "cannot change qualification after use", "precise", "");
  7510. symbol->getWritableType().getQualifier().noContraction = true;
  7511. } else if (qualifier.specConstant) {
  7512. symbol->getWritableType().getQualifier().makeSpecConstant();
  7513. if (qualifier.hasSpecConstantId())
  7514. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  7515. } else
  7516. warn(loc, "unknown requalification", "", "");
  7517. }
  7518. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  7519. {
  7520. for (unsigned int i = 0; i < identifiers.size(); ++i)
  7521. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  7522. }
  7523. //
  7524. // Update the intermediate for the given input geometry
  7525. //
  7526. bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7527. {
  7528. switch (geometry) {
  7529. case ElgPoints: // fall through
  7530. case ElgLines: // ...
  7531. case ElgTriangles: // ...
  7532. case ElgLinesAdjacency: // ...
  7533. case ElgTrianglesAdjacency: // ...
  7534. if (! intermediate.setInputPrimitive(geometry)) {
  7535. error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7536. return false;
  7537. }
  7538. break;
  7539. default:
  7540. error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
  7541. return false;
  7542. }
  7543. return true;
  7544. }
  7545. //
  7546. // Update the intermediate for the given output geometry
  7547. //
  7548. bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7549. {
  7550. // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
  7551. // Since that's an OK situation, return true for success.
  7552. if (language != EShLangGeometry)
  7553. return true;
  7554. switch (geometry) {
  7555. case ElgPoints:
  7556. case ElgLineStrip:
  7557. case ElgTriangleStrip:
  7558. if (! intermediate.setOutputPrimitive(geometry)) {
  7559. error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7560. return false;
  7561. }
  7562. break;
  7563. default:
  7564. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
  7565. return false;
  7566. }
  7567. return true;
  7568. }
  7569. //
  7570. // Selection attributes
  7571. //
  7572. void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
  7573. const TAttributes& attributes)
  7574. {
  7575. if (selection == nullptr)
  7576. return;
  7577. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7578. switch (it->name) {
  7579. case EatFlatten:
  7580. selection->setFlatten();
  7581. break;
  7582. case EatBranch:
  7583. selection->setDontFlatten();
  7584. break;
  7585. default:
  7586. warn(loc, "attribute does not apply to a selection", "", "");
  7587. break;
  7588. }
  7589. }
  7590. }
  7591. //
  7592. // Switch attributes
  7593. //
  7594. void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
  7595. const TAttributes& attributes)
  7596. {
  7597. if (selection == nullptr)
  7598. return;
  7599. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7600. switch (it->name) {
  7601. case EatFlatten:
  7602. selection->setFlatten();
  7603. break;
  7604. case EatBranch:
  7605. selection->setDontFlatten();
  7606. break;
  7607. default:
  7608. warn(loc, "attribute does not apply to a switch", "", "");
  7609. break;
  7610. }
  7611. }
  7612. }
  7613. //
  7614. // Loop attributes
  7615. //
  7616. void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
  7617. const TAttributes& attributes)
  7618. {
  7619. if (loop == nullptr)
  7620. return;
  7621. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7622. switch (it->name) {
  7623. case EatUnroll:
  7624. loop->setUnroll();
  7625. break;
  7626. case EatLoop:
  7627. loop->setDontUnroll();
  7628. break;
  7629. default:
  7630. warn(loc, "attribute does not apply to a loop", "", "");
  7631. break;
  7632. }
  7633. }
  7634. }
  7635. //
  7636. // Updating default qualifier for the case of a declaration with just a qualifier,
  7637. // no type, block, or identifier.
  7638. //
  7639. void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  7640. {
  7641. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  7642. assert(language == EShLangTessControl || language == EShLangGeometry);
  7643. // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  7644. }
  7645. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  7646. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  7647. error(loc, "cannot change previously set layout value", "invocations", "");
  7648. }
  7649. if (publicType.shaderQualifiers.geometry != ElgNone) {
  7650. if (publicType.qualifier.storage == EvqVaryingIn) {
  7651. switch (publicType.shaderQualifiers.geometry) {
  7652. case ElgPoints:
  7653. case ElgLines:
  7654. case ElgLinesAdjacency:
  7655. case ElgTriangles:
  7656. case ElgTrianglesAdjacency:
  7657. case ElgQuads:
  7658. case ElgIsolines:
  7659. break;
  7660. default:
  7661. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7662. "");
  7663. }
  7664. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  7665. handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
  7666. } else
  7667. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7668. GetStorageQualifierString(publicType.qualifier.storage));
  7669. }
  7670. if (publicType.shaderQualifiers.spacing != EvsNone)
  7671. intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
  7672. if (publicType.shaderQualifiers.order != EvoNone)
  7673. intermediate.setVertexOrder(publicType.shaderQualifiers.order);
  7674. if (publicType.shaderQualifiers.pointMode)
  7675. intermediate.setPointMode();
  7676. for (int i = 0; i < 3; ++i) {
  7677. if (publicType.shaderQualifiers.localSize[i] > 1) {
  7678. int max = 0;
  7679. switch (i) {
  7680. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  7681. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  7682. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  7683. default: break;
  7684. }
  7685. if (intermediate.getLocalSize(i) > (unsigned int)max)
  7686. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  7687. // Fix the existing constant gl_WorkGroupSize with this new information.
  7688. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7689. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  7690. }
  7691. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  7692. intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
  7693. // Set the workgroup built-in variable as a specialization constant
  7694. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7695. workGroupSize->getWritableType().getQualifier().specConstant = true;
  7696. }
  7697. }
  7698. if (publicType.shaderQualifiers.earlyFragmentTests)
  7699. intermediate.setEarlyFragmentTests();
  7700. const TQualifier& qualifier = publicType.qualifier;
  7701. switch (qualifier.storage) {
  7702. case EvqUniform:
  7703. if (qualifier.hasMatrix())
  7704. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  7705. if (qualifier.hasPacking())
  7706. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  7707. break;
  7708. case EvqBuffer:
  7709. if (qualifier.hasMatrix())
  7710. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  7711. if (qualifier.hasPacking())
  7712. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  7713. break;
  7714. case EvqVaryingIn:
  7715. break;
  7716. case EvqVaryingOut:
  7717. if (qualifier.hasStream())
  7718. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  7719. if (qualifier.hasXfbBuffer())
  7720. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  7721. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  7722. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  7723. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
  7724. qualifier.layoutXfbBuffer);
  7725. }
  7726. break;
  7727. default:
  7728. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
  7729. return;
  7730. }
  7731. }
  7732. //
  7733. // Take the sequence of statements that has been built up since the last case/default,
  7734. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  7735. // and follow that by the case/default we are on now. (See switch topology comment on
  7736. // TIntermSwitch.)
  7737. //
  7738. void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  7739. {
  7740. TIntermSequence* switchSequence = switchSequenceStack.back();
  7741. if (statements) {
  7742. statements->setOperator(EOpSequence);
  7743. switchSequence->push_back(statements);
  7744. }
  7745. if (branchNode) {
  7746. // check all previous cases for the same label (or both are 'default')
  7747. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  7748. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  7749. if (prevBranch) {
  7750. TIntermTyped* prevExpression = prevBranch->getExpression();
  7751. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  7752. if (prevExpression == nullptr && newExpression == nullptr)
  7753. error(branchNode->getLoc(), "duplicate label", "default", "");
  7754. else if (prevExpression != nullptr &&
  7755. newExpression != nullptr &&
  7756. prevExpression->getAsConstantUnion() &&
  7757. newExpression->getAsConstantUnion() &&
  7758. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  7759. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  7760. error(branchNode->getLoc(), "duplicated value", "case", "");
  7761. }
  7762. }
  7763. switchSequence->push_back(branchNode);
  7764. }
  7765. }
  7766. //
  7767. // Turn the top-level node sequence built up of wrapupSwitchSubsequence
  7768. // into a switch node.
  7769. //
  7770. TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
  7771. TIntermAggregate* lastStatements, const TAttributes& attributes)
  7772. {
  7773. wrapupSwitchSubsequence(lastStatements, nullptr);
  7774. if (expression == nullptr ||
  7775. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  7776. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  7777. error(loc, "condition must be a scalar integer expression", "switch", "");
  7778. // If there is nothing to do, drop the switch but still execute the expression
  7779. TIntermSequence* switchSequence = switchSequenceStack.back();
  7780. if (switchSequence->size() == 0)
  7781. return expression;
  7782. if (lastStatements == nullptr) {
  7783. // emulate a break for error recovery
  7784. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  7785. lastStatements->setOperator(EOpSequence);
  7786. switchSequence->push_back(lastStatements);
  7787. }
  7788. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  7789. body->getSequence() = *switchSequenceStack.back();
  7790. body->setLoc(loc);
  7791. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  7792. switchNode->setLoc(loc);
  7793. handleSwitchAttributes(loc, switchNode, attributes);
  7794. return switchNode;
  7795. }
  7796. // Make a new symbol-table level that is made out of the members of a structure.
  7797. // This should be done as an anonymous struct (name is "") so that the symbol table
  7798. // finds the members with no explicit reference to a 'this' variable.
  7799. void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
  7800. {
  7801. // member variables
  7802. TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
  7803. symbolTable.pushThis(thisVariable);
  7804. // member functions
  7805. for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
  7806. // member should have a prefix matching currentTypePrefix.back()
  7807. // but, symbol lookup within the class scope will just use the
  7808. // unprefixed name. Hence, there are two: one fully prefixed and
  7809. // one with no prefix.
  7810. TFunction& member = *it->function->clone();
  7811. member.removePrefix(currentTypePrefix.back());
  7812. symbolTable.insert(member);
  7813. }
  7814. }
  7815. // Track levels of class/struct/namespace nesting with a prefix string using
  7816. // the type names separated by the scoping operator. E.g., two levels
  7817. // would look like:
  7818. //
  7819. // outer::inner
  7820. //
  7821. // The string is empty when at normal global level.
  7822. //
  7823. void HlslParseContext::pushNamespace(const TString& typeName)
  7824. {
  7825. // make new type prefix
  7826. TString newPrefix;
  7827. if (currentTypePrefix.size() > 0)
  7828. newPrefix = currentTypePrefix.back();
  7829. newPrefix.append(typeName);
  7830. newPrefix.append(scopeMangler);
  7831. currentTypePrefix.push_back(newPrefix);
  7832. }
  7833. // Opposite of pushNamespace(), see above
  7834. void HlslParseContext::popNamespace()
  7835. {
  7836. currentTypePrefix.pop_back();
  7837. }
  7838. // Use the class/struct nesting string to create a global name for
  7839. // a member of a class/struct.
  7840. void HlslParseContext::getFullNamespaceName(TString*& name) const
  7841. {
  7842. if (currentTypePrefix.size() == 0)
  7843. return;
  7844. TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
  7845. fullName->append(*name);
  7846. name = fullName;
  7847. }
  7848. // Helper function to add the namespace scope mangling syntax to a string.
  7849. void HlslParseContext::addScopeMangler(TString& name)
  7850. {
  7851. name.append(scopeMangler);
  7852. }
  7853. // Return true if this has uniform-interface like decorations.
  7854. bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
  7855. {
  7856. return qualifier.hasUniformLayout() ||
  7857. qualifier.layoutPushConstant;
  7858. }
  7859. // Potentially not the opposite of hasUniform(), as if some characteristic is
  7860. // ever used for more than one thing (e.g., uniform or input), hasUniform() should
  7861. // say it exists, but clearUniform() should leave it in place.
  7862. void HlslParseContext::clearUniform(TQualifier& qualifier)
  7863. {
  7864. qualifier.clearUniformLayout();
  7865. qualifier.layoutPushConstant = false;
  7866. }
  7867. // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
  7868. bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
  7869. {
  7870. switch (qualifier.builtIn) {
  7871. case EbvPosition:
  7872. case EbvPointSize:
  7873. return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
  7874. case EbvClipDistance:
  7875. case EbvCullDistance:
  7876. return language != EShLangVertex && language != EShLangCompute;
  7877. case EbvFragCoord:
  7878. case EbvFace:
  7879. case EbvHelperInvocation:
  7880. case EbvLayer:
  7881. case EbvPointCoord:
  7882. case EbvSampleId:
  7883. case EbvSampleMask:
  7884. case EbvSamplePosition:
  7885. case EbvViewportIndex:
  7886. return language == EShLangFragment;
  7887. case EbvGlobalInvocationId:
  7888. case EbvLocalInvocationIndex:
  7889. case EbvLocalInvocationId:
  7890. case EbvNumWorkGroups:
  7891. case EbvWorkGroupId:
  7892. case EbvWorkGroupSize:
  7893. return language == EShLangCompute;
  7894. case EbvInvocationId:
  7895. return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
  7896. case EbvPatchVertices:
  7897. return language == EShLangTessControl || language == EShLangTessEvaluation;
  7898. case EbvInstanceId:
  7899. case EbvInstanceIndex:
  7900. case EbvVertexId:
  7901. case EbvVertexIndex:
  7902. return language == EShLangVertex;
  7903. case EbvPrimitiveId:
  7904. return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
  7905. case EbvTessLevelInner:
  7906. case EbvTessLevelOuter:
  7907. return language == EShLangTessEvaluation;
  7908. case EbvTessCoord:
  7909. return language == EShLangTessEvaluation;
  7910. default:
  7911. return false;
  7912. }
  7913. }
  7914. // Return true if there are decorations to preserve for input-like storage.
  7915. bool HlslParseContext::hasInput(const TQualifier& qualifier) const
  7916. {
  7917. if (qualifier.hasAnyLocation())
  7918. return true;
  7919. if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
  7920. return true;
  7921. if (language == EShLangTessEvaluation && qualifier.patch)
  7922. return true;
  7923. if (isInputBuiltIn(qualifier))
  7924. return true;
  7925. return false;
  7926. }
  7927. // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
  7928. bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
  7929. {
  7930. switch (qualifier.builtIn) {
  7931. case EbvPosition:
  7932. case EbvPointSize:
  7933. case EbvClipVertex:
  7934. case EbvClipDistance:
  7935. case EbvCullDistance:
  7936. return language != EShLangFragment && language != EShLangCompute;
  7937. case EbvFragDepth:
  7938. case EbvFragDepthGreater:
  7939. case EbvFragDepthLesser:
  7940. case EbvSampleMask:
  7941. return language == EShLangFragment;
  7942. case EbvLayer:
  7943. case EbvViewportIndex:
  7944. return language == EShLangGeometry || language == EShLangVertex;
  7945. case EbvPrimitiveId:
  7946. return language == EShLangGeometry;
  7947. case EbvTessLevelInner:
  7948. case EbvTessLevelOuter:
  7949. return language == EShLangTessControl;
  7950. default:
  7951. return false;
  7952. }
  7953. }
  7954. // Return true if there are decorations to preserve for output-like storage.
  7955. bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
  7956. {
  7957. if (qualifier.hasAnyLocation())
  7958. return true;
  7959. if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
  7960. return true;
  7961. if (language == EShLangTessControl && qualifier.patch)
  7962. return true;
  7963. if (language == EShLangGeometry && qualifier.hasStream())
  7964. return true;
  7965. if (isOutputBuiltIn(qualifier))
  7966. return true;
  7967. return false;
  7968. }
  7969. // Make the IO decorations etc. be appropriate only for an input interface.
  7970. void HlslParseContext::correctInput(TQualifier& qualifier)
  7971. {
  7972. clearUniform(qualifier);
  7973. if (language == EShLangVertex)
  7974. qualifier.clearInterstage();
  7975. if (language != EShLangTessEvaluation)
  7976. qualifier.patch = false;
  7977. if (language != EShLangFragment) {
  7978. qualifier.clearInterpolation();
  7979. qualifier.sample = false;
  7980. }
  7981. qualifier.clearStreamLayout();
  7982. qualifier.clearXfbLayout();
  7983. if (! isInputBuiltIn(qualifier))
  7984. qualifier.builtIn = EbvNone;
  7985. }
  7986. // Make the IO decorations etc. be appropriate only for an output interface.
  7987. void HlslParseContext::correctOutput(TQualifier& qualifier)
  7988. {
  7989. clearUniform(qualifier);
  7990. if (language == EShLangFragment)
  7991. qualifier.clearInterstage();
  7992. if (language != EShLangGeometry)
  7993. qualifier.clearStreamLayout();
  7994. if (language == EShLangFragment)
  7995. qualifier.clearXfbLayout();
  7996. if (language != EShLangTessControl)
  7997. qualifier.patch = false;
  7998. switch (qualifier.builtIn) {
  7999. case EbvFragDepth:
  8000. intermediate.setDepthReplacing();
  8001. intermediate.setDepth(EldAny);
  8002. break;
  8003. case EbvFragDepthGreater:
  8004. intermediate.setDepthReplacing();
  8005. intermediate.setDepth(EldGreater);
  8006. qualifier.builtIn = EbvFragDepth;
  8007. break;
  8008. case EbvFragDepthLesser:
  8009. intermediate.setDepthReplacing();
  8010. intermediate.setDepth(EldLess);
  8011. qualifier.builtIn = EbvFragDepth;
  8012. break;
  8013. default:
  8014. break;
  8015. }
  8016. if (! isOutputBuiltIn(qualifier))
  8017. qualifier.builtIn = EbvNone;
  8018. }
  8019. // Make the IO decorations etc. be appropriate only for uniform type interfaces.
  8020. void HlslParseContext::correctUniform(TQualifier& qualifier)
  8021. {
  8022. if (qualifier.declaredBuiltIn == EbvNone)
  8023. qualifier.declaredBuiltIn = qualifier.builtIn;
  8024. qualifier.builtIn = EbvNone;
  8025. qualifier.clearInterstage();
  8026. qualifier.clearInterstageLayout();
  8027. }
  8028. // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
  8029. void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
  8030. {
  8031. clearUniform(qualifier);
  8032. correctUniform(qualifier);
  8033. }
  8034. // Set texture return type. Returns success (not all types are valid).
  8035. bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
  8036. {
  8037. // Seed the output with an invalid index. We will set it to a valid one if we can.
  8038. sampler.structReturnIndex = TSampler::noReturnStruct;
  8039. // Arrays aren't supported.
  8040. if (retType.isArray()) {
  8041. error(loc, "Arrays not supported in texture template types", "", "");
  8042. return false;
  8043. }
  8044. // If return type is a vector, remember the vector size in the sampler, and return.
  8045. if (retType.isVector() || retType.isScalar()) {
  8046. sampler.vectorSize = retType.getVectorSize();
  8047. return true;
  8048. }
  8049. // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
  8050. // are checked below: just check for struct-ness here.
  8051. if (!retType.isStruct()) {
  8052. error(loc, "Invalid texture template type", "", "");
  8053. return false;
  8054. }
  8055. // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
  8056. if (sampler.isSubpass()) {
  8057. error(loc, "Unimplemented: structure template type in subpass input", "", "");
  8058. return false;
  8059. }
  8060. TTypeList* members = retType.getWritableStruct();
  8061. // Check for too many or not enough structure members.
  8062. if (members->size() > 4 || members->size() == 0) {
  8063. error(loc, "Invalid member count in texture template structure", "", "");
  8064. return false;
  8065. }
  8066. // Error checking: We must have <= 4 total components, all of the same basic type.
  8067. unsigned totalComponents = 0;
  8068. for (unsigned m = 0; m < members->size(); ++m) {
  8069. // Check for bad member types
  8070. if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
  8071. error(loc, "Invalid texture template struct member type", "", "");
  8072. return false;
  8073. }
  8074. const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
  8075. totalComponents += memberVectorSize;
  8076. // too many total member components
  8077. if (totalComponents > 4) {
  8078. error(loc, "Too many components in texture template structure type", "", "");
  8079. return false;
  8080. }
  8081. // All members must be of a common basic type
  8082. if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
  8083. error(loc, "Texture template structure members must same basic type", "", "");
  8084. return false;
  8085. }
  8086. }
  8087. // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
  8088. // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
  8089. for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
  8090. if (textureReturnStruct[idx] == members) {
  8091. sampler.structReturnIndex = idx;
  8092. return true;
  8093. }
  8094. }
  8095. // It wasn't found as an existing entry. See if we have room for a new one.
  8096. if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
  8097. error(loc, "Texture template struct return slots exceeded", "", "");
  8098. return false;
  8099. }
  8100. // Insert it in the vector that tracks struct return types.
  8101. sampler.structReturnIndex = unsigned(textureReturnStruct.size());
  8102. textureReturnStruct.push_back(members);
  8103. // Success!
  8104. return true;
  8105. }
  8106. // Return the sampler return type in retType.
  8107. void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
  8108. {
  8109. if (sampler.hasReturnStruct()) {
  8110. assert(textureReturnStruct.size() >= sampler.structReturnIndex);
  8111. // We land here if the texture return is a structure.
  8112. TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
  8113. const TType resultType(blockStruct, "");
  8114. retType.shallowCopy(resultType);
  8115. } else {
  8116. // We land here if the texture return is a vector or scalar.
  8117. const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
  8118. retType.shallowCopy(resultType);
  8119. }
  8120. }
  8121. // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
  8122. TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
  8123. {
  8124. const auto it = builtInTessLinkageSymbols.find(biType);
  8125. if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
  8126. return nullptr;
  8127. return intermediate.addSymbol(*it->second->getAsVariable());
  8128. }
  8129. // Find the patch constant function (issues error, returns nullptr if not found)
  8130. const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
  8131. {
  8132. if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
  8133. error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
  8134. return nullptr;
  8135. }
  8136. const TString mangledName = patchConstantFunctionName + "(";
  8137. // create list of PCF candidates
  8138. TVector<const TFunction*> candidateList;
  8139. bool builtIn;
  8140. symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
  8141. // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
  8142. // allow any disambiguation of overloads.
  8143. if (candidateList.empty()) {
  8144. error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
  8145. return nullptr;
  8146. }
  8147. // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
  8148. // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
  8149. // out if there is more than one candidate.
  8150. if (candidateList.size() > 1) {
  8151. error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
  8152. return nullptr;
  8153. }
  8154. return candidateList[0];
  8155. }
  8156. // Finalization step: Add patch constant function invocation
  8157. void HlslParseContext::addPatchConstantInvocation()
  8158. {
  8159. TSourceLoc loc;
  8160. loc.init();
  8161. // If there's no patch constant function, or we're not a HS, do nothing.
  8162. if (patchConstantFunctionName.empty() || language != EShLangTessControl)
  8163. return;
  8164. // Look for built-in variables in a function's parameter list.
  8165. const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
  8166. for (int p=0; p<function.getParamCount(); ++p) {
  8167. TStorageQualifier storage = function[p].type->getQualifier().storage;
  8168. if (storage == EvqConstReadOnly) // treated identically to input
  8169. storage = EvqIn;
  8170. if (function[p].getDeclaredBuiltIn() != EbvNone)
  8171. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
  8172. else
  8173. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
  8174. }
  8175. };
  8176. // If we synthesize a built-in interface variable, we must add it to the linkage.
  8177. const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
  8178. if (name == nullptr) {
  8179. error(loc, "unable to locate patch function parameter name", "", "");
  8180. return;
  8181. } else {
  8182. TVariable& variable = *new TVariable(name, type);
  8183. if (! symbolTable.insert(variable)) {
  8184. error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
  8185. return;
  8186. }
  8187. globalQualifierFix(loc, variable.getWritableType().getQualifier());
  8188. if (symbolNode != nullptr)
  8189. *symbolNode = intermediate.addSymbol(variable);
  8190. trackLinkage(variable);
  8191. }
  8192. };
  8193. const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
  8194. const TType& type = *patchConstantFunction[param].type;
  8195. const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
  8196. return type.isSizedArray() && biType == EbvOutputPatch;
  8197. };
  8198. // We will perform these steps. Each is in a scoped block for separation: they could
  8199. // become separate functions to make addPatchConstantInvocation shorter.
  8200. //
  8201. // 1. Union the interfaces, and create built-ins for anything present in the PCF and
  8202. // declared as a built-in variable that isn't present in the entry point's signature.
  8203. //
  8204. // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
  8205. // or the ones we created. Matching is based on built-in type. We may use synthesized
  8206. // variables from (1) above.
  8207. //
  8208. // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
  8209. //
  8210. // 3. Create a return sequence: copy the return value (if any) from the PCF to a
  8211. // (non-sanitized) output variable. In case this may involve multiple copies, such as for
  8212. // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
  8213. // indirections into a complex R-value coming from the call to the PCF.
  8214. //
  8215. // 4. Create a barrier.
  8216. //
  8217. // 5/5B. Call the PCF inside an if test for (invocation id == 0).
  8218. TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
  8219. if (patchConstantFunctionPtr == nullptr)
  8220. return;
  8221. TFunction& patchConstantFunction = *patchConstantFunctionPtr;
  8222. const int pcfParamCount = patchConstantFunction.getParamCount();
  8223. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  8224. TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
  8225. int outPatchParam = -1; // -1 means there isn't one.
  8226. // ================ Step 1A: Union Interfaces ================
  8227. // Our patch constant function.
  8228. {
  8229. std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
  8230. std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
  8231. assert(entryPointFunction);
  8232. assert(entryPointFunctionBody);
  8233. findBuiltIns(patchConstantFunction, pcfBuiltIns);
  8234. findBuiltIns(*entryPointFunction, epfBuiltIns);
  8235. // Find the set of built-ins in the PCF that are not present in the entry point.
  8236. std::set<tInterstageIoData> notInEntryPoint;
  8237. notInEntryPoint = pcfBuiltIns;
  8238. // std::set_difference not usable on unordered containers
  8239. for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
  8240. notInEntryPoint.erase(*bi);
  8241. // Now we'll add those to the entry and to the linkage.
  8242. for (int p=0; p<pcfParamCount; ++p) {
  8243. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8244. TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
  8245. // Track whether there is an output patch param
  8246. if (isOutputPatch(patchConstantFunction, p)) {
  8247. if (outPatchParam >= 0) {
  8248. // Presently we only support one per ctrl pt input.
  8249. error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
  8250. return;
  8251. }
  8252. outPatchParam = p;
  8253. }
  8254. if (biType != EbvNone) {
  8255. TType* paramType = patchConstantFunction[p].type->clone();
  8256. if (storage == EvqConstReadOnly) // treated identically to input
  8257. storage = EvqIn;
  8258. // Presently, the only non-built-in we support is InputPatch, which is treated as
  8259. // a pseudo-built-in.
  8260. if (biType == EbvInputPatch) {
  8261. builtInTessLinkageSymbols[biType] = inputPatch;
  8262. } else if (biType == EbvOutputPatch) {
  8263. // Nothing...
  8264. } else {
  8265. // Use the original declaration type for the linkage
  8266. paramType->getQualifier().builtIn = biType;
  8267. if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
  8268. addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
  8269. }
  8270. }
  8271. }
  8272. // If we didn't find it because the shader made one, add our own.
  8273. if (invocationIdSym == nullptr) {
  8274. TType invocationIdType(EbtUint, EvqIn, 1);
  8275. TString* invocationIdName = NewPoolTString("InvocationId");
  8276. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  8277. addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
  8278. }
  8279. assert(invocationIdSym);
  8280. }
  8281. TIntermTyped* pcfArguments = nullptr;
  8282. TVariable* perCtrlPtVar = nullptr;
  8283. // ================ Step 1B: Argument synthesis ================
  8284. // Create pcfArguments for synthesis of patchconstantfunction invocation
  8285. {
  8286. for (int p=0; p<pcfParamCount; ++p) {
  8287. TIntermTyped* inputArg = nullptr;
  8288. if (p == outPatchParam) {
  8289. if (perCtrlPtVar == nullptr) {
  8290. perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
  8291. *patchConstantFunction[outPatchParam].type);
  8292. perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
  8293. }
  8294. inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
  8295. } else {
  8296. // find which built-in it is
  8297. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8298. if (biType == EbvInputPatch && inputPatch == nullptr) {
  8299. error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
  8300. return;
  8301. }
  8302. inputArg = findTessLinkageSymbol(biType);
  8303. if (inputArg == nullptr) {
  8304. error(loc, "unable to find patch constant function built-in variable", "", "");
  8305. return;
  8306. }
  8307. }
  8308. if (pcfParamCount == 1)
  8309. pcfArguments = inputArg;
  8310. else
  8311. pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
  8312. }
  8313. }
  8314. // ================ Step 2: Synthesize call to PCF ================
  8315. TIntermAggregate* pcfCallSequence = nullptr;
  8316. TIntermTyped* pcfCall = nullptr;
  8317. {
  8318. // Create a function call to the patchconstantfunction
  8319. if (pcfArguments)
  8320. addInputArgumentConversions(patchConstantFunction, pcfArguments);
  8321. // Synthetic call.
  8322. pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
  8323. pcfCall->getAsAggregate()->setUserDefined();
  8324. pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
  8325. intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
  8326. patchConstantFunction.getMangledName());
  8327. if (pcfCall->getAsAggregate()) {
  8328. TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
  8329. for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
  8330. TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
  8331. qualifierList.push_back(qual);
  8332. }
  8333. pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
  8334. }
  8335. }
  8336. // ================ Step 2B: Per Control Point synthesis ================
  8337. // If there is per control point data, we must either emulate that with multiple
  8338. // invocations of the entry point to build up an array, or (TODO:) use a yet
  8339. // unavailable extension to look across the SIMD lanes. This is the former
  8340. // as a placeholder for the latter.
  8341. if (outPatchParam >= 0) {
  8342. // We must introduce a local temp variable of the type wanted by the PCF input.
  8343. const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
  8344. if (entryPointFunction->getType().getBasicType() == EbtVoid) {
  8345. error(loc, "entry point must return a value for use with patch constant function", "", "");
  8346. return;
  8347. }
  8348. // Create calls to wrapped main to fill in the array. We will substitute fixed values
  8349. // of invocation ID when calling the wrapped main.
  8350. // This is the type of the each member of the per ctrl point array.
  8351. const TType derefType(perCtrlPtVar->getType(), 0);
  8352. for (int cpt = 0; cpt < arraySize; ++cpt) {
  8353. // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
  8354. // for this function.
  8355. const TString origName = entryPointFunction->getName().substr(1);
  8356. TFunction callee(&origName, TType(EbtVoid));
  8357. TIntermTyped* callingArgs = nullptr;
  8358. for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
  8359. TParameter& param = (*entryPointFunction)[i];
  8360. TType& paramType = *param.type;
  8361. if (paramType.getQualifier().isParamOutput()) {
  8362. error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
  8363. return;
  8364. }
  8365. if (paramType.getQualifier().isParamInput()) {
  8366. TIntermTyped* arg = nullptr;
  8367. if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
  8368. // substitute invocation ID with the array element ID
  8369. arg = intermediate.addConstantUnion(cpt, loc);
  8370. } else {
  8371. TVariable* argVar = makeInternalVariable(*param.name, *param.type);
  8372. argVar->getWritableType().getQualifier().makeTemporary();
  8373. arg = intermediate.addSymbol(*argVar);
  8374. }
  8375. handleFunctionArgument(&callee, callingArgs, arg);
  8376. }
  8377. }
  8378. // Call and assign to per ctrl point variable
  8379. currentCaller = intermediate.getEntryPointMangledName().c_str();
  8380. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  8381. TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
  8382. TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
  8383. TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
  8384. element->setType(derefType);
  8385. element->setLoc(loc);
  8386. pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
  8387. handleAssign(loc, EOpAssign, element, callReturn));
  8388. }
  8389. }
  8390. // ================ Step 3: Create return Sequence ================
  8391. // Return sequence: copy PCF result to a temporary, then to shader output variable.
  8392. if (pcfCall->getBasicType() != EbtVoid) {
  8393. const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
  8394. TType outType; // output type that goes with the return type.
  8395. outType.shallowCopy(*retType);
  8396. // substitute the output type
  8397. const auto newLists = ioTypeMap.find(retType->getStruct());
  8398. if (newLists != ioTypeMap.end())
  8399. outType.setStruct(newLists->second.output);
  8400. // Substitute the top level type's built-in type
  8401. if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
  8402. outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
  8403. outType.getQualifier().patch = true; // make it a per-patch variable
  8404. TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
  8405. pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
  8406. if (pcfOutput->getType().containsBuiltIn())
  8407. split(*pcfOutput);
  8408. assignToInterface(*pcfOutput);
  8409. TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
  8410. // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
  8411. // repeated calls to the PCF:
  8412. TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
  8413. pcfCallResult->getWritableType().getQualifier().makeTemporary();
  8414. TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
  8415. TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
  8416. TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
  8417. intermediate.addSymbol(*pcfCallResult, loc));
  8418. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
  8419. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
  8420. } else {
  8421. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
  8422. }
  8423. // ================ Step 4: Barrier ================
  8424. TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
  8425. barrier->setLoc(loc);
  8426. barrier->setType(TType(EbtVoid));
  8427. epBodySeq.insert(epBodySeq.end(), barrier);
  8428. // ================ Step 5: Test on invocation ID ================
  8429. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  8430. TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
  8431. // ================ Step 5B: Create if statement on Invocation ID == 0 ================
  8432. intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
  8433. TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
  8434. invocationIdTest->setLoc(loc);
  8435. // add our test sequence before the return.
  8436. epBodySeq.insert(epBodySeq.end(), invocationIdTest);
  8437. }
  8438. // Finalization step: remove unused buffer blocks from linkage (we don't know until the
  8439. // shader is entirely compiled).
  8440. // Preserve order of remaining symbols.
  8441. void HlslParseContext::removeUnusedStructBufferCounters()
  8442. {
  8443. const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
  8444. [this](const TSymbol* sym) {
  8445. const auto sbcIt = structBufferCounter.find(sym->getName());
  8446. return sbcIt != structBufferCounter.end() && !sbcIt->second;
  8447. });
  8448. linkageSymbols.erase(endIt, linkageSymbols.end());
  8449. }
  8450. // Finalization step: patch texture shadow modes to match samplers they were combined with
  8451. void HlslParseContext::fixTextureShadowModes()
  8452. {
  8453. for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
  8454. TSampler& sampler = (*symbol)->getWritableType().getSampler();
  8455. if (sampler.isTexture()) {
  8456. const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
  8457. if (shadowMode != textureShadowVariant.end()) {
  8458. if (shadowMode->second->overloaded())
  8459. // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
  8460. intermediate.setNeedsLegalization();
  8461. sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
  8462. }
  8463. }
  8464. }
  8465. }
  8466. // Finalization step: patch append methods to use proper stream output, which isn't known until
  8467. // main is parsed, which could happen after the append method is parsed.
  8468. void HlslParseContext::finalizeAppendMethods()
  8469. {
  8470. TSourceLoc loc;
  8471. loc.init();
  8472. // Nothing to do: bypass test for valid stream output.
  8473. if (gsAppends.empty())
  8474. return;
  8475. if (gsStreamOutput == nullptr) {
  8476. error(loc, "unable to find output symbol for Append()", "", "");
  8477. return;
  8478. }
  8479. // Patch append sequences, now that we know the stream output symbol.
  8480. for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
  8481. append->node->getSequence()[0] =
  8482. handleAssign(append->loc, EOpAssign,
  8483. intermediate.addSymbol(*gsStreamOutput, append->loc),
  8484. append->node->getSequence()[0]->getAsTyped());
  8485. }
  8486. }
  8487. // post-processing
  8488. void HlslParseContext::finish()
  8489. {
  8490. // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
  8491. // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
  8492. if (! mipsOperatorMipArg.empty()) {
  8493. error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
  8494. }
  8495. removeUnusedStructBufferCounters();
  8496. addPatchConstantInvocation();
  8497. fixTextureShadowModes();
  8498. finalizeAppendMethods();
  8499. // Communicate out (esp. for command line) that we formed AST that will make
  8500. // illegal AST SPIR-V and it needs transforms to legalize it.
  8501. if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
  8502. infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
  8503. TParseContextBase::finish();
  8504. }
  8505. } // end namespace glslang