hlslParseHelper.cpp 416 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986
  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/Include/Common.h"
  41. #include "../glslang/MachineIndependent/Scan.h"
  42. #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
  43. #include "../glslang/OSDependent/osinclude.h"
  44. #include <algorithm>
  45. #include <functional>
  46. #include <cctype>
  47. #include <array>
  48. #include <set>
  49. namespace glslang {
  50. HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
  51. int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
  52. TInfoSink& infoSink,
  53. const TString sourceEntryPointName,
  54. bool forwardCompatible, EShMessages messages) :
  55. TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
  56. forwardCompatible, messages, &sourceEntryPointName),
  57. annotationNestingLevel(0),
  58. inputPatch(nullptr),
  59. nextInLocation(0), nextOutLocation(0),
  60. entryPointFunction(nullptr),
  61. entryPointFunctionBody(nullptr),
  62. gsStreamOutput(nullptr),
  63. clipDistanceOutput(nullptr),
  64. cullDistanceOutput(nullptr),
  65. clipDistanceInput(nullptr),
  66. cullDistanceInput(nullptr)
  67. {
  68. globalUniformDefaults.clear();
  69. globalUniformDefaults.layoutMatrix = ElmRowMajor;
  70. globalUniformDefaults.layoutPacking = ElpStd140;
  71. globalBufferDefaults.clear();
  72. globalBufferDefaults.layoutMatrix = ElmRowMajor;
  73. globalBufferDefaults.layoutPacking = ElpStd430;
  74. globalInputDefaults.clear();
  75. globalOutputDefaults.clear();
  76. clipSemanticNSizeIn.fill(0);
  77. cullSemanticNSizeIn.fill(0);
  78. clipSemanticNSizeOut.fill(0);
  79. cullSemanticNSizeOut.fill(0);
  80. // "Shaders in the transform
  81. // feedback capturing mode have an initial global default of
  82. // layout(xfb_buffer = 0) out;"
  83. if (language == EShLangVertex ||
  84. language == EShLangTessControl ||
  85. language == EShLangTessEvaluation ||
  86. language == EShLangGeometry)
  87. globalOutputDefaults.layoutXfbBuffer = 0;
  88. if (language == EShLangGeometry)
  89. globalOutputDefaults.layoutStream = 0;
  90. }
  91. HlslParseContext::~HlslParseContext()
  92. {
  93. }
  94. void HlslParseContext::initializeExtensionBehavior()
  95. {
  96. TParseContextBase::initializeExtensionBehavior();
  97. // HLSL allows #line by default.
  98. extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
  99. }
  100. void HlslParseContext::setLimits(const TBuiltInResource& r)
  101. {
  102. resources = r;
  103. intermediate.setLimits(resources);
  104. }
  105. //
  106. // Parse an array of strings using the parser in HlslRules.
  107. //
  108. // Returns true for successful acceptance of the shader, false if any errors.
  109. //
  110. bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  111. {
  112. currentScanner = &input;
  113. ppContext.setInput(input, versionWillBeError);
  114. HlslScanContext scanContext(*this, ppContext);
  115. HlslGrammar grammar(scanContext, *this);
  116. if (!grammar.parse()) {
  117. // Print a message formated such that if you click on the message it will take you right to
  118. // the line through most UIs.
  119. const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
  120. infoSink.info << sourceLoc.getFilenameStr() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
  121. << ", HLSL parsing failed.\n";
  122. ++numErrors;
  123. return false;
  124. }
  125. finish();
  126. return numErrors == 0;
  127. }
  128. //
  129. // Return true if this l-value node should be converted in some manner.
  130. // For instance: turning a load aggregate into a store in an l-value.
  131. //
  132. bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
  133. {
  134. if (node == nullptr || node->getAsTyped() == nullptr)
  135. return false;
  136. const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  137. const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
  138. // If it's a swizzled/indexed aggregate, look at the left node instead.
  139. if (lhsAsBinary != nullptr &&
  140. (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
  141. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  142. if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
  143. return true;
  144. return false;
  145. }
  146. void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
  147. TTypeList* newTypeList)
  148. {
  149. newTypeList = nullptr;
  150. correctUniform(memberType.getQualifier());
  151. if (memberType.isStruct()) {
  152. auto it = ioTypeMap.find(memberType.getStruct());
  153. if (it != ioTypeMap.end() && it->second.uniform)
  154. newTypeList = it->second.uniform;
  155. }
  156. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
  157. }
  158. //
  159. // Return a TLayoutFormat corresponding to the given texture type.
  160. //
  161. TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
  162. {
  163. if (txType.isStruct()) {
  164. // TODO: implement.
  165. error(loc, "unimplemented: structure type in image or buffer", "", "");
  166. return ElfNone;
  167. }
  168. const int components = txType.getVectorSize();
  169. const TBasicType txBasicType = txType.getBasicType();
  170. const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
  171. if (intermediate.getNoStorageFormat())
  172. return ElfNone;
  173. return components == 1 ? v1 :
  174. components == 2 ? v2 : v4;
  175. };
  176. switch (txBasicType) {
  177. case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
  178. case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
  179. case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
  180. default:
  181. error(loc, "unknown basic type in image format", "", "");
  182. return ElfNone;
  183. }
  184. }
  185. //
  186. // Both test and if necessary, spit out an error, to see if the node is really
  187. // an l-value that can be operated on this way.
  188. //
  189. // Returns true if there was an error.
  190. //
  191. bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  192. {
  193. if (shouldConvertLValue(node)) {
  194. // if we're writing to a texture, it must be an RW form.
  195. TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  196. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  197. if (!object->getType().getSampler().isImage()) {
  198. error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
  199. return true;
  200. }
  201. }
  202. // We tolerate samplers as l-values, even though they are nominally
  203. // illegal, because we expect a later optimization to eliminate them.
  204. if (node->getType().getBasicType() == EbtSampler) {
  205. intermediate.setNeedsLegalization();
  206. return false;
  207. }
  208. // Let the base class check errors
  209. return TParseContextBase::lValueErrorCheck(loc, op, node);
  210. }
  211. //
  212. // This function handles l-value conversions and verifications. It uses, but is not synonymous
  213. // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
  214. // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
  215. // series of other image operations.
  216. //
  217. // Most things are passed through unmodified, except for error checking.
  218. //
  219. TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
  220. {
  221. if (node == nullptr)
  222. return nullptr;
  223. TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
  224. TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
  225. TIntermAggregate* sequence = nullptr;
  226. TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
  227. nodeAsBinary ? nodeAsBinary->getLeft() :
  228. nullptr;
  229. // Early bail out if there is no conversion to apply
  230. if (!shouldConvertLValue(lhs)) {
  231. if (lhs != nullptr)
  232. if (lValueErrorCheck(loc, op, lhs))
  233. return nullptr;
  234. return node;
  235. }
  236. // *** If we get here, we're going to apply some conversion to an l-value.
  237. // Helper to create a load.
  238. const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
  239. TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
  240. loadOp->setLoc(loc);
  241. loadOp->getSequence().push_back(object);
  242. loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
  243. loadOp->setType(derefType);
  244. sequence = intermediate.growAggregate(sequence,
  245. intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
  246. loc);
  247. };
  248. // Helper to create a store.
  249. const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
  250. TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
  251. storeOp->getSequence().push_back(object);
  252. storeOp->getSequence().push_back(coord);
  253. storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
  254. storeOp->setLoc(loc);
  255. storeOp->setType(TType(EbtVoid));
  256. sequence = intermediate.growAggregate(sequence, storeOp);
  257. };
  258. // Helper to create an assign.
  259. const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
  260. sequence = intermediate.growAggregate(sequence,
  261. intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
  262. loc);
  263. };
  264. // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
  265. const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
  266. // Add a trailing use of the temp, so the sequence returns the proper value.
  267. sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
  268. sequence->setOperator(EOpSequence);
  269. sequence->setLoc(loc);
  270. sequence->setType(derefType);
  271. return sequence;
  272. };
  273. // Helper to add unary op
  274. const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
  275. sequence = intermediate.growAggregate(sequence,
  276. intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
  277. rhsTmp->getType()),
  278. loc);
  279. };
  280. // Return true if swizzle or index writes all components of the given variable.
  281. const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
  282. if (swizzle == nullptr) // not a swizzle or index
  283. return true;
  284. // Track which components are being set.
  285. std::array<bool, 4> compIsSet;
  286. compIsSet.fill(false);
  287. const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
  288. const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
  289. // This could be either a direct index, or a swizzle.
  290. if (asConst) {
  291. compIsSet[asConst->getConstArray()[0].getIConst()] = true;
  292. } else if (asAggregate) {
  293. const TIntermSequence& seq = asAggregate->getSequence();
  294. for (int comp=0; comp<int(seq.size()); ++comp)
  295. compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
  296. } else {
  297. assert(0);
  298. }
  299. // Return true if all components are being set by the index or swizzle
  300. return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
  301. [](bool isSet) { return isSet; } );
  302. };
  303. // Create swizzle matching input swizzle
  304. const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
  305. if (swizzle)
  306. return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
  307. else
  308. return var;
  309. };
  310. TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
  311. TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
  312. bool lhsIsSwizzle = false;
  313. // If it's a swizzled L-value, remember the swizzle, and use the LHS.
  314. if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
  315. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  316. lhsIsSwizzle = true;
  317. }
  318. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  319. TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
  320. const TSampler& texSampler = object->getType().getSampler();
  321. TType objDerefType;
  322. getTextureReturnType(texSampler, objDerefType);
  323. if (nodeAsBinary) {
  324. TIntermTyped* rhs = nodeAsBinary->getRight();
  325. const TOperator assignOp = nodeAsBinary->getOp();
  326. bool isModifyOp = false;
  327. switch (assignOp) {
  328. case EOpAddAssign:
  329. case EOpSubAssign:
  330. case EOpMulAssign:
  331. case EOpVectorTimesMatrixAssign:
  332. case EOpVectorTimesScalarAssign:
  333. case EOpMatrixTimesScalarAssign:
  334. case EOpMatrixTimesMatrixAssign:
  335. case EOpDivAssign:
  336. case EOpModAssign:
  337. case EOpAndAssign:
  338. case EOpInclusiveOrAssign:
  339. case EOpExclusiveOrAssign:
  340. case EOpLeftShiftAssign:
  341. case EOpRightShiftAssign:
  342. isModifyOp = true;
  343. // fall through...
  344. case EOpAssign:
  345. {
  346. // Since this is an lvalue, we'll convert an image load to a sequence like this
  347. // (to still provide the value):
  348. // OpSequence
  349. // OpImageStore(object, lhs, rhs)
  350. // rhs
  351. // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
  352. // so we'll convert instead to this:
  353. // OpSequence
  354. // rhsTmp = rhs
  355. // OpImageStore(object, coord, rhsTmp)
  356. // rhsTmp
  357. // If this is a read-modify-write op, like +=, we issue:
  358. // OpSequence
  359. // coordtmp = load's param1
  360. // rhsTmp = OpImageLoad(object, coordTmp)
  361. // rhsTmp op= rhs
  362. // OpImageStore(object, coordTmp, rhsTmp)
  363. // rhsTmp
  364. //
  365. // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
  366. // ...
  367. // rhsTmp.some_swizzle = ...
  368. // For partial writes, an error is generated.
  369. TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
  370. TIntermTyped* coordTmp = coord;
  371. if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
  372. rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  373. // Partial updates not yet supported
  374. if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
  375. error(loc, "unimplemented: partial image updates", "", "");
  376. }
  377. // Assign storeTemp = rhs
  378. if (isModifyOp) {
  379. // We have to make a temp var for the coordinate, to avoid evaluating it twice.
  380. coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  381. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  382. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  383. }
  384. // rhsTmp op= rhs.
  385. makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
  386. }
  387. makeStore(object, coordTmp, rhsTmp); // add a store
  388. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  389. }
  390. default:
  391. break;
  392. }
  393. }
  394. if (nodeAsUnary) {
  395. const TOperator assignOp = nodeAsUnary->getOp();
  396. switch (assignOp) {
  397. case EOpPreIncrement:
  398. case EOpPreDecrement:
  399. {
  400. // We turn this into:
  401. // OpSequence
  402. // coordtmp = load's param1
  403. // rhsTmp = OpImageLoad(object, coordTmp)
  404. // rhsTmp op
  405. // OpImageStore(object, coordTmp, rhsTmp)
  406. // rhsTmp
  407. TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  408. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  409. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  410. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  411. makeUnary(assignOp, rhsTmp); // op rhsTmp
  412. makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
  413. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  414. }
  415. case EOpPostIncrement:
  416. case EOpPostDecrement:
  417. {
  418. // We turn this into:
  419. // OpSequence
  420. // coordtmp = load's param1
  421. // rhsTmp1 = OpImageLoad(object, coordTmp)
  422. // rhsTmp2 = rhsTmp1
  423. // rhsTmp2 op
  424. // OpImageStore(object, coordTmp, rhsTmp2)
  425. // rhsTmp1 (pre-op value)
  426. TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
  427. TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
  428. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  429. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  430. makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
  431. makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
  432. makeUnary(assignOp, rhsTmp2); // rhsTmp op
  433. makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
  434. return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
  435. }
  436. default:
  437. break;
  438. }
  439. }
  440. if (lhs)
  441. if (lValueErrorCheck(loc, op, lhs))
  442. return nullptr;
  443. return node;
  444. }
  445. void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  446. {
  447. if (pragmaCallback)
  448. pragmaCallback(loc.line, tokens);
  449. if (tokens.size() == 0)
  450. return;
  451. // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
  452. TVector<TString> lowerTokens = tokens;
  453. for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
  454. std::transform(it->begin(), it->end(), it->begin(), ::tolower);
  455. // Handle pack_matrix
  456. if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
  457. // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
  458. // Row major becomes column major and vice versa.
  459. if (lowerTokens[2] == "row_major") {
  460. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  461. } else if (lowerTokens[2] == "column_major") {
  462. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  463. } else {
  464. // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
  465. warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
  466. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  467. }
  468. return;
  469. }
  470. // Handle once
  471. if (lowerTokens[0] == "once") {
  472. warn(loc, "not implemented", "#pragma once", "");
  473. return;
  474. }
  475. }
  476. //
  477. // Look at a '.' matrix selector string and change it into components
  478. // for a matrix. There are two types:
  479. //
  480. // _21 second row, first column (one based)
  481. // _m21 third row, second column (zero based)
  482. //
  483. // Returns true if there is no error.
  484. //
  485. bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
  486. TSwizzleSelectors<TMatrixSelector>& components)
  487. {
  488. int startPos[MaxSwizzleSelectors];
  489. int numComps = 0;
  490. TString compString = fields;
  491. // Find where each component starts,
  492. // recording the first character position after the '_'.
  493. for (size_t c = 0; c < compString.size(); ++c) {
  494. if (compString[c] == '_') {
  495. if (numComps >= MaxSwizzleSelectors) {
  496. error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
  497. return false;
  498. }
  499. if (c > compString.size() - 3 ||
  500. ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
  501. error(loc, "matrix component swizzle missing", compString.c_str(), "");
  502. return false;
  503. }
  504. startPos[numComps++] = (int)c + 1;
  505. }
  506. }
  507. // Process each component
  508. for (int i = 0; i < numComps; ++i) {
  509. int pos = startPos[i];
  510. int bias = -1;
  511. if (compString[pos] == 'm' || compString[pos] == 'M') {
  512. bias = 0;
  513. ++pos;
  514. }
  515. TMatrixSelector comp;
  516. comp.coord1 = compString[pos+0] - '0' + bias;
  517. comp.coord2 = compString[pos+1] - '0' + bias;
  518. if (comp.coord1 < 0 || comp.coord1 >= cols) {
  519. error(loc, "matrix row component out of range", compString.c_str(), "");
  520. return false;
  521. }
  522. if (comp.coord2 < 0 || comp.coord2 >= rows) {
  523. error(loc, "matrix column component out of range", compString.c_str(), "");
  524. return false;
  525. }
  526. components.push_back(comp);
  527. }
  528. return true;
  529. }
  530. // If the 'comps' express a column of a matrix,
  531. // return the column. Column means the first coords all match.
  532. //
  533. // Otherwise, return -1.
  534. //
  535. int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
  536. {
  537. int col = -1;
  538. // right number of comps?
  539. if (selector.size() != rows)
  540. return -1;
  541. // all comps in the same column?
  542. // rows in order?
  543. col = selector[0].coord1;
  544. for (int i = 0; i < rows; ++i) {
  545. if (col != selector[i].coord1)
  546. return -1;
  547. if (i != selector[i].coord2)
  548. return -1;
  549. }
  550. return col;
  551. }
  552. //
  553. // Handle seeing a variable identifier in the grammar.
  554. //
  555. TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
  556. {
  557. int thisDepth;
  558. TSymbol* symbol = symbolTable.find(*string, thisDepth);
  559. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  560. error(loc, "expected symbol, not user-defined type", string->c_str(), "");
  561. return nullptr;
  562. }
  563. const TVariable* variable = nullptr;
  564. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  565. TIntermTyped* node = nullptr;
  566. if (anon) {
  567. // It was a member of an anonymous container, which could be a 'this' structure.
  568. // Create a subtree for its dereference.
  569. if (thisDepth > 0) {
  570. variable = getImplicitThis(thisDepth);
  571. if (variable == nullptr)
  572. error(loc, "cannot access member variables (static member function?)", "this", "");
  573. }
  574. if (variable == nullptr)
  575. variable = anon->getAnonContainer().getAsVariable();
  576. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  577. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  578. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  579. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  580. if (node->getType().hiddenMember())
  581. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  582. } else {
  583. // Not a member of an anonymous container.
  584. // The symbol table search was done in the lexical phase.
  585. // See if it was a variable.
  586. variable = symbol ? symbol->getAsVariable() : nullptr;
  587. if (variable) {
  588. if ((variable->getType().getBasicType() == EbtBlock ||
  589. variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
  590. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  591. variable = nullptr;
  592. }
  593. } else {
  594. if (symbol)
  595. error(loc, "variable name expected", string->c_str(), "");
  596. }
  597. // Recovery, if it wasn't found or was not a variable.
  598. if (variable == nullptr) {
  599. error(loc, "unknown variable", string->c_str(), "");
  600. variable = new TVariable(string, TType(EbtVoid));
  601. }
  602. if (variable->getType().getQualifier().isFrontEndConstant())
  603. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  604. else
  605. node = intermediate.addSymbol(*variable, loc);
  606. }
  607. if (variable->getType().getQualifier().isIo())
  608. intermediate.addIoAccessed(*string);
  609. return node;
  610. }
  611. //
  612. // Handle operator[] on any objects it applies to. Currently:
  613. // Textures
  614. // Buffers
  615. //
  616. TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  617. {
  618. // handle r-value operator[] on textures and images. l-values will be processed later.
  619. if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
  620. const TSampler& sampler = base->getType().getSampler();
  621. if (sampler.isImage() || sampler.isTexture()) {
  622. if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
  623. // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
  624. mipsOperatorMipArg.back().mipLevel = index;
  625. return base; // next [] index is to the same base.
  626. } else {
  627. TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
  628. TType sampReturnType;
  629. getTextureReturnType(sampler, sampReturnType);
  630. load->setType(sampReturnType);
  631. load->setLoc(loc);
  632. load->getSequence().push_back(base);
  633. load->getSequence().push_back(index);
  634. // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
  635. if (sampler.isTexture()) {
  636. if (! mipsOperatorMipArg.empty()) {
  637. load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
  638. mipsOperatorMipArg.pop_back();
  639. } else {
  640. load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
  641. }
  642. }
  643. return load;
  644. }
  645. }
  646. }
  647. // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
  648. // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
  649. TIntermTyped* sbArray = indexStructBufferContent(loc, base);
  650. if (sbArray != nullptr) {
  651. if (sbArray == nullptr)
  652. return nullptr;
  653. // Now we'll apply the [] index to that array
  654. const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  655. TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
  656. const TType derefType(sbArray->getType(), 0);
  657. element->setType(derefType);
  658. return element;
  659. }
  660. return nullptr;
  661. }
  662. //
  663. // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
  664. TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
  665. {
  666. const TBasicType indexBasicType = index->getType().getBasicType();
  667. const int vecSize = index->getType().getVectorSize();
  668. // We can use int types directly as the index
  669. if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
  670. indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
  671. return index;
  672. // Cast index to unsigned integer if it isn't one.
  673. return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
  674. }
  675. //
  676. // Handle seeing a base[index] dereference in the grammar.
  677. //
  678. TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  679. {
  680. index = makeIntegerIndex(index);
  681. if (index == nullptr) {
  682. error(loc, " unknown index type ", "", "");
  683. return nullptr;
  684. }
  685. TIntermTyped* result = handleBracketOperator(loc, base, index);
  686. if (result != nullptr)
  687. return result; // it was handled as an operator[]
  688. bool flattened = false;
  689. int indexValue = 0;
  690. if (index->getQualifier().isFrontEndConstant())
  691. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  692. variableCheck(base);
  693. if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
  694. if (base->getAsSymbolNode())
  695. error(loc, " left of '[' is not of type array, matrix, or vector ",
  696. base->getAsSymbolNode()->getName().c_str(), "");
  697. else
  698. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  699. } else if (base->getType().getQualifier().isFrontEndConstant() &&
  700. index->getQualifier().isFrontEndConstant()) {
  701. // both base and index are front-end constants
  702. checkIndex(loc, base->getType(), indexValue);
  703. return intermediate.foldDereference(base, indexValue, loc);
  704. } else {
  705. // at least one of base and index is variable...
  706. if (index->getQualifier().isFrontEndConstant())
  707. checkIndex(loc, base->getType(), indexValue);
  708. if (base->getType().isScalarOrVec1())
  709. result = base;
  710. else if (base->getAsSymbolNode() && wasFlattened(base)) {
  711. if (index->getQualifier().storage != EvqConst)
  712. error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
  713. result = flattenAccess(base, indexValue);
  714. flattened = (result != base);
  715. } else {
  716. if (index->getQualifier().isFrontEndConstant()) {
  717. if (base->getType().isUnsizedArray())
  718. base->getWritableType().updateImplicitArraySize(indexValue + 1);
  719. else
  720. checkIndex(loc, base->getType(), indexValue);
  721. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  722. } else
  723. result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
  724. }
  725. }
  726. if (result == nullptr) {
  727. // Insert dummy error-recovery result
  728. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  729. } else {
  730. // If the array reference was flattened, it has the correct type. E.g, if it was
  731. // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
  732. // In that case, we preserve the qualifiers.
  733. if (!flattened) {
  734. // Insert valid dereferenced result
  735. TType newType(base->getType(), 0); // dereferenced type
  736. if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
  737. newType.getQualifier().storage = EvqConst;
  738. else
  739. newType.getQualifier().storage = EvqTemporary;
  740. result->setType(newType);
  741. }
  742. }
  743. return result;
  744. }
  745. // Handle seeing a binary node with a math operation.
  746. TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  747. TIntermTyped* left, TIntermTyped* right)
  748. {
  749. TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
  750. if (result == nullptr)
  751. binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
  752. return result;
  753. }
  754. // Handle seeing a unary node with a math operation.
  755. TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  756. TIntermTyped* childNode)
  757. {
  758. TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
  759. if (result)
  760. return result;
  761. else
  762. unaryOpError(loc, str, childNode->getCompleteString());
  763. return childNode;
  764. }
  765. //
  766. // Return true if the name is a struct buffer method
  767. //
  768. bool HlslParseContext::isStructBufferMethod(const TString& name) const
  769. {
  770. return
  771. name == "GetDimensions" ||
  772. name == "Load" ||
  773. name == "Load2" ||
  774. name == "Load3" ||
  775. name == "Load4" ||
  776. name == "Store" ||
  777. name == "Store2" ||
  778. name == "Store3" ||
  779. name == "Store4" ||
  780. name == "InterlockedAdd" ||
  781. name == "InterlockedAnd" ||
  782. name == "InterlockedCompareExchange" ||
  783. name == "InterlockedCompareStore" ||
  784. name == "InterlockedExchange" ||
  785. name == "InterlockedMax" ||
  786. name == "InterlockedMin" ||
  787. name == "InterlockedOr" ||
  788. name == "InterlockedXor" ||
  789. name == "IncrementCounter" ||
  790. name == "DecrementCounter" ||
  791. name == "Append" ||
  792. name == "Consume";
  793. }
  794. //
  795. // Handle seeing a base.field dereference in the grammar, where 'field' is a
  796. // swizzle or member variable.
  797. //
  798. TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  799. {
  800. variableCheck(base);
  801. if (base->isArray()) {
  802. error(loc, "cannot apply to an array:", ".", field.c_str());
  803. return base;
  804. }
  805. TIntermTyped* result = base;
  806. if (base->getType().getBasicType() == EbtSampler) {
  807. // Handle .mips[mipid][pos] operation on textures
  808. const TSampler& sampler = base->getType().getSampler();
  809. if (sampler.isTexture() && field == "mips") {
  810. // Push a null to signify that we expect a mip level under operator[] next.
  811. mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
  812. // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
  813. } else {
  814. if (field == "mips")
  815. error(loc, "unexpected texture type for .mips[][] operator:",
  816. base->getType().getCompleteString().c_str(), "");
  817. else
  818. error(loc, "unexpected operator on texture type:", field.c_str(),
  819. base->getType().getCompleteString().c_str());
  820. }
  821. } else if (base->isVector() || base->isScalar()) {
  822. TSwizzleSelectors<TVectorSelector> selectors;
  823. parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
  824. if (base->isScalar()) {
  825. if (selectors.size() == 1)
  826. return result;
  827. else {
  828. TType type(base->getBasicType(), EvqTemporary, selectors.size());
  829. return addConstructor(loc, base, type);
  830. }
  831. }
  832. if (base->getVectorSize() == 1) {
  833. TType scalarType(base->getBasicType(), EvqTemporary, 1);
  834. if (selectors.size() == 1)
  835. return addConstructor(loc, base, scalarType);
  836. else {
  837. TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
  838. return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
  839. }
  840. }
  841. if (base->getType().getQualifier().isFrontEndConstant())
  842. result = intermediate.foldSwizzle(base, selectors, loc);
  843. else {
  844. if (selectors.size() == 1) {
  845. TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
  846. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  847. result->setType(TType(base->getBasicType(), EvqTemporary));
  848. } else {
  849. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  850. result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
  851. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  852. selectors.size()));
  853. }
  854. }
  855. } else if (base->isMatrix()) {
  856. TSwizzleSelectors<TMatrixSelector> selectors;
  857. if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
  858. return result;
  859. if (selectors.size() == 1) {
  860. // Representable by m[c][r]
  861. if (base->getType().getQualifier().isFrontEndConstant()) {
  862. result = intermediate.foldDereference(base, selectors[0].coord1, loc);
  863. result = intermediate.foldDereference(result, selectors[0].coord2, loc);
  864. } else {
  865. result = intermediate.addIndex(EOpIndexDirect, base,
  866. intermediate.addConstantUnion(selectors[0].coord1, loc),
  867. loc);
  868. TType dereferencedCol(base->getType(), 0);
  869. result->setType(dereferencedCol);
  870. result = intermediate.addIndex(EOpIndexDirect, result,
  871. intermediate.addConstantUnion(selectors[0].coord2, loc),
  872. loc);
  873. TType dereferenced(dereferencedCol, 0);
  874. result->setType(dereferenced);
  875. }
  876. } else {
  877. int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
  878. if (column >= 0) {
  879. // Representable by m[c]
  880. if (base->getType().getQualifier().isFrontEndConstant())
  881. result = intermediate.foldDereference(base, column, loc);
  882. else {
  883. result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
  884. loc);
  885. TType dereferenced(base->getType(), 0);
  886. result->setType(dereferenced);
  887. }
  888. } else {
  889. // general case, not a column, not a single component
  890. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  891. result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
  892. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  893. selectors.size()));
  894. }
  895. }
  896. } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
  897. const TTypeList* fields = base->getType().getStruct();
  898. bool fieldFound = false;
  899. int member;
  900. for (member = 0; member < (int)fields->size(); ++member) {
  901. if ((*fields)[member].type->getFieldName() == field) {
  902. fieldFound = true;
  903. break;
  904. }
  905. }
  906. if (fieldFound) {
  907. if (base->getAsSymbolNode() && wasFlattened(base)) {
  908. result = flattenAccess(base, member);
  909. } else {
  910. if (base->getType().getQualifier().storage == EvqConst)
  911. result = intermediate.foldDereference(base, member, loc);
  912. else {
  913. TIntermTyped* index = intermediate.addConstantUnion(member, loc);
  914. result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
  915. result->setType(*(*fields)[member].type);
  916. }
  917. }
  918. } else
  919. error(loc, "no such field in structure", field.c_str(), "");
  920. } else
  921. error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
  922. return result;
  923. }
  924. //
  925. // Return true if the field should be treated as a built-in method.
  926. // Return false otherwise.
  927. //
  928. bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
  929. {
  930. if (base == nullptr)
  931. return false;
  932. variableCheck(base);
  933. if (base->getType().getBasicType() == EbtSampler) {
  934. return true;
  935. } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
  936. return true;
  937. } else if (field == "Append" ||
  938. field == "RestartStrip") {
  939. // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
  940. // the code is around in the shader source.
  941. return true;
  942. } else
  943. return false;
  944. }
  945. // Independently establish a built-in that is a member of a structure.
  946. // 'arraySizes' are what's desired for the independent built-in, whatever
  947. // the higher-level source/expression of them was.
  948. void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
  949. const TQualifier& outerQualifier)
  950. {
  951. // Because of arrays of structs, we might be asked more than once,
  952. // but the arraySizes passed in should have captured the whole thing
  953. // the first time.
  954. // However, clip/cull rely on multiple updates.
  955. if (!isClipOrCullDistance(memberType))
  956. if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
  957. splitBuiltIns.end())
  958. return;
  959. TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
  960. if (arraySizes != nullptr && !memberType.isArray())
  961. ioVar->getWritableType().copyArraySizes(*arraySizes);
  962. splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
  963. if (!isClipOrCullDistance(ioVar->getType()))
  964. trackLinkage(*ioVar);
  965. // Merge qualifier from the user structure
  966. mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
  967. // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
  968. // shader declared them). This is done after mergeQualifiers(), in case fixBuiltInIoType looks
  969. // at the qualifier to determine e.g, in or out qualifications.
  970. fixBuiltInIoType(ioVar->getWritableType());
  971. // But, not location, we're losing that
  972. ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  973. }
  974. // Split a type into
  975. // 1. a struct of non-I/O members
  976. // 2. a collection of independent I/O variables
  977. void HlslParseContext::split(const TVariable& variable)
  978. {
  979. // Create a new variable:
  980. const TType& clonedType = *variable.getType().clone();
  981. const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
  982. splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
  983. }
  984. // Recursive implementation of split().
  985. // Returns reference to the modified type.
  986. const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
  987. {
  988. if (type.isStruct()) {
  989. TTypeList* userStructure = type.getWritableStruct();
  990. for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
  991. if (ioType->type->isBuiltIn()) {
  992. // move out the built-in
  993. splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
  994. ioType = userStructure->erase(ioType);
  995. } else {
  996. split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
  997. ++ioType;
  998. }
  999. }
  1000. }
  1001. return type;
  1002. }
  1003. // Is this an aggregate that should be flattened?
  1004. // Can be applied to intermediate levels of type in a hierarchy.
  1005. // Some things like flattening uniform arrays are only about the top level
  1006. // of the aggregate, triggered on 'topLevel'.
  1007. bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
  1008. {
  1009. switch (qualifier) {
  1010. case EvqVaryingIn:
  1011. case EvqVaryingOut:
  1012. return type.isStruct() || type.isArray();
  1013. case EvqUniform:
  1014. return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
  1015. (type.isStruct() && type.containsOpaque());
  1016. default:
  1017. return false;
  1018. };
  1019. }
  1020. // Top level variable flattening: construct data
  1021. void HlslParseContext::flatten(const TVariable& variable, bool linkage)
  1022. {
  1023. const TType& type = variable.getType();
  1024. // If it's a standalone built-in, there is nothing to flatten
  1025. if (type.isBuiltIn() && !type.isStruct())
  1026. return;
  1027. auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
  1028. TFlattenData(type.getQualifier().layoutBinding,
  1029. type.getQualifier().layoutLocation)));
  1030. // the item is a map pair, so first->second is the TFlattenData itself.
  1031. flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
  1032. }
  1033. // Recursively flatten the given variable at the provided type, building the flattenData as we go.
  1034. //
  1035. // This is mutually recursive with flattenStruct and flattenArray.
  1036. // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
  1037. // members, and later on, we want to turn a path through the tree structure into a final
  1038. // location in this linear sequence.
  1039. //
  1040. // If the tree was N-ary, that can be directly calculated. However, we are dealing with
  1041. // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
  1042. // build a data structure to allow the sequence of bracket and dot operators on arrays and
  1043. // structs to arrive at the proper member.
  1044. //
  1045. // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
  1046. // The leaves are the indexes into the flattened member array.
  1047. // Each level will have the next location for the Nth item stored sequentially, so for instance:
  1048. //
  1049. // struct { float2 a[2]; int b; float4 c[3] };
  1050. //
  1051. // This will produce the following flattened tree:
  1052. // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  1053. // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
  1054. //
  1055. // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
  1056. // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
  1057. //
  1058. // so the 4th flattened member in traversal order is ours.
  1059. //
  1060. int HlslParseContext::flatten(const TVariable& variable, const TType& type,
  1061. TFlattenData& flattenData, TString name, bool linkage,
  1062. const TQualifier& outerQualifier,
  1063. const TArraySizes* builtInArraySizes)
  1064. {
  1065. // If something is an arrayed struct, the array flattener will recursively call flatten()
  1066. // to then flatten the struct, so this is an "if else": we don't do both.
  1067. if (type.isArray())
  1068. return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
  1069. else if (type.isStruct())
  1070. return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
  1071. else {
  1072. assert(0); // should never happen
  1073. return -1;
  1074. }
  1075. }
  1076. // Add a single flattened member to the flattened data being tracked for the composite
  1077. // Returns true for the final flattening level.
  1078. int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
  1079. const TString& memberName, bool linkage,
  1080. const TQualifier& outerQualifier,
  1081. const TArraySizes* builtInArraySizes)
  1082. {
  1083. if (!shouldFlatten(type, outerQualifier.storage, false)) {
  1084. // This is as far as we flatten. Insert the variable.
  1085. TVariable* memberVariable = makeInternalVariable(memberName, type);
  1086. mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
  1087. if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
  1088. memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
  1089. if (memberVariable->getType().isBuiltIn()) {
  1090. // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
  1091. memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  1092. } else {
  1093. // inherited locations must be auto bumped, not replicated
  1094. if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
  1095. memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
  1096. flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
  1097. nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
  1098. }
  1099. }
  1100. flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
  1101. flattenData.members.push_back(memberVariable);
  1102. if (linkage)
  1103. trackLinkage(*memberVariable);
  1104. return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
  1105. } else {
  1106. // Further recursion required
  1107. return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
  1108. }
  1109. }
  1110. // Figure out the mapping between an aggregate's top members and an
  1111. // equivalent set of individual variables.
  1112. //
  1113. // Assumes shouldFlatten() or equivalent was called first.
  1114. int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
  1115. TFlattenData& flattenData, TString name, bool linkage,
  1116. const TQualifier& outerQualifier,
  1117. const TArraySizes* builtInArraySizes)
  1118. {
  1119. assert(type.isStruct());
  1120. auto members = *type.getStruct();
  1121. // Reserve space for this tree level.
  1122. int start = static_cast<int>(flattenData.offsets.size());
  1123. int pos = start;
  1124. flattenData.offsets.resize(int(pos + members.size()), -1);
  1125. for (int member = 0; member < (int)members.size(); ++member) {
  1126. TType& dereferencedType = *members[member].type;
  1127. if (dereferencedType.isBuiltIn())
  1128. splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
  1129. else {
  1130. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1131. name + "." + dereferencedType.getFieldName(),
  1132. linkage, outerQualifier,
  1133. builtInArraySizes == nullptr && dereferencedType.isArray()
  1134. ? dereferencedType.getArraySizes()
  1135. : builtInArraySizes);
  1136. flattenData.offsets[pos++] = mpos;
  1137. }
  1138. }
  1139. return start;
  1140. }
  1141. // Figure out mapping between an array's members and an
  1142. // equivalent set of individual variables.
  1143. //
  1144. // Assumes shouldFlatten() or equivalent was called first.
  1145. int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
  1146. TFlattenData& flattenData, TString name, bool linkage,
  1147. const TQualifier& outerQualifier)
  1148. {
  1149. assert(type.isSizedArray());
  1150. const int size = type.getOuterArraySize();
  1151. const TType dereferencedType(type, 0);
  1152. if (name.empty())
  1153. name = variable.getName();
  1154. // Reserve space for this tree level.
  1155. int start = static_cast<int>(flattenData.offsets.size());
  1156. int pos = start;
  1157. flattenData.offsets.resize(int(pos + size), -1);
  1158. for (int element=0; element < size; ++element) {
  1159. char elementNumBuf[20]; // sufficient for MAXINT
  1160. snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
  1161. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1162. name + elementNumBuf, linkage, outerQualifier,
  1163. type.getArraySizes());
  1164. flattenData.offsets[pos++] = mpos;
  1165. }
  1166. return start;
  1167. }
  1168. // Return true if we have flattened this node.
  1169. bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
  1170. {
  1171. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1172. wasFlattened(node->getAsSymbolNode()->getId());
  1173. }
  1174. // Return true if we have split this structure
  1175. bool HlslParseContext::wasSplit(const TIntermTyped* node) const
  1176. {
  1177. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1178. wasSplit(node->getAsSymbolNode()->getId());
  1179. }
  1180. // Turn an access into an aggregate that was flattened to instead be
  1181. // an access to the individual variable the member was flattened to.
  1182. // Assumes wasFlattened() or equivalent was called first.
  1183. TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
  1184. {
  1185. const TType dereferencedType(base->getType(), member); // dereferenced type
  1186. const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
  1187. TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
  1188. dereferencedType, symbolNode.getFlattenSubset());
  1189. return flattened ? flattened : base;
  1190. }
  1191. TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
  1192. const TType& dereferencedType, int subset)
  1193. {
  1194. const auto flattenData = flattenMap.find(uniqueId);
  1195. if (flattenData == flattenMap.end())
  1196. return nullptr;
  1197. // Calculate new cumulative offset from the packed tree
  1198. int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
  1199. TIntermSymbol* subsetSymbol;
  1200. if (!shouldFlatten(dereferencedType, outerStorage, false)) {
  1201. // Finished flattening: create symbol for variable
  1202. member = flattenData->second.offsets[newSubset];
  1203. const TVariable* memberVariable = flattenData->second.members[member];
  1204. subsetSymbol = intermediate.addSymbol(*memberVariable);
  1205. subsetSymbol->setFlattenSubset(-1);
  1206. } else {
  1207. // If this is not the final flattening, accumulate the position and return
  1208. // an object of the partially dereferenced type.
  1209. subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
  1210. subsetSymbol->setFlattenSubset(newSubset);
  1211. }
  1212. return subsetSymbol;
  1213. }
  1214. // For finding where the first leaf is in a subtree of a multi-level aggregate
  1215. // that is just getting a subset assigned. Follows the same logic as flattenAccess,
  1216. // but logically going down the "left-most" tree branch each step of the way.
  1217. //
  1218. // Returns the offset into the first leaf of the subset.
  1219. int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
  1220. {
  1221. const TIntermSymbol* sym = node.getAsSymbolNode();
  1222. if (sym == nullptr)
  1223. return 0;
  1224. if (!sym->isArray() && !sym->isStruct())
  1225. return 0;
  1226. int subset = sym->getFlattenSubset();
  1227. if (subset == -1)
  1228. return 0;
  1229. // Getting this far means a partial aggregate is identified by the flatten subset.
  1230. // Find the first leaf of the subset.
  1231. const auto flattenData = flattenMap.find(sym->getId());
  1232. if (flattenData == flattenMap.end())
  1233. return 0;
  1234. return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
  1235. do {
  1236. subset = flattenData->second.offsets[subset];
  1237. } while (true);
  1238. }
  1239. // Recursively do the desent
  1240. int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
  1241. {
  1242. if (!type.isArray() && !type.isStruct())
  1243. return offsets[subset];
  1244. TType derefType(type, 0);
  1245. return findSubtreeOffset(derefType, offsets[subset], offsets);
  1246. };
  1247. // Find and return the split IO TVariable for id, or nullptr if none.
  1248. TVariable* HlslParseContext::getSplitNonIoVar(int id) const
  1249. {
  1250. const auto splitNonIoVar = splitNonIoVars.find(id);
  1251. if (splitNonIoVar == splitNonIoVars.end())
  1252. return nullptr;
  1253. return splitNonIoVar->second;
  1254. }
  1255. // Pass through to base class after remembering built-in mappings.
  1256. void HlslParseContext::trackLinkage(TSymbol& symbol)
  1257. {
  1258. TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
  1259. if (biType != EbvNone)
  1260. builtInTessLinkageSymbols[biType] = symbol.clone();
  1261. TParseContextBase::trackLinkage(symbol);
  1262. }
  1263. // Returns true if the built-in is a clip or cull distance variable.
  1264. bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
  1265. {
  1266. return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
  1267. }
  1268. // Some types require fixed array sizes in SPIR-V, but can be scalars or
  1269. // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
  1270. // This creates the right size. A conversion is performed when the internal
  1271. // type is copied to or from the external type. This corrects the externally
  1272. // facing input or output type to abide downstream semantics.
  1273. void HlslParseContext::fixBuiltInIoType(TType& type)
  1274. {
  1275. int requiredArraySize = 0;
  1276. int requiredVectorSize = 0;
  1277. switch (type.getQualifier().builtIn) {
  1278. case EbvTessLevelOuter: requiredArraySize = 4; break;
  1279. case EbvTessLevelInner: requiredArraySize = 2; break;
  1280. case EbvSampleMask:
  1281. {
  1282. // Promote scalar to array of size 1. Leave existing arrays alone.
  1283. if (!type.isArray())
  1284. requiredArraySize = 1;
  1285. break;
  1286. }
  1287. case EbvWorkGroupId: requiredVectorSize = 3; break;
  1288. case EbvGlobalInvocationId: requiredVectorSize = 3; break;
  1289. case EbvLocalInvocationId: requiredVectorSize = 3; break;
  1290. case EbvTessCoord: requiredVectorSize = 3; break;
  1291. default:
  1292. if (isClipOrCullDistance(type)) {
  1293. const int loc = type.getQualifier().layoutLocation;
  1294. if (type.getQualifier().builtIn == EbvClipDistance) {
  1295. if (type.getQualifier().storage == EvqVaryingIn)
  1296. clipSemanticNSizeIn[loc] = type.getVectorSize();
  1297. else
  1298. clipSemanticNSizeOut[loc] = type.getVectorSize();
  1299. } else {
  1300. if (type.getQualifier().storage == EvqVaryingIn)
  1301. cullSemanticNSizeIn[loc] = type.getVectorSize();
  1302. else
  1303. cullSemanticNSizeOut[loc] = type.getVectorSize();
  1304. }
  1305. }
  1306. return;
  1307. }
  1308. // Alter or set vector size as needed.
  1309. if (requiredVectorSize > 0) {
  1310. TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
  1311. newType.getQualifier() = type.getQualifier();
  1312. type.shallowCopy(newType);
  1313. }
  1314. // Alter or set array size as needed.
  1315. if (requiredArraySize > 0) {
  1316. if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
  1317. TArraySizes* arraySizes = new TArraySizes;
  1318. arraySizes->addInnerSize(requiredArraySize);
  1319. type.transferArraySizes(arraySizes);
  1320. }
  1321. }
  1322. }
  1323. // Variables that correspond to the user-interface in and out of a stage
  1324. // (not the built-in interface) are
  1325. // - assigned locations
  1326. // - registered as a linkage node (part of the stage's external interface).
  1327. // Assumes it is called in the order in which locations should be assigned.
  1328. void HlslParseContext::assignToInterface(TVariable& variable)
  1329. {
  1330. const auto assignLocation = [&](TVariable& variable) {
  1331. TType& type = variable.getWritableType();
  1332. if (!type.isStruct() || type.getStruct()->size() > 0) {
  1333. TQualifier& qualifier = type.getQualifier();
  1334. if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
  1335. if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
  1336. // Strip off the outer array dimension for those having an extra one.
  1337. int size;
  1338. if (type.isArray() && qualifier.isArrayedIo(language)) {
  1339. TType elementType(type, 0);
  1340. size = intermediate.computeTypeLocationSize(elementType, language);
  1341. } else
  1342. size = intermediate.computeTypeLocationSize(type, language);
  1343. if (qualifier.storage == EvqVaryingIn) {
  1344. variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
  1345. nextInLocation += size;
  1346. } else {
  1347. variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
  1348. nextOutLocation += size;
  1349. }
  1350. }
  1351. trackLinkage(variable);
  1352. }
  1353. }
  1354. };
  1355. if (wasFlattened(variable.getUniqueId())) {
  1356. auto& memberList = flattenMap[variable.getUniqueId()].members;
  1357. for (auto member = memberList.begin(); member != memberList.end(); ++member)
  1358. assignLocation(**member);
  1359. } else if (wasSplit(variable.getUniqueId())) {
  1360. TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
  1361. assignLocation(*splitIoVar);
  1362. } else {
  1363. assignLocation(variable);
  1364. }
  1365. }
  1366. //
  1367. // Handle seeing a function declarator in the grammar. This is the precursor
  1368. // to recognizing a function prototype or function definition.
  1369. //
  1370. void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  1371. {
  1372. //
  1373. // Multiple declarations of the same function name are allowed.
  1374. //
  1375. // If this is a definition, the definition production code will check for redefinitions
  1376. // (we don't know at this point if it's a definition or not).
  1377. //
  1378. bool builtIn;
  1379. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1380. const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
  1381. if (prototype) {
  1382. // All built-in functions are defined, even though they don't have a body.
  1383. // Count their prototype as a definition instead.
  1384. if (symbolTable.atBuiltInLevel())
  1385. function.setDefined();
  1386. else {
  1387. if (prevDec && ! builtIn)
  1388. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1389. function.setPrototyped();
  1390. }
  1391. }
  1392. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1393. // other forms of name collisions.
  1394. if (! symbolTable.insert(function))
  1395. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1396. }
  1397. // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
  1398. // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
  1399. // Otherwise, it's a no-op
  1400. void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
  1401. TIntermAggregate*& paramNodes)
  1402. {
  1403. if (! hasStructBuffCounter(*param.type))
  1404. return;
  1405. const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
  1406. TType counterType;
  1407. counterBufferType(loc, counterType);
  1408. TVariable *variable = makeInternalVariable(counterBlockName, counterType);
  1409. if (! symbolTable.insert(*variable))
  1410. error(loc, "redefinition", variable->getName().c_str(), "");
  1411. paramNodes = intermediate.growAggregate(paramNodes,
  1412. intermediate.addSymbol(*variable, loc),
  1413. loc);
  1414. }
  1415. //
  1416. // Handle seeing the function prototype in front of a function definition in the grammar.
  1417. // The body is handled after this function returns.
  1418. //
  1419. // Returns an aggregate of parameter-symbol nodes.
  1420. //
  1421. TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
  1422. const TAttributes& attributes,
  1423. TIntermNode*& entryPointTree)
  1424. {
  1425. currentCaller = function.getMangledName();
  1426. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1427. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1428. if (prevDec == nullptr)
  1429. error(loc, "can't find function", function.getName().c_str(), "");
  1430. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1431. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1432. // an earlier occurrence.
  1433. if (prevDec && prevDec->isDefined()) {
  1434. // Then this function already has a body.
  1435. error(loc, "function already has a body", function.getName().c_str(), "");
  1436. }
  1437. if (prevDec && ! prevDec->isDefined()) {
  1438. prevDec->setDefined();
  1439. // Remember the return type for later checking for RETURN statements.
  1440. currentFunctionType = &(prevDec->getType());
  1441. } else
  1442. currentFunctionType = new TType(EbtVoid);
  1443. functionReturnsValue = false;
  1444. // Entry points need different I/O and other handling, transform it so the
  1445. // rest of this function doesn't care.
  1446. entryPointTree = transformEntryPoint(loc, function, attributes);
  1447. //
  1448. // New symbol table scope for body of function plus its arguments
  1449. //
  1450. pushScope();
  1451. //
  1452. // Insert parameters into the symbol table.
  1453. // If the parameter has no name, it's not an error, just don't insert it
  1454. // (could be used for unused args).
  1455. //
  1456. // Also, accumulate the list of parameters into the AST, so lower level code
  1457. // knows where to find parameters.
  1458. //
  1459. TIntermAggregate* paramNodes = new TIntermAggregate;
  1460. for (int i = 0; i < function.getParamCount(); i++) {
  1461. TParameter& param = function[i];
  1462. if (param.name != nullptr) {
  1463. TVariable *variable = new TVariable(param.name, *param.type);
  1464. if (i == 0 && function.hasImplicitThis()) {
  1465. // Anonymous 'this' members are already in a symbol-table level,
  1466. // and we need to know what function parameter to map them to.
  1467. symbolTable.makeInternalVariable(*variable);
  1468. pushImplicitThis(variable);
  1469. }
  1470. // Insert the parameters with name in the symbol table.
  1471. if (! symbolTable.insert(*variable))
  1472. error(loc, "redefinition", variable->getName().c_str(), "");
  1473. // Add parameters to the AST list.
  1474. if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
  1475. // Expand the AST parameter nodes (but not the name mangling or symbol table view)
  1476. // for structures that need to be flattened.
  1477. flatten(*variable, false);
  1478. const TTypeList* structure = variable->getType().getStruct();
  1479. for (int mem = 0; mem < (int)structure->size(); ++mem) {
  1480. paramNodes = intermediate.growAggregate(paramNodes,
  1481. flattenAccess(variable->getUniqueId(), mem,
  1482. variable->getType().getQualifier().storage,
  1483. *(*structure)[mem].type),
  1484. loc);
  1485. }
  1486. } else {
  1487. // Add the parameter to the AST
  1488. paramNodes = intermediate.growAggregate(paramNodes,
  1489. intermediate.addSymbol(*variable, loc),
  1490. loc);
  1491. }
  1492. // Add hidden AST parameter for struct buffer counters, if needed.
  1493. addStructBufferHiddenCounterParam(loc, param, paramNodes);
  1494. } else
  1495. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1496. }
  1497. if (function.hasIllegalImplicitThis())
  1498. pushImplicitThis(nullptr);
  1499. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1500. loopNestingLevel = 0;
  1501. controlFlowNestingLevel = 0;
  1502. postEntryPointReturn = false;
  1503. return paramNodes;
  1504. }
  1505. // Handle all [attrib] attribute for the shader entry point
  1506. void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
  1507. {
  1508. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1509. switch (it->name) {
  1510. case EatNumThreads:
  1511. {
  1512. const TIntermSequence& sequence = it->args->getSequence();
  1513. for (int lid = 0; lid < int(sequence.size()); ++lid)
  1514. intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
  1515. break;
  1516. }
  1517. case EatMaxVertexCount:
  1518. {
  1519. int maxVertexCount;
  1520. if (! it->getInt(maxVertexCount)) {
  1521. error(loc, "invalid maxvertexcount", "", "");
  1522. } else {
  1523. if (! intermediate.setVertices(maxVertexCount))
  1524. error(loc, "cannot change previously set maxvertexcount attribute", "", "");
  1525. }
  1526. break;
  1527. }
  1528. case EatPatchConstantFunc:
  1529. {
  1530. TString pcfName;
  1531. if (! it->getString(pcfName, 0, false)) {
  1532. error(loc, "invalid patch constant function", "", "");
  1533. } else {
  1534. patchConstantFunctionName = pcfName;
  1535. }
  1536. break;
  1537. }
  1538. case EatDomain:
  1539. {
  1540. // Handle [domain("...")]
  1541. TString domainStr;
  1542. if (! it->getString(domainStr)) {
  1543. error(loc, "invalid domain", "", "");
  1544. } else {
  1545. TLayoutGeometry domain = ElgNone;
  1546. if (domainStr == "tri") {
  1547. domain = ElgTriangles;
  1548. } else if (domainStr == "quad") {
  1549. domain = ElgQuads;
  1550. } else if (domainStr == "isoline") {
  1551. domain = ElgIsolines;
  1552. } else {
  1553. error(loc, "unsupported domain type", domainStr.c_str(), "");
  1554. }
  1555. if (language == EShLangTessEvaluation) {
  1556. if (! intermediate.setInputPrimitive(domain))
  1557. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1558. } else {
  1559. if (! intermediate.setOutputPrimitive(domain))
  1560. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1561. }
  1562. }
  1563. break;
  1564. }
  1565. case EatOutputTopology:
  1566. {
  1567. // Handle [outputtopology("...")]
  1568. TString topologyStr;
  1569. if (! it->getString(topologyStr)) {
  1570. error(loc, "invalid outputtopology", "", "");
  1571. } else {
  1572. TVertexOrder vertexOrder = EvoNone;
  1573. TLayoutGeometry primitive = ElgNone;
  1574. if (topologyStr == "point") {
  1575. intermediate.setPointMode();
  1576. } else if (topologyStr == "line") {
  1577. primitive = ElgIsolines;
  1578. } else if (topologyStr == "triangle_cw") {
  1579. vertexOrder = EvoCw;
  1580. primitive = ElgTriangles;
  1581. } else if (topologyStr == "triangle_ccw") {
  1582. vertexOrder = EvoCcw;
  1583. primitive = ElgTriangles;
  1584. } else {
  1585. error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
  1586. }
  1587. if (vertexOrder != EvoNone) {
  1588. if (! intermediate.setVertexOrder(vertexOrder)) {
  1589. error(loc, "cannot change previously set outputtopology",
  1590. TQualifier::getVertexOrderString(vertexOrder), "");
  1591. }
  1592. }
  1593. if (primitive != ElgNone)
  1594. intermediate.setOutputPrimitive(primitive);
  1595. }
  1596. break;
  1597. }
  1598. case EatPartitioning:
  1599. {
  1600. // Handle [partitioning("...")]
  1601. TString partitionStr;
  1602. if (! it->getString(partitionStr)) {
  1603. error(loc, "invalid partitioning", "", "");
  1604. } else {
  1605. TVertexSpacing partitioning = EvsNone;
  1606. if (partitionStr == "integer") {
  1607. partitioning = EvsEqual;
  1608. } else if (partitionStr == "fractional_even") {
  1609. partitioning = EvsFractionalEven;
  1610. } else if (partitionStr == "fractional_odd") {
  1611. partitioning = EvsFractionalOdd;
  1612. //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
  1613. } else {
  1614. error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
  1615. }
  1616. if (! intermediate.setVertexSpacing(partitioning))
  1617. error(loc, "cannot change previously set partitioning",
  1618. TQualifier::getVertexSpacingString(partitioning), "");
  1619. }
  1620. break;
  1621. }
  1622. case EatOutputControlPoints:
  1623. {
  1624. // Handle [outputcontrolpoints("...")]
  1625. int ctrlPoints;
  1626. if (! it->getInt(ctrlPoints)) {
  1627. error(loc, "invalid outputcontrolpoints", "", "");
  1628. } else {
  1629. if (! intermediate.setVertices(ctrlPoints)) {
  1630. error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
  1631. }
  1632. }
  1633. break;
  1634. }
  1635. case EatEarlyDepthStencil:
  1636. intermediate.setEarlyFragmentTests();
  1637. break;
  1638. case EatBuiltIn:
  1639. case EatLocation:
  1640. // tolerate these because of dual use of entrypoint and type attributes
  1641. break;
  1642. default:
  1643. warn(loc, "attribute does not apply to entry point", "", "");
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. // Update the given type with any type-like attribute information in the
  1649. // attributes.
  1650. void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
  1651. bool allowEntry)
  1652. {
  1653. if (attributes.size() == 0)
  1654. return;
  1655. int value;
  1656. TString builtInString;
  1657. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1658. switch (it->name) {
  1659. case EatLocation:
  1660. // location
  1661. if (it->getInt(value))
  1662. type.getQualifier().layoutLocation = value;
  1663. else
  1664. error(loc, "needs a literal integer", "location", "");
  1665. break;
  1666. case EatBinding:
  1667. // binding
  1668. if (it->getInt(value)) {
  1669. type.getQualifier().layoutBinding = value;
  1670. type.getQualifier().layoutSet = 0;
  1671. } else
  1672. error(loc, "needs a literal integer", "binding", "");
  1673. // set
  1674. if (it->getInt(value, 1))
  1675. type.getQualifier().layoutSet = value;
  1676. break;
  1677. case EatGlobalBinding:
  1678. // global cbuffer binding
  1679. if (it->getInt(value))
  1680. globalUniformBinding = value;
  1681. else
  1682. error(loc, "needs a literal integer", "global binding", "");
  1683. // global cbuffer set
  1684. if (it->getInt(value, 1))
  1685. globalUniformSet = value;
  1686. break;
  1687. case EatInputAttachment:
  1688. // input attachment
  1689. if (it->getInt(value))
  1690. type.getQualifier().layoutAttachment = value;
  1691. else
  1692. error(loc, "needs a literal integer", "input attachment", "");
  1693. break;
  1694. case EatBuiltIn:
  1695. // PointSize built-in
  1696. if (it->getString(builtInString, 0, false)) {
  1697. if (builtInString == "PointSize")
  1698. type.getQualifier().builtIn = EbvPointSize;
  1699. }
  1700. break;
  1701. case EatPushConstant:
  1702. // push_constant
  1703. type.getQualifier().layoutPushConstant = true;
  1704. break;
  1705. case EatConstantId:
  1706. // specialization constant
  1707. if (it->getInt(value)) {
  1708. TSourceLoc loc;
  1709. loc.init();
  1710. setSpecConstantId(loc, type.getQualifier(), value);
  1711. }
  1712. break;
  1713. default:
  1714. if (! allowEntry)
  1715. warn(loc, "attribute does not apply to a type", "", "");
  1716. break;
  1717. }
  1718. }
  1719. }
  1720. //
  1721. // Do all special handling for the entry point, including wrapping
  1722. // the shader's entry point with the official entry point that will call it.
  1723. //
  1724. // The following:
  1725. //
  1726. // retType shaderEntryPoint(args...) // shader declared entry point
  1727. // { body }
  1728. //
  1729. // Becomes
  1730. //
  1731. // out retType ret;
  1732. // in iargs<that are input>...;
  1733. // out oargs<that are output> ...;
  1734. //
  1735. // void shaderEntryPoint() // synthesized, but official, entry point
  1736. // {
  1737. // args<that are input> = iargs...;
  1738. // ret = @shaderEntryPoint(args...);
  1739. // oargs = args<that are output>...;
  1740. // }
  1741. // retType @shaderEntryPoint(args...)
  1742. // { body }
  1743. //
  1744. // The symbol table will still map the original entry point name to the
  1745. // the modified function and its new name:
  1746. //
  1747. // symbol table: shaderEntryPoint -> @shaderEntryPoint
  1748. //
  1749. // Returns nullptr if no entry-point tree was built, otherwise, returns
  1750. // a subtree that creates the entry point.
  1751. //
  1752. TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
  1753. const TAttributes& attributes)
  1754. {
  1755. // Return true if this is a tessellation patch constant function input to a domain shader.
  1756. const auto isDsPcfInput = [this](const TType& type) {
  1757. return language == EShLangTessEvaluation &&
  1758. type.contains([](const TType* t) {
  1759. return t->getQualifier().builtIn == EbvTessLevelOuter ||
  1760. t->getQualifier().builtIn == EbvTessLevelInner;
  1761. });
  1762. };
  1763. // if we aren't in the entry point, fix the IO as such and exit
  1764. if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
  1765. remapNonEntryPointIO(userFunction);
  1766. return nullptr;
  1767. }
  1768. entryPointFunction = &userFunction; // needed in finish()
  1769. // Handle entry point attributes
  1770. handleEntryPointAttributes(loc, attributes);
  1771. // entry point logic...
  1772. // Move parameters and return value to shader in/out
  1773. TVariable* entryPointOutput; // gets created in remapEntryPointIO
  1774. TVector<TVariable*> inputs;
  1775. TVector<TVariable*> outputs;
  1776. remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
  1777. // Further this return/in/out transform by flattening, splitting, and assigning locations
  1778. const auto makeVariableInOut = [&](TVariable& variable) {
  1779. if (variable.getType().isStruct()) {
  1780. if (variable.getType().getQualifier().isArrayedIo(language)) {
  1781. if (variable.getType().containsBuiltIn())
  1782. split(variable);
  1783. } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
  1784. flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
  1785. }
  1786. // TODO: flatten arrays too
  1787. // TODO: flatten everything in I/O
  1788. // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
  1789. // For clip and cull distance, multiple output variables potentially get merged
  1790. // into one in assignClipCullDistance. That code in assignClipCullDistance
  1791. // handles the interface logic, so we avoid it here in that case.
  1792. if (!isClipOrCullDistance(variable.getType()))
  1793. assignToInterface(variable);
  1794. };
  1795. if (entryPointOutput != nullptr)
  1796. makeVariableInOut(*entryPointOutput);
  1797. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1798. if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
  1799. makeVariableInOut(*(*it));
  1800. for (auto it = outputs.begin(); it != outputs.end(); ++it)
  1801. makeVariableInOut(*(*it));
  1802. // In the domain shader, PCF input must be at the end of the linkage. That's because in the
  1803. // hull shader there is no ordering: the output comes from the separate PCF, which does not
  1804. // participate in the argument list. That is always put at the end of the HS linkage, so the
  1805. // input side of the DS must match. The argument may be in any position in the DS argument list
  1806. // however, so this ensures the linkage is built in the correct order regardless of argument order.
  1807. if (language == EShLangTessEvaluation) {
  1808. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1809. if (isDsPcfInput((*it)->getType()))
  1810. makeVariableInOut(*(*it));
  1811. }
  1812. // Synthesize the call
  1813. pushScope(); // matches the one in handleFunctionBody()
  1814. // new signature
  1815. TType voidType(EbtVoid);
  1816. TFunction synthEntryPoint(&userFunction.getName(), voidType);
  1817. TIntermAggregate* synthParams = new TIntermAggregate();
  1818. intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
  1819. intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
  1820. intermediate.incrementEntryPointCount();
  1821. TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
  1822. // change original name
  1823. userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
  1824. // Copy inputs (shader-in -> calling arg), while building up the call node
  1825. TVector<TVariable*> argVars;
  1826. TIntermAggregate* synthBody = new TIntermAggregate();
  1827. auto inputIt = inputs.begin();
  1828. TIntermTyped* callingArgs = nullptr;
  1829. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1830. TParameter& param = userFunction[i];
  1831. argVars.push_back(makeInternalVariable(*param.name, *param.type));
  1832. argVars.back()->getWritableType().getQualifier().makeTemporary();
  1833. // Track the input patch, which is the only non-builtin supported by hull shader PCF.
  1834. if (param.getDeclaredBuiltIn() == EbvInputPatch)
  1835. inputPatch = argVars.back();
  1836. TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
  1837. handleFunctionArgument(&callee, callingArgs, arg);
  1838. if (param.type->getQualifier().isParamInput()) {
  1839. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1840. intermediate.addSymbol(**inputIt)));
  1841. inputIt++;
  1842. }
  1843. }
  1844. // Call
  1845. currentCaller = synthEntryPoint.getMangledName();
  1846. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  1847. currentCaller = userFunction.getMangledName();
  1848. // Return value
  1849. if (entryPointOutput) {
  1850. TIntermTyped* returnAssign;
  1851. // For hull shaders, the wrapped entry point return value is written to
  1852. // an array element as indexed by invocation ID, which we might have to make up.
  1853. // This is required to match SPIR-V semantics.
  1854. if (language == EShLangTessControl) {
  1855. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  1856. // If there is no user declared invocation ID, we must make one.
  1857. if (invocationIdSym == nullptr) {
  1858. TType invocationIdType(EbtUint, EvqIn, 1);
  1859. TString* invocationIdName = NewPoolTString("InvocationId");
  1860. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  1861. TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
  1862. globalQualifierFix(loc, variable->getWritableType().getQualifier());
  1863. trackLinkage(*variable);
  1864. invocationIdSym = intermediate.addSymbol(*variable);
  1865. }
  1866. TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
  1867. invocationIdSym, loc);
  1868. // Set the type of the array element being dereferenced
  1869. const TType derefElementType(entryPointOutput->getType(), 0);
  1870. element->setType(derefElementType);
  1871. returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
  1872. } else {
  1873. returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
  1874. }
  1875. intermediate.growAggregate(synthBody, returnAssign);
  1876. } else
  1877. intermediate.growAggregate(synthBody, callReturn);
  1878. // Output copies
  1879. auto outputIt = outputs.begin();
  1880. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1881. TParameter& param = userFunction[i];
  1882. // GS outputs are via emit, so we do not copy them here.
  1883. if (param.type->getQualifier().isParamOutput()) {
  1884. if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
  1885. // GS output stream does not assign outputs here: it's the Append() method
  1886. // which writes to the output, probably multiple times separated by Emit.
  1887. // We merely remember the output to use, here.
  1888. gsStreamOutput = *outputIt;
  1889. } else {
  1890. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
  1891. intermediate.addSymbol(**outputIt),
  1892. intermediate.addSymbol(*argVars[i])));
  1893. }
  1894. outputIt++;
  1895. }
  1896. }
  1897. // Put the pieces together to form a full function subtree
  1898. // for the synthesized entry point.
  1899. synthBody->setOperator(EOpSequence);
  1900. TIntermNode* synthFunctionDef = synthParams;
  1901. handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
  1902. entryPointFunctionBody = synthBody;
  1903. return synthFunctionDef;
  1904. }
  1905. void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
  1906. TIntermNode*& node)
  1907. {
  1908. node = intermediate.growAggregate(node, functionBody);
  1909. intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
  1910. node->getAsAggregate()->setName(function.getMangledName().c_str());
  1911. popScope();
  1912. if (function.hasImplicitThis())
  1913. popImplicitThis();
  1914. if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
  1915. error(loc, "function does not return a value:", "", function.getName().c_str());
  1916. }
  1917. // AST I/O is done through shader globals declared in the 'in' or 'out'
  1918. // storage class. An HLSL entry point has a return value, input parameters
  1919. // and output parameters. These need to get remapped to the AST I/O.
  1920. void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
  1921. TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
  1922. {
  1923. // We might have in input structure type with no decorations that caused it
  1924. // to look like an input type, yet it has (e.g.) interpolation types that
  1925. // must be modified that turn it into an input type.
  1926. // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
  1927. const auto synthesizeEditedInput = [this](TType& type) {
  1928. // True if a type needs to be 'flat'
  1929. const auto needsFlat = [](const TType& type) {
  1930. return type.containsBasicType(EbtInt) ||
  1931. type.containsBasicType(EbtUint) ||
  1932. type.containsBasicType(EbtInt64) ||
  1933. type.containsBasicType(EbtUint64) ||
  1934. type.containsBasicType(EbtBool) ||
  1935. type.containsBasicType(EbtDouble);
  1936. };
  1937. if (language == EShLangFragment && needsFlat(type)) {
  1938. if (type.isStruct()) {
  1939. TTypeList* finalList = nullptr;
  1940. auto it = ioTypeMap.find(type.getStruct());
  1941. if (it == ioTypeMap.end() || it->second.input == nullptr) {
  1942. // Getting here means we have no input struct, but we need one.
  1943. auto list = new TTypeList;
  1944. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  1945. TType* newType = new TType;
  1946. newType->shallowCopy(*member->type);
  1947. TTypeLoc typeLoc = { newType, member->loc };
  1948. list->push_back(typeLoc);
  1949. }
  1950. // install the new input type
  1951. if (it == ioTypeMap.end()) {
  1952. tIoKinds newLists = { list, nullptr, nullptr };
  1953. ioTypeMap[type.getStruct()] = newLists;
  1954. } else
  1955. it->second.input = list;
  1956. finalList = list;
  1957. } else
  1958. finalList = it->second.input;
  1959. // edit for 'flat'
  1960. for (auto member = finalList->begin(); member != finalList->end(); ++member) {
  1961. if (needsFlat(*member->type)) {
  1962. member->type->getQualifier().clearInterpolation();
  1963. member->type->getQualifier().flat = true;
  1964. }
  1965. }
  1966. } else {
  1967. type.getQualifier().clearInterpolation();
  1968. type.getQualifier().flat = true;
  1969. }
  1970. }
  1971. };
  1972. // Do the actual work to make a type be a shader input or output variable,
  1973. // and clear the original to be non-IO (for use as a normal function parameter/return).
  1974. const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
  1975. TVariable* ioVariable = makeInternalVariable(name, type);
  1976. clearUniformInputOutput(type.getQualifier());
  1977. if (type.isStruct()) {
  1978. auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
  1979. if (newLists != ioTypeMap.end()) {
  1980. if (storage == EvqVaryingIn && newLists->second.input)
  1981. ioVariable->getWritableType().setStruct(newLists->second.input);
  1982. else if (storage == EvqVaryingOut && newLists->second.output)
  1983. ioVariable->getWritableType().setStruct(newLists->second.output);
  1984. }
  1985. }
  1986. if (storage == EvqVaryingIn) {
  1987. correctInput(ioVariable->getWritableType().getQualifier());
  1988. if (language == EShLangTessEvaluation)
  1989. if (!ioVariable->getType().isArray())
  1990. ioVariable->getWritableType().getQualifier().patch = true;
  1991. } else {
  1992. correctOutput(ioVariable->getWritableType().getQualifier());
  1993. }
  1994. ioVariable->getWritableType().getQualifier().storage = storage;
  1995. fixBuiltInIoType(ioVariable->getWritableType());
  1996. return ioVariable;
  1997. };
  1998. // return value is actually a shader-scoped output (out)
  1999. if (function.getType().getBasicType() == EbtVoid) {
  2000. returnValue = nullptr;
  2001. } else {
  2002. if (language == EShLangTessControl) {
  2003. // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
  2004. // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
  2005. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2006. TType outputType;
  2007. outputType.shallowCopy(function.getType());
  2008. // vertices has necessarily already been set when handling entry point attributes.
  2009. TArraySizes* arraySizes = new TArraySizes;
  2010. arraySizes->addInnerSize(intermediate.getVertices());
  2011. outputType.transferArraySizes(arraySizes);
  2012. clearUniformInputOutput(function.getWritableType().getQualifier());
  2013. returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
  2014. } else {
  2015. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2016. }
  2017. }
  2018. // parameters are actually shader-scoped inputs and outputs (in or out)
  2019. for (int i = 0; i < function.getParamCount(); i++) {
  2020. TType& paramType = *function[i].type;
  2021. if (paramType.getQualifier().isParamInput()) {
  2022. synthesizeEditedInput(paramType);
  2023. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
  2024. inputs.push_back(argAsGlobal);
  2025. }
  2026. if (paramType.getQualifier().isParamOutput()) {
  2027. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
  2028. outputs.push_back(argAsGlobal);
  2029. }
  2030. }
  2031. }
  2032. // An HLSL function that looks like an entry point, but is not,
  2033. // declares entry point IO built-ins, but these have to be undone.
  2034. void HlslParseContext::remapNonEntryPointIO(TFunction& function)
  2035. {
  2036. // return value
  2037. if (function.getType().getBasicType() != EbtVoid)
  2038. clearUniformInputOutput(function.getWritableType().getQualifier());
  2039. // parameters.
  2040. // References to structuredbuffer types are left unmodified
  2041. for (int i = 0; i < function.getParamCount(); i++)
  2042. if (!isReference(*function[i].type))
  2043. clearUniformInputOutput(function[i].type->getQualifier());
  2044. }
  2045. // Handle function returns, including type conversions to the function return type
  2046. // if necessary.
  2047. TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  2048. {
  2049. functionReturnsValue = true;
  2050. if (currentFunctionType->getBasicType() == EbtVoid) {
  2051. error(loc, "void function cannot return a value", "return", "");
  2052. return intermediate.addBranch(EOpReturn, loc);
  2053. } else if (*currentFunctionType != value->getType()) {
  2054. value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  2055. if (value && *currentFunctionType != value->getType())
  2056. value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
  2057. if (value == nullptr || *currentFunctionType != value->getType()) {
  2058. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  2059. return value;
  2060. }
  2061. }
  2062. return intermediate.addBranch(EOpReturn, value, loc);
  2063. }
  2064. void HlslParseContext::handleFunctionArgument(TFunction* function,
  2065. TIntermTyped*& arguments, TIntermTyped* newArg)
  2066. {
  2067. TParameter param = { 0, new TType, nullptr };
  2068. param.type->shallowCopy(newArg->getType());
  2069. function->addParameter(param);
  2070. if (arguments)
  2071. arguments = intermediate.growAggregate(arguments, newArg);
  2072. else
  2073. arguments = newArg;
  2074. }
  2075. // Position may require special handling: we can optionally invert Y.
  2076. // See: https://github.com/KhronosGroup/glslang/issues/1173
  2077. // https://github.com/KhronosGroup/glslang/issues/494
  2078. TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
  2079. TIntermTyped* left, TIntermTyped* right)
  2080. {
  2081. // If we are not asked for Y inversion, use a plain old assign.
  2082. if (!intermediate.getInvertY())
  2083. return intermediate.addAssign(op, left, right, loc);
  2084. // If we get here, we should invert Y.
  2085. TIntermAggregate* assignList = nullptr;
  2086. // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
  2087. TVariable* rhsTempVar = nullptr;
  2088. rhsTempVar = makeInternalVariable("@position", right->getType());
  2089. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2090. {
  2091. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2092. assignList = intermediate.growAggregate(assignList,
  2093. intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
  2094. }
  2095. // pos.y = -pos.y
  2096. {
  2097. const int Y = 1;
  2098. TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
  2099. TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
  2100. TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
  2101. TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
  2102. TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
  2103. const TType derefType(right->getType(), 0);
  2104. lhsElement->setType(derefType);
  2105. rhsElement->setType(derefType);
  2106. TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
  2107. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
  2108. }
  2109. // Assign the rhs temp (now with Y inversion) to the final output
  2110. {
  2111. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2112. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
  2113. }
  2114. assert(assignList != nullptr);
  2115. assignList->setOperator(EOpSequence);
  2116. return assignList;
  2117. }
  2118. // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
  2119. // these can be float scalar, float vector, or arrays of float scalar or float vector.
  2120. // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
  2121. // (e.g, both x and y components of a float2) out into the destination float array.
  2122. //
  2123. // The values are assigned to sequential members of the output array. The inner dimension
  2124. // is vector components. The outer dimension is array elements.
  2125. TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
  2126. TIntermTyped* left, TIntermTyped* right)
  2127. {
  2128. switch (language) {
  2129. case EShLangFragment:
  2130. case EShLangVertex:
  2131. case EShLangGeometry:
  2132. break;
  2133. default:
  2134. error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
  2135. return nullptr;
  2136. }
  2137. TVariable** clipCullVar = nullptr;
  2138. // Figure out if we are assigning to, or from, clip or cull distance.
  2139. const bool isOutput = isClipOrCullDistance(left->getType());
  2140. // This is the rvalue or lvalue holding the clip or cull distance.
  2141. TIntermTyped* clipCullNode = isOutput ? left : right;
  2142. // This is the value going into or out of the clip or cull distance.
  2143. TIntermTyped* internalNode = isOutput ? right : left;
  2144. const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
  2145. decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
  2146. // Refer to either the clip or the cull distance, depending on semantic.
  2147. switch (builtInType) {
  2148. case EbvClipDistance:
  2149. clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
  2150. semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
  2151. break;
  2152. case EbvCullDistance:
  2153. clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
  2154. semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
  2155. break;
  2156. // called invalidly: we expected a clip or a cull distance.
  2157. // static compile time problem: should not happen.
  2158. default: assert(0); return nullptr;
  2159. }
  2160. // This is the offset in the destination array of a given semantic's data
  2161. std::array<int, maxClipCullRegs> semanticOffset;
  2162. // Calculate offset of variable of semantic N in destination array
  2163. int arrayLoc = 0;
  2164. int vecItems = 0;
  2165. for (int x = 0; x < maxClipCullRegs; ++x) {
  2166. // See if we overflowed the vec4 packing
  2167. if ((vecItems + (*semanticNSize)[x]) > 4) {
  2168. arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
  2169. vecItems = 0;
  2170. }
  2171. semanticOffset[x] = arrayLoc;
  2172. vecItems += (*semanticNSize)[x];
  2173. arrayLoc += (*semanticNSize)[x];
  2174. }
  2175. // It can have up to 2 array dimensions (in the case of geometry shader inputs)
  2176. const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
  2177. const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
  2178. // vector sizes:
  2179. const int internalVectorSize = internalNode->getType().getVectorSize();
  2180. // array sizes, or 1 if it's not an array:
  2181. const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
  2182. const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
  2183. // The created type may be an array of arrays, e.g, for geometry shader inputs.
  2184. const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
  2185. // If we haven't created the output already, create it now.
  2186. if (*clipCullVar == nullptr) {
  2187. // ClipDistance and CullDistance are handled specially in the entry point input/output copy
  2188. // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
  2189. // into a float array, or vice versa. Here, we make the array the right size and type,
  2190. // which depends on the incoming data, which has several potential dimensions:
  2191. // * Semantic ID
  2192. // * vector size
  2193. // * array size
  2194. // Of those, semantic ID and array size cannot appear simultaneously.
  2195. //
  2196. // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
  2197. // array dimensions. The shader's declaration may have one or two array dimensions. One is always
  2198. // the geometry's dimension.
  2199. const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
  2200. const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
  2201. const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
  2202. TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
  2203. clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
  2204. // Create required array dimension
  2205. TArraySizes* arraySizes = new TArraySizes;
  2206. if (isImplicitlyArrayed)
  2207. arraySizes->addInnerSize(requiredOuterArraySize);
  2208. arraySizes->addInnerSize(requiredInnerArraySize);
  2209. clipCullType.transferArraySizes(arraySizes);
  2210. // Obtain symbol name: we'll use that for the symbol we introduce.
  2211. TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
  2212. assert(sym != nullptr);
  2213. // We are moving the semantic ID from the layout location, so it is no longer needed or
  2214. // desired there.
  2215. clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  2216. // Create variable and track its linkage
  2217. *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
  2218. trackLinkage(**clipCullVar);
  2219. }
  2220. // Create symbol for the clip or cull variable.
  2221. TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
  2222. // vector sizes:
  2223. const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
  2224. // array sizes, or 1 if it's not an array:
  2225. const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
  2226. const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
  2227. const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
  2228. // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
  2229. // fixBuiltInIoType() should have handled that upstream.
  2230. assert(clipCullSym->getType().isArray());
  2231. assert(clipCullSym->getType().getVectorSize() == 1);
  2232. assert(clipCullSym->getType().getBasicType() == EbtFloat);
  2233. // We may be creating multiple sub-assignments. This is an aggregate to hold them.
  2234. // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
  2235. TIntermAggregate* assignList = nullptr;
  2236. // Holds individual component assignments as we make them.
  2237. TIntermTyped* clipCullAssign = nullptr;
  2238. // If the types are homomorphic, use a simple assign. No need to mess about with
  2239. // individual components.
  2240. if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
  2241. clipCullInnerArraySize == internalInnerArraySize &&
  2242. clipCullOuterArraySize == internalOuterArraySize &&
  2243. clipCullVectorSize == internalVectorSize) {
  2244. if (isOutput)
  2245. clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
  2246. else
  2247. clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
  2248. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2249. assignList->setOperator(EOpSequence);
  2250. return assignList;
  2251. }
  2252. // We are going to copy each component of the internal (per array element if indicated) to sequential
  2253. // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
  2254. // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
  2255. int clipCullInnerArrayPos = semanticOffset[semanticId];
  2256. int clipCullOuterArrayPos = 0;
  2257. // Lambda to add an index to a node, set the type of the result, and return the new node.
  2258. const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
  2259. const TType derefType(node->getType(), 0);
  2260. node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
  2261. node->setType(derefType);
  2262. return node;
  2263. };
  2264. // Loop through every component of every element of the internal, and copy to or from the matching external.
  2265. for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
  2266. for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
  2267. for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
  2268. // clip/cull array member to read from / write to:
  2269. TIntermTyped* clipCullMember = clipCullSym;
  2270. // If implicitly arrayed, there is an outer array dimension involved
  2271. if (isImplicitlyArrayed)
  2272. clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
  2273. // Index into proper array position for clip cull member
  2274. clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
  2275. // if needed, start over with next outer array slice.
  2276. if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
  2277. clipCullInnerArrayPos = semanticOffset[semanticId];
  2278. ++clipCullOuterArrayPos;
  2279. }
  2280. // internal member to read from / write to:
  2281. TIntermTyped* internalMember = internalNode;
  2282. // If internal node has outer array dimension, index appropriately.
  2283. if (internalArrayDims > 1)
  2284. internalMember = addIndex(internalMember, internalOuterArrayPos);
  2285. // If internal node has inner array dimension, index appropriately.
  2286. if (internalArrayDims > 0)
  2287. internalMember = addIndex(internalMember, internalInnerArrayPos);
  2288. // If internal node is a vector, extract the component of interest.
  2289. if (internalNode->getType().isVector())
  2290. internalMember = addIndex(internalMember, internalComponent);
  2291. // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
  2292. if (isOutput)
  2293. clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
  2294. else
  2295. clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
  2296. // Track assignment in the sequence.
  2297. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2298. }
  2299. }
  2300. }
  2301. assert(assignList != nullptr);
  2302. assignList->setOperator(EOpSequence);
  2303. return assignList;
  2304. }
  2305. // Some simple source assignments need to be flattened to a sequence
  2306. // of AST assignments. Catch these and flatten, otherwise, pass through
  2307. // to intermediate.addAssign().
  2308. //
  2309. // Also, assignment to matrix swizzles requires multiple component assignments,
  2310. // intercept those as well.
  2311. TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2312. TIntermTyped* right)
  2313. {
  2314. if (left == nullptr || right == nullptr)
  2315. return nullptr;
  2316. // writing to opaques will require fixing transforms
  2317. if (left->getType().containsOpaque())
  2318. intermediate.setNeedsLegalization();
  2319. if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
  2320. return handleAssignToMatrixSwizzle(loc, op, left, right);
  2321. // Return true if the given node is an index operation into a split variable.
  2322. const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
  2323. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2324. if (binaryNode == nullptr)
  2325. return false;
  2326. return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
  2327. wasSplit(binaryNode->getLeft());
  2328. };
  2329. // Return true if this stage assigns clip position with potentially inverted Y
  2330. const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
  2331. return node->getType().getQualifier().builtIn == EbvPosition &&
  2332. (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
  2333. };
  2334. const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
  2335. const bool isSplitRight = wasSplit(right) || indexesSplit(right);
  2336. const bool isFlattenLeft = wasFlattened(left);
  2337. const bool isFlattenRight = wasFlattened(right);
  2338. // OK to do a single assign if neither side is split or flattened. Otherwise,
  2339. // fall through to a member-wise copy.
  2340. if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
  2341. // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
  2342. if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
  2343. const bool isOutput = isClipOrCullDistance(left->getType());
  2344. const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
  2345. return assignClipCullDistance(loc, op, semanticId, left, right);
  2346. } else if (assignsClipPos(left)) {
  2347. // Position can require special handling: see comment above assignPosition
  2348. return assignPosition(loc, op, left, right);
  2349. } else if (left->getQualifier().builtIn == EbvSampleMask) {
  2350. // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
  2351. // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
  2352. if (left->isArray() && !right->isArray()) {
  2353. const TType derefType(left->getType(), 0);
  2354. left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
  2355. left->setType(derefType);
  2356. // Fall through to add assign.
  2357. }
  2358. }
  2359. return intermediate.addAssign(op, left, right, loc);
  2360. }
  2361. TIntermAggregate* assignList = nullptr;
  2362. const TVector<TVariable*>* leftVariables = nullptr;
  2363. const TVector<TVariable*>* rightVariables = nullptr;
  2364. // A temporary to store the right node's value, so we don't keep indirecting into it
  2365. // if it's not a simple symbol.
  2366. TVariable* rhsTempVar = nullptr;
  2367. // If the RHS is a simple symbol node, we'll copy it for each member.
  2368. TIntermSymbol* cloneSymNode = nullptr;
  2369. int memberCount = 0;
  2370. // Track how many items there are to copy.
  2371. if (left->getType().isStruct())
  2372. memberCount = (int)left->getType().getStruct()->size();
  2373. if (left->getType().isArray())
  2374. memberCount = left->getType().getCumulativeArraySize();
  2375. if (isFlattenLeft)
  2376. leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
  2377. if (isFlattenRight) {
  2378. rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
  2379. } else {
  2380. // The RHS is not flattened. There are several cases:
  2381. // 1. 1 item to copy: Use the RHS directly.
  2382. // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
  2383. // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
  2384. if (memberCount <= 1) {
  2385. // case 1: we'll use the symbol directly below. Nothing to do.
  2386. } else {
  2387. if (right->getAsSymbolNode() != nullptr) {
  2388. // case 2: we'll copy the symbol per iteration below.
  2389. cloneSymNode = right->getAsSymbolNode();
  2390. } else {
  2391. // case 3: assign to a temp, and indirect into that.
  2392. rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
  2393. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2394. TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
  2395. // Add this to the aggregate being built.
  2396. assignList = intermediate.growAggregate(assignList,
  2397. intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
  2398. }
  2399. }
  2400. }
  2401. // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
  2402. // variables, which is awkward when copying between split and unsplit structures. This variable tracks
  2403. // array indirections so they can be percolated from outer structs to inner variables.
  2404. std::vector <int> arrayElement;
  2405. TStorageQualifier leftStorage = left->getType().getQualifier().storage;
  2406. TStorageQualifier rightStorage = right->getType().getQualifier().storage;
  2407. int leftOffset = findSubtreeOffset(*left);
  2408. int rightOffset = findSubtreeOffset(*right);
  2409. const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
  2410. bool flattened)
  2411. -> TIntermTyped * {
  2412. const bool split = isLeft ? isSplitLeft : isSplitRight;
  2413. TIntermTyped* subTree;
  2414. const TType derefType(type, member);
  2415. const TVariable* builtInVar = nullptr;
  2416. if ((flattened || split) && derefType.isBuiltIn()) {
  2417. auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
  2418. derefType.getQualifier().builtIn,
  2419. isLeft ? leftStorage : rightStorage));
  2420. if (splitPair != splitBuiltIns.end())
  2421. builtInVar = splitPair->second;
  2422. }
  2423. if (builtInVar != nullptr) {
  2424. // copy from interstage IO built-in if needed
  2425. subTree = intermediate.addSymbol(*builtInVar);
  2426. if (subTree->getType().isArray()) {
  2427. // Arrayness of builtIn symbols isn't handled by the normal recursion:
  2428. // it's been extracted and moved to the built-in.
  2429. if (!arrayElement.empty()) {
  2430. const TType splitDerefType(subTree->getType(), arrayElement.back());
  2431. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2432. intermediate.addConstantUnion(arrayElement.back(), loc), loc);
  2433. subTree->setType(splitDerefType);
  2434. } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
  2435. // This might also be a stage with arrayed outputs, in which case there's an index
  2436. // operation we should transfer to the output builtin.
  2437. const TType splitDerefType(subTree->getType(), 0);
  2438. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2439. splitNode->getAsBinaryNode()->getRight(), loc);
  2440. subTree->setType(splitDerefType);
  2441. }
  2442. }
  2443. } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
  2444. if (isLeft)
  2445. subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
  2446. else
  2447. subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
  2448. } else {
  2449. // Index operator if it's an aggregate, else EOpNull
  2450. const TOperator accessOp = type.isArray() ? EOpIndexDirect
  2451. : type.isStruct() ? EOpIndexDirectStruct
  2452. : EOpNull;
  2453. if (accessOp == EOpNull) {
  2454. subTree = splitNode;
  2455. } else {
  2456. subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
  2457. loc);
  2458. const TType splitDerefType(splitNode->getType(), splitMember);
  2459. subTree->setType(splitDerefType);
  2460. }
  2461. }
  2462. return subTree;
  2463. };
  2464. // Use the proper RHS node: a new symbol from a TVariable, copy
  2465. // of an TIntermSymbol node, or sometimes the right node directly.
  2466. right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
  2467. cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
  2468. right;
  2469. // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
  2470. // whole thing. So, we'll resort to an explicit type via std::function.
  2471. const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2472. bool topLevel)>
  2473. traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2474. bool topLevel) -> void {
  2475. // If we get here, we are assigning to or from a whole array or struct that must be
  2476. // flattened, so have to do member-by-member assignment:
  2477. bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
  2478. bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
  2479. if ((left->getType().isArray() || right->getType().isArray()) &&
  2480. (shouldFlattenSubsetLeft || isSplitLeft ||
  2481. shouldFlattenSubsetRight || isSplitRight)) {
  2482. const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
  2483. const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
  2484. // The arrays might not be the same size,
  2485. // e.g., if the size has been forced for EbvTessLevelInner/Outer.
  2486. const int elementsToCopy = std::min(elementsL, elementsR);
  2487. // array case
  2488. for (int element = 0; element < elementsToCopy; ++element) {
  2489. arrayElement.push_back(element);
  2490. // Add a new AST symbol node if we have a temp variable holding a complex RHS.
  2491. TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
  2492. shouldFlattenSubsetLeft);
  2493. TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
  2494. shouldFlattenSubsetRight);
  2495. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
  2496. element, shouldFlattenSubsetLeft)
  2497. : subLeft;
  2498. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
  2499. element, shouldFlattenSubsetRight)
  2500. : subRight;
  2501. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2502. arrayElement.pop_back();
  2503. }
  2504. } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
  2505. shouldFlattenSubsetRight || isSplitRight)) {
  2506. // struct case
  2507. const auto& membersL = *left->getType().getStruct();
  2508. const auto& membersR = *right->getType().getStruct();
  2509. // These track the members in the split structures corresponding to the same in the unsplit structures,
  2510. // which we traverse in parallel.
  2511. int memberL = 0;
  2512. int memberR = 0;
  2513. // Handle empty structure assignment
  2514. if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
  2515. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2516. for (int member = 0; member < int(membersL.size()); ++member) {
  2517. const TType& typeL = *membersL[member].type;
  2518. const TType& typeR = *membersR[member].type;
  2519. TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
  2520. shouldFlattenSubsetLeft);
  2521. TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
  2522. shouldFlattenSubsetRight);
  2523. // If there is no splitting, use the same values to avoid inefficiency.
  2524. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
  2525. memberL, shouldFlattenSubsetLeft)
  2526. : subLeft;
  2527. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
  2528. memberR, shouldFlattenSubsetRight)
  2529. : subRight;
  2530. if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
  2531. // Clip and cull distance built-in assignment is complex in its own right, and is handled in
  2532. // a separate function dedicated to that task. See comment above assignClipCullDistance;
  2533. const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
  2534. // Since all clip/cull semantics boil down to the same built-in type, we need to get the
  2535. // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
  2536. const TType derefType((isOutput ? left : right)->getType(), member);
  2537. const int semanticId = derefType.getQualifier().layoutLocation;
  2538. TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
  2539. subSplitLeft, subSplitRight);
  2540. assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
  2541. } else if (assignsClipPos(subSplitLeft)) {
  2542. // Position can require special handling: see comment above assignPosition
  2543. TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
  2544. assignList = intermediate.growAggregate(assignList, positionAssign, loc);
  2545. } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
  2546. !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
  2547. // If this is the final flattening (no nested types below to flatten)
  2548. // we'll copy the member, else recurse into the type hierarchy.
  2549. // However, if splitting the struct, that means we can copy a whole
  2550. // subtree here IFF it does not itself contain any interstage built-in
  2551. // IO variables, so we only have to recurse into it if there's something
  2552. // for splitting to do. That can save a lot of AST verbosity for
  2553. // a bunch of memberwise copies.
  2554. assignList = intermediate.growAggregate(assignList,
  2555. intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
  2556. loc);
  2557. } else {
  2558. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2559. }
  2560. memberL += (typeL.isBuiltIn() ? 0 : 1);
  2561. memberR += (typeR.isBuiltIn() ? 0 : 1);
  2562. }
  2563. } else {
  2564. // Member copy
  2565. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2566. }
  2567. };
  2568. TIntermTyped* splitLeft = left;
  2569. TIntermTyped* splitRight = right;
  2570. // If either left or right was a split structure, we must read or write it, but still have to
  2571. // parallel-recurse through the unsplit structure to identify the built-in IO vars.
  2572. // The left can be either a symbol, or an index into a symbol (e.g, array reference)
  2573. if (isSplitLeft) {
  2574. if (indexesSplit(left)) {
  2575. // Index case: Refer to the indexed symbol, if the left is an index operator.
  2576. const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2577. TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2578. splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
  2579. left->getAsBinaryNode()->getRight(), loc);
  2580. const TType derefType(splitLeftNonIo->getType(), 0);
  2581. splitLeft->setType(derefType);
  2582. } else {
  2583. // Symbol case: otherwise, if not indexed, we have the symbol directly.
  2584. const TIntermSymbol* symNode = left->getAsSymbolNode();
  2585. splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2586. }
  2587. }
  2588. if (isSplitRight)
  2589. splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
  2590. // This makes the whole assignment, recursing through subtypes as needed.
  2591. traverse(left, right, splitLeft, splitRight, true);
  2592. assert(assignList != nullptr);
  2593. assignList->setOperator(EOpSequence);
  2594. return assignList;
  2595. }
  2596. // An assignment to matrix swizzle must be decomposed into individual assignments.
  2597. // These must be selected component-wise from the RHS and stored component-wise
  2598. // into the LHS.
  2599. TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2600. TIntermTyped* right)
  2601. {
  2602. assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
  2603. if (op != EOpAssign)
  2604. error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
  2605. // isolate the matrix and swizzle nodes
  2606. TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
  2607. const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
  2608. // if the RHS isn't already a simple vector, let's store into one
  2609. TIntermSymbol* vector = right->getAsSymbolNode();
  2610. TIntermTyped* vectorAssign = nullptr;
  2611. if (vector == nullptr) {
  2612. // create a new intermediate vector variable to assign to
  2613. TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
  2614. vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
  2615. // assign the right to the new vector
  2616. vectorAssign = handleAssign(loc, op, vector, right);
  2617. }
  2618. // Assign the vector components to the matrix components.
  2619. // Store this as a sequence, so a single aggregate node represents this
  2620. // entire operation.
  2621. TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
  2622. TType columnType(matrix->getType(), 0);
  2623. TType componentType(columnType, 0);
  2624. TType indexType(EbtInt);
  2625. for (int i = 0; i < (int)swizzle.size(); i += 2) {
  2626. // the right component, single index into the RHS vector
  2627. TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
  2628. intermediate.addConstantUnion(i/2, loc), loc);
  2629. // the left component, double index into the LHS matrix
  2630. TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
  2631. intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
  2632. indexType, loc),
  2633. loc);
  2634. leftComp->setType(columnType);
  2635. leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
  2636. intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
  2637. indexType, loc),
  2638. loc);
  2639. leftComp->setType(componentType);
  2640. // Add the assignment to the aggregate
  2641. result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
  2642. }
  2643. result->setOp(EOpSequence);
  2644. return result;
  2645. }
  2646. //
  2647. // HLSL atomic operations have slightly different arguments than
  2648. // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
  2649. // This provides the post-decomposition equivalent opcode.
  2650. //
  2651. TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
  2652. {
  2653. switch (op) {
  2654. case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
  2655. case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
  2656. case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
  2657. case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
  2658. case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
  2659. case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
  2660. case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
  2661. case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
  2662. case EOpInterlockedCompareStore: // TODO: ...
  2663. default:
  2664. error(loc, "unknown atomic operation", "unknown op", "");
  2665. return EOpNull;
  2666. }
  2667. }
  2668. //
  2669. // Create a combined sampler/texture from separate sampler and texture.
  2670. //
  2671. TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
  2672. TIntermTyped* argSampler)
  2673. {
  2674. TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
  2675. txcombine->getSequence().push_back(argTex);
  2676. txcombine->getSequence().push_back(argSampler);
  2677. TSampler samplerType = argTex->getType().getSampler();
  2678. samplerType.combined = true;
  2679. // TODO:
  2680. // This block exists until the spec no longer requires shadow modes on texture objects.
  2681. // It can be deleted after that, along with the shadowTextureVariant member.
  2682. {
  2683. const bool shadowMode = argSampler->getType().getSampler().shadow;
  2684. TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
  2685. if (texSymbol == nullptr)
  2686. texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2687. if (texSymbol == nullptr) {
  2688. error(loc, "unable to find texture symbol", "", "");
  2689. return nullptr;
  2690. }
  2691. // This forces the texture's shadow state to be the sampler's
  2692. // shadow state. This depends on downstream optimization to
  2693. // DCE one variant in [shadow, nonshadow] if both are present,
  2694. // or the SPIR-V module would be invalid.
  2695. int newId = texSymbol->getId();
  2696. // Check to see if this texture has been given a shadow mode already.
  2697. // If so, look up the one we already have.
  2698. const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
  2699. if (textureShadowEntry != textureShadowVariant.end())
  2700. newId = textureShadowEntry->second->get(shadowMode);
  2701. else
  2702. textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
  2703. // Sometimes we have to create another symbol (if this texture has been seen before,
  2704. // and we haven't created the form for this shadow mode).
  2705. if (newId == -1) {
  2706. TType texType;
  2707. texType.shallowCopy(argTex->getType());
  2708. texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
  2709. globalQualifierFix(loc, texType.getQualifier());
  2710. TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
  2711. trackLinkage(*newTexture);
  2712. newId = newTexture->getUniqueId();
  2713. }
  2714. assert(newId != -1);
  2715. if (textureShadowVariant.find(newId) == textureShadowVariant.end())
  2716. textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
  2717. textureShadowVariant[newId]->set(shadowMode, newId);
  2718. // Remember this shadow mode in the texture and the merged type.
  2719. argTex->getWritableType().getSampler().shadow = shadowMode;
  2720. samplerType.shadow = shadowMode;
  2721. texSymbol->switchId(newId);
  2722. }
  2723. txcombine->setType(TType(samplerType, EvqTemporary));
  2724. txcombine->setLoc(loc);
  2725. return txcombine;
  2726. }
  2727. // Return true if this a buffer type that has an associated counter buffer.
  2728. bool HlslParseContext::hasStructBuffCounter(const TType& type) const
  2729. {
  2730. switch (type.getQualifier().declaredBuiltIn) {
  2731. case EbvAppendConsume: // fall through...
  2732. case EbvRWStructuredBuffer: // ...
  2733. return true;
  2734. default:
  2735. return false; // the other structuredbuffer types do not have a counter.
  2736. }
  2737. }
  2738. void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
  2739. {
  2740. // Counter type
  2741. TType* counterType = new TType(EbtUint, EvqBuffer);
  2742. counterType->setFieldName(intermediate.implicitCounterName);
  2743. TTypeList* blockStruct = new TTypeList;
  2744. TTypeLoc member = { counterType, loc };
  2745. blockStruct->push_back(member);
  2746. TType blockType(blockStruct, "", counterType->getQualifier());
  2747. blockType.getQualifier().storage = EvqBuffer;
  2748. type.shallowCopy(blockType);
  2749. shareStructBufferType(type);
  2750. }
  2751. // declare counter for a structured buffer type
  2752. void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
  2753. {
  2754. // Bail out if not a struct buffer
  2755. if (! isStructBufferType(bufferType))
  2756. return;
  2757. if (! hasStructBuffCounter(bufferType))
  2758. return;
  2759. TType blockType;
  2760. counterBufferType(loc, blockType);
  2761. TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
  2762. // Counter buffer is not yet in use
  2763. structBufferCounter[*blockName] = false;
  2764. shareStructBufferType(blockType);
  2765. declareBlock(loc, blockType, blockName);
  2766. }
  2767. // return the counter that goes with a given structuredbuffer
  2768. TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
  2769. {
  2770. // Bail out if not a struct buffer
  2771. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  2772. return nullptr;
  2773. const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
  2774. // Mark the counter as being used
  2775. structBufferCounter[counterBlockName] = true;
  2776. TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
  2777. TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
  2778. TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
  2779. counterMember->setType(TType(EbtUint));
  2780. return counterMember;
  2781. }
  2782. //
  2783. // Decompose structure buffer methods into AST
  2784. //
  2785. void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  2786. {
  2787. if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
  2788. return;
  2789. const TOperator op = node->getAsOperator()->getOp();
  2790. TIntermAggregate* argAggregate = arguments->getAsAggregate();
  2791. // Buffer is the object upon which method is called, so always arg 0
  2792. TIntermTyped* bufferObj = nullptr;
  2793. // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
  2794. if (argAggregate) {
  2795. if (argAggregate->getSequence().empty())
  2796. return;
  2797. if (argAggregate->getSequence()[0])
  2798. bufferObj = argAggregate->getSequence()[0]->getAsTyped();
  2799. } else {
  2800. bufferObj = arguments->getAsSymbolNode();
  2801. }
  2802. if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
  2803. return;
  2804. // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
  2805. // This lambda adds something to it and returns the old value.
  2806. const auto incDecCounter = [&](int incval) -> TIntermTyped* {
  2807. TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
  2808. TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
  2809. if (counter == nullptr)
  2810. return nullptr;
  2811. TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
  2812. counterIncrement->setType(TType(EbtUint, EvqTemporary));
  2813. counterIncrement->setLoc(loc);
  2814. counterIncrement->getSequence().push_back(counter);
  2815. counterIncrement->getSequence().push_back(incrementValue);
  2816. return counterIncrement;
  2817. };
  2818. // Index to obtain the runtime sized array out of the buffer.
  2819. TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
  2820. if (argArray == nullptr)
  2821. return; // It might not be a struct buffer method.
  2822. switch (op) {
  2823. case EOpMethodLoad:
  2824. {
  2825. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2826. const TType& bufferType = bufferObj->getType();
  2827. const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
  2828. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2829. // buffer then, but that's what it calls itself.
  2830. const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
  2831. builtInType == EbvRWByteAddressBuffer);
  2832. if (isByteAddressBuffer)
  2833. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2834. intermediate.addConstantUnion(2, loc, true),
  2835. loc, TType(EbtInt));
  2836. // Index into the array to find the item being loaded.
  2837. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2838. node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2839. const TType derefType(argArray->getType(), 0);
  2840. node->setType(derefType);
  2841. }
  2842. break;
  2843. case EOpMethodLoad2:
  2844. case EOpMethodLoad3:
  2845. case EOpMethodLoad4:
  2846. {
  2847. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2848. TOperator constructOp = EOpNull;
  2849. int size = 0;
  2850. switch (op) {
  2851. case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
  2852. case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
  2853. case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
  2854. default: assert(0);
  2855. }
  2856. TIntermTyped* body = nullptr;
  2857. // First, we'll store the address in a variable to avoid multiple shifts
  2858. // (we must convert the byte address to an item address)
  2859. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2860. intermediate.addConstantUnion(2, loc, true),
  2861. loc, TType(EbtInt));
  2862. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2863. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2864. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2865. TIntermTyped* vec = nullptr;
  2866. // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
  2867. // address conversion.
  2868. for (int idx=0; idx<size; ++idx) {
  2869. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2870. // add index offset
  2871. if (idx != 0)
  2872. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
  2873. intermediate.addConstantUnion(idx, loc, true),
  2874. loc, TType(EbtInt));
  2875. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2876. : EOpIndexIndirect;
  2877. TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2878. TType derefType(argArray->getType(), 0);
  2879. derefType.getQualifier().makeTemporary();
  2880. indexVal->setType(derefType);
  2881. vec = intermediate.growAggregate(vec, indexVal);
  2882. }
  2883. vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
  2884. vec->getAsAggregate()->setOperator(constructOp);
  2885. body = intermediate.growAggregate(body, vec);
  2886. body->setType(vec->getType());
  2887. body->getAsAggregate()->setOperator(EOpSequence);
  2888. node = body;
  2889. }
  2890. break;
  2891. case EOpMethodStore:
  2892. case EOpMethodStore2:
  2893. case EOpMethodStore3:
  2894. case EOpMethodStore4:
  2895. {
  2896. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2897. TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
  2898. // Index into the array to find the item being loaded.
  2899. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2900. // buffer then, but that's what it calls itself).
  2901. int size = 0;
  2902. switch (op) {
  2903. case EOpMethodStore: size = 1; break;
  2904. case EOpMethodStore2: size = 2; break;
  2905. case EOpMethodStore3: size = 3; break;
  2906. case EOpMethodStore4: size = 4; break;
  2907. default: assert(0);
  2908. }
  2909. TIntermAggregate* body = nullptr;
  2910. // First, we'll store the address in a variable to avoid multiple shifts
  2911. // (we must convert the byte address to an item address)
  2912. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2913. intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
  2914. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2915. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2916. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2917. for (int idx=0; idx<size; ++idx) {
  2918. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2919. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  2920. // add index offset
  2921. if (idx != 0)
  2922. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
  2923. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2924. : EOpIndexIndirect;
  2925. TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2926. const TType derefType(argArray->getType(), 0);
  2927. lValue->setType(derefType);
  2928. TIntermTyped* rValue;
  2929. if (size == 1) {
  2930. rValue = argValue;
  2931. } else {
  2932. rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
  2933. const TType indexType(argValue->getType(), 0);
  2934. rValue->setType(indexType);
  2935. }
  2936. TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  2937. body = intermediate.growAggregate(body, assign);
  2938. }
  2939. body->setOperator(EOpSequence);
  2940. node = body;
  2941. }
  2942. break;
  2943. case EOpMethodGetDimensions:
  2944. {
  2945. const int numArgs = (int)argAggregate->getSequence().size();
  2946. TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
  2947. TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
  2948. TIntermAggregate* body = nullptr;
  2949. // Length output:
  2950. if (argArray->getType().isSizedArray()) {
  2951. const int length = argArray->getType().getOuterArraySize();
  2952. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
  2953. intermediate.addConstantUnion(length, loc, true), loc);
  2954. body = intermediate.growAggregate(body, assign, loc);
  2955. } else {
  2956. TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
  2957. argNumItems->getType());
  2958. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
  2959. body = intermediate.growAggregate(body, assign, loc);
  2960. }
  2961. // Stride output:
  2962. if (argStride != nullptr) {
  2963. int size;
  2964. int stride;
  2965. intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
  2966. argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
  2967. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
  2968. intermediate.addConstantUnion(stride, loc, true), loc);
  2969. body = intermediate.growAggregate(body, assign);
  2970. }
  2971. body->setOperator(EOpSequence);
  2972. node = body;
  2973. }
  2974. break;
  2975. case EOpInterlockedAdd:
  2976. case EOpInterlockedAnd:
  2977. case EOpInterlockedExchange:
  2978. case EOpInterlockedMax:
  2979. case EOpInterlockedMin:
  2980. case EOpInterlockedOr:
  2981. case EOpInterlockedXor:
  2982. case EOpInterlockedCompareExchange:
  2983. case EOpInterlockedCompareStore:
  2984. {
  2985. // We'll replace the first argument with the block dereference, and let
  2986. // downstream decomposition handle the rest.
  2987. TIntermSequence& sequence = argAggregate->getSequence();
  2988. TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
  2989. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
  2990. loc, TType(EbtInt));
  2991. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2992. TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2993. const TType derefType(argArray->getType(), 0);
  2994. element->setType(derefType);
  2995. // Replace the numeric byte offset parameter with array reference.
  2996. sequence[1] = element;
  2997. sequence.erase(sequence.begin(), sequence.begin()+1);
  2998. }
  2999. break;
  3000. case EOpMethodIncrementCounter:
  3001. {
  3002. node = incDecCounter(1);
  3003. break;
  3004. }
  3005. case EOpMethodDecrementCounter:
  3006. {
  3007. TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
  3008. node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
  3009. preIncValue->getType());
  3010. break;
  3011. }
  3012. case EOpMethodAppend:
  3013. {
  3014. TIntermTyped* oldCounter = incDecCounter(1);
  3015. TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
  3016. TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
  3017. const TType derefType(argArray->getType(), 0);
  3018. lValue->setType(derefType);
  3019. node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3020. break;
  3021. }
  3022. case EOpMethodConsume:
  3023. {
  3024. TIntermTyped* oldCounter = incDecCounter(-1);
  3025. TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
  3026. intermediate.addConstantUnion(-1, loc, true), loc,
  3027. oldCounter->getType());
  3028. node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
  3029. const TType derefType(argArray->getType(), 0);
  3030. node->setType(derefType);
  3031. break;
  3032. }
  3033. default:
  3034. break; // most pass through unchanged
  3035. }
  3036. }
  3037. // Create array of standard sample positions for given sample count.
  3038. // TODO: remove when a real method to query sample pos exists in SPIR-V.
  3039. TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
  3040. {
  3041. struct tSamplePos { float x, y; };
  3042. static const tSamplePos pos1[] = {
  3043. { 0.0/16.0, 0.0/16.0 },
  3044. };
  3045. // standard sample positions for 2, 4, 8, and 16 samples.
  3046. static const tSamplePos pos2[] = {
  3047. { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
  3048. };
  3049. static const tSamplePos pos4[] = {
  3050. {-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 },
  3051. };
  3052. static const tSamplePos pos8[] = {
  3053. { 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 },
  3054. {-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 },
  3055. };
  3056. static const tSamplePos pos16[] = {
  3057. { 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 },
  3058. {-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 },
  3059. {-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 },
  3060. {-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 },
  3061. };
  3062. const tSamplePos* sampleLoc = nullptr;
  3063. int numSamples = count;
  3064. switch (count) {
  3065. case 2: sampleLoc = pos2; break;
  3066. case 4: sampleLoc = pos4; break;
  3067. case 8: sampleLoc = pos8; break;
  3068. case 16: sampleLoc = pos16; break;
  3069. default:
  3070. sampleLoc = pos1;
  3071. numSamples = 1;
  3072. }
  3073. TConstUnionArray* values = new TConstUnionArray(numSamples*2);
  3074. for (int pos=0; pos<count; ++pos) {
  3075. TConstUnion x, y;
  3076. x.setDConst(sampleLoc[pos].x);
  3077. y.setDConst(sampleLoc[pos].y);
  3078. (*values)[pos*2+0] = x;
  3079. (*values)[pos*2+1] = y;
  3080. }
  3081. TType retType(EbtFloat, EvqConst, 2);
  3082. if (numSamples != 1) {
  3083. TArraySizes* arraySizes = new TArraySizes;
  3084. arraySizes->addInnerSize(numSamples);
  3085. retType.transferArraySizes(arraySizes);
  3086. }
  3087. return new TIntermConstantUnion(*values, retType);
  3088. }
  3089. //
  3090. // Decompose DX9 and DX10 sample intrinsics & object methods into AST
  3091. //
  3092. void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3093. {
  3094. if (node == nullptr || !node->getAsOperator())
  3095. return;
  3096. // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
  3097. const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
  3098. result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
  3099. TIntermTyped* convertedResult = nullptr;
  3100. TType retType;
  3101. getTextureReturnType(sampler, retType);
  3102. if (retType.isStruct()) {
  3103. // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
  3104. TIntermAggregate* conversionAggregate = new TIntermAggregate;
  3105. convertedResult = conversionAggregate;
  3106. // Convert vector output to return structure. We will need a temp symbol to copy the results to.
  3107. TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
  3108. // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
  3109. // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
  3110. TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
  3111. // Initial copy from texture to our sample result shadow.
  3112. TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
  3113. result, loc);
  3114. conversionAggregate->getSequence().push_back(shadowCopy);
  3115. unsigned vec4Pos = 0;
  3116. for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
  3117. const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
  3118. // Check for bad struct members. This should have been caught upstream. Complain, because
  3119. // wwe don't know what to do with it. This algorithm could be generalized to handle
  3120. // other things, e.g, sub-structures, but HLSL doesn't allow them.
  3121. if (!memberType.isVector() && !memberType.isScalar()) {
  3122. error(loc, "expected: scalar or vector type in texture structure", "", "");
  3123. return nullptr;
  3124. }
  3125. // Index into the struct variable to find the member to assign.
  3126. TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
  3127. intermediate.addSymbol(*structVar, loc),
  3128. intermediate.addConstantUnion(m, loc), loc);
  3129. structMember->setType(memberType);
  3130. // Assign each component of (possible) vector in struct member.
  3131. for (int component = 0; component < memberType.getVectorSize(); ++component) {
  3132. TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
  3133. intermediate.addSymbol(*sampleShadow, loc),
  3134. intermediate.addConstantUnion(vec4Pos++, loc), loc);
  3135. vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
  3136. TIntermTyped* memberAssign = nullptr;
  3137. if (memberType.isVector()) {
  3138. // Vector member: we need to create an access chain to the vector component.
  3139. TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
  3140. intermediate.addConstantUnion(component, loc), loc);
  3141. memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
  3142. } else {
  3143. // Scalar member: we can assign to it directly.
  3144. memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
  3145. }
  3146. conversionAggregate->getSequence().push_back(memberAssign);
  3147. }
  3148. }
  3149. // Add completed variable so the expression results in the whole struct value we just built.
  3150. conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
  3151. // Make it a sequence.
  3152. intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
  3153. } else {
  3154. // vector clamp the output if template vector type is smaller than sample result.
  3155. if (retType.getVectorSize() < node->getVectorSize()) {
  3156. // Too many components. Construct shorter vector from it.
  3157. const TOperator op = intermediate.mapTypeToConstructorOp(retType);
  3158. convertedResult = constructBuiltIn(retType, op, result, loc, false);
  3159. } else {
  3160. // Enough components. Use directly.
  3161. convertedResult = result;
  3162. }
  3163. }
  3164. convertedResult->setLoc(loc);
  3165. return convertedResult;
  3166. };
  3167. const TOperator op = node->getAsOperator()->getOp();
  3168. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3169. // Bail out if not a sampler method.
  3170. // Note though this is odd to do before checking the op, because the op
  3171. // could be something that takes the arguments, and the function in question
  3172. // takes the result of the op. So, this is not the final word.
  3173. if (arguments != nullptr) {
  3174. if (argAggregate == nullptr) {
  3175. if (arguments->getAsTyped()->getBasicType() != EbtSampler)
  3176. return;
  3177. } else {
  3178. if (argAggregate->getSequence().size() == 0 ||
  3179. argAggregate->getSequence()[0] == nullptr ||
  3180. argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
  3181. return;
  3182. }
  3183. }
  3184. switch (op) {
  3185. // **** DX9 intrinsics: ****
  3186. case EOpTexture:
  3187. {
  3188. // Texture with ddx & ddy is really gradient form in HLSL
  3189. if (argAggregate->getSequence().size() == 4)
  3190. node->getAsAggregate()->setOperator(EOpTextureGrad);
  3191. break;
  3192. }
  3193. case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
  3194. {
  3195. TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3196. TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3197. assert(argCoord->getVectorSize() == 4);
  3198. TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
  3199. TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
  3200. TOperator constructOp = EOpNull;
  3201. const TSampler &sampler = argSamp->getType().getSampler();
  3202. int coordSize = 0;
  3203. switch (sampler.dim)
  3204. {
  3205. case Esd1D: constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
  3206. case Esd2D: constructOp = EOpConstructVec2; coordSize = 2; break; // 2D
  3207. case Esd3D: constructOp = EOpConstructVec3; coordSize = 3; break; // 3D
  3208. case EsdCube: constructOp = EOpConstructVec3; coordSize = 3; break; // also 3D
  3209. default:
  3210. break;
  3211. }
  3212. TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
  3213. constructCoord->getSequence().push_back(argCoord);
  3214. constructCoord->setLoc(loc);
  3215. constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
  3216. TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
  3217. tex->getSequence().push_back(argSamp); // sampler
  3218. tex->getSequence().push_back(constructCoord); // coordinate
  3219. tex->getSequence().push_back(argLod); // lod
  3220. node = convertReturn(tex, sampler);
  3221. break;
  3222. }
  3223. case EOpTextureBias:
  3224. {
  3225. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3226. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3227. // HLSL puts bias in W component of coordinate. We extract it and add it to
  3228. // the argument list, instead
  3229. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3230. TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3231. TOperator constructOp = EOpNull;
  3232. const TSampler& sampler = arg0->getType().getSampler();
  3233. switch (sampler.dim) {
  3234. case Esd1D: constructOp = EOpConstructFloat; break; // 1D
  3235. case Esd2D: constructOp = EOpConstructVec2; break; // 2D
  3236. case Esd3D: constructOp = EOpConstructVec3; break; // 3D
  3237. case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
  3238. default: break;
  3239. }
  3240. TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
  3241. constructCoord->getSequence().push_back(arg1);
  3242. constructCoord->setLoc(loc);
  3243. // The input vector should never be less than 2, since there's always a bias.
  3244. // The max is for safety, and should be a no-op.
  3245. constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
  3246. TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
  3247. tex->getSequence().push_back(arg0); // sampler
  3248. tex->getSequence().push_back(constructCoord); // coordinate
  3249. tex->getSequence().push_back(bias); // bias
  3250. node = convertReturn(tex, sampler);
  3251. break;
  3252. }
  3253. // **** DX10 methods: ****
  3254. case EOpMethodSample: // fall through
  3255. case EOpMethodSampleBias: // ...
  3256. {
  3257. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3258. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3259. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3260. TIntermTyped* argBias = nullptr;
  3261. TIntermTyped* argOffset = nullptr;
  3262. const TSampler& sampler = argTex->getType().getSampler();
  3263. int nextArg = 3;
  3264. if (op == EOpMethodSampleBias) // SampleBias has a bias arg
  3265. argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3266. TOperator textureOp = EOpTexture;
  3267. if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
  3268. textureOp = EOpTextureOffset;
  3269. argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3270. }
  3271. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3272. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3273. txsample->getSequence().push_back(txcombine);
  3274. txsample->getSequence().push_back(argCoord);
  3275. if (argBias != nullptr)
  3276. txsample->getSequence().push_back(argBias);
  3277. if (argOffset != nullptr)
  3278. txsample->getSequence().push_back(argOffset);
  3279. node = convertReturn(txsample, sampler);
  3280. break;
  3281. }
  3282. case EOpMethodSampleGrad: // ...
  3283. {
  3284. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3285. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3286. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3287. TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
  3288. TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
  3289. TIntermTyped* argOffset = nullptr;
  3290. const TSampler& sampler = argTex->getType().getSampler();
  3291. TOperator textureOp = EOpTextureGrad;
  3292. if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
  3293. textureOp = EOpTextureGradOffset;
  3294. argOffset = argAggregate->getSequence()[5]->getAsTyped();
  3295. }
  3296. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3297. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3298. txsample->getSequence().push_back(txcombine);
  3299. txsample->getSequence().push_back(argCoord);
  3300. txsample->getSequence().push_back(argDDX);
  3301. txsample->getSequence().push_back(argDDY);
  3302. if (argOffset != nullptr)
  3303. txsample->getSequence().push_back(argOffset);
  3304. node = convertReturn(txsample, sampler);
  3305. break;
  3306. }
  3307. case EOpMethodGetDimensions:
  3308. {
  3309. // AST returns a vector of results, which we break apart component-wise into
  3310. // separate values to assign to the HLSL method's outputs, ala:
  3311. // tx . GetDimensions(width, height);
  3312. // float2 sizeQueryTemp = EOpTextureQuerySize
  3313. // width = sizeQueryTemp.X;
  3314. // height = sizeQueryTemp.Y;
  3315. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3316. const TType& texType = argTex->getType();
  3317. assert(texType.getBasicType() == EbtSampler);
  3318. const TSampler& sampler = texType.getSampler();
  3319. const TSamplerDim dim = sampler.dim;
  3320. const bool isImage = sampler.isImage();
  3321. const bool isMs = sampler.isMultiSample();
  3322. const int numArgs = (int)argAggregate->getSequence().size();
  3323. int numDims = 0;
  3324. switch (dim) {
  3325. case Esd1D: numDims = 1; break; // W
  3326. case Esd2D: numDims = 2; break; // W, H
  3327. case Esd3D: numDims = 3; break; // W, H, D
  3328. case EsdCube: numDims = 2; break; // W, H (cube)
  3329. case EsdBuffer: numDims = 1; break; // W (buffers)
  3330. case EsdRect: numDims = 2; break; // W, H (rect)
  3331. default:
  3332. assert(0 && "unhandled texture dimension");
  3333. }
  3334. // Arrayed adds another dimension for the number of array elements
  3335. if (sampler.isArrayed())
  3336. ++numDims;
  3337. // Establish whether the method itself is querying mip levels. This can be false even
  3338. // if the underlying query requires a MIP level, due to the available HLSL method overloads.
  3339. const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
  3340. // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
  3341. // True if:
  3342. // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
  3343. // or,
  3344. // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
  3345. const bool mipRequired =
  3346. ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
  3347. mipQuery; // 2...
  3348. // AST assumes integer return. Will be converted to float if required.
  3349. TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
  3350. sizeQuery->getSequence().push_back(argTex);
  3351. // If we're building an LOD query, add the LOD.
  3352. if (mipRequired) {
  3353. // If the base HLSL query had no MIP level given, use level 0.
  3354. TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
  3355. intermediate.addConstantUnion(0, loc, true);
  3356. sizeQuery->getSequence().push_back(queryLod);
  3357. }
  3358. sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
  3359. sizeQuery->setLoc(loc);
  3360. // Return value from size query
  3361. TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
  3362. tempArg->getWritableType().getQualifier().makeTemporary();
  3363. TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
  3364. intermediate.addSymbol(*tempArg, loc),
  3365. sizeQuery, loc);
  3366. // Compound statement for assigning outputs
  3367. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
  3368. // Index of first output parameter
  3369. const int outParamBase = mipQuery ? 2 : 1;
  3370. for (int compNum = 0; compNum < numDims; ++compNum) {
  3371. TIntermTyped* indexedOut = nullptr;
  3372. TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
  3373. if (numDims > 1) {
  3374. TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
  3375. indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
  3376. indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
  3377. indexedOut->setLoc(loc);
  3378. } else {
  3379. indexedOut = sizeQueryReturn;
  3380. }
  3381. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
  3382. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
  3383. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3384. }
  3385. // handle mip level parameter
  3386. if (mipQuery) {
  3387. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3388. TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
  3389. levelsQuery->getSequence().push_back(argTex);
  3390. levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3391. levelsQuery->setLoc(loc);
  3392. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
  3393. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3394. }
  3395. // 2DMS formats query # samples, which needs a different query op
  3396. if (sampler.isMultiSample()) {
  3397. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3398. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3399. samplesQuery->getSequence().push_back(argTex);
  3400. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3401. samplesQuery->setLoc(loc);
  3402. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
  3403. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3404. }
  3405. compoundStatement->setOperator(EOpSequence);
  3406. compoundStatement->setLoc(loc);
  3407. compoundStatement->setType(TType(EbtVoid));
  3408. node = compoundStatement;
  3409. break;
  3410. }
  3411. case EOpMethodSampleCmp: // fall through...
  3412. case EOpMethodSampleCmpLevelZero:
  3413. {
  3414. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3415. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3416. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3417. TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
  3418. TIntermTyped* argOffset = nullptr;
  3419. // Sampler argument should be a sampler.
  3420. if (argSamp->getType().getBasicType() != EbtSampler) {
  3421. error(loc, "expected: sampler type", "", "");
  3422. return;
  3423. }
  3424. // Sampler should be a SamplerComparisonState
  3425. if (! argSamp->getType().getSampler().isShadow()) {
  3426. error(loc, "expected: SamplerComparisonState", "", "");
  3427. return;
  3428. }
  3429. // optional offset value
  3430. if (argAggregate->getSequence().size() > 4)
  3431. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3432. const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
  3433. // AST wants comparison value as one of the texture coordinates
  3434. TOperator constructOp = EOpNull;
  3435. switch (coordDimWithCmpVal) {
  3436. // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
  3437. case 2: constructOp = EOpConstructVec2; break;
  3438. case 3: constructOp = EOpConstructVec3; break;
  3439. case 4: constructOp = EOpConstructVec4; break;
  3440. case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
  3441. default: assert(0); break;
  3442. }
  3443. TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
  3444. coordWithCmp->getSequence().push_back(argCoord);
  3445. if (coordDimWithCmpVal != 5) // cube array shadow is special.
  3446. coordWithCmp->getSequence().push_back(argCmpVal);
  3447. coordWithCmp->setLoc(loc);
  3448. coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
  3449. TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
  3450. if (argOffset != nullptr)
  3451. textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
  3452. // Create combined sampler & texture op
  3453. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3454. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3455. txsample->getSequence().push_back(txcombine);
  3456. txsample->getSequence().push_back(coordWithCmp);
  3457. if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
  3458. txsample->getSequence().push_back(argCmpVal);
  3459. // the LevelZero form uses 0 as an explicit LOD
  3460. if (op == EOpMethodSampleCmpLevelZero)
  3461. txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
  3462. // Add offset if present
  3463. if (argOffset != nullptr)
  3464. txsample->getSequence().push_back(argOffset);
  3465. txsample->setType(node->getType());
  3466. txsample->setLoc(loc);
  3467. node = txsample;
  3468. break;
  3469. }
  3470. case EOpMethodLoad:
  3471. {
  3472. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3473. TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
  3474. TIntermTyped* argOffset = nullptr;
  3475. TIntermTyped* lodComponent = nullptr;
  3476. TIntermTyped* coordSwizzle = nullptr;
  3477. const TSampler& sampler = argTex->getType().getSampler();
  3478. const bool isMS = sampler.isMultiSample();
  3479. const bool isBuffer = sampler.dim == EsdBuffer;
  3480. const bool isImage = sampler.isImage();
  3481. const TBasicType coordBaseType = argCoord->getType().getBasicType();
  3482. // Last component of coordinate is the mip level, for non-MS. we separate them here:
  3483. if (isMS || isBuffer || isImage) {
  3484. // MS, Buffer, and Image have no LOD
  3485. coordSwizzle = argCoord;
  3486. } else {
  3487. // Extract coordinate
  3488. int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
  3489. TSwizzleSelectors<TVectorSelector> coordFields;
  3490. for (int i = 0; i < swizzleSize; ++i)
  3491. coordFields.push_back(i);
  3492. TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
  3493. coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
  3494. coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
  3495. // Extract LOD
  3496. TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
  3497. lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
  3498. lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
  3499. }
  3500. const int numArgs = (int)argAggregate->getSequence().size();
  3501. const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
  3502. // Create texel fetch
  3503. const TOperator fetchOp = (isImage ? EOpImageLoad :
  3504. hasOffset ? EOpTextureFetchOffset :
  3505. EOpTextureFetch);
  3506. TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
  3507. // Build up the fetch
  3508. txfetch->getSequence().push_back(argTex);
  3509. txfetch->getSequence().push_back(coordSwizzle);
  3510. if (isMS) {
  3511. // add 2DMS sample index
  3512. TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
  3513. txfetch->getSequence().push_back(argSampleIdx);
  3514. } else if (isBuffer) {
  3515. // Nothing else to do for buffers.
  3516. } else if (isImage) {
  3517. // Nothing else to do for images.
  3518. } else {
  3519. // 2DMS and buffer have no LOD, but everything else does.
  3520. txfetch->getSequence().push_back(lodComponent);
  3521. }
  3522. // Obtain offset arg, if there is one.
  3523. if (hasOffset) {
  3524. const int offsetPos = (isMS ? 3 : 2);
  3525. argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
  3526. txfetch->getSequence().push_back(argOffset);
  3527. }
  3528. node = convertReturn(txfetch, sampler);
  3529. break;
  3530. }
  3531. case EOpMethodSampleLevel:
  3532. {
  3533. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3534. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3535. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3536. TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
  3537. TIntermTyped* argOffset = nullptr;
  3538. const TSampler& sampler = argTex->getType().getSampler();
  3539. const int numArgs = (int)argAggregate->getSequence().size();
  3540. if (numArgs == 5) // offset, if present
  3541. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3542. const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
  3543. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3544. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3545. txsample->getSequence().push_back(txcombine);
  3546. txsample->getSequence().push_back(argCoord);
  3547. txsample->getSequence().push_back(argLod);
  3548. if (argOffset != nullptr)
  3549. txsample->getSequence().push_back(argOffset);
  3550. node = convertReturn(txsample, sampler);
  3551. break;
  3552. }
  3553. case EOpMethodGather:
  3554. {
  3555. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3556. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3557. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3558. TIntermTyped* argOffset = nullptr;
  3559. // Offset is optional
  3560. if (argAggregate->getSequence().size() > 3)
  3561. argOffset = argAggregate->getSequence()[3]->getAsTyped();
  3562. const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
  3563. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3564. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3565. txgather->getSequence().push_back(txcombine);
  3566. txgather->getSequence().push_back(argCoord);
  3567. // Offset if not given is implicitly channel 0 (red)
  3568. if (argOffset != nullptr)
  3569. txgather->getSequence().push_back(argOffset);
  3570. txgather->setType(node->getType());
  3571. txgather->setLoc(loc);
  3572. node = txgather;
  3573. break;
  3574. }
  3575. case EOpMethodGatherRed: // fall through...
  3576. case EOpMethodGatherGreen: // ...
  3577. case EOpMethodGatherBlue: // ...
  3578. case EOpMethodGatherAlpha: // ...
  3579. case EOpMethodGatherCmpRed: // ...
  3580. case EOpMethodGatherCmpGreen: // ...
  3581. case EOpMethodGatherCmpBlue: // ...
  3582. case EOpMethodGatherCmpAlpha: // ...
  3583. {
  3584. int channel = 0; // the channel we are gathering
  3585. int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
  3586. switch (op) {
  3587. case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
  3588. case EOpMethodGatherRed: channel = 0; break;
  3589. case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
  3590. case EOpMethodGatherGreen: channel = 1; break;
  3591. case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
  3592. case EOpMethodGatherBlue: channel = 2; break;
  3593. case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
  3594. case EOpMethodGatherAlpha: channel = 3; break;
  3595. default: assert(0); break;
  3596. }
  3597. // For now, we have nothing to map the component-wise comparison forms
  3598. // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
  3599. // unimplemented error instead. Most of the machinery is here if that
  3600. // should ever become available. However, red can be passed through
  3601. // to OpImageDrefGather. G/B/A cannot, because that opcode does not
  3602. // accept a component.
  3603. if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
  3604. error(loc, "unimplemented: component-level gather compare", "", "");
  3605. return;
  3606. }
  3607. int arg = 0;
  3608. TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
  3609. TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
  3610. TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
  3611. TIntermTyped* argOffset = nullptr;
  3612. TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
  3613. // TIntermTyped* argStatus = nullptr; // TODO: residency
  3614. TIntermTyped* argCmp = nullptr;
  3615. const TSamplerDim dim = argTex->getType().getSampler().dim;
  3616. const int argSize = (int)argAggregate->getSequence().size();
  3617. bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
  3618. bool hasOffset1 = false;
  3619. bool hasOffset4 = false;
  3620. // Sampler argument should be a sampler.
  3621. if (argSamp->getType().getBasicType() != EbtSampler) {
  3622. error(loc, "expected: sampler type", "", "");
  3623. return;
  3624. }
  3625. // Cmp forms require SamplerComparisonState
  3626. if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
  3627. error(loc, "expected: SamplerComparisonState", "", "");
  3628. return;
  3629. }
  3630. // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
  3631. if (dim == Esd2D) {
  3632. hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
  3633. hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
  3634. }
  3635. assert(!(hasOffset1 && hasOffset4));
  3636. TOperator textureOp = EOpTextureGather;
  3637. // Compare forms have compare value
  3638. if (cmpValues != 0)
  3639. argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3640. // Some forms have single offset
  3641. if (hasOffset1) {
  3642. textureOp = EOpTextureGatherOffset; // single offset form
  3643. argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3644. }
  3645. // Some forms have 4 gather offsets
  3646. if (hasOffset4) {
  3647. textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
  3648. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3649. argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
  3650. }
  3651. // Residency status
  3652. if (hasStatus) {
  3653. // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
  3654. error(loc, "unimplemented: residency status", "", "");
  3655. return;
  3656. }
  3657. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3658. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3659. TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
  3660. txgather->getSequence().push_back(txcombine);
  3661. txgather->getSequence().push_back(argCoord);
  3662. // AST wants an array of 4 offsets, where HLSL has separate args. Here
  3663. // we construct an array from the separate args.
  3664. if (hasOffset4) {
  3665. TType arrayType(EbtInt, EvqTemporary, 2);
  3666. TArraySizes* arraySizes = new TArraySizes;
  3667. arraySizes->addInnerSize(4);
  3668. arrayType.transferArraySizes(arraySizes);
  3669. TIntermAggregate* initList = new TIntermAggregate(EOpNull);
  3670. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3671. initList->getSequence().push_back(argOffsets[offsetNum]);
  3672. argOffset = addConstructor(loc, initList, arrayType);
  3673. }
  3674. // Add comparison value if we have one
  3675. if (argCmp != nullptr)
  3676. txgather->getSequence().push_back(argCmp);
  3677. // Add offset (either 1, or an array of 4) if we have one
  3678. if (argOffset != nullptr)
  3679. txgather->getSequence().push_back(argOffset);
  3680. // Add channel value if the sampler is not shadow
  3681. if (! argSamp->getType().getSampler().isShadow())
  3682. txgather->getSequence().push_back(argChannel);
  3683. txgather->setType(node->getType());
  3684. txgather->setLoc(loc);
  3685. node = txgather;
  3686. break;
  3687. }
  3688. case EOpMethodCalculateLevelOfDetail:
  3689. case EOpMethodCalculateLevelOfDetailUnclamped:
  3690. {
  3691. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3692. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3693. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3694. TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
  3695. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3696. txquerylod->getSequence().push_back(txcombine);
  3697. txquerylod->getSequence().push_back(argCoord);
  3698. TIntermTyped* lodComponent = intermediate.addConstantUnion(
  3699. op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
  3700. loc, true);
  3701. TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
  3702. lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
  3703. node = lodComponentIdx;
  3704. break;
  3705. }
  3706. case EOpMethodGetSamplePosition:
  3707. {
  3708. // TODO: this entire decomposition exists because there is not yet a way to query
  3709. // the sample position directly through SPIR-V. Instead, we return fixed sample
  3710. // positions for common cases. *** If the sample positions are set differently,
  3711. // this will be wrong. ***
  3712. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3713. TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
  3714. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3715. samplesQuery->getSequence().push_back(argTex);
  3716. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3717. samplesQuery->setLoc(loc);
  3718. TIntermAggregate* compoundStatement = nullptr;
  3719. TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
  3720. outSampleCount->getWritableType().getQualifier().makeTemporary();
  3721. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
  3722. samplesQuery, loc);
  3723. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3724. TIntermTyped* idxtest[4];
  3725. // Create tests against 2, 4, 8, and 16 sample values
  3726. int count = 0;
  3727. for (int val = 2; val <= 16; val *= 2)
  3728. idxtest[count++] =
  3729. intermediate.addBinaryNode(EOpEqual,
  3730. intermediate.addSymbol(*outSampleCount, loc),
  3731. intermediate.addConstantUnion(val, loc),
  3732. loc, TType(EbtBool));
  3733. const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3734. // Create index ops into position arrays given sample index.
  3735. // TODO: should it be clamped?
  3736. TIntermTyped* index[4];
  3737. count = 0;
  3738. for (int val = 2; val <= 16; val *= 2) {
  3739. index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
  3740. index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
  3741. }
  3742. // Create expression as:
  3743. // (sampleCount == 2) ? pos2[idx] :
  3744. // (sampleCount == 4) ? pos4[idx] :
  3745. // (sampleCount == 8) ? pos8[idx] :
  3746. // (sampleCount == 16) ? pos16[idx] : float2(0,0);
  3747. TIntermTyped* test =
  3748. intermediate.addSelection(idxtest[0], index[0],
  3749. intermediate.addSelection(idxtest[1], index[1],
  3750. intermediate.addSelection(idxtest[2], index[2],
  3751. intermediate.addSelection(idxtest[3], index[3],
  3752. getSamplePosArray(1), loc), loc), loc), loc);
  3753. compoundStatement = intermediate.growAggregate(compoundStatement, test);
  3754. compoundStatement->setOperator(EOpSequence);
  3755. compoundStatement->setLoc(loc);
  3756. compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
  3757. node = compoundStatement;
  3758. break;
  3759. }
  3760. case EOpSubpassLoad:
  3761. {
  3762. const TIntermTyped* argSubpass =
  3763. argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
  3764. arguments->getAsTyped();
  3765. const TSampler& sampler = argSubpass->getType().getSampler();
  3766. // subpass load: the multisample form is overloaded. Here, we convert that to
  3767. // the EOpSubpassLoadMS opcode.
  3768. if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
  3769. node->getAsOperator()->setOp(EOpSubpassLoadMS);
  3770. node = convertReturn(node, sampler);
  3771. break;
  3772. }
  3773. default:
  3774. break; // most pass through unchanged
  3775. }
  3776. }
  3777. //
  3778. // Decompose geometry shader methods
  3779. //
  3780. void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3781. {
  3782. if (node == nullptr || !node->getAsOperator())
  3783. return;
  3784. const TOperator op = node->getAsOperator()->getOp();
  3785. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3786. switch (op) {
  3787. case EOpMethodAppend:
  3788. if (argAggregate) {
  3789. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3790. if (language != EShLangGeometry) {
  3791. node = nullptr;
  3792. return;
  3793. }
  3794. TIntermAggregate* sequence = nullptr;
  3795. TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
  3796. emit->setLoc(loc);
  3797. emit->setType(TType(EbtVoid));
  3798. TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
  3799. // This will be patched in finalization during finalizeAppendMethods()
  3800. sequence = intermediate.growAggregate(sequence, data, loc);
  3801. sequence = intermediate.growAggregate(sequence, emit);
  3802. sequence->setOperator(EOpSequence);
  3803. sequence->setLoc(loc);
  3804. sequence->setType(TType(EbtVoid));
  3805. gsAppends.push_back({sequence, loc});
  3806. node = sequence;
  3807. }
  3808. break;
  3809. case EOpMethodRestartStrip:
  3810. {
  3811. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3812. if (language != EShLangGeometry) {
  3813. node = nullptr;
  3814. return;
  3815. }
  3816. TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
  3817. cut->setLoc(loc);
  3818. cut->setType(TType(EbtVoid));
  3819. node = cut;
  3820. }
  3821. break;
  3822. default:
  3823. break; // most pass through unchanged
  3824. }
  3825. }
  3826. //
  3827. // Optionally decompose intrinsics to AST opcodes.
  3828. //
  3829. void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3830. {
  3831. // Helper to find image data for image atomics:
  3832. // OpImageLoad(image[idx])
  3833. // We take the image load apart and add its params to the atomic op aggregate node
  3834. const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
  3835. TIntermAggregate* loadOp = load->getAsAggregate();
  3836. if (loadOp == nullptr) {
  3837. error(loc, "unknown image type in atomic operation", "", "");
  3838. node = nullptr;
  3839. return;
  3840. }
  3841. atomic->getSequence().push_back(loadOp->getSequence()[0]);
  3842. atomic->getSequence().push_back(loadOp->getSequence()[1]);
  3843. };
  3844. // Return true if this is an imageLoad, which we will change to an image atomic.
  3845. const auto isImageParam = [](TIntermTyped* image) -> bool {
  3846. TIntermAggregate* imageAggregate = image->getAsAggregate();
  3847. return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
  3848. };
  3849. const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
  3850. TSymbol* symbol = symbolTable.find(name);
  3851. if (nullptr == symbol) {
  3852. type.getQualifier().builtIn = builtin;
  3853. TVariable* variable = new TVariable(NewPoolTString(name), type);
  3854. symbolTable.insert(*variable);
  3855. symbol = symbolTable.find(name);
  3856. assert(symbol && "Inserted symbol could not be found!");
  3857. }
  3858. return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
  3859. };
  3860. // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
  3861. // opcodes for compatibility with existing software stacks.
  3862. static const bool decomposeHlslIntrinsics = true;
  3863. if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
  3864. return;
  3865. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3866. TIntermUnary* fnUnary = node->getAsUnaryNode();
  3867. const TOperator op = node->getAsOperator()->getOp();
  3868. switch (op) {
  3869. case EOpGenMul:
  3870. {
  3871. // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
  3872. // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
  3873. // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
  3874. TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
  3875. TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
  3876. if (arg0->isVector() && arg1->isVector()) { // vec * vec
  3877. node->getAsAggregate()->setOperator(EOpDot);
  3878. } else {
  3879. node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
  3880. }
  3881. break;
  3882. }
  3883. case EOpRcp:
  3884. {
  3885. // rcp(a) -> 1 / a
  3886. TIntermTyped* arg0 = fnUnary->getOperand();
  3887. TBasicType type0 = arg0->getBasicType();
  3888. TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
  3889. node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
  3890. break;
  3891. }
  3892. case EOpAny: // fall through
  3893. case EOpAll:
  3894. {
  3895. TIntermTyped* typedArg = arguments->getAsTyped();
  3896. // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
  3897. // We'll convert here. Note that for efficiency, we could add a smarter
  3898. // decomposition for some type cases, e.g, maybe by decomposing a dot product.
  3899. if (typedArg->getType().getBasicType() != EbtBool) {
  3900. const TType boolType(EbtBool, EvqTemporary,
  3901. typedArg->getVectorSize(),
  3902. typedArg->getMatrixCols(),
  3903. typedArg->getMatrixRows(),
  3904. typedArg->isVector());
  3905. typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
  3906. node->getAsUnaryNode()->setOperand(typedArg);
  3907. }
  3908. break;
  3909. }
  3910. case EOpSaturate:
  3911. {
  3912. // saturate(a) -> clamp(a,0,1)
  3913. TIntermTyped* arg0 = fnUnary->getOperand();
  3914. TBasicType type0 = arg0->getBasicType();
  3915. TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
  3916. clamp->getSequence().push_back(arg0);
  3917. clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
  3918. clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
  3919. clamp->setLoc(loc);
  3920. clamp->setType(node->getType());
  3921. clamp->getWritableType().getQualifier().makeTemporary();
  3922. node = clamp;
  3923. break;
  3924. }
  3925. case EOpSinCos:
  3926. {
  3927. // sincos(a,b,c) -> b = sin(a), c = cos(a)
  3928. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  3929. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  3930. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
  3931. TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
  3932. TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
  3933. TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
  3934. TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
  3935. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
  3936. compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
  3937. compoundStatement->setOperator(EOpSequence);
  3938. compoundStatement->setLoc(loc);
  3939. compoundStatement->setType(TType(EbtVoid));
  3940. node = compoundStatement;
  3941. break;
  3942. }
  3943. case EOpClip:
  3944. {
  3945. // clip(a) -> if (any(a<0)) discard;
  3946. TIntermTyped* arg0 = fnUnary->getOperand();
  3947. TBasicType type0 = arg0->getBasicType();
  3948. TIntermTyped* compareNode = nullptr;
  3949. // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
  3950. if (!arg0->isScalar()) {
  3951. // component-wise compare: a < 0
  3952. TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
  3953. less->getSequence().push_back(arg0);
  3954. less->setLoc(loc);
  3955. // make vec or mat of bool matching dimensions of input
  3956. less->setType(TType(EbtBool, EvqTemporary,
  3957. arg0->getType().getVectorSize(),
  3958. arg0->getType().getMatrixCols(),
  3959. arg0->getType().getMatrixRows(),
  3960. arg0->getType().isVector()));
  3961. // calculate # of components for comparison const
  3962. const int constComponentCount =
  3963. std::max(arg0->getType().getVectorSize(), 1) *
  3964. std::max(arg0->getType().getMatrixCols(), 1) *
  3965. std::max(arg0->getType().getMatrixRows(), 1);
  3966. TConstUnion zero;
  3967. if (arg0->getType().isIntegerDomain())
  3968. zero.setDConst(0);
  3969. else
  3970. zero.setDConst(0.0);
  3971. TConstUnionArray zeros(constComponentCount, zero);
  3972. less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
  3973. compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
  3974. } else {
  3975. TIntermTyped* zero;
  3976. if (arg0->getType().isIntegerDomain())
  3977. zero = intermediate.addConstantUnion(0, loc, true);
  3978. else
  3979. zero = intermediate.addConstantUnion(0.0, type0, loc, true);
  3980. compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
  3981. }
  3982. TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
  3983. node = new TIntermSelection(compareNode, killNode, nullptr);
  3984. node->setLoc(loc);
  3985. break;
  3986. }
  3987. case EOpLog10:
  3988. {
  3989. // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
  3990. TIntermTyped* arg0 = fnUnary->getOperand();
  3991. TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
  3992. TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
  3993. node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
  3994. break;
  3995. }
  3996. case EOpDst:
  3997. {
  3998. // dest.x = 1;
  3999. // dest.y = src0.y * src1.y;
  4000. // dest.z = src0.z;
  4001. // dest.w = src1.w;
  4002. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4003. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4004. TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
  4005. TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
  4006. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  4007. TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
  4008. TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
  4009. TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
  4010. TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  4011. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4012. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4013. dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
  4014. dst->getSequence().push_back(src0z);
  4015. dst->getSequence().push_back(src1w);
  4016. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4017. dst->setLoc(loc);
  4018. node = dst;
  4019. break;
  4020. }
  4021. case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
  4022. case EOpInterlockedMin: // ...
  4023. case EOpInterlockedMax: // ...
  4024. case EOpInterlockedAnd: // ...
  4025. case EOpInterlockedOr: // ...
  4026. case EOpInterlockedXor: // ...
  4027. case EOpInterlockedExchange: // always has output arg
  4028. {
  4029. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4030. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
  4031. TIntermTyped* arg2 = nullptr;
  4032. if (argAggregate->getSequence().size() > 2)
  4033. arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4034. const bool isImage = isImageParam(arg0);
  4035. const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
  4036. TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
  4037. atomic->setType(arg0->getType());
  4038. atomic->getWritableType().getQualifier().makeTemporary();
  4039. atomic->setLoc(loc);
  4040. if (isImage) {
  4041. // orig_value = imageAtomicOp(image, loc, data)
  4042. imageAtomicParams(atomic, arg0);
  4043. atomic->getSequence().push_back(arg1);
  4044. if (argAggregate->getSequence().size() > 2) {
  4045. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4046. } else {
  4047. node = atomic; // no assignment needed, as there was no out var.
  4048. }
  4049. } else {
  4050. // Normal memory variable:
  4051. // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
  4052. if (argAggregate->getSequence().size() > 2) {
  4053. // optional output param is present. return value goes to arg2.
  4054. atomic->getSequence().push_back(arg0);
  4055. atomic->getSequence().push_back(arg1);
  4056. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4057. } else {
  4058. // Set the matching operator. Since output is absent, this is all we need to do.
  4059. node->getAsAggregate()->setOperator(atomicOp);
  4060. node->setType(atomic->getType());
  4061. }
  4062. }
  4063. break;
  4064. }
  4065. case EOpInterlockedCompareExchange:
  4066. {
  4067. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4068. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
  4069. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
  4070. TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
  4071. const bool isImage = isImageParam(arg0);
  4072. TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
  4073. atomic->setLoc(loc);
  4074. atomic->setType(arg2->getType());
  4075. atomic->getWritableType().getQualifier().makeTemporary();
  4076. if (isImage) {
  4077. imageAtomicParams(atomic, arg0);
  4078. } else {
  4079. atomic->getSequence().push_back(arg0);
  4080. }
  4081. atomic->getSequence().push_back(arg1);
  4082. atomic->getSequence().push_back(arg2);
  4083. node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
  4084. break;
  4085. }
  4086. case EOpEvaluateAttributeSnapped:
  4087. {
  4088. // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
  4089. // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
  4090. // iU = (iU<<28)>>28
  4091. // fU = ((float)iU)/16
  4092. // Targets might handle this natively, in which case they can disable
  4093. // decompositions.
  4094. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
  4095. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
  4096. TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
  4097. TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
  4098. handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
  4099. i28);
  4100. TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
  4101. TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
  4102. intermediate.addConversion(EOpConstructFloat,
  4103. TType(EbtFloat, EvqTemporary, 2), iU),
  4104. recip16);
  4105. TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
  4106. interp->getSequence().push_back(arg0);
  4107. interp->getSequence().push_back(floatOffset);
  4108. interp->setLoc(loc);
  4109. interp->setType(arg0->getType());
  4110. interp->getWritableType().getQualifier().makeTemporary();
  4111. node = interp;
  4112. break;
  4113. }
  4114. case EOpLit:
  4115. {
  4116. TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
  4117. TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
  4118. TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
  4119. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4120. // Ambient
  4121. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4122. // Diffuse:
  4123. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4124. TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
  4125. diffuse->getSequence().push_back(n_dot_l);
  4126. diffuse->getSequence().push_back(zero);
  4127. diffuse->setLoc(loc);
  4128. diffuse->setType(TType(EbtFloat));
  4129. dst->getSequence().push_back(diffuse);
  4130. // Specular:
  4131. TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
  4132. min_ndot->getSequence().push_back(n_dot_l);
  4133. min_ndot->getSequence().push_back(n_dot_h);
  4134. min_ndot->setLoc(loc);
  4135. min_ndot->setType(TType(EbtFloat));
  4136. TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
  4137. TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
  4138. dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
  4139. // One:
  4140. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4141. dst->setLoc(loc);
  4142. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4143. node = dst;
  4144. break;
  4145. }
  4146. case EOpAsDouble:
  4147. {
  4148. // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
  4149. // first construct a uint64.
  4150. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4151. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4152. if (arg0->getType().isVector()) { // TODO: ...
  4153. error(loc, "double2 conversion not implemented", "asdouble", "");
  4154. break;
  4155. }
  4156. TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
  4157. uint64->getSequence().push_back(arg0);
  4158. uint64->getSequence().push_back(arg1);
  4159. uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
  4160. uint64->setLoc(loc);
  4161. // bitcast uint2 to a double
  4162. TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
  4163. convert->getAsUnaryNode()->setOperand(uint64);
  4164. convert->setLoc(loc);
  4165. convert->setType(TType(EbtDouble, EvqTemporary));
  4166. node = convert;
  4167. break;
  4168. }
  4169. case EOpF16tof32:
  4170. {
  4171. // input uvecN with low 16 bits of each component holding a float16. convert to float32.
  4172. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4173. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  4174. const int vecSize = argValue->getType().getVectorSize();
  4175. TOperator constructOp = EOpNull;
  4176. switch (vecSize) {
  4177. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4178. case 2: constructOp = EOpConstructVec2; break;
  4179. case 3: constructOp = EOpConstructVec3; break;
  4180. case 4: constructOp = EOpConstructVec4; break;
  4181. default: assert(0); break;
  4182. }
  4183. // For scalar case, we don't need to construct another type.
  4184. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4185. if (result) {
  4186. result->setType(TType(EbtFloat, EvqTemporary, vecSize));
  4187. result->setLoc(loc);
  4188. }
  4189. for (int idx = 0; idx < vecSize; ++idx) {
  4190. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4191. TIntermTyped* component = argValue->getType().isVector() ?
  4192. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4193. if (component != argValue)
  4194. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4195. TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
  4196. unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
  4197. unpackOp->getAsUnaryNode()->setOperand(component);
  4198. unpackOp->setLoc(loc);
  4199. TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
  4200. if (result != nullptr) {
  4201. result->getSequence().push_back(lowOrder);
  4202. node = result;
  4203. } else {
  4204. node = lowOrder;
  4205. }
  4206. }
  4207. break;
  4208. }
  4209. case EOpF32tof16:
  4210. {
  4211. // input floatN converted to 16 bit float in low order bits of each component of uintN
  4212. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4213. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4214. const int vecSize = argValue->getType().getVectorSize();
  4215. TOperator constructOp = EOpNull;
  4216. switch (vecSize) {
  4217. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4218. case 2: constructOp = EOpConstructUVec2; break;
  4219. case 3: constructOp = EOpConstructUVec3; break;
  4220. case 4: constructOp = EOpConstructUVec4; break;
  4221. default: assert(0); break;
  4222. }
  4223. // For scalar case, we don't need to construct another type.
  4224. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4225. if (result) {
  4226. result->setType(TType(EbtUint, EvqTemporary, vecSize));
  4227. result->setLoc(loc);
  4228. }
  4229. for (int idx = 0; idx < vecSize; ++idx) {
  4230. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4231. TIntermTyped* component = argValue->getType().isVector() ?
  4232. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4233. if (component != argValue)
  4234. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4235. TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
  4236. vec2ComponentAndZero->getSequence().push_back(component);
  4237. vec2ComponentAndZero->getSequence().push_back(zero);
  4238. vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
  4239. vec2ComponentAndZero->setLoc(loc);
  4240. TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
  4241. packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
  4242. packOp->setLoc(loc);
  4243. packOp->setType(TType(EbtUint, EvqTemporary));
  4244. if (result != nullptr) {
  4245. result->getSequence().push_back(packOp);
  4246. node = result;
  4247. } else {
  4248. node = packOp;
  4249. }
  4250. }
  4251. break;
  4252. }
  4253. case EOpD3DCOLORtoUBYTE4:
  4254. {
  4255. // ivec4 ( x.zyxw * 255.001953 );
  4256. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4257. TSwizzleSelectors<TVectorSelector> selectors;
  4258. selectors.push_back(2);
  4259. selectors.push_back(1);
  4260. selectors.push_back(0);
  4261. selectors.push_back(3);
  4262. TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
  4263. TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
  4264. swizzled->setType(arg0->getType());
  4265. swizzled->getWritableType().getQualifier().makeTemporary();
  4266. TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
  4267. TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
  4268. rangeConverted->setType(arg0->getType());
  4269. rangeConverted->getWritableType().getQualifier().makeTemporary();
  4270. node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
  4271. node->setLoc(loc);
  4272. node->setType(TType(EbtInt, EvqTemporary, 4));
  4273. break;
  4274. }
  4275. case EOpIsFinite:
  4276. {
  4277. // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
  4278. // it to !isnan && !isinf
  4279. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4280. // We'll make a temporary in case the RHS is cmoplex
  4281. TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
  4282. tempArg->getWritableType().getQualifier().makeTemporary();
  4283. TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
  4284. intermediate.addSymbol(*tempArg, loc),
  4285. arg0, loc);
  4286. TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
  4287. const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
  4288. arg0->getMatrixRows());
  4289. TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
  4290. isnan->setType(boolType);
  4291. TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
  4292. notnan->setType(boolType);
  4293. TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
  4294. isinf->setType(boolType);
  4295. TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
  4296. notinf->setType(boolType);
  4297. TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
  4298. andNode->setType(boolType);
  4299. compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
  4300. compoundStatement->setOperator(EOpSequence);
  4301. compoundStatement->setLoc(loc);
  4302. compoundStatement->setType(boolType);
  4303. node = compoundStatement;
  4304. break;
  4305. }
  4306. case EOpWaveGetLaneCount:
  4307. {
  4308. // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
  4309. // so that it inhabits the symbol table, but has a user-invalid name
  4310. // in-case some source HLSL defined the symbol also).
  4311. TType type(EbtUint, EvqVaryingIn);
  4312. node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
  4313. break;
  4314. }
  4315. case EOpWaveGetLaneIndex:
  4316. {
  4317. // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
  4318. // symbol so that it inhabits the symbol table, but has a
  4319. // user-invalid name in-case some source HLSL defined the symbol
  4320. // also).
  4321. TType type(EbtUint, EvqVaryingIn);
  4322. node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
  4323. break;
  4324. }
  4325. case EOpWaveActiveCountBits:
  4326. {
  4327. // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
  4328. // uvec4 type.
  4329. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4330. // Get the uvec4 return from subgroupBallot().
  4331. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4332. EOpSubgroupBallot, true, arguments, uvec4Type);
  4333. // uint type.
  4334. TType uintType(EbtUint, EvqTemporary);
  4335. node = intermediate.addBuiltInFunctionCall(loc,
  4336. EOpSubgroupBallotBitCount, true, res, uintType);
  4337. break;
  4338. }
  4339. case EOpWavePrefixCountBits:
  4340. {
  4341. // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
  4342. // builtin
  4343. // uvec4 type.
  4344. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4345. // Get the uvec4 return from subgroupBallot().
  4346. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4347. EOpSubgroupBallot, true, arguments, uvec4Type);
  4348. // uint type.
  4349. TType uintType(EbtUint, EvqTemporary);
  4350. node = intermediate.addBuiltInFunctionCall(loc,
  4351. EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
  4352. break;
  4353. }
  4354. default:
  4355. break; // most pass through unchanged
  4356. }
  4357. }
  4358. //
  4359. // Handle seeing function call syntax in the grammar, which could be any of
  4360. // - .length() method
  4361. // - constructor
  4362. // - a call to a built-in function mapped to an operator
  4363. // - a call to a built-in function that will remain a function call (e.g., texturing)
  4364. // - user function
  4365. // - subroutine call (not implemented yet)
  4366. //
  4367. TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
  4368. {
  4369. TIntermTyped* result = nullptr;
  4370. TOperator op = function->getBuiltInOp();
  4371. if (op != EOpNull) {
  4372. //
  4373. // Then this should be a constructor.
  4374. // Don't go through the symbol table for constructors.
  4375. // Their parameters will be verified algorithmically.
  4376. //
  4377. TType type(EbtVoid); // use this to get the type back
  4378. if (! constructorError(loc, arguments, *function, op, type)) {
  4379. //
  4380. // It's a constructor, of type 'type'.
  4381. //
  4382. result = handleConstructor(loc, arguments, type);
  4383. if (result == nullptr) {
  4384. error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
  4385. return nullptr;
  4386. }
  4387. }
  4388. } else {
  4389. //
  4390. // Find it in the symbol table.
  4391. //
  4392. const TFunction* fnCandidate = nullptr;
  4393. bool builtIn = false;
  4394. int thisDepth = 0;
  4395. // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
  4396. // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
  4397. // It doesn't naturally fall out of processing an argument at a time in isolation.
  4398. if (function->getName() == "mul")
  4399. addGenMulArgumentConversion(loc, *function, arguments);
  4400. TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4401. // TODO: this needs improvement: there's no way at present to look up a signature in
  4402. // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
  4403. // It will have false positives, since it doesn't check arg counts or types.
  4404. if (arguments) {
  4405. // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
  4406. // look for either case.
  4407. TIntermTyped* arg0 = nullptr;
  4408. if (aggregate && aggregate->getSequence().size() > 0 && aggregate->getSequence()[0])
  4409. arg0 = aggregate->getSequence()[0]->getAsTyped();
  4410. else if (arguments->getAsSymbolNode())
  4411. arg0 = arguments->getAsSymbolNode();
  4412. if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
  4413. static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
  4414. if (function->getName().length() > methodPrefixSize &&
  4415. isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
  4416. const TString mangle = function->getName() + "(";
  4417. TSymbol* symbol = symbolTable.find(mangle, &builtIn);
  4418. if (symbol)
  4419. fnCandidate = symbol->getAsFunction();
  4420. }
  4421. }
  4422. }
  4423. if (fnCandidate == nullptr)
  4424. fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
  4425. if (fnCandidate) {
  4426. // This is a declared function that might map to
  4427. // - a built-in operator,
  4428. // - a built-in function not mapped to an operator, or
  4429. // - a user function.
  4430. // turn an implicit member-function resolution into an explicit call
  4431. TString callerName;
  4432. if (thisDepth == 0)
  4433. callerName = fnCandidate->getMangledName();
  4434. else {
  4435. // get the explicit (full) name of the function
  4436. callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
  4437. callerName += fnCandidate->getMangledName();
  4438. // insert the implicit calling argument
  4439. pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
  4440. }
  4441. // Convert 'in' arguments, so that types match.
  4442. // However, skip those that need expansion, that is covered next.
  4443. if (arguments)
  4444. addInputArgumentConversions(*fnCandidate, arguments);
  4445. // Expand arguments. Some arguments must physically expand to a different set
  4446. // than what the shader declared and passes.
  4447. if (arguments && !builtIn)
  4448. expandArguments(loc, *fnCandidate, arguments);
  4449. // Expansion may have changed the form of arguments
  4450. aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4451. op = fnCandidate->getBuiltInOp();
  4452. if (builtIn && op != EOpNull) {
  4453. // A function call mapped to a built-in operation.
  4454. result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
  4455. fnCandidate->getType());
  4456. if (result == nullptr) {
  4457. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  4458. "built in unary operator function. Type: %s",
  4459. static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
  4460. } else if (result->getAsOperator()) {
  4461. builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
  4462. }
  4463. } else {
  4464. // This is a function call not mapped to built-in operator.
  4465. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  4466. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  4467. TIntermAggregate* call = result->getAsAggregate();
  4468. call->setName(callerName);
  4469. // this is how we know whether the given function is a built-in function or a user-defined function
  4470. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  4471. // if builtIn == true, it's definitely a built-in function with EOpNull
  4472. if (! builtIn) {
  4473. call->setUserDefined();
  4474. intermediate.addToCallGraph(infoSink, currentCaller, callerName);
  4475. }
  4476. }
  4477. // for decompositions, since we want to operate on the function node, not the aggregate holding
  4478. // output conversions.
  4479. const TIntermTyped* fnNode = result;
  4480. decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
  4481. decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
  4482. decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
  4483. decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
  4484. // Create the qualifier list, carried in the AST for the call.
  4485. // Because some arguments expand to multiple arguments, the qualifier list will
  4486. // be longer than the formal parameter list.
  4487. if (result == fnNode && result->getAsAggregate()) {
  4488. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  4489. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  4490. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  4491. if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
  4492. // add buffer and counter buffer argument qualifier
  4493. qualifierList.push_back(qual);
  4494. qualifierList.push_back(qual);
  4495. } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
  4496. true)) {
  4497. // add structure member expansion
  4498. for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
  4499. qualifierList.push_back(qual);
  4500. } else {
  4501. // Normal 1:1 case
  4502. qualifierList.push_back(qual);
  4503. }
  4504. }
  4505. }
  4506. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  4507. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  4508. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  4509. // We don't do this is if there has been a decomposition, which will have added its own conversions
  4510. // for output parameters.
  4511. if (result == fnNode && result->getAsAggregate())
  4512. result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
  4513. }
  4514. }
  4515. // generic error recovery
  4516. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
  4517. // reduce cascades
  4518. if (result == nullptr)
  4519. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  4520. return result;
  4521. }
  4522. // An initial argument list is difficult: it can be null, or a single node,
  4523. // or an aggregate if more than one argument. Add one to the front, maintaining
  4524. // this lack of uniformity.
  4525. void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
  4526. {
  4527. if (arguments == nullptr)
  4528. arguments = front;
  4529. else if (arguments->getAsAggregate() != nullptr)
  4530. arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
  4531. else
  4532. arguments = intermediate.growAggregate(front, arguments);
  4533. }
  4534. //
  4535. // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
  4536. // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
  4537. // can look at both arguments insert explicit shape changes if required.
  4538. //
  4539. void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
  4540. {
  4541. TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
  4542. if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
  4543. // It really ought to have two arguments.
  4544. error(loc, "expected: mul arguments", "", "");
  4545. return;
  4546. }
  4547. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4548. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4549. if (arg0->isVector() && arg1->isVector()) {
  4550. // For:
  4551. // vec * vec: it's handled during intrinsic selection, so while we could do it here,
  4552. // we can also ignore it, which is easier.
  4553. } else if (arg0->isVector() && arg1->isMatrix()) {
  4554. // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4555. if (arg0->getVectorSize() < arg1->getMatrixCols()) {
  4556. // vec is smaller, so truncate larger mat dimension
  4557. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4558. 0, arg0->getVectorSize(), arg1->getMatrixRows());
  4559. arg1 = addConstructor(loc, arg1, truncType);
  4560. } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
  4561. // vec is larger, so truncate vec to mat size
  4562. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4563. arg1->getMatrixCols());
  4564. arg0 = addConstructor(loc, arg0, truncType);
  4565. }
  4566. } else if (arg0->isMatrix() && arg1->isVector()) {
  4567. // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4568. if (arg1->getVectorSize() < arg0->getMatrixRows()) {
  4569. // vec is smaller, so truncate larger mat dimension
  4570. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4571. 0, arg0->getMatrixCols(), arg1->getVectorSize());
  4572. arg0 = addConstructor(loc, arg0, truncType);
  4573. } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
  4574. // vec is larger, so truncate vec to mat size
  4575. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4576. arg0->getMatrixRows());
  4577. arg1 = addConstructor(loc, arg1, truncType);
  4578. }
  4579. } else if (arg0->isMatrix() && arg1->isMatrix()) {
  4580. // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
  4581. // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
  4582. if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
  4583. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4584. 0, arg0->getMatrixCols(), arg1->getMatrixCols());
  4585. arg0 = addConstructor(loc, arg0, truncType);
  4586. } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
  4587. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4588. 0, arg0->getMatrixRows(), arg1->getMatrixRows());
  4589. arg1 = addConstructor(loc, arg1, truncType);
  4590. }
  4591. } else {
  4592. // It's something with scalars: we'll just leave it alone. Function selection will handle it
  4593. // downstream.
  4594. }
  4595. // Warn if we altered one of the arguments
  4596. if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
  4597. warn(loc, "mul() matrix size mismatch", "", "");
  4598. // Put arguments back. (They might be unchanged, in which case this is harmless).
  4599. argAggregate->getSequence()[0] = arg0;
  4600. argAggregate->getSequence()[1] = arg1;
  4601. call[0].type = &arg0->getWritableType();
  4602. call[1].type = &arg1->getWritableType();
  4603. }
  4604. //
  4605. // Add any needed implicit conversions for function-call arguments to input parameters.
  4606. //
  4607. void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
  4608. {
  4609. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4610. // Replace a single argument with a single argument.
  4611. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4612. if (function.getParamCount() == 1)
  4613. arguments = arg;
  4614. else {
  4615. if (aggregate == nullptr)
  4616. arguments = arg;
  4617. else
  4618. aggregate->getSequence()[paramNum] = arg;
  4619. }
  4620. };
  4621. // Process each argument's conversion
  4622. for (int param = 0; param < function.getParamCount(); ++param) {
  4623. if (! function[param].type->getQualifier().isParamInput())
  4624. continue;
  4625. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4626. // is the single argument itself or its children are the arguments. Only one argument
  4627. // means take 'arguments' itself as the one argument.
  4628. TIntermTyped* arg = function.getParamCount() == 1
  4629. ? arguments->getAsTyped()
  4630. : (aggregate ?
  4631. aggregate->getSequence()[param]->getAsTyped() :
  4632. arguments->getAsTyped());
  4633. if (*function[param].type != arg->getType()) {
  4634. // In-qualified arguments just need an extra node added above the argument to
  4635. // convert to the correct type.
  4636. TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
  4637. if (convArg != nullptr)
  4638. convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
  4639. if (convArg != nullptr)
  4640. setArg(param, convArg);
  4641. else
  4642. error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
  4643. } else {
  4644. if (wasFlattened(arg)) {
  4645. // If both formal and calling arg are to be flattened, leave that to argument
  4646. // expansion, not conversion.
  4647. if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4648. // Will make a two-level subtree.
  4649. // The deepest will copy member-by-member to build the structure to pass.
  4650. // The level above that will be a two-operand EOpComma sequence that follows the copy by the
  4651. // object itself.
  4652. TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
  4653. internalAggregate->getWritableType().getQualifier().makeTemporary();
  4654. TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
  4655. internalAggregate->getName(),
  4656. internalAggregate->getType());
  4657. internalSymbolNode->setLoc(arg->getLoc());
  4658. // This makes the deepest level, the member-wise copy
  4659. TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
  4660. internalSymbolNode, arg)->getAsAggregate();
  4661. // Now, pair that with the resulting aggregate.
  4662. assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
  4663. assignAgg->setOperator(EOpComma);
  4664. assignAgg->setType(internalAggregate->getType());
  4665. setArg(param, assignAgg);
  4666. }
  4667. }
  4668. }
  4669. }
  4670. }
  4671. //
  4672. // Add any needed implicit expansion of calling arguments from what the shader listed to what's
  4673. // internally needed for the AST (given the constraints downstream).
  4674. //
  4675. void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
  4676. {
  4677. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4678. int functionParamNumberOffset = 0;
  4679. // Replace a single argument with a single argument.
  4680. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4681. if (function.getParamCount() + functionParamNumberOffset == 1)
  4682. arguments = arg;
  4683. else {
  4684. if (aggregate == nullptr)
  4685. arguments = arg;
  4686. else
  4687. aggregate->getSequence()[paramNum] = arg;
  4688. }
  4689. };
  4690. // Replace a single argument with a list of arguments
  4691. const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
  4692. if (args.size() == 1)
  4693. setArg(paramNum, args.front());
  4694. else if (args.size() > 1) {
  4695. if (function.getParamCount() + functionParamNumberOffset == 1) {
  4696. arguments = intermediate.makeAggregate(args.front());
  4697. std::for_each(args.begin() + 1, args.end(),
  4698. [&](TIntermTyped* arg) {
  4699. arguments = intermediate.growAggregate(arguments, arg);
  4700. });
  4701. } else {
  4702. auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
  4703. aggregate->getSequence().insert(it, args.begin(), args.end());
  4704. }
  4705. functionParamNumberOffset += (int)(args.size() - 1);
  4706. }
  4707. };
  4708. // Process each argument's conversion
  4709. for (int param = 0; param < function.getParamCount(); ++param) {
  4710. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4711. // is the single argument itself or its children are the arguments. Only one argument
  4712. // means take 'arguments' itself as the one argument.
  4713. TIntermTyped* arg = function.getParamCount() == 1
  4714. ? arguments->getAsTyped()
  4715. : (aggregate ?
  4716. aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
  4717. arguments->getAsTyped());
  4718. if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4719. // Need to pass the structure members instead of the structure.
  4720. TVector<TIntermTyped*> memberArgs;
  4721. for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
  4722. memberArgs.push_back(flattenAccess(arg, memb));
  4723. setArgList(param + functionParamNumberOffset, memberArgs);
  4724. }
  4725. }
  4726. // TODO: if we need both hidden counter args (below) and struct expansion (above)
  4727. // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
  4728. // parameters and arguments.
  4729. // If any argument is a pass-by-reference struct buffer with an associated counter
  4730. // buffer, we have to add another hidden parameter for that counter.
  4731. if (aggregate)
  4732. addStructBuffArguments(loc, aggregate);
  4733. }
  4734. //
  4735. // Add any needed implicit output conversions for function-call arguments. This
  4736. // can require a new tree topology, complicated further by whether the function
  4737. // has a return value.
  4738. //
  4739. // Returns a node of a subtree that evaluates to the return value of the function.
  4740. //
  4741. TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
  4742. {
  4743. assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
  4744. const TSourceLoc& loc = intermNode.getLoc();
  4745. TIntermSequence argSequence; // temp sequence for unary node args
  4746. if (intermNode.getAsUnaryNode())
  4747. argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
  4748. TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
  4749. const auto needsConversion = [&](int argNum) {
  4750. return function[argNum].type->getQualifier().isParamOutput() &&
  4751. (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
  4752. shouldConvertLValue(arguments[argNum]) ||
  4753. wasFlattened(arguments[argNum]->getAsTyped()));
  4754. };
  4755. // Will there be any output conversions?
  4756. bool outputConversions = false;
  4757. for (int i = 0; i < function.getParamCount(); ++i) {
  4758. if (needsConversion(i)) {
  4759. outputConversions = true;
  4760. break;
  4761. }
  4762. }
  4763. if (! outputConversions)
  4764. return &intermNode;
  4765. // Setup for the new tree, if needed:
  4766. //
  4767. // Output conversions need a different tree topology.
  4768. // Out-qualified arguments need a temporary of the correct type, with the call
  4769. // followed by an assignment of the temporary to the original argument:
  4770. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  4771. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  4772. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  4773. TIntermTyped* conversionTree = nullptr;
  4774. TVariable* tempRet = nullptr;
  4775. if (intermNode.getBasicType() != EbtVoid) {
  4776. // do the "tempRet = function(...), " bit from above
  4777. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  4778. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4779. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
  4780. } else
  4781. conversionTree = &intermNode;
  4782. conversionTree = intermediate.makeAggregate(conversionTree);
  4783. // Process each argument's conversion
  4784. for (int i = 0; i < function.getParamCount(); ++i) {
  4785. if (needsConversion(i)) {
  4786. // Out-qualified arguments needing conversion need to use the topology setup above.
  4787. // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
  4788. // Make a temporary for what the function expects the argument to look like.
  4789. TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
  4790. tempArg->getWritableType().getQualifier().makeTemporary();
  4791. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
  4792. // This makes the deepest level, the member-wise copy
  4793. TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
  4794. tempArgNode);
  4795. tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
  4796. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  4797. // replace the argument with another node for the same tempArg variable
  4798. arguments[i] = intermediate.addSymbol(*tempArg, loc);
  4799. }
  4800. }
  4801. // Finalize the tree topology (see bigger comment above).
  4802. if (tempRet) {
  4803. // do the "..., tempRet" bit from above
  4804. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4805. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
  4806. }
  4807. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
  4808. return conversionTree;
  4809. }
  4810. //
  4811. // Add any needed "hidden" counter buffer arguments for function calls.
  4812. //
  4813. // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
  4814. //
  4815. void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
  4816. {
  4817. // See if there are any SB types with counters.
  4818. const bool hasStructBuffArg =
  4819. std::any_of(aggregate->getSequence().begin(),
  4820. aggregate->getSequence().end(),
  4821. [this](const TIntermNode* node) {
  4822. return (node && node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
  4823. });
  4824. // Nothing to do, if we didn't find one.
  4825. if (! hasStructBuffArg)
  4826. return;
  4827. TIntermSequence argsWithCounterBuffers;
  4828. for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
  4829. argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
  4830. if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
  4831. const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
  4832. if (blockSym != nullptr) {
  4833. TType counterType;
  4834. counterBufferType(loc, counterType);
  4835. const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
  4836. TVariable* variable = makeInternalVariable(counterBlockName, counterType);
  4837. // Mark this buffer's counter block as being in use
  4838. structBufferCounter[counterBlockName] = true;
  4839. TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
  4840. argsWithCounterBuffers.push_back(sym);
  4841. }
  4842. }
  4843. }
  4844. // Swap with the temp list we've built up.
  4845. aggregate->getSequence().swap(argsWithCounterBuffers);
  4846. }
  4847. //
  4848. // Do additional checking of built-in function calls that is not caught
  4849. // by normal semantic checks on argument type, extension tagging, etc.
  4850. //
  4851. // Assumes there has been a semantically correct match to a built-in function prototype.
  4852. //
  4853. void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  4854. {
  4855. // Set up convenience accessors to the argument(s). There is almost always
  4856. // multiple arguments for the cases below, but when there might be one,
  4857. // check the unaryArg first.
  4858. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  4859. const TIntermTyped* unaryArg = nullptr;
  4860. const TIntermTyped* arg0 = nullptr;
  4861. if (callNode.getAsAggregate()) {
  4862. argp = &callNode.getAsAggregate()->getSequence();
  4863. if (argp->size() > 0)
  4864. arg0 = (*argp)[0]->getAsTyped();
  4865. } else {
  4866. assert(callNode.getAsUnaryNode());
  4867. unaryArg = callNode.getAsUnaryNode()->getOperand();
  4868. arg0 = unaryArg;
  4869. }
  4870. const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
  4871. switch (callNode.getOp()) {
  4872. case EOpTextureGather:
  4873. case EOpTextureGatherOffset:
  4874. case EOpTextureGatherOffsets:
  4875. {
  4876. // Figure out which variants are allowed by what extensions,
  4877. // and what arguments must be constant for which situations.
  4878. TString featureString = fnCandidate.getName() + "(...)";
  4879. const char* feature = featureString.c_str();
  4880. int compArg = -1; // track which argument, if any, is the constant component argument
  4881. switch (callNode.getOp()) {
  4882. case EOpTextureGather:
  4883. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  4884. // otherwise, need GL_ARB_texture_gather.
  4885. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
  4886. fnCandidate[0].type->getSampler().shadow) {
  4887. if (! fnCandidate[0].type->getSampler().shadow)
  4888. compArg = 2;
  4889. }
  4890. break;
  4891. case EOpTextureGatherOffset:
  4892. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  4893. if (! fnCandidate[0].type->getSampler().shadow)
  4894. compArg = 3;
  4895. break;
  4896. case EOpTextureGatherOffsets:
  4897. if (! fnCandidate[0].type->getSampler().shadow)
  4898. compArg = 3;
  4899. break;
  4900. default:
  4901. break;
  4902. }
  4903. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  4904. if (aggArgs[compArg]->getAsConstantUnion()) {
  4905. int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  4906. if (value < 0 || value > 3)
  4907. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  4908. } else
  4909. error(loc, "must be a compile-time constant:", feature, "component argument");
  4910. }
  4911. break;
  4912. }
  4913. case EOpTextureOffset:
  4914. case EOpTextureFetchOffset:
  4915. case EOpTextureProjOffset:
  4916. case EOpTextureLodOffset:
  4917. case EOpTextureProjLodOffset:
  4918. case EOpTextureGradOffset:
  4919. case EOpTextureProjGradOffset:
  4920. {
  4921. // Handle texture-offset limits checking
  4922. // Pick which argument has to hold constant offsets
  4923. int arg = -1;
  4924. switch (callNode.getOp()) {
  4925. case EOpTextureOffset: arg = 2; break;
  4926. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
  4927. case EOpTextureProjOffset: arg = 2; break;
  4928. case EOpTextureLodOffset: arg = 3; break;
  4929. case EOpTextureProjLodOffset: arg = 3; break;
  4930. case EOpTextureGradOffset: arg = 4; break;
  4931. case EOpTextureProjGradOffset: arg = 4; break;
  4932. default:
  4933. assert(0);
  4934. break;
  4935. }
  4936. if (arg > 0) {
  4937. if (aggArgs[arg]->getAsConstantUnion() == nullptr)
  4938. error(loc, "argument must be compile-time constant", "texel offset", "");
  4939. else {
  4940. const TType& type = aggArgs[arg]->getAsTyped()->getType();
  4941. for (int c = 0; c < type.getVectorSize(); ++c) {
  4942. int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  4943. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  4944. error(loc, "value is out of range:", "texel offset",
  4945. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  4946. }
  4947. }
  4948. }
  4949. break;
  4950. }
  4951. case EOpTextureQuerySamples:
  4952. case EOpImageQuerySamples:
  4953. break;
  4954. case EOpImageAtomicAdd:
  4955. case EOpImageAtomicMin:
  4956. case EOpImageAtomicMax:
  4957. case EOpImageAtomicAnd:
  4958. case EOpImageAtomicOr:
  4959. case EOpImageAtomicXor:
  4960. case EOpImageAtomicExchange:
  4961. case EOpImageAtomicCompSwap:
  4962. break;
  4963. case EOpInterpolateAtCentroid:
  4964. case EOpInterpolateAtSample:
  4965. case EOpInterpolateAtOffset:
  4966. // Make sure the first argument is an interpolant, or an array element of an interpolant
  4967. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  4968. // It might still be an array element.
  4969. //
  4970. // We could check more, but the semantics of the first argument are already met; the
  4971. // only way to turn an array into a float/vec* is array dereference and swizzle.
  4972. //
  4973. // ES and desktop 4.3 and earlier: swizzles may not be used
  4974. // desktop 4.4 and later: swizzles may be used
  4975. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
  4976. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  4977. error(loc, "first argument must be an interpolant, or interpolant-array element",
  4978. fnCandidate.getName().c_str(), "");
  4979. }
  4980. break;
  4981. default:
  4982. break;
  4983. }
  4984. }
  4985. //
  4986. // Handle seeing something in a grammar production that can be done by calling
  4987. // a constructor.
  4988. //
  4989. // The constructor still must be "handled" by handleFunctionCall(), which will
  4990. // then call handleConstructor().
  4991. //
  4992. TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
  4993. {
  4994. TOperator op = intermediate.mapTypeToConstructorOp(type);
  4995. if (op == EOpNull) {
  4996. error(loc, "cannot construct this type", type.getBasicString(), "");
  4997. return nullptr;
  4998. }
  4999. TString empty("");
  5000. return new TFunction(&empty, type, op);
  5001. }
  5002. //
  5003. // Handle seeing a "COLON semantic" at the end of a type declaration,
  5004. // by updating the type according to the semantic.
  5005. //
  5006. void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
  5007. const TString& upperCase)
  5008. {
  5009. // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
  5010. // semantic number is >= limit, errorMsg is issued and 0 is returned.
  5011. // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
  5012. // accept those in lambda functions.
  5013. const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
  5014. size_t pos = semantic.find_last_not_of("0123456789");
  5015. if (pos == std::string::npos)
  5016. return 0u;
  5017. unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
  5018. if (limit != 0 && semanticNum >= limit) {
  5019. error(loc, errorMsg, semantic.c_str(), "");
  5020. return 0u;
  5021. }
  5022. return semanticNum;
  5023. };
  5024. switch(builtIn) {
  5025. case EbvNone:
  5026. // Get location numbers from fragment outputs, instead of
  5027. // auto-assigning them.
  5028. if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
  5029. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5030. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5031. } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
  5032. builtIn = EbvClipDistance;
  5033. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
  5034. } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
  5035. builtIn = EbvCullDistance;
  5036. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
  5037. }
  5038. break;
  5039. case EbvPosition:
  5040. // adjust for stage in/out
  5041. if (language == EShLangFragment)
  5042. builtIn = EbvFragCoord;
  5043. break;
  5044. case EbvFragStencilRef:
  5045. error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
  5046. break;
  5047. case EbvTessLevelInner:
  5048. case EbvTessLevelOuter:
  5049. qualifier.patch = true;
  5050. break;
  5051. default:
  5052. break;
  5053. }
  5054. if (qualifier.builtIn == EbvNone)
  5055. qualifier.builtIn = builtIn;
  5056. qualifier.semanticName = intermediate.addSemanticName(upperCase);
  5057. }
  5058. //
  5059. // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
  5060. //
  5061. // 'location' has the "c[Subcomponent]" part.
  5062. // 'component' points to the "component" part, or nullptr if not present.
  5063. //
  5064. void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
  5065. const glslang::TString* component)
  5066. {
  5067. if (location.size() == 0 || location[0] != 'c') {
  5068. error(loc, "expected 'c'", "packoffset", "");
  5069. return;
  5070. }
  5071. if (location.size() == 1)
  5072. return;
  5073. if (! isdigit(location[1])) {
  5074. error(loc, "expected number after 'c'", "packoffset", "");
  5075. return;
  5076. }
  5077. qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
  5078. if (component != nullptr) {
  5079. int componentOffset = 0;
  5080. switch ((*component)[0]) {
  5081. case 'x': componentOffset = 0; break;
  5082. case 'y': componentOffset = 4; break;
  5083. case 'z': componentOffset = 8; break;
  5084. case 'w': componentOffset = 12; break;
  5085. default:
  5086. componentOffset = -1;
  5087. break;
  5088. }
  5089. if (componentOffset < 0 || component->size() > 1) {
  5090. error(loc, "expected {x, y, z, w} for component", "packoffset", "");
  5091. return;
  5092. }
  5093. qualifier.layoutOffset += componentOffset;
  5094. }
  5095. }
  5096. //
  5097. // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
  5098. //
  5099. // 'profile' points to the shader_profile part, or nullptr if not present.
  5100. // 'desc' is the type# part.
  5101. //
  5102. void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
  5103. const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
  5104. {
  5105. if (profile != nullptr)
  5106. warn(loc, "ignoring shader_profile", "register", "");
  5107. if (desc.size() < 1) {
  5108. error(loc, "expected register type", "register", "");
  5109. return;
  5110. }
  5111. int regNumber = 0;
  5112. if (desc.size() > 1) {
  5113. if (isdigit(desc[1]))
  5114. regNumber = atoi(desc.substr(1, desc.size()).c_str());
  5115. else {
  5116. error(loc, "expected register number after register type", "register", "");
  5117. return;
  5118. }
  5119. }
  5120. // more information about register types see
  5121. // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
  5122. const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
  5123. switch (std::tolower(desc[0])) {
  5124. case 'c':
  5125. // c register is the register slot in the global const buffer
  5126. // each slot is a vector of 4 32 bit components
  5127. qualifier.layoutOffset = regNumber * 4 * 4;
  5128. break;
  5129. // const buffer register slot
  5130. case 'b':
  5131. // textrues and structured buffers
  5132. case 't':
  5133. // samplers
  5134. case 's':
  5135. // uav resources
  5136. case 'u':
  5137. // if nothing else has set the binding, do so now
  5138. // (other mechanisms override this one)
  5139. if (!qualifier.hasBinding())
  5140. qualifier.layoutBinding = regNumber + subComponent;
  5141. // This handles per-register layout sets numbers. For the global mode which sets
  5142. // every symbol to the same value, see setLinkageLayoutSets().
  5143. if ((resourceInfo.size() % 3) == 0) {
  5144. // Apply per-symbol resource set and binding.
  5145. for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
  5146. if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
  5147. qualifier.layoutSet = atoi(it[1].c_str());
  5148. qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
  5149. break;
  5150. }
  5151. }
  5152. }
  5153. break;
  5154. default:
  5155. warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
  5156. break;
  5157. }
  5158. // space
  5159. unsigned int setNumber;
  5160. const auto crackSpace = [&]() -> bool {
  5161. const int spaceLen = 5;
  5162. if (spaceDesc->size() < spaceLen + 1)
  5163. return false;
  5164. if (spaceDesc->compare(0, spaceLen, "space") != 0)
  5165. return false;
  5166. if (! isdigit((*spaceDesc)[spaceLen]))
  5167. return false;
  5168. setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
  5169. return true;
  5170. };
  5171. // if nothing else has set the set, do so now
  5172. // (other mechanisms override this one)
  5173. if (spaceDesc && !qualifier.hasSet()) {
  5174. if (! crackSpace()) {
  5175. error(loc, "expected spaceN", "register", "");
  5176. return;
  5177. }
  5178. qualifier.layoutSet = setNumber;
  5179. }
  5180. }
  5181. // Convert to a scalar boolean, or if not allowed by HLSL semantics,
  5182. // report an error and return nullptr.
  5183. TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
  5184. bool mustBeScalar)
  5185. {
  5186. if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
  5187. error(loc, "requires a scalar", "conditional expression", "");
  5188. return nullptr;
  5189. }
  5190. return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
  5191. condition);
  5192. }
  5193. //
  5194. // Same error message for all places assignments don't work.
  5195. //
  5196. void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5197. {
  5198. error(loc, "", op, "cannot convert from '%s' to '%s'",
  5199. right.c_str(), left.c_str());
  5200. }
  5201. //
  5202. // Same error message for all places unary operations don't work.
  5203. //
  5204. void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  5205. {
  5206. error(loc, " wrong operand type", op,
  5207. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  5208. op, operand.c_str());
  5209. }
  5210. //
  5211. // Same error message for all binary operations don't work.
  5212. //
  5213. void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5214. {
  5215. error(loc, " wrong operand types:", op,
  5216. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  5217. "a right operand of type '%s' (or there is no acceptable conversion)",
  5218. op, left.c_str(), right.c_str());
  5219. }
  5220. //
  5221. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  5222. // it was not found as a variable in the symbol table. If so, give the error
  5223. // message and insert a dummy variable in the symbol table to prevent future errors.
  5224. //
  5225. void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
  5226. {
  5227. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  5228. if (! symbol)
  5229. return;
  5230. if (symbol->getType().getBasicType() == EbtVoid) {
  5231. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
  5232. // Add to symbol table to prevent future error messages on the same name
  5233. if (symbol->getName().size() > 0) {
  5234. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  5235. symbolTable.insert(*fakeVariable);
  5236. // substitute a symbol node for this new variable
  5237. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  5238. }
  5239. }
  5240. }
  5241. //
  5242. // Both test, and if necessary spit out an error, to see if the node is really
  5243. // a constant.
  5244. //
  5245. void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  5246. {
  5247. if (node->getQualifier().storage != EvqConst)
  5248. error(node->getLoc(), "constant expression required", token, "");
  5249. }
  5250. //
  5251. // Both test, and if necessary spit out an error, to see if the node is really
  5252. // an integer.
  5253. //
  5254. void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
  5255. {
  5256. if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
  5257. return;
  5258. error(node->getLoc(), "scalar integer expression required", token, "");
  5259. }
  5260. //
  5261. // Both test, and if necessary spit out an error, to see if we are currently
  5262. // globally scoped.
  5263. //
  5264. void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  5265. {
  5266. if (! symbolTable.atGlobalLevel())
  5267. error(loc, "not allowed in nested scope", token, "");
  5268. }
  5269. bool HlslParseContext::builtInName(const TString& /*identifier*/)
  5270. {
  5271. return false;
  5272. }
  5273. //
  5274. // Make sure there is enough data and not too many arguments provided to the
  5275. // constructor to build something of the type of the constructor. Also returns
  5276. // the type of the constructor.
  5277. //
  5278. // Returns true if there was an error in construction.
  5279. //
  5280. bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
  5281. TOperator op, TType& type)
  5282. {
  5283. type.shallowCopy(function.getType());
  5284. bool constructingMatrix = false;
  5285. switch (op) {
  5286. case EOpConstructTextureSampler:
  5287. error(loc, "unhandled texture constructor", "constructor", "");
  5288. return true;
  5289. case EOpConstructMat2x2:
  5290. case EOpConstructMat2x3:
  5291. case EOpConstructMat2x4:
  5292. case EOpConstructMat3x2:
  5293. case EOpConstructMat3x3:
  5294. case EOpConstructMat3x4:
  5295. case EOpConstructMat4x2:
  5296. case EOpConstructMat4x3:
  5297. case EOpConstructMat4x4:
  5298. case EOpConstructDMat2x2:
  5299. case EOpConstructDMat2x3:
  5300. case EOpConstructDMat2x4:
  5301. case EOpConstructDMat3x2:
  5302. case EOpConstructDMat3x3:
  5303. case EOpConstructDMat3x4:
  5304. case EOpConstructDMat4x2:
  5305. case EOpConstructDMat4x3:
  5306. case EOpConstructDMat4x4:
  5307. case EOpConstructIMat2x2:
  5308. case EOpConstructIMat2x3:
  5309. case EOpConstructIMat2x4:
  5310. case EOpConstructIMat3x2:
  5311. case EOpConstructIMat3x3:
  5312. case EOpConstructIMat3x4:
  5313. case EOpConstructIMat4x2:
  5314. case EOpConstructIMat4x3:
  5315. case EOpConstructIMat4x4:
  5316. case EOpConstructUMat2x2:
  5317. case EOpConstructUMat2x3:
  5318. case EOpConstructUMat2x4:
  5319. case EOpConstructUMat3x2:
  5320. case EOpConstructUMat3x3:
  5321. case EOpConstructUMat3x4:
  5322. case EOpConstructUMat4x2:
  5323. case EOpConstructUMat4x3:
  5324. case EOpConstructUMat4x4:
  5325. case EOpConstructBMat2x2:
  5326. case EOpConstructBMat2x3:
  5327. case EOpConstructBMat2x4:
  5328. case EOpConstructBMat3x2:
  5329. case EOpConstructBMat3x3:
  5330. case EOpConstructBMat3x4:
  5331. case EOpConstructBMat4x2:
  5332. case EOpConstructBMat4x3:
  5333. case EOpConstructBMat4x4:
  5334. constructingMatrix = true;
  5335. break;
  5336. default:
  5337. break;
  5338. }
  5339. //
  5340. // Walk the arguments for first-pass checks and collection of information.
  5341. //
  5342. int size = 0;
  5343. bool constType = true;
  5344. bool full = false;
  5345. bool overFull = false;
  5346. bool matrixInMatrix = false;
  5347. bool arrayArg = false;
  5348. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  5349. if (function[arg].type->isArray()) {
  5350. if (function[arg].type->isUnsizedArray()) {
  5351. // Can't construct from an unsized array.
  5352. error(loc, "array argument must be sized", "constructor", "");
  5353. return true;
  5354. }
  5355. arrayArg = true;
  5356. }
  5357. if (constructingMatrix && function[arg].type->isMatrix())
  5358. matrixInMatrix = true;
  5359. // 'full' will go to true when enough args have been seen. If we loop
  5360. // again, there is an extra argument.
  5361. if (full) {
  5362. // For vectors and matrices, it's okay to have too many components
  5363. // available, but not okay to have unused arguments.
  5364. overFull = true;
  5365. }
  5366. size += function[arg].type->computeNumComponents();
  5367. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  5368. full = true;
  5369. if (function[arg].type->getQualifier().storage != EvqConst)
  5370. constType = false;
  5371. }
  5372. if (constType)
  5373. type.getQualifier().storage = EvqConst;
  5374. if (type.isArray()) {
  5375. if (function.getParamCount() == 0) {
  5376. error(loc, "array constructor must have at least one argument", "constructor", "");
  5377. return true;
  5378. }
  5379. if (type.isUnsizedArray()) {
  5380. // auto adapt the constructor type to the number of arguments
  5381. type.changeOuterArraySize(function.getParamCount());
  5382. } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
  5383. error(loc, "array constructor needs one argument per array element", "constructor", "");
  5384. return true;
  5385. }
  5386. if (type.isArrayOfArrays()) {
  5387. // Types have to match, but we're still making the type.
  5388. // Finish making the type, and the comparison is done later
  5389. // when checking for conversion.
  5390. TArraySizes& arraySizes = *type.getArraySizes();
  5391. // At least the dimensionalities have to match.
  5392. if (! function[0].type->isArray() ||
  5393. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  5394. error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
  5395. return true;
  5396. }
  5397. if (arraySizes.isInnerUnsized()) {
  5398. // "Arrays of arrays ..., and the size for any dimension is optional"
  5399. // That means we need to adopt (from the first argument) the other array sizes into the type.
  5400. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  5401. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  5402. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  5403. }
  5404. }
  5405. }
  5406. }
  5407. }
  5408. // Some array -> array type casts are okay
  5409. if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
  5410. !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
  5411. type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
  5412. return false;
  5413. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  5414. error(loc, "constructing non-array constituent from array argument", "constructor", "");
  5415. return true;
  5416. }
  5417. if (matrixInMatrix && ! type.isArray()) {
  5418. return false;
  5419. }
  5420. if (overFull) {
  5421. error(loc, "too many arguments", "constructor", "");
  5422. return true;
  5423. }
  5424. if (op == EOpConstructStruct && ! type.isArray()) {
  5425. if (isScalarConstructor(node))
  5426. return false;
  5427. // Self-type construction: e.g, we can construct a struct from a single identically typed object.
  5428. if (function.getParamCount() == 1 && type == *function[0].type)
  5429. return false;
  5430. if ((int)type.getStruct()->size() != function.getParamCount()) {
  5431. error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
  5432. return true;
  5433. }
  5434. }
  5435. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  5436. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  5437. error(loc, "not enough data provided for construction", "constructor", "");
  5438. return true;
  5439. }
  5440. return false;
  5441. }
  5442. // See if 'node', in the context of constructing aggregates, is a scalar argument
  5443. // to a constructor.
  5444. //
  5445. bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
  5446. {
  5447. // Obviously, it must be a scalar, but an aggregate node might not be fully
  5448. // completed yet: holding a sequence of initializers under an aggregate
  5449. // would not yet be typed, so don't check it's type. This corresponds to
  5450. // the aggregate operator also not being set yet. (An aggregate operation
  5451. // that legitimately yields a scalar will have a getOp() of that operator,
  5452. // not EOpNull.)
  5453. return node->getAsTyped() != nullptr &&
  5454. node->getAsTyped()->isScalar() &&
  5455. (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
  5456. }
  5457. // Checks to see if a void variable has been declared and raise an error message for such a case
  5458. //
  5459. // returns true in case of an error
  5460. //
  5461. bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  5462. {
  5463. if (basicType == EbtVoid) {
  5464. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  5465. return true;
  5466. }
  5467. return false;
  5468. }
  5469. //
  5470. // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  5471. //
  5472. void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
  5473. {
  5474. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  5475. switch (qualifier.storage) {
  5476. case EvqIn:
  5477. qualifier.storage = EvqVaryingIn;
  5478. break;
  5479. case EvqOut:
  5480. qualifier.storage = EvqVaryingOut;
  5481. break;
  5482. default:
  5483. break;
  5484. }
  5485. }
  5486. //
  5487. // Merge characteristics of the 'src' qualifier into the 'dst'.
  5488. // If there is duplication, issue error messages, unless 'force'
  5489. // is specified, which means to just override default settings.
  5490. //
  5491. // Also, when force is false, it will be assumed that 'src' follows
  5492. // 'dst', for the purpose of error checking order for versions
  5493. // that require specific orderings of qualifiers.
  5494. //
  5495. void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
  5496. {
  5497. // Storage qualification
  5498. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  5499. dst.storage = src.storage;
  5500. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  5501. (dst.storage == EvqOut && src.storage == EvqIn))
  5502. dst.storage = EvqInOut;
  5503. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  5504. (dst.storage == EvqConst && src.storage == EvqIn))
  5505. dst.storage = EvqConstReadOnly;
  5506. // Layout qualifiers
  5507. mergeObjectLayoutQualifiers(dst, src, false);
  5508. // individual qualifiers
  5509. bool repeated = false;
  5510. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  5511. MERGE_SINGLETON(invariant);
  5512. MERGE_SINGLETON(noContraction);
  5513. MERGE_SINGLETON(centroid);
  5514. MERGE_SINGLETON(smooth);
  5515. MERGE_SINGLETON(flat);
  5516. MERGE_SINGLETON(nopersp);
  5517. MERGE_SINGLETON(patch);
  5518. MERGE_SINGLETON(sample);
  5519. MERGE_SINGLETON(coherent);
  5520. MERGE_SINGLETON(volatil);
  5521. MERGE_SINGLETON(restrict);
  5522. MERGE_SINGLETON(readonly);
  5523. MERGE_SINGLETON(writeonly);
  5524. MERGE_SINGLETON(specConstant);
  5525. MERGE_SINGLETON(nonUniform);
  5526. }
  5527. // used to flatten the sampler type space into a single dimension
  5528. // correlates with the declaration of defaultSamplerPrecision[]
  5529. int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
  5530. {
  5531. int arrayIndex = sampler.arrayed ? 1 : 0;
  5532. int shadowIndex = sampler.shadow ? 1 : 0;
  5533. int externalIndex = sampler.external ? 1 : 0;
  5534. return EsdNumDims *
  5535. (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
  5536. }
  5537. //
  5538. // Do size checking for an array type's size.
  5539. //
  5540. void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
  5541. {
  5542. bool isConst = false;
  5543. sizePair.size = 1;
  5544. sizePair.node = nullptr;
  5545. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  5546. if (constant) {
  5547. // handle true (non-specialization) constant
  5548. sizePair.size = constant->getConstArray()[0].getIConst();
  5549. isConst = true;
  5550. } else {
  5551. // see if it's a specialization constant instead
  5552. if (expr->getQualifier().isSpecConstant()) {
  5553. isConst = true;
  5554. sizePair.node = expr;
  5555. TIntermSymbol* symbol = expr->getAsSymbolNode();
  5556. if (symbol && symbol->getConstArray().size() > 0)
  5557. sizePair.size = symbol->getConstArray()[0].getIConst();
  5558. }
  5559. }
  5560. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  5561. error(loc, "array size must be a constant integer expression", "", "");
  5562. return;
  5563. }
  5564. if (sizePair.size <= 0) {
  5565. error(loc, "array size must be a positive integer", "", "");
  5566. return;
  5567. }
  5568. }
  5569. //
  5570. // Require array to be completely sized
  5571. //
  5572. void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  5573. {
  5574. if (arraySizes.hasUnsized())
  5575. error(loc, "array size required", "", "");
  5576. }
  5577. void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  5578. {
  5579. const TTypeList& structure = *type.getStruct();
  5580. for (int m = 0; m < (int)structure.size(); ++m) {
  5581. const TType& member = *structure[m].type;
  5582. if (member.isArray())
  5583. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  5584. }
  5585. }
  5586. //
  5587. // Do all the semantic checking for declaring or redeclaring an array, with and
  5588. // without a size, and make the right changes to the symbol table.
  5589. //
  5590. void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  5591. TSymbol*& symbol, bool track)
  5592. {
  5593. if (symbol == nullptr) {
  5594. bool currentScope;
  5595. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  5596. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  5597. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  5598. return;
  5599. }
  5600. if (symbol == nullptr || ! currentScope) {
  5601. //
  5602. // Successfully process a new definition.
  5603. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  5604. //
  5605. symbol = new TVariable(&identifier, type);
  5606. symbolTable.insert(*symbol);
  5607. if (track && symbolTable.atGlobalLevel())
  5608. trackLinkage(*symbol);
  5609. return;
  5610. }
  5611. if (symbol->getAsAnonMember()) {
  5612. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  5613. symbol = nullptr;
  5614. return;
  5615. }
  5616. }
  5617. //
  5618. // Process a redeclaration.
  5619. //
  5620. if (symbol == nullptr) {
  5621. error(loc, "array variable name expected", identifier.c_str(), "");
  5622. return;
  5623. }
  5624. // redeclareBuiltinVariable() should have already done the copyUp()
  5625. TType& existingType = symbol->getWritableType();
  5626. if (existingType.isSizedArray()) {
  5627. // be more lenient for input arrays to geometry shaders and tessellation control outputs,
  5628. // where the redeclaration is the same size
  5629. return;
  5630. }
  5631. existingType.updateArraySizes(type);
  5632. }
  5633. //
  5634. // Enforce non-initializer type/qualifier rules.
  5635. //
  5636. void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
  5637. TIntermTyped*& initializer)
  5638. {
  5639. //
  5640. // Make the qualifier make sense, given that there is an initializer.
  5641. //
  5642. if (initializer == nullptr) {
  5643. if (type.getQualifier().storage == EvqConst ||
  5644. type.getQualifier().storage == EvqConstReadOnly) {
  5645. initializer = intermediate.makeAggregate(loc);
  5646. warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
  5647. }
  5648. }
  5649. }
  5650. //
  5651. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  5652. // copy the symbol table's read-only built-in variable to the current
  5653. // global level, where it can be modified based on the passed in type.
  5654. //
  5655. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  5656. // needs to occur for it, not necessarily an error.
  5657. //
  5658. // Returns a redeclared and type-modified variable if a redeclared occurred.
  5659. //
  5660. TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
  5661. const TQualifier& /*qualifier*/,
  5662. const TShaderQualifiers& /*publicType*/)
  5663. {
  5664. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  5665. return nullptr;
  5666. return nullptr;
  5667. }
  5668. //
  5669. // Generate index to the array element in a structure buffer (SSBO)
  5670. //
  5671. TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
  5672. {
  5673. // Bail out if not a struct buffer
  5674. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  5675. return nullptr;
  5676. // Runtime sized array is always the last element.
  5677. const TTypeList* bufferStruct = buffer->getType().getStruct();
  5678. TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
  5679. TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
  5680. argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
  5681. return argArray;
  5682. }
  5683. //
  5684. // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
  5685. // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
  5686. //
  5687. TType* HlslParseContext::getStructBufferContentType(const TType& type) const
  5688. {
  5689. if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
  5690. return nullptr;
  5691. const int memberCount = (int)type.getStruct()->size();
  5692. assert(memberCount > 0);
  5693. TType* contentType = (*type.getStruct())[memberCount-1].type;
  5694. return contentType->isUnsizedArray() ? contentType : nullptr;
  5695. }
  5696. //
  5697. // If an existing struct buffer has a sharable type, then share it.
  5698. //
  5699. void HlslParseContext::shareStructBufferType(TType& type)
  5700. {
  5701. // PackOffset must be equivalent to share types on a per-member basis.
  5702. // Note: cannot use auto type due to recursion. Thus, this is a std::function.
  5703. const std::function<bool(TType& lhs, TType& rhs)>
  5704. compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
  5705. if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
  5706. return false;
  5707. if (lhs.isStruct() != rhs.isStruct())
  5708. return false;
  5709. if (lhs.isStruct() && rhs.isStruct()) {
  5710. if (lhs.getStruct()->size() != rhs.getStruct()->size())
  5711. return false;
  5712. for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
  5713. if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
  5714. return false;
  5715. }
  5716. return true;
  5717. };
  5718. // We need to compare certain qualifiers in addition to the type.
  5719. const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
  5720. if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
  5721. return false;
  5722. // If both are structures, recursively look for packOffset equality
  5723. // as well as type equality.
  5724. return compareQualifiers(lhs, rhs) && lhs == rhs;
  5725. };
  5726. // This is an exhaustive O(N) search, but real world shaders have
  5727. // only a small number of these.
  5728. for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
  5729. // If the deep structure matches, modulo qualifiers, use it
  5730. if (typeEqual(*structBufferTypes[idx], type)) {
  5731. type.shallowCopy(*structBufferTypes[idx]);
  5732. return;
  5733. }
  5734. }
  5735. // Otherwise, remember it:
  5736. TType* typeCopy = new TType;
  5737. typeCopy->shallowCopy(type);
  5738. structBufferTypes.push_back(typeCopy);
  5739. }
  5740. void HlslParseContext::paramFix(TType& type)
  5741. {
  5742. switch (type.getQualifier().storage) {
  5743. case EvqConst:
  5744. type.getQualifier().storage = EvqConstReadOnly;
  5745. break;
  5746. case EvqGlobal:
  5747. case EvqUniform:
  5748. case EvqTemporary:
  5749. type.getQualifier().storage = EvqIn;
  5750. break;
  5751. case EvqBuffer:
  5752. {
  5753. // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
  5754. correctUniform(type.getQualifier());
  5755. TQualifier bufferQualifier = globalBufferDefaults;
  5756. mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
  5757. bufferQualifier.storage = type.getQualifier().storage;
  5758. bufferQualifier.readonly = type.getQualifier().readonly;
  5759. bufferQualifier.coherent = type.getQualifier().coherent;
  5760. bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
  5761. type.getQualifier() = bufferQualifier;
  5762. break;
  5763. }
  5764. default:
  5765. break;
  5766. }
  5767. }
  5768. void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  5769. {
  5770. if (type.containsSpecializationSize())
  5771. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  5772. }
  5773. //
  5774. // Layout qualifier stuff.
  5775. //
  5776. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  5777. // This is before we know any type information for error checking.
  5778. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
  5779. {
  5780. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5781. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  5782. qualifier.layoutMatrix = ElmRowMajor;
  5783. return;
  5784. }
  5785. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  5786. qualifier.layoutMatrix = ElmColumnMajor;
  5787. return;
  5788. }
  5789. if (id == "push_constant") {
  5790. requireVulkan(loc, "push_constant");
  5791. qualifier.layoutPushConstant = true;
  5792. return;
  5793. }
  5794. if (language == EShLangGeometry || language == EShLangTessEvaluation) {
  5795. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5796. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5797. warn(loc, "ignored", id.c_str(), "");
  5798. return;
  5799. }
  5800. if (language == EShLangGeometry) {
  5801. if (id == TQualifier::getGeometryString(ElgPoints)) {
  5802. // publicType.shaderQualifiers.geometry = ElgPoints;
  5803. warn(loc, "ignored", id.c_str(), "");
  5804. return;
  5805. }
  5806. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  5807. // publicType.shaderQualifiers.geometry = ElgLineStrip;
  5808. warn(loc, "ignored", id.c_str(), "");
  5809. return;
  5810. }
  5811. if (id == TQualifier::getGeometryString(ElgLines)) {
  5812. // publicType.shaderQualifiers.geometry = ElgLines;
  5813. warn(loc, "ignored", id.c_str(), "");
  5814. return;
  5815. }
  5816. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  5817. // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  5818. warn(loc, "ignored", id.c_str(), "");
  5819. return;
  5820. }
  5821. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  5822. // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  5823. warn(loc, "ignored", id.c_str(), "");
  5824. return;
  5825. }
  5826. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  5827. // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  5828. warn(loc, "ignored", id.c_str(), "");
  5829. return;
  5830. }
  5831. } else {
  5832. assert(language == EShLangTessEvaluation);
  5833. // input primitive
  5834. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5835. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5836. warn(loc, "ignored", id.c_str(), "");
  5837. return;
  5838. }
  5839. if (id == TQualifier::getGeometryString(ElgQuads)) {
  5840. // publicType.shaderQualifiers.geometry = ElgQuads;
  5841. warn(loc, "ignored", id.c_str(), "");
  5842. return;
  5843. }
  5844. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  5845. // publicType.shaderQualifiers.geometry = ElgIsolines;
  5846. warn(loc, "ignored", id.c_str(), "");
  5847. return;
  5848. }
  5849. // vertex spacing
  5850. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  5851. // publicType.shaderQualifiers.spacing = EvsEqual;
  5852. warn(loc, "ignored", id.c_str(), "");
  5853. return;
  5854. }
  5855. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  5856. // publicType.shaderQualifiers.spacing = EvsFractionalEven;
  5857. warn(loc, "ignored", id.c_str(), "");
  5858. return;
  5859. }
  5860. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  5861. // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  5862. warn(loc, "ignored", id.c_str(), "");
  5863. return;
  5864. }
  5865. // triangle order
  5866. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  5867. // publicType.shaderQualifiers.order = EvoCw;
  5868. warn(loc, "ignored", id.c_str(), "");
  5869. return;
  5870. }
  5871. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  5872. // publicType.shaderQualifiers.order = EvoCcw;
  5873. warn(loc, "ignored", id.c_str(), "");
  5874. return;
  5875. }
  5876. // point mode
  5877. if (id == "point_mode") {
  5878. // publicType.shaderQualifiers.pointMode = true;
  5879. warn(loc, "ignored", id.c_str(), "");
  5880. return;
  5881. }
  5882. }
  5883. }
  5884. if (language == EShLangFragment) {
  5885. if (id == "origin_upper_left") {
  5886. // publicType.shaderQualifiers.originUpperLeft = true;
  5887. warn(loc, "ignored", id.c_str(), "");
  5888. return;
  5889. }
  5890. if (id == "pixel_center_integer") {
  5891. // publicType.shaderQualifiers.pixelCenterInteger = true;
  5892. warn(loc, "ignored", id.c_str(), "");
  5893. return;
  5894. }
  5895. if (id == "early_fragment_tests") {
  5896. // publicType.shaderQualifiers.earlyFragmentTests = true;
  5897. warn(loc, "ignored", id.c_str(), "");
  5898. return;
  5899. }
  5900. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
  5901. if (id == TQualifier::getLayoutDepthString(depth)) {
  5902. // publicType.shaderQualifiers.layoutDepth = depth;
  5903. warn(loc, "ignored", id.c_str(), "");
  5904. return;
  5905. }
  5906. }
  5907. if (id.compare(0, 13, "blend_support") == 0) {
  5908. bool found = false;
  5909. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  5910. if (id == TQualifier::getBlendEquationString(be)) {
  5911. requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
  5912. intermediate.addBlendEquation(be);
  5913. // publicType.shaderQualifiers.blendEquation = true;
  5914. warn(loc, "ignored", id.c_str(), "");
  5915. found = true;
  5916. break;
  5917. }
  5918. }
  5919. if (! found)
  5920. error(loc, "unknown blend equation", "blend_support", "");
  5921. return;
  5922. }
  5923. }
  5924. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  5925. }
  5926. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  5927. // This is before we know any type information for error checking.
  5928. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
  5929. const TIntermTyped* node)
  5930. {
  5931. const char* feature = "layout-id value";
  5932. // const char* nonLiteralFeature = "non-literal layout-id value";
  5933. integerCheck(node, feature);
  5934. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  5935. int value = 0;
  5936. if (constUnion) {
  5937. value = constUnion->getConstArray()[0].getIConst();
  5938. }
  5939. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5940. if (id == "offset") {
  5941. qualifier.layoutOffset = value;
  5942. return;
  5943. } else if (id == "align") {
  5944. // "The specified alignment must be a power of 2, or a compile-time error results."
  5945. if (! IsPow2(value))
  5946. error(loc, "must be a power of 2", "align", "");
  5947. else
  5948. qualifier.layoutAlign = value;
  5949. return;
  5950. } else if (id == "location") {
  5951. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  5952. error(loc, "location is too large", id.c_str(), "");
  5953. else
  5954. qualifier.layoutLocation = value;
  5955. return;
  5956. } else if (id == "set") {
  5957. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  5958. error(loc, "set is too large", id.c_str(), "");
  5959. else
  5960. qualifier.layoutSet = value;
  5961. return;
  5962. } else if (id == "binding") {
  5963. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  5964. error(loc, "binding is too large", id.c_str(), "");
  5965. else
  5966. qualifier.layoutBinding = value;
  5967. return;
  5968. } else if (id == "component") {
  5969. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  5970. error(loc, "component is too large", id.c_str(), "");
  5971. else
  5972. qualifier.layoutComponent = value;
  5973. return;
  5974. } else if (id.compare(0, 4, "xfb_") == 0) {
  5975. // "Any shader making any static use (after preprocessing) of any of these
  5976. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  5977. // capturing mode and hence responsible for describing the transform feedback
  5978. // setup."
  5979. intermediate.setXfbMode();
  5980. if (id == "xfb_buffer") {
  5981. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  5982. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  5983. if (value >= resources.maxTransformFeedbackBuffers)
  5984. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
  5985. resources.maxTransformFeedbackBuffers);
  5986. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  5987. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
  5988. else
  5989. qualifier.layoutXfbBuffer = value;
  5990. return;
  5991. } else if (id == "xfb_offset") {
  5992. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  5993. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
  5994. else
  5995. qualifier.layoutXfbOffset = value;
  5996. return;
  5997. } else if (id == "xfb_stride") {
  5998. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  5999. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  6000. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
  6001. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  6002. resources.maxTransformFeedbackInterleavedComponents);
  6003. else if (value >= (int)TQualifier::layoutXfbStrideEnd)
  6004. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
  6005. if (value < (int)TQualifier::layoutXfbStrideEnd)
  6006. qualifier.layoutXfbStride = value;
  6007. return;
  6008. }
  6009. }
  6010. if (id == "input_attachment_index") {
  6011. requireVulkan(loc, "input_attachment_index");
  6012. if (value >= (int)TQualifier::layoutAttachmentEnd)
  6013. error(loc, "attachment index is too large", id.c_str(), "");
  6014. else
  6015. qualifier.layoutAttachment = value;
  6016. return;
  6017. }
  6018. if (id == "constant_id") {
  6019. setSpecConstantId(loc, qualifier, value);
  6020. return;
  6021. }
  6022. switch (language) {
  6023. case EShLangVertex:
  6024. break;
  6025. case EShLangTessControl:
  6026. if (id == "vertices") {
  6027. if (value == 0)
  6028. error(loc, "must be greater than 0", "vertices", "");
  6029. else
  6030. // publicType.shaderQualifiers.vertices = value;
  6031. warn(loc, "ignored", id.c_str(), "");
  6032. return;
  6033. }
  6034. break;
  6035. case EShLangTessEvaluation:
  6036. break;
  6037. case EShLangGeometry:
  6038. if (id == "invocations") {
  6039. if (value == 0)
  6040. error(loc, "must be at least 1", "invocations", "");
  6041. else
  6042. // publicType.shaderQualifiers.invocations = value;
  6043. warn(loc, "ignored", id.c_str(), "");
  6044. return;
  6045. }
  6046. if (id == "max_vertices") {
  6047. // publicType.shaderQualifiers.vertices = value;
  6048. warn(loc, "ignored", id.c_str(), "");
  6049. if (value > resources.maxGeometryOutputVertices)
  6050. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  6051. return;
  6052. }
  6053. if (id == "stream") {
  6054. qualifier.layoutStream = value;
  6055. return;
  6056. }
  6057. break;
  6058. case EShLangFragment:
  6059. if (id == "index") {
  6060. qualifier.layoutIndex = value;
  6061. return;
  6062. }
  6063. break;
  6064. case EShLangCompute:
  6065. if (id.compare(0, 11, "local_size_") == 0) {
  6066. if (id == "local_size_x") {
  6067. // publicType.shaderQualifiers.localSize[0] = value;
  6068. warn(loc, "ignored", id.c_str(), "");
  6069. return;
  6070. }
  6071. if (id == "local_size_y") {
  6072. // publicType.shaderQualifiers.localSize[1] = value;
  6073. warn(loc, "ignored", id.c_str(), "");
  6074. return;
  6075. }
  6076. if (id == "local_size_z") {
  6077. // publicType.shaderQualifiers.localSize[2] = value;
  6078. warn(loc, "ignored", id.c_str(), "");
  6079. return;
  6080. }
  6081. if (spvVersion.spv != 0) {
  6082. if (id == "local_size_x_id") {
  6083. // publicType.shaderQualifiers.localSizeSpecId[0] = value;
  6084. warn(loc, "ignored", id.c_str(), "");
  6085. return;
  6086. }
  6087. if (id == "local_size_y_id") {
  6088. // publicType.shaderQualifiers.localSizeSpecId[1] = value;
  6089. warn(loc, "ignored", id.c_str(), "");
  6090. return;
  6091. }
  6092. if (id == "local_size_z_id") {
  6093. // publicType.shaderQualifiers.localSizeSpecId[2] = value;
  6094. warn(loc, "ignored", id.c_str(), "");
  6095. return;
  6096. }
  6097. }
  6098. }
  6099. break;
  6100. default:
  6101. break;
  6102. }
  6103. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  6104. }
  6105. void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
  6106. {
  6107. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  6108. error(loc, "specialization-constant id is too large", "constant_id", "");
  6109. } else {
  6110. qualifier.layoutSpecConstantId = value;
  6111. qualifier.specConstant = true;
  6112. if (! intermediate.addUsedConstantId(value))
  6113. error(loc, "specialization-constant id already used", "constant_id", "");
  6114. }
  6115. return;
  6116. }
  6117. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  6118. //
  6119. // "More than one layout qualifier may appear in a single declaration.
  6120. // Additionally, the same layout-qualifier-name can occur multiple times
  6121. // within a layout qualifier or across multiple layout qualifiers in the
  6122. // same declaration. When the same layout-qualifier-name occurs
  6123. // multiple times, in a single declaration, the last occurrence overrides
  6124. // the former occurrence(s). Further, if such a layout-qualifier-name
  6125. // will effect subsequent declarations or other observable behavior, it
  6126. // is only the last occurrence that will have any effect, behaving as if
  6127. // the earlier occurrence(s) within the declaration are not present.
  6128. // This is also true for overriding layout-qualifier-names, where one
  6129. // overrides the other (e.g., row_major vs. column_major); only the last
  6130. // occurrence has any effect."
  6131. //
  6132. void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  6133. {
  6134. if (src.hasMatrix())
  6135. dst.layoutMatrix = src.layoutMatrix;
  6136. if (src.hasPacking())
  6137. dst.layoutPacking = src.layoutPacking;
  6138. if (src.hasStream())
  6139. dst.layoutStream = src.layoutStream;
  6140. if (src.hasFormat())
  6141. dst.layoutFormat = src.layoutFormat;
  6142. if (src.hasXfbBuffer())
  6143. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  6144. if (src.hasAlign())
  6145. dst.layoutAlign = src.layoutAlign;
  6146. if (! inheritOnly) {
  6147. if (src.hasLocation())
  6148. dst.layoutLocation = src.layoutLocation;
  6149. if (src.hasComponent())
  6150. dst.layoutComponent = src.layoutComponent;
  6151. if (src.hasIndex())
  6152. dst.layoutIndex = src.layoutIndex;
  6153. if (src.hasOffset())
  6154. dst.layoutOffset = src.layoutOffset;
  6155. if (src.hasSet())
  6156. dst.layoutSet = src.layoutSet;
  6157. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  6158. dst.layoutBinding = src.layoutBinding;
  6159. if (src.hasXfbStride())
  6160. dst.layoutXfbStride = src.layoutXfbStride;
  6161. if (src.hasXfbOffset())
  6162. dst.layoutXfbOffset = src.layoutXfbOffset;
  6163. if (src.hasAttachment())
  6164. dst.layoutAttachment = src.layoutAttachment;
  6165. if (src.hasSpecConstantId())
  6166. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  6167. if (src.layoutPushConstant)
  6168. dst.layoutPushConstant = true;
  6169. }
  6170. }
  6171. //
  6172. // Look up a function name in the symbol table, and make sure it is a function.
  6173. //
  6174. // First, look for an exact match. If there is none, use the generic selector
  6175. // TParseContextBase::selectFunction() to find one, parameterized by the
  6176. // convertible() and better() predicates defined below.
  6177. //
  6178. // Return the function symbol if found, otherwise nullptr.
  6179. //
  6180. const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
  6181. TIntermTyped*& args)
  6182. {
  6183. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6184. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6185. return nullptr;
  6186. }
  6187. // first, look for an exact match
  6188. bool dummyScope;
  6189. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
  6190. if (symbol)
  6191. return symbol->getAsFunction();
  6192. // no exact match, use the generic selector, parameterized by the GLSL rules
  6193. // create list of candidates to send
  6194. TVector<const TFunction*> candidateList;
  6195. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6196. // These built-in ops can accept any type, so we bypass the argument selection
  6197. if (candidateList.size() == 1 && builtIn &&
  6198. (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6199. candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
  6200. candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
  6201. candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
  6202. candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6203. candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
  6204. return candidateList[0];
  6205. }
  6206. bool allowOnlyUpConversions = true;
  6207. // can 'from' convert to 'to'?
  6208. const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
  6209. if (from == to)
  6210. return true;
  6211. // no aggregate conversions
  6212. if (from.isArray() || to.isArray() ||
  6213. from.isStruct() || to.isStruct())
  6214. return false;
  6215. switch (op) {
  6216. case EOpInterlockedAdd:
  6217. case EOpInterlockedAnd:
  6218. case EOpInterlockedCompareExchange:
  6219. case EOpInterlockedCompareStore:
  6220. case EOpInterlockedExchange:
  6221. case EOpInterlockedMax:
  6222. case EOpInterlockedMin:
  6223. case EOpInterlockedOr:
  6224. case EOpInterlockedXor:
  6225. // We do not promote the texture or image type for these ocodes. Normally that would not
  6226. // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
  6227. // stage it's merely e.g, a basic integer type.
  6228. //
  6229. // Instead, we want to promote other arguments, but stay within the same family. In other
  6230. // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
  6231. // but it is allowed to promote its other arguments.
  6232. if (arg == 0)
  6233. return false;
  6234. break;
  6235. case EOpMethodSample:
  6236. case EOpMethodSampleBias:
  6237. case EOpMethodSampleCmp:
  6238. case EOpMethodSampleCmpLevelZero:
  6239. case EOpMethodSampleGrad:
  6240. case EOpMethodSampleLevel:
  6241. case EOpMethodLoad:
  6242. case EOpMethodGetDimensions:
  6243. case EOpMethodGetSamplePosition:
  6244. case EOpMethodGather:
  6245. case EOpMethodCalculateLevelOfDetail:
  6246. case EOpMethodCalculateLevelOfDetailUnclamped:
  6247. case EOpMethodGatherRed:
  6248. case EOpMethodGatherGreen:
  6249. case EOpMethodGatherBlue:
  6250. case EOpMethodGatherAlpha:
  6251. case EOpMethodGatherCmp:
  6252. case EOpMethodGatherCmpRed:
  6253. case EOpMethodGatherCmpGreen:
  6254. case EOpMethodGatherCmpBlue:
  6255. case EOpMethodGatherCmpAlpha:
  6256. case EOpMethodAppend:
  6257. case EOpMethodRestartStrip:
  6258. // those are method calls, the object type can not be changed
  6259. // they are equal if the dim and type match (is dim sufficient?)
  6260. if (arg == 0)
  6261. return from.getSampler().type == to.getSampler().type &&
  6262. from.getSampler().arrayed == to.getSampler().arrayed &&
  6263. from.getSampler().shadow == to.getSampler().shadow &&
  6264. from.getSampler().ms == to.getSampler().ms &&
  6265. from.getSampler().dim == to.getSampler().dim;
  6266. break;
  6267. default:
  6268. break;
  6269. }
  6270. // basic types have to be convertible
  6271. if (allowOnlyUpConversions)
  6272. if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
  6273. return false;
  6274. // shapes have to be convertible
  6275. if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
  6276. (from.isScalarOrVec1() && to.isVector()) ||
  6277. (from.isScalarOrVec1() && to.isMatrix()) ||
  6278. (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
  6279. return true;
  6280. // TODO: what are the matrix rules? they go here
  6281. return false;
  6282. };
  6283. // Is 'to2' a better conversion than 'to1'?
  6284. // Ties should not be considered as better.
  6285. // Assumes 'convertible' already said true.
  6286. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6287. // exact match is always better than mismatch
  6288. if (from == to2)
  6289. return from != to1;
  6290. if (from == to1)
  6291. return false;
  6292. // shape changes are always worse
  6293. if (from.isScalar() || from.isVector()) {
  6294. if (from.getVectorSize() == to2.getVectorSize() &&
  6295. from.getVectorSize() != to1.getVectorSize())
  6296. return true;
  6297. if (from.getVectorSize() == to1.getVectorSize() &&
  6298. from.getVectorSize() != to2.getVectorSize())
  6299. return false;
  6300. }
  6301. // Handle sampler betterness: An exact sampler match beats a non-exact match.
  6302. // (If we just looked at basic type, all EbtSamplers would look the same).
  6303. // If any type is not a sampler, just use the linearize function below.
  6304. if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
  6305. // We can ignore the vector size in the comparison.
  6306. TSampler to1Sampler = to1.getSampler();
  6307. TSampler to2Sampler = to2.getSampler();
  6308. to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
  6309. if (from.getSampler() == to2Sampler)
  6310. return from.getSampler() != to1Sampler;
  6311. if (from.getSampler() == to1Sampler)
  6312. return false;
  6313. }
  6314. // Might or might not be changing shape, which means basic type might
  6315. // or might not match, so within that, the question is how big a
  6316. // basic-type conversion is being done.
  6317. //
  6318. // Use a hierarchy of domains, translated to order of magnitude
  6319. // in a linearized view:
  6320. // - floating-point vs. integer
  6321. // - 32 vs. 64 bit (or width in general)
  6322. // - bool vs. non bool
  6323. // - signed vs. not signed
  6324. const auto linearize = [](const TBasicType& basicType) -> int {
  6325. switch (basicType) {
  6326. case EbtBool: return 1;
  6327. case EbtInt: return 10;
  6328. case EbtUint: return 11;
  6329. case EbtInt64: return 20;
  6330. case EbtUint64: return 21;
  6331. case EbtFloat: return 100;
  6332. case EbtDouble: return 110;
  6333. default: return 0;
  6334. }
  6335. };
  6336. return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
  6337. abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
  6338. };
  6339. // for ambiguity reporting
  6340. bool tie = false;
  6341. // send to the generic selector
  6342. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6343. if (bestMatch == nullptr) {
  6344. // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
  6345. // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
  6346. // upconversions possible.
  6347. allowOnlyUpConversions = false;
  6348. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6349. }
  6350. if (bestMatch == nullptr) {
  6351. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6352. return nullptr;
  6353. }
  6354. // For built-ins, we can convert across the arguments. This will happen in several steps:
  6355. // Step 1: If there's an exact match, use it.
  6356. // Step 2a: Otherwise, get the operator from the best match and promote arguments:
  6357. // Step 2b: reconstruct the TFunction based on the new arg types
  6358. // Step 3: Re-select after type promotion is applied, to find proper candidate.
  6359. if (builtIn) {
  6360. // Step 1: If there's an exact match, use it.
  6361. if (call.getMangledName() == bestMatch->getMangledName())
  6362. return bestMatch;
  6363. // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
  6364. // are that kind of operator.
  6365. if (args != nullptr) {
  6366. // The arg list can be a unary node, or an aggregate. We have to handle both.
  6367. // We will use the normal promote() facilities, which require an interm node.
  6368. TIntermOperator* promote = nullptr;
  6369. if (call.getParamCount() == 1) {
  6370. promote = new TIntermUnary(bestMatch->getBuiltInOp());
  6371. promote->getAsUnaryNode()->setOperand(args->getAsTyped());
  6372. } else {
  6373. promote = new TIntermAggregate(bestMatch->getBuiltInOp());
  6374. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6375. }
  6376. if (! intermediate.promote(promote))
  6377. return nullptr;
  6378. // Obtain the promoted arg list.
  6379. if (call.getParamCount() == 1) {
  6380. args = promote->getAsUnaryNode()->getOperand();
  6381. } else {
  6382. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6383. }
  6384. }
  6385. // Step 2b: reconstruct the TFunction based on the new arg types
  6386. TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
  6387. if (args->getAsAggregate()) {
  6388. // Handle aggregates: put all args into the new function call
  6389. for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
  6390. // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
  6391. TParameter param = { 0, new TType, nullptr };
  6392. param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
  6393. convertedCall.addParameter(param);
  6394. }
  6395. } else if (args->getAsUnaryNode()) {
  6396. // Handle unaries: put all args into the new function call
  6397. TParameter param = { 0, new TType, nullptr };
  6398. param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
  6399. convertedCall.addParameter(param);
  6400. } else if (args->getAsTyped()) {
  6401. // Handle bare e.g, floats, not in an aggregate.
  6402. TParameter param = { 0, new TType, nullptr };
  6403. param.type->shallowCopy(args->getAsTyped()->getType());
  6404. convertedCall.addParameter(param);
  6405. } else {
  6406. assert(0); // unknown argument list.
  6407. return nullptr;
  6408. }
  6409. // Step 3: Re-select after type promotion, to find proper candidate
  6410. // send to the generic selector
  6411. bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
  6412. // At this point, there should be no tie.
  6413. }
  6414. if (tie)
  6415. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6416. // Append default parameter values if needed
  6417. if (!tie && bestMatch != nullptr) {
  6418. for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
  6419. handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
  6420. }
  6421. }
  6422. return bestMatch;
  6423. }
  6424. //
  6425. // Do everything necessary to handle a typedef declaration, for a single symbol.
  6426. //
  6427. // 'parseType' is the type part of the declaration (to the left)
  6428. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6429. //
  6430. void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
  6431. {
  6432. TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
  6433. if (! symbolTable.insert(*typeSymbol))
  6434. error(loc, "name already defined", "typedef", identifier.c_str());
  6435. }
  6436. // Do everything necessary to handle a struct declaration, including
  6437. // making IO aliases because HLSL allows mixed IO in a struct that specializes
  6438. // based on the usage (input, output, uniform, none).
  6439. void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
  6440. {
  6441. // If it was named, which means the type can be reused later, add
  6442. // it to the symbol table. (Unless it's a block, in which
  6443. // case the name is not a type.)
  6444. if (type.getBasicType() == EbtBlock || structName.size() == 0)
  6445. return;
  6446. TVariable* userTypeDef = new TVariable(&structName, type, true);
  6447. if (! symbolTable.insert(*userTypeDef)) {
  6448. error(loc, "redefinition", structName.c_str(), "struct");
  6449. return;
  6450. }
  6451. // See if we need IO aliases for the structure typeList
  6452. const auto condAlloc = [](bool pred, TTypeList*& list) {
  6453. if (pred && list == nullptr)
  6454. list = new TTypeList;
  6455. };
  6456. tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
  6457. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6458. condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
  6459. condAlloc( hasInput(member->type->getQualifier()), newLists.input);
  6460. condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
  6461. if (member->type->isStruct()) {
  6462. auto it = ioTypeMap.find(member->type->getStruct());
  6463. if (it != ioTypeMap.end()) {
  6464. condAlloc(it->second.uniform != nullptr, newLists.uniform);
  6465. condAlloc(it->second.input != nullptr, newLists.input);
  6466. condAlloc(it->second.output != nullptr, newLists.output);
  6467. }
  6468. }
  6469. }
  6470. if (newLists.uniform == nullptr &&
  6471. newLists.input == nullptr &&
  6472. newLists.output == nullptr) {
  6473. // Won't do any IO caching, clear up the type and get out now.
  6474. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
  6475. clearUniformInputOutput(member->type->getQualifier());
  6476. return;
  6477. }
  6478. // We have IO involved.
  6479. // Make a pure typeList for the symbol table, and cache side copies of IO versions.
  6480. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6481. const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
  6482. if (s != nullptr) {
  6483. ioMember.type = new TType;
  6484. ioMember.type->shallowCopy(*member->type);
  6485. ioMember.type->setStruct(s);
  6486. }
  6487. };
  6488. const auto newMember = [&](TTypeLoc& m) {
  6489. if (m.type == nullptr) {
  6490. m.type = new TType;
  6491. m.type->shallowCopy(*member->type);
  6492. }
  6493. };
  6494. TTypeLoc newUniformMember = { nullptr, member->loc };
  6495. TTypeLoc newInputMember = { nullptr, member->loc };
  6496. TTypeLoc newOutputMember = { nullptr, member->loc };
  6497. if (member->type->isStruct()) {
  6498. // swap in an IO child if there is one
  6499. auto it = ioTypeMap.find(member->type->getStruct());
  6500. if (it != ioTypeMap.end()) {
  6501. inheritStruct(it->second.uniform, newUniformMember);
  6502. inheritStruct(it->second.input, newInputMember);
  6503. inheritStruct(it->second.output, newOutputMember);
  6504. }
  6505. }
  6506. if (newLists.uniform) {
  6507. newMember(newUniformMember);
  6508. // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
  6509. if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
  6510. newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
  6511. correctUniform(newUniformMember.type->getQualifier());
  6512. newLists.uniform->push_back(newUniformMember);
  6513. }
  6514. if (newLists.input) {
  6515. newMember(newInputMember);
  6516. correctInput(newInputMember.type->getQualifier());
  6517. newLists.input->push_back(newInputMember);
  6518. }
  6519. if (newLists.output) {
  6520. newMember(newOutputMember);
  6521. correctOutput(newOutputMember.type->getQualifier());
  6522. newLists.output->push_back(newOutputMember);
  6523. }
  6524. // make original pure
  6525. clearUniformInputOutput(member->type->getQualifier());
  6526. }
  6527. ioTypeMap[type.getStruct()] = newLists;
  6528. }
  6529. // Lookup a user-type by name.
  6530. // If found, fill in the type and return the defining symbol.
  6531. // If not found, return nullptr.
  6532. TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
  6533. {
  6534. TSymbol* symbol = symbolTable.find(typeName);
  6535. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  6536. type.shallowCopy(symbol->getType());
  6537. return symbol;
  6538. } else
  6539. return nullptr;
  6540. }
  6541. //
  6542. // Do everything necessary to handle a variable (non-block) declaration.
  6543. // Either redeclaring a variable, or making a new one, updating the symbol
  6544. // table, and all error checking.
  6545. //
  6546. // Returns a subtree node that computes an initializer, if needed.
  6547. // Returns nullptr if there is no code to execute for initialization.
  6548. //
  6549. // 'parseType' is the type part of the declaration (to the left)
  6550. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6551. //
  6552. TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
  6553. TIntermTyped* initializer)
  6554. {
  6555. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6556. return nullptr;
  6557. // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
  6558. // This test is implicitly recursive, because initializers propagate constness
  6559. // up the aggregate node tree during creation. E.g, for:
  6560. // { { 1, 2 }, { 3, 4 } }
  6561. // the initializer list is marked EvqConst at the top node, and remains so here. However:
  6562. // { 1, { myvar, 2 }, 3 }
  6563. // is not a const intializer, and still becomes EvqGlobal here.
  6564. const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
  6565. if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
  6566. // Force to global
  6567. type.getQualifier().storage = EvqGlobal;
  6568. }
  6569. // make const and initialization consistent
  6570. fixConstInit(loc, identifier, type, initializer);
  6571. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6572. TSymbol* symbol = nullptr;
  6573. inheritGlobalDefaults(type.getQualifier());
  6574. const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
  6575. // correct IO in the type
  6576. switch (type.getQualifier().storage) {
  6577. case EvqGlobal:
  6578. case EvqTemporary:
  6579. clearUniformInputOutput(type.getQualifier());
  6580. break;
  6581. case EvqUniform:
  6582. case EvqBuffer:
  6583. correctUniform(type.getQualifier());
  6584. if (type.isStruct()) {
  6585. auto it = ioTypeMap.find(type.getStruct());
  6586. if (it != ioTypeMap.end())
  6587. type.setStruct(it->second.uniform);
  6588. }
  6589. break;
  6590. default:
  6591. break;
  6592. }
  6593. // Declare the variable
  6594. if (type.isArray()) {
  6595. // array case
  6596. declareArray(loc, identifier, type, symbol, !flattenVar);
  6597. } else {
  6598. // non-array case
  6599. if (symbol == nullptr)
  6600. symbol = declareNonArray(loc, identifier, type, !flattenVar);
  6601. else if (type != symbol->getType())
  6602. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6603. }
  6604. if (symbol == nullptr)
  6605. return nullptr;
  6606. if (flattenVar)
  6607. flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
  6608. if (initializer == nullptr)
  6609. return nullptr;
  6610. // Deal with initializer
  6611. TVariable* variable = symbol->getAsVariable();
  6612. if (variable == nullptr) {
  6613. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6614. return nullptr;
  6615. }
  6616. return executeInitializer(loc, initializer, variable);
  6617. }
  6618. // Pick up global defaults from the provide global defaults into dst.
  6619. void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6620. {
  6621. if (dst.storage == EvqVaryingOut) {
  6622. if (! dst.hasStream() && language == EShLangGeometry)
  6623. dst.layoutStream = globalOutputDefaults.layoutStream;
  6624. if (! dst.hasXfbBuffer())
  6625. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6626. }
  6627. }
  6628. //
  6629. // Make an internal-only variable whose name is for debug purposes only
  6630. // and won't be searched for. Callers will only use the return value to use
  6631. // the variable, not the name to look it up. It is okay if the name
  6632. // is the same as other names; there won't be any conflict.
  6633. //
  6634. TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
  6635. {
  6636. TString* nameString = NewPoolTString(name);
  6637. TVariable* variable = new TVariable(nameString, type);
  6638. symbolTable.makeInternalVariable(*variable);
  6639. return variable;
  6640. }
  6641. // Make a symbol node holding a new internal temporary variable.
  6642. TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
  6643. const TType& type) const
  6644. {
  6645. TVariable* tmpVar = makeInternalVariable(name, type);
  6646. tmpVar->getWritableType().getQualifier().makeTemporary();
  6647. return intermediate.addSymbol(*tmpVar, loc);
  6648. }
  6649. //
  6650. // Declare a non-array variable, the main point being there is no redeclaration
  6651. // for resizing allowed.
  6652. //
  6653. // Return the successfully declared variable.
  6654. //
  6655. TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  6656. bool track)
  6657. {
  6658. // make a new variable
  6659. TVariable* variable = new TVariable(&identifier, type);
  6660. // add variable to symbol table
  6661. if (symbolTable.insert(*variable)) {
  6662. if (track && symbolTable.atGlobalLevel())
  6663. trackLinkage(*variable);
  6664. return variable;
  6665. }
  6666. error(loc, "redefinition", variable->getName().c_str(), "");
  6667. return nullptr;
  6668. }
  6669. //
  6670. // Handle all types of initializers from the grammar.
  6671. //
  6672. // Returning nullptr just means there is no code to execute to handle the
  6673. // initializer, which will, for example, be the case for constant initializers.
  6674. //
  6675. // Returns a subtree that accomplished the initialization.
  6676. //
  6677. TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6678. {
  6679. //
  6680. // Identifier must be of type constant, a global, or a temporary, and
  6681. // starting at version 120, desktop allows uniforms to have initializers.
  6682. //
  6683. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6684. //
  6685. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6686. // constructor-style subtree, allowing the rest of the code to operate
  6687. // identically for both kinds of initializers.
  6688. //
  6689. //
  6690. // Type can't be deduced from the initializer list, so a skeletal type to
  6691. // follow has to be passed in. Constness and specialization-constness
  6692. // should be deduced bottom up, not dictated by the skeletal type.
  6693. //
  6694. TType skeletalType;
  6695. skeletalType.shallowCopy(variable->getType());
  6696. skeletalType.getQualifier().makeTemporary();
  6697. if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
  6698. initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
  6699. if (initializer == nullptr) {
  6700. // error recovery; don't leave const without constant values
  6701. if (qualifier == EvqConst)
  6702. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6703. return nullptr;
  6704. }
  6705. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6706. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6707. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6708. // Inner arrayness can also get set by an initializer
  6709. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6710. initializer->getType().getArraySizes()->getNumDims() ==
  6711. variable->getType().getArraySizes()->getNumDims()) {
  6712. // adopt unsized sizes from the initializer's sizes
  6713. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6714. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6715. variable->getWritableType().getArraySizes()->setDimSize(d,
  6716. initializer->getType().getArraySizes()->getDimSize(d));
  6717. }
  6718. }
  6719. }
  6720. // Uniform and global consts require a constant initializer
  6721. if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
  6722. error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
  6723. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6724. return nullptr;
  6725. }
  6726. // Const variables require a constant initializer
  6727. if (qualifier == EvqConst) {
  6728. if (initializer->getType().getQualifier().storage != EvqConst) {
  6729. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6730. qualifier = EvqConstReadOnly;
  6731. }
  6732. }
  6733. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6734. // Compile-time tagging of the variable with its constant value...
  6735. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6736. if (initializer != nullptr && variable->getType() != initializer->getType())
  6737. initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
  6738. if (initializer == nullptr || !initializer->getAsConstantUnion() ||
  6739. variable->getType() != initializer->getType()) {
  6740. error(loc, "non-matching or non-convertible constant type for const initializer",
  6741. variable->getType().getStorageQualifierString(), "");
  6742. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6743. return nullptr;
  6744. }
  6745. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6746. } else {
  6747. // normal assigning of a value to a variable...
  6748. specializationCheck(loc, initializer->getType(), "initializer");
  6749. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6750. TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
  6751. if (initNode == nullptr)
  6752. assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
  6753. return initNode;
  6754. }
  6755. return nullptr;
  6756. }
  6757. //
  6758. // Reprocess any initializer-list { ... } parts of the initializer.
  6759. // Need to hierarchically assign correct types and implicit
  6760. // conversions. Will do this mimicking the same process used for
  6761. // creating a constructor-style initializer, ensuring we get the
  6762. // same form.
  6763. //
  6764. // Returns a node representing an expression for the initializer list expressed
  6765. // as the correct type.
  6766. //
  6767. // Returns nullptr if there is an error.
  6768. //
  6769. TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
  6770. TIntermTyped* initializer, TIntermTyped* scalarInit)
  6771. {
  6772. // Will operate recursively. Once a subtree is found that is constructor style,
  6773. // everything below it is already good: Only the "top part" of the initializer
  6774. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6775. // see if we have bottomed out in the tree within the initializer-list part
  6776. TIntermAggregate* initList = initializer->getAsAggregate();
  6777. if (initList == nullptr || initList->getOp() != EOpNull) {
  6778. // We don't have a list, but if it's a scalar and the 'type' is a
  6779. // composite, we need to lengthen below to make it useful.
  6780. // Otherwise, this is an already formed object to initialize with.
  6781. if (type.isScalar() || !initializer->getType().isScalar())
  6782. return initializer;
  6783. else
  6784. initList = intermediate.makeAggregate(initializer);
  6785. }
  6786. // Of the initializer-list set of nodes, need to process bottom up,
  6787. // so recurse deep, then process on the way up.
  6788. // Go down the tree here...
  6789. if (type.isArray()) {
  6790. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6791. // Later on, initializer execution code will deal with array size logic.
  6792. TType arrayType;
  6793. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6794. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6795. // edit array sizes to fill in unsized dimensions
  6796. if (type.isUnsizedArray())
  6797. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6798. // set unsized array dimensions that can be derived from the initializer's first element
  6799. if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
  6800. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6801. if (firstInit->getType().isArray() &&
  6802. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6803. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6804. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6805. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6806. }
  6807. }
  6808. }
  6809. // lengthen list to be long enough
  6810. lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
  6811. // recursively process each element
  6812. TType elementType(arrayType, 0); // dereferenced type
  6813. for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
  6814. initList->getSequence()[i] = convertInitializerList(loc, elementType,
  6815. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6816. if (initList->getSequence()[i] == nullptr)
  6817. return nullptr;
  6818. }
  6819. return addConstructor(loc, initList, arrayType);
  6820. } else if (type.isStruct()) {
  6821. // do we have implicit assignments to opaques?
  6822. for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
  6823. if ((*type.getStruct())[i].type->containsOpaque()) {
  6824. error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
  6825. return nullptr;
  6826. }
  6827. }
  6828. // lengthen list to be long enough
  6829. lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
  6830. if (type.getStruct()->size() != initList->getSequence().size()) {
  6831. error(loc, "wrong number of structure members", "initializer list", "");
  6832. return nullptr;
  6833. }
  6834. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6835. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
  6836. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6837. if (initList->getSequence()[i] == nullptr)
  6838. return nullptr;
  6839. }
  6840. } else if (type.isMatrix()) {
  6841. if (type.computeNumComponents() == (int)initList->getSequence().size()) {
  6842. // This means the matrix is initialized component-wise, rather than as
  6843. // a series of rows and columns. We can just use the list directly as
  6844. // a constructor; no further processing needed.
  6845. } else {
  6846. // lengthen list to be long enough
  6847. lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
  6848. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  6849. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
  6850. return nullptr;
  6851. }
  6852. TType vectorType(type, 0); // dereferenced type
  6853. for (int i = 0; i < type.getMatrixCols(); ++i) {
  6854. initList->getSequence()[i] = convertInitializerList(loc, vectorType,
  6855. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6856. if (initList->getSequence()[i] == nullptr)
  6857. return nullptr;
  6858. }
  6859. }
  6860. } else if (type.isVector()) {
  6861. // lengthen list to be long enough
  6862. lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
  6863. // error check; we're at bottom, so work is finished below
  6864. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  6865. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
  6866. type.getCompleteString().c_str());
  6867. return nullptr;
  6868. }
  6869. } else if (type.isScalar()) {
  6870. // lengthen list to be long enough
  6871. lengthenList(loc, initList->getSequence(), 1, scalarInit);
  6872. if ((int)initList->getSequence().size() != 1) {
  6873. error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
  6874. return nullptr;
  6875. }
  6876. } else {
  6877. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
  6878. return nullptr;
  6879. }
  6880. // Now that the subtree is processed, process this node as if the
  6881. // initializer list is a set of arguments to a constructor.
  6882. TIntermTyped* emulatedConstructorArguments;
  6883. if (initList->getSequence().size() == 1)
  6884. emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
  6885. else
  6886. emulatedConstructorArguments = initList;
  6887. return addConstructor(loc, emulatedConstructorArguments, type);
  6888. }
  6889. // Lengthen list to be long enough to cover any gap from the current list size
  6890. // to 'size'. If the list is longer, do nothing.
  6891. // The value to lengthen with is the default for short lists.
  6892. //
  6893. // By default, lists that are too short due to lack of initializers initialize to zero.
  6894. // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
  6895. // based on whether something is passed in as 'scalarInit'.
  6896. //
  6897. // 'scalarInit' must be safe to use each time this is called (no side effects replication).
  6898. //
  6899. void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
  6900. {
  6901. for (int c = (int)list.size(); c < size; ++c) {
  6902. if (scalarInit == nullptr)
  6903. list.push_back(intermediate.addConstantUnion(0, loc));
  6904. else
  6905. list.push_back(scalarInit);
  6906. }
  6907. }
  6908. //
  6909. // Test for the correctness of the parameters passed to various constructor functions
  6910. // and also convert them to the right data type, if allowed and required.
  6911. //
  6912. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  6913. //
  6914. TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6915. {
  6916. if (node == nullptr)
  6917. return nullptr;
  6918. // Construct identical type
  6919. if (type == node->getType())
  6920. return node;
  6921. // Handle the idiom "(struct type)<scalar value>"
  6922. if (type.isStruct() && isScalarConstructor(node)) {
  6923. // 'node' will almost always get used multiple times, so should not be used directly,
  6924. // it would create a DAG instead of a tree, which might be okay (would
  6925. // like to formalize that for constants and symbols), but if it has
  6926. // side effects, they would get executed multiple times, which is not okay.
  6927. if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
  6928. TIntermAggregate* seq = intermediate.makeAggregate(loc);
  6929. TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
  6930. seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
  6931. seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
  6932. seq->setOp(EOpComma);
  6933. seq->setType(type);
  6934. return seq;
  6935. } else
  6936. return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
  6937. }
  6938. return addConstructor(loc, node, type);
  6939. }
  6940. // Add a constructor, either from the grammar, or other programmatic reasons.
  6941. //
  6942. // 'node' is what to construct from.
  6943. // 'type' is what type to construct.
  6944. //
  6945. // Returns the constructed object.
  6946. // Return nullptr if it can't be done.
  6947. //
  6948. TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6949. {
  6950. TIntermAggregate* aggrNode = node->getAsAggregate();
  6951. TOperator op = intermediate.mapTypeToConstructorOp(type);
  6952. if (op == EOpConstructTextureSampler)
  6953. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  6954. TTypeList::const_iterator memberTypes;
  6955. if (op == EOpConstructStruct)
  6956. memberTypes = type.getStruct()->begin();
  6957. TType elementType;
  6958. if (type.isArray()) {
  6959. TType dereferenced(type, 0);
  6960. elementType.shallowCopy(dereferenced);
  6961. } else
  6962. elementType.shallowCopy(type);
  6963. bool singleArg;
  6964. if (aggrNode != nullptr) {
  6965. if (aggrNode->getOp() != EOpNull)
  6966. singleArg = true;
  6967. else
  6968. singleArg = false;
  6969. } else
  6970. singleArg = true;
  6971. TIntermTyped *newNode;
  6972. if (singleArg) {
  6973. // Handle array -> array conversion
  6974. // Constructing an array of one type from an array of another type is allowed,
  6975. // assuming there are enough components available (semantic-checked earlier).
  6976. if (type.isArray() && node->isArray())
  6977. newNode = convertArray(node, type);
  6978. // If structure constructor or array constructor is being called
  6979. // for only one parameter inside the aggregate, we need to call constructAggregate function once.
  6980. else if (type.isArray())
  6981. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  6982. else if (op == EOpConstructStruct)
  6983. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  6984. else {
  6985. // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
  6986. // is replicated into every element of the matrix (not just the diagnonal), so
  6987. // that is handled specially here.
  6988. if (type.isMatrix() && node->getType().isScalarOrVec1())
  6989. node = intermediate.addShapeConversion(type, node);
  6990. newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
  6991. }
  6992. if (newNode && (type.isArray() || op == EOpConstructStruct))
  6993. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  6994. return newNode;
  6995. }
  6996. //
  6997. // Handle list of arguments.
  6998. //
  6999. TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  7000. // if the structure constructor contains more than one parameter, then construct
  7001. // each parameter
  7002. int paramCount = 0; // keeps a track of the constructor parameter number being checked
  7003. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  7004. // to the right type if possible (and allowed).
  7005. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  7006. for (TIntermSequence::iterator p = sequenceVector.begin();
  7007. p != sequenceVector.end(); p++, paramCount++) {
  7008. if (type.isArray())
  7009. newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
  7010. else if (op == EOpConstructStruct)
  7011. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
  7012. else
  7013. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7014. if (newNode)
  7015. *p = newNode;
  7016. else
  7017. return nullptr;
  7018. }
  7019. TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7020. return constructor;
  7021. }
  7022. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7023. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7024. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7025. // float, then float is converted to int.
  7026. //
  7027. // Returns nullptr for an error or the constructed node.
  7028. //
  7029. TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
  7030. const TSourceLoc& loc, bool subset)
  7031. {
  7032. TIntermTyped* newNode;
  7033. TOperator basicOp;
  7034. //
  7035. // First, convert types as needed.
  7036. //
  7037. switch (op) {
  7038. case EOpConstructF16Vec2:
  7039. case EOpConstructF16Vec3:
  7040. case EOpConstructF16Vec4:
  7041. case EOpConstructF16Mat2x2:
  7042. case EOpConstructF16Mat2x3:
  7043. case EOpConstructF16Mat2x4:
  7044. case EOpConstructF16Mat3x2:
  7045. case EOpConstructF16Mat3x3:
  7046. case EOpConstructF16Mat3x4:
  7047. case EOpConstructF16Mat4x2:
  7048. case EOpConstructF16Mat4x3:
  7049. case EOpConstructF16Mat4x4:
  7050. case EOpConstructFloat16:
  7051. basicOp = EOpConstructFloat16;
  7052. break;
  7053. case EOpConstructVec2:
  7054. case EOpConstructVec3:
  7055. case EOpConstructVec4:
  7056. case EOpConstructMat2x2:
  7057. case EOpConstructMat2x3:
  7058. case EOpConstructMat2x4:
  7059. case EOpConstructMat3x2:
  7060. case EOpConstructMat3x3:
  7061. case EOpConstructMat3x4:
  7062. case EOpConstructMat4x2:
  7063. case EOpConstructMat4x3:
  7064. case EOpConstructMat4x4:
  7065. case EOpConstructFloat:
  7066. basicOp = EOpConstructFloat;
  7067. break;
  7068. case EOpConstructDVec2:
  7069. case EOpConstructDVec3:
  7070. case EOpConstructDVec4:
  7071. case EOpConstructDMat2x2:
  7072. case EOpConstructDMat2x3:
  7073. case EOpConstructDMat2x4:
  7074. case EOpConstructDMat3x2:
  7075. case EOpConstructDMat3x3:
  7076. case EOpConstructDMat3x4:
  7077. case EOpConstructDMat4x2:
  7078. case EOpConstructDMat4x3:
  7079. case EOpConstructDMat4x4:
  7080. case EOpConstructDouble:
  7081. basicOp = EOpConstructDouble;
  7082. break;
  7083. case EOpConstructI16Vec2:
  7084. case EOpConstructI16Vec3:
  7085. case EOpConstructI16Vec4:
  7086. case EOpConstructInt16:
  7087. basicOp = EOpConstructInt16;
  7088. break;
  7089. case EOpConstructIVec2:
  7090. case EOpConstructIVec3:
  7091. case EOpConstructIVec4:
  7092. case EOpConstructIMat2x2:
  7093. case EOpConstructIMat2x3:
  7094. case EOpConstructIMat2x4:
  7095. case EOpConstructIMat3x2:
  7096. case EOpConstructIMat3x3:
  7097. case EOpConstructIMat3x4:
  7098. case EOpConstructIMat4x2:
  7099. case EOpConstructIMat4x3:
  7100. case EOpConstructIMat4x4:
  7101. case EOpConstructInt:
  7102. basicOp = EOpConstructInt;
  7103. break;
  7104. case EOpConstructU16Vec2:
  7105. case EOpConstructU16Vec3:
  7106. case EOpConstructU16Vec4:
  7107. case EOpConstructUint16:
  7108. basicOp = EOpConstructUint16;
  7109. break;
  7110. case EOpConstructUVec2:
  7111. case EOpConstructUVec3:
  7112. case EOpConstructUVec4:
  7113. case EOpConstructUMat2x2:
  7114. case EOpConstructUMat2x3:
  7115. case EOpConstructUMat2x4:
  7116. case EOpConstructUMat3x2:
  7117. case EOpConstructUMat3x3:
  7118. case EOpConstructUMat3x4:
  7119. case EOpConstructUMat4x2:
  7120. case EOpConstructUMat4x3:
  7121. case EOpConstructUMat4x4:
  7122. case EOpConstructUint:
  7123. basicOp = EOpConstructUint;
  7124. break;
  7125. case EOpConstructBVec2:
  7126. case EOpConstructBVec3:
  7127. case EOpConstructBVec4:
  7128. case EOpConstructBMat2x2:
  7129. case EOpConstructBMat2x3:
  7130. case EOpConstructBMat2x4:
  7131. case EOpConstructBMat3x2:
  7132. case EOpConstructBMat3x3:
  7133. case EOpConstructBMat3x4:
  7134. case EOpConstructBMat4x2:
  7135. case EOpConstructBMat4x3:
  7136. case EOpConstructBMat4x4:
  7137. case EOpConstructBool:
  7138. basicOp = EOpConstructBool;
  7139. break;
  7140. default:
  7141. error(loc, "unsupported construction", "", "");
  7142. return nullptr;
  7143. }
  7144. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7145. if (newNode == nullptr) {
  7146. error(loc, "can't convert", "constructor", "");
  7147. return nullptr;
  7148. }
  7149. //
  7150. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7151. //
  7152. // Otherwise, skip out early.
  7153. if (subset || (newNode != node && newNode->getType() == type))
  7154. return newNode;
  7155. // setAggregateOperator will insert a new node for the constructor, as needed.
  7156. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7157. }
  7158. // Convert the array in node to the requested type, which is also an array.
  7159. // Returns nullptr on failure, otherwise returns aggregate holding the list of
  7160. // elements needed to construct the array.
  7161. TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
  7162. {
  7163. assert(node->isArray() && type.isArray());
  7164. if (node->getType().computeNumComponents() < type.computeNumComponents())
  7165. return nullptr;
  7166. // TODO: write an argument replicator, for the case the argument should not be
  7167. // executed multiple times, yet multiple copies are needed.
  7168. TIntermTyped* constructee = node->getAsTyped();
  7169. // track where we are in consuming the argument
  7170. int constructeeElement = 0;
  7171. int constructeeComponent = 0;
  7172. // bump up to the next component to consume
  7173. const auto getNextComponent = [&]() {
  7174. TIntermTyped* component;
  7175. component = handleBracketDereference(node->getLoc(), constructee,
  7176. intermediate.addConstantUnion(constructeeElement, node->getLoc()));
  7177. if (component->isVector())
  7178. component = handleBracketDereference(node->getLoc(), component,
  7179. intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
  7180. // bump component pointer up
  7181. ++constructeeComponent;
  7182. if (constructeeComponent == constructee->getVectorSize()) {
  7183. constructeeComponent = 0;
  7184. ++constructeeElement;
  7185. }
  7186. return component;
  7187. };
  7188. // make one subnode per constructed array element
  7189. TIntermAggregate* constructor = nullptr;
  7190. TType derefType(type, 0);
  7191. TType speculativeComponentType(derefType, 0);
  7192. TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
  7193. TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
  7194. TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
  7195. for (int e = 0; e < type.getOuterArraySize(); ++e) {
  7196. // construct an element
  7197. TIntermTyped* elementArg;
  7198. if (type.getVectorSize() == constructee->getVectorSize()) {
  7199. // same element shape
  7200. elementArg = handleBracketDereference(node->getLoc(), constructee,
  7201. intermediate.addConstantUnion(e, node->getLoc()));
  7202. } else {
  7203. // mismatched element shapes
  7204. if (type.getVectorSize() == 1)
  7205. elementArg = getNextComponent();
  7206. else {
  7207. // make a vector
  7208. TIntermAggregate* elementConstructee = nullptr;
  7209. for (int c = 0; c < type.getVectorSize(); ++c)
  7210. elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
  7211. elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
  7212. }
  7213. }
  7214. // convert basic types
  7215. elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
  7216. if (elementArg == nullptr)
  7217. return nullptr;
  7218. // combine with top-level constructor
  7219. constructor = intermediate.growAggregate(constructor, elementArg);
  7220. }
  7221. return constructor;
  7222. }
  7223. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7224. // an error message if the expected type does not match the parameter passed to the constructor.
  7225. //
  7226. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7227. //
  7228. TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
  7229. const TSourceLoc& loc)
  7230. {
  7231. // Handle cases that map more 1:1 between constructor arguments and constructed.
  7232. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7233. if (converted == nullptr || converted->getType() != type) {
  7234. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7235. node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
  7236. return nullptr;
  7237. }
  7238. return converted;
  7239. }
  7240. //
  7241. // Do everything needed to add an interface block.
  7242. //
  7243. void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
  7244. {
  7245. assert(type.getWritableStruct() != nullptr);
  7246. // Clean up top-level decorations that don't belong.
  7247. switch (type.getQualifier().storage) {
  7248. case EvqUniform:
  7249. case EvqBuffer:
  7250. correctUniform(type.getQualifier());
  7251. break;
  7252. case EvqVaryingIn:
  7253. correctInput(type.getQualifier());
  7254. break;
  7255. case EvqVaryingOut:
  7256. correctOutput(type.getQualifier());
  7257. break;
  7258. default:
  7259. break;
  7260. }
  7261. TTypeList& typeList = *type.getWritableStruct();
  7262. // fix and check for member storage qualifiers and types that don't belong within a block
  7263. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7264. TType& memberType = *typeList[member].type;
  7265. TQualifier& memberQualifier = memberType.getQualifier();
  7266. const TSourceLoc& memberLoc = typeList[member].loc;
  7267. globalQualifierFix(memberLoc, memberQualifier);
  7268. memberQualifier.storage = type.getQualifier().storage;
  7269. if (memberType.isStruct()) {
  7270. // clean up and pick up the right set of decorations
  7271. auto it = ioTypeMap.find(memberType.getStruct());
  7272. switch (type.getQualifier().storage) {
  7273. case EvqUniform:
  7274. case EvqBuffer:
  7275. correctUniform(type.getQualifier());
  7276. if (it != ioTypeMap.end() && it->second.uniform)
  7277. memberType.setStruct(it->second.uniform);
  7278. break;
  7279. case EvqVaryingIn:
  7280. correctInput(type.getQualifier());
  7281. if (it != ioTypeMap.end() && it->second.input)
  7282. memberType.setStruct(it->second.input);
  7283. break;
  7284. case EvqVaryingOut:
  7285. correctOutput(type.getQualifier());
  7286. if (it != ioTypeMap.end() && it->second.output)
  7287. memberType.setStruct(it->second.output);
  7288. break;
  7289. default:
  7290. break;
  7291. }
  7292. }
  7293. }
  7294. // Make default block qualification, and adjust the member qualifications
  7295. TQualifier defaultQualification;
  7296. switch (type.getQualifier().storage) {
  7297. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7298. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7299. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7300. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7301. default: defaultQualification.clear(); break;
  7302. }
  7303. // Special case for "push_constant uniform", which has a default of std430,
  7304. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7305. if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
  7306. type.getQualifier().layoutPacking = ElpStd430;
  7307. // fix and check for member layout qualifiers
  7308. mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
  7309. bool memberWithLocation = false;
  7310. bool memberWithoutLocation = false;
  7311. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7312. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7313. const TSourceLoc& memberLoc = typeList[member].loc;
  7314. if (memberQualifier.hasStream()) {
  7315. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7316. error(memberLoc, "member cannot contradict block", "stream", "");
  7317. }
  7318. // "This includes a block's inheritance of the
  7319. // current global default buffer, a block member's inheritance of the block's
  7320. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7321. // member must match the buffer inherited from the block."
  7322. if (memberQualifier.hasXfbBuffer()) {
  7323. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7324. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7325. }
  7326. if (memberQualifier.hasLocation()) {
  7327. switch (type.getQualifier().storage) {
  7328. case EvqVaryingIn:
  7329. case EvqVaryingOut:
  7330. memberWithLocation = true;
  7331. break;
  7332. default:
  7333. break;
  7334. }
  7335. } else
  7336. memberWithoutLocation = true;
  7337. TQualifier newMemberQualification = defaultQualification;
  7338. mergeQualifiers(newMemberQualification, memberQualifier);
  7339. memberQualifier = newMemberQualification;
  7340. }
  7341. // Process the members
  7342. fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
  7343. fixXfbOffsets(type.getQualifier(), typeList);
  7344. fixBlockUniformOffsets(type.getQualifier(), typeList);
  7345. // reverse merge, so that currentBlockQualifier now has all layout information
  7346. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7347. mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
  7348. //
  7349. // Build and add the interface block as a new type named 'blockName'
  7350. //
  7351. // Use the instance name as the interface name if one exists, else the block name.
  7352. const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
  7353. TType blockType(&typeList, interfaceName, type.getQualifier());
  7354. if (type.isArray())
  7355. blockType.transferArraySizes(type.getArraySizes());
  7356. // Add the variable, as anonymous or named instanceName.
  7357. // Make an anonymous variable if no name was provided.
  7358. if (instanceName == nullptr)
  7359. instanceName = NewPoolTString("");
  7360. TVariable& variable = *new TVariable(instanceName, blockType);
  7361. if (! symbolTable.insert(variable)) {
  7362. if (*instanceName == "")
  7363. error(loc, "nameless block contains a member that already has a name at global scope",
  7364. "" /* blockName->c_str() */, "");
  7365. else
  7366. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7367. return;
  7368. }
  7369. // Save it in the AST for linker use.
  7370. if (symbolTable.atGlobalLevel())
  7371. trackLinkage(variable);
  7372. }
  7373. //
  7374. // "For a block, this process applies to the entire block, or until the first member
  7375. // is reached that has a location layout qualifier. When a block member is declared with a location
  7376. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7377. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7378. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7379. // declared in increasing order."
  7380. void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7381. {
  7382. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7383. // have a location layout qualifier, or a compile-time error results."
  7384. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7385. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7386. else {
  7387. if (memberWithLocation) {
  7388. // remove any block-level location and make it per *every* member
  7389. int nextLocation = 0; // by the rule above, initial value is not relevant
  7390. if (qualifier.hasAnyLocation()) {
  7391. nextLocation = qualifier.layoutLocation;
  7392. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7393. if (qualifier.hasComponent()) {
  7394. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7395. error(loc, "cannot apply to a block", "component", "");
  7396. }
  7397. if (qualifier.hasIndex()) {
  7398. error(loc, "cannot apply to a block", "index", "");
  7399. }
  7400. }
  7401. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7402. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7403. const TSourceLoc& memberLoc = typeList[member].loc;
  7404. if (! memberQualifier.hasLocation()) {
  7405. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7406. error(memberLoc, "location is too large", "location", "");
  7407. memberQualifier.layoutLocation = nextLocation;
  7408. memberQualifier.layoutComponent = 0;
  7409. }
  7410. nextLocation = memberQualifier.layoutLocation +
  7411. intermediate.computeTypeLocationSize(*typeList[member].type, language);
  7412. }
  7413. }
  7414. }
  7415. }
  7416. void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7417. {
  7418. // "If a block is qualified with xfb_offset, all its
  7419. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7420. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7421. // offsets."
  7422. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7423. return;
  7424. int nextOffset = qualifier.layoutXfbOffset;
  7425. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7426. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7427. bool contains64BitType = false;
  7428. bool contains32BitType = false;
  7429. bool contains16BitType = false;
  7430. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
  7431. // see if we need to auto-assign an offset to this member
  7432. if (! memberQualifier.hasXfbOffset()) {
  7433. // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
  7434. if (contains64BitType)
  7435. RoundToPow2(nextOffset, 8);
  7436. else if (contains32BitType)
  7437. RoundToPow2(nextOffset, 4);
  7438. // "if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2"
  7439. else if (contains16BitType)
  7440. RoundToPow2(nextOffset, 2);
  7441. memberQualifier.layoutXfbOffset = nextOffset;
  7442. } else
  7443. nextOffset = memberQualifier.layoutXfbOffset;
  7444. nextOffset += memberSize;
  7445. }
  7446. // The above gave all block members an offset, so we can take it off the block now,
  7447. // which will avoid double counting the offset usage.
  7448. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7449. }
  7450. // Calculate and save the offset of each block member, using the recursively
  7451. // defined block offset rules and the user-provided offset and align.
  7452. //
  7453. // Also, compute and save the total size of the block. For the block's size, arrayness
  7454. // is not taken into account, as each element is backed by a separate buffer.
  7455. //
  7456. void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
  7457. {
  7458. if (! qualifier.isUniformOrBuffer())
  7459. return;
  7460. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7461. return;
  7462. int offset = 0;
  7463. int memberSize;
  7464. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7465. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7466. const TSourceLoc& memberLoc = typeList[member].loc;
  7467. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7468. // modify just the children's view of matrix layout, if there is one for this member
  7469. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7470. int dummyStride;
  7471. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
  7472. qualifier.layoutPacking,
  7473. subMatrixLayout != ElmNone
  7474. ? subMatrixLayout == ElmRowMajor
  7475. : qualifier.layoutMatrix == ElmRowMajor);
  7476. if (memberQualifier.hasOffset()) {
  7477. // "The specified offset must be a multiple
  7478. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7479. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7480. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7481. // "The offset qualifier forces the qualified member to start at or after the specified
  7482. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7483. // "The actual offset of a member is computed as
  7484. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7485. offset = std::max(offset, memberQualifier.layoutOffset);
  7486. }
  7487. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7488. // (e.g., std140) base alignment for the member's type."
  7489. if (memberQualifier.hasAlign())
  7490. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7491. // "If the resulting offset is not a multiple of the actual alignment,
  7492. // increase it to the first offset that is a multiple of
  7493. // the actual alignment."
  7494. RoundToPow2(offset, memberAlignment);
  7495. typeList[member].type->getQualifier().layoutOffset = offset;
  7496. offset += memberSize;
  7497. }
  7498. }
  7499. // For an identifier that is already declared, add more qualification to it.
  7500. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  7501. {
  7502. TSymbol* symbol = symbolTable.find(identifier);
  7503. if (symbol == nullptr) {
  7504. error(loc, "identifier not previously declared", identifier.c_str(), "");
  7505. return;
  7506. }
  7507. if (symbol->getAsFunction()) {
  7508. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  7509. return;
  7510. }
  7511. if (qualifier.isAuxiliary() ||
  7512. qualifier.isMemory() ||
  7513. qualifier.isInterpolation() ||
  7514. qualifier.hasLayout() ||
  7515. qualifier.storage != EvqTemporary ||
  7516. qualifier.precision != EpqNone) {
  7517. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  7518. return;
  7519. }
  7520. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  7521. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  7522. if (symbol->isReadOnly())
  7523. symbol = symbolTable.copyUp(symbol);
  7524. if (qualifier.invariant) {
  7525. if (intermediate.inIoAccessed(identifier))
  7526. error(loc, "cannot change qualification after use", "invariant", "");
  7527. symbol->getWritableType().getQualifier().invariant = true;
  7528. } else if (qualifier.noContraction) {
  7529. if (intermediate.inIoAccessed(identifier))
  7530. error(loc, "cannot change qualification after use", "precise", "");
  7531. symbol->getWritableType().getQualifier().noContraction = true;
  7532. } else if (qualifier.specConstant) {
  7533. symbol->getWritableType().getQualifier().makeSpecConstant();
  7534. if (qualifier.hasSpecConstantId())
  7535. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  7536. } else
  7537. warn(loc, "unknown requalification", "", "");
  7538. }
  7539. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  7540. {
  7541. for (unsigned int i = 0; i < identifiers.size(); ++i)
  7542. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  7543. }
  7544. //
  7545. // Update the intermediate for the given input geometry
  7546. //
  7547. bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7548. {
  7549. switch (geometry) {
  7550. case ElgPoints: // fall through
  7551. case ElgLines: // ...
  7552. case ElgTriangles: // ...
  7553. case ElgLinesAdjacency: // ...
  7554. case ElgTrianglesAdjacency: // ...
  7555. if (! intermediate.setInputPrimitive(geometry)) {
  7556. error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7557. return false;
  7558. }
  7559. break;
  7560. default:
  7561. error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
  7562. return false;
  7563. }
  7564. return true;
  7565. }
  7566. //
  7567. // Update the intermediate for the given output geometry
  7568. //
  7569. bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7570. {
  7571. // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
  7572. // Since that's an OK situation, return true for success.
  7573. if (language != EShLangGeometry)
  7574. return true;
  7575. switch (geometry) {
  7576. case ElgPoints:
  7577. case ElgLineStrip:
  7578. case ElgTriangleStrip:
  7579. if (! intermediate.setOutputPrimitive(geometry)) {
  7580. error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7581. return false;
  7582. }
  7583. break;
  7584. default:
  7585. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
  7586. return false;
  7587. }
  7588. return true;
  7589. }
  7590. //
  7591. // Selection attributes
  7592. //
  7593. void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
  7594. const TAttributes& attributes)
  7595. {
  7596. if (selection == nullptr)
  7597. return;
  7598. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7599. switch (it->name) {
  7600. case EatFlatten:
  7601. selection->setFlatten();
  7602. break;
  7603. case EatBranch:
  7604. selection->setDontFlatten();
  7605. break;
  7606. default:
  7607. warn(loc, "attribute does not apply to a selection", "", "");
  7608. break;
  7609. }
  7610. }
  7611. }
  7612. //
  7613. // Switch attributes
  7614. //
  7615. void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
  7616. const TAttributes& attributes)
  7617. {
  7618. if (selection == nullptr)
  7619. return;
  7620. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7621. switch (it->name) {
  7622. case EatFlatten:
  7623. selection->setFlatten();
  7624. break;
  7625. case EatBranch:
  7626. selection->setDontFlatten();
  7627. break;
  7628. default:
  7629. warn(loc, "attribute does not apply to a switch", "", "");
  7630. break;
  7631. }
  7632. }
  7633. }
  7634. //
  7635. // Loop attributes
  7636. //
  7637. void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
  7638. const TAttributes& attributes)
  7639. {
  7640. if (loop == nullptr)
  7641. return;
  7642. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7643. switch (it->name) {
  7644. case EatUnroll:
  7645. loop->setUnroll();
  7646. break;
  7647. case EatLoop:
  7648. loop->setDontUnroll();
  7649. break;
  7650. default:
  7651. warn(loc, "attribute does not apply to a loop", "", "");
  7652. break;
  7653. }
  7654. }
  7655. }
  7656. //
  7657. // Updating default qualifier for the case of a declaration with just a qualifier,
  7658. // no type, block, or identifier.
  7659. //
  7660. void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  7661. {
  7662. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  7663. assert(language == EShLangTessControl || language == EShLangGeometry);
  7664. // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  7665. }
  7666. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  7667. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  7668. error(loc, "cannot change previously set layout value", "invocations", "");
  7669. }
  7670. if (publicType.shaderQualifiers.geometry != ElgNone) {
  7671. if (publicType.qualifier.storage == EvqVaryingIn) {
  7672. switch (publicType.shaderQualifiers.geometry) {
  7673. case ElgPoints:
  7674. case ElgLines:
  7675. case ElgLinesAdjacency:
  7676. case ElgTriangles:
  7677. case ElgTrianglesAdjacency:
  7678. case ElgQuads:
  7679. case ElgIsolines:
  7680. break;
  7681. default:
  7682. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7683. "");
  7684. }
  7685. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  7686. handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
  7687. } else
  7688. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7689. GetStorageQualifierString(publicType.qualifier.storage));
  7690. }
  7691. if (publicType.shaderQualifiers.spacing != EvsNone)
  7692. intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
  7693. if (publicType.shaderQualifiers.order != EvoNone)
  7694. intermediate.setVertexOrder(publicType.shaderQualifiers.order);
  7695. if (publicType.shaderQualifiers.pointMode)
  7696. intermediate.setPointMode();
  7697. for (int i = 0; i < 3; ++i) {
  7698. if (publicType.shaderQualifiers.localSize[i] > 1) {
  7699. int max = 0;
  7700. switch (i) {
  7701. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  7702. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  7703. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  7704. default: break;
  7705. }
  7706. if (intermediate.getLocalSize(i) > (unsigned int)max)
  7707. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  7708. // Fix the existing constant gl_WorkGroupSize with this new information.
  7709. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7710. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  7711. }
  7712. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  7713. intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
  7714. // Set the workgroup built-in variable as a specialization constant
  7715. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7716. workGroupSize->getWritableType().getQualifier().specConstant = true;
  7717. }
  7718. }
  7719. if (publicType.shaderQualifiers.earlyFragmentTests)
  7720. intermediate.setEarlyFragmentTests();
  7721. const TQualifier& qualifier = publicType.qualifier;
  7722. switch (qualifier.storage) {
  7723. case EvqUniform:
  7724. if (qualifier.hasMatrix())
  7725. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  7726. if (qualifier.hasPacking())
  7727. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  7728. break;
  7729. case EvqBuffer:
  7730. if (qualifier.hasMatrix())
  7731. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  7732. if (qualifier.hasPacking())
  7733. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  7734. break;
  7735. case EvqVaryingIn:
  7736. break;
  7737. case EvqVaryingOut:
  7738. if (qualifier.hasStream())
  7739. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  7740. if (qualifier.hasXfbBuffer())
  7741. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  7742. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  7743. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  7744. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
  7745. qualifier.layoutXfbBuffer);
  7746. }
  7747. break;
  7748. default:
  7749. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
  7750. return;
  7751. }
  7752. }
  7753. //
  7754. // Take the sequence of statements that has been built up since the last case/default,
  7755. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  7756. // and follow that by the case/default we are on now. (See switch topology comment on
  7757. // TIntermSwitch.)
  7758. //
  7759. void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  7760. {
  7761. TIntermSequence* switchSequence = switchSequenceStack.back();
  7762. if (statements) {
  7763. statements->setOperator(EOpSequence);
  7764. switchSequence->push_back(statements);
  7765. }
  7766. if (branchNode) {
  7767. // check all previous cases for the same label (or both are 'default')
  7768. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  7769. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  7770. if (prevBranch) {
  7771. TIntermTyped* prevExpression = prevBranch->getExpression();
  7772. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  7773. if (prevExpression == nullptr && newExpression == nullptr)
  7774. error(branchNode->getLoc(), "duplicate label", "default", "");
  7775. else if (prevExpression != nullptr &&
  7776. newExpression != nullptr &&
  7777. prevExpression->getAsConstantUnion() &&
  7778. newExpression->getAsConstantUnion() &&
  7779. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  7780. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  7781. error(branchNode->getLoc(), "duplicated value", "case", "");
  7782. }
  7783. }
  7784. switchSequence->push_back(branchNode);
  7785. }
  7786. }
  7787. //
  7788. // Turn the top-level node sequence built up of wrapupSwitchSubsequence
  7789. // into a switch node.
  7790. //
  7791. TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
  7792. TIntermAggregate* lastStatements, const TAttributes& attributes)
  7793. {
  7794. wrapupSwitchSubsequence(lastStatements, nullptr);
  7795. if (expression == nullptr ||
  7796. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  7797. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  7798. error(loc, "condition must be a scalar integer expression", "switch", "");
  7799. // If there is nothing to do, drop the switch but still execute the expression
  7800. TIntermSequence* switchSequence = switchSequenceStack.back();
  7801. if (switchSequence->size() == 0)
  7802. return expression;
  7803. if (lastStatements == nullptr) {
  7804. // emulate a break for error recovery
  7805. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  7806. lastStatements->setOperator(EOpSequence);
  7807. switchSequence->push_back(lastStatements);
  7808. }
  7809. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  7810. body->getSequence() = *switchSequenceStack.back();
  7811. body->setLoc(loc);
  7812. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  7813. switchNode->setLoc(loc);
  7814. handleSwitchAttributes(loc, switchNode, attributes);
  7815. return switchNode;
  7816. }
  7817. // Make a new symbol-table level that is made out of the members of a structure.
  7818. // This should be done as an anonymous struct (name is "") so that the symbol table
  7819. // finds the members with no explicit reference to a 'this' variable.
  7820. void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
  7821. {
  7822. // member variables
  7823. TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
  7824. symbolTable.pushThis(thisVariable);
  7825. // member functions
  7826. for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
  7827. // member should have a prefix matching currentTypePrefix.back()
  7828. // but, symbol lookup within the class scope will just use the
  7829. // unprefixed name. Hence, there are two: one fully prefixed and
  7830. // one with no prefix.
  7831. TFunction& member = *it->function->clone();
  7832. member.removePrefix(currentTypePrefix.back());
  7833. symbolTable.insert(member);
  7834. }
  7835. }
  7836. // Track levels of class/struct/namespace nesting with a prefix string using
  7837. // the type names separated by the scoping operator. E.g., two levels
  7838. // would look like:
  7839. //
  7840. // outer::inner
  7841. //
  7842. // The string is empty when at normal global level.
  7843. //
  7844. void HlslParseContext::pushNamespace(const TString& typeName)
  7845. {
  7846. // make new type prefix
  7847. TString newPrefix;
  7848. if (currentTypePrefix.size() > 0)
  7849. newPrefix = currentTypePrefix.back();
  7850. newPrefix.append(typeName);
  7851. newPrefix.append(scopeMangler);
  7852. currentTypePrefix.push_back(newPrefix);
  7853. }
  7854. // Opposite of pushNamespace(), see above
  7855. void HlslParseContext::popNamespace()
  7856. {
  7857. currentTypePrefix.pop_back();
  7858. }
  7859. // Use the class/struct nesting string to create a global name for
  7860. // a member of a class/struct.
  7861. void HlslParseContext::getFullNamespaceName(TString*& name) const
  7862. {
  7863. if (currentTypePrefix.size() == 0)
  7864. return;
  7865. TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
  7866. fullName->append(*name);
  7867. name = fullName;
  7868. }
  7869. // Helper function to add the namespace scope mangling syntax to a string.
  7870. void HlslParseContext::addScopeMangler(TString& name)
  7871. {
  7872. name.append(scopeMangler);
  7873. }
  7874. // Return true if this has uniform-interface like decorations.
  7875. bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
  7876. {
  7877. return qualifier.hasUniformLayout() ||
  7878. qualifier.layoutPushConstant;
  7879. }
  7880. // Potentially not the opposite of hasUniform(), as if some characteristic is
  7881. // ever used for more than one thing (e.g., uniform or input), hasUniform() should
  7882. // say it exists, but clearUniform() should leave it in place.
  7883. void HlslParseContext::clearUniform(TQualifier& qualifier)
  7884. {
  7885. qualifier.clearUniformLayout();
  7886. qualifier.layoutPushConstant = false;
  7887. }
  7888. // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
  7889. bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
  7890. {
  7891. switch (qualifier.builtIn) {
  7892. case EbvPosition:
  7893. case EbvPointSize:
  7894. return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
  7895. case EbvClipDistance:
  7896. case EbvCullDistance:
  7897. return language != EShLangVertex && language != EShLangCompute;
  7898. case EbvFragCoord:
  7899. case EbvFace:
  7900. case EbvHelperInvocation:
  7901. case EbvLayer:
  7902. case EbvPointCoord:
  7903. case EbvSampleId:
  7904. case EbvSampleMask:
  7905. case EbvSamplePosition:
  7906. case EbvViewportIndex:
  7907. return language == EShLangFragment;
  7908. case EbvGlobalInvocationId:
  7909. case EbvLocalInvocationIndex:
  7910. case EbvLocalInvocationId:
  7911. case EbvNumWorkGroups:
  7912. case EbvWorkGroupId:
  7913. case EbvWorkGroupSize:
  7914. return language == EShLangCompute;
  7915. case EbvInvocationId:
  7916. return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
  7917. case EbvPatchVertices:
  7918. return language == EShLangTessControl || language == EShLangTessEvaluation;
  7919. case EbvInstanceId:
  7920. case EbvInstanceIndex:
  7921. case EbvVertexId:
  7922. case EbvVertexIndex:
  7923. return language == EShLangVertex;
  7924. case EbvPrimitiveId:
  7925. return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
  7926. case EbvTessLevelInner:
  7927. case EbvTessLevelOuter:
  7928. return language == EShLangTessEvaluation;
  7929. case EbvTessCoord:
  7930. return language == EShLangTessEvaluation;
  7931. default:
  7932. return false;
  7933. }
  7934. }
  7935. // Return true if there are decorations to preserve for input-like storage.
  7936. bool HlslParseContext::hasInput(const TQualifier& qualifier) const
  7937. {
  7938. if (qualifier.hasAnyLocation())
  7939. return true;
  7940. if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
  7941. return true;
  7942. if (language == EShLangTessEvaluation && qualifier.patch)
  7943. return true;
  7944. if (isInputBuiltIn(qualifier))
  7945. return true;
  7946. return false;
  7947. }
  7948. // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
  7949. bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
  7950. {
  7951. switch (qualifier.builtIn) {
  7952. case EbvPosition:
  7953. case EbvPointSize:
  7954. case EbvClipVertex:
  7955. case EbvClipDistance:
  7956. case EbvCullDistance:
  7957. return language != EShLangFragment && language != EShLangCompute;
  7958. case EbvFragDepth:
  7959. case EbvFragDepthGreater:
  7960. case EbvFragDepthLesser:
  7961. case EbvSampleMask:
  7962. return language == EShLangFragment;
  7963. case EbvLayer:
  7964. case EbvViewportIndex:
  7965. return language == EShLangGeometry || language == EShLangVertex;
  7966. case EbvPrimitiveId:
  7967. return language == EShLangGeometry;
  7968. case EbvTessLevelInner:
  7969. case EbvTessLevelOuter:
  7970. return language == EShLangTessControl;
  7971. default:
  7972. return false;
  7973. }
  7974. }
  7975. // Return true if there are decorations to preserve for output-like storage.
  7976. bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
  7977. {
  7978. if (qualifier.hasAnyLocation())
  7979. return true;
  7980. if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
  7981. return true;
  7982. if (language == EShLangTessControl && qualifier.patch)
  7983. return true;
  7984. if (language == EShLangGeometry && qualifier.hasStream())
  7985. return true;
  7986. if (isOutputBuiltIn(qualifier))
  7987. return true;
  7988. return false;
  7989. }
  7990. // Make the IO decorations etc. be appropriate only for an input interface.
  7991. void HlslParseContext::correctInput(TQualifier& qualifier)
  7992. {
  7993. clearUniform(qualifier);
  7994. if (language == EShLangVertex)
  7995. qualifier.clearInterstage();
  7996. if (language != EShLangTessEvaluation)
  7997. qualifier.patch = false;
  7998. if (language != EShLangFragment) {
  7999. qualifier.clearInterpolation();
  8000. qualifier.sample = false;
  8001. }
  8002. qualifier.clearStreamLayout();
  8003. qualifier.clearXfbLayout();
  8004. if (! isInputBuiltIn(qualifier))
  8005. qualifier.builtIn = EbvNone;
  8006. }
  8007. // Make the IO decorations etc. be appropriate only for an output interface.
  8008. void HlslParseContext::correctOutput(TQualifier& qualifier)
  8009. {
  8010. clearUniform(qualifier);
  8011. if (language == EShLangFragment)
  8012. qualifier.clearInterstage();
  8013. if (language != EShLangGeometry)
  8014. qualifier.clearStreamLayout();
  8015. if (language == EShLangFragment)
  8016. qualifier.clearXfbLayout();
  8017. if (language != EShLangTessControl)
  8018. qualifier.patch = false;
  8019. switch (qualifier.builtIn) {
  8020. case EbvFragDepth:
  8021. intermediate.setDepthReplacing();
  8022. intermediate.setDepth(EldAny);
  8023. break;
  8024. case EbvFragDepthGreater:
  8025. intermediate.setDepthReplacing();
  8026. intermediate.setDepth(EldGreater);
  8027. qualifier.builtIn = EbvFragDepth;
  8028. break;
  8029. case EbvFragDepthLesser:
  8030. intermediate.setDepthReplacing();
  8031. intermediate.setDepth(EldLess);
  8032. qualifier.builtIn = EbvFragDepth;
  8033. break;
  8034. default:
  8035. break;
  8036. }
  8037. if (! isOutputBuiltIn(qualifier))
  8038. qualifier.builtIn = EbvNone;
  8039. }
  8040. // Make the IO decorations etc. be appropriate only for uniform type interfaces.
  8041. void HlslParseContext::correctUniform(TQualifier& qualifier)
  8042. {
  8043. if (qualifier.declaredBuiltIn == EbvNone)
  8044. qualifier.declaredBuiltIn = qualifier.builtIn;
  8045. qualifier.builtIn = EbvNone;
  8046. qualifier.clearInterstage();
  8047. qualifier.clearInterstageLayout();
  8048. }
  8049. // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
  8050. void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
  8051. {
  8052. clearUniform(qualifier);
  8053. correctUniform(qualifier);
  8054. }
  8055. // Set texture return type. Returns success (not all types are valid).
  8056. bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
  8057. {
  8058. // Seed the output with an invalid index. We will set it to a valid one if we can.
  8059. sampler.structReturnIndex = TSampler::noReturnStruct;
  8060. // Arrays aren't supported.
  8061. if (retType.isArray()) {
  8062. error(loc, "Arrays not supported in texture template types", "", "");
  8063. return false;
  8064. }
  8065. // If return type is a vector, remember the vector size in the sampler, and return.
  8066. if (retType.isVector() || retType.isScalar()) {
  8067. sampler.vectorSize = retType.getVectorSize();
  8068. return true;
  8069. }
  8070. // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
  8071. // are checked below: just check for struct-ness here.
  8072. if (!retType.isStruct()) {
  8073. error(loc, "Invalid texture template type", "", "");
  8074. return false;
  8075. }
  8076. // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
  8077. if (sampler.isSubpass()) {
  8078. error(loc, "Unimplemented: structure template type in subpass input", "", "");
  8079. return false;
  8080. }
  8081. TTypeList* members = retType.getWritableStruct();
  8082. // Check for too many or not enough structure members.
  8083. if (members->size() > 4 || members->size() == 0) {
  8084. error(loc, "Invalid member count in texture template structure", "", "");
  8085. return false;
  8086. }
  8087. // Error checking: We must have <= 4 total components, all of the same basic type.
  8088. unsigned totalComponents = 0;
  8089. for (unsigned m = 0; m < members->size(); ++m) {
  8090. // Check for bad member types
  8091. if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
  8092. error(loc, "Invalid texture template struct member type", "", "");
  8093. return false;
  8094. }
  8095. const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
  8096. totalComponents += memberVectorSize;
  8097. // too many total member components
  8098. if (totalComponents > 4) {
  8099. error(loc, "Too many components in texture template structure type", "", "");
  8100. return false;
  8101. }
  8102. // All members must be of a common basic type
  8103. if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
  8104. error(loc, "Texture template structure members must same basic type", "", "");
  8105. return false;
  8106. }
  8107. }
  8108. // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
  8109. // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
  8110. for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
  8111. if (textureReturnStruct[idx] == members) {
  8112. sampler.structReturnIndex = idx;
  8113. return true;
  8114. }
  8115. }
  8116. // It wasn't found as an existing entry. See if we have room for a new one.
  8117. if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
  8118. error(loc, "Texture template struct return slots exceeded", "", "");
  8119. return false;
  8120. }
  8121. // Insert it in the vector that tracks struct return types.
  8122. sampler.structReturnIndex = unsigned(textureReturnStruct.size());
  8123. textureReturnStruct.push_back(members);
  8124. // Success!
  8125. return true;
  8126. }
  8127. // Return the sampler return type in retType.
  8128. void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
  8129. {
  8130. if (sampler.hasReturnStruct()) {
  8131. assert(textureReturnStruct.size() >= sampler.structReturnIndex);
  8132. // We land here if the texture return is a structure.
  8133. TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
  8134. const TType resultType(blockStruct, "");
  8135. retType.shallowCopy(resultType);
  8136. } else {
  8137. // We land here if the texture return is a vector or scalar.
  8138. const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
  8139. retType.shallowCopy(resultType);
  8140. }
  8141. }
  8142. // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
  8143. TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
  8144. {
  8145. const auto it = builtInTessLinkageSymbols.find(biType);
  8146. if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
  8147. return nullptr;
  8148. return intermediate.addSymbol(*it->second->getAsVariable());
  8149. }
  8150. // Find the patch constant function (issues error, returns nullptr if not found)
  8151. const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
  8152. {
  8153. if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
  8154. error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
  8155. return nullptr;
  8156. }
  8157. const TString mangledName = patchConstantFunctionName + "(";
  8158. // create list of PCF candidates
  8159. TVector<const TFunction*> candidateList;
  8160. bool builtIn;
  8161. symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
  8162. // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
  8163. // allow any disambiguation of overloads.
  8164. if (candidateList.empty()) {
  8165. error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
  8166. return nullptr;
  8167. }
  8168. // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
  8169. // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
  8170. // out if there is more than one candidate.
  8171. if (candidateList.size() > 1) {
  8172. error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
  8173. return nullptr;
  8174. }
  8175. return candidateList[0];
  8176. }
  8177. // Finalization step: Add patch constant function invocation
  8178. void HlslParseContext::addPatchConstantInvocation()
  8179. {
  8180. TSourceLoc loc;
  8181. loc.init();
  8182. // If there's no patch constant function, or we're not a HS, do nothing.
  8183. if (patchConstantFunctionName.empty() || language != EShLangTessControl)
  8184. return;
  8185. // Look for built-in variables in a function's parameter list.
  8186. const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
  8187. for (int p=0; p<function.getParamCount(); ++p) {
  8188. TStorageQualifier storage = function[p].type->getQualifier().storage;
  8189. if (storage == EvqConstReadOnly) // treated identically to input
  8190. storage = EvqIn;
  8191. if (function[p].getDeclaredBuiltIn() != EbvNone)
  8192. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
  8193. else
  8194. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
  8195. }
  8196. };
  8197. // If we synthesize a built-in interface variable, we must add it to the linkage.
  8198. const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
  8199. if (name == nullptr) {
  8200. error(loc, "unable to locate patch function parameter name", "", "");
  8201. return;
  8202. } else {
  8203. TVariable& variable = *new TVariable(name, type);
  8204. if (! symbolTable.insert(variable)) {
  8205. error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
  8206. return;
  8207. }
  8208. globalQualifierFix(loc, variable.getWritableType().getQualifier());
  8209. if (symbolNode != nullptr)
  8210. *symbolNode = intermediate.addSymbol(variable);
  8211. trackLinkage(variable);
  8212. }
  8213. };
  8214. const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
  8215. const TType& type = *patchConstantFunction[param].type;
  8216. const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
  8217. return type.isSizedArray() && biType == EbvOutputPatch;
  8218. };
  8219. // We will perform these steps. Each is in a scoped block for separation: they could
  8220. // become separate functions to make addPatchConstantInvocation shorter.
  8221. //
  8222. // 1. Union the interfaces, and create built-ins for anything present in the PCF and
  8223. // declared as a built-in variable that isn't present in the entry point's signature.
  8224. //
  8225. // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
  8226. // or the ones we created. Matching is based on built-in type. We may use synthesized
  8227. // variables from (1) above.
  8228. //
  8229. // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
  8230. //
  8231. // 3. Create a return sequence: copy the return value (if any) from the PCF to a
  8232. // (non-sanitized) output variable. In case this may involve multiple copies, such as for
  8233. // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
  8234. // indirections into a complex R-value coming from the call to the PCF.
  8235. //
  8236. // 4. Create a barrier.
  8237. //
  8238. // 5/5B. Call the PCF inside an if test for (invocation id == 0).
  8239. TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
  8240. if (patchConstantFunctionPtr == nullptr)
  8241. return;
  8242. TFunction& patchConstantFunction = *patchConstantFunctionPtr;
  8243. const int pcfParamCount = patchConstantFunction.getParamCount();
  8244. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  8245. TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
  8246. int outPatchParam = -1; // -1 means there isn't one.
  8247. // ================ Step 1A: Union Interfaces ================
  8248. // Our patch constant function.
  8249. {
  8250. std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
  8251. std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
  8252. assert(entryPointFunction);
  8253. assert(entryPointFunctionBody);
  8254. findBuiltIns(patchConstantFunction, pcfBuiltIns);
  8255. findBuiltIns(*entryPointFunction, epfBuiltIns);
  8256. // Find the set of built-ins in the PCF that are not present in the entry point.
  8257. std::set<tInterstageIoData> notInEntryPoint;
  8258. notInEntryPoint = pcfBuiltIns;
  8259. // std::set_difference not usable on unordered containers
  8260. for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
  8261. notInEntryPoint.erase(*bi);
  8262. // Now we'll add those to the entry and to the linkage.
  8263. for (int p=0; p<pcfParamCount; ++p) {
  8264. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8265. TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
  8266. // Track whether there is an output patch param
  8267. if (isOutputPatch(patchConstantFunction, p)) {
  8268. if (outPatchParam >= 0) {
  8269. // Presently we only support one per ctrl pt input.
  8270. error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
  8271. return;
  8272. }
  8273. outPatchParam = p;
  8274. }
  8275. if (biType != EbvNone) {
  8276. TType* paramType = patchConstantFunction[p].type->clone();
  8277. if (storage == EvqConstReadOnly) // treated identically to input
  8278. storage = EvqIn;
  8279. // Presently, the only non-built-in we support is InputPatch, which is treated as
  8280. // a pseudo-built-in.
  8281. if (biType == EbvInputPatch) {
  8282. builtInTessLinkageSymbols[biType] = inputPatch;
  8283. } else if (biType == EbvOutputPatch) {
  8284. // Nothing...
  8285. } else {
  8286. // Use the original declaration type for the linkage
  8287. paramType->getQualifier().builtIn = biType;
  8288. if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
  8289. addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
  8290. }
  8291. }
  8292. }
  8293. // If we didn't find it because the shader made one, add our own.
  8294. if (invocationIdSym == nullptr) {
  8295. TType invocationIdType(EbtUint, EvqIn, 1);
  8296. TString* invocationIdName = NewPoolTString("InvocationId");
  8297. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  8298. addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
  8299. }
  8300. assert(invocationIdSym);
  8301. }
  8302. TIntermTyped* pcfArguments = nullptr;
  8303. TVariable* perCtrlPtVar = nullptr;
  8304. // ================ Step 1B: Argument synthesis ================
  8305. // Create pcfArguments for synthesis of patchconstantfunction invocation
  8306. {
  8307. for (int p=0; p<pcfParamCount; ++p) {
  8308. TIntermTyped* inputArg = nullptr;
  8309. if (p == outPatchParam) {
  8310. if (perCtrlPtVar == nullptr) {
  8311. perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
  8312. *patchConstantFunction[outPatchParam].type);
  8313. perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
  8314. }
  8315. inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
  8316. } else {
  8317. // find which built-in it is
  8318. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8319. if (biType == EbvInputPatch && inputPatch == nullptr) {
  8320. error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
  8321. return;
  8322. }
  8323. inputArg = findTessLinkageSymbol(biType);
  8324. if (inputArg == nullptr) {
  8325. error(loc, "unable to find patch constant function built-in variable", "", "");
  8326. return;
  8327. }
  8328. }
  8329. if (pcfParamCount == 1)
  8330. pcfArguments = inputArg;
  8331. else
  8332. pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
  8333. }
  8334. }
  8335. // ================ Step 2: Synthesize call to PCF ================
  8336. TIntermAggregate* pcfCallSequence = nullptr;
  8337. TIntermTyped* pcfCall = nullptr;
  8338. {
  8339. // Create a function call to the patchconstantfunction
  8340. if (pcfArguments)
  8341. addInputArgumentConversions(patchConstantFunction, pcfArguments);
  8342. // Synthetic call.
  8343. pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
  8344. pcfCall->getAsAggregate()->setUserDefined();
  8345. pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
  8346. intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
  8347. patchConstantFunction.getMangledName());
  8348. if (pcfCall->getAsAggregate()) {
  8349. TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
  8350. for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
  8351. TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
  8352. qualifierList.push_back(qual);
  8353. }
  8354. pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
  8355. }
  8356. }
  8357. // ================ Step 2B: Per Control Point synthesis ================
  8358. // If there is per control point data, we must either emulate that with multiple
  8359. // invocations of the entry point to build up an array, or (TODO:) use a yet
  8360. // unavailable extension to look across the SIMD lanes. This is the former
  8361. // as a placeholder for the latter.
  8362. if (outPatchParam >= 0) {
  8363. // We must introduce a local temp variable of the type wanted by the PCF input.
  8364. const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
  8365. if (entryPointFunction->getType().getBasicType() == EbtVoid) {
  8366. error(loc, "entry point must return a value for use with patch constant function", "", "");
  8367. return;
  8368. }
  8369. // Create calls to wrapped main to fill in the array. We will substitute fixed values
  8370. // of invocation ID when calling the wrapped main.
  8371. // This is the type of the each member of the per ctrl point array.
  8372. const TType derefType(perCtrlPtVar->getType(), 0);
  8373. for (int cpt = 0; cpt < arraySize; ++cpt) {
  8374. // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
  8375. // for this function.
  8376. const TString origName = entryPointFunction->getName().substr(1);
  8377. TFunction callee(&origName, TType(EbtVoid));
  8378. TIntermTyped* callingArgs = nullptr;
  8379. for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
  8380. TParameter& param = (*entryPointFunction)[i];
  8381. TType& paramType = *param.type;
  8382. if (paramType.getQualifier().isParamOutput()) {
  8383. error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
  8384. return;
  8385. }
  8386. if (paramType.getQualifier().isParamInput()) {
  8387. TIntermTyped* arg = nullptr;
  8388. if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
  8389. // substitute invocation ID with the array element ID
  8390. arg = intermediate.addConstantUnion(cpt, loc);
  8391. } else {
  8392. TVariable* argVar = makeInternalVariable(*param.name, *param.type);
  8393. argVar->getWritableType().getQualifier().makeTemporary();
  8394. arg = intermediate.addSymbol(*argVar);
  8395. }
  8396. handleFunctionArgument(&callee, callingArgs, arg);
  8397. }
  8398. }
  8399. // Call and assign to per ctrl point variable
  8400. currentCaller = intermediate.getEntryPointMangledName().c_str();
  8401. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  8402. TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
  8403. TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
  8404. TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
  8405. element->setType(derefType);
  8406. element->setLoc(loc);
  8407. pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
  8408. handleAssign(loc, EOpAssign, element, callReturn));
  8409. }
  8410. }
  8411. // ================ Step 3: Create return Sequence ================
  8412. // Return sequence: copy PCF result to a temporary, then to shader output variable.
  8413. if (pcfCall->getBasicType() != EbtVoid) {
  8414. const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
  8415. TType outType; // output type that goes with the return type.
  8416. outType.shallowCopy(*retType);
  8417. // substitute the output type
  8418. const auto newLists = ioTypeMap.find(retType->getStruct());
  8419. if (newLists != ioTypeMap.end())
  8420. outType.setStruct(newLists->second.output);
  8421. // Substitute the top level type's built-in type
  8422. if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
  8423. outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
  8424. outType.getQualifier().patch = true; // make it a per-patch variable
  8425. TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
  8426. pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
  8427. if (pcfOutput->getType().containsBuiltIn())
  8428. split(*pcfOutput);
  8429. assignToInterface(*pcfOutput);
  8430. TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
  8431. // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
  8432. // repeated calls to the PCF:
  8433. TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
  8434. pcfCallResult->getWritableType().getQualifier().makeTemporary();
  8435. TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
  8436. TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
  8437. TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
  8438. intermediate.addSymbol(*pcfCallResult, loc));
  8439. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
  8440. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
  8441. } else {
  8442. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
  8443. }
  8444. // ================ Step 4: Barrier ================
  8445. TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
  8446. barrier->setLoc(loc);
  8447. barrier->setType(TType(EbtVoid));
  8448. epBodySeq.insert(epBodySeq.end(), barrier);
  8449. // ================ Step 5: Test on invocation ID ================
  8450. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  8451. TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
  8452. // ================ Step 5B: Create if statement on Invocation ID == 0 ================
  8453. intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
  8454. TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
  8455. invocationIdTest->setLoc(loc);
  8456. // add our test sequence before the return.
  8457. epBodySeq.insert(epBodySeq.end(), invocationIdTest);
  8458. }
  8459. // Finalization step: remove unused buffer blocks from linkage (we don't know until the
  8460. // shader is entirely compiled).
  8461. // Preserve order of remaining symbols.
  8462. void HlslParseContext::removeUnusedStructBufferCounters()
  8463. {
  8464. const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
  8465. [this](const TSymbol* sym) {
  8466. const auto sbcIt = structBufferCounter.find(sym->getName());
  8467. return sbcIt != structBufferCounter.end() && !sbcIt->second;
  8468. });
  8469. linkageSymbols.erase(endIt, linkageSymbols.end());
  8470. }
  8471. // Finalization step: patch texture shadow modes to match samplers they were combined with
  8472. void HlslParseContext::fixTextureShadowModes()
  8473. {
  8474. for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
  8475. TSampler& sampler = (*symbol)->getWritableType().getSampler();
  8476. if (sampler.isTexture()) {
  8477. const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
  8478. if (shadowMode != textureShadowVariant.end()) {
  8479. if (shadowMode->second->overloaded())
  8480. // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
  8481. intermediate.setNeedsLegalization();
  8482. sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
  8483. }
  8484. }
  8485. }
  8486. }
  8487. // Finalization step: patch append methods to use proper stream output, which isn't known until
  8488. // main is parsed, which could happen after the append method is parsed.
  8489. void HlslParseContext::finalizeAppendMethods()
  8490. {
  8491. TSourceLoc loc;
  8492. loc.init();
  8493. // Nothing to do: bypass test for valid stream output.
  8494. if (gsAppends.empty())
  8495. return;
  8496. if (gsStreamOutput == nullptr) {
  8497. error(loc, "unable to find output symbol for Append()", "", "");
  8498. return;
  8499. }
  8500. // Patch append sequences, now that we know the stream output symbol.
  8501. for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
  8502. append->node->getSequence()[0] =
  8503. handleAssign(append->loc, EOpAssign,
  8504. intermediate.addSymbol(*gsStreamOutput, append->loc),
  8505. append->node->getSequence()[0]->getAsTyped());
  8506. }
  8507. }
  8508. // post-processing
  8509. void HlslParseContext::finish()
  8510. {
  8511. // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
  8512. // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
  8513. if (! mipsOperatorMipArg.empty()) {
  8514. error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
  8515. }
  8516. removeUnusedStructBufferCounters();
  8517. addPatchConstantInvocation();
  8518. fixTextureShadowModes();
  8519. finalizeAppendMethods();
  8520. // Communicate out (esp. for command line) that we formed AST that will make
  8521. // illegal AST SPIR-V and it needs transforms to legalize it.
  8522. if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
  8523. infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
  8524. TParseContextBase::finish();
  8525. }
  8526. } // end namespace glslang