SpirvEmitter.cpp 496 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406
  1. //===------- SpirvEmitter.cpp - SPIR-V Binary Code Emitter ------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a SPIR-V emitter class that takes in HLSL AST and emits
  10. // SPIR-V binary words.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SpirvEmitter.h"
  14. #include "AlignmentSizeCalculator.h"
  15. #include "RawBufferMethods.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "spirv-tools/optimizer.hpp"
  18. #include "clang/SPIRV/AstTypeProbe.h"
  19. #include "clang/Sema/Sema.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "InitListHandler.h"
  22. #include "dxc/DXIL/DxilConstants.h"
  23. #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO
  24. #include "clang/Basic/Version.h"
  25. #else
  26. namespace clang {
  27. uint32_t getGitCommitCount() { return 0; }
  28. const char *getGitCommitHash() { return "<unknown-hash>"; }
  29. } // namespace clang
  30. #endif // SUPPORT_QUERY_GIT_COMMIT_INFO
  31. namespace clang {
  32. namespace spirv {
  33. namespace {
  34. // Returns true if the given decl is an implicit variable declaration inside the
  35. // "vk" namespace.
  36. bool isImplicitVarDeclInVkNamespace(const Decl *decl) {
  37. if (!decl)
  38. return false;
  39. if (auto *varDecl = dyn_cast<VarDecl>(decl)) {
  40. // Check whether it is implicitly defined.
  41. if (!decl->isImplicit())
  42. return false;
  43. if (auto *nsDecl = dyn_cast<NamespaceDecl>(varDecl->getDeclContext()))
  44. if (nsDecl->getName().equals("vk"))
  45. return true;
  46. }
  47. return false;
  48. }
  49. // Returns true if the given decl has the given semantic.
  50. bool hasSemantic(const DeclaratorDecl *decl,
  51. hlsl::DXIL::SemanticKind semanticKind) {
  52. using namespace hlsl;
  53. for (auto *annotation : decl->getUnusualAnnotations()) {
  54. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  55. llvm::StringRef semanticName;
  56. uint32_t semanticIndex = 0;
  57. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  58. &semanticIndex);
  59. const auto *semantic = Semantic::GetByName(semanticName);
  60. if (semantic->GetKind() == semanticKind)
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. const ParmVarDecl *patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  67. for (const auto *param : pcf->parameters())
  68. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  69. return param;
  70. return nullptr;
  71. }
  72. inline bool isSpirvMatrixOp(spv::Op opcode) {
  73. return opcode == spv::Op::OpMatrixTimesMatrix ||
  74. opcode == spv::Op::OpMatrixTimesVector ||
  75. opcode == spv::Op::OpMatrixTimesScalar;
  76. }
  77. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  78. /// index. Otherwiser, returns false.
  79. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  80. // duplicate of doCXXMemberCallExpr.
  81. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  82. using namespace hlsl;
  83. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  84. const auto *callee = indexing->getDirectCallee();
  85. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  86. llvm::StringRef group;
  87. if (GetIntrinsicOp(callee, opcode, group)) {
  88. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  89. const auto *object = indexing->getImplicitObjectArgument();
  90. if (isStructuredBuffer(object->getType())) {
  91. *index = indexing->getArg(0);
  92. return indexing->getImplicitObjectArgument();
  93. }
  94. }
  95. }
  96. }
  97. return nullptr;
  98. }
  99. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  100. /// not in the Private or Function storage class.
  101. inline bool isExternalVar(const VarDecl *var) {
  102. // Class static variables should be put in the Private storage class.
  103. // groupshared variables are allowed to be declared as "static". But we still
  104. // need to put them in the Workgroup storage class. That is, when seeing
  105. // "static groupshared", ignore "static".
  106. return var->hasExternalFormalLinkage()
  107. ? !var->isStaticDataMember()
  108. : (var->getAttr<HLSLGroupSharedAttr>() != nullptr);
  109. }
  110. /// Returns the referenced variable's DeclContext if the given expr is
  111. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  112. /// returns nullptr.
  113. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  114. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  115. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  116. if (isConstantTextureBuffer(varDecl->getType()))
  117. return hlsl::GetHLSLResourceResultType(varDecl->getType())
  118. ->getAs<RecordType>()
  119. ->getDecl();
  120. return nullptr;
  121. }
  122. /// Returns true if
  123. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  124. /// buffer and it is non-alias one, or
  125. /// * the given expr is an CallExpr returning a kind of structured or byte
  126. /// buffer.
  127. /// * the given expr is an ArraySubscriptExpr referencing a kind of structured
  128. /// or byte buffer.
  129. ///
  130. /// Note: legalization specific code
  131. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  132. expr = expr->IgnoreParenCasts();
  133. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  134. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  135. if (isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  136. return isExternalVar(varDecl);
  137. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  138. if (isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  139. return true;
  140. } else if (const auto *arrSubExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  141. return isReferencingNonAliasStructuredOrByteBuffer(arrSubExpr->getBase());
  142. }
  143. return false;
  144. }
  145. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  146. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  147. using namespace hlsl;
  148. using namespace spv;
  149. switch (opcode) {
  150. case IntrinsicOp::IOP_InterlockedAdd:
  151. case IntrinsicOp::MOP_InterlockedAdd:
  152. return Op::OpAtomicIAdd;
  153. case IntrinsicOp::IOP_InterlockedAnd:
  154. case IntrinsicOp::MOP_InterlockedAnd:
  155. return Op::OpAtomicAnd;
  156. case IntrinsicOp::IOP_InterlockedOr:
  157. case IntrinsicOp::MOP_InterlockedOr:
  158. return Op::OpAtomicOr;
  159. case IntrinsicOp::IOP_InterlockedXor:
  160. case IntrinsicOp::MOP_InterlockedXor:
  161. return Op::OpAtomicXor;
  162. case IntrinsicOp::IOP_InterlockedUMax:
  163. case IntrinsicOp::MOP_InterlockedUMax:
  164. return Op::OpAtomicUMax;
  165. case IntrinsicOp::IOP_InterlockedUMin:
  166. case IntrinsicOp::MOP_InterlockedUMin:
  167. return Op::OpAtomicUMin;
  168. case IntrinsicOp::IOP_InterlockedMax:
  169. case IntrinsicOp::MOP_InterlockedMax:
  170. return Op::OpAtomicSMax;
  171. case IntrinsicOp::IOP_InterlockedMin:
  172. case IntrinsicOp::MOP_InterlockedMin:
  173. return Op::OpAtomicSMin;
  174. case IntrinsicOp::IOP_InterlockedExchange:
  175. case IntrinsicOp::MOP_InterlockedExchange:
  176. return Op::OpAtomicExchange;
  177. default:
  178. // Only atomic opcodes are relevant.
  179. break;
  180. }
  181. assert(false && "unimplemented hlsl intrinsic opcode");
  182. return Op::Max;
  183. }
  184. // Returns true if the given opcode is an accepted binary opcode in
  185. // OpSpecConstantOp.
  186. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  187. switch (op) {
  188. case spv::Op::OpIAdd:
  189. case spv::Op::OpISub:
  190. case spv::Op::OpIMul:
  191. case spv::Op::OpUDiv:
  192. case spv::Op::OpSDiv:
  193. case spv::Op::OpUMod:
  194. case spv::Op::OpSRem:
  195. case spv::Op::OpSMod:
  196. case spv::Op::OpShiftRightLogical:
  197. case spv::Op::OpShiftRightArithmetic:
  198. case spv::Op::OpShiftLeftLogical:
  199. case spv::Op::OpBitwiseOr:
  200. case spv::Op::OpBitwiseXor:
  201. case spv::Op::OpBitwiseAnd:
  202. case spv::Op::OpVectorShuffle:
  203. case spv::Op::OpCompositeExtract:
  204. case spv::Op::OpCompositeInsert:
  205. case spv::Op::OpLogicalOr:
  206. case spv::Op::OpLogicalAnd:
  207. case spv::Op::OpLogicalNot:
  208. case spv::Op::OpLogicalEqual:
  209. case spv::Op::OpLogicalNotEqual:
  210. case spv::Op::OpIEqual:
  211. case spv::Op::OpINotEqual:
  212. case spv::Op::OpULessThan:
  213. case spv::Op::OpSLessThan:
  214. case spv::Op::OpUGreaterThan:
  215. case spv::Op::OpSGreaterThan:
  216. case spv::Op::OpULessThanEqual:
  217. case spv::Op::OpSLessThanEqual:
  218. case spv::Op::OpUGreaterThanEqual:
  219. case spv::Op::OpSGreaterThanEqual:
  220. return true;
  221. default:
  222. // Accepted binary opcodes return true. Anything else is false.
  223. return false;
  224. }
  225. return false;
  226. }
  227. /// Returns true if the given expression is an accepted initializer for a spec
  228. /// constant.
  229. bool isAcceptedSpecConstantInit(const Expr *init) {
  230. // Allow numeric casts
  231. init = init->IgnoreParenCasts();
  232. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  233. isa<FloatingLiteral>(init))
  234. return true;
  235. // Allow the minus operator which is used to specify negative values
  236. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  237. return unaryOp->getOpcode() == UO_Minus &&
  238. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  239. return false;
  240. }
  241. /// Returns true if the given function parameter can act as shader stage
  242. /// input parameter.
  243. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  244. // If the parameter has no in/out/inout attribute, it is defaulted to
  245. // an in parameter.
  246. return !param->hasAttr<HLSLOutAttr>() &&
  247. // GS output streams are marked as inout, but it should not be
  248. // used as in parameter.
  249. !hlsl::IsHLSLStreamOutputType(param->getType());
  250. }
  251. /// Returns true if the given function parameter can act as shader stage
  252. /// output parameter.
  253. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  254. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>() ||
  255. hlsl::IsHLSLRayQueryType(param->getType());
  256. }
  257. /// Returns true if the given expression is of builtin type and can be evaluated
  258. /// to a constant zero. Returns false otherwise.
  259. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  260. const auto type = expr->getType();
  261. if (!type->isBuiltinType())
  262. return false;
  263. Expr::EvalResult evalResult;
  264. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  265. !evalResult.HasSideEffects) {
  266. const auto &val = evalResult.Val;
  267. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  268. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  269. (type->isFloatingType() && val.getFloat().isZero()));
  270. }
  271. return false;
  272. }
  273. /// Returns the real definition of the callee of the given CallExpr.
  274. ///
  275. /// If we are calling a forward-declared function, callee will be the
  276. /// FunctionDecl for the foward-declared function, not the actual
  277. /// definition. The foward-delcaration and defintion are two completely
  278. /// different AST nodes.
  279. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  280. const auto *callee = expr->getDirectCallee();
  281. if (callee->isThisDeclarationADefinition())
  282. return callee;
  283. // We need to update callee to the actual definition here
  284. if (!callee->isDefined(callee))
  285. return nullptr;
  286. return callee;
  287. }
  288. /// Returns the referenced definition. The given expr is expected to be a
  289. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  290. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  291. if (!expr)
  292. return nullptr;
  293. expr = expr->IgnoreParenCasts();
  294. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  295. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  296. }
  297. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  298. return getCalleeDefinition(callExpr);
  299. }
  300. return nullptr;
  301. }
  302. /// Returns the number of base classes if this type is a derived class/struct.
  303. /// Returns zero otherwise.
  304. inline uint32_t getNumBaseClasses(QualType type) {
  305. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  306. return cxxDecl->getNumBases();
  307. return 0;
  308. }
  309. /// Gets the index sequence of casting a derived object to a base object by
  310. /// following the cast chain.
  311. void getBaseClassIndices(const CastExpr *expr,
  312. llvm::SmallVectorImpl<uint32_t> *indices) {
  313. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  314. expr->getCastKind() == CK_HLSLDerivedToBase);
  315. indices->clear();
  316. QualType derivedType = expr->getSubExpr()->getType();
  317. // There are two types of UncheckedDerivedToBase/HLSLDerivedToBase casts:
  318. //
  319. // The first is when a derived object tries to access a member in the base.
  320. // For example: derived.base_member.
  321. // ImplicitCastExpr 'Base' lvalue <UncheckedDerivedToBase (Base)>
  322. // `-DeclRefExpr 'Derived' lvalue Var 0x1f0d9bb2890 'derived' 'Derived'
  323. //
  324. // The second is when a pointer of the dervied is used to access members or
  325. // methods of the base. There are currently no pointers in HLSL, but the
  326. // method defintions can use the "this" pointer.
  327. // For example:
  328. // class Base { float value; };
  329. // class Derviced : Base {
  330. // float4 getBaseValue() { return value; }
  331. // };
  332. //
  333. // In this example, the 'this' pointer (pointing to Derived) is used inside
  334. // 'getBaseValue', which is then cast to a Base pointer:
  335. //
  336. // ImplicitCastExpr 'Base *' <UncheckedDerivedToBase (Base)>
  337. // `-CXXThisExpr 'Derviced *' this
  338. //
  339. // Therefore in order to obtain the derivedDecl below, we must make sure that
  340. // we handle the second case too by using the pointee type.
  341. if (derivedType->isPointerType())
  342. derivedType = derivedType->getPointeeType();
  343. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  344. // Go through the base cast chain: for each of the derived to base cast, find
  345. // the index of the base in question in the derived's bases.
  346. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  347. pathIt != pathIe; ++pathIt) {
  348. // The type of the base in question
  349. const auto baseType = (*pathIt)->getType();
  350. uint32_t index = 0;
  351. for (auto baseIt = derivedDecl->bases_begin(),
  352. baseIe = derivedDecl->bases_end();
  353. baseIt != baseIe; ++baseIt, ++index)
  354. if (baseIt->getType() == baseType) {
  355. indices->push_back(index);
  356. break;
  357. }
  358. assert(index < derivedDecl->getNumBases());
  359. // Continue to proceed the next base in the chain
  360. derivedType = baseType;
  361. if (derivedType->isPointerType())
  362. derivedType = derivedType->getPointeeType();
  363. derivedDecl = derivedType->getAsCXXRecordDecl();
  364. }
  365. }
  366. std::string getNamespacePrefix(const Decl *decl) {
  367. std::string nsPrefix = "";
  368. const DeclContext *dc = decl->getDeclContext();
  369. while (dc && !dc->isTranslationUnit()) {
  370. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  371. if (!ns->isAnonymousNamespace()) {
  372. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  373. }
  374. }
  375. dc = dc->getParent();
  376. }
  377. return nsPrefix;
  378. }
  379. std::string getFnName(const FunctionDecl *fn) {
  380. // Prefix the function name with the struct name if necessary
  381. std::string classOrStructName = "";
  382. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  383. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  384. classOrStructName = st->getName().str() + ".";
  385. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  386. }
  387. bool isMemoryObjectDeclaration(SpirvInstruction *inst) {
  388. return isa<SpirvVariable>(inst) || isa<SpirvFunctionParameter>(inst);
  389. }
  390. } // namespace
  391. SpirvEmitter::SpirvEmitter(CompilerInstance &ci)
  392. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  393. diags(ci.getDiagnostics()),
  394. spirvOptions(ci.getCodeGenOpts().SpirvOptions),
  395. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction), spvContext(),
  396. featureManager(diags, spirvOptions),
  397. spvBuilder(astContext, spvContext, spirvOptions),
  398. declIdMapper(astContext, spvContext, spvBuilder, *this, featureManager,
  399. spirvOptions),
  400. entryFunction(nullptr), curFunction(nullptr), curThis(nullptr),
  401. seenPushConstantAt(), isSpecConstantMode(false), needsLegalization(false),
  402. beforeHlslLegalization(false), mainSourceFile(nullptr) {
  403. // Get ShaderModel from command line hlsl profile option.
  404. const hlsl::ShaderModel *shaderModel =
  405. hlsl::ShaderModel::GetByName(ci.getCodeGenOpts().HLSLProfile.c_str());
  406. if (shaderModel->GetKind() == hlsl::ShaderModel::Kind::Invalid)
  407. emitError("unknown shader module: %0", {}) << shaderModel->GetName();
  408. if (spirvOptions.invertY && !shaderModel->IsVS() && !shaderModel->IsDS() &&
  409. !shaderModel->IsGS())
  410. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  411. if (spirvOptions.useGlLayout && spirvOptions.useDxLayout)
  412. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  413. {});
  414. // Set shader model kind and hlsl major/minor version.
  415. spvContext.setCurrentShaderModelKind(shaderModel->GetKind());
  416. spvContext.setMajorVersion(shaderModel->GetMajor());
  417. spvContext.setMinorVersion(shaderModel->GetMinor());
  418. if (spirvOptions.useDxLayout) {
  419. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  420. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  421. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::FxcSBuffer;
  422. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::FxcSBuffer;
  423. } else if (spirvOptions.useGlLayout) {
  424. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::GLSLStd140;
  425. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  426. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  427. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::GLSLStd430;
  428. } else if (spirvOptions.useScalarLayout) {
  429. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::Scalar;
  430. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::Scalar;
  431. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::Scalar;
  432. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::Scalar;
  433. } else {
  434. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd140;
  435. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  436. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  437. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  438. }
  439. // Set shader module version, source file name, and source file content (if
  440. // needed).
  441. llvm::StringRef source;
  442. std::vector<llvm::StringRef> fileNames;
  443. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  444. // File name
  445. if (spirvOptions.debugInfoFile && !inputFiles.empty()) {
  446. for (const auto &inputFile : inputFiles) {
  447. fileNames.push_back(inputFile.getFile());
  448. }
  449. }
  450. // Source code
  451. if (spirvOptions.debugInfoSource) {
  452. const auto &sm = ci.getSourceManager();
  453. const llvm::MemoryBuffer *mainFile =
  454. sm.getBuffer(sm.getMainFileID(), SourceLocation());
  455. source = StringRef(mainFile->getBufferStart(), mainFile->getBufferSize());
  456. }
  457. mainSourceFile = spvBuilder.setDebugSource(spvContext.getMajorVersion(),
  458. spvContext.getMinorVersion(),
  459. fileNames, source);
  460. // OpenCL.DebugInfo.100 DebugSource
  461. if (spirvOptions.debugInfoRich) {
  462. auto *dbgSrc = spvBuilder.createDebugSource(mainSourceFile->getString());
  463. // spvContext.getDebugInfo().insert() inserts {string key, RichDebugInfo}
  464. // pair and returns {{string key, RichDebugInfo}, true /*Success*/}.
  465. // spvContext.getDebugInfo().insert().first->second is a RichDebugInfo.
  466. auto *richDebugInfo =
  467. &spvContext.getDebugInfo()
  468. .insert(
  469. {mainSourceFile->getString(),
  470. RichDebugInfo(dbgSrc,
  471. spvBuilder.createDebugCompilationUnit(dbgSrc))})
  472. .first->second;
  473. spvContext.pushDebugLexicalScope(richDebugInfo,
  474. richDebugInfo->scopeStack.back());
  475. }
  476. if (spirvOptions.debugInfoTool &&
  477. featureManager.isTargetEnvVulkan1p1OrAbove()) {
  478. // Emit OpModuleProcessed to indicate the commit information.
  479. std::string commitHash =
  480. std::string("dxc-commit-hash: ") + clang::getGitCommitHash();
  481. spvBuilder.addModuleProcessed(commitHash);
  482. // Emit OpModuleProcessed to indicate the command line options that were
  483. // used to generate this module.
  484. if (!spirvOptions.clOptions.empty()) {
  485. // Using this format: "dxc-cl-option: XXXXXX"
  486. std::string clOptionStr = "dxc-cl-option:" + spirvOptions.clOptions;
  487. spvBuilder.addModuleProcessed(clOptionStr);
  488. }
  489. }
  490. }
  491. void SpirvEmitter::HandleTranslationUnit(ASTContext &context) {
  492. // Stop translating if there are errors in previous compilation stages.
  493. if (context.getDiagnostics().hasErrorOccurred())
  494. return;
  495. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  496. uint32_t numEntryPoints = 0;
  497. // The entry function is the seed of the queue.
  498. for (auto *decl : tu->decls()) {
  499. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  500. if (spvContext.isLib()) {
  501. if (const auto *shaderAttr = funcDecl->getAttr<HLSLShaderAttr>()) {
  502. // If we are compiling as a library then add everything that has a
  503. // ShaderAttr.
  504. addFunctionToWorkQueue(getShaderModelKind(shaderAttr->getStage()),
  505. funcDecl, /*isEntryFunction*/ true);
  506. numEntryPoints++;
  507. } else if (funcDecl->getAttr<HLSLExportAttr>()) {
  508. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
  509. funcDecl, /*isEntryFunction*/ false);
  510. }
  511. } else {
  512. if (funcDecl->getName() == entryFunctionName) {
  513. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
  514. funcDecl, /*isEntryFunction*/ true);
  515. numEntryPoints++;
  516. }
  517. }
  518. } else {
  519. doDecl(decl);
  520. }
  521. if (context.getDiagnostics().hasErrorOccurred())
  522. return;
  523. }
  524. // Translate all functions reachable from the entry function.
  525. // The queue can grow in the meanwhile; so need to keep evaluating
  526. // workQueue.size().
  527. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  528. const FunctionInfo *curEntryOrCallee = workQueue[i];
  529. spvContext.setCurrentShaderModelKind(curEntryOrCallee->shaderModelKind);
  530. doDecl(curEntryOrCallee->funcDecl);
  531. if (context.getDiagnostics().hasErrorOccurred())
  532. return;
  533. }
  534. // Addressing and memory model are required in a valid SPIR-V module.
  535. spvBuilder.setMemoryModel(spv::AddressingModel::Logical,
  536. spv::MemoryModel::GLSL450);
  537. // Even though the 'workQueue' grows due to the above loop, the first
  538. // 'numEntryPoints' entries in the 'workQueue' are the ones with the HLSL
  539. // 'shader' attribute, and must therefore be entry functions.
  540. assert(numEntryPoints <= workQueue.size());
  541. for (uint32_t i = 0; i < numEntryPoints; ++i) {
  542. // TODO: assign specific StageVars w.r.t. to entry point
  543. const FunctionInfo *entryInfo = workQueue[i];
  544. assert(entryInfo->isEntryFunction);
  545. spvBuilder.addEntryPoint(
  546. getSpirvShaderStage(entryInfo->shaderModelKind),
  547. entryInfo->entryFunction, entryInfo->funcDecl->getName(),
  548. featureManager.isTargetEnvVulkan1p2OrAbove()
  549. ? spvBuilder.getModule()->getVariables()
  550. : llvm::ArrayRef<SpirvVariable *>(declIdMapper.collectStageVars()));
  551. }
  552. // Add Location decorations to stage input/output variables.
  553. if (!declIdMapper.decorateStageIOLocations())
  554. return;
  555. // Add descriptor set and binding decorations to resource variables.
  556. if (!declIdMapper.decorateResourceBindings())
  557. return;
  558. // Add Coherent docrations to resource variables.
  559. if (!declIdMapper.decorateResourceCoherent())
  560. return;
  561. // Output the constructed module.
  562. std::vector<uint32_t> m = spvBuilder.takeModule();
  563. if (!spirvOptions.codeGenHighLevel) {
  564. // In order to flatten composite resources, we must also unroll loops.
  565. // Therefore we should run legalization before optimization.
  566. needsLegalization = needsLegalization ||
  567. declIdMapper.requiresLegalization() ||
  568. spirvOptions.flattenResourceArrays ||
  569. declIdMapper.requiresFlatteningCompositeResources();
  570. // Run legalization passes
  571. if (needsLegalization) {
  572. std::string messages;
  573. if (!spirvToolsLegalize(&m, &messages)) {
  574. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  575. emitNote("please file a bug report on "
  576. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  577. "with source code if possible",
  578. {});
  579. return;
  580. } else if (!messages.empty()) {
  581. emitWarning("SPIR-V legalization: %0", {}) << messages;
  582. }
  583. }
  584. // Run optimization passes
  585. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  586. std::string messages;
  587. if (!spirvToolsOptimize(&m, &messages)) {
  588. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  589. emitNote("please file a bug report on "
  590. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  591. "with source code if possible",
  592. {});
  593. return;
  594. }
  595. }
  596. }
  597. // Validate the generated SPIR-V code
  598. if (!spirvOptions.disableValidation) {
  599. std::string messages;
  600. if (!spirvToolsValidate(&m, &messages)) {
  601. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  602. emitNote("please file a bug report on "
  603. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  604. "with source code if possible",
  605. {});
  606. return;
  607. }
  608. }
  609. theCompilerInstance.getOutStream()->write(
  610. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  611. }
  612. void SpirvEmitter::doDecl(const Decl *decl) {
  613. if (isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  614. return;
  615. // Implicit decls are lazily created when needed.
  616. if (decl->isImplicit()) {
  617. return;
  618. }
  619. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  620. doVarDecl(varDecl);
  621. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  622. for (auto *subDecl : namespaceDecl->decls())
  623. // Note: We only emit functions as they are discovered through the call
  624. // graph starting from the entry-point. We should not emit unused
  625. // functions inside namespaces.
  626. if (!isa<FunctionDecl>(subDecl))
  627. doDecl(subDecl);
  628. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  629. doFunctionDecl(funcDecl);
  630. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  631. doHLSLBufferDecl(bufferDecl);
  632. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  633. doRecordDecl(recordDecl);
  634. } else if (const auto *enumDecl = dyn_cast<EnumDecl>(decl)) {
  635. doEnumDecl(enumDecl);
  636. } else if (const auto *classTemplateDecl =
  637. dyn_cast<ClassTemplateDecl>(decl)) {
  638. doClassTemplateDecl(classTemplateDecl);
  639. } else if (const auto *functionTemplateDecl =
  640. dyn_cast<FunctionTemplateDecl>(decl)) {
  641. // nothing to do.
  642. } else {
  643. emitError("decl type %0 unimplemented", decl->getLocation())
  644. << decl->getDeclKindName();
  645. }
  646. }
  647. RichDebugInfo *
  648. SpirvEmitter::getOrCreateRichDebugInfo(const SourceLocation &loc) {
  649. const StringRef file =
  650. astContext.getSourceManager().getPresumedLoc(loc).getFilename();
  651. auto &debugInfo = spvContext.getDebugInfo();
  652. auto it = debugInfo.find(file);
  653. if (it != debugInfo.end())
  654. return &it->second;
  655. auto *dbgSrc = spvBuilder.createDebugSource(file);
  656. // debugInfo.insert() inserts {string key, RichDebugInfo} pair and
  657. // returns {{string key, RichDebugInfo}, true /*Success*/}.
  658. // debugInfo.insert().first->second is a RichDebugInfo.
  659. return &debugInfo
  660. .insert({file, RichDebugInfo(
  661. dbgSrc, spvBuilder.createDebugCompilationUnit(
  662. dbgSrc))})
  663. .first->second;
  664. }
  665. void SpirvEmitter::doStmt(const Stmt *stmt,
  666. llvm::ArrayRef<const Attr *> attrs) {
  667. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  668. if (spirvOptions.debugInfoRich) {
  669. // Any opening of curly braces ('{') starts a CompoundStmt in the AST
  670. // tree. It also means we have a new lexical block!
  671. const auto loc = stmt->getLocStart();
  672. const auto &sm = astContext.getSourceManager();
  673. const uint32_t line = sm.getPresumedLineNumber(loc);
  674. const uint32_t column = sm.getPresumedColumnNumber(loc);
  675. RichDebugInfo *info = getOrCreateRichDebugInfo(loc);
  676. auto *debugLexicalBlock = spvBuilder.createDebugLexicalBlock(
  677. info->source, line, column, info->scopeStack.back());
  678. // Add this lexical block to the stack of lexical scopes.
  679. spvContext.pushDebugLexicalScope(info, debugLexicalBlock);
  680. // Update or add DebugScope.
  681. if (spvBuilder.getInsertPoint()->empty()) {
  682. spvBuilder.getInsertPoint()->updateDebugScope(
  683. new (spvContext) SpirvDebugScope(debugLexicalBlock));
  684. } else if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  685. spvBuilder.createDebugScope(debugLexicalBlock);
  686. }
  687. // Iterate over sub-statements
  688. for (auto *st : compoundStmt->body())
  689. doStmt(st);
  690. // We are done with processing this compound statement. Remove its lexical
  691. // block from the stack of lexical scopes.
  692. spvContext.popDebugLexicalScope(info);
  693. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  694. spvBuilder.createDebugScope(spvContext.getCurrentLexicalScope());
  695. }
  696. } else {
  697. // Iterate over sub-statements
  698. for (auto *st : compoundStmt->body())
  699. doStmt(st);
  700. }
  701. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  702. doReturnStmt(retStmt);
  703. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  704. doDeclStmt(declStmt);
  705. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  706. doIfStmt(ifStmt, attrs);
  707. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  708. doSwitchStmt(switchStmt, attrs);
  709. } else if (dyn_cast<CaseStmt>(stmt)) {
  710. processCaseStmtOrDefaultStmt(stmt);
  711. } else if (dyn_cast<DefaultStmt>(stmt)) {
  712. processCaseStmtOrDefaultStmt(stmt);
  713. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  714. doBreakStmt(breakStmt);
  715. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  716. doDoStmt(theDoStmt, attrs);
  717. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  718. doDiscardStmt(discardStmt);
  719. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  720. doContinueStmt(continueStmt);
  721. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  722. doWhileStmt(whileStmt, attrs);
  723. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  724. doForStmt(forStmt, attrs);
  725. } else if (dyn_cast<NullStmt>(stmt)) {
  726. // For the null statement ";". We don't need to do anything.
  727. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  728. // All cases for expressions used as statements
  729. doExpr(expr);
  730. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  731. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  732. } else {
  733. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  734. << stmt->getStmtClassName() << stmt->getSourceRange();
  735. }
  736. }
  737. SpirvInstruction *SpirvEmitter::doExpr(const Expr *expr) {
  738. SpirvInstruction *result = nullptr;
  739. expr = expr->IgnoreParens();
  740. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  741. auto *decl = declRefExpr->getDecl();
  742. if (isImplicitVarDeclInVkNamespace(declRefExpr->getDecl())) {
  743. result = doExpr(cast<VarDecl>(decl)->getInit());
  744. } else {
  745. result = declIdMapper.getDeclEvalInfo(decl, expr->getLocStart());
  746. }
  747. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  748. result = doMemberExpr(memberExpr);
  749. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  750. result = doCastExpr(castExpr);
  751. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  752. result = doInitListExpr(initListExpr);
  753. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  754. result =
  755. spvBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  756. result->setRValue();
  757. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  758. result = translateAPInt(intLiteral->getValue(), expr->getType());
  759. result->setRValue();
  760. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  761. result = translateAPFloat(floatLiteral->getValue(), expr->getType());
  762. result->setRValue();
  763. } else if (const auto *stringLiteral = dyn_cast<StringLiteral>(expr)) {
  764. result = spvBuilder.getString(stringLiteral->getString());
  765. } else if (const auto *compoundAssignOp =
  766. dyn_cast<CompoundAssignOperator>(expr)) {
  767. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  768. // checked before BinaryOperator.
  769. result = doCompoundAssignOperator(compoundAssignOp);
  770. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  771. result = doBinaryOperator(binOp);
  772. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  773. result = doUnaryOperator(unaryOp);
  774. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  775. result = doHLSLVectorElementExpr(vecElemExpr);
  776. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  777. result = doExtMatrixElementExpr(matElemExpr);
  778. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  779. result = doCallExpr(funcCall);
  780. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  781. result = doArraySubscriptExpr(subscriptExpr);
  782. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  783. result = doConditionalOperator(condExpr);
  784. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  785. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  786. } else if (isa<CXXThisExpr>(expr)) {
  787. assert(curThis);
  788. result = curThis;
  789. } else if (isa<CXXConstructExpr>(expr)) {
  790. result = curThis;
  791. } else if (const auto *unaryExpr = dyn_cast<UnaryExprOrTypeTraitExpr>(expr)) {
  792. result = doUnaryExprOrTypeTraitExpr(unaryExpr);
  793. } else {
  794. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  795. << expr->getStmtClassName() << expr->getSourceRange();
  796. }
  797. return result;
  798. }
  799. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr) {
  800. // We are trying to load the value here, which is what an LValueToRValue
  801. // implicit cast is intended to do. We can ignore the cast if exists.
  802. expr = expr->IgnoreParenLValueCasts();
  803. return loadIfGLValue(expr, doExpr(expr));
  804. }
  805. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr,
  806. SpirvInstruction *info) {
  807. const auto exprType = expr->getType();
  808. // Do nothing if this is already rvalue
  809. if (!info || info->isRValue())
  810. return info;
  811. // Check whether we are trying to load an array of opaque objects as a whole.
  812. // If true, we are likely to copy it as a whole. To assist per-element
  813. // copying, avoid the load here and return the pointer directly.
  814. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  815. if (isOpaqueArrayType(exprType))
  816. return info;
  817. // Check whether we are trying to load an externally visible structured/byte
  818. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  819. // the load and write the pointer directly to the alias variable then.
  820. //
  821. // Also for the case of alias function returns. If we are trying to load an
  822. // alias function return as a whole, it means we are assigning it to another
  823. // alias variable. Avoid the load and write the pointer directly.
  824. //
  825. // Note: legalization specific code
  826. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  827. return info;
  828. }
  829. if (loadIfAliasVarRef(expr, &info)) {
  830. // We are loading an alias variable as a whole here. This is likely for
  831. // wholesale assignments or function returns. Need to load the pointer.
  832. //
  833. // Note: legalization specific code
  834. return info;
  835. }
  836. SpirvInstruction *loadedInstr = nullptr;
  837. // TODO: Ouch. Very hacky. We need special path to get the value type if
  838. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  839. // type translation path won't work.
  840. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  841. loadedInstr = spvBuilder.createLoad(
  842. declIdMapper.getCTBufferPushConstantType(declContext), info,
  843. expr->getExprLoc());
  844. } else {
  845. loadedInstr = spvBuilder.createLoad(exprType, info, expr->getExprLoc());
  846. }
  847. assert(loadedInstr);
  848. // Special-case: According to the SPIR-V Spec: There is no physical size or
  849. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  850. // to represent booleans when layout is required. In such cases, after loading
  851. // the uint, we should perform a comparison.
  852. {
  853. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  854. if (info->getLayoutRule() != SpirvLayoutRule::Void &&
  855. isBoolOrVecMatOfBoolType(exprType)) {
  856. QualType uintType = astContext.UnsignedIntTy;
  857. if (isScalarType(exprType) || isVectorType(exprType, nullptr, &vecSize)) {
  858. const auto fromType =
  859. vecSize == 1 ? uintType
  860. : astContext.getExtVectorType(uintType, vecSize);
  861. loadedInstr =
  862. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  863. } else {
  864. const bool isMat = isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  865. assert(isMat);
  866. (void)isMat;
  867. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  868. const RecordType *RT = cast<RecordType>(type);
  869. const ClassTemplateSpecializationDecl *templateSpecDecl =
  870. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  871. ClassTemplateDecl *templateDecl =
  872. templateSpecDecl->getSpecializedTemplate();
  873. const auto fromType = getHLSLMatrixType(
  874. astContext, theCompilerInstance.getSema(), templateDecl,
  875. astContext.UnsignedIntTy, numRows, numCols);
  876. loadedInstr =
  877. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  878. }
  879. // Now that it is converted to Bool, it has no layout rule.
  880. // This result-id should be evaluated as bool from here on out.
  881. loadedInstr->setLayoutRule(SpirvLayoutRule::Void);
  882. }
  883. }
  884. loadedInstr->setRValue();
  885. return loadedInstr;
  886. }
  887. SpirvInstruction *SpirvEmitter::loadIfAliasVarRef(const Expr *expr) {
  888. auto *instr = doExpr(expr);
  889. loadIfAliasVarRef(expr, &instr);
  890. return instr;
  891. }
  892. bool SpirvEmitter::loadIfAliasVarRef(const Expr *varExpr,
  893. SpirvInstruction **instr) {
  894. assert(instr);
  895. if ((*instr) && (*instr)->containsAliasComponent() &&
  896. isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  897. // Load the pointer of the aliased-to-variable if the expression has a
  898. // pointer to pointer type.
  899. if (varExpr->isGLValue()) {
  900. *instr = spvBuilder.createLoad(varExpr->getType(), *instr,
  901. varExpr->getExprLoc());
  902. }
  903. return true;
  904. }
  905. return false;
  906. }
  907. SpirvInstruction *SpirvEmitter::castToType(SpirvInstruction *value,
  908. QualType fromType, QualType toType,
  909. SourceLocation srcLoc) {
  910. if (isFloatOrVecMatOfFloatType(toType))
  911. return castToFloat(value, fromType, toType, srcLoc);
  912. // Order matters here. Bool (vector) values will also be considered as uint
  913. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  914. // will also return true. We need to check bool before uint. The opposite is
  915. // not true.
  916. if (isBoolOrVecMatOfBoolType(toType))
  917. return castToBool(value, fromType, toType, srcLoc);
  918. if (isSintOrVecMatOfSintType(toType) || isUintOrVecMatOfUintType(toType))
  919. return castToInt(value, fromType, toType, srcLoc);
  920. emitError("casting to type %0 unimplemented", {}) << toType;
  921. return nullptr;
  922. }
  923. void SpirvEmitter::doFunctionDecl(const FunctionDecl *decl) {
  924. // Forward declaration of a function inside another.
  925. if(!decl->isThisDeclarationADefinition()) {
  926. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(), decl,
  927. /*isEntryFunction*/ false);
  928. return;
  929. }
  930. // A RAII class for maintaining the current function under traversal.
  931. class FnEnvRAII {
  932. public:
  933. // Creates a new instance which sets fnEnv to the newFn on creation,
  934. // and resets fnEnv to its original value on destruction.
  935. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  936. : oldFn(*fnEnv), fnSlot(fnEnv) {
  937. *fnEnv = newFn;
  938. }
  939. ~FnEnvRAII() { *fnSlot = oldFn; }
  940. private:
  941. const FunctionDecl *oldFn;
  942. const FunctionDecl **fnSlot;
  943. };
  944. FnEnvRAII fnEnvRAII(&curFunction, decl);
  945. // We are about to start translation for a new function. Clear the break stack
  946. // and the continue stack.
  947. breakStack = std::stack<SpirvBasicBlock *>();
  948. continueStack = std::stack<SpirvBasicBlock *>();
  949. // This will allow the entry-point name to be something like
  950. // myNamespace::myEntrypointFunc.
  951. std::string funcName = getFnName(decl);
  952. std::string debugFuncName = funcName;
  953. SpirvFunction *func = declIdMapper.getOrRegisterFn(decl);
  954. const auto iter = functionInfoMap.find(decl);
  955. if (iter != functionInfoMap.end()) {
  956. const auto &entryInfo = iter->second;
  957. if (entryInfo->isEntryFunction) {
  958. funcName = "src." + funcName;
  959. // Create wrapper for the entry function
  960. if (!emitEntryFunctionWrapper(decl, func))
  961. return;
  962. }
  963. }
  964. const QualType retType =
  965. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  966. spvBuilder.beginFunction(retType, decl->getLocStart(), funcName,
  967. decl->hasAttr<HLSLPreciseAttr>(),
  968. decl->hasAttr<NoInlineAttr>(), func);
  969. auto loc = decl->getLocStart();
  970. RichDebugInfo *info = nullptr;
  971. const auto &sm = astContext.getSourceManager();
  972. if (spirvOptions.debugInfoRich && decl->hasBody()) {
  973. const uint32_t line = sm.getPresumedLineNumber(loc);
  974. const uint32_t column = sm.getPresumedColumnNumber(loc);
  975. info = getOrCreateRichDebugInfo(loc);
  976. auto *source = info->source;
  977. // Note that info->scopeStack.back() is a lexical scope of the function
  978. // caller.
  979. auto *parentScope = info->compilationUnit;
  980. // TODO: figure out the proper flag based on the function decl.
  981. // using FlagIsPublic for now.
  982. uint32_t flags = 3u;
  983. // The line number in the source program at which the function scope begins.
  984. auto scopeLine = sm.getPresumedLineNumber(decl->getBody()->getLocStart());
  985. SpirvDebugFunction *debugFunction = spvBuilder.createDebugFunction(
  986. decl, debugFuncName, source, line, column, parentScope, "", flags,
  987. scopeLine, func);
  988. func->setDebugScope(new (spvContext) SpirvDebugScope(debugFunction));
  989. spvContext.pushDebugLexicalScope(info, debugFunction);
  990. }
  991. bool isNonStaticMemberFn = false;
  992. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  993. if (!memberFn->isStatic()) {
  994. // For non-static member function, the first parameter should be the
  995. // object on which we are invoking this method.
  996. QualType valueType = memberFn->getThisType(astContext)->getPointeeType();
  997. // Remember the parameter for the 'this' object so later we can handle
  998. // CXXThisExpr correctly.
  999. curThis = spvBuilder.addFnParam(valueType, /*isPrecise*/ false,
  1000. decl->getLocStart(), "param.this");
  1001. if (isOrContainsAKindOfStructuredOrByteBuffer(valueType)) {
  1002. curThis->setContainsAliasComponent(true);
  1003. needsLegalization = true;
  1004. }
  1005. if (spirvOptions.debugInfoRich) {
  1006. // Add DebugLocalVariable information
  1007. const auto &sm = astContext.getSourceManager();
  1008. const uint32_t line = sm.getPresumedLineNumber(loc);
  1009. const uint32_t column = sm.getPresumedColumnNumber(loc);
  1010. if (!info)
  1011. info = getOrCreateRichDebugInfo(loc);
  1012. // TODO: replace this with FlagArtificial|FlagObjectPointer.
  1013. uint32_t flags = (1 << 5) | (1 << 8);
  1014. auto *debugLocalVar = spvBuilder.createDebugLocalVariable(
  1015. valueType, "this", info->source, line, column,
  1016. info->scopeStack.back(), flags, 1);
  1017. spvBuilder.createDebugDeclare(debugLocalVar, curThis);
  1018. }
  1019. isNonStaticMemberFn = true;
  1020. }
  1021. }
  1022. // Create all parameters.
  1023. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  1024. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  1025. if (spvContext.isHS() && decl == patchConstFunc &&
  1026. hlsl::IsHLSLOutputPatchType(paramDecl->getType())) {
  1027. // Since the output patch used in hull shaders is translated to
  1028. // a variable with Output storage class, there is no need
  1029. // to pass the variable as function parameter in SPIR-V.
  1030. continue;
  1031. }
  1032. (void)declIdMapper.createFnParam(paramDecl, i + 1 + isNonStaticMemberFn);
  1033. }
  1034. if (decl->hasBody()) {
  1035. // The entry basic block.
  1036. auto *entryLabel = spvBuilder.createBasicBlock("bb.entry");
  1037. spvBuilder.setInsertPoint(entryLabel);
  1038. // Process all statments in the body.
  1039. doStmt(decl->getBody());
  1040. // We have processed all Stmts in this function and now in the last
  1041. // basic block. Make sure we have a termination instruction.
  1042. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  1043. const auto retType = decl->getReturnType();
  1044. const auto returnLoc = decl->getBody()->getLocEnd();
  1045. if (retType->isVoidType()) {
  1046. spvBuilder.createReturn(returnLoc);
  1047. } else {
  1048. // If the source code does not provide a proper return value for some
  1049. // control flow path, it's undefined behavior. We just return null
  1050. // value here.
  1051. spvBuilder.createReturnValue(spvBuilder.getConstantNull(retType),
  1052. returnLoc);
  1053. }
  1054. }
  1055. }
  1056. spvBuilder.endFunction();
  1057. if (spirvOptions.debugInfoRich) {
  1058. spvContext.popDebugLexicalScope(info);
  1059. }
  1060. }
  1061. bool SpirvEmitter::validateVKAttributes(const NamedDecl *decl) {
  1062. bool success = true;
  1063. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  1064. const auto varType = varDecl->getType();
  1065. if ((isSubpassInput(varType) || isSubpassInputMS(varType)) &&
  1066. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  1067. emitError("missing vk::input_attachment_index attribute",
  1068. varDecl->getLocation());
  1069. success = false;
  1070. }
  1071. }
  1072. if (decl->getAttr<VKInputAttachmentIndexAttr>()) {
  1073. if (!spvContext.isPS()) {
  1074. emitError("SubpassInput(MS) only allowed in pixel shader",
  1075. decl->getLocation());
  1076. success = false;
  1077. }
  1078. if (!decl->isExternallyVisible()) {
  1079. emitError("SubpassInput(MS) must be externally visible",
  1080. decl->getLocation());
  1081. success = false;
  1082. }
  1083. // We only allow VKInputAttachmentIndexAttr to be attached to global
  1084. // variables. So it should be fine to cast here.
  1085. const auto elementType =
  1086. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  1087. if (!isScalarType(elementType) && !isVectorType(elementType)) {
  1088. emitError(
  1089. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  1090. decl->getLocation());
  1091. // Return directly to avoid further type processing, which will hit
  1092. // asserts when lowering the type.
  1093. return false;
  1094. }
  1095. }
  1096. // The frontend will make sure that
  1097. // * vk::push_constant applies to global variables of struct type
  1098. // * vk::binding applies to global variables or cbuffers/tbuffers
  1099. // * vk::counter_binding applies to global variables of RW/Append/Consume
  1100. // StructuredBuffer
  1101. // * vk::location applies to function parameters/returns and struct fields
  1102. // So the only case we need to check co-existence is vk::push_constant and
  1103. // vk::binding.
  1104. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1105. const auto loc = pcAttr->getLocation();
  1106. if (seenPushConstantAt.isInvalid()) {
  1107. seenPushConstantAt = loc;
  1108. } else {
  1109. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1110. // There must be no more than one push constant block statically used
  1111. // per shader entry point.
  1112. // But we are checking whether there are more than one push constant
  1113. // blocks defined. Tracking usage requires more work.
  1114. emitError("cannot have more than one push constant block", loc);
  1115. emitNote("push constant block previously defined here",
  1116. seenPushConstantAt);
  1117. success = false;
  1118. }
  1119. if (decl->hasAttr<VKBindingAttr>()) {
  1120. emitError("vk::push_constant attribute cannot be used together with "
  1121. "vk::binding attribute",
  1122. loc);
  1123. success = false;
  1124. }
  1125. }
  1126. // vk::shader_record_nv is supported only on cbuffer/ConstantBuffer
  1127. if (const auto *srbAttr = decl->getAttr<VKShaderRecordNVAttr>()) {
  1128. const auto loc = srbAttr->getLocation();
  1129. const HLSLBufferDecl *bufDecl = nullptr;
  1130. bool isValidType = false;
  1131. if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl)))
  1132. isValidType = bufDecl->isCBuffer();
  1133. else if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl->getDeclContext())))
  1134. isValidType = bufDecl->isCBuffer();
  1135. else if (isa<VarDecl>(decl))
  1136. isValidType = isConstantBuffer(dyn_cast<VarDecl>(decl)->getType());
  1137. if (!isValidType) {
  1138. emitError(
  1139. "vk::shader_record_nv can be applied only to cbuffer/ConstantBuffer",
  1140. loc);
  1141. success = false;
  1142. }
  1143. if (decl->hasAttr<VKBindingAttr>()) {
  1144. emitError("vk::shader_record_nv attribute cannot be used together with "
  1145. "vk::binding attribute",
  1146. loc);
  1147. success = false;
  1148. }
  1149. }
  1150. // vk::shader_record_ext is supported only on cbuffer/ConstantBuffer
  1151. if (const auto *srbAttr = decl->getAttr<VKShaderRecordEXTAttr>()) {
  1152. const auto loc = srbAttr->getLocation();
  1153. const HLSLBufferDecl *bufDecl = nullptr;
  1154. bool isValidType = false;
  1155. if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl)))
  1156. isValidType = bufDecl->isCBuffer();
  1157. else if ((bufDecl = dyn_cast<HLSLBufferDecl>(decl->getDeclContext())))
  1158. isValidType = bufDecl->isCBuffer();
  1159. else if (isa<VarDecl>(decl))
  1160. isValidType = isConstantBuffer(dyn_cast<VarDecl>(decl)->getType());
  1161. if (!isValidType) {
  1162. emitError(
  1163. "vk::shader_record_ext can be applied only to cbuffer/ConstantBuffer",
  1164. loc);
  1165. success = false;
  1166. }
  1167. if (decl->hasAttr<VKBindingAttr>()) {
  1168. emitError("vk::shader_record_ext attribute cannot be used together with "
  1169. "vk::binding attribute",
  1170. loc);
  1171. success = false;
  1172. }
  1173. }
  1174. return success;
  1175. }
  1176. void SpirvEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1177. // This is a cbuffer/tbuffer decl.
  1178. // Check and emit warnings for member intializers which are not
  1179. // supported in Vulkan
  1180. for (const auto *member : bufferDecl->decls()) {
  1181. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1182. if (!spirvOptions.noWarnIgnoredFeatures) {
  1183. if (const auto *init = varMember->getInit())
  1184. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1185. "ignored since no Vulkan equivalent",
  1186. init->getExprLoc())
  1187. << bufferDecl->isCBuffer() << init->getSourceRange();
  1188. }
  1189. // We cannot handle external initialization of column-major matrices now.
  1190. if (isOrContainsNonFpColMajorMatrix(astContext, spirvOptions,
  1191. varMember->getType(), varMember)) {
  1192. emitError("externally initialized non-floating-point column-major "
  1193. "matrices not supported yet",
  1194. varMember->getLocation());
  1195. }
  1196. }
  1197. }
  1198. if (!validateVKAttributes(bufferDecl))
  1199. return;
  1200. if (bufferDecl->hasAttr<VKShaderRecordNVAttr>()) {
  1201. (void)declIdMapper.createShaderRecordBuffer(
  1202. bufferDecl, DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferNV);
  1203. } else if (bufferDecl->hasAttr<VKShaderRecordEXTAttr>()) {
  1204. (void)declIdMapper.createShaderRecordBuffer(
  1205. bufferDecl,
  1206. DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferEXT);
  1207. } else {
  1208. (void)declIdMapper.createCTBuffer(bufferDecl);
  1209. }
  1210. }
  1211. void SpirvEmitter::doClassTemplateDecl(
  1212. const ClassTemplateDecl *classTemplateDecl) {
  1213. for (auto classTemplateSpecializationDeclItr :
  1214. classTemplateDecl->specializations()) {
  1215. if (const CXXRecordDecl *recordDecl =
  1216. dyn_cast<CXXRecordDecl>(&*classTemplateSpecializationDeclItr)) {
  1217. doRecordDecl(recordDecl);
  1218. }
  1219. }
  1220. }
  1221. void SpirvEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1222. // Ignore implict records
  1223. // Somehow we'll have implicit records with:
  1224. // static const int Length = count;
  1225. // that can mess up with the normal CodeGen.
  1226. if (recordDecl->isImplicit())
  1227. return;
  1228. // Handle each static member with inline initializer.
  1229. // Each static member has a corresponding VarDecl inside the
  1230. // RecordDecl. For those defined in the translation unit,
  1231. // their VarDecls do not have initializer.
  1232. for (auto *subDecl : recordDecl->decls())
  1233. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1234. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1235. doVarDecl(varDecl);
  1236. }
  1237. void SpirvEmitter::doEnumDecl(const EnumDecl *decl) {
  1238. for (auto it = decl->enumerator_begin(); it != decl->enumerator_end(); ++it)
  1239. declIdMapper.createEnumConstant(*it);
  1240. }
  1241. void SpirvEmitter::doVarDecl(const VarDecl *decl) {
  1242. if (!validateVKAttributes(decl))
  1243. return;
  1244. const auto loc = decl->getLocation();
  1245. // HLSL has the 'string' type which can be used for rare purposes such as
  1246. // printf (SPIR-V's DebugPrintf). SPIR-V does not have a 'char' or 'string'
  1247. // type, and therefore any variable of such type should not be created.
  1248. // DeclResultIdMapper maps such decl to an OpString instruction that
  1249. // represents the variable's initializer literal.
  1250. if (isStringType(decl->getType())) {
  1251. declIdMapper.createOrUpdateStringVar(decl);
  1252. return;
  1253. }
  1254. // We cannot handle external initialization of column-major matrices now.
  1255. if (isExternalVar(decl) &&
  1256. isOrContainsNonFpColMajorMatrix(astContext, spirvOptions, decl->getType(),
  1257. decl)) {
  1258. emitError("externally initialized non-floating-point column-major "
  1259. "matrices not supported yet",
  1260. loc);
  1261. }
  1262. // Reject arrays of RW/append/consume structured buffers. They have assoicated
  1263. // counters, which are quite nasty to handle.
  1264. if (decl->getType()->isArrayType()) {
  1265. auto type = decl->getType();
  1266. do {
  1267. type = type->getAsArrayTypeUnsafe()->getElementType();
  1268. } while (type->isArrayType());
  1269. if (isRWAppendConsumeSBuffer(type)) {
  1270. emitError("arrays of RW/append/consume structured buffers unsupported",
  1271. loc);
  1272. return;
  1273. }
  1274. }
  1275. if (decl->hasAttr<VKConstantIdAttr>()) {
  1276. // This is a VarDecl for specialization constant.
  1277. createSpecConstant(decl);
  1278. return;
  1279. }
  1280. if (decl->hasAttr<VKPushConstantAttr>()) {
  1281. // This is a VarDecl for PushConstant block.
  1282. (void)declIdMapper.createPushConstant(decl);
  1283. return;
  1284. }
  1285. if (decl->hasAttr<VKShaderRecordNVAttr>()) {
  1286. (void)declIdMapper.createShaderRecordBuffer(
  1287. decl, DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferNV);
  1288. return;
  1289. }
  1290. if (decl->hasAttr<VKShaderRecordEXTAttr>()) {
  1291. (void)declIdMapper.createShaderRecordBuffer(
  1292. decl, DeclResultIdMapper::ContextUsageKind::ShaderRecordBufferEXT);
  1293. return;
  1294. }
  1295. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  1296. // to emit their cbuffer/tbuffer as a whole and access each individual one
  1297. // using access chains.
  1298. // cbuffers and tbuffers are HLSLBufferDecls
  1299. // ConstantBuffers and TextureBuffers are not HLSLBufferDecls.
  1300. if (const auto *bufferDecl =
  1301. dyn_cast<HLSLBufferDecl>(decl->getDeclContext())) {
  1302. // This is a VarDecl of cbuffer/tbuffer type.
  1303. doHLSLBufferDecl(bufferDecl);
  1304. return;
  1305. }
  1306. if (isConstantTextureBuffer(decl->getType())) {
  1307. // This is a VarDecl of ConstantBuffer/TextureBuffer type.
  1308. (void)declIdMapper.createCTBuffer(decl);
  1309. return;
  1310. }
  1311. SpirvVariable *var = nullptr;
  1312. // The contents in externally visible variables can be updated via the
  1313. // pipeline. They should be handled differently from file and function scope
  1314. // variables.
  1315. // File scope variables (static "global" and "local" variables) belongs to
  1316. // the Private storage class, while function scope variables (normal "local"
  1317. // variables) belongs to the Function storage class.
  1318. if (isExternalVar(decl)) {
  1319. var = declIdMapper.createExternVar(decl);
  1320. } else {
  1321. // We already know the variable is not externally visible here. If it does
  1322. // not have local storage, it should be file scope variable.
  1323. const bool isFileScopeVar = !decl->hasLocalStorage();
  1324. if (isFileScopeVar)
  1325. var = declIdMapper.createFileVar(decl, llvm::None);
  1326. else
  1327. var = declIdMapper.createFnVar(decl, llvm::None);
  1328. // Emit OpStore to initialize the variable
  1329. // TODO: revert back to use OpVariable initializer
  1330. // We should only evaluate the initializer once for a static variable.
  1331. if (isFileScopeVar) {
  1332. if (decl->isStaticLocal()) {
  1333. initOnce(decl->getType(), decl->getName(), var, decl->getInit());
  1334. } else {
  1335. // Defer to initialize these global variables at the beginning of the
  1336. // entry function.
  1337. toInitGloalVars.push_back(decl);
  1338. }
  1339. }
  1340. // Function local variables. Just emit OpStore at the current insert point.
  1341. else if (const Expr *init = decl->getInit()) {
  1342. if (auto *constInit = tryToEvaluateAsConst(init)) {
  1343. spvBuilder.createStore(var, constInit, loc);
  1344. } else {
  1345. storeValue(var, loadIfGLValue(init), decl->getType(), loc);
  1346. }
  1347. // Update counter variable associated with local variables
  1348. tryToAssignCounterVar(decl, init);
  1349. }
  1350. if (!isFileScopeVar && spirvOptions.debugInfoRich) {
  1351. // Add DebugLocalVariable information
  1352. const auto &sm = astContext.getSourceManager();
  1353. const uint32_t line = sm.getPresumedLineNumber(loc);
  1354. const uint32_t column = sm.getPresumedColumnNumber(loc);
  1355. const auto *info = getOrCreateRichDebugInfo(loc);
  1356. // TODO: replace this with FlagIsLocal enum.
  1357. uint32_t flags = 1 << 2;
  1358. auto *debugLocalVar = spvBuilder.createDebugLocalVariable(
  1359. decl->getType(), decl->getName(), info->source, line, column,
  1360. info->scopeStack.back(), flags);
  1361. spvBuilder.createDebugDeclare(debugLocalVar, var);
  1362. }
  1363. // Variables that are not externally visible and of opaque types should
  1364. // request legalization.
  1365. if (!needsLegalization && isOpaqueType(decl->getType()))
  1366. needsLegalization = true;
  1367. }
  1368. // All variables that are of opaque struct types should request legalization.
  1369. if (!needsLegalization && isOpaqueStructType(decl->getType()))
  1370. needsLegalization = true;
  1371. }
  1372. spv::LoopControlMask SpirvEmitter::translateLoopAttribute(const Stmt *stmt,
  1373. const Attr &attr) {
  1374. switch (attr.getKind()) {
  1375. case attr::HLSLLoop:
  1376. case attr::HLSLFastOpt:
  1377. return spv::LoopControlMask::DontUnroll;
  1378. case attr::HLSLUnroll:
  1379. return spv::LoopControlMask::Unroll;
  1380. case attr::HLSLAllowUAVCondition:
  1381. if (!spirvOptions.noWarnIgnoredFeatures) {
  1382. emitWarning("unsupported allow_uav_condition attribute ignored",
  1383. stmt->getLocStart());
  1384. }
  1385. break;
  1386. default:
  1387. llvm_unreachable("found unknown loop attribute");
  1388. }
  1389. return spv::LoopControlMask::MaskNone;
  1390. }
  1391. void SpirvEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1392. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1393. // The discard statement can only be called from a pixel shader
  1394. if (!spvContext.isPS()) {
  1395. emitError("discard statement may only be used in pixel shaders",
  1396. discardStmt->getLoc());
  1397. return;
  1398. }
  1399. if (featureManager.isExtensionEnabled(
  1400. Extension::EXT_demote_to_helper_invocation)) {
  1401. // SPV_EXT_demote_to_helper_invocation SPIR-V extension provides a new
  1402. // instruction OpDemoteToHelperInvocationEXT allowing shaders to "demote" a
  1403. // fragment shader invocation to behave like a helper invocation for its
  1404. // duration. The demoted invocation will have no further side effects and
  1405. // will not output to the framebuffer, but remains active and can
  1406. // participate in computing derivatives and in subgroup operations. This is
  1407. // a better match for the "discard" instruction in HLSL.
  1408. spvBuilder.createDemoteToHelperInvocationEXT(discardStmt->getLoc());
  1409. } else {
  1410. // Note: if/when the demote behavior becomes part of the core Vulkan spec,
  1411. // we should no longer generate OpKill for 'discard', and always generate
  1412. // the demote behavior.
  1413. spvBuilder.createKill(discardStmt->getLoc());
  1414. // Some statements that alter the control flow (break, continue, return, and
  1415. // discard), require creation of a new basic block to hold any statement
  1416. // that may follow them.
  1417. auto *newBB = spvBuilder.createBasicBlock();
  1418. spvBuilder.setInsertPoint(newBB);
  1419. }
  1420. }
  1421. void SpirvEmitter::doDoStmt(const DoStmt *theDoStmt,
  1422. llvm::ArrayRef<const Attr *> attrs) {
  1423. // do-while loops are composed of:
  1424. //
  1425. // do {
  1426. // <body>
  1427. // } while(<check>);
  1428. //
  1429. // SPIR-V requires loops to have a merge basic block as well as a continue
  1430. // basic block. Even though do-while loops do not have an explicit continue
  1431. // block as in for-loops, we still do need to create a continue block.
  1432. //
  1433. // Since SPIR-V requires structured control flow, we need two more basic
  1434. // blocks, <header> and <merge>. <header> is the block before control flow
  1435. // diverges, and <merge> is the block where control flow subsequently
  1436. // converges. The <check> can be performed in the <continue> basic block.
  1437. // The final CFG should normally be like the following. Exceptions
  1438. // will occur with non-local exits like loop breaks or early returns.
  1439. //
  1440. // +----------+
  1441. // | header | <-----------------------------------+
  1442. // +----------+ |
  1443. // | | (true)
  1444. // v |
  1445. // +------+ +--------------------+ |
  1446. // | body | ----> | continue (<check>) |-----------+
  1447. // +------+ +--------------------+
  1448. // |
  1449. // | (false)
  1450. // +-------+ |
  1451. // | merge | <-------------+
  1452. // +-------+
  1453. //
  1454. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1455. const spv::LoopControlMask loopControl =
  1456. attrs.empty() ? spv::LoopControlMask::MaskNone
  1457. : translateLoopAttribute(theDoStmt, *attrs.front());
  1458. // Create basic blocks
  1459. auto *headerBB = spvBuilder.createBasicBlock("do_while.header");
  1460. auto *bodyBB = spvBuilder.createBasicBlock("do_while.body");
  1461. auto *continueBB = spvBuilder.createBasicBlock("do_while.continue");
  1462. auto *mergeBB = spvBuilder.createBasicBlock("do_while.merge");
  1463. // Make sure any continue statements branch to the continue block, and any
  1464. // break statements branch to the merge block.
  1465. continueStack.push(continueBB);
  1466. breakStack.push(mergeBB);
  1467. // Branch from the current insert point to the header block.
  1468. spvBuilder.createBranch(headerBB, theDoStmt->getLocStart());
  1469. spvBuilder.addSuccessor(headerBB);
  1470. // Process the <header> block
  1471. // The header block must always branch to the body.
  1472. spvBuilder.setInsertPoint(headerBB);
  1473. const Stmt *body = theDoStmt->getBody();
  1474. spvBuilder.createBranch(bodyBB,
  1475. body ? body->getLocStart() : theDoStmt->getLocStart(),
  1476. mergeBB, continueBB, loopControl);
  1477. spvBuilder.addSuccessor(bodyBB);
  1478. // The current basic block has OpLoopMerge instruction. We need to set its
  1479. // continue and merge target.
  1480. spvBuilder.setContinueTarget(continueBB);
  1481. spvBuilder.setMergeTarget(mergeBB);
  1482. // Process the <body> block
  1483. spvBuilder.setInsertPoint(bodyBB);
  1484. if (body) {
  1485. doStmt(body);
  1486. }
  1487. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  1488. spvBuilder.createBranch(continueBB, body ? body->getLocEnd()
  1489. : theDoStmt->getLocStart());
  1490. }
  1491. spvBuilder.addSuccessor(continueBB);
  1492. // Process the <continue> block. The check for whether the loop should
  1493. // continue lies in the continue block.
  1494. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1495. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1496. // OpBranchConditional must be specified.
  1497. spvBuilder.setInsertPoint(continueBB);
  1498. SpirvInstruction *condition = nullptr;
  1499. if (const Expr *check = theDoStmt->getCond()) {
  1500. condition = doExpr(check);
  1501. } else {
  1502. condition = spvBuilder.getConstantBool(true);
  1503. }
  1504. spvBuilder.createConditionalBranch(condition, headerBB, mergeBB,
  1505. theDoStmt->getLocEnd());
  1506. spvBuilder.addSuccessor(headerBB);
  1507. spvBuilder.addSuccessor(mergeBB);
  1508. // Set insertion point to the <merge> block for subsequent statements
  1509. spvBuilder.setInsertPoint(mergeBB);
  1510. // Done with the current scope's continue block and merge block.
  1511. continueStack.pop();
  1512. breakStack.pop();
  1513. }
  1514. void SpirvEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1515. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1516. auto *continueTargetBB = continueStack.top();
  1517. spvBuilder.createBranch(continueTargetBB, continueStmt->getLocStart());
  1518. spvBuilder.addSuccessor(continueTargetBB);
  1519. // Some statements that alter the control flow (break, continue, return, and
  1520. // discard), require creation of a new basic block to hold any statement that
  1521. // may follow them. For example: StmtB and StmtC below are put inside a new
  1522. // basic block which is unreachable.
  1523. //
  1524. // while (true) {
  1525. // StmtA;
  1526. // continue;
  1527. // StmtB;
  1528. // StmtC;
  1529. // }
  1530. auto *newBB = spvBuilder.createBasicBlock();
  1531. spvBuilder.setInsertPoint(newBB);
  1532. }
  1533. void SpirvEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1534. llvm::ArrayRef<const Attr *> attrs) {
  1535. // While loops are composed of:
  1536. // while (<check>) { <body> }
  1537. //
  1538. // SPIR-V requires loops to have a merge basic block as well as a continue
  1539. // basic block. Even though while loops do not have an explicit continue
  1540. // block as in for-loops, we still do need to create a continue block.
  1541. //
  1542. // Since SPIR-V requires structured control flow, we need two more basic
  1543. // blocks, <header> and <merge>. <header> is the block before control flow
  1544. // diverges, and <merge> is the block where control flow subsequently
  1545. // converges. The <check> block can take the responsibility of the <header>
  1546. // block. The final CFG should normally be like the following. Exceptions
  1547. // will occur with non-local exits like loop breaks or early returns.
  1548. //
  1549. // +----------+
  1550. // | header | <------------------+
  1551. // | (check) | |
  1552. // +----------+ |
  1553. // | |
  1554. // +-------+-------+ |
  1555. // | false | true |
  1556. // | v |
  1557. // | +------+ +------------------+
  1558. // | | body | --> | continue (no-op) |
  1559. // v +------+ +------------------+
  1560. // +-------+
  1561. // | merge |
  1562. // +-------+
  1563. //
  1564. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1565. const spv::LoopControlMask loopControl =
  1566. attrs.empty() ? spv::LoopControlMask::MaskNone
  1567. : translateLoopAttribute(whileStmt, *attrs.front());
  1568. // Create basic blocks
  1569. auto *checkBB = spvBuilder.createBasicBlock("while.check");
  1570. auto *bodyBB = spvBuilder.createBasicBlock("while.body");
  1571. auto *continueBB = spvBuilder.createBasicBlock("while.continue");
  1572. auto *mergeBB = spvBuilder.createBasicBlock("while.merge");
  1573. // Make sure any continue statements branch to the continue block, and any
  1574. // break statements branch to the merge block.
  1575. continueStack.push(continueBB);
  1576. breakStack.push(mergeBB);
  1577. // Process the <check> block
  1578. spvBuilder.createBranch(checkBB, whileStmt->getLocStart());
  1579. spvBuilder.addSuccessor(checkBB);
  1580. spvBuilder.setInsertPoint(checkBB);
  1581. // If we have:
  1582. // while (int a = foo()) {...}
  1583. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1584. // to occur.
  1585. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1586. doStmt(condVarDecl);
  1587. SpirvInstruction *condition = nullptr;
  1588. const Expr *check = whileStmt->getCond();
  1589. if (check) {
  1590. condition = doExpr(check);
  1591. } else {
  1592. condition = spvBuilder.getConstantBool(true);
  1593. }
  1594. spvBuilder.createConditionalBranch(
  1595. condition, bodyBB,
  1596. /*false branch*/ mergeBB, whileStmt->getLocStart(),
  1597. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1598. loopControl);
  1599. spvBuilder.addSuccessor(bodyBB);
  1600. spvBuilder.addSuccessor(mergeBB);
  1601. // The current basic block has OpLoopMerge instruction. We need to set its
  1602. // continue and merge target.
  1603. spvBuilder.setContinueTarget(continueBB);
  1604. spvBuilder.setMergeTarget(mergeBB);
  1605. // Process the <body> block
  1606. spvBuilder.setInsertPoint(bodyBB);
  1607. const Stmt *body = whileStmt->getBody();
  1608. if (body) {
  1609. doStmt(body);
  1610. }
  1611. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1612. spvBuilder.createBranch(continueBB, whileStmt->getLocEnd());
  1613. spvBuilder.addSuccessor(continueBB);
  1614. // Process the <continue> block. While loops do not have an explicit
  1615. // continue block. The continue block just branches to the <check> block.
  1616. spvBuilder.setInsertPoint(continueBB);
  1617. spvBuilder.createBranch(checkBB, whileStmt->getLocEnd());
  1618. spvBuilder.addSuccessor(checkBB);
  1619. // Set insertion point to the <merge> block for subsequent statements
  1620. spvBuilder.setInsertPoint(mergeBB);
  1621. // Done with the current scope's continue and merge blocks.
  1622. continueStack.pop();
  1623. breakStack.pop();
  1624. }
  1625. void SpirvEmitter::doForStmt(const ForStmt *forStmt,
  1626. llvm::ArrayRef<const Attr *> attrs) {
  1627. // for loops are composed of:
  1628. // for (<init>; <check>; <continue>) <body>
  1629. //
  1630. // To translate a for loop, we'll need to emit all <init> statements
  1631. // in the current basic block, and then have separate basic blocks for
  1632. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1633. // structured control flow, we need two more basic blocks, <header>
  1634. // and <merge>. <header> is the block before control flow diverges,
  1635. // while <merge> is the block where control flow subsequently converges.
  1636. // The <check> block can take the responsibility of the <header> block.
  1637. // The final CFG should normally be like the following. Exceptions will
  1638. // occur with non-local exits like loop breaks or early returns.
  1639. // +--------+
  1640. // | init |
  1641. // +--------+
  1642. // |
  1643. // v
  1644. // +----------+
  1645. // | header | <---------------+
  1646. // | (check) | |
  1647. // +----------+ |
  1648. // | |
  1649. // +-------+-------+ |
  1650. // | false | true |
  1651. // | v |
  1652. // | +------+ +----------+
  1653. // | | body | --> | continue |
  1654. // v +------+ +----------+
  1655. // +-------+
  1656. // | merge |
  1657. // +-------+
  1658. //
  1659. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1660. const spv::LoopControlMask loopControl =
  1661. attrs.empty() ? spv::LoopControlMask::MaskNone
  1662. : translateLoopAttribute(forStmt, *attrs.front());
  1663. // Create basic blocks
  1664. auto *checkBB = spvBuilder.createBasicBlock("for.check");
  1665. auto *bodyBB = spvBuilder.createBasicBlock("for.body");
  1666. auto *continueBB = spvBuilder.createBasicBlock("for.continue");
  1667. auto *mergeBB = spvBuilder.createBasicBlock("for.merge");
  1668. // Make sure any continue statements branch to the continue block, and any
  1669. // break statements branch to the merge block.
  1670. continueStack.push(continueBB);
  1671. breakStack.push(mergeBB);
  1672. // Process the <init> block
  1673. if (const Stmt *initStmt = forStmt->getInit()) {
  1674. doStmt(initStmt);
  1675. }
  1676. const Expr *check = forStmt->getCond();
  1677. spvBuilder.createBranch(checkBB, check ? check->getLocStart()
  1678. : forStmt->getLocStart());
  1679. spvBuilder.addSuccessor(checkBB);
  1680. // Process the <check> block
  1681. spvBuilder.setInsertPoint(checkBB);
  1682. SpirvInstruction *condition = nullptr;
  1683. if (check) {
  1684. condition = doExpr(check);
  1685. } else {
  1686. condition = spvBuilder.getConstantBool(true);
  1687. }
  1688. const Stmt *body = forStmt->getBody();
  1689. spvBuilder.createConditionalBranch(
  1690. condition, bodyBB,
  1691. /*false branch*/ mergeBB,
  1692. check ? check->getLocEnd()
  1693. : (body ? body->getLocStart() : forStmt->getLocStart()),
  1694. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1695. loopControl);
  1696. spvBuilder.addSuccessor(bodyBB);
  1697. spvBuilder.addSuccessor(mergeBB);
  1698. // The current basic block has OpLoopMerge instruction. We need to set its
  1699. // continue and merge target.
  1700. spvBuilder.setContinueTarget(continueBB);
  1701. spvBuilder.setMergeTarget(mergeBB);
  1702. // Process the <body> block
  1703. spvBuilder.setInsertPoint(bodyBB);
  1704. if (body) {
  1705. doStmt(body);
  1706. }
  1707. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1708. spvBuilder.createBranch(continueBB, forStmt->getLocEnd());
  1709. spvBuilder.addSuccessor(continueBB);
  1710. // Process the <continue> block
  1711. spvBuilder.setInsertPoint(continueBB);
  1712. if (const Expr *cont = forStmt->getInc()) {
  1713. doExpr(cont);
  1714. }
  1715. // <continue> should jump back to header
  1716. spvBuilder.createBranch(checkBB, forStmt->getLocEnd());
  1717. spvBuilder.addSuccessor(checkBB);
  1718. // Set insertion point to the <merge> block for subsequent statements
  1719. spvBuilder.setInsertPoint(mergeBB);
  1720. // Done with the current scope's continue block and merge block.
  1721. continueStack.pop();
  1722. breakStack.pop();
  1723. }
  1724. void SpirvEmitter::doIfStmt(const IfStmt *ifStmt,
  1725. llvm::ArrayRef<const Attr *> attrs) {
  1726. // if statements are composed of:
  1727. // if (<check>) { <then> } else { <else> }
  1728. //
  1729. // To translate if statements, we'll need to emit the <check> expressions
  1730. // in the current basic block, and then create separate basic blocks for
  1731. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1732. // SPIR-V's structured control flow requirements. Depending whether there
  1733. // exists the else branch, the final CFG should normally be like the
  1734. // following. Exceptions will occur with non-local exits like loop breaks
  1735. // or early returns.
  1736. // +-------+ +-------+
  1737. // | check | | check |
  1738. // +-------+ +-------+
  1739. // | |
  1740. // +-------+-------+ +-----+-----+
  1741. // | true | false | true | false
  1742. // v v or v |
  1743. // +------+ +------+ +------+ |
  1744. // | then | | else | | then | |
  1745. // +------+ +------+ +------+ |
  1746. // | | | v
  1747. // | +-------+ | | +-------+
  1748. // +-> | merge | <-+ +---> | merge |
  1749. // +-------+ +-------+
  1750. { // Try to see if we can const-eval the condition
  1751. bool condition = false;
  1752. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1753. if (condition) {
  1754. doStmt(ifStmt->getThen());
  1755. } else if (ifStmt->getElse()) {
  1756. doStmt(ifStmt->getElse());
  1757. }
  1758. return;
  1759. }
  1760. }
  1761. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1762. if (!attrs.empty()) {
  1763. const Attr *attribute = attrs.front();
  1764. switch (attribute->getKind()) {
  1765. case attr::HLSLBranch:
  1766. selectionControl = spv::SelectionControlMask::DontFlatten;
  1767. break;
  1768. case attr::HLSLFlatten:
  1769. selectionControl = spv::SelectionControlMask::Flatten;
  1770. break;
  1771. default:
  1772. // warning emitted in hlsl::ProcessStmtAttributeForHLSL
  1773. break;
  1774. }
  1775. }
  1776. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1777. doDeclStmt(declStmt);
  1778. // First emit the instruction for evaluating the condition.
  1779. auto *condition = doExpr(ifStmt->getCond());
  1780. // Then we need to emit the instruction for the conditional branch.
  1781. // We'll need the <label-id> for the then/else/merge block to do so.
  1782. const bool hasElse = ifStmt->getElse() != nullptr;
  1783. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  1784. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  1785. auto *elseBB = hasElse ? spvBuilder.createBasicBlock("if.false") : mergeBB;
  1786. // Create the branch instruction. This will end the current basic block.
  1787. const auto *then = ifStmt->getThen();
  1788. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  1789. then->getLocStart(), mergeBB,
  1790. /*continue*/ 0, selectionControl);
  1791. spvBuilder.addSuccessor(thenBB);
  1792. spvBuilder.addSuccessor(elseBB);
  1793. // The current basic block has the OpSelectionMerge instruction. We need
  1794. // to record its merge target.
  1795. spvBuilder.setMergeTarget(mergeBB);
  1796. // Handle the then branch
  1797. spvBuilder.setInsertPoint(thenBB);
  1798. doStmt(then);
  1799. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1800. spvBuilder.createBranch(mergeBB, ifStmt->getLocEnd());
  1801. spvBuilder.addSuccessor(mergeBB);
  1802. // Handle the else branch (if exists)
  1803. if (hasElse) {
  1804. spvBuilder.setInsertPoint(elseBB);
  1805. const auto *elseStmt = ifStmt->getElse();
  1806. doStmt(elseStmt);
  1807. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1808. spvBuilder.createBranch(mergeBB, elseStmt->getLocEnd());
  1809. spvBuilder.addSuccessor(mergeBB);
  1810. }
  1811. // From now on, we'll emit instructions into the merge block.
  1812. spvBuilder.setInsertPoint(mergeBB);
  1813. }
  1814. void SpirvEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1815. if (const auto *retVal = stmt->getRetValue()) {
  1816. // Update counter variable associated with function returns
  1817. tryToAssignCounterVar(curFunction, retVal);
  1818. auto *retInfo = loadIfGLValue(retVal);
  1819. if (!retInfo)
  1820. return;
  1821. auto retType = retVal->getType();
  1822. if (retInfo->getLayoutRule() != SpirvLayoutRule::Void &&
  1823. retType->isStructureType()) {
  1824. // We are returning some value from a non-Function storage class. Need to
  1825. // create a temporary variable to "convert" the value to Function storage
  1826. // class and then return.
  1827. auto *tempVar =
  1828. spvBuilder.addFnVar(retType, retVal->getLocEnd(), "temp.var.ret");
  1829. storeValue(tempVar, retInfo, retType, retVal->getLocEnd());
  1830. spvBuilder.createReturnValue(
  1831. spvBuilder.createLoad(retType, tempVar, retVal->getLocEnd()),
  1832. stmt->getReturnLoc());
  1833. } else {
  1834. spvBuilder.createReturnValue(retInfo, stmt->getReturnLoc());
  1835. }
  1836. } else {
  1837. spvBuilder.createReturn(stmt->getReturnLoc());
  1838. }
  1839. // We are translating a ReturnStmt, we should be in some function's body.
  1840. assert(curFunction->hasBody());
  1841. // If this return statement is the last statement in the function, then
  1842. // whe have no more work to do.
  1843. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1844. return;
  1845. // Some statements that alter the control flow (break, continue, return, and
  1846. // discard), require creation of a new basic block to hold any statement that
  1847. // may follow them. In this case, the newly created basic block will contain
  1848. // any statement that may come after an early return.
  1849. auto *newBB = spvBuilder.createBasicBlock();
  1850. spvBuilder.setInsertPoint(newBB);
  1851. }
  1852. void SpirvEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1853. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1854. auto *breakTargetBB = breakStack.top();
  1855. spvBuilder.addSuccessor(breakTargetBB);
  1856. spvBuilder.createBranch(breakTargetBB, breakStmt->getLocStart());
  1857. // Some statements that alter the control flow (break, continue, return, and
  1858. // discard), require creation of a new basic block to hold any statement that
  1859. // may follow them. For example: StmtB and StmtC below are put inside a new
  1860. // basic block which is unreachable.
  1861. //
  1862. // while (true) {
  1863. // StmtA;
  1864. // break;
  1865. // StmtB;
  1866. // StmtC;
  1867. // }
  1868. auto *newBB = spvBuilder.createBasicBlock();
  1869. spvBuilder.setInsertPoint(newBB);
  1870. }
  1871. void SpirvEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1872. llvm::ArrayRef<const Attr *> attrs) {
  1873. // Switch statements are composed of:
  1874. // switch (<condition variable>) {
  1875. // <CaseStmt>
  1876. // <CaseStmt>
  1877. // <CaseStmt>
  1878. // <DefaultStmt> (optional)
  1879. // }
  1880. //
  1881. // +-------+
  1882. // | check |
  1883. // +-------+
  1884. // |
  1885. // +-------+-------+----------------+---------------+
  1886. // | 1 | 2 | 3 | (others)
  1887. // v v v v
  1888. // +-------+ +-------------+ +-------+ +------------+
  1889. // | case1 | | case2 | | case3 | ... | default |
  1890. // | | |(fallthrough)|---->| | | (optional) |
  1891. // +-------+ |+------------+ +-------+ +------------+
  1892. // | | |
  1893. // | | |
  1894. // | +-------+ | |
  1895. // | | | <--------------------+ |
  1896. // +-> | merge | |
  1897. // | | <-------------------------------------+
  1898. // +-------+
  1899. // If no attributes are given, or if "forcecase" attribute was provided,
  1900. // we'll do our best to use OpSwitch if possible.
  1901. // If any of the cases compares to a variable (rather than an integer
  1902. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1903. // numbers as parameters.
  1904. const bool isAttrForceCase =
  1905. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1906. const bool canUseSpirvOpSwitch =
  1907. (attrs.empty() || isAttrForceCase) &&
  1908. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1909. if (isAttrForceCase && !canUseSpirvOpSwitch &&
  1910. !spirvOptions.noWarnIgnoredFeatures) {
  1911. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1912. "since one or more case values are not integer literals",
  1913. switchStmt->getLocStart());
  1914. }
  1915. if (canUseSpirvOpSwitch)
  1916. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1917. else
  1918. processSwitchStmtUsingIfStmts(switchStmt);
  1919. }
  1920. SpirvInstruction *
  1921. SpirvEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1922. llvm::SmallVector<SpirvInstruction *, 4> indices;
  1923. const auto *base = collectArrayStructIndices(
  1924. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  1925. auto *info = loadIfAliasVarRef(base);
  1926. if (!indices.empty()) {
  1927. info = turnIntoElementPtr(base->getType(), info, expr->getType(), indices,
  1928. base->getExprLoc());
  1929. }
  1930. return info;
  1931. }
  1932. SpirvInstruction *SpirvEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1933. const auto opcode = expr->getOpcode();
  1934. // Handle assignment first since we need to evaluate rhs before lhs.
  1935. // For other binary operations, we need to evaluate lhs before rhs.
  1936. if (opcode == BO_Assign) {
  1937. // Update counter variable associated with lhs of assignments
  1938. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1939. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1940. /*isCompoundAssignment=*/false);
  1941. }
  1942. // Try to optimize floatMxN * float and floatN * float case
  1943. if (opcode == BO_Mul) {
  1944. if (auto *result = tryToGenFloatMatrixScale(expr))
  1945. return result;
  1946. if (auto *result = tryToGenFloatVectorScale(expr))
  1947. return result;
  1948. }
  1949. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1950. expr->getLHS()->getType(), expr->getType(),
  1951. expr->getSourceRange(), expr->getOperatorLoc());
  1952. }
  1953. SpirvInstruction *SpirvEmitter::doCallExpr(const CallExpr *callExpr) {
  1954. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1955. return doCXXOperatorCallExpr(operatorCall);
  1956. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1957. return doCXXMemberCallExpr(memberCall);
  1958. // Intrinsic functions such as 'dot' or 'mul'
  1959. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1960. return processIntrinsicCallExpr(callExpr);
  1961. }
  1962. // Normal standalone functions
  1963. return processCall(callExpr);
  1964. }
  1965. SpirvInstruction *SpirvEmitter::getBaseOfMemberFunction(QualType objectType,
  1966. SpirvInstruction * objInstr,
  1967. const CXXMethodDecl* memberFn,
  1968. SourceLocation loc) {
  1969. // If objectType is different from the parent of memberFn, memberFn should be
  1970. // defined in a base struct/class of objectType. We create OpAccessChain with
  1971. // index 0 while iterating bases of objectType until we find the base with
  1972. // the definition of memberFn.
  1973. if (const auto *ptrType = objectType->getAs<PointerType>()) {
  1974. if (const auto *recordType = ptrType->getPointeeType()->getAs<RecordType>()) {
  1975. const auto *parentDeclOfMemberFn = memberFn->getParent();
  1976. if (recordType->getDecl() != parentDeclOfMemberFn) {
  1977. const auto *cxxRecordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl());
  1978. auto *zero =
  1979. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  1980. for (auto baseItr = cxxRecordDecl->bases_begin(), itrEnd = cxxRecordDecl->bases_end();
  1981. baseItr != itrEnd; baseItr++) {
  1982. const auto *baseType = baseItr->getType()->getAs<RecordType>();
  1983. objectType = astContext.getPointerType(baseType->desugar());
  1984. objInstr = spvBuilder.createAccessChain(objectType,
  1985. objInstr, {zero},
  1986. loc);
  1987. if (baseType->getDecl() == parentDeclOfMemberFn) return objInstr;
  1988. }
  1989. }
  1990. }
  1991. }
  1992. return nullptr;
  1993. }
  1994. SpirvInstruction *SpirvEmitter::processCall(const CallExpr *callExpr) {
  1995. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1996. // Note that we always want the defintion because Stmts/Exprs in the
  1997. // function body references the parameters in the definition.
  1998. if (!callee) {
  1999. emitError("found undefined function", callExpr->getExprLoc());
  2000. return nullptr;
  2001. }
  2002. const auto paramTypeMatchesArgType = [](QualType paramType,
  2003. QualType argType) {
  2004. if (argType == paramType)
  2005. return true;
  2006. if (const auto *refType = paramType->getAs<ReferenceType>())
  2007. paramType = refType->getPointeeType();
  2008. auto argUnqualifiedType = argType->getUnqualifiedDesugaredType();
  2009. auto paramUnqualifiedType = paramType->getUnqualifiedDesugaredType();
  2010. if (argUnqualifiedType == paramUnqualifiedType)
  2011. return true;
  2012. return false;
  2013. };
  2014. const auto numParams = callee->getNumParams();
  2015. bool isNonStaticMemberCall = false;
  2016. QualType objectType = {}; // Type of the object (if exists)
  2017. SpirvInstruction *objInstr = nullptr; // EvalInfo for the object (if exists)
  2018. llvm::SmallVector<SpirvInstruction *, 4> vars; // Variables for function call
  2019. llvm::SmallVector<bool, 4> isTempVar; // Temporary variable or not
  2020. llvm::SmallVector<SpirvInstruction *, 4> args; // Evaluated arguments
  2021. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  2022. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  2023. isNonStaticMemberCall = !memberFn->isStatic();
  2024. if (isNonStaticMemberCall) {
  2025. // For non-static member calls, evaluate the object and pass it as the
  2026. // first argument.
  2027. const auto *object = memberCall->getImplicitObjectArgument();
  2028. object = object->IgnoreParenNoopCasts(astContext);
  2029. // Update counter variable associated with the implicit object
  2030. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  2031. objectType = object->getType();
  2032. objInstr = doExpr(object);
  2033. if (auto *accessToBaseInstr = getBaseOfMemberFunction(objectType, objInstr, memberFn, memberCall->getExprLoc())) {
  2034. objInstr = accessToBaseInstr;
  2035. objectType = accessToBaseInstr->getAstResultType();
  2036. }
  2037. // If not already a variable, we need to create a temporary variable and
  2038. // pass the object pointer to the function. Example:
  2039. // getObject().objectMethod();
  2040. // Also, any parameter passed to the member function must be of Function
  2041. // storage class.
  2042. if (objInstr->isRValue()) {
  2043. args.push_back(createTemporaryVar(
  2044. objectType, getAstTypeName(objectType),
  2045. // May need to load to use as initializer
  2046. loadIfGLValue(object, objInstr), object->getLocStart()));
  2047. } else {
  2048. // Based on SPIR-V spec, function parameter must always be in Function
  2049. // scope. If we pass a non-function scope argument, we need
  2050. // the legalization.
  2051. if (objInstr->getStorageClass() != spv::StorageClass::Function ||
  2052. !isMemoryObjectDeclaration(objInstr))
  2053. beforeHlslLegalization = true;
  2054. args.push_back(objInstr);
  2055. }
  2056. // We do not need to create a new temporary variable for the this
  2057. // object. Use the evaluated argument.
  2058. vars.push_back(args.back());
  2059. isTempVar.push_back(false);
  2060. }
  2061. }
  2062. // Evaluate parameters
  2063. for (uint32_t i = 0; i < numParams; ++i) {
  2064. // We want the argument variable here so that we can write back to it
  2065. // later. We will do the OpLoad of this argument manually. So ingore
  2066. // the LValueToRValue implicit cast here.
  2067. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  2068. const auto *param = callee->getParamDecl(i);
  2069. const auto paramType = param->getType();
  2070. // Get the evaluation info if this argument is referencing some variable
  2071. // *as a whole*, in which case we can avoid creating the temporary variable
  2072. // for it if it can act as out parameter.
  2073. SpirvInstruction *argInfo = nullptr;
  2074. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(arg)) {
  2075. argInfo = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
  2076. arg->getLocStart());
  2077. }
  2078. auto *argInst = doExpr(arg);
  2079. // If argInfo is nullptr and argInst is a rvalue, we do not have a proper
  2080. // pointer to pass to the function. we need a temporary variable in that
  2081. // case.
  2082. //
  2083. // If we have an 'out/inout' resource as function argument, we need to
  2084. // create a temporary variable for it because the function definition
  2085. // expects are point-to-pointer argument for resources, which will be
  2086. // resolved by legalization.
  2087. if ((argInfo || (argInst && !argInst->isRValue())) &&
  2088. canActAsOutParmVar(param) && !isResourceType(paramType) &&
  2089. paramTypeMatchesArgType(paramType, arg->getType())) {
  2090. // Based on SPIR-V spec, function parameter must be always Function
  2091. // scope. In addition, we must pass memory object declaration argument
  2092. // to function. If we pass an argument that is not function scope
  2093. // or not memory object declaration, we need the legalization.
  2094. if (!argInfo || argInfo->getStorageClass() != spv::StorageClass::Function)
  2095. beforeHlslLegalization = true;
  2096. isTempVar.push_back(false);
  2097. args.push_back(argInst);
  2098. vars.push_back(argInfo ? argInfo : argInst);
  2099. } else {
  2100. // We need to create variables for holding the values to be used as
  2101. // arguments. The variables themselves are of pointer types.
  2102. const QualType varType =
  2103. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  2104. const std::string varName = "param.var." + param->getNameAsString();
  2105. // Temporary "param.var.*" variables are used for OpFunctionCall purposes.
  2106. // 'precise' attribute on function parameters only affect computations
  2107. // inside the function, not the variables at the call sites. Therefore, we
  2108. // do not need to mark the "param.var.*" variables as precise.
  2109. const bool isPrecise = false;
  2110. auto *tempVar =
  2111. spvBuilder.addFnVar(varType, arg->getLocStart(), varName, isPrecise);
  2112. vars.push_back(tempVar);
  2113. isTempVar.push_back(true);
  2114. args.push_back(argInst);
  2115. // Update counter variable associated with function parameters
  2116. tryToAssignCounterVar(param, arg);
  2117. // Manually load the argument here
  2118. auto *rhsVal = loadIfGLValue(arg, args.back());
  2119. // The AST does not include cast nodes to and from the function parameter
  2120. // type for 'out' and 'inout' cases. Example:
  2121. //
  2122. // void foo(out half3 param) {...}
  2123. // void main() { float3 arg; foo(arg); }
  2124. //
  2125. // In such cases, we first do a manual cast before passing the argument to
  2126. // the function. And we will cast back the results once the function call
  2127. // has returned.
  2128. if (canActAsOutParmVar(param) &&
  2129. !paramTypeMatchesArgType(paramType, arg->getType())) {
  2130. if (const auto *refType = paramType->getAs<ReferenceType>())
  2131. rhsVal = castToType(rhsVal, arg->getType(), refType->getPointeeType(),
  2132. arg->getLocStart());
  2133. }
  2134. // Initialize the temporary variables using the contents of the arguments
  2135. storeValue(tempVar, rhsVal, paramType, arg->getLocStart());
  2136. }
  2137. }
  2138. if (beforeHlslLegalization)
  2139. needsLegalization = true;
  2140. assert(vars.size() == isTempVar.size());
  2141. assert(vars.size() == args.size());
  2142. // Push the callee into the work queue if it is not there.
  2143. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(), callee,
  2144. /*isEntryFunction*/ false);
  2145. const QualType retType =
  2146. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  2147. // Get or forward declare the function <result-id>
  2148. SpirvFunction *func = declIdMapper.getOrRegisterFn(callee);
  2149. auto *retVal = spvBuilder.createFunctionCall(
  2150. retType, func, vars, callExpr->getCallee()->getExprLoc());
  2151. // Go through all parameters and write those marked as out/inout
  2152. for (uint32_t i = 0; i < numParams; ++i) {
  2153. const auto *param = callee->getParamDecl(i);
  2154. const auto paramType = param->getType();
  2155. // If it calls a non-static member function, the object itself is argument
  2156. // 0, and therefore all other argument positions are shifted by 1.
  2157. const uint32_t index = i + isNonStaticMemberCall;
  2158. // Using a resouce as a function parameter is never passed-by-copy. As a
  2159. // result, even if the function parameter is marked as 'out' or 'inout',
  2160. // there is no reason to copy back the results after the function call into
  2161. // the resource.
  2162. if (isTempVar[index] && canActAsOutParmVar(param) &&
  2163. !isResourceType(paramType)) {
  2164. const auto *arg = callExpr->getArg(i);
  2165. SpirvInstruction *value =
  2166. spvBuilder.createLoad(paramType, vars[index], arg->getLocStart());
  2167. // Now we want to assign 'value' to arg. But first, in rare cases when
  2168. // using 'out' or 'inout' where the parameter and argument have a type
  2169. // mismatch, we need to first cast 'value' to the type of 'arg' because
  2170. // the AST will not include a cast node.
  2171. if (!paramTypeMatchesArgType(paramType, arg->getType())) {
  2172. if (const auto *refType = paramType->getAs<ReferenceType>())
  2173. value = castToType(value, refType->getPointeeType(), arg->getType(),
  2174. arg->getLocStart());
  2175. }
  2176. processAssignment(arg, value, false, args[index]);
  2177. }
  2178. }
  2179. return retVal;
  2180. }
  2181. SpirvInstruction *SpirvEmitter::doCastExpr(const CastExpr *expr) {
  2182. const Expr *subExpr = expr->getSubExpr();
  2183. const QualType subExprType = subExpr->getType();
  2184. const QualType toType = expr->getType();
  2185. const auto srcLoc = expr->getExprLoc();
  2186. switch (expr->getCastKind()) {
  2187. case CastKind::CK_LValueToRValue:
  2188. return loadIfGLValue(subExpr);
  2189. case CastKind::CK_NoOp:
  2190. return doExpr(subExpr);
  2191. case CastKind::CK_IntegralCast:
  2192. case CastKind::CK_FloatingToIntegral:
  2193. case CastKind::CK_HLSLCC_IntegralCast:
  2194. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  2195. // Integer literals in the AST are represented using 64bit APInt
  2196. // themselves and then implicitly casted into the expected bitwidth.
  2197. // We need special treatment of integer literals here because generating
  2198. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  2199. // capability. We should avoid introducing unnecessary capabilities to
  2200. // our best.
  2201. if (auto *value = tryToEvaluateAsConst(expr)) {
  2202. value->setRValue();
  2203. return value;
  2204. }
  2205. auto *value = castToInt(loadIfGLValue(subExpr), subExprType, toType,
  2206. subExpr->getLocStart());
  2207. value->setRValue();
  2208. return value;
  2209. }
  2210. case CastKind::CK_FloatingCast:
  2211. case CastKind::CK_IntegralToFloating:
  2212. case CastKind::CK_HLSLCC_FloatingCast:
  2213. case CastKind::CK_HLSLCC_IntegralToFloating: {
  2214. // First try to see if we can do constant folding for floating point
  2215. // numbers like what we are doing for integers in the above.
  2216. if (auto *value = tryToEvaluateAsConst(expr)) {
  2217. value->setRValue();
  2218. return value;
  2219. }
  2220. auto *value = castToFloat(loadIfGLValue(subExpr), subExprType, toType,
  2221. subExpr->getLocStart());
  2222. value->setRValue();
  2223. return value;
  2224. }
  2225. case CastKind::CK_IntegralToBoolean:
  2226. case CastKind::CK_FloatingToBoolean:
  2227. case CastKind::CK_HLSLCC_IntegralToBoolean:
  2228. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  2229. // First try to see if we can do constant folding.
  2230. if (auto *value = tryToEvaluateAsConst(expr)) {
  2231. value->setRValue();
  2232. return value;
  2233. }
  2234. auto *value = castToBool(loadIfGLValue(subExpr), subExprType, toType,
  2235. subExpr->getLocStart());
  2236. value->setRValue();
  2237. return value;
  2238. }
  2239. case CastKind::CK_HLSLVectorSplat: {
  2240. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  2241. return createVectorSplat(subExpr, size);
  2242. }
  2243. case CastKind::CK_HLSLVectorTruncationCast: {
  2244. const QualType toVecType = toType;
  2245. const QualType elemType = hlsl::GetHLSLVecElementType(toType);
  2246. const auto toSize = hlsl::GetHLSLVecSize(toType);
  2247. auto *composite = doExpr(subExpr);
  2248. llvm::SmallVector<SpirvInstruction *, 4> elements;
  2249. for (uint32_t i = 0; i < toSize; ++i) {
  2250. elements.push_back(spvBuilder.createCompositeExtract(
  2251. elemType, composite, {i}, expr->getExprLoc()));
  2252. }
  2253. auto *value = elements.front();
  2254. if (toSize > 1) {
  2255. value = spvBuilder.createCompositeConstruct(toVecType, elements,
  2256. expr->getExprLoc());
  2257. }
  2258. value->setRValue();
  2259. return value;
  2260. }
  2261. case CastKind::CK_HLSLVectorToScalarCast: {
  2262. // The underlying should already be a vector of size 1.
  2263. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  2264. return doExpr(subExpr);
  2265. }
  2266. case CastKind::CK_HLSLVectorToMatrixCast: {
  2267. // If target type is already an 1xN matrix type, we just return the
  2268. // underlying vector.
  2269. if (is1xNMatrix(toType))
  2270. return doExpr(subExpr);
  2271. // A vector can have no more than 4 elements. The only remaining case
  2272. // is casting from size-4 vector to size-2-by-2 matrix.
  2273. auto *vec = loadIfGLValue(subExpr);
  2274. QualType elemType = {};
  2275. uint32_t rowCount = 0, colCount = 0;
  2276. const bool isMat = isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  2277. assert(isMat && rowCount == 2 && colCount == 2);
  2278. (void)isMat;
  2279. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2280. auto *subVec1 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1},
  2281. expr->getLocStart());
  2282. auto *subVec2 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3},
  2283. expr->getLocStart());
  2284. auto *mat = spvBuilder.createCompositeConstruct(toType, {subVec1, subVec2},
  2285. expr->getLocStart());
  2286. mat->setRValue();
  2287. return mat;
  2288. }
  2289. case CastKind::CK_HLSLMatrixSplat: {
  2290. // From scalar to matrix
  2291. uint32_t rowCount = 0, colCount = 0;
  2292. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  2293. // Handle degenerated cases first
  2294. if (rowCount == 1 && colCount == 1)
  2295. return doExpr(subExpr);
  2296. if (colCount == 1)
  2297. return createVectorSplat(subExpr, rowCount);
  2298. const auto vecSplat = createVectorSplat(subExpr, colCount);
  2299. if (rowCount == 1)
  2300. return vecSplat;
  2301. if (isa<SpirvConstant>(vecSplat)) {
  2302. llvm::SmallVector<SpirvConstant *, 4> vectors(
  2303. size_t(rowCount), cast<SpirvConstant>(vecSplat));
  2304. auto *value = spvBuilder.getConstantComposite(toType, vectors);
  2305. value->setRValue();
  2306. return value;
  2307. } else {
  2308. llvm::SmallVector<SpirvInstruction *, 4> vectors(size_t(rowCount),
  2309. vecSplat);
  2310. auto *value = spvBuilder.createCompositeConstruct(toType, vectors,
  2311. expr->getLocEnd());
  2312. value->setRValue();
  2313. return value;
  2314. }
  2315. }
  2316. case CastKind::CK_HLSLMatrixTruncationCast: {
  2317. const QualType srcType = subExprType;
  2318. auto *src = doExpr(subExpr);
  2319. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  2320. llvm::SmallVector<uint32_t, 4> indexes;
  2321. // It is possible that the source matrix is in fact a vector.
  2322. // Example 1: Truncate float1x3 --> float1x2.
  2323. // Example 2: Truncate float1x3 --> float1x1.
  2324. // The front-end disallows float1x3 --> float2x1.
  2325. {
  2326. uint32_t srcVecSize = 0, dstVecSize = 0;
  2327. if (isVectorType(srcType, nullptr, &srcVecSize) && isScalarType(toType)) {
  2328. auto *val = spvBuilder.createCompositeExtract(toType, src, {0},
  2329. expr->getLocStart());
  2330. val->setRValue();
  2331. return val;
  2332. }
  2333. if (isVectorType(srcType, nullptr, &srcVecSize) &&
  2334. isVectorType(toType, nullptr, &dstVecSize)) {
  2335. for (uint32_t i = 0; i < dstVecSize; ++i)
  2336. indexes.push_back(i);
  2337. auto *val = spvBuilder.createVectorShuffle(toType, src, src, indexes,
  2338. expr->getLocStart());
  2339. val->setRValue();
  2340. return val;
  2341. }
  2342. }
  2343. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  2344. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  2345. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  2346. const QualType srcRowType = astContext.getExtVectorType(elemType, srcCols);
  2347. const QualType dstRowType = astContext.getExtVectorType(elemType, dstCols);
  2348. // Indexes to pass to OpVectorShuffle
  2349. for (uint32_t i = 0; i < dstCols; ++i)
  2350. indexes.push_back(i);
  2351. llvm::SmallVector<SpirvInstruction *, 4> extractedVecs;
  2352. for (uint32_t row = 0; row < dstRows; ++row) {
  2353. // Extract a row
  2354. SpirvInstruction *rowInstr = spvBuilder.createCompositeExtract(
  2355. srcRowType, src, {row}, expr->getExprLoc());
  2356. // Extract the necessary columns from that row.
  2357. // The front-end ensures dstCols <= srcCols.
  2358. // If dstCols equals srcCols, we can use the whole row directly.
  2359. if (dstCols == 1) {
  2360. rowInstr = spvBuilder.createCompositeExtract(elemType, rowInstr, {0},
  2361. expr->getLocStart());
  2362. } else if (dstCols < srcCols) {
  2363. rowInstr = spvBuilder.createVectorShuffle(
  2364. dstRowType, rowInstr, rowInstr, indexes, expr->getLocStart());
  2365. }
  2366. extractedVecs.push_back(rowInstr);
  2367. }
  2368. auto *val = extractedVecs.front();
  2369. if (extractedVecs.size() > 1) {
  2370. val = spvBuilder.createCompositeConstruct(toType, extractedVecs,
  2371. expr->getExprLoc());
  2372. }
  2373. val->setRValue();
  2374. return val;
  2375. }
  2376. case CastKind::CK_HLSLMatrixToScalarCast: {
  2377. // The underlying should already be a matrix of 1x1.
  2378. assert(is1x1Matrix(subExprType));
  2379. return doExpr(subExpr);
  2380. }
  2381. case CastKind::CK_HLSLMatrixToVectorCast: {
  2382. // If the underlying matrix is Mx1 or 1xM for M in {1, 2,3,4}, we can return
  2383. // the underlying matrix because it'll be evaluated as a vector by default.
  2384. if (is1x1Matrix(subExprType) || is1xNMatrix(subExprType) ||
  2385. isMx1Matrix(subExprType))
  2386. return doExpr(subExpr);
  2387. // A vector can have no more than 4 elements. The only remaining case
  2388. // is casting from a 2x2 matrix to a vector of size 4.
  2389. auto *mat = loadIfGLValue(subExpr);
  2390. QualType elemType = {};
  2391. uint32_t rowCount = 0, colCount = 0, elemCount = 0;
  2392. const bool isMat =
  2393. isMxNMatrix(subExprType, &elemType, &rowCount, &colCount);
  2394. const bool isVec = isVectorType(toType, nullptr, &elemCount);
  2395. assert(isMat && rowCount == 2 && colCount == 2);
  2396. assert(isVec && elemCount == 4);
  2397. (void)isMat;
  2398. (void)isVec;
  2399. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2400. auto *row0 = spvBuilder.createCompositeExtract(vec2Type, mat, {0}, srcLoc);
  2401. auto *row1 = spvBuilder.createCompositeExtract(vec2Type, mat, {1}, srcLoc);
  2402. auto *vec = spvBuilder.createVectorShuffle(toType, row0, row1, {0, 1, 2, 3},
  2403. srcLoc);
  2404. vec->setRValue();
  2405. return vec;
  2406. }
  2407. case CastKind::CK_FunctionToPointerDecay:
  2408. // Just need to return the function id
  2409. return doExpr(subExpr);
  2410. case CastKind::CK_FlatConversion: {
  2411. SpirvInstruction *subExprInstr = nullptr;
  2412. QualType evalType = subExprType;
  2413. // Optimization: we can use OpConstantNull for cases where we want to
  2414. // initialize an entire data structure to zeros.
  2415. if (evaluatesToConstZero(subExpr, astContext)) {
  2416. subExprInstr = spvBuilder.getConstantNull(toType);
  2417. subExprInstr->setRValue();
  2418. return subExprInstr;
  2419. }
  2420. // Try to evaluate float literals as float rather than double.
  2421. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2422. subExprInstr = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2423. if (subExprInstr)
  2424. evalType = astContext.FloatTy;
  2425. }
  2426. // Evaluate 'literal float' initializer type as float rather than double.
  2427. // TODO: This could result in rounding error if the initializer is a
  2428. // non-literal expression that requires larger than 32 bits and has the
  2429. // 'literal float' type.
  2430. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2431. evalType = astContext.FloatTy;
  2432. }
  2433. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2434. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2435. const bool isSigned = subExprType->isSignedIntegerType();
  2436. subExprInstr = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2437. if (subExprInstr)
  2438. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2439. }
  2440. // For assigning one array instance to another one with the same array type
  2441. // (regardless of constness and literalness), the rhs will be wrapped in a
  2442. // FlatConversion. Similarly for assigning a struct to another struct with
  2443. // identical members.
  2444. // |- <lhs>
  2445. // `- ImplicitCastExpr <FlatConversion>
  2446. // `- ImplicitCastExpr <LValueToRValue>
  2447. // `- <rhs>
  2448. else if (isSameType(astContext, toType, evalType) ||
  2449. // We can have casts changing the shape but without affecting
  2450. // memory order, e.g., `float4 a[2]; float b[8] = (float[8])a;`.
  2451. // This is also represented as FlatConversion. For such cases, we
  2452. // can rely on the InitListHandler, which can decompse
  2453. // vectors/matrices.
  2454. subExprType->isArrayType()) {
  2455. auto *valInstr =
  2456. InitListHandler(astContext, *this).processCast(toType, subExpr);
  2457. if (valInstr)
  2458. valInstr->setRValue();
  2459. return valInstr;
  2460. }
  2461. // We can have casts changing the shape but without affecting memory order,
  2462. // e.g., `float4 a[2]; float b[8] = (float[8])a;`. This is also represented
  2463. // as FlatConversion. For such cases, we can rely on the InitListHandler,
  2464. // which can decompse vectors/matrices.
  2465. else if (subExprType->isArrayType()) {
  2466. auto *valInstr = InitListHandler(astContext, *this)
  2467. .processCast(expr->getType(), subExpr);
  2468. if (valInstr)
  2469. valInstr->setRValue();
  2470. return valInstr;
  2471. }
  2472. if (!subExprInstr)
  2473. subExprInstr = doExpr(subExpr);
  2474. auto *val = processFlatConversion(toType, evalType, subExprInstr,
  2475. expr->getExprLoc());
  2476. val->setRValue();
  2477. return val;
  2478. }
  2479. case CastKind::CK_UncheckedDerivedToBase:
  2480. case CastKind::CK_HLSLDerivedToBase: {
  2481. // Find the index sequence of the base to which we are casting
  2482. llvm::SmallVector<uint32_t, 4> baseIndices;
  2483. getBaseClassIndices(expr, &baseIndices);
  2484. // Turn them in to SPIR-V constants
  2485. llvm::SmallVector<SpirvInstruction *, 4> baseIndexInstructions(
  2486. baseIndices.size(), nullptr);
  2487. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2488. baseIndexInstructions[i] = spvBuilder.getConstantInt(
  2489. astContext.UnsignedIntTy, llvm::APInt(32, baseIndices[i]));
  2490. auto *derivedInfo = doExpr(subExpr);
  2491. return turnIntoElementPtr(subExpr->getType(), derivedInfo, expr->getType(),
  2492. baseIndexInstructions, subExpr->getExprLoc());
  2493. }
  2494. case CastKind::CK_ArrayToPointerDecay: {
  2495. // Literal string to const string conversion falls under this category.
  2496. if (hlsl::IsStringLiteralType(subExprType) && hlsl::IsStringType(toType)) {
  2497. return doExpr(subExpr);
  2498. } else {
  2499. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2500. << expr->getCastKindName() << expr->getSourceRange();
  2501. expr->dump();
  2502. return 0;
  2503. }
  2504. }
  2505. default:
  2506. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2507. << expr->getCastKindName() << expr->getSourceRange();
  2508. expr->dump();
  2509. return 0;
  2510. }
  2511. }
  2512. SpirvInstruction *SpirvEmitter::processFlatConversion(
  2513. const QualType type, const QualType initType, SpirvInstruction *initInstr,
  2514. SourceLocation srcLoc) {
  2515. // When translating ConstantBuffer<T> or TextureBuffer<T> types, we consider
  2516. // the underlying type (T), and therefore we should bypass the FlatConversion
  2517. // node when accessing these types:
  2518. // `-MemberExpr
  2519. // `-ImplicitCastExpr 'const T' lvalue <FlatConversion>
  2520. // `-ArraySubscriptExpr 'ConstantBuffer<T>':'ConstantBuffer<T>' lvalue
  2521. if (isConstantTextureBuffer(initType)) {
  2522. return initInstr;
  2523. }
  2524. // Try to translate the canonical type first
  2525. const auto canonicalType = type.getCanonicalType();
  2526. if (canonicalType != type)
  2527. return processFlatConversion(canonicalType, initType, initInstr, srcLoc);
  2528. // Primitive types
  2529. {
  2530. QualType ty = {};
  2531. if (isScalarType(type, &ty)) {
  2532. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2533. switch (builtinType->getKind()) {
  2534. case BuiltinType::Void: {
  2535. emitError("cannot create a constant of void type", srcLoc);
  2536. return 0;
  2537. }
  2538. case BuiltinType::Bool:
  2539. return castToBool(initInstr, initType, ty, srcLoc);
  2540. // Target type is an integer variant.
  2541. case BuiltinType::Int:
  2542. case BuiltinType::Short:
  2543. case BuiltinType::Min12Int:
  2544. case BuiltinType::Min16Int:
  2545. case BuiltinType::Min16UInt:
  2546. case BuiltinType::UShort:
  2547. case BuiltinType::UInt:
  2548. case BuiltinType::Long:
  2549. case BuiltinType::LongLong:
  2550. case BuiltinType::ULong:
  2551. case BuiltinType::ULongLong:
  2552. case BuiltinType::Int8_4Packed:
  2553. case BuiltinType::UInt8_4Packed:
  2554. return castToInt(initInstr, initType, ty, srcLoc);
  2555. // Target type is a float variant.
  2556. case BuiltinType::Double:
  2557. case BuiltinType::Float:
  2558. case BuiltinType::Half:
  2559. case BuiltinType::HalfFloat:
  2560. case BuiltinType::Min10Float:
  2561. case BuiltinType::Min16Float:
  2562. return castToFloat(initInstr, initType, ty, srcLoc);
  2563. default:
  2564. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2565. << builtinType->getTypeClassName();
  2566. return 0;
  2567. }
  2568. }
  2569. }
  2570. }
  2571. // Vector types
  2572. {
  2573. QualType elemType = {};
  2574. uint32_t elemCount = {};
  2575. if (isVectorType(type, &elemType, &elemCount)) {
  2576. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2577. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(elemCount),
  2578. elem);
  2579. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2580. }
  2581. }
  2582. // Matrix types
  2583. {
  2584. QualType elemType = {};
  2585. uint32_t rowCount = 0, colCount = 0;
  2586. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2587. // By default HLSL matrices are row major, while SPIR-V matrices are
  2588. // column major. We are mapping what HLSL semantically mean a row into a
  2589. // column here.
  2590. const QualType vecType = astContext.getExtVectorType(elemType, colCount);
  2591. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2592. const llvm::SmallVector<SpirvInstruction *, 4> constituents(
  2593. size_t(colCount), elem);
  2594. auto *col =
  2595. spvBuilder.createCompositeConstruct(vecType, constituents, srcLoc);
  2596. const llvm::SmallVector<SpirvInstruction *, 4> rows(size_t(rowCount),
  2597. col);
  2598. return spvBuilder.createCompositeConstruct(type, rows, srcLoc);
  2599. }
  2600. }
  2601. // Struct type
  2602. if (const auto *structType = type->getAs<RecordType>()) {
  2603. const auto *decl = structType->getDecl();
  2604. llvm::SmallVector<SpirvInstruction *, 4> fields;
  2605. for (const auto *field : decl->fields()) {
  2606. // There is a special case for FlatConversion. If T is a struct with only
  2607. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2608. // constructs a new T instance using the instance of S as its only member.
  2609. // Check whether we are handling that case here first.
  2610. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2611. fields.push_back(initInstr);
  2612. } else {
  2613. fields.push_back(processFlatConversion(field->getType(), initType,
  2614. initInstr, srcLoc));
  2615. }
  2616. }
  2617. return spvBuilder.createCompositeConstruct(type, fields, srcLoc);
  2618. }
  2619. // Array type
  2620. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2621. const auto size =
  2622. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2623. auto *elem = processFlatConversion(arrayType->getElementType(), initType,
  2624. initInstr, srcLoc);
  2625. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(size), elem);
  2626. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2627. }
  2628. emitError("flat conversion of type %0 unimplemented", {})
  2629. << type->getTypeClassName();
  2630. type->dump();
  2631. return 0;
  2632. }
  2633. SpirvInstruction *
  2634. SpirvEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2635. const auto opcode = expr->getOpcode();
  2636. // Try to optimize floatMxN *= float and floatN *= float case
  2637. if (opcode == BO_MulAssign) {
  2638. if (auto *result = tryToGenFloatMatrixScale(expr))
  2639. return result;
  2640. if (auto *result = tryToGenFloatVectorScale(expr))
  2641. return result;
  2642. }
  2643. const auto *rhs = expr->getRHS();
  2644. const auto *lhs = expr->getLHS();
  2645. SpirvInstruction *lhsPtr = nullptr;
  2646. auto *result = processBinaryOp(
  2647. lhs, rhs, opcode, expr->getComputationLHSType(), expr->getType(),
  2648. expr->getSourceRange(), expr->getOperatorLoc(), &lhsPtr);
  2649. return processAssignment(lhs, result, true, lhsPtr);
  2650. }
  2651. SpirvInstruction *
  2652. SpirvEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2653. const auto type = expr->getType();
  2654. const SourceLocation loc = expr->getExprLoc();
  2655. const Expr *cond = expr->getCond();
  2656. const Expr *falseExpr = expr->getFalseExpr();
  2657. const Expr *trueExpr = expr->getTrueExpr();
  2658. // According to HLSL doc, all sides of the ?: expression are always evaluated.
  2659. // Corner-case: In HLSL, the condition of the ternary operator can be a
  2660. // matrix of booleans which results in selecting between components of two
  2661. // matrices. However, a matrix of booleans is not a valid type in SPIR-V.
  2662. // If the AST has inserted a splat of a scalar/vector to a matrix, we can just
  2663. // use that scalar/vector as an if-clause condition.
  2664. if (auto *cast = dyn_cast<ImplicitCastExpr>(cond))
  2665. if (cast->getCastKind() == CK_HLSLMatrixSplat)
  2666. cond = cast->getSubExpr();
  2667. // If we are selecting between two SampleState objects, none of the three
  2668. // operands has a LValueToRValue implicit cast.
  2669. auto *condition = loadIfGLValue(cond);
  2670. auto *trueBranch = loadIfGLValue(trueExpr);
  2671. auto *falseBranch = loadIfGLValue(falseExpr);
  2672. // Corner-case: In HLSL, the condition of the ternary operator can be a
  2673. // matrix of booleans which results in selecting between components of two
  2674. // matrices. However, a matrix of booleans is not a valid type in SPIR-V.
  2675. // Therefore, we need to perform OpSelect for each row of the matrix.
  2676. {
  2677. QualType condElemType = {}, elemType = {};
  2678. uint32_t rowCount = 0, colCount = 0;
  2679. if (isMxNMatrix(type, &elemType, &rowCount, &colCount) &&
  2680. isMxNMatrix(cond->getType(), &condElemType) &&
  2681. condElemType->isBooleanType()) {
  2682. const auto rowType = astContext.getExtVectorType(elemType, colCount);
  2683. const auto condRowType =
  2684. astContext.getExtVectorType(condElemType, colCount);
  2685. llvm::SmallVector<SpirvInstruction *, 4> rows;
  2686. for (uint32_t i = 0; i < rowCount; ++i) {
  2687. auto *condRow =
  2688. spvBuilder.createCompositeExtract(condRowType, condition, {i}, loc);
  2689. auto *trueRow =
  2690. spvBuilder.createCompositeExtract(rowType, trueBranch, {i}, loc);
  2691. auto *falseRow =
  2692. spvBuilder.createCompositeExtract(rowType, falseBranch, {i}, loc);
  2693. rows.push_back(
  2694. spvBuilder.createSelect(rowType, condRow, trueRow, falseRow, loc));
  2695. }
  2696. auto *result = spvBuilder.createCompositeConstruct(type, rows, loc);
  2697. result->setRValue();
  2698. return result;
  2699. }
  2700. }
  2701. // For cases where the return type is a scalar or a vector, we can use
  2702. // OpSelect to choose between the two. OpSelect's return type must be either
  2703. // scalar or vector.
  2704. if (isScalarType(type) || isVectorType(type)) {
  2705. // The SPIR-V OpSelect instruction must have a selection argument that is
  2706. // the same size as the return type. If the return type is a vector, the
  2707. // selection must be a vector of booleans (one per output component).
  2708. uint32_t count = 0;
  2709. if (isVectorType(expr->getType(), nullptr, &count) &&
  2710. !isVectorType(expr->getCond()->getType())) {
  2711. const llvm::SmallVector<SpirvInstruction *, 4> components(size_t(count),
  2712. condition);
  2713. condition = spvBuilder.createCompositeConstruct(
  2714. astContext.getExtVectorType(astContext.BoolTy, count), components,
  2715. expr->getCond()->getLocEnd());
  2716. }
  2717. auto *value =
  2718. spvBuilder.createSelect(type, condition, trueBranch, falseBranch, loc);
  2719. value->setRValue();
  2720. return value;
  2721. }
  2722. // If we can't use OpSelect, we need to create if-else control flow.
  2723. auto *tempVar = spvBuilder.addFnVar(type, loc, "temp.var.ternary");
  2724. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  2725. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  2726. auto *elseBB = spvBuilder.createBasicBlock("if.false");
  2727. // Create the branch instruction. This will end the current basic block.
  2728. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  2729. expr->getCond()->getLocEnd(), mergeBB);
  2730. spvBuilder.addSuccessor(thenBB);
  2731. spvBuilder.addSuccessor(elseBB);
  2732. spvBuilder.setMergeTarget(mergeBB);
  2733. // Handle the then branch
  2734. spvBuilder.setInsertPoint(thenBB);
  2735. spvBuilder.createStore(tempVar, trueBranch,
  2736. expr->getTrueExpr()->getLocStart());
  2737. spvBuilder.createBranch(mergeBB, expr->getTrueExpr()->getLocEnd());
  2738. spvBuilder.addSuccessor(mergeBB);
  2739. // Handle the else branch
  2740. spvBuilder.setInsertPoint(elseBB);
  2741. spvBuilder.createStore(tempVar, falseBranch,
  2742. expr->getFalseExpr()->getLocStart());
  2743. spvBuilder.createBranch(mergeBB, expr->getFalseExpr()->getLocEnd());
  2744. spvBuilder.addSuccessor(mergeBB);
  2745. // From now on, emit instructions into the merge block.
  2746. spvBuilder.setInsertPoint(mergeBB);
  2747. auto *result = spvBuilder.createLoad(type, tempVar, expr->getLocEnd());
  2748. result->setRValue();
  2749. return result;
  2750. }
  2751. SpirvInstruction *
  2752. SpirvEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2753. const CXXMemberCallExpr *expr) {
  2754. const auto *object = expr->getImplicitObjectArgument();
  2755. auto *objectInstr = loadIfAliasVarRef(object);
  2756. const auto type = object->getType();
  2757. const bool isBABuf = isByteAddressBuffer(type) || isRWByteAddressBuffer(type);
  2758. const bool isStructuredBuf = isStructuredBuffer(type) ||
  2759. isAppendStructuredBuffer(type) ||
  2760. isConsumeStructuredBuffer(type);
  2761. assert(isBABuf || isStructuredBuf);
  2762. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2763. // with only one member that is a runtime array. We need to perform
  2764. // OpArrayLength on member 0.
  2765. SpirvInstruction *length = spvBuilder.createArrayLength(
  2766. astContext.UnsignedIntTy, expr->getExprLoc(), objectInstr, 0);
  2767. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2768. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2769. // array. Therefore we must multiply the results by 4.
  2770. if (isBABuf) {
  2771. length = spvBuilder.createBinaryOp(
  2772. spv::Op::OpIMul, astContext.UnsignedIntTy, length,
  2773. // TODO(jaebaek): What line info we should emit for constants?
  2774. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2775. llvm::APInt(32, 4u)),
  2776. expr->getExprLoc());
  2777. }
  2778. spvBuilder.createStore(doExpr(expr->getArg(0)), length,
  2779. expr->getArg(0)->getLocStart());
  2780. if (isStructuredBuf) {
  2781. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2782. // size of the struct) must also be written to the second argument.
  2783. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  2784. uint32_t size = 0, stride = 0;
  2785. std::tie(std::ignore, size) =
  2786. alignmentCalc.getAlignmentAndSize(type, spirvOptions.sBufferLayoutRule,
  2787. /*isRowMajor*/ llvm::None, &stride);
  2788. auto *sizeInstr = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2789. llvm::APInt(32, size));
  2790. spvBuilder.createStore(doExpr(expr->getArg(1)), sizeInstr,
  2791. expr->getArg(1)->getLocStart());
  2792. }
  2793. return nullptr;
  2794. }
  2795. SpirvInstruction *SpirvEmitter::processRWByteAddressBufferAtomicMethods(
  2796. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2797. // The signature of RWByteAddressBuffer atomic methods are largely:
  2798. // void Interlocked*(in UINT dest, in UINT value);
  2799. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2800. const auto *object = expr->getImplicitObjectArgument();
  2801. auto *objectInfo = loadIfAliasVarRef(object);
  2802. auto *zero =
  2803. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  2804. auto *offset = doExpr(expr->getArg(0));
  2805. // Right shift by 2 to convert the byte offset to uint32_t offset
  2806. auto *address = spvBuilder.createBinaryOp(
  2807. spv::Op::OpShiftRightLogical, astContext.UnsignedIntTy, offset,
  2808. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  2809. expr->getExprLoc());
  2810. auto *ptr =
  2811. spvBuilder.createAccessChain(astContext.UnsignedIntTy, objectInfo,
  2812. {zero, address}, object->getLocStart());
  2813. const bool isCompareExchange =
  2814. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2815. const bool isCompareStore =
  2816. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2817. if (isCompareExchange || isCompareStore) {
  2818. auto *comparator = doExpr(expr->getArg(1));
  2819. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  2820. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2821. spv::MemorySemanticsMask::MaskNone, spv::MemorySemanticsMask::MaskNone,
  2822. doExpr(expr->getArg(2)), comparator, expr->getCallee()->getExprLoc());
  2823. if (isCompareExchange)
  2824. spvBuilder.createStore(doExpr(expr->getArg(3)), originalVal,
  2825. expr->getArg(3)->getLocStart());
  2826. } else {
  2827. auto *value = doExpr(expr->getArg(1));
  2828. SpirvInstruction *originalVal = spvBuilder.createAtomicOp(
  2829. translateAtomicHlslOpcodeToSpirvOpcode(opcode),
  2830. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2831. spv::MemorySemanticsMask::MaskNone, value,
  2832. expr->getCallee()->getExprLoc());
  2833. if (expr->getNumArgs() > 2) {
  2834. originalVal = castToType(originalVal, astContext.UnsignedIntTy,
  2835. expr->getArg(2)->getType(),
  2836. expr->getArg(2)->getLocStart());
  2837. spvBuilder.createStore(doExpr(expr->getArg(2)), originalVal,
  2838. expr->getArg(2)->getLocStart());
  2839. }
  2840. }
  2841. return nullptr;
  2842. }
  2843. SpirvInstruction *
  2844. SpirvEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2845. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2846. auto *sampleCount = spvBuilder.createImageQuery(
  2847. spv::Op::OpImageQuerySamples, astContext.UnsignedIntTy,
  2848. expr->getExprLoc(), loadIfGLValue(object));
  2849. if (!spirvOptions.noWarnEmulatedFeatures)
  2850. emitWarning("GetSamplePosition is emulated using many SPIR-V instructions "
  2851. "due to lack of direct SPIR-V equivalent, so it only supports "
  2852. "standard sample settings with 1, 2, 4, 8, or 16 samples and "
  2853. "will return float2(0, 0) for other cases",
  2854. expr->getCallee()->getExprLoc());
  2855. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)),
  2856. expr->getCallee()->getExprLoc());
  2857. }
  2858. SpirvInstruction *
  2859. SpirvEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2860. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2861. SpirvInstruction *sample =
  2862. expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : nullptr;
  2863. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2864. auto *location = spvBuilder.getConstantComposite(
  2865. astContext.getExtVectorType(astContext.IntTy, 2), {zero, zero});
  2866. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2867. /*varOffset*/ 0, /*lod*/ sample,
  2868. /*residencyCode*/ 0, expr->getExprLoc());
  2869. }
  2870. SpirvInstruction *
  2871. SpirvEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2872. const auto *object = expr->getImplicitObjectArgument();
  2873. auto *objectInstr = loadIfGLValue(object);
  2874. const auto type = object->getType();
  2875. const auto *recType = type->getAs<RecordType>();
  2876. assert(recType);
  2877. const auto typeName = recType->getDecl()->getName();
  2878. const auto numArgs = expr->getNumArgs();
  2879. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2880. assert(isTexture(type) || isRWTexture(type) || isBuffer(type) ||
  2881. isRWBuffer(type));
  2882. // For Texture1D, arguments are either:
  2883. // a) width
  2884. // b) MipLevel, width, NumLevels
  2885. // For Texture1DArray, arguments are either:
  2886. // a) width, elements
  2887. // b) MipLevel, width, elements, NumLevels
  2888. // For Texture2D, arguments are either:
  2889. // a) width, height
  2890. // b) MipLevel, width, height, NumLevels
  2891. // For Texture2DArray, arguments are either:
  2892. // a) width, height, elements
  2893. // b) MipLevel, width, height, elements, NumLevels
  2894. // For Texture3D, arguments are either:
  2895. // a) width, height, depth
  2896. // b) MipLevel, width, height, depth, NumLevels
  2897. // For Texture2DMS, arguments are: width, height, NumSamples
  2898. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2899. // For TextureCube, arguments are either:
  2900. // a) width, height
  2901. // b) MipLevel, width, height, NumLevels
  2902. // For TextureCubeArray, arguments are either:
  2903. // a) width, height, elements
  2904. // b) MipLevel, width, height, elements, NumLevels
  2905. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2906. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2907. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2908. // The HLSL methods, however, have overloaded functions which have float
  2909. // output arguments. Since the AST naturally won't have casting AST nodes for
  2910. // such cases, we'll have to perform the cast ourselves.
  2911. const auto storeToOutputArg = [this](const Expr *outputArg,
  2912. SpirvInstruction *id, QualType type) {
  2913. id = castToType(id, type, outputArg->getType(), outputArg->getExprLoc());
  2914. spvBuilder.createStore(doExpr(outputArg), id, outputArg->getLocStart());
  2915. };
  2916. if ((typeName == "Texture1D" && numArgs > 1) ||
  2917. (typeName == "Texture2D" && numArgs > 2) ||
  2918. (typeName == "TextureCube" && numArgs > 2) ||
  2919. (typeName == "Texture3D" && numArgs > 3) ||
  2920. (typeName == "Texture1DArray" && numArgs > 2) ||
  2921. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2922. (typeName == "Texture2DArray" && numArgs > 3)) {
  2923. mipLevel = expr->getArg(0);
  2924. numLevels = expr->getArg(numArgs - 1);
  2925. }
  2926. if (isTextureMS(type)) {
  2927. numSamples = expr->getArg(numArgs - 1);
  2928. }
  2929. uint32_t querySize = numArgs;
  2930. // If numLevels arg is present, mipLevel must also be present. These are not
  2931. // queried via ImageQuerySizeLod.
  2932. if (numLevels)
  2933. querySize -= 2;
  2934. // If numLevels arg is present, mipLevel must also be present.
  2935. else if (numSamples)
  2936. querySize -= 1;
  2937. const QualType resultQualType =
  2938. querySize == 1
  2939. ? astContext.UnsignedIntTy
  2940. : astContext.getExtVectorType(astContext.UnsignedIntTy, querySize);
  2941. // Only Texture types use ImageQuerySizeLod.
  2942. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2943. SpirvInstruction *lod = nullptr;
  2944. if (isTexture(type) && !numSamples) {
  2945. if (mipLevel) {
  2946. // For Texture types when mipLevel argument is present.
  2947. lod = doExpr(mipLevel);
  2948. } else {
  2949. // For Texture types when mipLevel argument is omitted.
  2950. lod = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2951. }
  2952. }
  2953. SpirvInstruction *query =
  2954. lod ? cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2955. spv::Op::OpImageQuerySizeLod, resultQualType,
  2956. expr->getCallee()->getExprLoc(), objectInstr, lod))
  2957. : cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2958. spv::Op::OpImageQuerySize, resultQualType,
  2959. expr->getCallee()->getExprLoc(), objectInstr));
  2960. if (querySize == 1) {
  2961. const uint32_t argIndex = mipLevel ? 1 : 0;
  2962. storeToOutputArg(expr->getArg(argIndex), query, resultQualType);
  2963. } else {
  2964. for (uint32_t i = 0; i < querySize; ++i) {
  2965. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2966. auto *component = spvBuilder.createCompositeExtract(
  2967. astContext.UnsignedIntTy, query, {i},
  2968. expr->getCallee()->getExprLoc());
  2969. // If the first arg is the mipmap level, we must write the results
  2970. // starting from Arg(i+1), not Arg(i).
  2971. storeToOutputArg(expr->getArg(argIndex), component,
  2972. astContext.UnsignedIntTy);
  2973. }
  2974. }
  2975. if (numLevels || numSamples) {
  2976. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2977. const spv::Op opcode =
  2978. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2979. auto *numLevelsSamplesQuery = spvBuilder.createImageQuery(
  2980. opcode, astContext.UnsignedIntTy, expr->getCallee()->getExprLoc(),
  2981. objectInstr);
  2982. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery,
  2983. astContext.UnsignedIntTy);
  2984. }
  2985. return nullptr;
  2986. }
  2987. SpirvInstruction *
  2988. SpirvEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr,
  2989. bool unclamped) {
  2990. // Possible signatures are as follows:
  2991. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2992. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2993. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2994. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2995. // Return type is always a single float (LOD).
  2996. assert(expr->getNumArgs() == 2u);
  2997. const auto *object = expr->getImplicitObjectArgument();
  2998. auto *objectInfo = loadIfGLValue(object);
  2999. auto *samplerState = doExpr(expr->getArg(0));
  3000. auto *coordinate = doExpr(expr->getArg(1));
  3001. auto *sampledImage = spvBuilder.createSampledImage(
  3002. object->getType(), objectInfo, samplerState, expr->getExprLoc());
  3003. // The result type of OpImageQueryLod must be a float2.
  3004. const QualType queryResultType =
  3005. astContext.getExtVectorType(astContext.FloatTy, 2u);
  3006. auto *query =
  3007. spvBuilder.createImageQuery(spv::Op::OpImageQueryLod, queryResultType,
  3008. expr->getExprLoc(), sampledImage, coordinate);
  3009. // The first component of the float2 contains the mipmap array layer.
  3010. // The second component of the float2 represents the unclamped lod.
  3011. return spvBuilder.createCompositeExtract(astContext.FloatTy, query,
  3012. unclamped ? 1 : 0,
  3013. expr->getCallee()->getExprLoc());
  3014. }
  3015. SpirvInstruction *SpirvEmitter::processTextureGatherRGBACmpRGBA(
  3016. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  3017. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  3018. // two sets:
  3019. // * SamplerState s, float2 location, int2 offset
  3020. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  3021. // int offset2, int2 offset3
  3022. //
  3023. // An additional 'out uint status' parameter can appear in both of the above.
  3024. //
  3025. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  3026. // two sets:
  3027. // * SamplerState s, float2 location, float compare_value, int2 offset
  3028. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  3029. // int2 offset2, int2 offset3, int2 offset4
  3030. //
  3031. // An additional 'out uint status' parameter can appear in both of the above.
  3032. //
  3033. // TextureCube's signature is somewhat different from the rest.
  3034. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  3035. // * SamplerState s, float2 location, out uint status
  3036. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  3037. // * SamplerState s, float2 location, float compare_value, out uint status
  3038. //
  3039. // Return type is always a 4-component vector.
  3040. const FunctionDecl *callee = expr->getDirectCallee();
  3041. const auto numArgs = expr->getNumArgs();
  3042. const auto *imageExpr = expr->getImplicitObjectArgument();
  3043. const auto loc = expr->getCallee()->getExprLoc();
  3044. const QualType imageType = imageExpr->getType();
  3045. const QualType retType = callee->getReturnType();
  3046. // If the last arg is an unsigned integer, it must be the status.
  3047. const bool hasStatusArg =
  3048. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3049. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  3050. // it exists), and subtract 2 for SamplerState and location.
  3051. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  3052. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  3053. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  3054. auto *image = loadIfGLValue(imageExpr);
  3055. auto *sampler = doExpr(expr->getArg(0));
  3056. auto *coordinate = doExpr(expr->getArg(1));
  3057. auto *compareVal = isCmp ? doExpr(expr->getArg(2)) : nullptr;
  3058. // Handle offsets (if any).
  3059. bool needsEmulation = false;
  3060. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr,
  3061. *constOffsets = nullptr;
  3062. if (numOffsetArgs == 1) {
  3063. // The offset arg is not optional.
  3064. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  3065. } else if (numOffsetArgs == 4) {
  3066. auto *offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  3067. auto *offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  3068. auto *offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  3069. auto *offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  3070. // If any of the offsets is not constant, we then need to emulate the call
  3071. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  3072. // ConstOffsets image operand.
  3073. if (offset0 && offset1 && offset2 && offset3) {
  3074. const QualType v2i32 = astContext.getExtVectorType(astContext.IntTy, 2);
  3075. const auto offsetType = astContext.getConstantArrayType(
  3076. v2i32, llvm::APInt(32, 4), clang::ArrayType::Normal, 0);
  3077. constOffsets = spvBuilder.getConstantComposite(
  3078. offsetType, {offset0, offset1, offset2, offset3});
  3079. } else {
  3080. needsEmulation = true;
  3081. }
  3082. }
  3083. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3084. if (needsEmulation) {
  3085. const auto elemType = hlsl::GetHLSLVecElementType(callee->getReturnType());
  3086. SpirvInstruction *texels[4];
  3087. for (uint32_t i = 0; i < 4; ++i) {
  3088. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  3089. auto *gatherRet = spvBuilder.createImageGather(
  3090. retType, imageType, image, sampler, coordinate,
  3091. spvBuilder.getConstantInt(astContext.IntTy,
  3092. llvm::APInt(32, component, true)),
  3093. compareVal,
  3094. /*constOffset*/ nullptr, varOffset, /*constOffsets*/ nullptr,
  3095. /*sampleNumber*/ nullptr, status, loc);
  3096. texels[i] =
  3097. spvBuilder.createCompositeExtract(elemType, gatherRet, {i}, loc);
  3098. }
  3099. return spvBuilder.createCompositeConstruct(
  3100. retType, {texels[0], texels[1], texels[2], texels[3]}, loc);
  3101. }
  3102. return spvBuilder.createImageGather(
  3103. retType, imageType, image, sampler, coordinate,
  3104. spvBuilder.getConstantInt(astContext.IntTy,
  3105. llvm::APInt(32, component, true)),
  3106. compareVal, constOffset, varOffset, constOffsets,
  3107. /*sampleNumber*/ nullptr, status, loc);
  3108. }
  3109. SpirvInstruction *
  3110. SpirvEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  3111. // Signature for Texture2D/Texture2DArray:
  3112. //
  3113. // float4 GatherCmp(
  3114. // in SamplerComparisonState s,
  3115. // in float2 location,
  3116. // in float compare_value
  3117. // [,in int2 offset]
  3118. // [,out uint Status]
  3119. // );
  3120. //
  3121. // Signature for TextureCube/TextureCubeArray:
  3122. //
  3123. // float4 GatherCmp(
  3124. // in SamplerComparisonState s,
  3125. // in float2 location,
  3126. // in float compare_value,
  3127. // out uint Status
  3128. // );
  3129. //
  3130. // Other Texture types do not have the GatherCmp method.
  3131. const FunctionDecl *callee = expr->getDirectCallee();
  3132. const auto numArgs = expr->getNumArgs();
  3133. const auto loc = expr->getExprLoc();
  3134. const bool hasStatusArg =
  3135. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3136. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  3137. const auto *imageExpr = expr->getImplicitObjectArgument();
  3138. auto *image = loadIfGLValue(imageExpr);
  3139. auto *sampler = doExpr(expr->getArg(0));
  3140. auto *coordinate = doExpr(expr->getArg(1));
  3141. auto *comparator = doExpr(expr->getArg(2));
  3142. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3143. if (hasOffsetArg)
  3144. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3145. const auto retType = callee->getReturnType();
  3146. const auto imageType = imageExpr->getType();
  3147. const auto status =
  3148. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3149. return spvBuilder.createImageGather(
  3150. retType, imageType, image, sampler, coordinate,
  3151. /*component*/ nullptr, comparator, constOffset, varOffset,
  3152. /*constOffsets*/ nullptr,
  3153. /*sampleNumber*/ nullptr, status, loc);
  3154. }
  3155. SpirvInstruction *SpirvEmitter::processBufferTextureLoad(
  3156. const Expr *object, SpirvInstruction *location,
  3157. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  3158. SpirvInstruction *lod, SpirvInstruction *residencyCode,
  3159. SourceLocation loc) {
  3160. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  3161. // The result type of an OpImageFetch must be a vec4 of float or int.
  3162. const auto type = object->getType();
  3163. assert(isBuffer(type) || isRWBuffer(type) || isTexture(type) ||
  3164. isRWTexture(type) || isSubpassInput(type) || isSubpassInputMS(type));
  3165. const bool doFetch = isBuffer(type) || isTexture(type);
  3166. auto *objectInfo = loadIfGLValue(object);
  3167. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  3168. SpirvInstruction *sampleNumber = nullptr;
  3169. if (isTextureMS(type) || isSubpassInputMS(type)) {
  3170. sampleNumber = lod;
  3171. lod = nullptr;
  3172. }
  3173. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  3174. QualType elemType = sampledType;
  3175. uint32_t elemCount = 1;
  3176. bool isTemplateOverStruct = false;
  3177. // Check whether the template type is a vector type or struct type.
  3178. if (!isVectorType(sampledType, &elemType, &elemCount)) {
  3179. if (sampledType->getAsStructureType()) {
  3180. isTemplateOverStruct = true;
  3181. // For struct type, we need to make sure it can fit into a 4-component
  3182. // vector. Detailed failing reasons will be emitted by the function so
  3183. // we don't need to emit errors here.
  3184. if (!canFitIntoOneRegister(astContext, sampledType, &elemType,
  3185. &elemCount))
  3186. return nullptr;
  3187. }
  3188. }
  3189. {
  3190. // Treat a vector of size 1 the same as a scalar.
  3191. if (hlsl::IsHLSLVecType(elemType) && hlsl::GetHLSLVecSize(elemType) == 1)
  3192. elemType = hlsl::GetHLSLVecElementType(elemType);
  3193. if (!elemType->isFloatingType() && !elemType->isIntegerType()) {
  3194. emitError("loading %0 value unsupported", object->getExprLoc()) << type;
  3195. return nullptr;
  3196. }
  3197. }
  3198. // If residencyCode is nullptr, we are dealing with a Load method with 2
  3199. // arguments which does not return the operation status.
  3200. if (residencyCode && residencyCode->isRValue()) {
  3201. emitError(
  3202. "an lvalue argument should be used for returning the operation status",
  3203. loc);
  3204. return nullptr;
  3205. }
  3206. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  3207. const QualType texelType = astContext.getExtVectorType(elemType, 4u);
  3208. auto *texel = spvBuilder.createImageFetchOrRead(
  3209. doFetch, texelType, type, objectInfo, location, lod, constOffset,
  3210. varOffset, /*constOffsets*/ nullptr, sampleNumber, residencyCode, loc);
  3211. // If the result type is a vec1, vec2, or vec3, some extra processing
  3212. // (extraction) is required.
  3213. auto *retVal = extractVecFromVec4(texel, elemCount, elemType, loc);
  3214. if (isTemplateOverStruct) {
  3215. // Convert to the struct so that we are consistent with types in the AST.
  3216. retVal = convertVectorToStruct(sampledType, elemType, retVal, loc);
  3217. }
  3218. retVal->setRValue();
  3219. return retVal;
  3220. }
  3221. SpirvInstruction *SpirvEmitter::processByteAddressBufferLoadStore(
  3222. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  3223. SpirvInstruction *result = nullptr;
  3224. const auto object = expr->getImplicitObjectArgument();
  3225. auto *objectInfo = loadIfAliasVarRef(object);
  3226. assert(numWords >= 1 && numWords <= 4);
  3227. if (doStore) {
  3228. assert(isRWByteAddressBuffer(object->getType()));
  3229. assert(expr->getNumArgs() == 2);
  3230. } else {
  3231. assert(isRWByteAddressBuffer(object->getType()) ||
  3232. isByteAddressBuffer(object->getType()));
  3233. if (expr->getNumArgs() == 2) {
  3234. emitError(
  3235. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  3236. expr->getExprLoc());
  3237. return 0;
  3238. }
  3239. }
  3240. const Expr *addressExpr = expr->getArg(0);
  3241. auto *byteAddress = doExpr(addressExpr);
  3242. const QualType addressType = addressExpr->getType();
  3243. // The front-end prevents usage of templated Load2, Load3, Load4, Store2,
  3244. // Store3, Store4 intrinsic functions.
  3245. const bool isTemplatedLoadOrStore =
  3246. (numWords == 1) &&
  3247. (doStore ? !expr->getArg(1)->getType()->isSpecificBuiltinType(
  3248. BuiltinType::UInt)
  3249. : !expr->getType()->isSpecificBuiltinType(BuiltinType::UInt));
  3250. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  3251. // access). The AST always casts the address to unsinged integer, so shift
  3252. // by unsinged integer 2.
  3253. auto *constUint2 =
  3254. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  3255. SpirvInstruction *address =
  3256. spvBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, addressType,
  3257. byteAddress, constUint2, expr->getExprLoc());
  3258. if (isTemplatedLoadOrStore) {
  3259. // Templated load. Need to (potentially) perform more
  3260. // loads/casts/composite-constructs.
  3261. uint32_t bitOffset = 0;
  3262. if (doStore) {
  3263. auto *values = doExpr(expr->getArg(1));
  3264. RawBufferHandler(*this).processTemplatedStoreToBuffer(
  3265. values, objectInfo, address, expr->getArg(1)->getType(), bitOffset);
  3266. return nullptr;
  3267. } else {
  3268. RawBufferHandler rawBufferHandler(*this);
  3269. return rawBufferHandler.processTemplatedLoadFromBuffer(
  3270. objectInfo, address, expr->getType(), bitOffset);
  3271. }
  3272. }
  3273. // Perform access chain into the RWByteAddressBuffer.
  3274. // First index must be zero (member 0 of the struct is a
  3275. // runtimeArray). The second index passed to OpAccessChain should be
  3276. // the address.
  3277. auto *constUint0 =
  3278. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3279. if (doStore) {
  3280. auto *values = doExpr(expr->getArg(1));
  3281. auto *curStoreAddress = address;
  3282. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  3283. // Extract a 32-bit word from the input.
  3284. auto *curValue = numWords == 1
  3285. ? values
  3286. : spvBuilder.createCompositeExtract(
  3287. astContext.UnsignedIntTy, values,
  3288. {wordCounter}, expr->getArg(1)->getExprLoc());
  3289. // Update the output address if necessary.
  3290. if (wordCounter > 0) {
  3291. auto *offset = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  3292. llvm::APInt(32, wordCounter));
  3293. curStoreAddress =
  3294. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3295. offset, expr->getCallee()->getExprLoc());
  3296. }
  3297. // Store the word to the right address at the output.
  3298. auto *storePtr = spvBuilder.createAccessChain(
  3299. astContext.UnsignedIntTy, objectInfo, {constUint0, curStoreAddress},
  3300. object->getLocStart());
  3301. spvBuilder.createStore(storePtr, curValue,
  3302. expr->getCallee()->getExprLoc());
  3303. }
  3304. } else {
  3305. auto *loadPtr = spvBuilder.createAccessChain(
  3306. astContext.UnsignedIntTy, objectInfo, {constUint0, address},
  3307. object->getLocStart());
  3308. result = spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3309. expr->getCallee()->getExprLoc());
  3310. if (numWords > 1) {
  3311. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  3312. // return a vector result.
  3313. llvm::SmallVector<SpirvInstruction *, 4> values;
  3314. values.push_back(result);
  3315. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  3316. auto *offset = spvBuilder.getConstantInt(
  3317. astContext.UnsignedIntTy, llvm::APInt(32, wordCounter - 1));
  3318. auto *newAddress =
  3319. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3320. offset, expr->getCallee()->getExprLoc());
  3321. loadPtr = spvBuilder.createAccessChain(
  3322. astContext.UnsignedIntTy, objectInfo, {constUint0, newAddress},
  3323. object->getLocStart());
  3324. values.push_back(
  3325. spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3326. expr->getCallee()->getExprLoc()));
  3327. }
  3328. const QualType resultType =
  3329. astContext.getExtVectorType(addressType, numWords);
  3330. result = spvBuilder.createCompositeConstruct(resultType, values,
  3331. expr->getLocStart());
  3332. result->setRValue();
  3333. }
  3334. }
  3335. return result;
  3336. }
  3337. SpirvInstruction *
  3338. SpirvEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  3339. if (expr->getNumArgs() == 2) {
  3340. emitError(
  3341. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  3342. expr->getExprLoc());
  3343. return 0;
  3344. }
  3345. const auto *buffer = expr->getImplicitObjectArgument();
  3346. auto *info = loadIfAliasVarRef(buffer);
  3347. const QualType structType =
  3348. hlsl::GetHLSLResourceResultType(buffer->getType());
  3349. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  3350. auto *index = doExpr(expr->getArg(0));
  3351. return turnIntoElementPtr(buffer->getType(), info, structType, {zero, index},
  3352. buffer->getExprLoc());
  3353. }
  3354. SpirvInstruction *
  3355. SpirvEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  3356. bool isInc, bool loadObject) {
  3357. auto *zero =
  3358. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3359. auto *sOne =
  3360. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 1, true));
  3361. const auto srcLoc = expr->getCallee()->getExprLoc();
  3362. const auto *object =
  3363. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3364. if (loadObject) {
  3365. // We don't need the object's <result-id> here since counter variable is a
  3366. // separate variable. But we still need the side effects of evaluating the
  3367. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  3368. // want to emit the code for foo(...).
  3369. (void)doExpr(object);
  3370. }
  3371. const auto *counterPair = getFinalACSBufferCounter(object);
  3372. if (!counterPair) {
  3373. emitFatalError("cannot find the associated counter variable",
  3374. object->getExprLoc());
  3375. return nullptr;
  3376. }
  3377. auto *counterPtr = spvBuilder.createAccessChain(
  3378. astContext.IntTy, counterPair->get(spvBuilder, spvContext), {zero},
  3379. srcLoc);
  3380. SpirvInstruction *index = nullptr;
  3381. if (isInc) {
  3382. index = spvBuilder.createAtomicOp(
  3383. spv::Op::OpAtomicIAdd, astContext.IntTy, counterPtr, spv::Scope::Device,
  3384. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3385. } else {
  3386. // Note that OpAtomicISub returns the value before the subtraction;
  3387. // so we need to do substraction again with OpAtomicISub's return value.
  3388. auto *prev = spvBuilder.createAtomicOp(
  3389. spv::Op::OpAtomicISub, astContext.IntTy, counterPtr, spv::Scope::Device,
  3390. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3391. index = spvBuilder.createBinaryOp(spv::Op::OpISub, astContext.IntTy, prev,
  3392. sOne, srcLoc);
  3393. }
  3394. return index;
  3395. }
  3396. bool SpirvEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  3397. const Expr *srcExpr) {
  3398. // We are handling associated counters here. Casts should not alter which
  3399. // associated counter to manipulate.
  3400. srcExpr = srcExpr->IgnoreParenCasts();
  3401. // For parameters of forward-declared functions. We must make sure the
  3402. // associated counter variable is created. But for forward-declared functions,
  3403. // the translation of the real definition may not be started yet.
  3404. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  3405. declIdMapper.createFnParamCounterVar(param);
  3406. // For implicit objects of methods. Similar to the above.
  3407. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  3408. declIdMapper.createFnParamCounterVar(thisObject);
  3409. // Handle AssocCounter#1 (see CounterVarFields comment)
  3410. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  3411. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3412. if (!srcPair) {
  3413. emitFatalError("cannot find the associated counter variable",
  3414. srcExpr->getExprLoc());
  3415. return false;
  3416. }
  3417. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3418. return true;
  3419. }
  3420. // Handle AssocCounter#3
  3421. llvm::SmallVector<uint32_t, 4> srcIndices;
  3422. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  3423. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3424. if (dstFields && srcFields) {
  3425. // The destination is a struct whose fields are directly alias resources.
  3426. // But that's not necessarily true for the source, which can be deep
  3427. // nested structs. That means they will have different index "prefixes"
  3428. // for all their fields; while the "prefix" for destination is effectively
  3429. // an empty list (since it is not nested in other structs). We need to
  3430. // strip the index prefix from the source.
  3431. return dstFields->assign(*srcFields, /*dstIndices=*/{}, srcIndices,
  3432. spvBuilder, spvContext);
  3433. }
  3434. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  3435. // is a stand-alone decl in this method.
  3436. return false;
  3437. }
  3438. bool SpirvEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  3439. const Expr *srcExpr) {
  3440. dstExpr = dstExpr->IgnoreParenCasts();
  3441. srcExpr = srcExpr->IgnoreParenCasts();
  3442. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  3443. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3444. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  3445. emitFatalError("cannot handle associated counter variable assignment",
  3446. srcExpr->getExprLoc());
  3447. return false;
  3448. }
  3449. // Handle AssocCounter#1 & AssocCounter#2
  3450. if (dstPair && srcPair) {
  3451. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3452. return true;
  3453. }
  3454. // Handle AssocCounter#3 & AssocCounter#4
  3455. llvm::SmallVector<uint32_t, 4> dstIndices;
  3456. llvm::SmallVector<uint32_t, 4> srcIndices;
  3457. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3458. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  3459. if (dstFields && srcFields) {
  3460. return dstFields->assign(*srcFields, dstIndices, srcIndices, spvBuilder,
  3461. spvContext);
  3462. }
  3463. return false;
  3464. }
  3465. const CounterIdAliasPair *
  3466. SpirvEmitter::getFinalACSBufferCounter(const Expr *expr) {
  3467. // AssocCounter#1: referencing some stand-alone variable
  3468. if (const auto *decl = getReferencedDef(expr))
  3469. return declIdMapper.getCounterIdAliasPair(decl);
  3470. // AssocCounter#2: referencing some non-struct field
  3471. llvm::SmallVector<uint32_t, 4> rawIndices;
  3472. const auto *base = collectArrayStructIndices(
  3473. expr, /*rawIndex=*/true, &rawIndices, /*indices*/ nullptr);
  3474. const auto *decl =
  3475. (base && isa<CXXThisExpr>(base))
  3476. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3477. : getReferencedDef(base);
  3478. return declIdMapper.getCounterIdAliasPair(decl, &rawIndices);
  3479. }
  3480. const CounterVarFields *SpirvEmitter::getIntermediateACSBufferCounter(
  3481. const Expr *expr, llvm::SmallVector<uint32_t, 4> *rawIndices) {
  3482. const auto *base = collectArrayStructIndices(expr, /*rawIndex=*/true,
  3483. rawIndices, /*indices*/ nullptr);
  3484. const auto *decl =
  3485. (base && isa<CXXThisExpr>(base))
  3486. // Use the decl we created to represent the implicit object
  3487. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3488. // Find the referenced decl from the original source code
  3489. : getReferencedDef(base);
  3490. return declIdMapper.getCounterVarFields(decl);
  3491. }
  3492. const ImplicitParamDecl *
  3493. SpirvEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  3494. const auto found = thisDecls.find(method);
  3495. if (found != thisDecls.end())
  3496. return found->second;
  3497. const std::string name = method->getName().str() + ".this";
  3498. // Create a new identifier to convey the name
  3499. auto &identifier = astContext.Idents.get(name);
  3500. return thisDecls[method] = ImplicitParamDecl::Create(
  3501. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  3502. method->getThisType(astContext)->getPointeeType());
  3503. }
  3504. SpirvInstruction *
  3505. SpirvEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  3506. const bool isAppend = expr->getNumArgs() == 1;
  3507. auto *zero =
  3508. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3509. const auto *object =
  3510. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3511. auto *bufferInfo = loadIfAliasVarRef(object);
  3512. auto *index = incDecRWACSBufferCounter(
  3513. expr, isAppend,
  3514. // We have already translated the object in the above. Avoid duplication.
  3515. /*loadObject=*/false);
  3516. auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  3517. // If this is a variable to communicate with host e.g., ACSBuffer
  3518. // and its type is bool or vector of bool, its effective type used
  3519. // for SPIRV must be uint not bool. We must convert it to uint here.
  3520. bool needCast = false;
  3521. if (bufferInfo->getLayoutRule() != SpirvLayoutRule::Void &&
  3522. isBoolOrVecOfBoolType(bufferElemTy)) {
  3523. uint32_t vecSize = 1;
  3524. const bool isVec = isVectorType(bufferElemTy, nullptr, &vecSize);
  3525. bufferElemTy =
  3526. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  3527. : astContext.UnsignedIntTy;
  3528. needCast = true;
  3529. }
  3530. bufferInfo = turnIntoElementPtr(object->getType(), bufferInfo, bufferElemTy,
  3531. {zero, index}, object->getExprLoc());
  3532. if (isAppend) {
  3533. // Write out the value
  3534. auto *arg0 = doExpr(expr->getArg(0));
  3535. if (!arg0)
  3536. return nullptr;
  3537. if (!arg0->isRValue()) {
  3538. arg0 = spvBuilder.createLoad(bufferElemTy, arg0,
  3539. expr->getArg(0)->getExprLoc());
  3540. }
  3541. if (needCast &&
  3542. !isSameType(astContext, bufferElemTy, arg0->getAstResultType())) {
  3543. arg0 = castToType(arg0, arg0->getAstResultType(), bufferElemTy,
  3544. expr->getArg(0)->getExprLoc());
  3545. }
  3546. storeValue(bufferInfo, arg0, bufferElemTy, expr->getCallee()->getExprLoc());
  3547. return 0;
  3548. } else {
  3549. // Note that we are returning a pointer (lvalue) here inorder to further
  3550. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  3551. // cannot forcefully set all normal function calls as returning rvalue.
  3552. return bufferInfo;
  3553. }
  3554. }
  3555. SpirvInstruction *
  3556. SpirvEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  3557. // TODO: handle multiple stream-output objects
  3558. const auto *object =
  3559. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3560. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  3561. auto *value = doExpr(expr->getArg(0));
  3562. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  3563. spvBuilder.createEmitVertex(expr->getExprLoc());
  3564. return nullptr;
  3565. }
  3566. SpirvInstruction *
  3567. SpirvEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  3568. // TODO: handle multiple stream-output objects
  3569. spvBuilder.createEndPrimitive(expr->getExprLoc());
  3570. return 0;
  3571. }
  3572. SpirvInstruction *
  3573. SpirvEmitter::emitGetSamplePosition(SpirvInstruction *sampleCount,
  3574. SpirvInstruction *sampleIndex,
  3575. SourceLocation loc) {
  3576. struct Float2 {
  3577. float x;
  3578. float y;
  3579. };
  3580. static const Float2 pos2[] = {
  3581. {4.0 / 16.0, 4.0 / 16.0},
  3582. {-4.0 / 16.0, -4.0 / 16.0},
  3583. };
  3584. static const Float2 pos4[] = {
  3585. {-2.0 / 16.0, -6.0 / 16.0},
  3586. {6.0 / 16.0, -2.0 / 16.0},
  3587. {-6.0 / 16.0, 2.0 / 16.0},
  3588. {2.0 / 16.0, 6.0 / 16.0},
  3589. };
  3590. static const Float2 pos8[] = {
  3591. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3592. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3593. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3594. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3595. };
  3596. static const Float2 pos16[] = {
  3597. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3598. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3599. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3600. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3601. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3602. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3603. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3604. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3605. };
  3606. // We are emitting the SPIR-V for the following HLSL source code:
  3607. //
  3608. // float2 position;
  3609. //
  3610. // if (count == 2) {
  3611. // position = pos2[index];
  3612. // }
  3613. // else if (count == 4) {
  3614. // position = pos4[index];
  3615. // }
  3616. // else if (count == 8) {
  3617. // position = pos8[index];
  3618. // }
  3619. // else if (count == 16) {
  3620. // position = pos16[index];
  3621. // }
  3622. // else {
  3623. // position = float2(0.0f, 0.0f);
  3624. // }
  3625. const auto v2f32Type = astContext.getExtVectorType(astContext.FloatTy, 2);
  3626. // Creates a SPIR-V function scope variable of type float2[len].
  3627. const auto createArray = [this, v2f32Type, loc](const Float2 *ptr,
  3628. uint32_t len) {
  3629. llvm::SmallVector<SpirvConstant *, 16> components;
  3630. for (uint32_t i = 0; i < len; ++i) {
  3631. auto *x = spvBuilder.getConstantFloat(astContext.FloatTy,
  3632. llvm::APFloat(ptr[i].x));
  3633. auto *y = spvBuilder.getConstantFloat(astContext.FloatTy,
  3634. llvm::APFloat(ptr[i].y));
  3635. components.push_back(spvBuilder.getConstantComposite(v2f32Type, {x, y}));
  3636. }
  3637. const auto arrType = astContext.getConstantArrayType(
  3638. v2f32Type, llvm::APInt(32, len), clang::ArrayType::Normal, 0);
  3639. auto *val = spvBuilder.getConstantComposite(arrType, components);
  3640. const std::string varName =
  3641. "var.GetSamplePosition.data." + std::to_string(len);
  3642. auto *var = spvBuilder.addFnVar(arrType, loc, varName);
  3643. spvBuilder.createStore(var, val, loc);
  3644. return var;
  3645. };
  3646. auto *pos2Arr = createArray(pos2, 2);
  3647. auto *pos4Arr = createArray(pos4, 4);
  3648. auto *pos8Arr = createArray(pos8, 8);
  3649. auto *pos16Arr = createArray(pos16, 16);
  3650. auto *resultVar =
  3651. spvBuilder.addFnVar(v2f32Type, loc, "var.GetSamplePosition.result");
  3652. auto *then2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3653. auto *then4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3654. auto *then8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3655. auto *then16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3656. auto *else2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3657. auto *else4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3658. auto *else8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3659. auto *else16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3660. auto *merge2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3661. auto *merge4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3662. auto *merge8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3663. auto *merge16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3664. // if (count == 2) {
  3665. const auto check2 = spvBuilder.createBinaryOp(
  3666. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3667. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  3668. loc);
  3669. spvBuilder.createConditionalBranch(check2, then2BB, else2BB, loc, merge2BB);
  3670. spvBuilder.addSuccessor(then2BB);
  3671. spvBuilder.addSuccessor(else2BB);
  3672. spvBuilder.setMergeTarget(merge2BB);
  3673. // position = pos2[index];
  3674. // }
  3675. spvBuilder.setInsertPoint(then2BB);
  3676. auto *ac =
  3677. spvBuilder.createAccessChain(v2f32Type, pos2Arr, {sampleIndex}, loc);
  3678. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3679. loc);
  3680. spvBuilder.createBranch(merge2BB, loc);
  3681. spvBuilder.addSuccessor(merge2BB);
  3682. // else if (count == 4) {
  3683. spvBuilder.setInsertPoint(else2BB);
  3684. const auto check4 = spvBuilder.createBinaryOp(
  3685. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3686. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 4)),
  3687. loc);
  3688. spvBuilder.createConditionalBranch(check4, then4BB, else4BB, loc, merge4BB);
  3689. spvBuilder.addSuccessor(then4BB);
  3690. spvBuilder.addSuccessor(else4BB);
  3691. spvBuilder.setMergeTarget(merge4BB);
  3692. // position = pos4[index];
  3693. // }
  3694. spvBuilder.setInsertPoint(then4BB);
  3695. ac = spvBuilder.createAccessChain(v2f32Type, pos4Arr, {sampleIndex}, loc);
  3696. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3697. loc);
  3698. spvBuilder.createBranch(merge4BB, loc);
  3699. spvBuilder.addSuccessor(merge4BB);
  3700. // else if (count == 8) {
  3701. spvBuilder.setInsertPoint(else4BB);
  3702. const auto check8 = spvBuilder.createBinaryOp(
  3703. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3704. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8)),
  3705. loc);
  3706. spvBuilder.createConditionalBranch(check8, then8BB, else8BB, loc, merge8BB);
  3707. spvBuilder.addSuccessor(then8BB);
  3708. spvBuilder.addSuccessor(else8BB);
  3709. spvBuilder.setMergeTarget(merge8BB);
  3710. // position = pos8[index];
  3711. // }
  3712. spvBuilder.setInsertPoint(then8BB);
  3713. ac = spvBuilder.createAccessChain(v2f32Type, pos8Arr, {sampleIndex}, loc);
  3714. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3715. loc);
  3716. spvBuilder.createBranch(merge8BB, loc);
  3717. spvBuilder.addSuccessor(merge8BB);
  3718. // else if (count == 16) {
  3719. spvBuilder.setInsertPoint(else8BB);
  3720. const auto check16 = spvBuilder.createBinaryOp(
  3721. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3722. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16)),
  3723. loc);
  3724. spvBuilder.createConditionalBranch(check16, then16BB, else16BB, loc,
  3725. merge16BB);
  3726. spvBuilder.addSuccessor(then16BB);
  3727. spvBuilder.addSuccessor(else16BB);
  3728. spvBuilder.setMergeTarget(merge16BB);
  3729. // position = pos16[index];
  3730. // }
  3731. spvBuilder.setInsertPoint(then16BB);
  3732. ac = spvBuilder.createAccessChain(v2f32Type, pos16Arr, {sampleIndex}, loc);
  3733. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3734. loc);
  3735. spvBuilder.createBranch(merge16BB, loc);
  3736. spvBuilder.addSuccessor(merge16BB);
  3737. // else {
  3738. // position = float2(0.0f, 0.0f);
  3739. // }
  3740. spvBuilder.setInsertPoint(else16BB);
  3741. auto *zero =
  3742. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  3743. auto *v2f32Zero = spvBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3744. spvBuilder.createStore(resultVar, v2f32Zero, loc);
  3745. spvBuilder.createBranch(merge16BB, loc);
  3746. spvBuilder.addSuccessor(merge16BB);
  3747. spvBuilder.setInsertPoint(merge16BB);
  3748. spvBuilder.createBranch(merge8BB, loc);
  3749. spvBuilder.addSuccessor(merge8BB);
  3750. spvBuilder.setInsertPoint(merge8BB);
  3751. spvBuilder.createBranch(merge4BB, loc);
  3752. spvBuilder.addSuccessor(merge4BB);
  3753. spvBuilder.setInsertPoint(merge4BB);
  3754. spvBuilder.createBranch(merge2BB, loc);
  3755. spvBuilder.addSuccessor(merge2BB);
  3756. spvBuilder.setInsertPoint(merge2BB);
  3757. return spvBuilder.createLoad(v2f32Type, resultVar, loc);
  3758. }
  3759. SpirvInstruction *
  3760. SpirvEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3761. const FunctionDecl *callee = expr->getDirectCallee();
  3762. llvm::StringRef group;
  3763. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3764. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3765. return processIntrinsicMemberCall(expr,
  3766. static_cast<hlsl::IntrinsicOp>(opcode));
  3767. }
  3768. return processCall(expr);
  3769. }
  3770. void SpirvEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3771. uint32_t index,
  3772. SpirvInstruction **constOffset,
  3773. SpirvInstruction **varOffset) {
  3774. assert(constOffset && varOffset);
  3775. // Ensure the given arg index is not out-of-range.
  3776. assert(index < expr->getNumArgs());
  3777. *constOffset = *varOffset = nullptr; // Initialize both first
  3778. if ((*constOffset = tryToEvaluateAsConst(expr->getArg(index))))
  3779. return; // Constant offset
  3780. else
  3781. *varOffset = doExpr(expr->getArg(index));
  3782. }
  3783. SpirvInstruction *
  3784. SpirvEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3785. hlsl::IntrinsicOp opcode) {
  3786. using namespace hlsl;
  3787. SpirvInstruction *retVal = nullptr;
  3788. switch (opcode) {
  3789. case IntrinsicOp::MOP_Sample:
  3790. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3791. break;
  3792. case IntrinsicOp::MOP_Gather:
  3793. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3794. break;
  3795. case IntrinsicOp::MOP_SampleBias:
  3796. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3797. break;
  3798. case IntrinsicOp::MOP_SampleLevel:
  3799. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3800. break;
  3801. case IntrinsicOp::MOP_SampleGrad:
  3802. retVal = processTextureSampleGrad(expr);
  3803. break;
  3804. case IntrinsicOp::MOP_SampleCmp:
  3805. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3806. break;
  3807. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3808. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3809. break;
  3810. case IntrinsicOp::MOP_GatherRed:
  3811. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3812. break;
  3813. case IntrinsicOp::MOP_GatherGreen:
  3814. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3815. break;
  3816. case IntrinsicOp::MOP_GatherBlue:
  3817. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3818. break;
  3819. case IntrinsicOp::MOP_GatherAlpha:
  3820. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3821. break;
  3822. case IntrinsicOp::MOP_GatherCmp:
  3823. retVal = processTextureGatherCmp(expr);
  3824. break;
  3825. case IntrinsicOp::MOP_GatherCmpRed:
  3826. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3827. break;
  3828. case IntrinsicOp::MOP_Load:
  3829. return processBufferTextureLoad(expr);
  3830. case IntrinsicOp::MOP_Load2:
  3831. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3832. case IntrinsicOp::MOP_Load3:
  3833. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3834. case IntrinsicOp::MOP_Load4:
  3835. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3836. case IntrinsicOp::MOP_Store:
  3837. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3838. case IntrinsicOp::MOP_Store2:
  3839. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3840. case IntrinsicOp::MOP_Store3:
  3841. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3842. case IntrinsicOp::MOP_Store4:
  3843. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3844. case IntrinsicOp::MOP_GetDimensions:
  3845. retVal = processGetDimensions(expr);
  3846. break;
  3847. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3848. retVal = processTextureLevelOfDetail(expr, /* unclamped */ false);
  3849. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3850. retVal = processTextureLevelOfDetail(expr, /* unclamped */ true);
  3851. break;
  3852. case IntrinsicOp::MOP_IncrementCounter:
  3853. retVal =
  3854. spvBuilder.createUnaryOp(spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3855. incDecRWACSBufferCounter(expr, /*isInc*/ true),
  3856. expr->getCallee()->getExprLoc());
  3857. break;
  3858. case IntrinsicOp::MOP_DecrementCounter:
  3859. retVal = spvBuilder.createUnaryOp(
  3860. spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3861. incDecRWACSBufferCounter(expr, /*isInc*/ false),
  3862. expr->getCallee()->getExprLoc());
  3863. break;
  3864. case IntrinsicOp::MOP_Append:
  3865. if (hlsl::IsHLSLStreamOutputType(
  3866. expr->getImplicitObjectArgument()->getType()))
  3867. return processStreamOutputAppend(expr);
  3868. else
  3869. return processACSBufferAppendConsume(expr);
  3870. case IntrinsicOp::MOP_Consume:
  3871. return processACSBufferAppendConsume(expr);
  3872. case IntrinsicOp::MOP_RestartStrip:
  3873. retVal = processStreamOutputRestart(expr);
  3874. break;
  3875. case IntrinsicOp::MOP_InterlockedAdd:
  3876. case IntrinsicOp::MOP_InterlockedAnd:
  3877. case IntrinsicOp::MOP_InterlockedOr:
  3878. case IntrinsicOp::MOP_InterlockedXor:
  3879. case IntrinsicOp::MOP_InterlockedUMax:
  3880. case IntrinsicOp::MOP_InterlockedUMin:
  3881. case IntrinsicOp::MOP_InterlockedMax:
  3882. case IntrinsicOp::MOP_InterlockedMin:
  3883. case IntrinsicOp::MOP_InterlockedExchange:
  3884. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3885. case IntrinsicOp::MOP_InterlockedCompareStore:
  3886. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3887. break;
  3888. case IntrinsicOp::MOP_GetSamplePosition:
  3889. retVal = processGetSamplePosition(expr);
  3890. break;
  3891. case IntrinsicOp::MOP_SubpassLoad:
  3892. retVal = processSubpassLoad(expr);
  3893. break;
  3894. case IntrinsicOp::MOP_GatherCmpGreen:
  3895. case IntrinsicOp::MOP_GatherCmpBlue:
  3896. case IntrinsicOp::MOP_GatherCmpAlpha:
  3897. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3898. expr->getCallee()->getExprLoc())
  3899. << expr->getMethodDecl()->getName();
  3900. return nullptr;
  3901. case IntrinsicOp::MOP_TraceRayInline:
  3902. return processTraceRayInline(expr);
  3903. case IntrinsicOp::MOP_Abort:
  3904. case IntrinsicOp::MOP_CandidateGeometryIndex:
  3905. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  3906. case IntrinsicOp::MOP_CandidateInstanceID:
  3907. case IntrinsicOp::MOP_CandidateInstanceIndex:
  3908. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  3909. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  3910. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  3911. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  3912. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  3913. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  3914. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  3915. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  3916. case IntrinsicOp::MOP_CandidateTriangleRayT:
  3917. case IntrinsicOp::MOP_CandidateType:
  3918. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  3919. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  3920. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  3921. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  3922. case IntrinsicOp::MOP_CommittedGeometryIndex:
  3923. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  3924. case IntrinsicOp::MOP_CommittedInstanceID:
  3925. case IntrinsicOp::MOP_CommittedInstanceIndex:
  3926. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  3927. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  3928. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  3929. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  3930. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  3931. case IntrinsicOp::MOP_CommittedRayT:
  3932. case IntrinsicOp::MOP_CommittedStatus:
  3933. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  3934. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  3935. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  3936. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  3937. case IntrinsicOp::MOP_Proceed:
  3938. case IntrinsicOp::MOP_RayFlags:
  3939. case IntrinsicOp::MOP_RayTMin:
  3940. case IntrinsicOp::MOP_WorldRayDirection:
  3941. case IntrinsicOp::MOP_WorldRayOrigin:
  3942. return processRayQueryIntrinsics(expr, opcode);
  3943. default:
  3944. emitError("intrinsic '%0' method unimplemented",
  3945. expr->getCallee()->getExprLoc())
  3946. << expr->getDirectCallee()->getName();
  3947. return nullptr;
  3948. }
  3949. if (retVal)
  3950. retVal->setRValue();
  3951. return retVal;
  3952. }
  3953. SpirvInstruction *SpirvEmitter::createImageSample(
  3954. QualType retType, QualType imageType, SpirvInstruction *image,
  3955. SpirvInstruction *sampler, SpirvInstruction *coordinate,
  3956. SpirvInstruction *compareVal, SpirvInstruction *bias, SpirvInstruction *lod,
  3957. std::pair<SpirvInstruction *, SpirvInstruction *> grad,
  3958. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  3959. SpirvInstruction *constOffsets, SpirvInstruction *sample,
  3960. SpirvInstruction *minLod, SpirvInstruction *residencyCodeId,
  3961. SourceLocation loc) {
  3962. // SampleDref* instructions in SPIR-V always return a scalar.
  3963. // They also have the correct type in HLSL.
  3964. if (compareVal) {
  3965. return spvBuilder.createImageSample(retType, imageType, image, sampler,
  3966. coordinate, compareVal, bias, lod, grad,
  3967. constOffset, varOffset, constOffsets,
  3968. sample, minLod, residencyCodeId, loc);
  3969. }
  3970. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3971. auto texelType = retType;
  3972. QualType elemType = {};
  3973. uint32_t retVecSize = 0;
  3974. if (isVectorType(retType, &elemType, &retVecSize) && retVecSize != 4) {
  3975. texelType = astContext.getExtVectorType(elemType, 4);
  3976. } else if (isScalarType(retType)) {
  3977. retVecSize = 1;
  3978. elemType = retType;
  3979. texelType = astContext.getExtVectorType(retType, 4);
  3980. }
  3981. // The Lod and Grad image operands requires explicit-lod instructions.
  3982. // Otherwise we use implicit-lod instructions.
  3983. const bool isExplicit = lod || (grad.first && grad.second);
  3984. // Implicit-lod instructions are only allowed in pixel shader.
  3985. if (!spvContext.isPS() && !isExplicit)
  3986. emitError("sampling with implicit lod is only allowed in fragment shaders",
  3987. loc);
  3988. auto *retVal = spvBuilder.createImageSample(
  3989. texelType, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3990. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3991. residencyCodeId, loc);
  3992. // Extract smaller vector from the vec4 result if necessary.
  3993. if (texelType != retType) {
  3994. retVal = extractVecFromVec4(retVal, retVecSize, elemType, loc);
  3995. }
  3996. return retVal;
  3997. }
  3998. SpirvInstruction *
  3999. SpirvEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  4000. const bool isSample) {
  4001. // Signatures:
  4002. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  4003. // DXGI_FORMAT Object.Sample(sampler_state S,
  4004. // float Location
  4005. // [, int Offset]
  4006. // [, float Clamp]
  4007. // [, out uint Status]);
  4008. //
  4009. // For TextureCube and TextureCubeArray:
  4010. // DXGI_FORMAT Object.Sample(sampler_state S,
  4011. // float Location
  4012. // [, float Clamp]
  4013. // [, out uint Status]);
  4014. //
  4015. // For Texture2D/Texture2DArray:
  4016. // <Template Type>4 Object.Gather(sampler_state S,
  4017. // float2|3|4 Location,
  4018. // int2 Offset
  4019. // [, uint Status]);
  4020. //
  4021. // For TextureCube/TextureCubeArray:
  4022. // <Template Type>4 Object.Gather(sampler_state S,
  4023. // float2|3|4 Location
  4024. // [, uint Status]);
  4025. //
  4026. // Other Texture types do not have a Gather method.
  4027. const auto numArgs = expr->getNumArgs();
  4028. const auto loc = expr->getExprLoc();
  4029. const bool hasStatusArg =
  4030. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4031. SpirvInstruction *clamp = nullptr;
  4032. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  4033. clamp = doExpr(expr->getArg(2));
  4034. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  4035. clamp = doExpr(expr->getArg(3));
  4036. const bool hasClampArg = (clamp != 0);
  4037. const auto status =
  4038. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4039. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  4040. // and subtract 2 for sampler_state and location.
  4041. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  4042. const auto *imageExpr = expr->getImplicitObjectArgument();
  4043. const QualType imageType = imageExpr->getType();
  4044. auto *image = loadIfGLValue(imageExpr);
  4045. auto *sampler = doExpr(expr->getArg(0));
  4046. auto *coordinate = doExpr(expr->getArg(1));
  4047. // .Sample()/.Gather() may have a third optional paramter for offset.
  4048. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4049. if (hasOffsetArg)
  4050. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  4051. const auto retType = expr->getDirectCallee()->getReturnType();
  4052. if (isSample) {
  4053. return createImageSample(retType, imageType, image, sampler, coordinate,
  4054. /*compareVal*/ nullptr, /*bias*/ nullptr,
  4055. /*lod*/ nullptr, std::make_pair(nullptr, nullptr),
  4056. constOffset, varOffset,
  4057. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  4058. /*minLod*/ clamp, status,
  4059. expr->getCallee()->getLocStart());
  4060. } else {
  4061. return spvBuilder.createImageGather(
  4062. retType, imageType, image, sampler, coordinate,
  4063. // .Gather() doc says we return four components of red data.
  4064. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)),
  4065. /*compareVal*/ nullptr, constOffset, varOffset,
  4066. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, status, loc);
  4067. }
  4068. }
  4069. SpirvInstruction *
  4070. SpirvEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  4071. const bool isBias) {
  4072. // Signatures:
  4073. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  4074. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  4075. // float Location,
  4076. // float Bias
  4077. // [, int Offset]
  4078. // [, float clamp]
  4079. // [, out uint Status]);
  4080. //
  4081. // For TextureCube and TextureCubeArray:
  4082. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  4083. // float Location,
  4084. // float Bias
  4085. // [, float clamp]
  4086. // [, out uint Status]);
  4087. //
  4088. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  4089. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  4090. // float Location,
  4091. // float LOD
  4092. // [, int Offset]
  4093. // [, out uint Status]);
  4094. //
  4095. // For TextureCube and TextureCubeArray:
  4096. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  4097. // float Location,
  4098. // float LOD
  4099. // [, out uint Status]);
  4100. const auto numArgs = expr->getNumArgs();
  4101. const bool hasStatusArg =
  4102. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4103. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4104. SpirvInstruction *clamp = nullptr;
  4105. // The .SampleLevel() methods do not take the clamp argument.
  4106. if (isBias) {
  4107. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  4108. clamp = doExpr(expr->getArg(3));
  4109. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  4110. clamp = doExpr(expr->getArg(4));
  4111. }
  4112. const bool hasClampArg = clamp != nullptr;
  4113. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  4114. // and 3 for sampler_state, location, and Bias/LOD.
  4115. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  4116. const auto *imageExpr = expr->getImplicitObjectArgument();
  4117. const QualType imageType = imageExpr->getType();
  4118. auto *image = loadIfGLValue(imageExpr);
  4119. auto *sampler = doExpr(expr->getArg(0));
  4120. auto *coordinate = doExpr(expr->getArg(1));
  4121. SpirvInstruction *lod = nullptr;
  4122. SpirvInstruction *bias = nullptr;
  4123. if (isBias) {
  4124. bias = doExpr(expr->getArg(2));
  4125. } else {
  4126. lod = doExpr(expr->getArg(2));
  4127. }
  4128. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  4129. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4130. if (hasOffsetArg)
  4131. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  4132. const auto retType = expr->getDirectCallee()->getReturnType();
  4133. return createImageSample(
  4134. retType, imageType, image, sampler, coordinate,
  4135. /*compareVal*/ nullptr, bias, lod, std::make_pair(nullptr, nullptr),
  4136. constOffset, varOffset,
  4137. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  4138. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  4139. }
  4140. SpirvInstruction *
  4141. SpirvEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  4142. // Signature:
  4143. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  4144. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  4145. // float Location,
  4146. // float DDX,
  4147. // float DDY
  4148. // [, int Offset]
  4149. // [, float Clamp]
  4150. // [, out uint Status]);
  4151. //
  4152. // For TextureCube and TextureCubeArray:
  4153. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  4154. // float Location,
  4155. // float DDX,
  4156. // float DDY
  4157. // [, float Clamp]
  4158. // [, out uint Status]);
  4159. const auto numArgs = expr->getNumArgs();
  4160. const bool hasStatusArg =
  4161. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4162. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4163. SpirvInstruction *clamp = nullptr;
  4164. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  4165. clamp = doExpr(expr->getArg(4));
  4166. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  4167. clamp = doExpr(expr->getArg(5));
  4168. const bool hasClampArg = clamp != nullptr;
  4169. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  4170. // and 4 for sampler_state, location, DDX, and DDY;
  4171. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  4172. const auto *imageExpr = expr->getImplicitObjectArgument();
  4173. const QualType imageType = imageExpr->getType();
  4174. auto *image = loadIfGLValue(imageExpr);
  4175. auto *sampler = doExpr(expr->getArg(0));
  4176. auto *coordinate = doExpr(expr->getArg(1));
  4177. auto *ddx = doExpr(expr->getArg(2));
  4178. auto *ddy = doExpr(expr->getArg(3));
  4179. // If offset is present in .SampleGrad(), it is the fifth argument.
  4180. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4181. if (hasOffsetArg)
  4182. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  4183. const auto retType = expr->getDirectCallee()->getReturnType();
  4184. return createImageSample(
  4185. retType, imageType, image, sampler, coordinate,
  4186. /*compareVal*/ nullptr, /*bias*/ nullptr,
  4187. /*lod*/ nullptr, std::make_pair(ddx, ddy), constOffset, varOffset,
  4188. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  4189. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  4190. }
  4191. SpirvInstruction *
  4192. SpirvEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  4193. const bool isCmp) {
  4194. // .SampleCmp() Signature:
  4195. //
  4196. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  4197. // float Object.SampleCmp(
  4198. // SamplerComparisonState S,
  4199. // float Location,
  4200. // float CompareValue
  4201. // [, int Offset]
  4202. // [, float Clamp]
  4203. // [, out uint Status]
  4204. // );
  4205. //
  4206. // For TextureCube and TextureCubeArray:
  4207. // float Object.SampleCmp(
  4208. // SamplerComparisonState S,
  4209. // float Location,
  4210. // float CompareValue
  4211. // [, float Clamp]
  4212. // [, out uint Status]
  4213. // );
  4214. //
  4215. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  4216. // It never takes a clamp argument, which is good because lod and clamp may
  4217. // not be used together.
  4218. //
  4219. // .SampleCmpLevelZero() Signature:
  4220. //
  4221. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  4222. // float Object.SampleCmpLevelZero(
  4223. // SamplerComparisonState S,
  4224. // float Location,
  4225. // float CompareValue
  4226. // [, int Offset]
  4227. // [, out uint Status]
  4228. // );
  4229. //
  4230. // For TextureCube and TextureCubeArray:
  4231. // float Object.SampleCmpLevelZero(
  4232. // SamplerComparisonState S,
  4233. // float Location,
  4234. // float CompareValue
  4235. // [, out uint Status]
  4236. // );
  4237. const auto numArgs = expr->getNumArgs();
  4238. const bool hasStatusArg =
  4239. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4240. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4241. SpirvInstruction *clamp = nullptr;
  4242. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  4243. if (isCmp) {
  4244. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  4245. clamp = doExpr(expr->getArg(3));
  4246. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  4247. clamp = doExpr(expr->getArg(4));
  4248. }
  4249. const bool hasClampArg = clamp != nullptr;
  4250. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  4251. // and 3 for sampler_state, location, and compare_value.
  4252. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  4253. const auto *imageExpr = expr->getImplicitObjectArgument();
  4254. auto *image = loadIfGLValue(imageExpr);
  4255. auto *sampler = doExpr(expr->getArg(0));
  4256. auto *coordinate = doExpr(expr->getArg(1));
  4257. auto *compareVal = doExpr(expr->getArg(2));
  4258. // If offset is present in .SampleCmp(), it will be the fourth argument.
  4259. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4260. if (hasOffsetArg)
  4261. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  4262. auto *lod = isCmp ? nullptr
  4263. : spvBuilder.getConstantFloat(astContext.FloatTy,
  4264. llvm::APFloat(0.0f));
  4265. const auto retType = expr->getDirectCallee()->getReturnType();
  4266. const auto imageType = imageExpr->getType();
  4267. return createImageSample(
  4268. retType, imageType, image, sampler, coordinate, compareVal,
  4269. /*bias*/ nullptr, lod, std::make_pair(nullptr, nullptr), constOffset,
  4270. varOffset,
  4271. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, /*minLod*/ clamp,
  4272. status, expr->getCallee()->getLocStart());
  4273. }
  4274. SpirvInstruction *
  4275. SpirvEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  4276. // Signature:
  4277. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  4278. // ret Object.Load(int Location
  4279. // [, int Offset]
  4280. // [, uint status]);
  4281. //
  4282. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  4283. // ret Object.Load(int Location
  4284. // [, int SampleIndex]
  4285. // [, int Offset]
  4286. // [, uint status]);
  4287. //
  4288. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  4289. // RWTexture2DArray, RWTexture3D:
  4290. // ret Object.Load (int Location
  4291. // [, uint status]);
  4292. //
  4293. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  4294. // methods that take an additional Status argument. However, since these types
  4295. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  4296. // figuring out the Residency Code for them. Therefore having the Status
  4297. // argument for these types is not supported.
  4298. //
  4299. // For (RW)ByteAddressBuffer:
  4300. // ret Object.{Load,Load2,Load3,Load4} (int Location
  4301. // [, uint status]);
  4302. //
  4303. // For (RW)StructuredBuffer:
  4304. // ret Object.Load (int Location
  4305. // [, uint status]);
  4306. //
  4307. const auto *object = expr->getImplicitObjectArgument();
  4308. const auto objectType = object->getType();
  4309. if (isRWByteAddressBuffer(objectType) || isByteAddressBuffer(objectType))
  4310. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  4311. if (isStructuredBuffer(objectType))
  4312. return processStructuredBufferLoad(expr);
  4313. const auto numArgs = expr->getNumArgs();
  4314. const auto *locationArg = expr->getArg(0);
  4315. const bool textureMS = isTextureMS(objectType);
  4316. const bool hasStatusArg =
  4317. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4318. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4319. auto loc = expr->getExprLoc();
  4320. if (isBuffer(objectType) || isRWBuffer(objectType) || isRWTexture(objectType))
  4321. return processBufferTextureLoad(object, doExpr(locationArg),
  4322. /*constOffset*/ nullptr,
  4323. /*varOffset*/ nullptr, /*lod*/ nullptr,
  4324. /*residencyCode*/ status, loc);
  4325. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  4326. // and 1 for location.
  4327. const bool hasOffsetArg = numArgs - hasStatusArg - textureMS - 1 > 0;
  4328. if (isTexture(objectType)) {
  4329. // .Load() has a second optional paramter for offset.
  4330. SpirvInstruction *location = doExpr(locationArg);
  4331. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4332. SpirvInstruction *coordinate = location, *lod = nullptr;
  4333. if (textureMS) {
  4334. // SampleIndex is only available when the Object is of Texture2DMS or
  4335. // Texture2DMSArray types. Under those cases, Offset will be the third
  4336. // parameter (index 2).
  4337. lod = doExpr(expr->getArg(1));
  4338. if (hasOffsetArg)
  4339. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  4340. } else {
  4341. // For Texture Load() functions, the location parameter is a vector
  4342. // that consists of both the coordinate and the mipmap level (via the
  4343. // last vector element). We need to split it here since the
  4344. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  4345. splitVecLastElement(locationArg->getType(), location, &coordinate, &lod,
  4346. locationArg->getExprLoc());
  4347. // For textures other than Texture2DMS(Array), offset should be the
  4348. // second parameter (index 1).
  4349. if (hasOffsetArg)
  4350. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  4351. }
  4352. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  4353. lod, status, loc);
  4354. }
  4355. emitError("Load() of the given object type unimplemented",
  4356. object->getExprLoc());
  4357. return nullptr;
  4358. }
  4359. SpirvInstruction *
  4360. SpirvEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  4361. const auto objectType = expr->getImplicitObjectArgument()->getType();
  4362. if (isTexture(objectType) || isRWTexture(objectType) ||
  4363. isBuffer(objectType) || isRWBuffer(objectType)) {
  4364. return processBufferTextureGetDimensions(expr);
  4365. } else if (isByteAddressBuffer(objectType) ||
  4366. isRWByteAddressBuffer(objectType) ||
  4367. isStructuredBuffer(objectType) ||
  4368. isAppendStructuredBuffer(objectType) ||
  4369. isConsumeStructuredBuffer(objectType)) {
  4370. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  4371. } else {
  4372. emitError("GetDimensions() of the given object type unimplemented",
  4373. expr->getExprLoc());
  4374. return nullptr;
  4375. }
  4376. }
  4377. SpirvInstruction *
  4378. SpirvEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  4379. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  4380. const Expr *baseExpr = nullptr;
  4381. const Expr *indexExpr = nullptr;
  4382. const Expr *lodExpr = nullptr;
  4383. // For Textures, regular indexing (operator[]) uses slice 0.
  4384. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  4385. auto *lod = isTexture(baseExpr->getType())
  4386. ? spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  4387. llvm::APInt(32, 0))
  4388. : nullptr;
  4389. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4390. /*constOffset*/ nullptr,
  4391. /*varOffset*/ nullptr, lod,
  4392. /*residencyCode*/ nullptr,
  4393. expr->getExprLoc());
  4394. }
  4395. // .mips[][] or .sample[][] must use the correct slice.
  4396. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  4397. auto *lod = doExpr(lodExpr);
  4398. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4399. /*constOffset*/ nullptr,
  4400. /*varOffset*/ nullptr, lod,
  4401. /*residencyCode*/ nullptr,
  4402. expr->getExprLoc());
  4403. }
  4404. }
  4405. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4406. const Expr *baseExpr = collectArrayStructIndices(
  4407. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4408. auto base = loadIfAliasVarRef(baseExpr);
  4409. if (indices.empty())
  4410. return base; // For indexing into size-1 vectors and 1xN matrices
  4411. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  4412. // to create a local variable to hold the rvalue.
  4413. //
  4414. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  4415. // all indices are contant integers.
  4416. if (base->isRValue()) {
  4417. base = createTemporaryVar(baseExpr->getType(), "vector", base,
  4418. baseExpr->getExprLoc());
  4419. }
  4420. return turnIntoElementPtr(baseExpr->getType(), base, expr->getType(), indices,
  4421. baseExpr->getExprLoc());
  4422. }
  4423. SpirvInstruction *
  4424. SpirvEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  4425. const Expr *baseExpr = expr->getBase();
  4426. auto *baseInfo = doExpr(baseExpr);
  4427. const auto layoutRule = baseInfo->getLayoutRule();
  4428. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  4429. const auto accessor = expr->getEncodedElementAccess();
  4430. uint32_t rowCount = 0, colCount = 0;
  4431. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  4432. // Construct a temporary vector out of all elements accessed:
  4433. // 1. Create access chain for each element using OpAccessChain
  4434. // 2. Load each element using OpLoad
  4435. // 3. Create the vector using OpCompositeConstruct
  4436. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4437. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4438. uint32_t row = 0, col = 0;
  4439. SpirvInstruction *elem = nullptr;
  4440. accessor.GetPosition(i, &row, &col);
  4441. llvm::SmallVector<uint32_t, 2> indices;
  4442. // If the matrix only has one row/column, we are indexing into a vector
  4443. // then. Only one index is needed for such cases.
  4444. if (rowCount > 1)
  4445. indices.push_back(row);
  4446. if (colCount > 1)
  4447. indices.push_back(col);
  4448. if (!baseInfo->isRValue()) {
  4449. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  4450. nullptr);
  4451. for (uint32_t i = 0; i < indices.size(); ++i)
  4452. indexInstructions[i] = spvBuilder.getConstantInt(
  4453. astContext.IntTy, llvm::APInt(32, indices[i], true));
  4454. if (!indices.empty()) {
  4455. assert(!baseInfo->isRValue());
  4456. // Load the element via access chain
  4457. elem = spvBuilder.createAccessChain(
  4458. elemType, baseInfo, indexInstructions, baseExpr->getLocStart());
  4459. } else {
  4460. // The matrix is of size 1x1. No need to use access chain, base should
  4461. // be the source pointer.
  4462. elem = baseInfo;
  4463. }
  4464. elem = spvBuilder.createLoad(elemType, elem, baseExpr->getLocStart());
  4465. } else { // e.g., (mat1 + mat2)._m11
  4466. elem = spvBuilder.createCompositeExtract(elemType, baseInfo, indices,
  4467. baseExpr->getLocStart());
  4468. }
  4469. elements.push_back(elem);
  4470. }
  4471. const auto size = elements.size();
  4472. auto *value = elements.front();
  4473. if (size > 1) {
  4474. value = spvBuilder.createCompositeConstruct(
  4475. astContext.getExtVectorType(elemType, size), elements,
  4476. expr->getLocStart());
  4477. }
  4478. // Note: Special-case: Booleans have no physical layout, and therefore when
  4479. // layout is required booleans are represented as unsigned integers.
  4480. // Therefore, after loading the uint we should convert it boolean.
  4481. if (elemType->isBooleanType() && layoutRule != SpirvLayoutRule::Void) {
  4482. const auto fromType =
  4483. size == 1 ? astContext.UnsignedIntTy
  4484. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  4485. const auto toType =
  4486. size == 1 ? astContext.BoolTy
  4487. : astContext.getExtVectorType(astContext.BoolTy, size);
  4488. value = castToBool(value, fromType, toType, expr->getLocStart());
  4489. }
  4490. value->setRValue();
  4491. return value;
  4492. }
  4493. SpirvInstruction *
  4494. SpirvEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  4495. const Expr *baseExpr = nullptr;
  4496. hlsl::VectorMemberAccessPositions accessor;
  4497. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  4498. const QualType baseType = baseExpr->getType();
  4499. assert(hlsl::IsHLSLVecType(baseType));
  4500. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4501. const auto accessorSize = static_cast<size_t>(accessor.Count);
  4502. // Depending on the number of elements selected, we emit different
  4503. // instructions.
  4504. // For vectors of size greater than 1, if we are only selecting one element,
  4505. // typical access chain or composite extraction should be fine. But if we
  4506. // are selecting more than one elements, we must resolve to vector specific
  4507. // operations.
  4508. // For size-1 vectors, if we are selecting their single elements multiple
  4509. // times, we need composite construct instructions.
  4510. if (accessorSize == 1) {
  4511. auto *baseInfo = doExpr(baseExpr);
  4512. if (!baseInfo || baseSize == 1) {
  4513. // Selecting one element from a size-1 vector. The underlying vector is
  4514. // already treated as a scalar.
  4515. return baseInfo;
  4516. }
  4517. // If the base is an lvalue, we should emit an access chain instruction
  4518. // so that we can load/store the specified element. For rvalue base,
  4519. // we should use composite extraction. We should check the immediate base
  4520. // instead of the original base here since we can have something like
  4521. // v.xyyz to turn a lvalue v into rvalue.
  4522. const auto type = expr->getType();
  4523. if (!baseInfo->isRValue()) { // E.g., v.x;
  4524. auto *index = spvBuilder.getConstantInt(
  4525. astContext.IntTy, llvm::APInt(32, accessor.Swz0, true));
  4526. // We need a lvalue here. Do not try to load.
  4527. return spvBuilder.createAccessChain(type, baseInfo, {index},
  4528. baseExpr->getLocStart());
  4529. } else { // E.g., (v + w).x;
  4530. // The original base vector may not be a rvalue. Need to load it if
  4531. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  4532. // for that case.
  4533. SpirvInstruction *result = spvBuilder.createCompositeExtract(
  4534. type, baseInfo, {accessor.Swz0}, baseExpr->getLocStart());
  4535. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  4536. // used to represent them when layout is required.
  4537. if (expr->getType()->isBooleanType() &&
  4538. baseInfo->getLayoutRule() != SpirvLayoutRule::Void)
  4539. result = castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy,
  4540. expr->getLocStart());
  4541. return result;
  4542. }
  4543. }
  4544. if (baseSize == 1) {
  4545. // Selecting more than one element from a size-1 vector, for example,
  4546. // <scalar>.xx. Construct the vector.
  4547. auto *info = loadIfGLValue(baseExpr);
  4548. const auto type = expr->getType();
  4549. llvm::SmallVector<SpirvInstruction *, 4> components(accessorSize, info);
  4550. info = spvBuilder.createCompositeConstruct(type, components,
  4551. expr->getLocStart());
  4552. info->setRValue();
  4553. return info;
  4554. }
  4555. llvm::SmallVector<uint32_t, 4> selectors;
  4556. selectors.resize(accessorSize);
  4557. // Whether we are selecting elements in the original order
  4558. bool originalOrder = baseSize == accessorSize;
  4559. for (uint32_t i = 0; i < accessorSize; ++i) {
  4560. accessor.GetPosition(i, &selectors[i]);
  4561. // We can select more elements than the vector provides. This handles
  4562. // that case too.
  4563. originalOrder &= selectors[i] == i;
  4564. }
  4565. if (originalOrder)
  4566. return doExpr(baseExpr);
  4567. auto *info = loadIfGLValue(baseExpr);
  4568. // Use base for both vectors. But we are only selecting values from the
  4569. // first one.
  4570. return spvBuilder.createVectorShuffle(expr->getType(), info, info, selectors,
  4571. expr->getLocStart());
  4572. }
  4573. SpirvInstruction *SpirvEmitter::doInitListExpr(const InitListExpr *expr) {
  4574. if (auto *id = tryToEvaluateAsConst(expr)) {
  4575. id->setRValue();
  4576. return id;
  4577. }
  4578. auto *result = InitListHandler(astContext, *this).processInit(expr);
  4579. result->setRValue();
  4580. return result;
  4581. }
  4582. SpirvInstruction *SpirvEmitter::doMemberExpr(const MemberExpr *expr) {
  4583. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4584. const Expr *base = collectArrayStructIndices(
  4585. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4586. auto *instr = loadIfAliasVarRef(base);
  4587. if (instr && !indices.empty()) {
  4588. instr = turnIntoElementPtr(base->getType(), instr, expr->getType(), indices,
  4589. base->getExprLoc());
  4590. }
  4591. return instr;
  4592. }
  4593. SpirvVariable *SpirvEmitter::createTemporaryVar(QualType type,
  4594. llvm::StringRef name,
  4595. SpirvInstruction *init,
  4596. SourceLocation loc) {
  4597. // We are creating a temporary variable in the Function storage class here,
  4598. // which means it has void layout rule.
  4599. const std::string varName = "temp.var." + name.str();
  4600. auto *var = spvBuilder.addFnVar(type, loc, varName);
  4601. storeValue(var, init, type, loc);
  4602. return var;
  4603. }
  4604. SpirvInstruction *SpirvEmitter::doUnaryOperator(const UnaryOperator *expr) {
  4605. const auto opcode = expr->getOpcode();
  4606. const auto *subExpr = expr->getSubExpr();
  4607. const auto subType = subExpr->getType();
  4608. auto *subValue = doExpr(subExpr);
  4609. switch (opcode) {
  4610. case UO_PreInc:
  4611. case UO_PreDec:
  4612. case UO_PostInc:
  4613. case UO_PostDec: {
  4614. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  4615. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  4616. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  4617. SpirvInstruction *originValue =
  4618. subValue->isRValue()
  4619. ? subValue
  4620. : spvBuilder.createLoad(subType, subValue, subExpr->getLocStart());
  4621. auto *one = hlsl::IsHLSLMatType(subType) ? getMatElemValueOne(subType)
  4622. : getValueOne(subType);
  4623. SpirvInstruction *incValue = nullptr;
  4624. if (isMxNMatrix(subType)) {
  4625. // For matrices, we can only increment/decrement each vector of it.
  4626. const auto actOnEachVec = [this, spvOp, one,
  4627. expr](uint32_t /*index*/, QualType vecType,
  4628. SpirvInstruction *lhsVec) {
  4629. auto *val = spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, one,
  4630. expr->getOperatorLoc());
  4631. val->setRValue();
  4632. return val;
  4633. };
  4634. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec,
  4635. expr->getLocStart());
  4636. } else {
  4637. incValue = spvBuilder.createBinaryOp(spvOp, subType, originValue, one,
  4638. expr->getOperatorLoc());
  4639. }
  4640. // If this is a RWBuffer/RWTexture assignment, OpImageWrite will be used.
  4641. // Otherwise, store using OpStore.
  4642. if (tryToAssignToRWBufferRWTexture(subExpr, incValue)) {
  4643. incValue->setRValue();
  4644. subValue = incValue;
  4645. } else {
  4646. spvBuilder.createStore(subValue, incValue, subExpr->getLocStart());
  4647. }
  4648. // Prefix increment/decrement operator returns a lvalue, while postfix
  4649. // increment/decrement returns a rvalue.
  4650. if (isPre) {
  4651. return subValue;
  4652. } else {
  4653. originValue->setRValue();
  4654. return originValue;
  4655. }
  4656. }
  4657. case UO_Not: {
  4658. subValue = spvBuilder.createUnaryOp(spv::Op::OpNot, subType, subValue,
  4659. expr->getOperatorLoc());
  4660. subValue->setRValue();
  4661. return subValue;
  4662. }
  4663. case UO_LNot: {
  4664. // Parsing will do the necessary casting to make sure we are applying the
  4665. // ! operator on boolean values.
  4666. subValue = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, subType,
  4667. subValue, expr->getOperatorLoc());
  4668. subValue->setRValue();
  4669. return subValue;
  4670. }
  4671. case UO_Plus:
  4672. // No need to do anything for the prefix + operator.
  4673. return subValue;
  4674. case UO_Minus: {
  4675. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4676. const spv::Op spvOp = isFloatOrVecMatOfFloatType(subType)
  4677. ? spv::Op::OpFNegate
  4678. : spv::Op::OpSNegate;
  4679. if (isMxNMatrix(subType)) {
  4680. // For matrices, we can only negate each vector of it.
  4681. const auto actOnEachVec = [this, spvOp, expr](uint32_t /*index*/,
  4682. QualType vecType,
  4683. SpirvInstruction *lhsVec) {
  4684. return spvBuilder.createUnaryOp(spvOp, vecType, lhsVec,
  4685. expr->getOperatorLoc());
  4686. };
  4687. return processEachVectorInMatrix(subExpr, subValue, actOnEachVec,
  4688. expr->getLocStart());
  4689. } else {
  4690. subValue = spvBuilder.createUnaryOp(spvOp, subType, subValue,
  4691. expr->getOperatorLoc());
  4692. subValue->setRValue();
  4693. return subValue;
  4694. }
  4695. }
  4696. default:
  4697. break;
  4698. }
  4699. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4700. << expr->getOpcodeStr(opcode);
  4701. expr->dump();
  4702. return 0;
  4703. }
  4704. spv::Op SpirvEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4705. const bool isSintType = isSintOrVecMatOfSintType(type);
  4706. const bool isUintType = isUintOrVecMatOfUintType(type);
  4707. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4708. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4709. \
  4710. case BO_##kind: { \
  4711. if (isSintType || isUintType) { \
  4712. return spv::Op::Op##intBinOp; \
  4713. } \
  4714. if (isFloatType) { \
  4715. return spv::Op::Op##floatBinOp; \
  4716. } \
  4717. } break
  4718. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4719. \
  4720. case BO_##kind: { \
  4721. if (isSintType) { \
  4722. return spv::Op::Op##sintBinOp; \
  4723. } \
  4724. if (isUintType) { \
  4725. return spv::Op::Op##uintBinOp; \
  4726. } \
  4727. if (isFloatType) { \
  4728. return spv::Op::Op##floatBinOp; \
  4729. } \
  4730. } break
  4731. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4732. \
  4733. case BO_##kind: { \
  4734. if (isSintType) { \
  4735. return spv::Op::Op##sintBinOp; \
  4736. } \
  4737. if (isUintType) { \
  4738. return spv::Op::Op##uintBinOp; \
  4739. } \
  4740. } break
  4741. switch (op) {
  4742. case BO_EQ: {
  4743. if (isBoolOrVecMatOfBoolType(type))
  4744. return spv::Op::OpLogicalEqual;
  4745. if (isSintType || isUintType)
  4746. return spv::Op::OpIEqual;
  4747. if (isFloatType)
  4748. return spv::Op::OpFOrdEqual;
  4749. } break;
  4750. case BO_NE: {
  4751. if (isBoolOrVecMatOfBoolType(type))
  4752. return spv::Op::OpLogicalNotEqual;
  4753. if (isSintType || isUintType)
  4754. return spv::Op::OpINotEqual;
  4755. if (isFloatType)
  4756. return spv::Op::OpFOrdNotEqual;
  4757. } break;
  4758. // According to HLSL doc, all sides of the && and || expression are always
  4759. // evaluated.
  4760. case BO_LAnd:
  4761. return spv::Op::OpLogicalAnd;
  4762. case BO_LOr:
  4763. return spv::Op::OpLogicalOr;
  4764. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4765. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4766. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4767. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4768. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4769. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4770. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4771. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4772. // According to HLSL spec, "the modulus operator returns the remainder of
  4773. // a division." "The % operator is defined only in cases where either both
  4774. // sides are positive or both sides are negative."
  4775. //
  4776. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4777. // the former, the sign of a non-0 result comes from Operand 1, while
  4778. // with the latter, from Operand 2.
  4779. //
  4780. // For operands with different signs, technically we can map % to either
  4781. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4782. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4783. // const expression evaluation if we map % to Op*Rem.
  4784. //
  4785. // Note there is no OpURem in SPIR-V.
  4786. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4787. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4788. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4789. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4790. FOrdLessThanEqual);
  4791. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4792. FOrdGreaterThan);
  4793. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4794. FOrdGreaterThanEqual);
  4795. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4796. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4797. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4798. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4799. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4800. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4801. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4802. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4803. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4804. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4805. default:
  4806. break;
  4807. }
  4808. #undef BIN_OP_CASE_INT_FLOAT
  4809. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4810. #undef BIN_OP_CASE_SINT_UINT
  4811. emitError("translating binary operator '%0' unimplemented", {})
  4812. << BinaryOperator::getOpcodeStr(op);
  4813. return spv::Op::OpNop;
  4814. }
  4815. SpirvInstruction *
  4816. SpirvEmitter::processAssignment(const Expr *lhs, SpirvInstruction *rhs,
  4817. const bool isCompoundAssignment,
  4818. SpirvInstruction *lhsPtr) {
  4819. lhs = lhs->IgnoreParenNoopCasts(astContext);
  4820. // Assigning to vector swizzling should be handled differently.
  4821. if (SpirvInstruction *result = tryToAssignToVectorElements(lhs, rhs))
  4822. return result;
  4823. // Assigning to matrix swizzling should be handled differently.
  4824. if (SpirvInstruction *result = tryToAssignToMatrixElements(lhs, rhs))
  4825. return result;
  4826. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4827. if (SpirvInstruction *result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4828. return result;
  4829. // Assigning to a out attribute or indices object in mesh shader should be
  4830. // handled differently.
  4831. if (SpirvInstruction *result = tryToAssignToMSOutAttrsOrIndices(lhs, rhs))
  4832. return result;
  4833. // Assigning to a 'string' variable. SPIR-V doesn't have a string type, and we
  4834. // do not allow creating or modifying string variables. We do allow use of
  4835. // string literals using OpString.
  4836. if (isStringType(lhs->getType())) {
  4837. emitError("string variables are immutable in SPIR-V.", lhs->getExprLoc());
  4838. return nullptr;
  4839. }
  4840. // Normal assignment procedure
  4841. if (!lhsPtr)
  4842. lhsPtr = doExpr(lhs);
  4843. storeValue(lhsPtr, rhs, lhs->getType(), lhs->getLocStart());
  4844. // Plain assignment returns a rvalue, while compound assignment returns
  4845. // lvalue.
  4846. return isCompoundAssignment ? lhsPtr : rhs;
  4847. }
  4848. void SpirvEmitter::storeValue(SpirvInstruction *lhsPtr,
  4849. SpirvInstruction *rhsVal, QualType lhsValType,
  4850. SourceLocation loc) {
  4851. // Defend against nullptr source or destination so errors can bubble up to the
  4852. // user.
  4853. if (!lhsPtr || !rhsVal)
  4854. return;
  4855. if (const auto *refType = lhsValType->getAs<ReferenceType>())
  4856. lhsValType = refType->getPointeeType();
  4857. QualType matElemType = {};
  4858. const bool lhsIsMat = isMxNMatrix(lhsValType, &matElemType);
  4859. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4860. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4861. if (isScalarType(lhsValType) || isVectorType(lhsValType) || lhsIsFloatMat) {
  4862. // Special-case: According to the SPIR-V Spec: There is no physical size
  4863. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4864. // is used to represent booleans when layout is required. In such cases,
  4865. // we should cast the boolean to uint before creating OpStore.
  4866. if (isBoolOrVecOfBoolType(lhsValType) &&
  4867. lhsPtr->getLayoutRule() != SpirvLayoutRule::Void) {
  4868. uint32_t vecSize = 1;
  4869. const bool isVec = isVectorType(lhsValType, nullptr, &vecSize);
  4870. const auto toType =
  4871. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4872. : astContext.UnsignedIntTy;
  4873. const auto fromType =
  4874. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4875. : astContext.BoolTy;
  4876. rhsVal = castToInt(rhsVal, fromType, toType, {});
  4877. }
  4878. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4879. } else if (isOpaqueType(lhsValType)) {
  4880. // Resource types are represented using RecordType in the AST.
  4881. // Handle them before the general RecordType.
  4882. //
  4883. // HLSL allows to put resource types that translating into SPIR-V opaque
  4884. // types in structs, or assign to variables of resource types. These can all
  4885. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4886. // let SPIRV-Tools opt to do the legalization work.
  4887. //
  4888. // Note: legalization specific code
  4889. if (hlsl::IsHLSLRayQueryType(lhsValType)) {
  4890. emitError("store value of type %0 is unsupported", {}) << lhsValType;
  4891. return;
  4892. }
  4893. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4894. needsLegalization = true;
  4895. } else if (isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4896. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4897. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4898. // up.
  4899. //
  4900. // Note: legalization specific code
  4901. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4902. needsLegalization = true;
  4903. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4904. // recursively like normal structs using the following logic.
  4905. //
  4906. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4907. // variables as function parameters/returns/variables, but happily accepts
  4908. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4909. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4910. // represented differently as struct T.
  4911. } else if (isOpaqueArrayType(lhsValType)) {
  4912. // For opaque array types, we cannot perform OpLoad on the whole array and
  4913. // then write out as a whole; instead, we need to OpLoad each element
  4914. // using access chains. This is to influence later SPIR-V transformations
  4915. // to use access chains to access each opaque object; if we do array
  4916. // wholesale handling here, they will be in the final transformed code.
  4917. // Drivers don't like that.
  4918. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4919. assert(!rhsVal->isRValue());
  4920. if (!lhsValType->isConstantArrayType()) {
  4921. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4922. needsLegalization = true;
  4923. return;
  4924. }
  4925. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4926. const auto elemType = arrayType->getElementType();
  4927. const auto arraySize =
  4928. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4929. // Do separate load of each element via access chain
  4930. llvm::SmallVector<SpirvInstruction *, 8> elements;
  4931. for (uint32_t i = 0; i < arraySize; ++i) {
  4932. auto *subRhsPtr = spvBuilder.createAccessChain(
  4933. elemType, rhsVal,
  4934. {spvBuilder.getConstantInt(astContext.IntTy,
  4935. llvm::APInt(32, i, true))},
  4936. loc);
  4937. elements.push_back(spvBuilder.createLoad(elemType, subRhsPtr, loc));
  4938. }
  4939. // Create a new composite and write out once
  4940. spvBuilder.createStore(
  4941. lhsPtr,
  4942. spvBuilder.createCompositeConstruct(lhsValType, elements,
  4943. rhsVal->getSourceLocation()),
  4944. loc);
  4945. } else if (lhsPtr->getLayoutRule() == rhsVal->getLayoutRule()) {
  4946. // If lhs and rhs has the same memory layout, we should be safe to load
  4947. // from rhs and directly store into lhs and avoid decomposing rhs.
  4948. // Note: this check should happen after those setting needsLegalization.
  4949. // TODO: is this optimization always correct?
  4950. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4951. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4952. lhsIsNonFpMat) {
  4953. spvBuilder.createStore(
  4954. lhsPtr,
  4955. reconstructValue(rhsVal, lhsValType, lhsPtr->getLayoutRule(), loc),
  4956. loc);
  4957. } else {
  4958. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4959. }
  4960. }
  4961. SpirvInstruction *SpirvEmitter::reconstructValue(SpirvInstruction *srcVal,
  4962. const QualType valType,
  4963. SpirvLayoutRule dstLR,
  4964. SourceLocation loc) {
  4965. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4966. // of the reconstruction (lhs or rhs) has a layout rule.
  4967. const auto handleBooleanLayout = [this, &srcVal, dstLR,
  4968. loc](SpirvInstruction *val,
  4969. QualType valType) {
  4970. // We only need to cast if we have a scalar or vector of booleans.
  4971. if (!isBoolOrVecOfBoolType(valType))
  4972. return val;
  4973. SpirvLayoutRule srcLR = srcVal->getLayoutRule();
  4974. // Source value has a layout rule, and has therefore been represented
  4975. // as a uint. Cast it to boolean before using.
  4976. bool shouldCastToBool =
  4977. srcLR != SpirvLayoutRule::Void && dstLR == SpirvLayoutRule::Void;
  4978. // Destination has a layout rule, and should therefore be represented
  4979. // as a uint. Cast to uint before using.
  4980. bool shouldCastToUint =
  4981. srcLR == SpirvLayoutRule::Void && dstLR != SpirvLayoutRule::Void;
  4982. // No boolean layout issues to take care of.
  4983. if (!shouldCastToBool && !shouldCastToUint)
  4984. return val;
  4985. uint32_t vecSize = 1;
  4986. isVectorType(valType, nullptr, &vecSize);
  4987. QualType boolType =
  4988. vecSize == 1 ? astContext.BoolTy
  4989. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4990. QualType uintType =
  4991. vecSize == 1
  4992. ? astContext.UnsignedIntTy
  4993. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4994. if (shouldCastToBool)
  4995. return castToBool(val, uintType, boolType, loc);
  4996. if (shouldCastToUint)
  4997. return castToInt(val, boolType, uintType, loc);
  4998. return val;
  4999. };
  5000. // Lambda for cases where we want to reconstruct an array
  5001. const auto reconstructArray = [this, &srcVal, valType, dstLR,
  5002. loc](uint32_t arraySize,
  5003. QualType arrayElemType) {
  5004. llvm::SmallVector<SpirvInstruction *, 4> elements;
  5005. for (uint32_t i = 0; i < arraySize; ++i) {
  5006. SpirvInstruction *subSrcVal =
  5007. spvBuilder.createCompositeExtract(arrayElemType, srcVal, {i}, loc);
  5008. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  5009. elements.push_back(
  5010. reconstructValue(subSrcVal, arrayElemType, dstLR, loc));
  5011. }
  5012. auto *result = spvBuilder.createCompositeConstruct(
  5013. valType, elements, srcVal->getSourceLocation());
  5014. result->setLayoutRule(dstLR);
  5015. return result;
  5016. };
  5017. // Constant arrays
  5018. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  5019. const auto elemType = arrayType->getElementType();
  5020. const auto size =
  5021. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  5022. return reconstructArray(size, elemType);
  5023. }
  5024. // Non-floating-point matrices
  5025. QualType matElemType = {};
  5026. uint32_t numRows = 0, numCols = 0;
  5027. const bool isNonFpMat =
  5028. isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  5029. !matElemType->isFloatingType();
  5030. if (isNonFpMat) {
  5031. // Note: This check should happen before the RecordType check.
  5032. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  5033. // Each array element is a vector. Get the QualType for the vector.
  5034. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  5035. return reconstructArray(numRows, elemType);
  5036. }
  5037. // Note: This check should happen before the RecordType check since
  5038. // vector/matrix/resource types are represented as RecordType in the AST.
  5039. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  5040. return handleBooleanLayout(srcVal, valType);
  5041. // Structs
  5042. if (const auto *recordType = valType->getAs<RecordType>()) {
  5043. uint32_t index = 0;
  5044. llvm::SmallVector<SpirvInstruction *, 4> elements;
  5045. // If the struct inherits from other structs, visit the bases.
  5046. const auto *decl = valType->getAsCXXRecordDecl();
  5047. for (auto baseIt = decl->bases_begin(), baseIe = decl->bases_end();
  5048. baseIt != baseIe; ++baseIt, ++index) {
  5049. SpirvInstruction *subSrcVal = spvBuilder.createCompositeExtract(
  5050. baseIt->getType(), srcVal, {index}, loc);
  5051. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  5052. elements.push_back(
  5053. reconstructValue(subSrcVal, baseIt->getType(), dstLR, loc));
  5054. }
  5055. // Go over struct fields.
  5056. for (const auto *field : recordType->getDecl()->fields()) {
  5057. SpirvInstruction *subSrcVal = spvBuilder.createCompositeExtract(
  5058. field->getType(), srcVal, {index}, loc);
  5059. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  5060. elements.push_back(
  5061. reconstructValue(subSrcVal, field->getType(), dstLR, loc));
  5062. ++index;
  5063. }
  5064. auto *result = spvBuilder.createCompositeConstruct(
  5065. valType, elements, srcVal->getSourceLocation());
  5066. result->setLayoutRule(dstLR);
  5067. return result;
  5068. }
  5069. return handleBooleanLayout(srcVal, valType);
  5070. }
  5071. SpirvInstruction *SpirvEmitter::processBinaryOp(
  5072. const Expr *lhs, const Expr *rhs, const BinaryOperatorKind opcode,
  5073. const QualType computationType, const QualType resultType,
  5074. SourceRange sourceRange, SourceLocation loc, SpirvInstruction **lhsInfo,
  5075. const spv::Op mandateGenOpcode) {
  5076. const QualType lhsType = lhs->getType();
  5077. const QualType rhsType = rhs->getType();
  5078. // If the operands are of matrix type, we need to dispatch the operation
  5079. // onto each element vector iff the operands are not degenerated matrices
  5080. // and we don't have a matrix specific SPIR-V instruction for the operation.
  5081. if (!isSpirvMatrixOp(mandateGenOpcode) && isMxNMatrix(lhsType)) {
  5082. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange, loc);
  5083. }
  5084. // Comma operator works differently from other binary operations as there is
  5085. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  5086. // respectively, and return the results of rhs.
  5087. if (opcode == BO_Comma) {
  5088. (void)doExpr(lhs);
  5089. return doExpr(rhs);
  5090. }
  5091. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  5092. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5093. // Evalute rhs before lhs
  5094. rhsVal = loadIfGLValue(rhs);
  5095. lhsVal = lhsPtr = doExpr(lhs);
  5096. // This is a compound assignment. We need to load the lhs value if lhs
  5097. // is not already rvalue and does not generate a vector shuffle.
  5098. if (!lhsPtr->isRValue() && !isVectorShuffle(lhs)) {
  5099. lhsVal = loadIfGLValue(lhs, lhsPtr);
  5100. }
  5101. // For a compound assignments, the AST does not have the proper implicit
  5102. // cast if lhs and rhs have different types. So we need to manually cast lhs
  5103. // to the computation type.
  5104. if (computationType != lhsType)
  5105. lhsVal = castToType(lhsVal, lhsType, computationType, lhs->getExprLoc());
  5106. } else {
  5107. // Evalute lhs before rhs
  5108. lhsPtr = doExpr(lhs);
  5109. if (!lhsPtr)
  5110. return nullptr;
  5111. lhsVal = loadIfGLValue(lhs, lhsPtr);
  5112. rhsVal = loadIfGLValue(rhs);
  5113. }
  5114. if (lhsInfo)
  5115. *lhsInfo = lhsPtr;
  5116. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  5117. ? translateOp(opcode, computationType)
  5118. : mandateGenOpcode;
  5119. switch (opcode) {
  5120. case BO_Shl:
  5121. case BO_Shr:
  5122. case BO_ShlAssign:
  5123. case BO_ShrAssign:
  5124. // We need to cull the RHS to make sure that we are not shifting by an
  5125. // amount that is larger than the bitwidth of the LHS.
  5126. rhsVal = spvBuilder.createBinaryOp(spv::Op::OpBitwiseAnd, computationType,
  5127. rhsVal, getMaskForBitwidthValue(rhsType),
  5128. loc);
  5129. // Fall through
  5130. case BO_Add:
  5131. case BO_Sub:
  5132. case BO_Mul:
  5133. case BO_Div:
  5134. case BO_Rem:
  5135. case BO_LT:
  5136. case BO_LE:
  5137. case BO_GT:
  5138. case BO_GE:
  5139. case BO_EQ:
  5140. case BO_NE:
  5141. case BO_And:
  5142. case BO_Or:
  5143. case BO_Xor:
  5144. case BO_LAnd:
  5145. case BO_LOr:
  5146. case BO_AddAssign:
  5147. case BO_SubAssign:
  5148. case BO_MulAssign:
  5149. case BO_DivAssign:
  5150. case BO_RemAssign:
  5151. case BO_AndAssign:
  5152. case BO_OrAssign:
  5153. case BO_XorAssign: {
  5154. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  5155. // both operands are constant and at least one of them is a spec constant.
  5156. if (SpirvConstant *lhsValConstant = dyn_cast<SpirvConstant>(lhsVal)) {
  5157. if (SpirvConstant *rhsValConstant = dyn_cast<SpirvConstant>(rhsVal)) {
  5158. if (isAcceptedSpecConstantBinaryOp(spvOp)) {
  5159. if (lhsValConstant->isSpecConstant() ||
  5160. rhsValConstant->isSpecConstant()) {
  5161. auto *val = spvBuilder.createSpecConstantBinaryOp(
  5162. spvOp, resultType, lhsVal, rhsVal, loc);
  5163. val->setRValue();
  5164. return val;
  5165. }
  5166. }
  5167. }
  5168. }
  5169. // Normal binary operation
  5170. SpirvInstruction *val = nullptr;
  5171. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5172. val = spvBuilder.createBinaryOp(spvOp, computationType, lhsVal, rhsVal,
  5173. loc);
  5174. // For a compound assignments, the AST does not have the proper implicit
  5175. // cast if lhs and rhs have different types. So we need to manually cast
  5176. // the result back to lhs' type.
  5177. if (computationType != lhsType)
  5178. val = castToType(val, computationType, lhsType, lhs->getExprLoc());
  5179. } else {
  5180. val = spvBuilder.createBinaryOp(spvOp, resultType, lhsVal, rhsVal, loc);
  5181. }
  5182. val->setRValue();
  5183. // Propagate RelaxedPrecision
  5184. if ((lhsVal && lhsVal->isRelaxedPrecision()) ||
  5185. (rhsVal && rhsVal->isRelaxedPrecision()))
  5186. val->setRelaxedPrecision();
  5187. return val;
  5188. }
  5189. case BO_Assign:
  5190. llvm_unreachable("assignment should not be handled here");
  5191. break;
  5192. case BO_PtrMemD:
  5193. case BO_PtrMemI:
  5194. case BO_Comma:
  5195. // Unimplemented
  5196. break;
  5197. }
  5198. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  5199. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  5200. return nullptr;
  5201. }
  5202. void SpirvEmitter::initOnce(QualType varType, std::string varName,
  5203. SpirvVariable *var, const Expr *varInit) {
  5204. // For uninitialized resource objects, we do nothing since there is no
  5205. // meaningful zero values for them.
  5206. if (!varInit && hlsl::IsHLSLResourceType(varType))
  5207. return;
  5208. varName = "init.done." + varName;
  5209. auto loc = varInit ? varInit->getLocStart() : SourceLocation();
  5210. // Create a file/module visible variable to hold the initialization state.
  5211. SpirvVariable *initDoneVar = spvBuilder.addModuleVar(
  5212. astContext.BoolTy, spv::StorageClass::Private, /*isPrecise*/ false,
  5213. varName, spvBuilder.getConstantBool(false));
  5214. auto *condition = spvBuilder.createLoad(astContext.BoolTy, initDoneVar, loc);
  5215. auto *todoBB = spvBuilder.createBasicBlock("if.init.todo");
  5216. auto *doneBB = spvBuilder.createBasicBlock("if.init.done");
  5217. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  5218. // jump to the "todo" basic block.
  5219. spvBuilder.createConditionalBranch(condition, doneBB, todoBB, loc, doneBB);
  5220. spvBuilder.addSuccessor(todoBB);
  5221. spvBuilder.addSuccessor(doneBB);
  5222. spvBuilder.setMergeTarget(doneBB);
  5223. spvBuilder.setInsertPoint(todoBB);
  5224. // Do initialization and mark done
  5225. if (varInit) {
  5226. var->setStorageClass(spv::StorageClass::Private);
  5227. storeValue(
  5228. // Static function variable are of private storage class
  5229. var, loadIfGLValue(varInit), varInit->getType(), varInit->getLocEnd());
  5230. } else {
  5231. spvBuilder.createStore(var, spvBuilder.getConstantNull(varType), loc);
  5232. }
  5233. spvBuilder.createStore(initDoneVar, spvBuilder.getConstantBool(true), loc);
  5234. spvBuilder.createBranch(doneBB, loc);
  5235. spvBuilder.addSuccessor(doneBB);
  5236. spvBuilder.setInsertPoint(doneBB);
  5237. }
  5238. bool SpirvEmitter::isVectorShuffle(const Expr *expr) {
  5239. // TODO: the following check is essentially duplicated from
  5240. // doHLSLVectorElementExpr. Should unify them.
  5241. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  5242. const Expr *base = nullptr;
  5243. hlsl::VectorMemberAccessPositions accessor;
  5244. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  5245. const auto accessorSize = accessor.Count;
  5246. if (accessorSize == 1) {
  5247. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  5248. // such cases.
  5249. return false;
  5250. }
  5251. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  5252. if (accessorSize != baseSize)
  5253. return true;
  5254. for (uint32_t i = 0; i < accessorSize; ++i) {
  5255. uint32_t position;
  5256. accessor.GetPosition(i, &position);
  5257. if (position != i)
  5258. return true;
  5259. }
  5260. // Selecting exactly the original vector. No vector shuffle generated.
  5261. return false;
  5262. }
  5263. return false;
  5264. }
  5265. bool SpirvEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  5266. const Expr **base,
  5267. const Expr **location,
  5268. const Expr **lod) {
  5269. if (!expr)
  5270. return false;
  5271. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  5272. const CXXOperatorCallExpr *outerExpr = expr;
  5273. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  5274. return false;
  5275. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  5276. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  5277. // Must have an inner operator[]
  5278. if (!innerExpr ||
  5279. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  5280. return false;
  5281. }
  5282. const Expr *innerArg0 =
  5283. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  5284. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  5285. if (!memberExpr)
  5286. return false;
  5287. // Must be accessing the member named "mips" or "sample"
  5288. const auto &memberName =
  5289. memberExpr->getMemberNameInfo().getName().getAsString();
  5290. if (memberName != "mips" && memberName != "sample")
  5291. return false;
  5292. const Expr *object = memberExpr->getBase();
  5293. const auto objectType = object->getType();
  5294. if (!isTexture(objectType))
  5295. return false;
  5296. if (base)
  5297. *base = object;
  5298. if (lod)
  5299. *lod = innerExpr->getArg(1);
  5300. if (location)
  5301. *location = outerExpr->getArg(1);
  5302. return true;
  5303. }
  5304. bool SpirvEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  5305. const Expr **base,
  5306. const Expr **index) {
  5307. if (!indexExpr)
  5308. return false;
  5309. // Must be operator[]
  5310. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  5311. return false;
  5312. const Expr *object = indexExpr->getArg(0);
  5313. const auto objectType = object->getType();
  5314. if (isBuffer(objectType) || isRWBuffer(objectType) || isTexture(objectType) ||
  5315. isRWTexture(objectType)) {
  5316. if (base)
  5317. *base = object;
  5318. if (index)
  5319. *index = indexExpr->getArg(1);
  5320. return true;
  5321. }
  5322. return false;
  5323. }
  5324. void SpirvEmitter::condenseVectorElementExpr(
  5325. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  5326. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  5327. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  5328. *basePtr = expr;
  5329. // Recursively descending until we find the true base vector (the base vector
  5330. // that does not have a base vector). In the meanwhile, collecting accessors
  5331. // in the reverse order.
  5332. // Example: for myVector.yxwz.yxz.xx.yx, the true base is 'myVector'.
  5333. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  5334. accessors.push_back(vecElemBase->getEncodedElementAccess());
  5335. *basePtr = vecElemBase->getBase();
  5336. // We need to skip any number of parentheses around swizzling at any level.
  5337. while (const auto *parenExpr = dyn_cast<ParenExpr>(*basePtr))
  5338. *basePtr = parenExpr->getSubExpr();
  5339. }
  5340. *flattenedAccessor = accessors.back();
  5341. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  5342. const auto &currentAccessor = accessors[i];
  5343. // Apply the current level of accessor to the flattened accessor of all
  5344. // previous levels of ones.
  5345. hlsl::VectorMemberAccessPositions combinedAccessor;
  5346. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  5347. uint32_t currentPosition = 0;
  5348. currentAccessor.GetPosition(j, &currentPosition);
  5349. uint32_t previousPosition = 0;
  5350. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  5351. combinedAccessor.SetPosition(j, previousPosition);
  5352. }
  5353. combinedAccessor.Count = currentAccessor.Count;
  5354. combinedAccessor.IsValid =
  5355. flattenedAccessor->IsValid && currentAccessor.IsValid;
  5356. *flattenedAccessor = combinedAccessor;
  5357. }
  5358. }
  5359. SpirvInstruction *SpirvEmitter::createVectorSplat(const Expr *scalarExpr,
  5360. uint32_t size) {
  5361. SpirvInstruction *scalarVal = nullptr;
  5362. // Try to evaluate the element as constant first. If successful, then we
  5363. // can generate constant instructions for this vector splat.
  5364. if ((scalarVal = tryToEvaluateAsConst(scalarExpr))) {
  5365. scalarVal->setRValue();
  5366. } else {
  5367. scalarVal = loadIfGLValue(scalarExpr);
  5368. }
  5369. if (!scalarVal || size == 1) {
  5370. // Just return the scalar value for vector splat with size 1.
  5371. // Note that can be used as an lvalue, so we need to carry over
  5372. // the lvalueness for non-constant cases.
  5373. return scalarVal;
  5374. }
  5375. const auto vecType = astContext.getExtVectorType(scalarExpr->getType(), size);
  5376. // TODO: we are saying the constant has Function storage class here.
  5377. // Should find a more meaningful one.
  5378. if (auto *constVal = dyn_cast<SpirvConstant>(scalarVal)) {
  5379. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), constVal);
  5380. auto *value = spvBuilder.getConstantComposite(vecType, elements);
  5381. value->setRValue();
  5382. return value;
  5383. } else {
  5384. llvm::SmallVector<SpirvInstruction *, 4> elements(size_t(size), scalarVal);
  5385. auto *value = spvBuilder.createCompositeConstruct(
  5386. vecType, elements, scalarExpr->getLocStart());
  5387. value->setRValue();
  5388. return value;
  5389. }
  5390. }
  5391. void SpirvEmitter::splitVecLastElement(QualType vecType, SpirvInstruction *vec,
  5392. SpirvInstruction **residual,
  5393. SpirvInstruction **lastElement,
  5394. SourceLocation loc) {
  5395. assert(hlsl::IsHLSLVecType(vecType));
  5396. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  5397. assert(count > 1);
  5398. const QualType elemType = hlsl::GetHLSLVecElementType(vecType);
  5399. if (count == 2) {
  5400. *residual = spvBuilder.createCompositeExtract(elemType, vec, 0, loc);
  5401. } else {
  5402. llvm::SmallVector<uint32_t, 4> indices;
  5403. for (uint32_t i = 0; i < count - 1; ++i)
  5404. indices.push_back(i);
  5405. const QualType type = astContext.getExtVectorType(elemType, count - 1);
  5406. *residual = spvBuilder.createVectorShuffle(type, vec, vec, indices, loc);
  5407. }
  5408. *lastElement =
  5409. spvBuilder.createCompositeExtract(elemType, vec, {count - 1}, loc);
  5410. }
  5411. SpirvInstruction *SpirvEmitter::convertVectorToStruct(QualType structType,
  5412. QualType elemType,
  5413. SpirvInstruction *vector,
  5414. SourceLocation loc) {
  5415. assert(structType->isStructureType());
  5416. const auto *structDecl = structType->getAsStructureType()->getDecl();
  5417. uint32_t vectorIndex = 0;
  5418. uint32_t elemCount = 1;
  5419. llvm::SmallVector<SpirvInstruction *, 4> members;
  5420. for (const auto *field : structDecl->fields()) {
  5421. if (isScalarType(field->getType())) {
  5422. members.push_back(spvBuilder.createCompositeExtract(
  5423. elemType, vector, {vectorIndex++}, loc));
  5424. } else if (isVectorType(field->getType(), nullptr, &elemCount)) {
  5425. llvm::SmallVector<uint32_t, 4> indices;
  5426. for (uint32_t i = 0; i < elemCount; ++i)
  5427. indices.push_back(vectorIndex++);
  5428. members.push_back(spvBuilder.createVectorShuffle(
  5429. astContext.getExtVectorType(elemType, elemCount), vector, vector,
  5430. indices, loc));
  5431. } else {
  5432. assert(false && "unhandled type");
  5433. }
  5434. }
  5435. return spvBuilder.createCompositeConstruct(structType, members,
  5436. vector->getSourceLocation());
  5437. }
  5438. SpirvInstruction *
  5439. SpirvEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  5440. const QualType type = expr->getType();
  5441. const SourceRange range = expr->getSourceRange();
  5442. QualType elemType = {};
  5443. // We can only translate floatN * float into OpVectorTimesScalar.
  5444. // So the result type must be floatN. Note that float1 is not a valid vector
  5445. // in SPIR-V.
  5446. if (!(isVectorType(type, &elemType) && elemType->isFloatingType()))
  5447. return nullptr;
  5448. const Expr *lhs = expr->getLHS();
  5449. const Expr *rhs = expr->getRHS();
  5450. // Multiplying a float vector with a float scalar will be represented in
  5451. // AST via a binary operation with two float vectors as operands; one of
  5452. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  5453. // vector * scalar
  5454. if (hlsl::IsHLSLVecType(lhs->getType())) {
  5455. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5456. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5457. const QualType vecType = expr->getType();
  5458. if (const auto *compoundAssignExpr =
  5459. dyn_cast<CompoundAssignOperator>(expr)) {
  5460. const auto computationType =
  5461. compoundAssignExpr->getComputationLHSType();
  5462. SpirvInstruction *lhsPtr = nullptr;
  5463. auto *result = processBinaryOp(lhs, cast->getSubExpr(),
  5464. expr->getOpcode(), computationType,
  5465. vecType, range, expr->getOperatorLoc(),
  5466. &lhsPtr, spv::Op::OpVectorTimesScalar);
  5467. return processAssignment(lhs, result, true, lhsPtr);
  5468. } else {
  5469. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5470. vecType, vecType, range,
  5471. expr->getOperatorLoc(), nullptr,
  5472. spv::Op::OpVectorTimesScalar);
  5473. }
  5474. }
  5475. }
  5476. }
  5477. // scalar * vector
  5478. if (hlsl::IsHLSLVecType(rhs->getType())) {
  5479. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5480. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5481. const QualType vecType = expr->getType();
  5482. // We need to switch the positions of lhs and rhs here because
  5483. // OpVectorTimesScalar requires the first operand to be a vector and
  5484. // the second to be a scalar.
  5485. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5486. vecType, vecType, range, expr->getOperatorLoc(),
  5487. nullptr, spv::Op::OpVectorTimesScalar);
  5488. }
  5489. }
  5490. }
  5491. return nullptr;
  5492. }
  5493. SpirvInstruction *
  5494. SpirvEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  5495. const QualType type = expr->getType();
  5496. const SourceRange range = expr->getSourceRange();
  5497. // We translate 'floatMxN * float' into OpMatrixTimesScalar.
  5498. // We translate 'floatMx1 * float' and 'float1xN * float' using
  5499. // OpVectorTimesScalar.
  5500. // So the result type can be floatMxN, floatMx1, or float1xN.
  5501. if (!hlsl::IsHLSLMatType(type) ||
  5502. !hlsl::GetHLSLMatElementType(type)->isFloatingType() || is1x1Matrix(type))
  5503. return 0;
  5504. const Expr *lhs = expr->getLHS();
  5505. const Expr *rhs = expr->getRHS();
  5506. const QualType lhsType = lhs->getType();
  5507. const QualType rhsType = rhs->getType();
  5508. const auto selectOpcode = [](const QualType ty) {
  5509. return isMx1Matrix(ty) || is1xNMatrix(ty) ? spv::Op::OpVectorTimesScalar
  5510. : spv::Op::OpMatrixTimesScalar;
  5511. };
  5512. // Multiplying a float matrix with a float scalar will be represented in
  5513. // AST via a binary operation with two float matrices as operands; one of
  5514. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  5515. // matrix * scalar
  5516. if (hlsl::IsHLSLMatType(lhsType)) {
  5517. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5518. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5519. const QualType matType = expr->getType();
  5520. const spv::Op opcode = selectOpcode(lhsType);
  5521. if (const auto *compoundAssignExpr =
  5522. dyn_cast<CompoundAssignOperator>(expr)) {
  5523. const auto computationType =
  5524. compoundAssignExpr->getComputationLHSType();
  5525. SpirvInstruction *lhsPtr = nullptr;
  5526. auto *result = processBinaryOp(
  5527. lhs, cast->getSubExpr(), expr->getOpcode(), computationType,
  5528. matType, range, expr->getOperatorLoc(), &lhsPtr, opcode);
  5529. return processAssignment(lhs, result, true, lhsPtr);
  5530. } else {
  5531. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5532. matType, matType, range,
  5533. expr->getOperatorLoc(), nullptr, opcode);
  5534. }
  5535. }
  5536. }
  5537. }
  5538. // scalar * matrix
  5539. if (hlsl::IsHLSLMatType(rhsType)) {
  5540. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5541. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5542. const QualType matType = expr->getType();
  5543. const spv::Op opcode = selectOpcode(rhsType);
  5544. // We need to switch the positions of lhs and rhs here because
  5545. // OpMatrixTimesScalar requires the first operand to be a matrix and
  5546. // the second to be a scalar.
  5547. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5548. matType, matType, range, expr->getOperatorLoc(),
  5549. nullptr, opcode);
  5550. }
  5551. }
  5552. }
  5553. return nullptr;
  5554. }
  5555. SpirvInstruction *
  5556. SpirvEmitter::tryToAssignToVectorElements(const Expr *lhs,
  5557. SpirvInstruction *rhs) {
  5558. // Assigning to a vector swizzling lhs is tricky if we are neither
  5559. // writing to one element nor all elements in their original order.
  5560. // Under such cases, we need to create a new vector swizzling involving
  5561. // both the lhs and rhs vectors and then write the result of this swizzling
  5562. // into the base vector of lhs.
  5563. // For example, for vec4.yz = vec2, we nee to do the following:
  5564. //
  5565. // %vec4Val = OpLoad %v4float %vec4
  5566. // %vec2Val = OpLoad %v2float %vec2
  5567. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  5568. // OpStore %vec4 %shuffle
  5569. //
  5570. // When doing the vector shuffle, we use the lhs base vector as the first
  5571. // vector and the rhs vector as the second vector. Therefore, all elements
  5572. // in the second vector will be selected into the shuffle result.
  5573. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  5574. if (!lhsExpr)
  5575. return 0;
  5576. // Special case for <scalar-value>.x, which will have an AST of
  5577. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  5578. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  5579. // for such case.
  5580. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  5581. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  5582. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  5583. return processAssignment(baseCast->getSubExpr(), rhs, false);
  5584. const Expr *base = nullptr;
  5585. hlsl::VectorMemberAccessPositions accessor;
  5586. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  5587. const QualType baseType = base->getType();
  5588. assert(hlsl::IsHLSLVecType(baseType));
  5589. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  5590. const auto accessorSize = accessor.Count;
  5591. // Whether selecting the whole original vector
  5592. bool isSelectOrigin = accessorSize == baseSize;
  5593. // Assigning to one component
  5594. if (accessorSize == 1) {
  5595. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  5596. // Assigning to one component of a RWBuffer/RWTexture element
  5597. // We need to use OpImageWrite here.
  5598. // Compose the new vector value first
  5599. auto *oldVec = doExpr(base);
  5600. auto *newVec = spvBuilder.createCompositeInsert(
  5601. baseType, oldVec, {accessor.Swz0}, rhs, lhs->getLocStart());
  5602. auto *result = tryToAssignToRWBufferRWTexture(base, newVec);
  5603. assert(result); // Definitely RWBuffer/RWTexture assignment
  5604. (void)result;
  5605. return rhs; // TODO: incorrect for compound assignments
  5606. } else {
  5607. // Assigning to one component of mesh out attribute/indices vector object.
  5608. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5609. astContext.UnsignedIntTy, llvm::APInt(32, accessor.Swz0));
  5610. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, vecComponent))
  5611. return rhs;
  5612. // Assigning to one normal vector component. Nothing special, just fall
  5613. // back to the normal CodeGen path.
  5614. return nullptr;
  5615. }
  5616. }
  5617. if (isSelectOrigin) {
  5618. for (uint32_t i = 0; i < accessorSize; ++i) {
  5619. uint32_t position;
  5620. accessor.GetPosition(i, &position);
  5621. if (position != i)
  5622. isSelectOrigin = false;
  5623. }
  5624. }
  5625. // Assigning to the original vector
  5626. if (isSelectOrigin) {
  5627. // Ignore this HLSLVectorElementExpr and dispatch to base
  5628. return processAssignment(base, rhs, false);
  5629. }
  5630. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, /*vecComponent=*/nullptr,
  5631. /*noWriteBack=*/true)) {
  5632. // Assigning to 'n' components of mesh out attribute/indices vector object.
  5633. const QualType elemType =
  5634. hlsl::GetHLSLVecElementType(rhs->getAstResultType());
  5635. uint32_t i = 0;
  5636. for (; i < accessor.Count; ++i) {
  5637. auto *rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5638. lhs->getLocStart());
  5639. uint32_t position;
  5640. accessor.GetPosition(i, &position);
  5641. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5642. astContext.UnsignedIntTy, llvm::APInt(32, position));
  5643. if (!tryToAssignToMSOutAttrsOrIndices(base, rhsElem, vecComponent))
  5644. break;
  5645. }
  5646. assert(i == accessor.Count);
  5647. return rhs;
  5648. }
  5649. llvm::SmallVector<uint32_t, 4> selectors;
  5650. selectors.resize(baseSize);
  5651. // Assume we are selecting all original elements first.
  5652. for (uint32_t i = 0; i < baseSize; ++i) {
  5653. selectors[i] = i;
  5654. }
  5655. // Now fix up the elements that actually got overwritten by the rhs vector.
  5656. // Since we are using the rhs vector as the second vector, their index
  5657. // should be offset'ed by the size of the lhs base vector.
  5658. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5659. uint32_t position;
  5660. accessor.GetPosition(i, &position);
  5661. selectors[position] = baseSize + i;
  5662. }
  5663. auto *vec1 = doExpr(base);
  5664. auto *vec1Val = vec1->isRValue() ? vec1
  5665. : spvBuilder.createLoad(baseType, vec1,
  5666. base->getLocStart());
  5667. auto *shuffle = spvBuilder.createVectorShuffle(baseType, vec1Val, rhs,
  5668. selectors, lhs->getLocStart());
  5669. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  5670. spvBuilder.createStore(vec1, shuffle, lhs->getLocStart());
  5671. // TODO: OK, this return value is incorrect for compound assignments, for
  5672. // which cases we should return lvalues. Should at least emit errors if
  5673. // this return value is used (can be checked via ASTContext.getParents).
  5674. return rhs;
  5675. }
  5676. SpirvInstruction *
  5677. SpirvEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  5678. SpirvInstruction *rhs) {
  5679. const Expr *baseExpr = nullptr;
  5680. const Expr *indexExpr = nullptr;
  5681. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  5682. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  5683. auto *loc = doExpr(indexExpr);
  5684. const QualType imageType = baseExpr->getType();
  5685. auto *baseInfo = doExpr(baseExpr);
  5686. auto *image =
  5687. spvBuilder.createLoad(imageType, baseInfo, baseExpr->getExprLoc());
  5688. spvBuilder.createImageWrite(imageType, image, loc, rhs, lhs->getExprLoc());
  5689. return rhs;
  5690. }
  5691. return nullptr;
  5692. }
  5693. SpirvInstruction *
  5694. SpirvEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  5695. SpirvInstruction *rhs) {
  5696. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  5697. if (!lhsExpr)
  5698. return nullptr;
  5699. const Expr *baseMat = lhsExpr->getBase();
  5700. auto *base = doExpr(baseMat);
  5701. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  5702. uint32_t rowCount = 0, colCount = 0;
  5703. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  5704. // For each lhs element written to:
  5705. // 1. Extract the corresponding rhs element using OpCompositeExtract
  5706. // 2. Create access chain for the lhs element using OpAccessChain
  5707. // 3. Write using OpStore
  5708. const auto accessor = lhsExpr->getEncodedElementAccess();
  5709. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5710. uint32_t row = 0, col = 0;
  5711. accessor.GetPosition(i, &row, &col);
  5712. llvm::SmallVector<uint32_t, 2> indices;
  5713. // If the matrix only have one row/column, we are indexing into a vector
  5714. // then. Only one index is needed for such cases.
  5715. if (rowCount > 1)
  5716. indices.push_back(row);
  5717. if (colCount > 1)
  5718. indices.push_back(col);
  5719. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  5720. nullptr);
  5721. for (uint32_t i = 0; i < indices.size(); ++i)
  5722. indexInstructions[i] = spvBuilder.getConstantInt(
  5723. astContext.IntTy, llvm::APInt(32, indices[i], true));
  5724. // If we are writing to only one element, the rhs should already be a
  5725. // scalar value.
  5726. auto *rhsElem = rhs;
  5727. if (accessor.Count > 1) {
  5728. rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5729. rhs->getSourceLocation());
  5730. }
  5731. // If the lhs is actually a matrix of size 1x1, we don't need the access
  5732. // chain. base is already the dest pointer.
  5733. auto *lhsElemPtr = base;
  5734. if (!indexInstructions.empty()) {
  5735. assert(!base->isRValue());
  5736. // Load the element via access chain
  5737. lhsElemPtr = spvBuilder.createAccessChain(
  5738. elemType, lhsElemPtr, indexInstructions, lhs->getLocStart());
  5739. }
  5740. spvBuilder.createStore(lhsElemPtr, rhsElem, lhs->getLocStart());
  5741. }
  5742. // TODO: OK, this return value is incorrect for compound assignments, for
  5743. // which cases we should return lvalues. Should at least emit errors if
  5744. // this return value is used (can be checked via ASTContext.getParents).
  5745. return rhs;
  5746. }
  5747. SpirvInstruction *SpirvEmitter::tryToAssignToMSOutAttrsOrIndices(
  5748. const Expr *lhs, SpirvInstruction *rhs, SpirvInstruction *vecComponent,
  5749. bool noWriteBack) {
  5750. // Early exit for non-mesh shaders.
  5751. if (!spvContext.isMS())
  5752. return nullptr;
  5753. llvm::SmallVector<SpirvInstruction *, 4> indices;
  5754. bool isMSOutAttribute = false;
  5755. bool isMSOutAttributeBlock = false;
  5756. bool isMSOutIndices = false;
  5757. const Expr *base = collectArrayStructIndices(lhs, /*rawIndex*/ false,
  5758. /*rawIndices*/ nullptr, &indices,
  5759. &isMSOutAttribute);
  5760. // Expecting at least one array index - early exit.
  5761. if (!base || indices.empty())
  5762. return nullptr;
  5763. const DeclaratorDecl *varDecl = nullptr;
  5764. if (isMSOutAttribute) {
  5765. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(base);
  5766. assert(memberExpr);
  5767. varDecl = cast<DeclaratorDecl>(memberExpr->getMemberDecl());
  5768. } else {
  5769. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  5770. if ((varDecl = dyn_cast<DeclaratorDecl>(arg->getDecl()))) {
  5771. if (varDecl->hasAttr<HLSLIndicesAttr>()) {
  5772. isMSOutIndices = true;
  5773. } else if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  5774. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  5775. isMSOutAttributeBlock = true;
  5776. }
  5777. }
  5778. }
  5779. }
  5780. // Return if no out attribute or indices object found.
  5781. if (!(isMSOutAttribute || isMSOutAttributeBlock || isMSOutIndices)) {
  5782. return nullptr;
  5783. }
  5784. // For noWriteBack, return without generating write instructions.
  5785. if (noWriteBack) {
  5786. return rhs;
  5787. }
  5788. // Add vecComponent to indices.
  5789. if (vecComponent) {
  5790. indices.push_back(vecComponent);
  5791. }
  5792. if (isMSOutAttribute) {
  5793. assignToMSOutAttribute(varDecl, rhs, indices);
  5794. } else if (isMSOutIndices) {
  5795. assignToMSOutIndices(varDecl, rhs, indices);
  5796. } else {
  5797. assert(isMSOutAttributeBlock);
  5798. QualType type = varDecl->getType();
  5799. assert(isa<ConstantArrayType>(type));
  5800. type = astContext.getAsConstantArrayType(type)->getElementType();
  5801. assert(type->isStructureType());
  5802. // Extract subvalue and assign to its corresponding member attribute.
  5803. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  5804. for (const auto *field : structDecl->fields()) {
  5805. const auto fieldType = field->getType();
  5806. SpirvInstruction *subValue = spvBuilder.createCompositeExtract(
  5807. fieldType, rhs, {getNumBaseClasses(type) + field->getFieldIndex()},
  5808. lhs->getLocStart());
  5809. assignToMSOutAttribute(field, subValue, indices);
  5810. }
  5811. }
  5812. // TODO: OK, this return value is incorrect for compound assignments, for
  5813. // which cases we should return lvalues. Should at least emit errors if
  5814. // this return value is used (can be checked via ASTContext.getParents).
  5815. return rhs;
  5816. }
  5817. void SpirvEmitter::assignToMSOutAttribute(
  5818. const DeclaratorDecl *decl, SpirvInstruction *value,
  5819. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5820. assert(spvContext.isMS() && !indices.empty());
  5821. // Extract attribute index and vecComponent (if any).
  5822. SpirvInstruction *attrIndex = indices.front();
  5823. SpirvInstruction *vecComponent = nullptr;
  5824. if (indices.size() > 1) {
  5825. vecComponent = indices.back();
  5826. }
  5827. auto semanticInfo = declIdMapper.getStageVarSemantic(decl);
  5828. assert(semanticInfo.isValid());
  5829. const auto loc = decl->getLocation();
  5830. // Special handle writes to clip/cull distance attributes.
  5831. if (!declIdMapper.glPerVertex.tryToAccess(
  5832. hlsl::DXIL::SigPointKind::MSOut, semanticInfo.semantic->GetKind(),
  5833. semanticInfo.index, attrIndex, &value, /*noWriteBack=*/false,
  5834. vecComponent, loc)) {
  5835. // All other attribute writes are handled below.
  5836. auto *varInstr = declIdMapper.getStageVarInstruction(decl);
  5837. QualType valueType = value->getAstResultType();
  5838. varInstr = spvBuilder.createAccessChain(valueType, varInstr, indices, loc);
  5839. spvBuilder.createStore(varInstr, value, loc);
  5840. }
  5841. }
  5842. void SpirvEmitter::assignToMSOutIndices(
  5843. const DeclaratorDecl *decl, SpirvInstruction *value,
  5844. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5845. assert(spvContext.isMS() && !indices.empty());
  5846. // Extract vertex index and vecComponent (if any).
  5847. SpirvInstruction *vertIndex = indices.front();
  5848. SpirvInstruction *vecComponent = nullptr;
  5849. if (indices.size() > 1) {
  5850. vecComponent = indices.back();
  5851. }
  5852. auto *var = declIdMapper.getStageVarInstruction(decl);
  5853. const auto *varTypeDecl = astContext.getAsConstantArrayType(decl->getType());
  5854. QualType varType = varTypeDecl->getElementType();
  5855. uint32_t numVertices = 1;
  5856. if (!isVectorType(varType, nullptr, &numVertices)) {
  5857. assert(isScalarType(varType));
  5858. }
  5859. QualType valueType = value->getAstResultType();
  5860. uint32_t numValues = 1;
  5861. if (!isVectorType(valueType, nullptr, &numValues)) {
  5862. assert(isScalarType(valueType));
  5863. }
  5864. const auto loc = decl->getLocation();
  5865. if (numVertices == 1) {
  5866. // for "point" output topology.
  5867. assert(numValues == 1);
  5868. // create accesschain for PrimitiveIndicesNV[vertIndex].
  5869. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5870. {vertIndex}, loc);
  5871. // finally create store for PrimitiveIndicesNV[vertIndex] = value.
  5872. spvBuilder.createStore(ptr, value, loc);
  5873. } else {
  5874. // for "line" or "triangle" output topology.
  5875. assert(numVertices == 2 || numVertices == 3);
  5876. // set baseOffset = vertIndex * numVertices.
  5877. auto *baseOffset = spvBuilder.createBinaryOp(
  5878. spv::Op::OpIMul, astContext.UnsignedIntTy, vertIndex,
  5879. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5880. llvm::APInt(32, numVertices)),
  5881. loc);
  5882. if (vecComponent) {
  5883. // write an individual vector component of uint2 or uint3.
  5884. assert(numValues == 1);
  5885. // set baseOffset = baseOffset + vecComponent.
  5886. baseOffset =
  5887. spvBuilder.createBinaryOp(spv::Op::OpIAdd, astContext.UnsignedIntTy,
  5888. baseOffset, vecComponent, loc);
  5889. // create accesschain for PrimitiveIndicesNV[baseOffset].
  5890. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5891. {baseOffset}, loc);
  5892. // finally create store for PrimitiveIndicesNV[baseOffset] = value.
  5893. spvBuilder.createStore(ptr, value, loc);
  5894. } else {
  5895. // write all vector components of uint2 or uint3.
  5896. assert(numValues == numVertices);
  5897. auto *curOffset = baseOffset;
  5898. for (uint32_t i = 0; i < numValues; ++i) {
  5899. if (i != 0) {
  5900. // set curOffset = baseOffset + i.
  5901. curOffset = spvBuilder.createBinaryOp(
  5902. spv::Op::OpIAdd, astContext.UnsignedIntTy, baseOffset,
  5903. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5904. llvm::APInt(32, i)),
  5905. loc);
  5906. }
  5907. // create accesschain for PrimitiveIndicesNV[curOffset].
  5908. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5909. {curOffset}, loc);
  5910. // finally create store for PrimitiveIndicesNV[curOffset] = value[i].
  5911. spvBuilder.createStore(ptr,
  5912. spvBuilder.createCompositeExtract(
  5913. astContext.UnsignedIntTy, value, {i}, loc),
  5914. loc);
  5915. }
  5916. }
  5917. }
  5918. }
  5919. SpirvInstruction *SpirvEmitter::processEachVectorInMatrix(
  5920. const Expr *matrix, SpirvInstruction *matrixVal,
  5921. llvm::function_ref<SpirvInstruction *(uint32_t, QualType,
  5922. SpirvInstruction *)>
  5923. actOnEachVector,
  5924. SourceLocation loc) {
  5925. const auto matType = matrix->getType();
  5926. assert(isMxNMatrix(matType));
  5927. const QualType vecType = getComponentVectorType(astContext, matType);
  5928. uint32_t rowCount = 0, colCount = 0;
  5929. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  5930. llvm::SmallVector<SpirvInstruction *, 4> vectors;
  5931. // Extract each component vector and do operation on it
  5932. for (uint32_t i = 0; i < rowCount; ++i) {
  5933. auto *lhsVec = spvBuilder.createCompositeExtract(vecType, matrixVal, {i},
  5934. matrix->getLocStart());
  5935. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  5936. }
  5937. // Construct the result matrix
  5938. auto *val = spvBuilder.createCompositeConstruct(matType, vectors, loc);
  5939. val->setRValue();
  5940. return val;
  5941. }
  5942. void SpirvEmitter::createSpecConstant(const VarDecl *varDecl) {
  5943. class SpecConstantEnvRAII {
  5944. public:
  5945. // Creates a new instance which sets mode to true on creation,
  5946. // and resets mode to false on destruction.
  5947. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  5948. ~SpecConstantEnvRAII() { *modeSlot = false; }
  5949. private:
  5950. bool *modeSlot;
  5951. };
  5952. const QualType varType = varDecl->getType();
  5953. bool hasError = false;
  5954. if (!varDecl->isExternallyVisible()) {
  5955. emitError("specialization constant must be externally visible",
  5956. varDecl->getLocation());
  5957. hasError = true;
  5958. }
  5959. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5960. switch (builtinType->getKind()) {
  5961. case BuiltinType::Bool:
  5962. case BuiltinType::Int:
  5963. case BuiltinType::UInt:
  5964. case BuiltinType::Float:
  5965. break;
  5966. default:
  5967. emitError("unsupported specialization constant type",
  5968. varDecl->getLocStart());
  5969. hasError = true;
  5970. }
  5971. }
  5972. const auto *init = varDecl->getInit();
  5973. if (!init) {
  5974. emitError("missing default value for specialization constant",
  5975. varDecl->getLocation());
  5976. hasError = true;
  5977. } else if (!isAcceptedSpecConstantInit(init)) {
  5978. emitError("unsupported specialization constant initializer",
  5979. init->getLocStart())
  5980. << init->getSourceRange();
  5981. hasError = true;
  5982. }
  5983. if (hasError)
  5984. return;
  5985. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5986. const auto specConstant = doExpr(init);
  5987. // We are not creating a variable to hold the spec constant, instead, we
  5988. // translate the varDecl directly into the spec constant here.
  5989. spvBuilder.decorateSpecId(
  5990. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId(),
  5991. varDecl->getLocation());
  5992. specConstant->setDebugName(varDecl->getName());
  5993. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5994. }
  5995. SpirvInstruction *
  5996. SpirvEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5997. const BinaryOperatorKind opcode,
  5998. SourceRange range, SourceLocation loc) {
  5999. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  6000. const auto lhsType = lhs->getType();
  6001. assert(isMxNMatrix(lhsType));
  6002. const spv::Op spvOp = translateOp(opcode, lhsType);
  6003. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  6004. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  6005. // Evalute rhs before lhs
  6006. rhsVal = doExpr(rhs);
  6007. lhsPtr = doExpr(lhs);
  6008. lhsVal = spvBuilder.createLoad(lhsType, lhsPtr, lhs->getLocStart());
  6009. } else {
  6010. // Evalute lhs before rhs
  6011. lhsVal = lhsPtr = doExpr(lhs);
  6012. rhsVal = doExpr(rhs);
  6013. }
  6014. switch (opcode) {
  6015. case BO_Add:
  6016. case BO_Sub:
  6017. case BO_Mul:
  6018. case BO_Div:
  6019. case BO_Rem:
  6020. case BO_AddAssign:
  6021. case BO_SubAssign:
  6022. case BO_MulAssign:
  6023. case BO_DivAssign:
  6024. case BO_RemAssign: {
  6025. const auto actOnEachVec = [this, spvOp, rhsVal, rhs,
  6026. loc](uint32_t index, QualType vecType,
  6027. SpirvInstruction *lhsVec) {
  6028. // For each vector of lhs, we need to load the corresponding vector of
  6029. // rhs and do the operation on them.
  6030. auto *rhsVec = spvBuilder.createCompositeExtract(vecType, rhsVal, {index},
  6031. rhs->getLocStart());
  6032. auto *val =
  6033. spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec, loc);
  6034. val->setRValue();
  6035. return val;
  6036. };
  6037. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec,
  6038. lhs->getLocStart());
  6039. }
  6040. case BO_Assign:
  6041. llvm_unreachable("assignment should not be handled here");
  6042. default:
  6043. break;
  6044. }
  6045. emitError("binary operator '%0' over matrix type unimplemented",
  6046. lhs->getExprLoc())
  6047. << BinaryOperator::getOpcodeStr(opcode) << range;
  6048. return nullptr;
  6049. }
  6050. const Expr *SpirvEmitter::collectArrayStructIndices(
  6051. const Expr *expr, bool rawIndex,
  6052. llvm::SmallVectorImpl<uint32_t> *rawIndices,
  6053. llvm::SmallVectorImpl<SpirvInstruction *> *indices,
  6054. bool *isMSOutAttribute) {
  6055. assert((rawIndex && rawIndices) || (!rawIndex && indices));
  6056. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  6057. // First check whether this is referring to a static member. If it is, we
  6058. // create a DeclRefExpr for it.
  6059. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  6060. if (varDecl->isStaticDataMember())
  6061. return DeclRefExpr::Create(
  6062. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  6063. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  6064. varDecl->getType(), VK_LValue);
  6065. const Expr *base = collectArrayStructIndices(
  6066. indexing->getBase(), rawIndex, rawIndices, indices, isMSOutAttribute);
  6067. if (isMSOutAttribute && base) {
  6068. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  6069. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  6070. if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  6071. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  6072. assert(spvContext.isMS());
  6073. *isMSOutAttribute = true;
  6074. return expr;
  6075. }
  6076. }
  6077. }
  6078. }
  6079. // Append the index of the current level
  6080. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  6081. assert(fieldDecl);
  6082. // If we are accessing a derived struct, we need to account for the number
  6083. // of base structs, since they are placed as fields at the beginning of the
  6084. // derived struct.
  6085. auto baseType = indexing->getBase()->getType();
  6086. if (baseType->isPointerType()) {
  6087. baseType = baseType->getPointeeType();
  6088. }
  6089. const uint32_t index =
  6090. getNumBaseClasses(baseType) + fieldDecl->getFieldIndex();
  6091. if (rawIndex) {
  6092. rawIndices->push_back(index);
  6093. } else {
  6094. indices->push_back(spvBuilder.getConstantInt(
  6095. astContext.IntTy, llvm::APInt(32, index, true)));
  6096. }
  6097. return base;
  6098. }
  6099. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  6100. if (rawIndex)
  6101. return nullptr; // TODO: handle constant array index
  6102. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  6103. // cast. We need to ingore it to avoid creating OpLoad.
  6104. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  6105. const Expr *base = collectArrayStructIndices(thisBase, rawIndex, rawIndices,
  6106. indices, isMSOutAttribute);
  6107. // The index into an array must be an integer number.
  6108. const auto *idxExpr = indexing->getIdx();
  6109. const auto idxExprType = idxExpr->getType();
  6110. if (idxExpr->isLValue()) {
  6111. // If the given HLSL code is correct, this case will not happen, because
  6112. // the correct HLSL code will not use LValue for the index of an array.
  6113. emitError("Index of ArraySubscriptExpr must be rvalue",
  6114. idxExpr->getExprLoc());
  6115. return nullptr;
  6116. }
  6117. // Since `doExpr(idxExpr)` can generate LValue SPIR-V instruction for
  6118. // RValue `idxExpr` (see
  6119. // https://github.com/microsoft/DirectXShaderCompiler/issues/3620),
  6120. // we have to use `loadIfGLValue(idxExpr)` instead of `doExpr(idxExpr)`.
  6121. SpirvInstruction *thisIndex = loadIfGLValue(idxExpr);
  6122. if (!idxExprType->isIntegerType() || idxExprType->isBooleanType()) {
  6123. thisIndex = castToInt(thisIndex, idxExprType, astContext.UnsignedIntTy,
  6124. idxExpr->getExprLoc());
  6125. }
  6126. indices->push_back(thisIndex);
  6127. return base;
  6128. }
  6129. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  6130. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  6131. if (rawIndex)
  6132. return nullptr; // TODO: handle constant array index
  6133. // If this is indexing into resources, we need specific OpImage*
  6134. // instructions for accessing. Return directly to avoid further building
  6135. // up the access chain.
  6136. if (isBufferTextureIndexing(indexing))
  6137. return indexing;
  6138. const Expr *thisBase =
  6139. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  6140. const auto thisBaseType = thisBase->getType();
  6141. const Expr *base = collectArrayStructIndices(
  6142. thisBase, rawIndex, rawIndices, indices, isMSOutAttribute);
  6143. if (thisBaseType != base->getType() &&
  6144. isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  6145. // The immediate base is a kind of structured or byte buffer. It should
  6146. // be an alias variable. Break the normal index collecting chain.
  6147. // Return the immediate base as the base so that we can apply other
  6148. // hacks for legalization over it.
  6149. //
  6150. // Note: legalization specific code
  6151. indices->clear();
  6152. base = thisBase;
  6153. }
  6154. // If the base is a StructureType, we need to push an addtional index 0
  6155. // here. This is because we created an additional OpTypeRuntimeArray
  6156. // in the structure.
  6157. if (isStructuredBuffer(thisBaseType))
  6158. indices->push_back(
  6159. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  6160. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  6161. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  6162. is1x1Matrix(thisBaseType) || is1xNMatrix(thisBaseType)) {
  6163. // If this is a size-1 vector or 1xN matrix, ignore the index.
  6164. } else {
  6165. indices->push_back(doExpr(indexing->getArg(1)));
  6166. }
  6167. return base;
  6168. }
  6169. {
  6170. const Expr *index = nullptr;
  6171. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  6172. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  6173. if (rawIndex)
  6174. return nullptr; // TODO: handle constant array index
  6175. // For object.Load(index), there should be no more indexing into the
  6176. // object.
  6177. indices->push_back(
  6178. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  6179. indices->push_back(doExpr(index));
  6180. return object;
  6181. }
  6182. }
  6183. {
  6184. // Indexing into ConstantBuffers and TextureBuffers involves an additional
  6185. // FlatConversion node which casts the handle to the underlying structure
  6186. // type. We can look past the FlatConversion to continue to collect indices.
  6187. // For example: MyConstantBufferArray[0].structMember1
  6188. // `-MemberExpr .structMember1
  6189. // `-ImplicitCastExpr 'const T' lvalue <FlatConversion>
  6190. // `-ArraySubscriptExpr 'ConstantBuffer<T>':'ConstantBuffer<T>' lvalue
  6191. if (auto *castExpr = dyn_cast<ImplicitCastExpr>(expr)) {
  6192. if (castExpr->getCastKind() == CK_FlatConversion) {
  6193. const auto *subExpr = castExpr->getSubExpr();
  6194. const QualType subExprType = subExpr->getType();
  6195. if (isConstantTextureBuffer(subExprType)) {
  6196. return collectArrayStructIndices(subExpr, rawIndex, rawIndices,
  6197. indices, isMSOutAttribute);
  6198. }
  6199. }
  6200. }
  6201. }
  6202. // This the deepest we can go. No more array or struct indexing.
  6203. return expr;
  6204. }
  6205. SpirvInstruction *SpirvEmitter::turnIntoElementPtr(
  6206. QualType baseType, SpirvInstruction *base, QualType elemType,
  6207. const llvm::SmallVector<SpirvInstruction *, 4> &indices,
  6208. SourceLocation loc) {
  6209. // If this is a rvalue, we need a temporary object to hold it
  6210. // so that we can get access chain from it.
  6211. const bool needTempVar = base->isRValue();
  6212. SpirvInstruction *accessChainBase = base;
  6213. if (needTempVar) {
  6214. auto varName = getAstTypeName(baseType);
  6215. const auto var = createTemporaryVar(baseType, varName, base, loc);
  6216. var->setLayoutRule(SpirvLayoutRule::Void);
  6217. var->setStorageClass(spv::StorageClass::Function);
  6218. var->setContainsAliasComponent(base->containsAliasComponent());
  6219. accessChainBase = var;
  6220. }
  6221. base = spvBuilder.createAccessChain(elemType, accessChainBase, indices, loc);
  6222. // Okay, this part seems weird, but it is intended:
  6223. // If the base is originally a rvalue, the whole AST involving the base
  6224. // is consistently set up to handle rvalues. By copying the base into
  6225. // a temporary variable and grab an access chain from it, we are breaking
  6226. // the consistency by turning the base from rvalue into lvalue. Keep in
  6227. // mind that there will be no LValueToRValue casts in the AST for us
  6228. // to rely on to load the access chain if a rvalue is expected. Therefore,
  6229. // we must do the load here. Otherwise, it's up to the consumer of this
  6230. // access chain to do the load, and that can be everywhere.
  6231. if (needTempVar) {
  6232. base = spvBuilder.createLoad(elemType, base, loc);
  6233. }
  6234. return base;
  6235. }
  6236. SpirvInstruction *SpirvEmitter::castToBool(SpirvInstruction *fromVal,
  6237. QualType fromType,
  6238. QualType toBoolType,
  6239. SourceLocation loc) {
  6240. if (isSameType(astContext, fromType, toBoolType))
  6241. return fromVal;
  6242. { // Special case handling for converting to a matrix of booleans.
  6243. QualType elemType = {};
  6244. uint32_t rowCount = 0, colCount = 0;
  6245. if (isMxNMatrix(fromType, &elemType, &rowCount, &colCount)) {
  6246. const auto fromRowQualType =
  6247. astContext.getExtVectorType(elemType, colCount);
  6248. const auto toBoolRowQualType =
  6249. astContext.getExtVectorType(astContext.BoolTy, colCount);
  6250. llvm::SmallVector<SpirvInstruction *, 4> rows;
  6251. for (uint32_t i = 0; i < rowCount; ++i) {
  6252. auto *row = spvBuilder.createCompositeExtract(fromRowQualType, fromVal,
  6253. {i}, loc);
  6254. rows.push_back(
  6255. castToBool(row, fromRowQualType, toBoolRowQualType, loc));
  6256. }
  6257. return spvBuilder.createCompositeConstruct(toBoolType, rows, loc);
  6258. }
  6259. }
  6260. // Converting to bool means comparing with value zero.
  6261. const spv::Op spvOp = translateOp(BO_NE, fromType);
  6262. auto *zeroVal = getValueZero(fromType);
  6263. return spvBuilder.createBinaryOp(spvOp, toBoolType, fromVal, zeroVal, loc);
  6264. }
  6265. SpirvInstruction *SpirvEmitter::castToInt(SpirvInstruction *fromVal,
  6266. QualType fromType, QualType toIntType,
  6267. SourceLocation srcLoc) {
  6268. if (isEnumType(fromType))
  6269. fromType = astContext.IntTy;
  6270. if (isSameType(astContext, fromType, toIntType))
  6271. return fromVal;
  6272. if (isBoolOrVecOfBoolType(fromType)) {
  6273. auto *one = getValueOne(toIntType);
  6274. auto *zero = getValueZero(toIntType);
  6275. return spvBuilder.createSelect(toIntType, fromVal, one, zero, srcLoc);
  6276. }
  6277. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  6278. // First convert the source to the bitwidth of the destination if necessary.
  6279. QualType convertedType = {};
  6280. fromVal =
  6281. convertBitwidth(fromVal, srcLoc, fromType, toIntType, &convertedType);
  6282. // If bitwidth conversion was the only thing we needed to do, we're done.
  6283. if (isSameScalarOrVecType(convertedType, toIntType))
  6284. return fromVal;
  6285. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, toIntType, fromVal,
  6286. srcLoc);
  6287. }
  6288. if (isFloatOrVecOfFloatType(fromType)) {
  6289. // First convert the source to the bitwidth of the destination if necessary.
  6290. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toIntType);
  6291. if (isSintOrVecOfSintType(toIntType)) {
  6292. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToS, toIntType,
  6293. fromVal, srcLoc);
  6294. } else if (isUintOrVecOfUintType(toIntType)) {
  6295. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToU, toIntType,
  6296. fromVal, srcLoc);
  6297. } else {
  6298. emitError("casting from floating point to integer unimplemented", srcLoc);
  6299. }
  6300. }
  6301. {
  6302. QualType elemType = {};
  6303. uint32_t numRows = 0, numCols = 0;
  6304. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  6305. // The source matrix and the target matrix must have the same dimensions.
  6306. QualType toElemType = {};
  6307. uint32_t toNumRows = 0, toNumCols = 0;
  6308. const bool isMat =
  6309. isMxNMatrix(toIntType, &toElemType, &toNumRows, &toNumCols);
  6310. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  6311. (void)isMat;
  6312. (void)toNumRows;
  6313. (void)toNumCols;
  6314. // Casting to a matrix of integers: Cast each row and construct a
  6315. // composite.
  6316. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  6317. const QualType vecType = getComponentVectorType(astContext, fromType);
  6318. const auto fromVecQualType =
  6319. astContext.getExtVectorType(elemType, numCols);
  6320. const auto toIntVecQualType =
  6321. astContext.getExtVectorType(toElemType, numCols);
  6322. for (uint32_t row = 0; row < numRows; ++row) {
  6323. auto *rowId =
  6324. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  6325. castedRows.push_back(
  6326. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6327. }
  6328. return spvBuilder.createCompositeConstruct(toIntType, castedRows, srcLoc);
  6329. }
  6330. }
  6331. return nullptr;
  6332. }
  6333. SpirvInstruction *SpirvEmitter::convertBitwidth(SpirvInstruction *fromVal,
  6334. SourceLocation loc,
  6335. QualType fromType,
  6336. QualType toType,
  6337. QualType *resultType) {
  6338. // At the moment, we will not make bitwidth conversions to/from literal int
  6339. // and literal float types because they do not represent the intended SPIR-V
  6340. // bitwidth.
  6341. if (isLitTypeOrVecOfLitType(fromType) || isLitTypeOrVecOfLitType(toType))
  6342. return fromVal;
  6343. const auto fromBitwidth = getElementSpirvBitwidth(
  6344. astContext, fromType, spirvOptions.enable16BitTypes);
  6345. const auto toBitwidth = getElementSpirvBitwidth(
  6346. astContext, toType, spirvOptions.enable16BitTypes);
  6347. if (fromBitwidth == toBitwidth) {
  6348. if (resultType)
  6349. *resultType = fromType;
  6350. return fromVal;
  6351. }
  6352. // We want the 'fromType' with the 'toBitwidth'.
  6353. const QualType targetType =
  6354. getTypeWithCustomBitwidth(astContext, fromType, toBitwidth);
  6355. if (resultType)
  6356. *resultType = targetType;
  6357. if (isFloatOrVecOfFloatType(fromType))
  6358. return spvBuilder.createUnaryOp(spv::Op::OpFConvert, targetType, fromVal,
  6359. loc);
  6360. if (isSintOrVecOfSintType(fromType))
  6361. return spvBuilder.createUnaryOp(spv::Op::OpSConvert, targetType, fromVal,
  6362. loc);
  6363. if (isUintOrVecOfUintType(fromType))
  6364. return spvBuilder.createUnaryOp(spv::Op::OpUConvert, targetType, fromVal,
  6365. loc);
  6366. llvm_unreachable("invalid type passed to convertBitwidth");
  6367. }
  6368. SpirvInstruction *SpirvEmitter::castToFloat(SpirvInstruction *fromVal,
  6369. QualType fromType,
  6370. QualType toFloatType,
  6371. SourceLocation srcLoc) {
  6372. if (isSameType(astContext, fromType, toFloatType))
  6373. return fromVal;
  6374. if (isBoolOrVecOfBoolType(fromType)) {
  6375. auto *one = getValueOne(toFloatType);
  6376. auto *zero = getValueZero(toFloatType);
  6377. return spvBuilder.createSelect(toFloatType, fromVal, one, zero, srcLoc);
  6378. }
  6379. if (isSintOrVecOfSintType(fromType)) {
  6380. // First convert the source to the bitwidth of the destination if necessary.
  6381. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6382. return spvBuilder.createUnaryOp(spv::Op::OpConvertSToF, toFloatType,
  6383. fromVal, srcLoc);
  6384. }
  6385. if (isUintOrVecOfUintType(fromType)) {
  6386. // First convert the source to the bitwidth of the destination if necessary.
  6387. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6388. return spvBuilder.createUnaryOp(spv::Op::OpConvertUToF, toFloatType,
  6389. fromVal, srcLoc);
  6390. }
  6391. if (isFloatOrVecOfFloatType(fromType)) {
  6392. // This is the case of float to float conversion with different bitwidths.
  6393. return convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6394. }
  6395. // Casting matrix types
  6396. {
  6397. QualType elemType = {};
  6398. uint32_t numRows = 0, numCols = 0;
  6399. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  6400. // The source matrix and the target matrix must have the same dimensions.
  6401. QualType toElemType = {};
  6402. uint32_t toNumRows = 0, toNumCols = 0;
  6403. const auto isMat =
  6404. isMxNMatrix(toFloatType, &toElemType, &toNumRows, &toNumCols);
  6405. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  6406. (void)isMat;
  6407. (void)toNumRows;
  6408. (void)toNumCols;
  6409. // Casting to a matrix of floats: Cast each row and construct a
  6410. // composite.
  6411. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  6412. const QualType vecType = getComponentVectorType(astContext, fromType);
  6413. const auto fromVecQualType =
  6414. astContext.getExtVectorType(elemType, numCols);
  6415. const auto toIntVecQualType =
  6416. astContext.getExtVectorType(toElemType, numCols);
  6417. for (uint32_t row = 0; row < numRows; ++row) {
  6418. auto *rowId =
  6419. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  6420. castedRows.push_back(
  6421. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6422. }
  6423. return spvBuilder.createCompositeConstruct(toFloatType, castedRows,
  6424. srcLoc);
  6425. }
  6426. }
  6427. emitError("casting to floating point unimplemented", srcLoc);
  6428. return nullptr;
  6429. }
  6430. SpirvInstruction *
  6431. SpirvEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  6432. const FunctionDecl *callee = callExpr->getDirectCallee();
  6433. const SourceLocation srcLoc = callExpr->getExprLoc();
  6434. assert(hlsl::IsIntrinsicOp(callee) &&
  6435. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  6436. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  6437. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  6438. // Figure out which intrinsic function to translate.
  6439. llvm::StringRef group;
  6440. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  6441. hlsl::GetIntrinsicOp(callee, opcode, group);
  6442. GLSLstd450 glslOpcode = GLSLstd450Bad;
  6443. SpirvInstruction *retVal = nullptr;
  6444. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  6445. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6446. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  6447. doEachVec); \
  6448. } break
  6449. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  6450. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6451. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  6452. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6453. srcLoc); \
  6454. } break
  6455. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  6456. doEachVec) \
  6457. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6458. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  6459. : GLSLstd450::GLSLstd450##glslIntOp; \
  6460. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6461. srcLoc); \
  6462. } break
  6463. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  6464. doEachVec) \
  6465. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6466. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6467. : GLSLstd450::GLSLstd450##glslUintOp; \
  6468. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6469. srcLoc); \
  6470. } break
  6471. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  6472. glslFloatOp, doEachVec) \
  6473. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6474. glslOpcode = isFloatType \
  6475. ? GLSLstd450::GLSLstd450##glslFloatOp \
  6476. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6477. : GLSLstd450::GLSLstd450##glslUintOp; \
  6478. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6479. srcLoc); \
  6480. } break
  6481. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  6482. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  6483. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  6484. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  6485. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  6486. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  6487. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  6488. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  6489. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  6490. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  6491. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  6492. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  6493. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  6494. break;
  6495. case hlsl::IntrinsicOp::IOP_NonUniformResourceIndex:
  6496. retVal = processIntrinsicNonUniformResourceIndex(callExpr);
  6497. break;
  6498. case hlsl::IntrinsicOp::IOP_tex1D:
  6499. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  6500. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  6501. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  6502. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  6503. case hlsl::IntrinsicOp::IOP_tex2D:
  6504. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  6505. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  6506. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  6507. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  6508. case hlsl::IntrinsicOp::IOP_tex3D:
  6509. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  6510. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  6511. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  6512. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  6513. case hlsl::IntrinsicOp::IOP_texCUBE:
  6514. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  6515. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  6516. case hlsl::IntrinsicOp::IOP_texCUBElod:
  6517. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  6518. emitError("deprecated %0 intrinsic function will not be supported", srcLoc)
  6519. << callee->getName();
  6520. return nullptr;
  6521. }
  6522. case hlsl::IntrinsicOp::IOP_dot:
  6523. retVal = processIntrinsicDot(callExpr);
  6524. break;
  6525. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  6526. retVal = processIntrinsicMemoryBarrier(callExpr,
  6527. /*isDevice*/ false,
  6528. /*groupSync*/ false,
  6529. /*isAllBarrier*/ false);
  6530. break;
  6531. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  6532. retVal = processIntrinsicMemoryBarrier(callExpr,
  6533. /*isDevice*/ false,
  6534. /*groupSync*/ true,
  6535. /*isAllBarrier*/ false);
  6536. break;
  6537. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  6538. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6539. /*groupSync*/ false,
  6540. /*isAllBarrier*/ false);
  6541. break;
  6542. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  6543. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6544. /*groupSync*/ true,
  6545. /*isAllBarrier*/ false);
  6546. break;
  6547. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  6548. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6549. /*groupSync*/ false,
  6550. /*isAllBarrier*/ true);
  6551. break;
  6552. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  6553. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6554. /*groupSync*/ true,
  6555. /*isAllBarrier*/ true);
  6556. break;
  6557. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  6558. retVal = spvBuilder.createImageSparseTexelsResident(
  6559. doExpr(callExpr->getArg(0)), srcLoc);
  6560. break;
  6561. case hlsl::IntrinsicOp::IOP_mul:
  6562. case hlsl::IntrinsicOp::IOP_umul:
  6563. retVal = processIntrinsicMul(callExpr);
  6564. break;
  6565. case hlsl::IntrinsicOp::IOP_all:
  6566. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  6567. break;
  6568. case hlsl::IntrinsicOp::IOP_any:
  6569. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  6570. break;
  6571. case hlsl::IntrinsicOp::IOP_asdouble:
  6572. case hlsl::IntrinsicOp::IOP_asfloat:
  6573. case hlsl::IntrinsicOp::IOP_asint:
  6574. case hlsl::IntrinsicOp::IOP_asuint:
  6575. retVal = processIntrinsicAsType(callExpr);
  6576. break;
  6577. case hlsl::IntrinsicOp::IOP_clip:
  6578. retVal = processIntrinsicClip(callExpr);
  6579. break;
  6580. case hlsl::IntrinsicOp::IOP_dst:
  6581. retVal = processIntrinsicDst(callExpr);
  6582. break;
  6583. case hlsl::IntrinsicOp::IOP_clamp:
  6584. case hlsl::IntrinsicOp::IOP_uclamp:
  6585. retVal = processIntrinsicClamp(callExpr);
  6586. break;
  6587. case hlsl::IntrinsicOp::IOP_frexp:
  6588. retVal = processIntrinsicFrexp(callExpr);
  6589. break;
  6590. case hlsl::IntrinsicOp::IOP_ldexp:
  6591. retVal = processIntrinsicLdexp(callExpr);
  6592. break;
  6593. case hlsl::IntrinsicOp::IOP_lit:
  6594. retVal = processIntrinsicLit(callExpr);
  6595. break;
  6596. case hlsl::IntrinsicOp::IOP_mad:
  6597. case hlsl::IntrinsicOp::IOP_umad:
  6598. retVal = processIntrinsicMad(callExpr);
  6599. break;
  6600. case hlsl::IntrinsicOp::IOP_modf:
  6601. retVal = processIntrinsicModf(callExpr);
  6602. break;
  6603. case hlsl::IntrinsicOp::IOP_msad4:
  6604. retVal = processIntrinsicMsad4(callExpr);
  6605. break;
  6606. case hlsl::IntrinsicOp::IOP_printf:
  6607. retVal = processIntrinsicPrintf(callExpr);
  6608. break;
  6609. case hlsl::IntrinsicOp::IOP_sign: {
  6610. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  6611. retVal = processIntrinsicFloatSign(callExpr);
  6612. else
  6613. retVal =
  6614. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  6615. /*actPerRowForMatrices*/ true, srcLoc);
  6616. } break;
  6617. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  6618. retVal = processD3DCOLORtoUBYTE4(callExpr);
  6619. break;
  6620. case hlsl::IntrinsicOp::IOP_isfinite:
  6621. retVal = processIntrinsicIsFinite(callExpr);
  6622. break;
  6623. case hlsl::IntrinsicOp::IOP_sincos:
  6624. retVal = processIntrinsicSinCos(callExpr);
  6625. break;
  6626. case hlsl::IntrinsicOp::IOP_rcp:
  6627. retVal = processIntrinsicRcp(callExpr);
  6628. break;
  6629. case hlsl::IntrinsicOp::IOP_VkReadClock:
  6630. retVal = processIntrinsicReadClock(callExpr);
  6631. break;
  6632. case hlsl::IntrinsicOp::IOP_saturate:
  6633. retVal = processIntrinsicSaturate(callExpr);
  6634. break;
  6635. case hlsl::IntrinsicOp::IOP_log10:
  6636. retVal = processIntrinsicLog10(callExpr);
  6637. break;
  6638. case hlsl::IntrinsicOp::IOP_f16tof32:
  6639. retVal = processIntrinsicF16ToF32(callExpr);
  6640. break;
  6641. case hlsl::IntrinsicOp::IOP_f32tof16:
  6642. retVal = processIntrinsicF32ToF16(callExpr);
  6643. break;
  6644. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  6645. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  6646. srcLoc);
  6647. const QualType retType = callExpr->getCallReturnType(astContext);
  6648. auto *var =
  6649. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize, retType, srcLoc);
  6650. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6651. } break;
  6652. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  6653. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  6654. srcLoc);
  6655. const QualType retType = callExpr->getCallReturnType(astContext);
  6656. auto *var = declIdMapper.getBuiltinVar(
  6657. spv::BuiltIn::SubgroupLocalInvocationId, retType, srcLoc);
  6658. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6659. } break;
  6660. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  6661. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  6662. break;
  6663. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  6664. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  6665. break;
  6666. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  6667. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  6668. break;
  6669. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  6670. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  6671. break;
  6672. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  6673. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  6674. break;
  6675. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  6676. retVal = processWaveCountBits(callExpr, spv::GroupOperation::Reduce);
  6677. break;
  6678. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  6679. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  6680. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  6681. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  6682. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  6683. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  6684. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  6685. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  6686. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  6687. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  6688. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  6689. const auto retType = callExpr->getCallReturnType(astContext);
  6690. retVal = processWaveReductionOrPrefix(
  6691. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6692. spv::GroupOperation::Reduce);
  6693. } break;
  6694. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  6695. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  6696. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  6697. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  6698. const auto retType = callExpr->getCallReturnType(astContext);
  6699. retVal = processWaveReductionOrPrefix(
  6700. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6701. spv::GroupOperation::ExclusiveScan);
  6702. } break;
  6703. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  6704. retVal = processWaveCountBits(callExpr, spv::GroupOperation::ExclusiveScan);
  6705. break;
  6706. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  6707. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  6708. retVal = processWaveBroadcast(callExpr);
  6709. break;
  6710. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6711. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6712. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6713. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6714. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  6715. break;
  6716. case hlsl::IntrinsicOp::IOP_abort:
  6717. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  6718. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  6719. emitError("no equivalent for %0 intrinsic function in Vulkan", srcLoc)
  6720. << callee->getName();
  6721. return 0;
  6722. }
  6723. case hlsl::IntrinsicOp::IOP_transpose: {
  6724. const Expr *mat = callExpr->getArg(0);
  6725. const QualType matType = mat->getType();
  6726. if (isVectorType(matType) || isScalarType(matType)) {
  6727. // A 1xN or Nx1 or 1x1 matrix is a SPIR-V vector/scalar, and its transpose
  6728. // is the vector/scalar itself.
  6729. retVal = doExpr(mat);
  6730. } else {
  6731. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  6732. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose,
  6733. false);
  6734. else
  6735. retVal = processNonFpMatrixTranspose(matType, doExpr(mat), srcLoc);
  6736. }
  6737. break;
  6738. }
  6739. case hlsl::IntrinsicOp::IOP_pack_s8:
  6740. case hlsl::IntrinsicOp::IOP_pack_u8:
  6741. case hlsl::IntrinsicOp::IOP_pack_clamp_s8:
  6742. case hlsl::IntrinsicOp::IOP_pack_clamp_u8: {
  6743. retVal = processIntrinsic8BitPack(callExpr, hlslOpcode);
  6744. break;
  6745. }
  6746. case hlsl::IntrinsicOp::IOP_unpack_s8s16:
  6747. case hlsl::IntrinsicOp::IOP_unpack_s8s32:
  6748. case hlsl::IntrinsicOp::IOP_unpack_u8u16:
  6749. case hlsl::IntrinsicOp::IOP_unpack_u8u32: {
  6750. retVal = processIntrinsic8BitUnpack(callExpr, hlslOpcode);
  6751. break;
  6752. }
  6753. // DXR raytracing intrinsics
  6754. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  6755. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  6756. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  6757. case hlsl::IntrinsicOp::IOP_HitKind:
  6758. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  6759. case hlsl::IntrinsicOp::IOP_InstanceID:
  6760. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  6761. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  6762. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  6763. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  6764. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  6765. case hlsl::IntrinsicOp::IOP_RayFlags:
  6766. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  6767. case hlsl::IntrinsicOp::IOP_RayTMin:
  6768. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  6769. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  6770. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  6771. case hlsl::IntrinsicOp::IOP_WorldToObject4x3: {
  6772. retVal = processRayBuiltins(callExpr, hlslOpcode);
  6773. break;
  6774. }
  6775. case hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch:
  6776. case hlsl::IntrinsicOp::IOP_IgnoreHit: {
  6777. // Any modifications made to the ray payload in an any hit shader are
  6778. // preserved before calling AcceptHit/IgnoreHit. Write out the results to
  6779. // the payload which is visible only in entry functions
  6780. const auto iter = functionInfoMap.find(curFunction);
  6781. if (iter != functionInfoMap.end()) {
  6782. const auto &entryInfo = iter->second;
  6783. if (entryInfo->isEntryFunction) {
  6784. const auto payloadArg = curFunction->getParamDecl(0);
  6785. const auto payloadArgInst =
  6786. declIdMapper.getDeclEvalInfo(payloadArg, payloadArg->getLocStart());
  6787. auto tempLoad = spvBuilder.createLoad(
  6788. payloadArg->getType(), payloadArgInst, payloadArg->getLocStart());
  6789. spvBuilder.createStore(currentRayPayload, tempLoad,
  6790. callExpr->getExprLoc());
  6791. }
  6792. }
  6793. bool nvRayTracing =
  6794. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  6795. if (nvRayTracing) {
  6796. spvBuilder.createRayTracingOpsNV(
  6797. hlslOpcode == hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch
  6798. ? spv::Op::OpTerminateRayNV
  6799. : spv::Op::OpIgnoreIntersectionNV,
  6800. QualType(), {}, srcLoc);
  6801. } else {
  6802. spvBuilder.createRaytracingTerminateKHR(
  6803. hlslOpcode == hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch
  6804. ? spv::Op::OpTerminateRayKHR
  6805. : spv::Op::OpIgnoreIntersectionKHR,
  6806. srcLoc);
  6807. // According to the SPIR-V spec, both OpTerminateRayKHR and
  6808. // OpIgnoreIntersectionKHR are termination instructions.
  6809. // The spec also requires that these instructions must be the last
  6810. // instruction in a block.
  6811. // Therefore we need to create a new basic block, and the following
  6812. // instructions will go there.
  6813. auto *newBB = spvBuilder.createBasicBlock();
  6814. spvBuilder.setInsertPoint(newBB);
  6815. }
  6816. break;
  6817. }
  6818. case hlsl::IntrinsicOp::IOP_ReportHit: {
  6819. retVal = processReportHit(callExpr);
  6820. break;
  6821. }
  6822. case hlsl::IntrinsicOp::IOP_TraceRay: {
  6823. processTraceRay(callExpr);
  6824. break;
  6825. }
  6826. case hlsl::IntrinsicOp::IOP_CallShader: {
  6827. processCallShader(callExpr);
  6828. break;
  6829. }
  6830. case hlsl::IntrinsicOp::IOP_DispatchMesh: {
  6831. processDispatchMesh(callExpr);
  6832. break;
  6833. }
  6834. case hlsl::IntrinsicOp::IOP_SetMeshOutputCounts: {
  6835. processMeshOutputCounts(callExpr);
  6836. break;
  6837. }
  6838. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  6839. INTRINSIC_SPIRV_OP_CASE(ddx_coarse, DPdxCoarse, false);
  6840. INTRINSIC_SPIRV_OP_CASE(ddx_fine, DPdxFine, false);
  6841. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  6842. INTRINSIC_SPIRV_OP_CASE(ddy_coarse, DPdyCoarse, false);
  6843. INTRINSIC_SPIRV_OP_CASE(ddy_fine, DPdyFine, false);
  6844. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  6845. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  6846. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  6847. INTRINSIC_SPIRV_OP_CASE(fmod, FRem, true);
  6848. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  6849. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  6850. INTRINSIC_OP_CASE(round, Round, true);
  6851. INTRINSIC_OP_CASE(uabs, SAbs, true);
  6852. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  6853. INTRINSIC_OP_CASE(acos, Acos, true);
  6854. INTRINSIC_OP_CASE(asin, Asin, true);
  6855. INTRINSIC_OP_CASE(atan, Atan, true);
  6856. INTRINSIC_OP_CASE(atan2, Atan2, true);
  6857. INTRINSIC_OP_CASE(ceil, Ceil, true);
  6858. INTRINSIC_OP_CASE(cos, Cos, true);
  6859. INTRINSIC_OP_CASE(cosh, Cosh, true);
  6860. INTRINSIC_OP_CASE(cross, Cross, false);
  6861. INTRINSIC_OP_CASE(degrees, Degrees, true);
  6862. INTRINSIC_OP_CASE(distance, Distance, false);
  6863. INTRINSIC_OP_CASE(determinant, Determinant, false);
  6864. INTRINSIC_OP_CASE(exp, Exp, true);
  6865. INTRINSIC_OP_CASE(exp2, Exp2, true);
  6866. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  6867. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  6868. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  6869. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  6870. INTRINSIC_OP_CASE(floor, Floor, true);
  6871. INTRINSIC_OP_CASE(fma, Fma, true);
  6872. INTRINSIC_OP_CASE(frac, Fract, true);
  6873. INTRINSIC_OP_CASE(length, Length, false);
  6874. INTRINSIC_OP_CASE(lerp, FMix, true);
  6875. INTRINSIC_OP_CASE(log, Log, true);
  6876. INTRINSIC_OP_CASE(log2, Log2, true);
  6877. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  6878. INTRINSIC_OP_CASE(umax, UMax, true);
  6879. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  6880. INTRINSIC_OP_CASE(umin, UMin, true);
  6881. INTRINSIC_OP_CASE(normalize, Normalize, false);
  6882. INTRINSIC_OP_CASE(pow, Pow, true);
  6883. INTRINSIC_OP_CASE(radians, Radians, true);
  6884. INTRINSIC_OP_CASE(reflect, Reflect, false);
  6885. INTRINSIC_OP_CASE(refract, Refract, false);
  6886. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  6887. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  6888. INTRINSIC_OP_CASE(step, Step, true);
  6889. INTRINSIC_OP_CASE(sin, Sin, true);
  6890. INTRINSIC_OP_CASE(sinh, Sinh, true);
  6891. INTRINSIC_OP_CASE(tan, Tan, true);
  6892. INTRINSIC_OP_CASE(tanh, Tanh, true);
  6893. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  6894. INTRINSIC_OP_CASE(trunc, Trunc, true);
  6895. default:
  6896. emitError("%0 intrinsic function unimplemented", srcLoc)
  6897. << callee->getName();
  6898. return 0;
  6899. }
  6900. #undef INTRINSIC_OP_CASE
  6901. #undef INTRINSIC_OP_CASE_INT_FLOAT
  6902. if (retVal)
  6903. retVal->setRValue();
  6904. return retVal;
  6905. }
  6906. SpirvInstruction *
  6907. SpirvEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  6908. hlsl::IntrinsicOp opcode) {
  6909. // The signature of intrinsic atomic methods are:
  6910. // void Interlocked*(in R dest, in T value);
  6911. // void Interlocked*(in R dest, in T value, out T original_value);
  6912. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  6913. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  6914. // parameter is not an unsigned integer, the frontend inserts an
  6915. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  6916. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  6917. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  6918. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  6919. // the following OpAtomicIAdd is invalid because the pointee type defined in
  6920. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  6921. // unsigned integer.
  6922. //
  6923. // %_ptr_Image_int = OpTypePointer Image %int
  6924. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  6925. // %2 = OpLoad %int %value
  6926. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  6927. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  6928. //
  6929. // In such cases, we bypass the forced IntegralCast.
  6930. // Moreover, the frontend does not add a cast AST node to cast uint to int
  6931. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  6932. auto *zero =
  6933. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  6934. const auto *dest = expr->getArg(0);
  6935. const auto srcLoc = expr->getExprLoc();
  6936. const auto baseType = dest->getType()->getCanonicalTypeUnqualified();
  6937. if (!baseType->isIntegerType()) {
  6938. emitError("can only perform atomic operations on scalar integer values",
  6939. dest->getLocStart());
  6940. return nullptr;
  6941. }
  6942. const auto doArg = [baseType, this](const CallExpr *callExpr,
  6943. uint32_t argIndex) {
  6944. const Expr *valueExpr = callExpr->getArg(argIndex);
  6945. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  6946. if (castExpr->getCastKind() == CK_IntegralCast &&
  6947. castExpr->getSubExpr()->getType()->getCanonicalTypeUnqualified() ==
  6948. baseType)
  6949. valueExpr = castExpr->getSubExpr();
  6950. auto *argInstr = doExpr(valueExpr);
  6951. if (valueExpr->getType() != baseType)
  6952. argInstr = castToInt(argInstr, valueExpr->getType(), baseType,
  6953. valueExpr->getExprLoc());
  6954. return argInstr;
  6955. };
  6956. const auto writeToOutputArg = [&baseType, dest,
  6957. this](SpirvInstruction *toWrite,
  6958. const CallExpr *callExpr,
  6959. uint32_t outputArgIndex) {
  6960. const auto outputArg = callExpr->getArg(outputArgIndex);
  6961. const auto outputArgType = outputArg->getType();
  6962. if (baseType != outputArgType)
  6963. toWrite =
  6964. castToInt(toWrite, baseType, outputArgType, dest->getLocStart());
  6965. spvBuilder.createStore(doExpr(outputArg), toWrite, callExpr->getExprLoc());
  6966. };
  6967. // If a vector swizzling of a texture is done as an argument of an
  6968. // interlocked method, we need to handle the access to the texture
  6969. // buffer element correctly. For example:
  6970. //
  6971. // InterlockedAdd(myRWTexture[index].r, 1);
  6972. //
  6973. // `-CallExpr
  6974. // |-ImplicitCastExpr
  6975. // | `-DeclRefExpr Function 'InterlockedAdd'
  6976. // | 'void (unsigned int &, unsigned int)'
  6977. // |-HLSLVectorElementExpr 'unsigned int' lvalue vectorcomponent r
  6978. // | `-ImplicitCastExpr 'vector<uint, 1>':'vector<unsigned int, 1>'
  6979. // | <HLSLVectorSplat>
  6980. // | `-CXXOperatorCallExpr 'unsigned int' lvalue
  6981. const auto *cxxOpCall = dyn_cast<CXXOperatorCallExpr>(dest);
  6982. if (const auto *vector = dyn_cast<HLSLVectorElementExpr>(dest)) {
  6983. const Expr *base = vector->getBase();
  6984. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(base);
  6985. if (const auto *cast = dyn_cast<CastExpr>(base)) {
  6986. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(cast->getSubExpr());
  6987. }
  6988. }
  6989. // If the argument is indexing into a texture/buffer, we need to create an
  6990. // OpImageTexelPointer instruction.
  6991. SpirvInstruction *ptr = nullptr;
  6992. if (cxxOpCall) {
  6993. const Expr *base = nullptr;
  6994. const Expr *index = nullptr;
  6995. if (isBufferTextureIndexing(cxxOpCall, &base, &index)) {
  6996. if (hlsl::IsHLSLResourceType(base->getType())) {
  6997. const auto resultTy = hlsl::GetHLSLResourceResultType(base->getType());
  6998. if (!isScalarType(resultTy, nullptr)) {
  6999. emitError("Interlocked operation for texture buffer whose result "
  7000. "type is non-scalar type is not allowed",
  7001. dest->getExprLoc());
  7002. return nullptr;
  7003. }
  7004. }
  7005. auto *baseInstr = doExpr(base);
  7006. if (baseInstr->isRValue()) {
  7007. // OpImageTexelPointer's Image argument must have a type of
  7008. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  7009. // variable if the baseId is an rvalue.
  7010. baseInstr =
  7011. createTemporaryVar(base->getType(), getAstTypeName(base->getType()),
  7012. baseInstr, base->getExprLoc());
  7013. }
  7014. auto *coordInstr = doExpr(index);
  7015. ptr = spvBuilder.createImageTexelPointer(baseType, baseInstr, coordInstr,
  7016. zero, srcLoc);
  7017. }
  7018. }
  7019. if (!ptr) {
  7020. auto *ptrInfo = doExpr(dest);
  7021. const auto sc = ptrInfo->getStorageClass();
  7022. if (sc == spv::StorageClass::Private || sc == spv::StorageClass::Function) {
  7023. emitError("using static variable or function scope variable in "
  7024. "interlocked operation is not allowed",
  7025. dest->getExprLoc());
  7026. return nullptr;
  7027. }
  7028. ptr = ptrInfo;
  7029. }
  7030. const bool isCompareExchange =
  7031. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  7032. const bool isCompareStore =
  7033. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  7034. if (isCompareExchange || isCompareStore) {
  7035. auto *comparator = doArg(expr, 1);
  7036. auto *valueInstr = doArg(expr, 2);
  7037. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  7038. baseType, ptr, spv::Scope::Device, spv::MemorySemanticsMask::MaskNone,
  7039. spv::MemorySemanticsMask::MaskNone, valueInstr, comparator, srcLoc);
  7040. if (isCompareExchange)
  7041. writeToOutputArg(originalVal, expr, 3);
  7042. } else {
  7043. auto *value = doArg(expr, 1);
  7044. // Since these atomic operations write through the provided pointer, the
  7045. // signed vs. unsigned opcode must be decided based on the pointee type
  7046. // of the first argument. However, the frontend decides the opcode based on
  7047. // the second argument (value). Therefore, the HLSL opcode provided by the
  7048. // frontend may be wrong. Therefore we need the following code to make sure
  7049. // we are using the correct SPIR-V opcode.
  7050. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  7051. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  7052. atomicOp = spv::Op::OpAtomicSMax;
  7053. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  7054. atomicOp = spv::Op::OpAtomicUMax;
  7055. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  7056. atomicOp = spv::Op::OpAtomicSMin;
  7057. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  7058. atomicOp = spv::Op::OpAtomicUMin;
  7059. auto *originalVal = spvBuilder.createAtomicOp(
  7060. atomicOp, baseType, ptr, spv::Scope::Device,
  7061. spv::MemorySemanticsMask::MaskNone, value, srcLoc);
  7062. if (expr->getNumArgs() > 2)
  7063. writeToOutputArg(originalVal, expr, 2);
  7064. }
  7065. return nullptr;
  7066. }
  7067. SpirvInstruction *
  7068. SpirvEmitter::processIntrinsicNonUniformResourceIndex(const CallExpr *expr) {
  7069. auto *index = doExpr(expr->getArg(0));
  7070. // Decorate the expression in NonUniformResourceIndex() with NonUniformEXT.
  7071. // Aside from this, we also need to eventually populate the NonUniformEXT
  7072. // status to the usages of this expression. This is done by the
  7073. // NonUniformVisitor class.
  7074. //
  7075. // The decoration shouldn't be applied to the operand, rather to a copy of the
  7076. // result. Even though applying the decoration to the operand may not be
  7077. // functionally incorrect (since adding NonUniform is more conservative), it
  7078. // could affect performance and isn't the intent of the shader.
  7079. auto *copyInstr =
  7080. spvBuilder.createCopyObject(expr->getType(), index, expr->getExprLoc());
  7081. copyInstr->setNonUniform();
  7082. return copyInstr;
  7083. }
  7084. SpirvInstruction *
  7085. SpirvEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  7086. const auto loc = callExpr->getExprLoc();
  7087. if (!spirvOptions.noWarnEmulatedFeatures)
  7088. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  7089. "instructions due to lack of direct SPIR-V equivalent",
  7090. loc);
  7091. // Compares a 4-byte reference value and an 8-byte source value and
  7092. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  7093. // of absolute differences of a different byte alignment between the
  7094. // reference value and the source value.
  7095. // If we have:
  7096. // uint v0; // reference
  7097. // uint2 v1; // source
  7098. // uint4 v2; // accum
  7099. // uint4 o0; // result of msad4
  7100. // uint4 r0, t0; // temporary values
  7101. //
  7102. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  7103. // to fxc:
  7104. // Step 1:
  7105. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  7106. // Step 2:
  7107. // [result], [ width ], [ offset ], [ insert ], [ base ]
  7108. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  7109. // mov t0.x, v1.x
  7110. // Step 3:
  7111. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  7112. const auto boolType = astContext.BoolTy;
  7113. const auto intType = astContext.IntTy;
  7114. const auto uintType = astContext.UnsignedIntTy;
  7115. const auto uint4Type = astContext.getExtVectorType(uintType, 4);
  7116. auto *reference = doExpr(callExpr->getArg(0));
  7117. auto *source = doExpr(callExpr->getArg(1));
  7118. auto *accum = doExpr(callExpr->getArg(2));
  7119. const auto uint0 =
  7120. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  7121. const auto uint8 =
  7122. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8));
  7123. const auto uint16 =
  7124. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16));
  7125. const auto uint24 =
  7126. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 24));
  7127. // Step 1.
  7128. auto *v1x = spvBuilder.createCompositeExtract(uintType, source, {0}, loc);
  7129. // r0.x = v1xS8 = v1.x shifted by 8 bits
  7130. auto *v1xS8 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical, uintType,
  7131. v1x, uint8, loc);
  7132. // r0.y = v1xS16 = v1.x shifted by 16 bits
  7133. auto *v1xS16 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  7134. uintType, v1x, uint16, loc);
  7135. // r0.z = v1xS24 = v1.x shifted by 24 bits
  7136. auto *v1xS24 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  7137. uintType, v1x, uint24, loc);
  7138. // Step 2.
  7139. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  7140. auto *v1y = spvBuilder.createCompositeExtract(uintType, source, {1}, loc);
  7141. // Note that t0.x = v1.x, nothing we need to do for that.
  7142. auto *t0y =
  7143. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  7144. /*offset*/ uint24,
  7145. /*width*/ uint8, loc);
  7146. auto *t0z =
  7147. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  7148. /*offset*/ uint16,
  7149. /*width*/ uint16, loc);
  7150. auto *t0w =
  7151. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  7152. /*offset*/ uint8,
  7153. /*width*/ uint24, loc);
  7154. // Step 3. MSAD (Masked Sum of Absolute Differences)
  7155. // Now perform MSAD four times.
  7156. // Need to mimic this algorithm in SPIR-V!
  7157. //
  7158. // UINT msad( UINT ref, UINT src, UINT accum )
  7159. // {
  7160. // for (UINT i = 0; i < 4; i++)
  7161. // {
  7162. // BYTE refByte, srcByte, absDiff;
  7163. //
  7164. // refByte = (BYTE)(ref >> (i * 8));
  7165. // if (!refByte)
  7166. // {
  7167. // continue;
  7168. // }
  7169. //
  7170. // srcByte = (BYTE)(src >> (i * 8));
  7171. // if (refByte >= srcByte)
  7172. // {
  7173. // absDiff = refByte - srcByte;
  7174. // }
  7175. // else
  7176. // {
  7177. // absDiff = srcByte - refByte;
  7178. // }
  7179. //
  7180. // // The recommended overflow behavior for MSAD is
  7181. // // to do a 32-bit saturate. This is not
  7182. // // required, however, and wrapping is allowed.
  7183. // // So from an application point of view,
  7184. // // overflow behavior is undefined.
  7185. // if (UINT_MAX - accum < absDiff)
  7186. // {
  7187. // accum = UINT_MAX;
  7188. // break;
  7189. // }
  7190. // accum += absDiff;
  7191. // }
  7192. //
  7193. // return accum;
  7194. // }
  7195. auto *accum0 = spvBuilder.createCompositeExtract(uintType, accum, {0}, loc);
  7196. auto *accum1 = spvBuilder.createCompositeExtract(uintType, accum, {1}, loc);
  7197. auto *accum2 = spvBuilder.createCompositeExtract(uintType, accum, {2}, loc);
  7198. auto *accum3 = spvBuilder.createCompositeExtract(uintType, accum, {3}, loc);
  7199. const llvm::SmallVector<SpirvInstruction *, 4> sources = {v1x, t0y, t0z, t0w};
  7200. llvm::SmallVector<SpirvInstruction *, 4> accums = {accum0, accum1, accum2,
  7201. accum3};
  7202. llvm::SmallVector<SpirvInstruction *, 4> refBytes;
  7203. llvm::SmallVector<SpirvInstruction *, 4> signedRefBytes;
  7204. llvm::SmallVector<SpirvInstruction *, 4> isRefByteZero;
  7205. for (uint32_t i = 0; i < 4; ++i) {
  7206. refBytes.push_back(spvBuilder.createBitFieldExtract(
  7207. uintType, reference, /*offset*/
  7208. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  7209. llvm::APInt(32, i * 8)),
  7210. /*count*/ uint8, /*isSigned*/ false, loc));
  7211. signedRefBytes.push_back(spvBuilder.createUnaryOp(
  7212. spv::Op::OpBitcast, intType, refBytes.back(), loc));
  7213. isRefByteZero.push_back(spvBuilder.createBinaryOp(
  7214. spv::Op::OpIEqual, boolType, refBytes.back(), uint0, loc));
  7215. }
  7216. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  7217. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  7218. // 'count' is always 8 because we are extracting 8 bits out of 32.
  7219. auto *srcByte = spvBuilder.createBitFieldExtract(
  7220. uintType, sources[msadNum],
  7221. /*offset*/
  7222. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  7223. llvm::APInt(32, 8 * byteCount)),
  7224. /*count*/ uint8, /*isSigned*/ false, loc);
  7225. auto *signedSrcByte =
  7226. spvBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte, loc);
  7227. auto *sub = spvBuilder.createBinaryOp(spv::Op::OpISub, intType,
  7228. signedRefBytes[byteCount],
  7229. signedSrcByte, loc);
  7230. auto *absSub = spvBuilder.createGLSLExtInst(
  7231. intType, GLSLstd450::GLSLstd450SAbs, {sub}, loc);
  7232. auto *diff = spvBuilder.createSelect(
  7233. uintType, isRefByteZero[byteCount], uint0,
  7234. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub, loc),
  7235. loc);
  7236. // As pointed out by the DXIL reference above, it is *not* required to
  7237. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  7238. // also allowed. For simplicity, we will wrap around at this point.
  7239. accums[msadNum] = spvBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  7240. accums[msadNum], diff, loc);
  7241. }
  7242. }
  7243. return spvBuilder.createCompositeConstruct(uint4Type, accums, loc);
  7244. }
  7245. SpirvInstruction *SpirvEmitter::processWaveQuery(const CallExpr *callExpr,
  7246. spv::Op opcode) {
  7247. // Signatures:
  7248. // bool WaveIsFirstLane()
  7249. // uint WaveGetLaneCount()
  7250. // uint WaveGetLaneIndex()
  7251. assert(callExpr->getNumArgs() == 0);
  7252. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7253. callExpr->getExprLoc());
  7254. const QualType retType = callExpr->getCallReturnType(astContext);
  7255. return spvBuilder.createGroupNonUniformElect(
  7256. opcode, retType, spv::Scope::Subgroup, callExpr->getExprLoc());
  7257. }
  7258. SpirvInstruction *SpirvEmitter::processWaveVote(const CallExpr *callExpr,
  7259. spv::Op opcode) {
  7260. // Signatures:
  7261. // bool WaveActiveAnyTrue( bool expr )
  7262. // bool WaveActiveAllTrue( bool expr )
  7263. // bool uint4 WaveActiveBallot( bool expr )
  7264. assert(callExpr->getNumArgs() == 1);
  7265. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7266. callExpr->getExprLoc());
  7267. auto *predicate = doExpr(callExpr->getArg(0));
  7268. const QualType retType = callExpr->getCallReturnType(astContext);
  7269. return spvBuilder.createGroupNonUniformUnaryOp(
  7270. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate);
  7271. }
  7272. spv::Op SpirvEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  7273. SourceLocation srcLoc) {
  7274. const bool isSintType = isSintOrVecMatOfSintType(type);
  7275. const bool isUintType = isUintOrVecMatOfUintType(type);
  7276. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  7277. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  7278. \
  7279. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  7280. if (isSintType || isUintType) { \
  7281. return spv::Op::OpGroupNonUniform##intWaveOp; \
  7282. } \
  7283. } break
  7284. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  7285. \
  7286. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  7287. if (isSintType || isUintType) { \
  7288. return spv::Op::OpGroupNonUniform##intWaveOp; \
  7289. } \
  7290. if (isFloatType) { \
  7291. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  7292. } \
  7293. } break
  7294. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  7295. floatWaveOp) \
  7296. \
  7297. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  7298. if (isSintType) { \
  7299. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  7300. } \
  7301. if (isUintType) { \
  7302. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  7303. } \
  7304. if (isFloatType) { \
  7305. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  7306. } \
  7307. } break
  7308. switch (op) {
  7309. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  7310. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  7311. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  7312. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  7313. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  7314. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  7315. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  7316. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  7317. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  7318. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  7319. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  7320. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  7321. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  7322. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  7323. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  7324. default:
  7325. // Only Simple Wave Ops are handled here.
  7326. break;
  7327. }
  7328. #undef WAVE_OP_CASE_INT_FLOAT
  7329. #undef WAVE_OP_CASE_INT
  7330. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  7331. emitError("translating wave operator '%0' unimplemented", srcLoc)
  7332. << static_cast<uint32_t>(op);
  7333. return spv::Op::OpNop;
  7334. }
  7335. SpirvInstruction *
  7336. SpirvEmitter::processWaveCountBits(const CallExpr *callExpr,
  7337. spv::GroupOperation groupOp) {
  7338. // Signatures:
  7339. // uint WaveActiveCountBits(bool bBit)
  7340. // uint WavePrefixCountBits(Bool bBit)
  7341. assert(callExpr->getNumArgs() == 1);
  7342. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7343. callExpr->getExprLoc());
  7344. auto *predicate = doExpr(callExpr->getArg(0));
  7345. const auto srcLoc = callExpr->getExprLoc();
  7346. const QualType u32Type = astContext.UnsignedIntTy;
  7347. const QualType v4u32Type = astContext.getExtVectorType(u32Type, 4);
  7348. const QualType retType = callExpr->getCallReturnType(astContext);
  7349. auto *ballot = spvBuilder.createGroupNonUniformUnaryOp(
  7350. srcLoc, spv::Op::OpGroupNonUniformBallot, v4u32Type, spv::Scope::Subgroup,
  7351. predicate);
  7352. return spvBuilder.createGroupNonUniformUnaryOp(
  7353. srcLoc, spv::Op::OpGroupNonUniformBallotBitCount, retType,
  7354. spv::Scope::Subgroup, ballot,
  7355. llvm::Optional<spv::GroupOperation>(groupOp));
  7356. }
  7357. SpirvInstruction *SpirvEmitter::processWaveReductionOrPrefix(
  7358. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  7359. // Signatures:
  7360. // bool WaveActiveAllEqual( <type> expr )
  7361. // <type> WaveActiveSum( <type> expr )
  7362. // <type> WaveActiveProduct( <type> expr )
  7363. // <int_type> WaveActiveBitAnd( <int_type> expr )
  7364. // <int_type> WaveActiveBitOr( <int_type> expr )
  7365. // <int_type> WaveActiveBitXor( <int_type> expr )
  7366. // <type> WaveActiveMin( <type> expr)
  7367. // <type> WaveActiveMax( <type> expr)
  7368. //
  7369. // <type> WavePrefixProduct(<type> value)
  7370. // <type> WavePrefixSum(<type> value)
  7371. assert(callExpr->getNumArgs() == 1);
  7372. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7373. callExpr->getExprLoc());
  7374. auto *predicate = doExpr(callExpr->getArg(0));
  7375. const QualType retType = callExpr->getCallReturnType(astContext);
  7376. return spvBuilder.createGroupNonUniformUnaryOp(
  7377. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate,
  7378. llvm::Optional<spv::GroupOperation>(groupOp));
  7379. }
  7380. SpirvInstruction *SpirvEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  7381. // Signatures:
  7382. // <type> WaveReadLaneFirst(<type> expr)
  7383. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  7384. const auto numArgs = callExpr->getNumArgs();
  7385. const auto srcLoc = callExpr->getExprLoc();
  7386. assert(numArgs == 1 || numArgs == 2);
  7387. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7388. callExpr->getExprLoc());
  7389. auto *value = doExpr(callExpr->getArg(0));
  7390. const QualType retType = callExpr->getCallReturnType(astContext);
  7391. if (numArgs == 2)
  7392. // WaveReadLaneAt is in fact not a broadcast operation (even though its name
  7393. // might incorrectly suggest so). The proper mapping to SPIR-V for
  7394. // it is OpGroupNonUniformShuffle, *not* OpGroupNonUniformBroadcast.
  7395. return spvBuilder.createGroupNonUniformBinaryOp(
  7396. spv::Op::OpGroupNonUniformShuffle, retType, spv::Scope::Subgroup, value,
  7397. doExpr(callExpr->getArg(1)), srcLoc);
  7398. else
  7399. return spvBuilder.createGroupNonUniformUnaryOp(
  7400. srcLoc, spv::Op::OpGroupNonUniformBroadcastFirst, retType,
  7401. spv::Scope::Subgroup, value);
  7402. }
  7403. SpirvInstruction *
  7404. SpirvEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  7405. hlsl::IntrinsicOp op) {
  7406. // Signatures:
  7407. // <type> QuadReadAcrossX(<type> localValue)
  7408. // <type> QuadReadAcrossY(<type> localValue)
  7409. // <type> QuadReadAcrossDiagonal(<type> localValue)
  7410. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  7411. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  7412. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7413. callExpr->getExprLoc());
  7414. auto *value = doExpr(callExpr->getArg(0));
  7415. const auto srcLoc = callExpr->getExprLoc();
  7416. const QualType retType = callExpr->getCallReturnType(astContext);
  7417. SpirvInstruction *target = nullptr;
  7418. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  7419. switch (op) {
  7420. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  7421. target =
  7422. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  7423. break;
  7424. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  7425. target =
  7426. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  7427. break;
  7428. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  7429. target =
  7430. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  7431. break;
  7432. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  7433. target = doExpr(callExpr->getArg(1));
  7434. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  7435. break;
  7436. default:
  7437. llvm_unreachable("case should not appear here");
  7438. }
  7439. return spvBuilder.createGroupNonUniformBinaryOp(
  7440. opcode, retType, spv::Scope::Subgroup, value, target, srcLoc);
  7441. }
  7442. SpirvInstruction *SpirvEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  7443. // Signature is: ret modf(x, ip)
  7444. // [in] x: the input floating-point value.
  7445. // [out] ip: the integer portion of x.
  7446. // [out] ret: the fractional portion of x.
  7447. // All of the above must be a scalar, vector, or matrix with the same
  7448. // component types. Component types can be float or int.
  7449. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  7450. // fractional part and the second member is the integer portion.
  7451. // ModfStruct {
  7452. // <scalar or vector of float> frac;
  7453. // <scalar or vector of float> ip;
  7454. // }
  7455. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  7456. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  7457. // argument is not treated the same way. Therefore, in such cases we'll have
  7458. // to manually convert the float result into int.
  7459. const Expr *arg = callExpr->getArg(0);
  7460. const Expr *ipArg = callExpr->getArg(1);
  7461. const auto loc = callExpr->getLocStart();
  7462. const auto argType = arg->getType();
  7463. const auto ipType = ipArg->getType();
  7464. const auto returnType = callExpr->getType();
  7465. auto *argInstr = doExpr(arg);
  7466. // For scalar and vector argument types.
  7467. {
  7468. if (isScalarType(argType) || isVectorType(argType)) {
  7469. // The struct members *must* have the same type.
  7470. const auto modfStructType = spvContext.getHybridStructType(
  7471. {HybridStructType::FieldInfo(argType, "frac"),
  7472. HybridStructType::FieldInfo(argType, "ip")},
  7473. "ModfStructType");
  7474. auto *modf = spvBuilder.createGLSLExtInst(
  7475. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {argInstr}, loc);
  7476. SpirvInstruction *ip =
  7477. spvBuilder.createCompositeExtract(argType, modf, {1}, loc);
  7478. // This will do nothing if the input number (x) and the ip are both of the
  7479. // same type. Otherwise, it will convert the ip into int as necessary.
  7480. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7481. processAssignment(ipArg, ip, false, nullptr);
  7482. return spvBuilder.createCompositeExtract(argType, modf, {0}, loc);
  7483. }
  7484. }
  7485. // For matrix argument types.
  7486. {
  7487. uint32_t rowCount = 0, colCount = 0;
  7488. QualType elemType = {};
  7489. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7490. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7491. const auto modfStructType = spvContext.getHybridStructType(
  7492. {HybridStructType::FieldInfo(colType, "frac"),
  7493. HybridStructType::FieldInfo(colType, "ip")},
  7494. "ModfStructType");
  7495. llvm::SmallVector<SpirvInstruction *, 4> fracs;
  7496. llvm::SmallVector<SpirvInstruction *, 4> ips;
  7497. for (uint32_t i = 0; i < rowCount; ++i) {
  7498. auto *curRow =
  7499. spvBuilder.createCompositeExtract(colType, argInstr, {i}, loc);
  7500. auto *modf = spvBuilder.createGLSLExtInst(
  7501. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {curRow}, loc);
  7502. ips.push_back(
  7503. spvBuilder.createCompositeExtract(colType, modf, {1}, loc));
  7504. fracs.push_back(
  7505. spvBuilder.createCompositeExtract(colType, modf, {0}, loc));
  7506. }
  7507. SpirvInstruction *ip =
  7508. spvBuilder.createCompositeConstruct(argType, ips, loc);
  7509. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  7510. // because this is internal to the intrinsic function. So, in such a
  7511. // case we need to cast manually.
  7512. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  7513. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7514. processAssignment(ipArg, ip, false, nullptr);
  7515. return spvBuilder.createCompositeConstruct(returnType, fracs, loc);
  7516. }
  7517. }
  7518. emitError("invalid argument type passed to Modf intrinsic function",
  7519. callExpr->getExprLoc());
  7520. return nullptr;
  7521. }
  7522. SpirvInstruction *SpirvEmitter::processIntrinsicMad(const CallExpr *callExpr) {
  7523. // Signature is: ret mad(a,b,c)
  7524. // All of the above must be a scalar, vector, or matrix with the same
  7525. // component types. Component types can be float or int.
  7526. // The return value is equal to "a * b + c"
  7527. // In the case of float arguments, we can use the GLSL extended instruction
  7528. // set's Fma instruction with NoContraction decoration. In the case of integer
  7529. // arguments, we'll have to manually perform an OpIMul followed by an OpIAdd
  7530. // (We should also apply NoContraction decoration to these two instructions to
  7531. // get precise arithmetic).
  7532. // TODO: We currently don't propagate the NoContraction decoration.
  7533. const auto loc = callExpr->getLocStart();
  7534. const Expr *arg0 = callExpr->getArg(0);
  7535. const Expr *arg1 = callExpr->getArg(1);
  7536. const Expr *arg2 = callExpr->getArg(2);
  7537. // All arguments and the return type are the same.
  7538. const auto argType = arg0->getType();
  7539. auto *arg0Instr = doExpr(arg0);
  7540. auto *arg1Instr = doExpr(arg1);
  7541. auto *arg2Instr = doExpr(arg2);
  7542. auto arg0Loc = arg0->getLocStart();
  7543. auto arg1Loc = arg1->getLocStart();
  7544. auto arg2Loc = arg2->getLocStart();
  7545. // For floating point arguments, we can use the extended instruction set's Fma
  7546. // instruction. Sadly we can't simply call processIntrinsicUsingGLSLInst
  7547. // because we need to specifically decorate the Fma instruction with
  7548. // NoContraction decoration.
  7549. if (isFloatOrVecMatOfFloatType(argType)) {
  7550. // For matrix cases, operate on each row of the matrix.
  7551. if (isMxNMatrix(arg0->getType())) {
  7552. const auto actOnEachVec = [this, loc, arg1Instr, arg2Instr, arg1Loc,
  7553. arg2Loc](uint32_t index, QualType vecType,
  7554. SpirvInstruction *arg0Row) {
  7555. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Instr,
  7556. {index}, arg1Loc);
  7557. auto *arg2Row = spvBuilder.createCompositeExtract(vecType, arg2Instr,
  7558. {index}, arg2Loc);
  7559. auto *fma = spvBuilder.createGLSLExtInst(
  7560. vecType, GLSLstd450Fma, {arg0Row, arg1Row, arg2Row}, loc);
  7561. spvBuilder.decorateNoContraction(fma, loc);
  7562. return fma;
  7563. };
  7564. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  7565. }
  7566. // Non-matrix cases
  7567. auto *fma = spvBuilder.createGLSLExtInst(
  7568. argType, GLSLstd450Fma, {arg0Instr, arg1Instr, arg2Instr}, loc);
  7569. spvBuilder.decorateNoContraction(fma, loc);
  7570. return fma;
  7571. }
  7572. // For scalar and vector argument types.
  7573. {
  7574. if (isScalarType(argType) || isVectorType(argType)) {
  7575. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, argType, arg0Instr,
  7576. arg1Instr, loc);
  7577. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, argType, mul,
  7578. arg2Instr, loc);
  7579. spvBuilder.decorateNoContraction(mul, loc);
  7580. spvBuilder.decorateNoContraction(add, loc);
  7581. return add;
  7582. }
  7583. }
  7584. // For matrix argument types.
  7585. {
  7586. uint32_t rowCount = 0, colCount = 0;
  7587. QualType elemType = {};
  7588. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7589. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7590. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  7591. for (uint32_t i = 0; i < rowCount; ++i) {
  7592. auto *rowArg0 =
  7593. spvBuilder.createCompositeExtract(colType, arg0Instr, {i}, arg0Loc);
  7594. auto *rowArg1 =
  7595. spvBuilder.createCompositeExtract(colType, arg1Instr, {i}, arg1Loc);
  7596. auto *rowArg2 =
  7597. spvBuilder.createCompositeExtract(colType, arg2Instr, {i}, arg2Loc);
  7598. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, colType, rowArg0,
  7599. rowArg1, loc);
  7600. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, colType, mul,
  7601. rowArg2, loc);
  7602. spvBuilder.decorateNoContraction(mul, loc);
  7603. spvBuilder.decorateNoContraction(add, loc);
  7604. resultRows.push_back(add);
  7605. }
  7606. return spvBuilder.createCompositeConstruct(argType, resultRows, loc);
  7607. }
  7608. }
  7609. emitError("invalid argument type passed to mad intrinsic function",
  7610. callExpr->getExprLoc());
  7611. return 0;
  7612. }
  7613. SpirvInstruction *SpirvEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  7614. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  7615. //
  7616. // This function returns a lighting coefficient vector
  7617. // (ambient, diffuse, specular, 1) where:
  7618. // ambient = 1.
  7619. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  7620. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  7621. auto *nDotL = doExpr(callExpr->getArg(0));
  7622. auto *nDotH = doExpr(callExpr->getArg(1));
  7623. auto *m = doExpr(callExpr->getArg(2));
  7624. const auto loc = callExpr->getExprLoc();
  7625. const QualType floatType = astContext.FloatTy;
  7626. const QualType boolType = astContext.BoolTy;
  7627. SpirvInstruction *floatZero =
  7628. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  7629. SpirvInstruction *floatOne =
  7630. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f));
  7631. const QualType retType = callExpr->getType();
  7632. auto *diffuse = spvBuilder.createGLSLExtInst(
  7633. floatType, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL}, loc);
  7634. auto *min = spvBuilder.createGLSLExtInst(
  7635. floatType, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH}, loc);
  7636. auto *isNeg = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7637. min, floatZero, loc);
  7638. auto *mul =
  7639. spvBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m, loc);
  7640. auto *specular =
  7641. spvBuilder.createSelect(floatType, isNeg, floatZero, mul, loc);
  7642. return spvBuilder.createCompositeConstruct(
  7643. retType, {floatOne, diffuse, specular, floatOne}, callExpr->getLocEnd());
  7644. }
  7645. SpirvInstruction *
  7646. SpirvEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  7647. // Signature is: ret frexp(x, exp)
  7648. // [in] x: the input floating-point value.
  7649. // [out] exp: the calculated exponent.
  7650. // [out] ret: the calculated mantissa.
  7651. // All of the above must be a scalar, vector, or matrix of *float* type.
  7652. // The FrexpStruct SPIR-V instruction returns a struct. The first
  7653. // member is the significand (mantissa) and must be of the same type as the
  7654. // input parameter, and the second member is the exponent and must always be a
  7655. // scalar or vector of 32-bit *integer* type.
  7656. // FrexpStruct {
  7657. // <scalar or vector of int/float> mantissa;
  7658. // <scalar or vector of integers> exponent;
  7659. // }
  7660. const Expr *arg = callExpr->getArg(0);
  7661. const auto argType = arg->getType();
  7662. const auto returnType = callExpr->getType();
  7663. const auto loc = callExpr->getExprLoc();
  7664. auto *argInstr = doExpr(arg);
  7665. auto *expInstr = doExpr(callExpr->getArg(1));
  7666. // For scalar and vector argument types.
  7667. {
  7668. uint32_t elemCount = 1;
  7669. if (isScalarType(argType) || isVectorType(argType, nullptr, &elemCount)) {
  7670. const QualType expType =
  7671. elemCount == 1
  7672. ? astContext.IntTy
  7673. : astContext.getExtVectorType(astContext.IntTy, elemCount);
  7674. const auto *frexpStructType = spvContext.getHybridStructType(
  7675. {HybridStructType::FieldInfo(argType, "mantissa"),
  7676. HybridStructType::FieldInfo(expType, "exponent")},
  7677. "FrexpStructType");
  7678. auto *frexp = spvBuilder.createGLSLExtInst(
  7679. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {argInstr}, loc);
  7680. auto *exponentInt =
  7681. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7682. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7683. // expects a float, an conversion must take place before writing the
  7684. // results.
  7685. auto *exponentFloat = spvBuilder.createUnaryOp(
  7686. spv::Op::OpConvertSToF, returnType, exponentInt, loc);
  7687. spvBuilder.createStore(expInstr, exponentFloat, loc);
  7688. return spvBuilder.createCompositeExtract(argType, frexp, {0}, loc);
  7689. }
  7690. }
  7691. // For matrix argument types.
  7692. {
  7693. uint32_t rowCount = 0, colCount = 0;
  7694. if (isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  7695. const auto expType =
  7696. astContext.getExtVectorType(astContext.IntTy, colCount);
  7697. const auto colType =
  7698. astContext.getExtVectorType(astContext.FloatTy, colCount);
  7699. const auto *frexpStructType = spvContext.getHybridStructType(
  7700. {HybridStructType::FieldInfo(colType, "mantissa"),
  7701. HybridStructType::FieldInfo(expType, "exponent")},
  7702. "FrexpStructType");
  7703. llvm::SmallVector<SpirvInstruction *, 4> exponents;
  7704. llvm::SmallVector<SpirvInstruction *, 4> mantissas;
  7705. for (uint32_t i = 0; i < rowCount; ++i) {
  7706. auto *curRow = spvBuilder.createCompositeExtract(colType, argInstr, {i},
  7707. arg->getLocStart());
  7708. auto *frexp = spvBuilder.createGLSLExtInst(
  7709. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {curRow}, loc);
  7710. auto *exponentInt =
  7711. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7712. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7713. // expects a float, an conversion must take place before writing the
  7714. // results.
  7715. auto *exponentFloat = spvBuilder.createUnaryOp(
  7716. spv::Op::OpConvertSToF, colType, exponentInt, loc);
  7717. exponents.push_back(exponentFloat);
  7718. mantissas.push_back(
  7719. spvBuilder.createCompositeExtract(colType, frexp, {0}, loc));
  7720. }
  7721. auto *exponentsResult =
  7722. spvBuilder.createCompositeConstruct(returnType, exponents, loc);
  7723. spvBuilder.createStore(expInstr, exponentsResult, loc);
  7724. return spvBuilder.createCompositeConstruct(returnType, mantissas,
  7725. callExpr->getLocEnd());
  7726. }
  7727. }
  7728. emitError("invalid argument type passed to Frexp intrinsic function",
  7729. callExpr->getExprLoc());
  7730. return nullptr;
  7731. }
  7732. SpirvInstruction *
  7733. SpirvEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  7734. // Signature: ret ldexp(x, exp)
  7735. // This function uses the following formula: x * 2^exp.
  7736. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  7737. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  7738. // exponent. So we must calculate the result manually.
  7739. const Expr *x = callExpr->getArg(0);
  7740. const auto paramType = x->getType();
  7741. auto *xInstr = doExpr(x);
  7742. auto *expInstr = doExpr(callExpr->getArg(1));
  7743. const auto loc = callExpr->getLocStart();
  7744. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7745. // For scalar and vector argument types.
  7746. if (isScalarType(paramType) || isVectorType(paramType)) {
  7747. const auto twoExp = spvBuilder.createGLSLExtInst(
  7748. paramType, GLSLstd450::GLSLstd450Exp2, {expInstr}, loc);
  7749. return spvBuilder.createBinaryOp(spv::Op::OpFMul, paramType, xInstr, twoExp,
  7750. loc);
  7751. }
  7752. // For matrix argument types.
  7753. {
  7754. uint32_t rowCount = 0, colCount = 0;
  7755. if (isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  7756. const auto actOnEachVec = [this, loc, expInstr,
  7757. arg1Loc](uint32_t index, QualType vecType,
  7758. SpirvInstruction *xRowInstr) {
  7759. auto *expRowInstr = spvBuilder.createCompositeExtract(vecType, expInstr,
  7760. {index}, arg1Loc);
  7761. auto *twoExp = spvBuilder.createGLSLExtInst(
  7762. vecType, GLSLstd450::GLSLstd450Exp2, {expRowInstr}, loc);
  7763. return spvBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowInstr,
  7764. twoExp, loc);
  7765. };
  7766. return processEachVectorInMatrix(x, xInstr, actOnEachVec, loc);
  7767. }
  7768. }
  7769. emitError("invalid argument type passed to ldexp intrinsic function",
  7770. callExpr->getExprLoc());
  7771. return nullptr;
  7772. }
  7773. SpirvInstruction *SpirvEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  7774. // Signature is float4 dst(float4 src0, float4 src1)
  7775. // result.x = 1;
  7776. // result.y = src0.y * src1.y;
  7777. // result.z = src0.z;
  7778. // result.w = src1.w;
  7779. const QualType f32 = astContext.FloatTy;
  7780. auto *arg0Id = doExpr(callExpr->getArg(0));
  7781. auto *arg1Id = doExpr(callExpr->getArg(1));
  7782. auto arg0Loc = callExpr->getArg(0)->getLocStart();
  7783. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7784. auto *arg0y = spvBuilder.createCompositeExtract(f32, arg0Id, {1}, arg0Loc);
  7785. auto *arg1y = spvBuilder.createCompositeExtract(f32, arg1Id, {1}, arg1Loc);
  7786. auto *arg0z = spvBuilder.createCompositeExtract(f32, arg0Id, {2}, arg0Loc);
  7787. auto *arg1w = spvBuilder.createCompositeExtract(f32, arg1Id, {3}, arg1Loc);
  7788. auto loc = callExpr->getLocEnd();
  7789. auto *arg0yMularg1y =
  7790. spvBuilder.createBinaryOp(spv::Op::OpFMul, f32, arg0y, arg1y, loc);
  7791. return spvBuilder.createCompositeConstruct(
  7792. callExpr->getType(),
  7793. {spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f)),
  7794. arg0yMularg1y, arg0z, arg1w},
  7795. loc);
  7796. }
  7797. SpirvInstruction *SpirvEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  7798. // Discards the current pixel if the specified value is less than zero.
  7799. // TODO: If the argument can be const folded and evaluated, we could
  7800. // potentially avoid creating a branch. This would be a bit challenging for
  7801. // matrix/vector arguments.
  7802. assert(callExpr->getNumArgs() == 1u);
  7803. const Expr *arg = callExpr->getArg(0);
  7804. const auto loc = callExpr->getExprLoc();
  7805. const auto argType = arg->getType();
  7806. const auto boolType = astContext.BoolTy;
  7807. SpirvInstruction *condition = nullptr;
  7808. // Could not determine the argument as a constant. We need to branch based on
  7809. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  7810. // element of the vector/matrix is less than zero.
  7811. auto *argInstr = doExpr(arg);
  7812. QualType elemType = {};
  7813. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  7814. if (isScalarType(argType)) {
  7815. auto *zero = getValueZero(argType);
  7816. condition = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7817. argInstr, zero, loc);
  7818. } else if (isVectorType(argType, nullptr, &elemCount)) {
  7819. auto *zero = getValueZero(argType);
  7820. const QualType boolVecType =
  7821. astContext.getExtVectorType(boolType, elemCount);
  7822. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolVecType,
  7823. argInstr, zero, loc);
  7824. condition = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7825. } else if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7826. const auto floatVecType = astContext.getExtVectorType(elemType, colCount);
  7827. auto *elemZero = getValueZero(elemType);
  7828. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(colCount), elemZero);
  7829. auto *zero = spvBuilder.getConstantComposite(floatVecType, elements);
  7830. llvm::SmallVector<SpirvInstruction *, 4> cmpResults;
  7831. for (uint32_t i = 0; i < rowCount; ++i) {
  7832. auto *lhsVec =
  7833. spvBuilder.createCompositeExtract(floatVecType, argInstr, {i}, loc);
  7834. const auto boolColType = astContext.getExtVectorType(boolType, colCount);
  7835. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  7836. boolColType, lhsVec, zero, loc);
  7837. auto *any = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7838. cmpResults.push_back(any);
  7839. }
  7840. const auto boolRowType = astContext.getExtVectorType(boolType, rowCount);
  7841. auto *results =
  7842. spvBuilder.createCompositeConstruct(boolRowType, cmpResults, loc);
  7843. condition =
  7844. spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, results, loc);
  7845. } else {
  7846. emitError("invalid argument type passed to clip intrinsic function", loc);
  7847. return nullptr;
  7848. }
  7849. // Then we need to emit the instruction for the conditional branch.
  7850. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  7851. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  7852. // Create the branch instruction. This will end the current basic block.
  7853. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  7854. spvBuilder.addSuccessor(thenBB);
  7855. spvBuilder.addSuccessor(mergeBB);
  7856. spvBuilder.setMergeTarget(mergeBB);
  7857. // Handle the then branch
  7858. spvBuilder.setInsertPoint(thenBB);
  7859. spvBuilder.createKill(loc);
  7860. spvBuilder.addSuccessor(mergeBB);
  7861. // From now on, we'll emit instructions into the merge block.
  7862. spvBuilder.setInsertPoint(mergeBB);
  7863. return nullptr;
  7864. }
  7865. SpirvInstruction *
  7866. SpirvEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  7867. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  7868. // one may be int, uint, or float.
  7869. const QualType returnType = callExpr->getType();
  7870. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  7871. if (isFloatOrVecMatOfFloatType(returnType))
  7872. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  7873. else if (isSintOrVecMatOfSintType(returnType))
  7874. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  7875. // Get the function parameters. Expect 3 parameters.
  7876. assert(callExpr->getNumArgs() == 3u);
  7877. const Expr *argX = callExpr->getArg(0);
  7878. const Expr *argMin = callExpr->getArg(1);
  7879. const Expr *argMax = callExpr->getArg(2);
  7880. const auto loc = callExpr->getExprLoc();
  7881. auto *argXInstr = doExpr(argX);
  7882. auto *argMinInstr = doExpr(argMin);
  7883. auto *argMaxInstr = doExpr(argMax);
  7884. const auto argMinLoc = argMin->getLocStart();
  7885. const auto argMaxLoc = argMax->getLocStart();
  7886. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  7887. // the operation on each vector of the matrix.
  7888. if (isMxNMatrix(argX->getType())) {
  7889. const auto actOnEachVec =
  7890. [this, loc, glslOpcode, argMinInstr, argMaxInstr, argMinLoc, argMaxLoc](
  7891. uint32_t index, QualType vecType, SpirvInstruction *curRow) {
  7892. auto *minRowInstr = spvBuilder.createCompositeExtract(
  7893. vecType, argMinInstr, {index}, argMinLoc);
  7894. auto *maxRowInstr = spvBuilder.createCompositeExtract(
  7895. vecType, argMaxInstr, {index}, argMaxLoc);
  7896. return spvBuilder.createGLSLExtInst(
  7897. vecType, glslOpcode, {curRow, minRowInstr, maxRowInstr}, loc);
  7898. };
  7899. return processEachVectorInMatrix(argX, argXInstr, actOnEachVec, loc);
  7900. }
  7901. return spvBuilder.createGLSLExtInst(
  7902. returnType, glslOpcode, {argXInstr, argMinInstr, argMaxInstr}, loc);
  7903. }
  7904. SpirvInstruction *
  7905. SpirvEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  7906. bool isDevice, bool groupSync,
  7907. bool isAllBarrier) {
  7908. // * DeviceMemoryBarrier =
  7909. // OpMemoryBarrier (memScope=Device,
  7910. // sem=Image|Uniform|AcquireRelease)
  7911. //
  7912. // * DeviceMemoryBarrierWithGroupSync =
  7913. // OpControlBarrier(execScope = Workgroup,
  7914. // memScope=Device,
  7915. // sem=Image|Uniform|AcquireRelease)
  7916. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  7917. spv::MemorySemanticsMask::ImageMemory |
  7918. spv::MemorySemanticsMask::UniformMemory |
  7919. spv::MemorySemanticsMask::AcquireRelease;
  7920. // * GroupMemoryBarrier =
  7921. // OpMemoryBarrier (memScope=Workgroup,
  7922. // sem = Workgroup|AcquireRelease)
  7923. //
  7924. // * GroupMemoryBarrierWithGroupSync =
  7925. // OpControlBarrier (execScope = Workgroup,
  7926. // memScope = Workgroup,
  7927. // sem = Workgroup|AcquireRelease)
  7928. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  7929. spv::MemorySemanticsMask::WorkgroupMemory |
  7930. spv::MemorySemanticsMask::AcquireRelease;
  7931. // * AllMemoryBarrier =
  7932. // OpMemoryBarrier(memScope = Device,
  7933. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7934. //
  7935. // * AllMemoryBarrierWithGroupSync =
  7936. // OpControlBarrier(execScope = Workgroup,
  7937. // memScope = Device,
  7938. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7939. const spv::MemorySemanticsMask allMemoryBarrierSema =
  7940. spv::MemorySemanticsMask::ImageMemory |
  7941. spv::MemorySemanticsMask::UniformMemory |
  7942. spv::MemorySemanticsMask::WorkgroupMemory |
  7943. spv::MemorySemanticsMask::AcquireRelease;
  7944. // Get <result-id> for execution scope.
  7945. // If present, execution scope is always Workgroup!
  7946. llvm::Optional<spv::Scope> execScope = llvm::None;
  7947. if (groupSync) {
  7948. execScope = spv::Scope::Workgroup;
  7949. }
  7950. // Get <result-id> for memory scope
  7951. const spv::Scope memScope =
  7952. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  7953. // Get <result-id> for memory semantics
  7954. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  7955. : isDevice ? deviceMemoryBarrierSema
  7956. : groupMemoryBarrierSema;
  7957. spvBuilder.createBarrier(memScope, memSemaMask, execScope,
  7958. callExpr->getExprLoc());
  7959. return nullptr;
  7960. }
  7961. SpirvInstruction *SpirvEmitter::processNonFpMatrixTranspose(
  7962. QualType matType, SpirvInstruction *matrix, SourceLocation loc) {
  7963. // Simplest way is to flatten the matrix construct a new matrix from the
  7964. // flattened elements. (for a mat4x4).
  7965. QualType elemType = {};
  7966. uint32_t numRows = 0, numCols = 0;
  7967. const bool isMat = isMxNMatrix(matType, &elemType, &numRows, &numCols);
  7968. assert(isMat && !elemType->isFloatingType());
  7969. (void)isMat;
  7970. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  7971. // You cannot perform a composite construct of an array using a few vectors.
  7972. // The number of constutients passed to OpCompositeConstruct must be equal to
  7973. // the number of array elements.
  7974. llvm::SmallVector<SpirvInstruction *, 4> elems;
  7975. for (uint32_t i = 0; i < numRows; ++i)
  7976. for (uint32_t j = 0; j < numCols; ++j)
  7977. elems.push_back(
  7978. spvBuilder.createCompositeExtract(elemType, matrix, {i, j}, loc));
  7979. llvm::SmallVector<SpirvInstruction *, 4> cols;
  7980. for (uint32_t i = 0; i < numCols; ++i) {
  7981. // The elements in the ith vector of the "transposed" array are at offset i,
  7982. // i + <original-vector-size>, ...
  7983. llvm::SmallVector<SpirvInstruction *, 4> indexes;
  7984. for (uint32_t j = 0; j < numRows; ++j)
  7985. indexes.push_back(elems[i + (j * numCols)]);
  7986. cols.push_back(
  7987. spvBuilder.createCompositeConstruct(colQualType, indexes, loc));
  7988. }
  7989. auto transposeType = astContext.getConstantArrayType(
  7990. colQualType, llvm::APInt(32, numCols), clang::ArrayType::Normal, 0);
  7991. return spvBuilder.createCompositeConstruct(transposeType, cols, loc);
  7992. }
  7993. SpirvInstruction *SpirvEmitter::processNonFpDot(SpirvInstruction *vec1Id,
  7994. SpirvInstruction *vec2Id,
  7995. uint32_t vecSize,
  7996. QualType elemType,
  7997. SourceLocation loc) {
  7998. llvm::SmallVector<SpirvInstruction *, 4> muls;
  7999. for (uint32_t i = 0; i < vecSize; ++i) {
  8000. auto *elem1 = spvBuilder.createCompositeExtract(elemType, vec1Id, {i}, loc);
  8001. auto *elem2 = spvBuilder.createCompositeExtract(elemType, vec2Id, {i}, loc);
  8002. muls.push_back(spvBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  8003. elemType, elem1, elem2, loc));
  8004. }
  8005. SpirvInstruction *sum = muls[0];
  8006. for (uint32_t i = 1; i < vecSize; ++i) {
  8007. sum = spvBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemType,
  8008. sum, muls[i], loc);
  8009. }
  8010. return sum;
  8011. }
  8012. SpirvInstruction *SpirvEmitter::processNonFpScalarTimesMatrix(
  8013. QualType scalarType, SpirvInstruction *scalar, QualType matrixType,
  8014. SpirvInstruction *matrix, SourceLocation loc) {
  8015. assert(isScalarType(scalarType));
  8016. QualType elemType = {};
  8017. uint32_t numRows = 0, numCols = 0;
  8018. const bool isMat = isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  8019. assert(isMat);
  8020. assert(isSameType(astContext, scalarType, elemType));
  8021. (void)isMat;
  8022. // We need to multiply the scalar by each vector of the matrix.
  8023. // The front-end guarantees that the scalar and matrix element type are
  8024. // the same. For example, if the scalar is a float, the matrix is casted
  8025. // to a float matrix before being passed to mul(). It is also guaranteed
  8026. // that types such as bool are casted to float or int before being
  8027. // passed to mul().
  8028. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  8029. llvm::SmallVector<SpirvInstruction *, 4> splat(size_t(numCols), scalar);
  8030. auto *scalarSplat = spvBuilder.createCompositeConstruct(rowType, splat, loc);
  8031. llvm::SmallVector<SpirvInstruction *, 4> mulRows;
  8032. for (uint32_t row = 0; row < numRows; ++row) {
  8033. auto *rowInstr =
  8034. spvBuilder.createCompositeExtract(rowType, matrix, {row}, loc);
  8035. mulRows.push_back(spvBuilder.createBinaryOp(
  8036. translateOp(BO_Mul, scalarType), rowType, rowInstr, scalarSplat, loc));
  8037. }
  8038. return spvBuilder.createCompositeConstruct(matrixType, mulRows, loc);
  8039. }
  8040. SpirvInstruction *SpirvEmitter::processNonFpVectorTimesMatrix(
  8041. QualType vecType, SpirvInstruction *vector, QualType matType,
  8042. SpirvInstruction *matrix, SourceLocation loc,
  8043. SpirvInstruction *matrixTranspose) {
  8044. // This function assumes that the vector element type and matrix elemet type
  8045. // are the same.
  8046. QualType vecElemType = {}, matElemType = {};
  8047. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  8048. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  8049. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  8050. assert(isSameType(astContext, vecElemType, matElemType));
  8051. assert(isVec);
  8052. assert(isMat);
  8053. assert(vecSize == numRows);
  8054. (void)isVec;
  8055. (void)isMat;
  8056. // When processing vector times matrix, the vector is a row vector, and it
  8057. // should be multiplied by the matrix *columns*. The most efficient way to
  8058. // handle this in SPIR-V would be to first transpose the matrix, and then use
  8059. // OpAccessChain.
  8060. if (!matrixTranspose)
  8061. matrixTranspose = processNonFpMatrixTranspose(matType, matrix, loc);
  8062. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  8063. for (uint32_t col = 0; col < numCols; ++col) {
  8064. auto *colInstr =
  8065. spvBuilder.createCompositeExtract(vecType, matrixTranspose, {col}, loc);
  8066. resultElems.push_back(
  8067. processNonFpDot(vector, colInstr, vecSize, vecElemType, loc));
  8068. }
  8069. return spvBuilder.createCompositeConstruct(
  8070. astContext.getExtVectorType(vecElemType, numCols), resultElems, loc);
  8071. }
  8072. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesVector(
  8073. QualType matType, SpirvInstruction *matrix, QualType vecType,
  8074. SpirvInstruction *vector, SourceLocation loc) {
  8075. // This function assumes that the vector element type and matrix elemet type
  8076. // are the same.
  8077. QualType vecElemType = {}, matElemType = {};
  8078. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  8079. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  8080. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  8081. assert(isSameType(astContext, vecElemType, matElemType));
  8082. assert(isVec);
  8083. assert(isMat);
  8084. assert(vecSize == numCols);
  8085. (void)isVec;
  8086. (void)isMat;
  8087. // When processing matrix times vector, the vector is a column vector. So we
  8088. // simply get each row of the matrix and perform a dot product with the
  8089. // vector.
  8090. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  8091. for (uint32_t row = 0; row < numRows; ++row) {
  8092. auto *rowInstr =
  8093. spvBuilder.createCompositeExtract(vecType, matrix, {row}, loc);
  8094. resultElems.push_back(
  8095. processNonFpDot(rowInstr, vector, vecSize, vecElemType, loc));
  8096. }
  8097. return spvBuilder.createCompositeConstruct(
  8098. astContext.getExtVectorType(vecElemType, numRows), resultElems, loc);
  8099. }
  8100. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesMatrix(
  8101. QualType lhsType, SpirvInstruction *lhs, QualType rhsType,
  8102. SpirvInstruction *rhs, SourceLocation loc) {
  8103. // This function assumes that the vector element type and matrix elemet type
  8104. // are the same.
  8105. QualType lhsElemType = {}, rhsElemType = {};
  8106. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  8107. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  8108. const bool lhsIsMat =
  8109. isMxNMatrix(lhsType, &lhsElemType, &lhsNumRows, &lhsNumCols);
  8110. const bool rhsIsMat =
  8111. isMxNMatrix(rhsType, &rhsElemType, &rhsNumRows, &rhsNumCols);
  8112. assert(isSameType(astContext, lhsElemType, rhsElemType));
  8113. assert(lhsIsMat && rhsIsMat);
  8114. assert(lhsNumCols == rhsNumRows);
  8115. (void)rhsIsMat;
  8116. (void)lhsIsMat;
  8117. auto *rhsTranspose = processNonFpMatrixTranspose(rhsType, rhs, loc);
  8118. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  8119. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  8120. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  8121. auto *rowInstr =
  8122. spvBuilder.createCompositeExtract(vecType, lhs, {row}, loc);
  8123. resultRows.push_back(processNonFpVectorTimesMatrix(
  8124. vecType, rowInstr, rhsType, rhs, loc, rhsTranspose));
  8125. }
  8126. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  8127. const auto resultColType =
  8128. astContext.getExtVectorType(lhsElemType, rhsNumCols);
  8129. const auto resultType = astContext.getConstantArrayType(
  8130. resultColType, llvm::APInt(32, lhsNumRows), clang::ArrayType::Normal, 0);
  8131. return spvBuilder.createCompositeConstruct(resultType, resultRows, loc);
  8132. }
  8133. SpirvInstruction *SpirvEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  8134. const QualType returnType = callExpr->getType();
  8135. // Get the function parameters. Expect 2 parameters.
  8136. assert(callExpr->getNumArgs() == 2u);
  8137. const Expr *arg0 = callExpr->getArg(0);
  8138. const Expr *arg1 = callExpr->getArg(1);
  8139. const QualType arg0Type = arg0->getType();
  8140. const QualType arg1Type = arg1->getType();
  8141. auto loc = callExpr->getExprLoc();
  8142. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  8143. // vector, or matrix. The frontend ensures that the two arguments have the
  8144. // same component type. The only allowed component types are int and float.
  8145. // mul(scalar, vector)
  8146. {
  8147. uint32_t elemCount = 0;
  8148. if (isScalarType(arg0Type) && isVectorType(arg1Type, nullptr, &elemCount)) {
  8149. auto *arg1Id = doExpr(arg1);
  8150. // We can use OpVectorTimesScalar if arguments are floats.
  8151. if (arg0Type->isFloatingType())
  8152. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  8153. returnType, arg1Id, doExpr(arg0), loc);
  8154. // Use OpIMul for integers
  8155. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType,
  8156. createVectorSplat(arg0, elemCount),
  8157. arg1Id, loc);
  8158. }
  8159. }
  8160. // mul(vector, scalar)
  8161. {
  8162. uint32_t elemCount = 0;
  8163. if (isVectorType(arg0Type, nullptr, &elemCount) && isScalarType(arg1Type)) {
  8164. auto *arg0Id = doExpr(arg0);
  8165. // We can use OpVectorTimesScalar if arguments are floats.
  8166. if (arg1Type->isFloatingType())
  8167. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  8168. returnType, arg0Id, doExpr(arg1), loc);
  8169. // Use OpIMul for integers
  8170. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType, arg0Id,
  8171. createVectorSplat(arg1, elemCount), loc);
  8172. }
  8173. }
  8174. // mul(vector, vector)
  8175. if (isVectorType(arg0Type) && isVectorType(arg1Type)) {
  8176. // mul( Mat(1xM), Mat(Mx1) ) results in a scalar (same as dot product)
  8177. if (isScalarType(returnType)) {
  8178. return processIntrinsicDot(callExpr);
  8179. }
  8180. // mul( Mat(Mx1), Mat(1xN) ) results in a MxN matrix.
  8181. QualType elemType = {};
  8182. uint32_t numRows = 0;
  8183. if (isMxNMatrix(returnType, &elemType, &numRows)) {
  8184. llvm::SmallVector<SpirvInstruction *, 4> rows;
  8185. auto *arg0Id = doExpr(arg0);
  8186. auto *arg1Id = doExpr(arg1);
  8187. for (uint32_t i = 0; i < numRows; ++i) {
  8188. auto *scalar =
  8189. spvBuilder.createCompositeExtract(elemType, arg0Id, {i}, loc);
  8190. rows.push_back(spvBuilder.createBinaryOp(
  8191. spv::Op::OpVectorTimesScalar, arg1Type, arg1Id, scalar, loc));
  8192. }
  8193. return spvBuilder.createCompositeConstruct(returnType, rows, loc);
  8194. }
  8195. llvm_unreachable("bad arguments passed to mul");
  8196. }
  8197. // All the following cases require handling arg0 and arg1 expressions first.
  8198. auto *arg0Id = doExpr(arg0);
  8199. auto *arg1Id = doExpr(arg1);
  8200. // mul(scalar, scalar)
  8201. if (isScalarType(arg0Type) && isScalarType(arg1Type))
  8202. return spvBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type), returnType,
  8203. arg0Id, arg1Id, loc);
  8204. // mul(scalar, matrix)
  8205. {
  8206. QualType elemType = {};
  8207. if (isScalarType(arg0Type) && isMxNMatrix(arg1Type, &elemType)) {
  8208. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  8209. // and the scalar type are float.
  8210. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  8211. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  8212. returnType, arg1Id, arg0Id, loc);
  8213. else
  8214. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  8215. callExpr->getExprLoc());
  8216. }
  8217. }
  8218. // mul(matrix, scalar)
  8219. {
  8220. QualType elemType = {};
  8221. if (isScalarType(arg1Type) && isMxNMatrix(arg0Type, &elemType)) {
  8222. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  8223. // and the scalar type are float.
  8224. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  8225. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  8226. returnType, arg0Id, arg1Id, loc);
  8227. else
  8228. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type, arg0Id,
  8229. callExpr->getExprLoc());
  8230. }
  8231. }
  8232. // mul(vector, matrix)
  8233. {
  8234. QualType vecElemType = {}, matElemType = {};
  8235. uint32_t elemCount = 0, numRows = 0;
  8236. if (isVectorType(arg0Type, &vecElemType, &elemCount) &&
  8237. isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  8238. assert(elemCount == numRows);
  8239. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  8240. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  8241. returnType, arg1Id, arg0Id, loc);
  8242. else
  8243. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  8244. callExpr->getExprLoc());
  8245. }
  8246. }
  8247. // mul(matrix, vector)
  8248. {
  8249. QualType vecElemType = {}, matElemType = {};
  8250. uint32_t elemCount = 0, numCols = 0;
  8251. if (isMxNMatrix(arg0Type, &matElemType, nullptr, &numCols) &&
  8252. isVectorType(arg1Type, &vecElemType, &elemCount)) {
  8253. assert(elemCount == numCols);
  8254. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  8255. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  8256. returnType, arg1Id, arg0Id, loc);
  8257. else
  8258. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type, arg1Id,
  8259. callExpr->getExprLoc());
  8260. }
  8261. }
  8262. // mul(matrix, matrix)
  8263. {
  8264. // The front-end ensures that the two matrix element types match.
  8265. QualType elemType = {};
  8266. uint32_t lhsCols = 0, rhsRows = 0;
  8267. if (isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  8268. isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  8269. assert(lhsCols == rhsRows);
  8270. if (elemType->isFloatingType())
  8271. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  8272. returnType, arg1Id, arg0Id, loc);
  8273. else
  8274. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  8275. callExpr->getExprLoc());
  8276. }
  8277. }
  8278. emitError("invalid argument type passed to mul intrinsic function",
  8279. callExpr->getExprLoc());
  8280. return nullptr;
  8281. }
  8282. SpirvInstruction *
  8283. SpirvEmitter::processIntrinsicPrintf(const CallExpr *callExpr) {
  8284. // C99, s6.5.2.2/6: "If the expression that denotes the called function has a
  8285. // type that does not include a prototype, the integer promotions are
  8286. // performed on each argument, and arguments that have type float are promoted
  8287. // to double. These are called the default argument promotions."
  8288. // C++: All the variadic parameters undergo default promotions before they're
  8289. // received by the function.
  8290. //
  8291. // Therefore by default floating point arguments will be evaluated as double
  8292. // by this function.
  8293. //
  8294. // TODO: We may want to change this behavior for SPIR-V.
  8295. const auto returnType = callExpr->getType();
  8296. const auto numArgs = callExpr->getNumArgs();
  8297. const auto loc = callExpr->getExprLoc();
  8298. assert(numArgs >= 1u);
  8299. llvm::SmallVector<SpirvInstruction *, 4> args;
  8300. for (uint32_t argIndex = 0; argIndex < numArgs; ++argIndex)
  8301. args.push_back(doExpr(callExpr->getArg(argIndex)));
  8302. return spvBuilder.createNonSemanticDebugPrintfExtInst(
  8303. returnType, NonSemanticDebugPrintfDebugPrintf, args, loc);
  8304. }
  8305. SpirvInstruction *SpirvEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  8306. // Get the function parameters. Expect 2 vectors as parameters.
  8307. assert(callExpr->getNumArgs() == 2u);
  8308. const Expr *arg0 = callExpr->getArg(0);
  8309. const Expr *arg1 = callExpr->getArg(1);
  8310. auto *arg0Id = doExpr(arg0);
  8311. auto *arg1Id = doExpr(arg1);
  8312. QualType arg0Type = arg0->getType();
  8313. QualType arg1Type = arg1->getType();
  8314. uint32_t vec0Size = 0, vec1Size = 0;
  8315. QualType vec0ComponentType = {}, vec1ComponentType = {};
  8316. QualType returnType = {};
  8317. const bool arg0isScalarOrVec =
  8318. isScalarOrVectorType(arg0Type, &vec0ComponentType, &vec0Size);
  8319. const bool arg1isScalarOrVec =
  8320. isScalarOrVectorType(arg1Type, &vec1ComponentType, &vec1Size);
  8321. const bool returnIsScalar = isScalarType(callExpr->getType(), &returnType);
  8322. // Each argument should either be a vector or a scalar
  8323. assert(arg0isScalarOrVec && arg1isScalarOrVec);
  8324. // The result type must be a scalar.
  8325. assert(returnIsScalar);
  8326. // The element type of each argument and the return type must be the same.
  8327. assert(returnType == vec1ComponentType);
  8328. assert(vec0ComponentType == vec1ComponentType);
  8329. // The size of the two arguments must be equal.
  8330. assert(vec0Size == vec1Size);
  8331. // Acceptable vector sizes are 1,2,3,4.
  8332. assert(vec0Size >= 1 && vec0Size <= 4);
  8333. (void)arg0isScalarOrVec;
  8334. (void)arg1isScalarOrVec;
  8335. (void)returnIsScalar;
  8336. (void)vec0ComponentType;
  8337. (void)vec1ComponentType;
  8338. (void)vec1Size;
  8339. auto loc = callExpr->getLocStart();
  8340. // According to HLSL reference, the dot function only works on integers
  8341. // and floats.
  8342. assert(returnType->isFloatingType() || returnType->isIntegerType());
  8343. // Special case: dot product of two vectors, each of size 1. That is
  8344. // basically the same as regular multiplication of 2 scalars.
  8345. if (vec0Size == 1) {
  8346. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  8347. return spvBuilder.createBinaryOp(spvOp, returnType, arg0Id, arg1Id, loc);
  8348. }
  8349. // If the vectors are of type Float, we can use OpDot.
  8350. if (returnType->isFloatingType()) {
  8351. return spvBuilder.createBinaryOp(spv::Op::OpDot, returnType, arg0Id, arg1Id,
  8352. loc);
  8353. }
  8354. // Vector component type is Integer (signed or unsigned).
  8355. // Create all instructions necessary to perform a dot product on
  8356. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  8357. // Therefore, we use other SPIR-V instructions (addition and
  8358. // multiplication).
  8359. else {
  8360. SpirvInstruction *result = nullptr;
  8361. llvm::SmallVector<SpirvInstruction *, 4> multIds;
  8362. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  8363. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  8364. // Extract members from the two vectors and multiply them.
  8365. for (unsigned int i = 0; i < vec0Size; ++i) {
  8366. auto *vec0member = spvBuilder.createCompositeExtract(
  8367. returnType, arg0Id, {i}, arg0->getLocStart());
  8368. auto *vec1member = spvBuilder.createCompositeExtract(
  8369. returnType, arg1Id, {i}, arg1->getLocStart());
  8370. auto *multId = spvBuilder.createBinaryOp(multSpvOp, returnType,
  8371. vec0member, vec1member, loc);
  8372. multIds.push_back(multId);
  8373. }
  8374. // Add all the multiplications.
  8375. result = multIds[0];
  8376. for (unsigned int i = 1; i < vec0Size; ++i) {
  8377. auto *additionId = spvBuilder.createBinaryOp(addSpvOp, returnType, result,
  8378. multIds[i], loc);
  8379. result = additionId;
  8380. }
  8381. return result;
  8382. }
  8383. }
  8384. SpirvInstruction *SpirvEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  8385. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  8386. // float or double.
  8387. assert(callExpr->getNumArgs() == 1u);
  8388. const QualType returnType = callExpr->getType();
  8389. const Expr *arg = callExpr->getArg(0);
  8390. auto *argId = doExpr(arg);
  8391. const QualType argType = arg->getType();
  8392. auto loc = callExpr->getLocStart();
  8393. // For cases with matrix argument.
  8394. QualType elemType = {};
  8395. uint32_t numRows = 0, numCols = 0;
  8396. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  8397. auto *vecOne = getVecValueOne(elemType, numCols);
  8398. const auto actOnEachVec = [this, vecOne, loc](uint32_t /*index*/,
  8399. QualType vecType,
  8400. SpirvInstruction *curRow) {
  8401. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne, curRow,
  8402. loc);
  8403. };
  8404. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8405. }
  8406. // For cases with scalar or vector arguments.
  8407. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, returnType,
  8408. getValueOne(argType), argId, loc);
  8409. }
  8410. SpirvInstruction *
  8411. SpirvEmitter::processIntrinsicReadClock(const CallExpr *callExpr) {
  8412. auto *scope = doExpr(callExpr->getArg(0));
  8413. assert(scope->getAstResultType()->isIntegerType());
  8414. return spvBuilder.createReadClock(scope, callExpr->getExprLoc());
  8415. }
  8416. SpirvInstruction *
  8417. SpirvEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  8418. spv::Op spvOp) {
  8419. // 'all' and 'any' take only 1 parameter.
  8420. assert(callExpr->getNumArgs() == 1u);
  8421. const QualType returnType = callExpr->getType();
  8422. const Expr *arg = callExpr->getArg(0);
  8423. const QualType argType = arg->getType();
  8424. const auto loc = callExpr->getExprLoc();
  8425. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  8426. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  8427. {
  8428. QualType scalarType = {};
  8429. if (isScalarType(argType, &scalarType) &&
  8430. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  8431. scalarType->isIntegerType()))
  8432. return castToBool(doExpr(arg), argType, returnType, loc);
  8433. }
  8434. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  8435. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  8436. {
  8437. QualType elemType = {};
  8438. uint32_t size = 0;
  8439. if (isVectorType(argType, &elemType, &size)) {
  8440. const QualType castToBoolType =
  8441. astContext.getExtVectorType(returnType, size);
  8442. auto *castedToBool =
  8443. castToBool(doExpr(arg), argType, castToBoolType, loc);
  8444. return spvBuilder.createUnaryOp(spvOp, returnType, castedToBool, loc);
  8445. }
  8446. }
  8447. // Handle MxN matrices as arguments.
  8448. {
  8449. QualType elemType = {};
  8450. uint32_t matRowCount = 0, matColCount = 0;
  8451. if (isMxNMatrix(argType, &elemType, &matRowCount, &matColCount)) {
  8452. auto *matrix = doExpr(arg);
  8453. const QualType vecType = getComponentVectorType(astContext, argType);
  8454. llvm::SmallVector<SpirvInstruction *, 4> rowResults;
  8455. for (uint32_t i = 0; i < matRowCount; ++i) {
  8456. // Extract the row which is a float vector of size matColCount.
  8457. auto *rowFloatVec = spvBuilder.createCompositeExtract(
  8458. vecType, matrix, {i}, arg->getLocStart());
  8459. // Cast the float vector to boolean vector.
  8460. const auto rowFloatQualType =
  8461. astContext.getExtVectorType(elemType, matColCount);
  8462. const auto rowBoolQualType =
  8463. astContext.getExtVectorType(returnType, matColCount);
  8464. auto *rowBoolVec = castToBool(rowFloatVec, rowFloatQualType,
  8465. rowBoolQualType, arg->getLocStart());
  8466. // Perform OpAny/OpAll on the boolean vector.
  8467. rowResults.push_back(
  8468. spvBuilder.createUnaryOp(spvOp, returnType, rowBoolVec, loc));
  8469. }
  8470. // Create a new vector that is the concatenation of results of all rows.
  8471. const QualType vecOfBools =
  8472. astContext.getExtVectorType(astContext.BoolTy, matRowCount);
  8473. auto *row =
  8474. spvBuilder.createCompositeConstruct(vecOfBools, rowResults, loc);
  8475. // Run OpAny/OpAll on the newly-created vector.
  8476. return spvBuilder.createUnaryOp(spvOp, returnType, row, loc);
  8477. }
  8478. }
  8479. // All types should be handled already.
  8480. llvm_unreachable("Unknown argument type passed to all()/any().");
  8481. return nullptr;
  8482. }
  8483. SpirvInstruction *
  8484. SpirvEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  8485. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  8486. // Method 1: ret asint(arg)
  8487. // arg component type = {float, uint}
  8488. // arg template type = {scalar, vector, matrix}
  8489. // ret template type = same as arg template type.
  8490. // ret component type = int
  8491. // Method 2: ret asuint(arg)
  8492. // arg component type = {float, int}
  8493. // arg template type = {scalar, vector, matrix}
  8494. // ret template type = same as arg template type.
  8495. // ret component type = uint
  8496. // Method 3: ret asfloat(arg)
  8497. // arg component type = {float, uint, int}
  8498. // arg template type = {scalar, vector, matrix}
  8499. // ret template type = same as arg template type.
  8500. // ret component type = float
  8501. // Method 4: double asdouble(uint lowbits, uint highbits)
  8502. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  8503. // Method 6:
  8504. // void asuint(
  8505. // in double value,
  8506. // out uint lowbits,
  8507. // out uint highbits
  8508. // );
  8509. const QualType returnType = callExpr->getType();
  8510. const uint32_t numArgs = callExpr->getNumArgs();
  8511. const Expr *arg0 = callExpr->getArg(0);
  8512. const QualType argType = arg0->getType();
  8513. const auto loc = callExpr->getExprLoc();
  8514. // Method 3 return type may be the same as arg type, so it would be a no-op.
  8515. if (isSameType(astContext, returnType, argType))
  8516. return doExpr(arg0);
  8517. switch (numArgs) {
  8518. case 1: {
  8519. // Handling Method 1, 2, and 3.
  8520. auto *argInstr = doExpr(arg0);
  8521. QualType fromElemType = {};
  8522. uint32_t numRows = 0, numCols = 0;
  8523. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  8524. if (!isMxNMatrix(argType, &fromElemType, &numRows, &numCols)) {
  8525. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, returnType, argInstr,
  8526. loc);
  8527. }
  8528. // Input or output type is a matrix.
  8529. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  8530. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  8531. const auto fromVecType = astContext.getExtVectorType(fromElemType, numCols);
  8532. const auto toVecType = astContext.getExtVectorType(toElemType, numCols);
  8533. for (uint32_t row = 0; row < numRows; ++row) {
  8534. auto *rowInstr = spvBuilder.createCompositeExtract(
  8535. fromVecType, argInstr, {row}, arg0->getLocStart());
  8536. castedRows.push_back(spvBuilder.createUnaryOp(spv::Op::OpBitcast,
  8537. toVecType, rowInstr, loc));
  8538. }
  8539. return spvBuilder.createCompositeConstruct(returnType, castedRows, loc);
  8540. }
  8541. case 2: {
  8542. auto *lowbits = doExpr(arg0);
  8543. auto *highbits = doExpr(callExpr->getArg(1));
  8544. const auto uintType = astContext.UnsignedIntTy;
  8545. const auto doubleType = astContext.DoubleTy;
  8546. // Handling Method 4
  8547. if (argType->isUnsignedIntegerType()) {
  8548. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8549. auto *operand = spvBuilder.createCompositeConstruct(
  8550. uintVec2Type, {lowbits, highbits}, loc);
  8551. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand,
  8552. loc);
  8553. }
  8554. // Handling Method 5
  8555. else {
  8556. const auto uintVec4Type = astContext.getExtVectorType(uintType, 4);
  8557. const auto doubleVec2Type = astContext.getExtVectorType(doubleType, 2);
  8558. auto *operand = spvBuilder.createVectorShuffle(
  8559. uintVec4Type, lowbits, highbits, {0, 2, 1, 3}, loc);
  8560. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  8561. operand, loc);
  8562. }
  8563. }
  8564. case 3: {
  8565. // Handling Method 6.
  8566. auto *value = doExpr(arg0);
  8567. auto *lowbits = doExpr(callExpr->getArg(1));
  8568. auto *highbits = doExpr(callExpr->getArg(2));
  8569. const auto uintType = astContext.UnsignedIntTy;
  8570. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8571. auto *vecResult =
  8572. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value, loc);
  8573. spvBuilder.createStore(lowbits,
  8574. spvBuilder.createCompositeExtract(
  8575. uintType, vecResult, {0}, arg0->getLocStart()),
  8576. loc);
  8577. spvBuilder.createStore(highbits,
  8578. spvBuilder.createCompositeExtract(
  8579. uintType, vecResult, {1}, arg0->getLocStart()),
  8580. loc);
  8581. return nullptr;
  8582. }
  8583. default:
  8584. emitError("unrecognized signature for %0 intrinsic function", loc)
  8585. << callExpr->getDirectCallee()->getName();
  8586. return nullptr;
  8587. }
  8588. }
  8589. SpirvInstruction *
  8590. SpirvEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  8591. // Should take a float4 and return an int4 by doing:
  8592. // int4 result = input.zyxw * 255.001953;
  8593. // Maximum float precision makes the scaling factor 255.002.
  8594. const auto arg = callExpr->getArg(0);
  8595. auto *argId = doExpr(arg);
  8596. const auto argType = arg->getType();
  8597. auto loc = callExpr->getLocStart();
  8598. auto *swizzle =
  8599. spvBuilder.createVectorShuffle(argType, argId, argId, {2, 1, 0, 3}, loc);
  8600. auto *scaled = spvBuilder.createBinaryOp(
  8601. spv::Op::OpVectorTimesScalar, argType, swizzle,
  8602. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(255.002f)),
  8603. loc);
  8604. return castToInt(scaled, arg->getType(), callExpr->getType(), loc);
  8605. }
  8606. SpirvInstruction *
  8607. SpirvEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  8608. // Since OpIsFinite needs the Kernel capability, translation is instead done
  8609. // using OpIsNan and OpIsInf:
  8610. // isFinite = !(isNan || isInf)
  8611. const auto arg = doExpr(callExpr->getArg(0));
  8612. const auto returnType = callExpr->getType();
  8613. const auto loc = callExpr->getExprLoc();
  8614. const auto isNan =
  8615. spvBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg, loc);
  8616. const auto isInf =
  8617. spvBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg, loc);
  8618. const auto isNanOrInf = spvBuilder.createBinaryOp(
  8619. spv::Op::OpLogicalOr, returnType, isNan, isInf, loc);
  8620. return spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType, isNanOrInf,
  8621. loc);
  8622. }
  8623. SpirvInstruction *
  8624. SpirvEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  8625. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  8626. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  8627. CallExpr *sincosExpr =
  8628. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  8629. sincosExpr->setType(callExpr->getArg(0)->getType());
  8630. sincosExpr->setNumArgs(astContext, 1);
  8631. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  8632. const auto srcLoc = callExpr->getExprLoc();
  8633. // Perform Sin and store results in argument 1.
  8634. auto *sin =
  8635. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  8636. /*actPerRowForMatrices*/ true, srcLoc);
  8637. spvBuilder.createStore(doExpr(callExpr->getArg(1)), sin, srcLoc);
  8638. // Perform Cos and store results in argument 2.
  8639. auto *cos =
  8640. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  8641. /*actPerRowForMatrices*/ true, srcLoc);
  8642. spvBuilder.createStore(doExpr(callExpr->getArg(2)), cos, srcLoc);
  8643. return nullptr;
  8644. }
  8645. SpirvInstruction *
  8646. SpirvEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  8647. const auto *arg = callExpr->getArg(0);
  8648. const auto loc = callExpr->getExprLoc();
  8649. auto *argId = doExpr(arg);
  8650. const auto argType = arg->getType();
  8651. const QualType returnType = callExpr->getType();
  8652. QualType elemType = {};
  8653. uint32_t vecSize = 0;
  8654. if (isScalarType(argType, &elemType)) {
  8655. auto *floatZero = getValueZero(elemType);
  8656. auto *floatOne = getValueOne(elemType);
  8657. return spvBuilder.createGLSLExtInst(returnType,
  8658. GLSLstd450::GLSLstd450FClamp,
  8659. {argId, floatZero, floatOne}, loc);
  8660. }
  8661. if (isVectorType(argType, &elemType, &vecSize)) {
  8662. auto *vecZero = getVecValueZero(elemType, vecSize);
  8663. auto *vecOne = getVecValueOne(elemType, vecSize);
  8664. return spvBuilder.createGLSLExtInst(returnType,
  8665. GLSLstd450::GLSLstd450FClamp,
  8666. {argId, vecZero, vecOne}, loc);
  8667. }
  8668. uint32_t numRows = 0, numCols = 0;
  8669. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  8670. auto *vecZero = getVecValueZero(elemType, numCols);
  8671. auto *vecOne = getVecValueOne(elemType, numCols);
  8672. const auto actOnEachVec = [this, loc, vecZero,
  8673. vecOne](uint32_t /*index*/, QualType vecType,
  8674. SpirvInstruction *curRow) {
  8675. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FClamp,
  8676. {curRow, vecZero, vecOne}, loc);
  8677. };
  8678. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8679. }
  8680. emitError("invalid argument type passed to saturate intrinsic function",
  8681. callExpr->getExprLoc());
  8682. return nullptr;
  8683. }
  8684. SpirvInstruction *
  8685. SpirvEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  8686. // Import the GLSL.std.450 extended instruction set.
  8687. const Expr *arg = callExpr->getArg(0);
  8688. const auto loc = callExpr->getExprLoc();
  8689. const QualType returnType = callExpr->getType();
  8690. const QualType argType = arg->getType();
  8691. assert(isFloatOrVecMatOfFloatType(argType));
  8692. auto *argId = doExpr(arg);
  8693. SpirvInstruction *floatSign = nullptr;
  8694. // For matrices, we can perform the instruction on each vector of the matrix.
  8695. if (isMxNMatrix(argType)) {
  8696. const auto actOnEachVec = [this, loc](uint32_t /*index*/, QualType vecType,
  8697. SpirvInstruction *curRow) {
  8698. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FSign,
  8699. {curRow}, loc);
  8700. };
  8701. floatSign = processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8702. } else {
  8703. floatSign = spvBuilder.createGLSLExtInst(
  8704. argType, GLSLstd450::GLSLstd450FSign, {argId}, loc);
  8705. }
  8706. return castToInt(floatSign, arg->getType(), returnType, arg->getLocStart());
  8707. }
  8708. SpirvInstruction *
  8709. SpirvEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  8710. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  8711. // The frontend should guarantee that by inserting implicit casts.
  8712. const QualType f32Type = astContext.FloatTy;
  8713. const QualType u32Type = astContext.UnsignedIntTy;
  8714. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8715. const auto loc = callExpr->getExprLoc();
  8716. const auto *arg = callExpr->getArg(0);
  8717. auto *argId = doExpr(arg);
  8718. uint32_t elemCount = {};
  8719. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8720. // The input is a vector. We need to handle each element separately.
  8721. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8722. for (uint32_t i = 0; i < elemCount; ++i) {
  8723. auto *srcElem = spvBuilder.createCompositeExtract(u32Type, argId, {i},
  8724. arg->getLocStart());
  8725. auto *convert = spvBuilder.createGLSLExtInst(
  8726. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem, loc);
  8727. elements.push_back(
  8728. spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc));
  8729. }
  8730. return spvBuilder.createCompositeConstruct(
  8731. astContext.getExtVectorType(f32Type, elemCount), elements, loc);
  8732. }
  8733. auto *convert = spvBuilder.createGLSLExtInst(
  8734. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, argId, loc);
  8735. // f16tof32() converts the float16 stored in the low-half of the uint to
  8736. // a float. So just need to return the first component.
  8737. return spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc);
  8738. }
  8739. SpirvInstruction *
  8740. SpirvEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  8741. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  8742. // The frontend should guarantee that by inserting implicit casts.
  8743. const QualType f32Type = astContext.FloatTy;
  8744. const QualType u32Type = astContext.UnsignedIntTy;
  8745. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8746. auto *zero = spvBuilder.getConstantFloat(f32Type, llvm::APFloat(0.0f));
  8747. const auto loc = callExpr->getExprLoc();
  8748. const auto *arg = callExpr->getArg(0);
  8749. auto *argId = doExpr(arg);
  8750. uint32_t elemCount = {};
  8751. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8752. // The input is a vector. We need to handle each element separately.
  8753. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8754. for (uint32_t i = 0; i < elemCount; ++i) {
  8755. auto *srcElem = spvBuilder.createCompositeExtract(f32Type, argId, {i},
  8756. arg->getLocStart());
  8757. auto *srcVec =
  8758. spvBuilder.createCompositeConstruct(v2f32Type, {srcElem, zero}, loc);
  8759. elements.push_back(spvBuilder.createGLSLExtInst(
  8760. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc));
  8761. }
  8762. return spvBuilder.createCompositeConstruct(
  8763. astContext.getExtVectorType(u32Type, elemCount), elements, loc);
  8764. }
  8765. // f16tof32() stores the float into the low-half of the uint. So we need
  8766. // to supply another zero to take the other half.
  8767. auto *srcVec =
  8768. spvBuilder.createCompositeConstruct(v2f32Type, {argId, zero}, loc);
  8769. return spvBuilder.createGLSLExtInst(
  8770. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc);
  8771. }
  8772. SpirvInstruction *SpirvEmitter::processIntrinsicUsingSpirvInst(
  8773. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  8774. // Certain opcodes are only allowed in pixel shader
  8775. if (!spvContext.isPS())
  8776. switch (opcode) {
  8777. case spv::Op::OpDPdx:
  8778. case spv::Op::OpDPdy:
  8779. case spv::Op::OpDPdxFine:
  8780. case spv::Op::OpDPdyFine:
  8781. case spv::Op::OpDPdxCoarse:
  8782. case spv::Op::OpDPdyCoarse:
  8783. case spv::Op::OpFwidth:
  8784. case spv::Op::OpFwidthFine:
  8785. case spv::Op::OpFwidthCoarse:
  8786. needsLegalization = true;
  8787. break;
  8788. default:
  8789. // Only the given opcodes need legalization. Anything else should preserve
  8790. // previous.
  8791. break;
  8792. }
  8793. const auto loc = callExpr->getExprLoc();
  8794. const QualType returnType = callExpr->getType();
  8795. if (callExpr->getNumArgs() == 1u) {
  8796. const Expr *arg = callExpr->getArg(0);
  8797. auto *argId = doExpr(arg);
  8798. // If the instruction does not operate on matrices, we can perform the
  8799. // instruction on each vector of the matrix.
  8800. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8801. const auto actOnEachVec = [this, opcode, loc](uint32_t /*index*/,
  8802. QualType vecType,
  8803. SpirvInstruction *curRow) {
  8804. return spvBuilder.createUnaryOp(opcode, vecType, curRow, loc);
  8805. };
  8806. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8807. }
  8808. return spvBuilder.createUnaryOp(opcode, returnType, argId, loc);
  8809. } else if (callExpr->getNumArgs() == 2u) {
  8810. const Expr *arg0 = callExpr->getArg(0);
  8811. auto *arg0Id = doExpr(arg0);
  8812. auto *arg1Id = doExpr(callExpr->getArg(1));
  8813. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8814. // If the instruction does not operate on matrices, we can perform the
  8815. // instruction on each vector of the matrix.
  8816. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8817. const auto actOnEachVec = [this, opcode, arg1Id, loc,
  8818. arg1Loc](uint32_t index, QualType vecType,
  8819. SpirvInstruction *arg0Row) {
  8820. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Id,
  8821. {index}, arg1Loc);
  8822. return spvBuilder.createBinaryOp(opcode, vecType, arg0Row, arg1Row,
  8823. loc);
  8824. };
  8825. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec, loc);
  8826. }
  8827. return spvBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id, loc);
  8828. }
  8829. emitError("unsupported %0 intrinsic function", loc)
  8830. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8831. return nullptr;
  8832. }
  8833. SpirvInstruction *SpirvEmitter::processIntrinsicUsingGLSLInst(
  8834. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices,
  8835. SourceLocation loc) {
  8836. // Import the GLSL.std.450 extended instruction set.
  8837. const QualType returnType = callExpr->getType();
  8838. if (callExpr->getNumArgs() == 1u) {
  8839. const Expr *arg = callExpr->getArg(0);
  8840. auto *argInstr = doExpr(arg);
  8841. // If the instruction does not operate on matrices, we can perform the
  8842. // instruction on each vector of the matrix.
  8843. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8844. const auto actOnEachVec = [this, loc,
  8845. opcode](uint32_t /*index*/, QualType vecType,
  8846. SpirvInstruction *curRowInstr) {
  8847. return spvBuilder.createGLSLExtInst(vecType, opcode, {curRowInstr},
  8848. loc);
  8849. };
  8850. return processEachVectorInMatrix(arg, argInstr, actOnEachVec, loc);
  8851. }
  8852. return spvBuilder.createGLSLExtInst(returnType, opcode, {argInstr}, loc);
  8853. } else if (callExpr->getNumArgs() == 2u) {
  8854. const Expr *arg0 = callExpr->getArg(0);
  8855. auto *arg0Instr = doExpr(arg0);
  8856. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8857. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8858. // If the instruction does not operate on matrices, we can perform the
  8859. // instruction on each vector of the matrix.
  8860. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8861. const auto actOnEachVec = [this, loc, opcode, arg1Instr,
  8862. arg1Loc](uint32_t index, QualType vecType,
  8863. SpirvInstruction *arg0RowInstr) {
  8864. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8865. vecType, arg1Instr, {index}, arg1Loc);
  8866. return spvBuilder.createGLSLExtInst(vecType, opcode,
  8867. {arg0RowInstr, arg1RowInstr}, loc);
  8868. };
  8869. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8870. }
  8871. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8872. {arg0Instr, arg1Instr}, loc);
  8873. } else if (callExpr->getNumArgs() == 3u) {
  8874. const Expr *arg0 = callExpr->getArg(0);
  8875. auto *arg0Instr = doExpr(arg0);
  8876. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8877. auto *arg2Instr = doExpr(callExpr->getArg(2));
  8878. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8879. auto arg2Loc = callExpr->getArg(2)->getLocStart();
  8880. // If the instruction does not operate on matrices, we can perform the
  8881. // instruction on each vector of the matrix.
  8882. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8883. const auto actOnEachVec = [this, loc, opcode, arg1Instr, arg2Instr,
  8884. arg1Loc,
  8885. arg2Loc](uint32_t index, QualType vecType,
  8886. SpirvInstruction *arg0RowInstr) {
  8887. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8888. vecType, arg1Instr, {index}, arg1Loc);
  8889. auto *arg2RowInstr = spvBuilder.createCompositeExtract(
  8890. vecType, arg2Instr, {index}, arg2Loc);
  8891. return spvBuilder.createGLSLExtInst(
  8892. vecType, opcode, {arg0RowInstr, arg1RowInstr, arg2RowInstr}, loc);
  8893. };
  8894. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8895. }
  8896. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8897. {arg0Instr, arg1Instr, arg2Instr}, loc);
  8898. }
  8899. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  8900. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8901. return nullptr;
  8902. }
  8903. SpirvInstruction *
  8904. SpirvEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  8905. // Since there is no log10 instruction in SPIR-V, we can use:
  8906. // log10(x) = log2(x) * ( 1 / log2(10) )
  8907. // 1 / log2(10) = 0.30103
  8908. auto loc = callExpr->getExprLoc();
  8909. auto *scale =
  8910. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.30103f));
  8911. auto *log2 = processIntrinsicUsingGLSLInst(
  8912. callExpr, GLSLstd450::GLSLstd450Log2, true, loc);
  8913. const auto returnType = callExpr->getType();
  8914. spv::Op scaleOp = isScalarType(returnType)
  8915. ? spv::Op::OpFMul
  8916. : isVectorType(returnType)
  8917. ? spv::Op::OpVectorTimesScalar
  8918. : spv::Op::OpMatrixTimesScalar;
  8919. return spvBuilder.createBinaryOp(scaleOp, returnType, log2, scale, loc);
  8920. }
  8921. SpirvInstruction *
  8922. SpirvEmitter::processIntrinsic8BitPack(const CallExpr *callExpr,
  8923. hlsl::IntrinsicOp op) {
  8924. const auto loc = callExpr->getExprLoc();
  8925. assert(op == hlsl::IntrinsicOp::IOP_pack_s8 ||
  8926. op == hlsl::IntrinsicOp::IOP_pack_u8 ||
  8927. op == hlsl::IntrinsicOp::IOP_pack_clamp_s8 ||
  8928. op == hlsl::IntrinsicOp::IOP_pack_clamp_u8);
  8929. // Here's the signature for the pack intrinsic operations:
  8930. //
  8931. // uint8_t4_packed pack_u8(uint32_t4 unpackedVal);
  8932. // uint8_t4_packed pack_u8(uint16_t4 unpackedVal);
  8933. // int8_t4_packed pack_s8(int32_t4 unpackedVal);
  8934. // int8_t4_packed pack_s8(int16_t4 unpackedVal);
  8935. //
  8936. // These functions take a vec4 of 16-bit or 32-bit integers as input. For each
  8937. // element of the vec4, they pick the lower 8 bits, and drop the other bits.
  8938. // The result is four 8-bit values (32 bits in total) which are packed in an
  8939. // unsigned uint32_t.
  8940. //
  8941. //
  8942. // Here's the signature for the pack_clamp intrinsic operations:
  8943. //
  8944. // uint8_t4_packed pack_clamp_u8(int32_t4 val); // Pack and Clamp [0, 255]
  8945. // uint8_t4_packed pack_clamp_u8(int16_t4 val); // Pack and Clamp [0, 255]
  8946. //
  8947. // int8_t4_packed pack_clamp_s8(int32_t4 val); // Pack and Clamp [-128, 127]
  8948. // int8_t4_packed pack_clamp_s8(int16_t4 val); // Pack and Clamp [-128, 127]
  8949. //
  8950. // These functions take a vec4 of 16-bit or 32-bit integers as input. For each
  8951. // element of the vec4, they first clamp the value to a range (depending on
  8952. // the signedness) then pick the lower 8 bits, and drop the other bits.
  8953. // The result is four 8-bit values (32 bits in total) which are packed in an
  8954. // unsigned uint32_t.
  8955. //
  8956. // Note: uint8_t4_packed and int8_t4_packed are NOT vector types! They are
  8957. // both scalar 32-bit unsigned integer types where each byte represents one
  8958. // value.
  8959. //
  8960. // Note: In pack_clamp_{s|u}8 intrinsics, an input of 0x100 will be turned
  8961. // into 0xFF, not 0x00. Therefore, it is important to perform a clamp first,
  8962. // and then a truncation.
  8963. // Steps:
  8964. // Use GLSL extended instruction set's clamp (only for clamp instructions).
  8965. // Use OpUConvert/OpSConvert to truncate each element of the vec4 to 8 bits.
  8966. // Use OpBitcast to make a 32-bit uint out of the new vec4.
  8967. auto *arg = callExpr->getArg(0);
  8968. const auto argType = arg->getType();
  8969. SpirvInstruction *argInstr = doExpr(arg);
  8970. QualType elemType = {};
  8971. uint32_t elemCount = 0;
  8972. (void)isVectorType(argType, &elemType, &elemCount);
  8973. const bool isSigned = elemType->isSignedIntegerType();
  8974. assert(elemCount == 4);
  8975. const bool doesClamp = op == hlsl::IntrinsicOp::IOP_pack_clamp_s8 ||
  8976. op == hlsl::IntrinsicOp::IOP_pack_clamp_u8;
  8977. if (doesClamp) {
  8978. const auto bitwidth = getElementSpirvBitwidth(
  8979. astContext, elemType, spirvOptions.enable16BitTypes);
  8980. int32_t clampMin = op == hlsl::IntrinsicOp::IOP_pack_clamp_u8 ? 0 : -128;
  8981. int32_t clampMax = op == hlsl::IntrinsicOp::IOP_pack_clamp_u8 ? 255 : 127;
  8982. auto *minInstr = spvBuilder.getConstantInt(
  8983. elemType, llvm::APInt(bitwidth, clampMin, isSigned));
  8984. auto *maxInstr = spvBuilder.getConstantInt(
  8985. elemType, llvm::APInt(bitwidth, clampMax, isSigned));
  8986. auto *minVec = spvBuilder.getConstantComposite(
  8987. argType, {minInstr, minInstr, minInstr, minInstr});
  8988. auto *maxVec = spvBuilder.getConstantComposite(
  8989. argType, {maxInstr, maxInstr, maxInstr, maxInstr});
  8990. auto clampOp = isSigned ? GLSLstd450SClamp : GLSLstd450UClamp;
  8991. argInstr = spvBuilder.createGLSLExtInst(argType, clampOp,
  8992. {argInstr, minVec, maxVec}, loc);
  8993. }
  8994. if (isSigned) {
  8995. QualType v4Int8Type =
  8996. astContext.getExtVectorType(astContext.SignedCharTy, 4);
  8997. auto *bytesVecInstr = spvBuilder.createUnaryOp(spv::Op::OpSConvert,
  8998. v4Int8Type, argInstr, loc);
  8999. return spvBuilder.createUnaryOp(
  9000. spv::Op::OpBitcast, astContext.Int8_4PackedTy, bytesVecInstr, loc);
  9001. } else {
  9002. QualType v4Uint8Type =
  9003. astContext.getExtVectorType(astContext.UnsignedCharTy, 4);
  9004. auto *bytesVecInstr = spvBuilder.createUnaryOp(spv::Op::OpUConvert,
  9005. v4Uint8Type, argInstr, loc);
  9006. return spvBuilder.createUnaryOp(
  9007. spv::Op::OpBitcast, astContext.UInt8_4PackedTy, bytesVecInstr, loc);
  9008. }
  9009. }
  9010. SpirvInstruction *
  9011. SpirvEmitter::processIntrinsic8BitUnpack(const CallExpr *callExpr,
  9012. hlsl::IntrinsicOp op) {
  9013. const auto loc = callExpr->getExprLoc();
  9014. assert(op == hlsl::IntrinsicOp::IOP_unpack_s8s16 ||
  9015. op == hlsl::IntrinsicOp::IOP_unpack_s8s32 ||
  9016. op == hlsl::IntrinsicOp::IOP_unpack_u8u16 ||
  9017. op == hlsl::IntrinsicOp::IOP_unpack_u8u32);
  9018. // Here's the signature for the pack intrinsic operations:
  9019. //
  9020. // int16_t4 unpack_s8s16(int8_t4_packed packedVal); // Sign Extended
  9021. // uint16_t4 unpack_u8u16(uint8_t4_packed packedVal); // Non-Sign Extended
  9022. // int32_t4 unpack_s8s32(int8_t4_packed packedVal); // Sign Extended
  9023. // uint32_t4 unpack_u8u32(uint8_t4_packed packedVal); // Non-Sign Extended
  9024. //
  9025. // These functions take a 32-bit unsigned integer as input (where each byte of
  9026. // the input represents one value, i.e. it's packed). They first unpack the
  9027. // 32-bit integer to a vector of 4 bytes. Then for each element of the vec4,
  9028. // they zero-extend or sign-extend the byte in order to achieve a 16-bit or
  9029. // 32-bit vector of integers.
  9030. //
  9031. // Note: uint8_t4_packed and int8_t4_packed are NOT vector types! They are
  9032. // both scalar 32-bit unsigned integer types where each byte represents one
  9033. // value.
  9034. // Steps:
  9035. // Use OpBitcast to make a vec4 of bytes from a 32-bit value.
  9036. // Use OpUConvert/OpSConvert to zero-extend/sign-extend each element of the
  9037. // vec4 to 16 or 32 bits.
  9038. auto *arg = callExpr->getArg(0);
  9039. SpirvInstruction *argInstr = doExpr(arg);
  9040. const bool isSigned = op == hlsl::IntrinsicOp::IOP_unpack_s8s16 ||
  9041. op == hlsl::IntrinsicOp::IOP_unpack_s8s32;
  9042. QualType resultType = {};
  9043. if (op == hlsl::IntrinsicOp::IOP_unpack_s8s16 ||
  9044. op == hlsl::IntrinsicOp::IOP_unpack_u8u16) {
  9045. resultType = astContext.getExtVectorType(
  9046. isSigned ? astContext.ShortTy : astContext.UnsignedShortTy, 4);
  9047. } else {
  9048. resultType = astContext.getExtVectorType(
  9049. isSigned ? astContext.IntTy : astContext.UnsignedIntTy, 4);
  9050. }
  9051. if (isSigned) {
  9052. QualType v4Int8Type =
  9053. astContext.getExtVectorType(astContext.SignedCharTy, 4);
  9054. auto *bytesVecInstr =
  9055. spvBuilder.createUnaryOp(spv::Op::OpBitcast, v4Int8Type, argInstr, loc);
  9056. return spvBuilder.createUnaryOp(spv::Op::OpSConvert, resultType,
  9057. bytesVecInstr, loc);
  9058. } else {
  9059. QualType v4Uint8Type =
  9060. astContext.getExtVectorType(astContext.UnsignedCharTy, 4);
  9061. auto *bytesVecInstr = spvBuilder.createUnaryOp(spv::Op::OpBitcast,
  9062. v4Uint8Type, argInstr, loc);
  9063. return spvBuilder.createUnaryOp(spv::Op::OpUConvert, resultType,
  9064. bytesVecInstr, loc);
  9065. }
  9066. }
  9067. SpirvInstruction *SpirvEmitter::processRayBuiltins(const CallExpr *callExpr,
  9068. hlsl::IntrinsicOp op) {
  9069. bool nvRayTracing =
  9070. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  9071. spv::BuiltIn builtin = spv::BuiltIn::Max;
  9072. bool transposeMatrix = false;
  9073. const auto loc = callExpr->getExprLoc();
  9074. switch (op) {
  9075. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  9076. builtin = spv::BuiltIn::LaunchSizeNV;
  9077. break;
  9078. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  9079. builtin = spv::BuiltIn::LaunchIdNV;
  9080. break;
  9081. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  9082. if (nvRayTracing)
  9083. builtin = spv::BuiltIn::HitTNV;
  9084. else
  9085. builtin = spv::BuiltIn::RayTmaxKHR;
  9086. break;
  9087. case hlsl::IntrinsicOp::IOP_RayTMin:
  9088. builtin = spv::BuiltIn::RayTminNV;
  9089. break;
  9090. case hlsl::IntrinsicOp::IOP_HitKind:
  9091. builtin = spv::BuiltIn::HitKindNV;
  9092. break;
  9093. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  9094. builtin = spv::BuiltIn::WorldRayDirectionNV;
  9095. break;
  9096. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  9097. builtin = spv::BuiltIn::WorldRayOriginNV;
  9098. break;
  9099. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  9100. builtin = spv::BuiltIn::ObjectRayDirectionNV;
  9101. break;
  9102. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  9103. builtin = spv::BuiltIn::ObjectRayOriginNV;
  9104. break;
  9105. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  9106. featureManager.requestExtension(Extension::KHR_ray_tracing,
  9107. "GeometryIndex()", loc);
  9108. builtin = spv::BuiltIn::RayGeometryIndexKHR;
  9109. break;
  9110. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  9111. builtin = spv::BuiltIn::InstanceId;
  9112. break;
  9113. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  9114. builtin = spv::BuiltIn::PrimitiveId;
  9115. break;
  9116. case hlsl::IntrinsicOp::IOP_InstanceID:
  9117. builtin = spv::BuiltIn::InstanceCustomIndexNV;
  9118. break;
  9119. case hlsl::IntrinsicOp::IOP_RayFlags:
  9120. builtin = spv::BuiltIn::IncomingRayFlagsNV;
  9121. break;
  9122. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  9123. transposeMatrix = true;
  9124. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  9125. builtin = spv::BuiltIn::ObjectToWorldNV;
  9126. break;
  9127. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  9128. transposeMatrix = true;
  9129. case hlsl::IntrinsicOp::IOP_WorldToObject4x3:
  9130. builtin = spv::BuiltIn::WorldToObjectNV;
  9131. break;
  9132. default:
  9133. emitError("ray intrinsic function unimplemented", loc);
  9134. return nullptr;
  9135. }
  9136. QualType builtinType = callExpr->getType();
  9137. if (transposeMatrix) {
  9138. // DXR defines ObjectToWorld3x4, WorldToObject3x4 as transposed matrices.
  9139. // SPIR-V has only non tranposed variant defined as a builtin
  9140. // So perform read of original non transposed builtin and perform transpose.
  9141. assert(hlsl::IsHLSLMatType(builtinType) && "Builtin should be matrix");
  9142. const clang::Type *type = builtinType.getCanonicalType().getTypePtr();
  9143. const RecordType *RT = cast<RecordType>(type);
  9144. const ClassTemplateSpecializationDecl *templateSpecDecl =
  9145. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  9146. ClassTemplateDecl *templateDecl =
  9147. templateSpecDecl->getSpecializedTemplate();
  9148. builtinType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  9149. templateDecl, astContext.FloatTy, 4, 3);
  9150. }
  9151. SpirvInstruction *retVal =
  9152. declIdMapper.getBuiltinVar(builtin, builtinType, loc);
  9153. retVal = spvBuilder.createLoad(builtinType, retVal, loc);
  9154. if (transposeMatrix)
  9155. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, callExpr->getType(),
  9156. retVal, loc);
  9157. return retVal;
  9158. }
  9159. SpirvInstruction *SpirvEmitter::processReportHit(const CallExpr *callExpr) {
  9160. SpirvInstruction *hitAttributeStageVar = nullptr;
  9161. const VarDecl *hitAttributeArg = nullptr;
  9162. QualType hitAttributeType;
  9163. const auto args = callExpr->getArgs();
  9164. if (callExpr->getNumArgs() != 3) {
  9165. emitError("invalid number of arguments to ReportHit",
  9166. callExpr->getExprLoc());
  9167. }
  9168. // HLSL Function :
  9169. // template<typename hitAttr>
  9170. // ReportHit(in float, in uint, in hitAttr)
  9171. if (const auto *implCastExpr = dyn_cast<CastExpr>(callExpr->getArg(2))) {
  9172. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9173. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9174. hitAttributeType = varDecl->getType();
  9175. hitAttributeArg = varDecl;
  9176. // Check if same type of hit attribute stage variable was already
  9177. // created, if so re-use
  9178. const auto iter = hitAttributeMap.find(hitAttributeType);
  9179. if (iter == hitAttributeMap.end()) {
  9180. hitAttributeStageVar = declIdMapper.createRayTracingNVStageVar(
  9181. spv::StorageClass::HitAttributeNV, varDecl);
  9182. hitAttributeMap[hitAttributeType] = hitAttributeStageVar;
  9183. } else {
  9184. hitAttributeStageVar = iter->second;
  9185. }
  9186. }
  9187. }
  9188. }
  9189. assert(hitAttributeStageVar && hitAttributeArg);
  9190. // Copy argument to stage variable
  9191. const auto hitAttributeArgInst =
  9192. declIdMapper.getDeclEvalInfo(hitAttributeArg, callExpr->getExprLoc());
  9193. auto tempLoad =
  9194. spvBuilder.createLoad(hitAttributeArg->getType(), hitAttributeArgInst,
  9195. hitAttributeArg->getLocStart());
  9196. spvBuilder.createStore(hitAttributeStageVar, tempLoad,
  9197. callExpr->getExprLoc());
  9198. // SPIR-V Instruction :
  9199. // bool OpReportIntersection(<id> float Hit, <id> uint HitKind)
  9200. llvm::SmallVector<SpirvInstruction *, 4> reportHitArgs;
  9201. reportHitArgs.push_back(doExpr(args[0])); // Hit
  9202. reportHitArgs.push_back(doExpr(args[1])); // HitKind
  9203. return spvBuilder.createRayTracingOpsNV(spv::Op::OpReportIntersectionNV,
  9204. astContext.BoolTy, reportHitArgs,
  9205. callExpr->getExprLoc());
  9206. }
  9207. void SpirvEmitter::processCallShader(const CallExpr *callExpr) {
  9208. bool nvRayTracing =
  9209. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  9210. SpirvInstruction *callDataLocInst = nullptr;
  9211. SpirvInstruction *callDataStageVar = nullptr;
  9212. const VarDecl *callDataArg = nullptr;
  9213. QualType callDataType;
  9214. const auto args = callExpr->getArgs();
  9215. if (callExpr->getNumArgs() != 2) {
  9216. emitError("invalid number of arguments to CallShader",
  9217. callExpr->getExprLoc());
  9218. }
  9219. // HLSL Func :
  9220. // template<typename CallData>
  9221. // void CallShader(in int sbtIndex, inout CallData arg)
  9222. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[1])) {
  9223. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9224. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9225. callDataType = varDecl->getType();
  9226. callDataArg = varDecl;
  9227. // Check if same type of callable data stage variable was already
  9228. // created, if so re-use
  9229. const auto callDataPair = callDataMap.find(callDataType);
  9230. if (callDataPair == callDataMap.end()) {
  9231. int numCallDataVars = callDataMap.size();
  9232. callDataStageVar = declIdMapper.createRayTracingNVStageVar(
  9233. spv::StorageClass::CallableDataNV, varDecl);
  9234. // Decorate unique location id for each created stage var
  9235. spvBuilder.decorateLocation(callDataStageVar, numCallDataVars);
  9236. callDataLocInst = spvBuilder.getConstantInt(
  9237. astContext.UnsignedIntTy, llvm::APInt(32, numCallDataVars));
  9238. callDataMap[callDataType] =
  9239. std::make_pair(callDataStageVar, callDataLocInst);
  9240. } else {
  9241. callDataStageVar = callDataPair->second.first;
  9242. callDataLocInst = callDataPair->second.second;
  9243. }
  9244. }
  9245. }
  9246. }
  9247. assert(callDataStageVar && callDataArg);
  9248. // Copy argument to stage variable
  9249. const auto callDataArgInst =
  9250. declIdMapper.getDeclEvalInfo(callDataArg, callExpr->getExprLoc());
  9251. auto tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataArgInst,
  9252. callDataArg->getLocStart());
  9253. spvBuilder.createStore(callDataStageVar, tempLoad, callExpr->getExprLoc());
  9254. // SPIR-V Instruction
  9255. // void OpExecuteCallable(<id> int SBT Index, <id> uint Callable Data Location
  9256. // Id)
  9257. llvm::SmallVector<SpirvInstruction *, 2> callShaderArgs;
  9258. callShaderArgs.push_back(doExpr(args[0]));
  9259. if (nvRayTracing) {
  9260. callShaderArgs.push_back(callDataLocInst);
  9261. spvBuilder.createRayTracingOpsNV(spv::Op::OpExecuteCallableNV, QualType(),
  9262. callShaderArgs, callExpr->getExprLoc());
  9263. } else {
  9264. callShaderArgs.push_back(callDataStageVar);
  9265. spvBuilder.createRayTracingOpsNV(spv::Op::OpExecuteCallableKHR, QualType(),
  9266. callShaderArgs, callExpr->getExprLoc());
  9267. }
  9268. // Copy data back to argument
  9269. tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataStageVar,
  9270. callDataArg->getLocStart());
  9271. spvBuilder.createStore(callDataArgInst, tempLoad, callExpr->getExprLoc());
  9272. return;
  9273. }
  9274. void SpirvEmitter::processTraceRay(const CallExpr *callExpr) {
  9275. bool nvRayTracing =
  9276. featureManager.isExtensionEnabled(Extension::NV_ray_tracing);
  9277. SpirvInstruction *rayPayloadLocInst = nullptr;
  9278. SpirvInstruction *rayPayloadStageVar = nullptr;
  9279. const VarDecl *rayPayloadArg = nullptr;
  9280. QualType rayPayloadType;
  9281. const auto args = callExpr->getArgs();
  9282. if (callExpr->getNumArgs() != 8) {
  9283. emitError("invalid number of arguments to TraceRay",
  9284. callExpr->getExprLoc());
  9285. }
  9286. // HLSL Func
  9287. // template<typename RayPayload>
  9288. // void TraceRay(RaytracingAccelerationStructure rs,
  9289. // uint rayflags,
  9290. // uint InstanceInclusionMask
  9291. // uint RayContributionToHitGroupIndex,
  9292. // uint MultiplierForGeometryContributionToHitGroupIndex,
  9293. // uint MissShaderIndex,
  9294. // RayDesc ray,
  9295. // inout RayPayload p)
  9296. // where RayDesc = {float3 origin, float tMin, float3 direction, float tMax}
  9297. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[7])) {
  9298. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9299. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9300. rayPayloadType = varDecl->getType();
  9301. rayPayloadArg = varDecl;
  9302. const auto rayPayloadPair = rayPayloadMap.find(rayPayloadType);
  9303. // Check if same type of rayPayload stage variable was already
  9304. // created, if so re-use
  9305. if (rayPayloadPair == rayPayloadMap.end()) {
  9306. int numPayloadVars = rayPayloadMap.size();
  9307. rayPayloadStageVar = declIdMapper.createRayTracingNVStageVar(
  9308. spv::StorageClass::RayPayloadNV, varDecl);
  9309. // Decorate unique location id for each created stage var
  9310. spvBuilder.decorateLocation(rayPayloadStageVar, numPayloadVars);
  9311. rayPayloadLocInst = spvBuilder.getConstantInt(
  9312. astContext.UnsignedIntTy, llvm::APInt(32, numPayloadVars));
  9313. rayPayloadMap[rayPayloadType] =
  9314. std::make_pair(rayPayloadStageVar, rayPayloadLocInst);
  9315. } else {
  9316. rayPayloadStageVar = rayPayloadPair->second.first;
  9317. rayPayloadLocInst = rayPayloadPair->second.second;
  9318. }
  9319. }
  9320. }
  9321. }
  9322. assert(rayPayloadStageVar && rayPayloadArg);
  9323. const auto floatType = astContext.FloatTy;
  9324. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  9325. // Extract the ray description to match SPIR-V
  9326. SpirvInstruction *rayDescArg = doExpr(args[6]);
  9327. const auto loc = args[6]->getLocStart();
  9328. const auto origin =
  9329. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  9330. const auto tMin =
  9331. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  9332. const auto direction =
  9333. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  9334. const auto tMax =
  9335. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  9336. // Copy argument to stage variable
  9337. const auto rayPayloadArgInst =
  9338. declIdMapper.getDeclEvalInfo(rayPayloadArg, rayPayloadArg->getLocStart());
  9339. auto tempLoad =
  9340. spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadArgInst,
  9341. rayPayloadArg->getLocStart());
  9342. spvBuilder.createStore(rayPayloadStageVar, tempLoad, callExpr->getExprLoc());
  9343. // SPIR-V Instruction
  9344. // void OpTraceNV ( <id> AccelerationStructureNV acStruct,
  9345. // <id> uint Ray Flags,
  9346. // <id> uint Cull Mask,
  9347. // <id> uint SBT Offset,
  9348. // <id> uint SBT Stride,
  9349. // <id> uint Miss Index,
  9350. // <id> vec4 Ray Origin,
  9351. // <id> float Ray Tmin,
  9352. // <id> vec3 Ray Direction,
  9353. // <id> float Ray Tmax,
  9354. // <id> uint RayPayload number)
  9355. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  9356. for (int ii = 0; ii < 6; ii++) {
  9357. traceArgs.push_back(doExpr(args[ii]));
  9358. }
  9359. traceArgs.push_back(origin);
  9360. traceArgs.push_back(tMin);
  9361. traceArgs.push_back(direction);
  9362. traceArgs.push_back(tMax);
  9363. if (nvRayTracing) {
  9364. traceArgs.push_back(rayPayloadLocInst);
  9365. spvBuilder.createRayTracingOpsNV(spv::Op::OpTraceNV, QualType(), traceArgs,
  9366. callExpr->getExprLoc());
  9367. } else {
  9368. traceArgs.push_back(rayPayloadStageVar);
  9369. spvBuilder.createRayTracingOpsNV(spv::Op::OpTraceRayKHR, QualType(),
  9370. traceArgs, callExpr->getExprLoc());
  9371. }
  9372. // Copy arguments back to stage variable
  9373. tempLoad = spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadStageVar,
  9374. rayPayloadArg->getLocStart());
  9375. spvBuilder.createStore(rayPayloadArgInst, tempLoad, callExpr->getExprLoc());
  9376. return;
  9377. }
  9378. void SpirvEmitter::processDispatchMesh(const CallExpr *callExpr) {
  9379. // HLSL Func - void DispatchMesh(uint ThreadGroupCountX,
  9380. // uint ThreadGroupCountY,
  9381. // uint ThreadGroupCountZ,
  9382. // groupshared <structType> MeshPayload);
  9383. assert(callExpr->getNumArgs() == 4);
  9384. const auto args = callExpr->getArgs();
  9385. const auto loc = callExpr->getExprLoc();
  9386. // 1) create a barrier GroupMemoryBarrierWithGroupSync().
  9387. processIntrinsicMemoryBarrier(callExpr,
  9388. /*isDevice*/ false,
  9389. /*groupSync*/ true,
  9390. /*isAllBarrier*/ false);
  9391. // 2) set TaskCountNV = threadX * threadY * threadZ.
  9392. auto *threadX = doExpr(args[0]);
  9393. auto *threadY = doExpr(args[1]);
  9394. auto *threadZ = doExpr(args[2]);
  9395. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::TaskCountNV,
  9396. astContext.UnsignedIntTy, loc);
  9397. auto *taskCount = spvBuilder.createBinaryOp(
  9398. spv::Op::OpIMul, astContext.UnsignedIntTy, threadX,
  9399. spvBuilder.createBinaryOp(spv::Op::OpIMul, astContext.UnsignedIntTy,
  9400. threadY, threadZ, loc),
  9401. loc);
  9402. spvBuilder.createStore(var, taskCount, loc);
  9403. // 3) create PerTaskNV out attribute block and store MeshPayload info.
  9404. const auto *sigPoint =
  9405. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::MSOut);
  9406. spv::StorageClass sc = spv::StorageClass::Output;
  9407. auto *payloadArg = doExpr(args[3]);
  9408. bool isValid = false;
  9409. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[3])) {
  9410. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  9411. if (const auto *paramDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  9412. if (paramDecl->hasAttr<HLSLGroupSharedAttr>()) {
  9413. isValid = declIdMapper.createPayloadStageVars(
  9414. sigPoint, sc, paramDecl, /*asInput=*/false, paramDecl->getType(),
  9415. "out.var", &payloadArg);
  9416. }
  9417. }
  9418. }
  9419. }
  9420. if (!isValid) {
  9421. emitError("expected groupshared object as argument to DispatchMesh()",
  9422. args[3]->getExprLoc());
  9423. }
  9424. }
  9425. void SpirvEmitter::processMeshOutputCounts(const CallExpr *callExpr) {
  9426. // HLSL Func - void SetMeshOutputCounts(uint numVertices, uint numPrimitives);
  9427. assert(callExpr->getNumArgs() == 2);
  9428. const auto args = callExpr->getArgs();
  9429. const auto loc = callExpr->getExprLoc();
  9430. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::PrimitiveCountNV,
  9431. astContext.UnsignedIntTy, loc);
  9432. spvBuilder.createStore(var, doExpr(args[1]), loc);
  9433. }
  9434. SpirvConstant *SpirvEmitter::getValueZero(QualType type) {
  9435. {
  9436. QualType scalarType = {};
  9437. if (isScalarType(type, &scalarType)) {
  9438. if (scalarType->isBooleanType()) {
  9439. return spvBuilder.getConstantBool(false);
  9440. }
  9441. if (scalarType->isIntegerType()) {
  9442. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 0));
  9443. }
  9444. if (scalarType->isFloatingType()) {
  9445. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(0.0f));
  9446. }
  9447. }
  9448. }
  9449. {
  9450. QualType elemType = {};
  9451. uint32_t size = {};
  9452. if (isVectorType(type, &elemType, &size)) {
  9453. return getVecValueZero(elemType, size);
  9454. }
  9455. }
  9456. {
  9457. QualType elemType = {};
  9458. uint32_t rowCount = 0, colCount = 0;
  9459. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  9460. auto *row = getVecValueZero(elemType, colCount);
  9461. llvm::SmallVector<SpirvConstant *, 4> rows((size_t)rowCount, row);
  9462. return spvBuilder.getConstantComposite(type, rows);
  9463. }
  9464. }
  9465. emitError("getting value 0 for type %0 unimplemented", {})
  9466. << type.getAsString();
  9467. return nullptr;
  9468. }
  9469. SpirvConstant *SpirvEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  9470. auto *elemZeroId = getValueZero(elemType);
  9471. if (size == 1)
  9472. return elemZeroId;
  9473. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemZeroId);
  9474. const QualType vecType = astContext.getExtVectorType(elemType, size);
  9475. return spvBuilder.getConstantComposite(vecType, elements);
  9476. }
  9477. SpirvConstant *SpirvEmitter::getValueOne(QualType type) {
  9478. {
  9479. QualType scalarType = {};
  9480. if (isScalarType(type, &scalarType)) {
  9481. if (scalarType->isBooleanType()) {
  9482. return spvBuilder.getConstantBool(true);
  9483. }
  9484. if (scalarType->isIntegerType()) {
  9485. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 1));
  9486. }
  9487. if (scalarType->isFloatingType()) {
  9488. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(1.0f));
  9489. }
  9490. }
  9491. }
  9492. {
  9493. QualType elemType = {};
  9494. uint32_t size = {};
  9495. if (isVectorType(type, &elemType, &size)) {
  9496. return getVecValueOne(elemType, size);
  9497. }
  9498. }
  9499. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  9500. return 0;
  9501. }
  9502. SpirvConstant *SpirvEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  9503. auto *elemOne = getValueOne(elemType);
  9504. if (size == 1)
  9505. return elemOne;
  9506. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemOne);
  9507. const QualType vecType = astContext.getExtVectorType(elemType, size);
  9508. return spvBuilder.getConstantComposite(vecType, elements);
  9509. }
  9510. SpirvConstant *SpirvEmitter::getMatElemValueOne(QualType type) {
  9511. assert(hlsl::IsHLSLMatType(type));
  9512. const auto elemType = hlsl::GetHLSLMatElementType(type);
  9513. uint32_t rowCount = 0, colCount = 0;
  9514. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  9515. if (rowCount == 1 && colCount == 1)
  9516. return getValueOne(elemType);
  9517. if (colCount == 1)
  9518. return getVecValueOne(elemType, rowCount);
  9519. return getVecValueOne(elemType, colCount);
  9520. }
  9521. SpirvConstant *SpirvEmitter::getMaskForBitwidthValue(QualType type) {
  9522. QualType elemType = {};
  9523. uint32_t count = 1;
  9524. if (isScalarType(type, &elemType) || isVectorType(type, &elemType, &count)) {
  9525. const auto bitwidth = getElementSpirvBitwidth(
  9526. astContext, elemType, spirvOptions.enable16BitTypes);
  9527. SpirvConstant *mask = spvBuilder.getConstantInt(
  9528. elemType,
  9529. llvm::APInt(bitwidth, bitwidth - 1, elemType->isSignedIntegerType()));
  9530. if (count == 1)
  9531. return mask;
  9532. const QualType resultType = astContext.getExtVectorType(elemType, count);
  9533. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(count), mask);
  9534. return spvBuilder.getConstantComposite(resultType, elements);
  9535. }
  9536. assert(false && "this method only supports scalars and vectors");
  9537. return nullptr;
  9538. }
  9539. SpirvConstant *SpirvEmitter::translateAPValue(const APValue &value,
  9540. const QualType targetType) {
  9541. SpirvConstant *result = nullptr;
  9542. if (targetType->isBooleanType()) {
  9543. result = spvBuilder.getConstantBool(value.getInt().getBoolValue(),
  9544. isSpecConstantMode);
  9545. } else if (targetType->isIntegerType()) {
  9546. result = translateAPInt(value.getInt(), targetType);
  9547. } else if (targetType->isFloatingType()) {
  9548. result = translateAPFloat(value.getFloat(), targetType);
  9549. } else if (hlsl::IsHLSLVecType(targetType)) {
  9550. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  9551. const auto numElements = value.getVectorLength();
  9552. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  9553. // size so we need to translate it to scalar values.
  9554. if (numElements == 1) {
  9555. result = translateAPValue(value.getVectorElt(0), elemType);
  9556. } else {
  9557. llvm::SmallVector<SpirvConstant *, 4> elements;
  9558. for (uint32_t i = 0; i < numElements; ++i) {
  9559. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  9560. }
  9561. result = spvBuilder.getConstantComposite(targetType, elements);
  9562. }
  9563. }
  9564. if (result)
  9565. return result;
  9566. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  9567. value.dump();
  9568. return 0;
  9569. }
  9570. SpirvConstant *SpirvEmitter::translateAPInt(const llvm::APInt &intValue,
  9571. QualType targetType) {
  9572. return spvBuilder.getConstantInt(targetType, intValue, isSpecConstantMode);
  9573. }
  9574. bool SpirvEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  9575. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  9576. const bool isSigned = expr->getType()->isSignedIntegerType();
  9577. const llvm::APInt &value = intLiteral->getValue();
  9578. return (isSigned && !value.isSignedIntN(32)) ||
  9579. (!isSigned && !value.isIntN(32));
  9580. }
  9581. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  9582. llvm::APFloat value = floatLiteral->getValue();
  9583. const auto &semantics = value.getSemantics();
  9584. // regular 'half' and 'float' can be represented in 32 bits.
  9585. if (&semantics == &llvm::APFloat::IEEEsingle ||
  9586. &semantics == &llvm::APFloat::IEEEhalf)
  9587. return true;
  9588. // See if 'double' value can be represented in 32 bits without losing info.
  9589. bool losesInfo = false;
  9590. const auto convertStatus =
  9591. value.convert(llvm::APFloat::IEEEsingle,
  9592. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9593. if (convertStatus != llvm::APFloat::opOK &&
  9594. convertStatus != llvm::APFloat::opInexact)
  9595. return true;
  9596. }
  9597. return false;
  9598. }
  9599. SpirvConstant *SpirvEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  9600. bool isSigned) {
  9601. if (isSigned && intValue.isSignedIntN(32)) {
  9602. return spvBuilder.getConstantInt(astContext.IntTy, intValue);
  9603. }
  9604. if (!isSigned && intValue.isIntN(32)) {
  9605. return spvBuilder.getConstantInt(astContext.UnsignedIntTy, intValue);
  9606. }
  9607. // Couldn't evaluate as a 32-bit int without losing information.
  9608. return nullptr;
  9609. }
  9610. SpirvConstant *
  9611. SpirvEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  9612. const auto &semantics = floatValue.getSemantics();
  9613. // If the given value is already a 32-bit float, there is no need to convert.
  9614. if (&semantics == &llvm::APFloat::IEEEsingle) {
  9615. return spvBuilder.getConstantFloat(astContext.FloatTy, floatValue,
  9616. isSpecConstantMode);
  9617. }
  9618. // Try to see if this literal float can be represented in 32-bit.
  9619. // Since the convert function below may modify the fp value, we call it on a
  9620. // temporary copy.
  9621. llvm::APFloat eval = floatValue;
  9622. bool losesInfo = false;
  9623. const auto convertStatus =
  9624. eval.convert(llvm::APFloat::IEEEsingle,
  9625. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9626. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  9627. return spvBuilder.getConstantFloat(astContext.FloatTy,
  9628. llvm::APFloat(eval.convertToFloat()));
  9629. // Couldn't evaluate as a 32-bit float without losing information.
  9630. return nullptr;
  9631. }
  9632. SpirvConstant *SpirvEmitter::translateAPFloat(llvm::APFloat floatValue,
  9633. QualType targetType) {
  9634. return spvBuilder.getConstantFloat(targetType, floatValue,
  9635. isSpecConstantMode);
  9636. }
  9637. SpirvConstant *SpirvEmitter::tryToEvaluateAsConst(const Expr *expr) {
  9638. Expr::EvalResult evalResult;
  9639. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  9640. !evalResult.HasSideEffects) {
  9641. return translateAPValue(evalResult.Val, expr->getType());
  9642. }
  9643. return nullptr;
  9644. }
  9645. hlsl::ShaderModel::Kind SpirvEmitter::getShaderModelKind(StringRef stageName) {
  9646. hlsl::ShaderModel::Kind smk;
  9647. switch (stageName[0]) {
  9648. case 'c':
  9649. switch (stageName[1]) {
  9650. case 'o':
  9651. smk = hlsl::ShaderModel::Kind::Compute;
  9652. break;
  9653. case 'l':
  9654. smk = hlsl::ShaderModel::Kind::ClosestHit;
  9655. break;
  9656. case 'a':
  9657. smk = hlsl::ShaderModel::Kind::Callable;
  9658. break;
  9659. default:
  9660. smk = hlsl::ShaderModel::Kind::Invalid;
  9661. break;
  9662. }
  9663. break;
  9664. case 'v':
  9665. smk = hlsl::ShaderModel::Kind::Vertex;
  9666. break;
  9667. case 'h':
  9668. smk = hlsl::ShaderModel::Kind::Hull;
  9669. break;
  9670. case 'd':
  9671. smk = hlsl::ShaderModel::Kind::Domain;
  9672. break;
  9673. case 'g':
  9674. smk = hlsl::ShaderModel::Kind::Geometry;
  9675. break;
  9676. case 'p':
  9677. smk = hlsl::ShaderModel::Kind::Pixel;
  9678. break;
  9679. case 'r':
  9680. smk = hlsl::ShaderModel::Kind::RayGeneration;
  9681. break;
  9682. case 'i':
  9683. smk = hlsl::ShaderModel::Kind::Intersection;
  9684. break;
  9685. case 'a':
  9686. switch (stageName[1]) {
  9687. case 'm':
  9688. smk = hlsl::ShaderModel::Kind::Amplification;
  9689. break;
  9690. case 'n':
  9691. smk = hlsl::ShaderModel::Kind::AnyHit;
  9692. break;
  9693. }
  9694. break;
  9695. case 'm':
  9696. switch (stageName[1]) {
  9697. case 'e':
  9698. smk = hlsl::ShaderModel::Kind::Mesh;
  9699. break;
  9700. case 'i':
  9701. smk = hlsl::ShaderModel::Kind::Miss;
  9702. break;
  9703. }
  9704. break;
  9705. default:
  9706. smk = hlsl::ShaderModel::Kind::Invalid;
  9707. break;
  9708. }
  9709. if (smk == hlsl::ShaderModel::Kind::Invalid) {
  9710. llvm_unreachable("unknown stage name");
  9711. }
  9712. return smk;
  9713. }
  9714. spv::ExecutionModel
  9715. SpirvEmitter::getSpirvShaderStage(hlsl::ShaderModel::Kind smk) {
  9716. switch (smk) {
  9717. case hlsl::ShaderModel::Kind::Vertex:
  9718. return spv::ExecutionModel::Vertex;
  9719. case hlsl::ShaderModel::Kind::Hull:
  9720. return spv::ExecutionModel::TessellationControl;
  9721. case hlsl::ShaderModel::Kind::Domain:
  9722. return spv::ExecutionModel::TessellationEvaluation;
  9723. case hlsl::ShaderModel::Kind::Geometry:
  9724. return spv::ExecutionModel::Geometry;
  9725. case hlsl::ShaderModel::Kind::Pixel:
  9726. return spv::ExecutionModel::Fragment;
  9727. case hlsl::ShaderModel::Kind::Compute:
  9728. return spv::ExecutionModel::GLCompute;
  9729. case hlsl::ShaderModel::Kind::RayGeneration:
  9730. return spv::ExecutionModel::RayGenerationNV;
  9731. case hlsl::ShaderModel::Kind::Intersection:
  9732. return spv::ExecutionModel::IntersectionNV;
  9733. case hlsl::ShaderModel::Kind::AnyHit:
  9734. return spv::ExecutionModel::AnyHitNV;
  9735. case hlsl::ShaderModel::Kind::ClosestHit:
  9736. return spv::ExecutionModel::ClosestHitNV;
  9737. case hlsl::ShaderModel::Kind::Miss:
  9738. return spv::ExecutionModel::MissNV;
  9739. case hlsl::ShaderModel::Kind::Callable:
  9740. return spv::ExecutionModel::CallableNV;
  9741. case hlsl::ShaderModel::Kind::Mesh:
  9742. return spv::ExecutionModel::MeshNV;
  9743. case hlsl::ShaderModel::Kind::Amplification:
  9744. return spv::ExecutionModel::TaskNV;
  9745. default:
  9746. llvm_unreachable("invalid shader model kind");
  9747. break;
  9748. }
  9749. }
  9750. bool SpirvEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  9751. uint32_t *arraySize) {
  9752. bool success = true;
  9753. assert(spvContext.isGS());
  9754. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  9755. spvBuilder.addExecutionMode(
  9756. entryFunction, spv::ExecutionMode::OutputVertices,
  9757. {static_cast<uint32_t>(vcAttr->getCount())}, decl->getLocation());
  9758. }
  9759. uint32_t invocations = 1;
  9760. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  9761. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  9762. }
  9763. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Invocations,
  9764. {invocations}, decl->getLocation());
  9765. // Only one primitive type is permitted for the geometry shader.
  9766. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  9767. inLine = false, inTriangle = false, inLineAdj = false,
  9768. inTriangleAdj = false;
  9769. for (const auto *param : decl->params()) {
  9770. // Add an execution mode based on the output stream type. Do not an
  9771. // execution mode more than once.
  9772. if (param->hasAttr<HLSLInOutAttr>()) {
  9773. const auto paramType = param->getType();
  9774. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  9775. spvBuilder.addExecutionMode(entryFunction,
  9776. spv::ExecutionMode::OutputTriangleStrip, {},
  9777. param->getLocation());
  9778. outTriangle = true;
  9779. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  9780. spvBuilder.addExecutionMode(entryFunction,
  9781. spv::ExecutionMode::OutputLineStrip, {},
  9782. param->getLocation());
  9783. outLine = true;
  9784. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  9785. spvBuilder.addExecutionMode(entryFunction,
  9786. spv::ExecutionMode::OutputPoints, {},
  9787. param->getLocation());
  9788. outPoint = true;
  9789. }
  9790. // An output stream parameter will not have the input primitive type
  9791. // attributes, so we can continue to the next parameter.
  9792. continue;
  9793. }
  9794. // Add an execution mode based on the input primitive type. Do not add an
  9795. // execution mode more than once.
  9796. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  9797. spvBuilder.addExecutionMode(entryFunction,
  9798. spv::ExecutionMode::InputPoints, {},
  9799. param->getLocation());
  9800. *arraySize = 1;
  9801. inPoint = true;
  9802. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  9803. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::InputLines,
  9804. {}, param->getLocation());
  9805. *arraySize = 2;
  9806. inLine = true;
  9807. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  9808. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Triangles,
  9809. {}, param->getLocation());
  9810. *arraySize = 3;
  9811. inTriangle = true;
  9812. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  9813. spvBuilder.addExecutionMode(entryFunction,
  9814. spv::ExecutionMode::InputLinesAdjacency, {},
  9815. param->getLocation());
  9816. *arraySize = 4;
  9817. inLineAdj = true;
  9818. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  9819. spvBuilder.addExecutionMode(entryFunction,
  9820. spv::ExecutionMode::InputTrianglesAdjacency,
  9821. {}, param->getLocation());
  9822. *arraySize = 6;
  9823. inTriangleAdj = true;
  9824. }
  9825. }
  9826. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  9827. emitError("only one input primitive type can be specified in the geometry "
  9828. "shader",
  9829. {});
  9830. success = false;
  9831. }
  9832. if (outPoint + outTriangle + outLine > 1) {
  9833. emitError("only one output primitive type can be specified in the geometry "
  9834. "shader",
  9835. {});
  9836. success = false;
  9837. }
  9838. return success;
  9839. }
  9840. void SpirvEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  9841. spvBuilder.addExecutionMode(entryFunction,
  9842. spv::ExecutionMode::OriginUpperLeft, {},
  9843. decl->getLocation());
  9844. if (decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  9845. spvBuilder.addExecutionMode(entryFunction,
  9846. spv::ExecutionMode::EarlyFragmentTests, {},
  9847. decl->getLocation());
  9848. }
  9849. if (decl->getAttr<VKPostDepthCoverageAttr>()) {
  9850. spvBuilder.addExecutionMode(entryFunction,
  9851. spv::ExecutionMode::PostDepthCoverage, {},
  9852. decl->getLocation());
  9853. }
  9854. }
  9855. void SpirvEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  9856. // If not explicitly specified, x, y, and z should be defaulted to 1.
  9857. uint32_t x = 1, y = 1, z = 1;
  9858. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  9859. x = static_cast<uint32_t>(numThreadsAttr->getX());
  9860. y = static_cast<uint32_t>(numThreadsAttr->getY());
  9861. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  9862. } else {
  9863. emitError("thread group size [numthreads(x,y,z)] is missing from the "
  9864. "entry-point function",
  9865. decl->getLocation());
  9866. return;
  9867. }
  9868. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  9869. {x, y, z}, decl->getLocation());
  9870. }
  9871. bool SpirvEmitter::processTessellationShaderAttributes(
  9872. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  9873. assert(spvContext.isHS() || spvContext.isDS());
  9874. using namespace spv;
  9875. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  9876. const auto domainType = domain->getDomainType().lower();
  9877. const ExecutionMode hsExecMode =
  9878. llvm::StringSwitch<ExecutionMode>(domainType)
  9879. .Case("tri", ExecutionMode::Triangles)
  9880. .Case("quad", ExecutionMode::Quads)
  9881. .Case("isoline", ExecutionMode::Isolines)
  9882. .Default(ExecutionMode::Max);
  9883. if (hsExecMode == ExecutionMode::Max) {
  9884. emitError("unknown domain type specified for entry function",
  9885. domain->getLocation());
  9886. return false;
  9887. }
  9888. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9889. decl->getLocation());
  9890. }
  9891. // Early return for domain shaders as domain shaders only takes the 'domain'
  9892. // attribute.
  9893. if (spvContext.isDS())
  9894. return true;
  9895. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  9896. const auto scheme = partitioning->getScheme().lower();
  9897. if (scheme == "pow2") {
  9898. emitError("pow2 partitioning scheme is not supported since there is no "
  9899. "equivalent in Vulkan",
  9900. partitioning->getLocation());
  9901. return false;
  9902. }
  9903. const ExecutionMode hsExecMode =
  9904. llvm::StringSwitch<ExecutionMode>(scheme)
  9905. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  9906. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  9907. .Case("integer", ExecutionMode::SpacingEqual)
  9908. .Default(ExecutionMode::Max);
  9909. if (hsExecMode == ExecutionMode::Max) {
  9910. emitError("unknown partitioning scheme in hull shader",
  9911. partitioning->getLocation());
  9912. return false;
  9913. }
  9914. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9915. decl->getLocation());
  9916. }
  9917. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  9918. const auto topology = outputTopology->getTopology().lower();
  9919. const ExecutionMode hsExecMode =
  9920. llvm::StringSwitch<ExecutionMode>(topology)
  9921. .Case("point", ExecutionMode::PointMode)
  9922. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  9923. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  9924. .Default(ExecutionMode::Max);
  9925. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  9926. // default?
  9927. if (topology != "line") {
  9928. if (hsExecMode != spv::ExecutionMode::Max) {
  9929. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9930. decl->getLocation());
  9931. } else {
  9932. emitError("unknown output topology in hull shader",
  9933. outputTopology->getLocation());
  9934. return false;
  9935. }
  9936. }
  9937. }
  9938. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  9939. *numOutputControlPoints = controlPoints->getCount();
  9940. spvBuilder.addExecutionMode(entryFunction,
  9941. spv::ExecutionMode::OutputVertices,
  9942. {*numOutputControlPoints}, decl->getLocation());
  9943. }
  9944. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  9945. llvm::StringRef pcf_name = pcf->getFunctionName();
  9946. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  9947. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  9948. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  9949. funcDecl->getName() == pcf_name)
  9950. patchConstFunc = funcDecl;
  9951. }
  9952. return true;
  9953. }
  9954. bool SpirvEmitter::emitEntryFunctionWrapperForRayTracing(
  9955. const FunctionDecl *decl, SpirvFunction *entryFuncInstr) {
  9956. // The entry basic block.
  9957. auto *entryLabel = spvBuilder.createBasicBlock();
  9958. spvBuilder.setInsertPoint(entryLabel);
  9959. // Initialize all global variables at the beginning of the wrapper
  9960. for (const VarDecl *varDecl : toInitGloalVars) {
  9961. const auto varInfo =
  9962. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  9963. if (const auto *init = varDecl->getInit()) {
  9964. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  9965. init->getLocStart());
  9966. // Update counter variable associated with global variables
  9967. tryToAssignCounterVar(varDecl, init);
  9968. }
  9969. // If not explicitly initialized, initialize with their zero values if not
  9970. // resource objects
  9971. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  9972. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  9973. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  9974. }
  9975. }
  9976. // Create temporary variables for holding function call arguments
  9977. llvm::SmallVector<SpirvInstruction *, 4> params;
  9978. llvm::SmallVector<QualType, 4> paramTypes;
  9979. llvm::SmallVector<SpirvInstruction *, 4> stageVars;
  9980. hlsl::ShaderModel::Kind sKind = spvContext.getCurrentShaderModelKind();
  9981. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  9982. const auto param = decl->getParamDecl(i);
  9983. const auto paramType = param->getType();
  9984. std::string tempVarName = "param.var." + param->getNameAsString();
  9985. auto *tempVar =
  9986. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  9987. param->hasAttr<HLSLPreciseAttr>());
  9988. SpirvVariable *curStageVar = nullptr;
  9989. params.push_back(tempVar);
  9990. paramTypes.push_back(paramType);
  9991. // Order of arguments is fixed
  9992. // Any-Hit/Closest-Hit : Arg 0 = rayPayload(inout), Arg1 = attribute(in)
  9993. // Miss : Arg 0 = rayPayload(inout)
  9994. // Callable : Arg 0 = callable data(inout)
  9995. // Raygeneration/Intersection : No Args allowed
  9996. if (sKind == hlsl::ShaderModel::Kind::RayGeneration) {
  9997. assert("Raygeneration shaders have no arguments of entry function");
  9998. } else if (sKind == hlsl::ShaderModel::Kind::Intersection) {
  9999. assert("Intersection shaders have no arguments of entry function");
  10000. } else if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  10001. sKind == hlsl::ShaderModel::Kind::AnyHit) {
  10002. // Generate rayPayloadInNV and hitAttributeNV stage variables
  10003. if (i == 0) {
  10004. // First argument is always rayPayload
  10005. curStageVar = declIdMapper.createRayTracingNVStageVar(
  10006. spv::StorageClass::IncomingRayPayloadNV, param);
  10007. currentRayPayload = curStageVar;
  10008. } else {
  10009. // Second argument is always attribute
  10010. curStageVar = declIdMapper.createRayTracingNVStageVar(
  10011. spv::StorageClass::HitAttributeNV, param);
  10012. }
  10013. } else if (sKind == hlsl::ShaderModel::Kind::Miss) {
  10014. // Generate rayPayloadInNV stage variable
  10015. // First and only argument is rayPayload
  10016. curStageVar = declIdMapper.createRayTracingNVStageVar(
  10017. spv::StorageClass::IncomingRayPayloadNV, param);
  10018. } else if (sKind == hlsl::ShaderModel::Kind::Callable) {
  10019. curStageVar = declIdMapper.createRayTracingNVStageVar(
  10020. spv::StorageClass::IncomingCallableDataNV, param);
  10021. }
  10022. if (curStageVar != nullptr) {
  10023. stageVars.push_back(curStageVar);
  10024. // Copy data to temporary
  10025. auto *tempLoadInst =
  10026. spvBuilder.createLoad(paramType, curStageVar, param->getLocation());
  10027. spvBuilder.createStore(tempVar, tempLoadInst, param->getLocation());
  10028. }
  10029. }
  10030. // Call the original entry function
  10031. const QualType retType = decl->getReturnType();
  10032. spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  10033. decl->getLocStart());
  10034. // Write certain output variables back
  10035. if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  10036. sKind == hlsl::ShaderModel::Kind::AnyHit ||
  10037. sKind == hlsl::ShaderModel::Kind::Miss ||
  10038. sKind == hlsl::ShaderModel::Kind::Callable) {
  10039. // Write back results to IncomingRayPayloadNV/IncomingCallableDataNV
  10040. auto *tempLoad = spvBuilder.createLoad(paramTypes[0], params[0],
  10041. decl->getBody()->getLocEnd());
  10042. spvBuilder.createStore(stageVars[0], tempLoad,
  10043. decl->getBody()->getLocEnd());
  10044. }
  10045. spvBuilder.createReturn(decl->getBody()->getLocEnd());
  10046. spvBuilder.endFunction();
  10047. return true;
  10048. }
  10049. bool SpirvEmitter::processMeshOrAmplificationShaderAttributes(
  10050. const FunctionDecl *decl, uint32_t *outVerticesArraySize) {
  10051. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  10052. uint32_t x, y, z;
  10053. x = static_cast<uint32_t>(numThreadsAttr->getX());
  10054. y = static_cast<uint32_t>(numThreadsAttr->getY());
  10055. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  10056. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  10057. {x, y, z}, decl->getLocation());
  10058. }
  10059. // Early return for amplification shaders as they only take the 'numthreads'
  10060. // attribute.
  10061. if (spvContext.isAS())
  10062. return true;
  10063. spv::ExecutionMode outputPrimitive = spv::ExecutionMode::Max;
  10064. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  10065. const auto topology = outputTopology->getTopology().lower();
  10066. outputPrimitive =
  10067. llvm::StringSwitch<spv::ExecutionMode>(topology)
  10068. .Case("point", spv::ExecutionMode::OutputPoints)
  10069. .Case("line", spv::ExecutionMode::OutputLinesNV)
  10070. .Case("triangle", spv::ExecutionMode::OutputTrianglesNV);
  10071. if (outputPrimitive != spv::ExecutionMode::Max) {
  10072. spvBuilder.addExecutionMode(entryFunction, outputPrimitive, {},
  10073. decl->getLocation());
  10074. } else {
  10075. emitError("unknown output topology in mesh shader",
  10076. outputTopology->getLocation());
  10077. return false;
  10078. }
  10079. }
  10080. uint32_t numVertices = 0;
  10081. uint32_t numIndices = 0;
  10082. uint32_t numPrimitives = 0;
  10083. bool payloadDeclSeen = false;
  10084. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  10085. const auto param = decl->getParamDecl(i);
  10086. const auto paramType = param->getType();
  10087. const auto paramLoc = param->getLocation();
  10088. if (param->hasAttr<HLSLVerticesAttr>() ||
  10089. param->hasAttr<HLSLIndicesAttr>() ||
  10090. param->hasAttr<HLSLPrimitivesAttr>()) {
  10091. uint32_t arraySize = 0;
  10092. if (const auto *arrayType =
  10093. astContext.getAsConstantArrayType(paramType)) {
  10094. const auto eleType =
  10095. arrayType->getElementType()->getCanonicalTypeUnqualified();
  10096. if (param->hasAttr<HLSLIndicesAttr>()) {
  10097. switch (outputPrimitive) {
  10098. case spv::ExecutionMode::OutputPoints:
  10099. if (eleType != astContext.UnsignedIntTy) {
  10100. emitError("expected 1D array of uint type", paramLoc);
  10101. return false;
  10102. }
  10103. break;
  10104. case spv::ExecutionMode::OutputLinesNV: {
  10105. QualType baseType;
  10106. uint32_t length;
  10107. if (!isVectorType(eleType, &baseType, &length) ||
  10108. baseType != astContext.UnsignedIntTy || length != 2) {
  10109. emitError("expected 1D array of uint2 type", paramLoc);
  10110. return false;
  10111. }
  10112. break;
  10113. }
  10114. case spv::ExecutionMode::OutputTrianglesNV: {
  10115. QualType baseType;
  10116. uint32_t length;
  10117. if (!isVectorType(eleType, &baseType, &length) ||
  10118. baseType != astContext.UnsignedIntTy || length != 3) {
  10119. emitError("expected 1D array of uint3 type", paramLoc);
  10120. return false;
  10121. }
  10122. break;
  10123. }
  10124. default:
  10125. assert(false && "unexpected spirv execution mode");
  10126. }
  10127. } else if (!eleType->isStructureType()) {
  10128. // vertices/primitives objects
  10129. emitError("expected 1D array of struct type", paramLoc);
  10130. return false;
  10131. }
  10132. arraySize = static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  10133. } else {
  10134. emitError("expected 1D array of indices/vertices/primitives object",
  10135. paramLoc);
  10136. return false;
  10137. }
  10138. if (param->hasAttr<HLSLVerticesAttr>()) {
  10139. if (numVertices != 0) {
  10140. emitError("only one object with 'vertices' modifier is allowed",
  10141. paramLoc);
  10142. return false;
  10143. }
  10144. numVertices = arraySize;
  10145. } else if (param->hasAttr<HLSLIndicesAttr>()) {
  10146. if (numIndices != 0) {
  10147. emitError("only one object with 'indices' modifier is allowed",
  10148. paramLoc);
  10149. return false;
  10150. }
  10151. numIndices = arraySize;
  10152. } else if (param->hasAttr<HLSLPrimitivesAttr>()) {
  10153. if (numPrimitives != 0) {
  10154. emitError("only one object with 'primitives' modifier is allowed",
  10155. paramLoc);
  10156. return false;
  10157. }
  10158. numPrimitives = arraySize;
  10159. }
  10160. } else if (param->hasAttr<HLSLPayloadAttr>()) {
  10161. if (payloadDeclSeen) {
  10162. emitError("only one object with 'payload' modifier is allowed",
  10163. paramLoc);
  10164. return false;
  10165. }
  10166. payloadDeclSeen = true;
  10167. if (!paramType->isStructureType()) {
  10168. emitError("expected payload of struct type", paramLoc);
  10169. return false;
  10170. }
  10171. }
  10172. }
  10173. // Vertex attribute array is a mandatory param to mesh entry function.
  10174. if (numVertices != 0) {
  10175. *outVerticesArraySize = numVertices;
  10176. spvBuilder.addExecutionMode(
  10177. entryFunction, spv::ExecutionMode::OutputVertices,
  10178. {static_cast<uint32_t>(numVertices)}, decl->getLocation());
  10179. } else {
  10180. emitError("expected vertices object declaration", decl->getLocation());
  10181. return false;
  10182. }
  10183. // Vertex indices array is a mandatory param to mesh entry function.
  10184. if (numIndices != 0) {
  10185. spvBuilder.addExecutionMode(
  10186. entryFunction, spv::ExecutionMode::OutputPrimitivesNV,
  10187. {static_cast<uint32_t>(numIndices)}, decl->getLocation());
  10188. // Primitive attribute array is an optional param to mesh entry function,
  10189. // but the array size should match the indices array.
  10190. if (numPrimitives != 0 && numPrimitives != numIndices) {
  10191. emitError("array size of primitives object should match 'indices' object",
  10192. decl->getLocation());
  10193. return false;
  10194. }
  10195. } else {
  10196. emitError("expected indices object declaration", decl->getLocation());
  10197. return false;
  10198. }
  10199. return true;
  10200. }
  10201. bool SpirvEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  10202. SpirvFunction *entryFuncInstr) {
  10203. // HS specific attributes
  10204. uint32_t numOutputControlPoints = 0;
  10205. SpirvInstruction *outputControlPointIdVal =
  10206. nullptr; // SV_OutputControlPointID value
  10207. SpirvInstruction *primitiveIdVar = nullptr; // SV_PrimitiveID variable
  10208. SpirvInstruction *viewIdVar = nullptr; // SV_ViewID variable
  10209. SpirvInstruction *hullMainInputPatchParam =
  10210. nullptr; // Temporary parameter for InputPatch<>
  10211. // The array size of per-vertex input/output variables
  10212. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  10213. uint32_t inputArraySize = 0;
  10214. uint32_t outputArraySize = 0;
  10215. // The wrapper entry function surely does not have pre-assigned <result-id>
  10216. // for it like other functions that got added to the work queue following
  10217. // function calls. And the wrapper is the entry function.
  10218. entryFunction = spvBuilder.beginFunction(
  10219. astContext.VoidTy, decl->getLocStart(), decl->getName());
  10220. // Specify that entryFunction is an entry function wrapper.
  10221. entryFunction->setEntryFunctionWrapper();
  10222. // Note this should happen before using declIdMapper for other tasks.
  10223. declIdMapper.setEntryFunction(entryFunction);
  10224. // Set entryFunction for current entry point.
  10225. auto iter = functionInfoMap.find(decl);
  10226. assert(iter != functionInfoMap.end());
  10227. auto &entryInfo = iter->second;
  10228. assert(entryInfo->isEntryFunction);
  10229. entryInfo->entryFunction = entryFunction;
  10230. if (spvContext.isRay()) {
  10231. return emitEntryFunctionWrapperForRayTracing(decl, entryFuncInstr);
  10232. }
  10233. // Handle attributes specific to each shader stage
  10234. if (spvContext.isPS()) {
  10235. processPixelShaderAttributes(decl);
  10236. } else if (spvContext.isCS()) {
  10237. processComputeShaderAttributes(decl);
  10238. } else if (spvContext.isHS()) {
  10239. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  10240. return false;
  10241. // The input array size for HS is specified in the InputPatch parameter.
  10242. for (const auto *param : decl->params())
  10243. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  10244. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  10245. break;
  10246. }
  10247. outputArraySize = numOutputControlPoints;
  10248. } else if (spvContext.isDS()) {
  10249. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  10250. return false;
  10251. // The input array size for HS is specified in the OutputPatch parameter.
  10252. for (const auto *param : decl->params())
  10253. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  10254. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  10255. break;
  10256. }
  10257. // The per-vertex output of DS is not an array.
  10258. } else if (spvContext.isGS()) {
  10259. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  10260. return false;
  10261. // The per-vertex output of GS is not an array.
  10262. } else if (spvContext.isMS() || spvContext.isAS()) {
  10263. if (!processMeshOrAmplificationShaderAttributes(decl, &outputArraySize))
  10264. return false;
  10265. }
  10266. // Go through all parameters and record the declaration of SV_ClipDistance
  10267. // and SV_CullDistance. We need to do this extra step because in HLSL we
  10268. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  10269. // or vector of float types, but we can only have one single float array
  10270. // for the ClipDistance/CullDistance builtin. So we need to group all
  10271. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  10272. // need to calculate the total size of the array and the offset of each
  10273. // variable within that array.
  10274. // Also go through all parameters to record the semantic strings provided for
  10275. // the builtins in gl_PerVertex.
  10276. for (const auto *param : decl->params()) {
  10277. if (canActAsInParmVar(param))
  10278. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  10279. return false;
  10280. if (canActAsOutParmVar(param))
  10281. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  10282. return false;
  10283. }
  10284. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  10285. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  10286. return false;
  10287. // Calculate the total size of the ClipDistance/CullDistance array and the
  10288. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  10289. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  10290. if (!spvContext.isCS() && !spvContext.isAS()) {
  10291. // Generate stand-alone builtins of Position, ClipDistance, and
  10292. // CullDistance, which belongs to gl_PerVertex.
  10293. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  10294. }
  10295. // The entry basic block.
  10296. auto *entryLabel = spvBuilder.createBasicBlock();
  10297. spvBuilder.setInsertPoint(entryLabel);
  10298. // Initialize all global variables at the beginning of the wrapper
  10299. for (const VarDecl *varDecl : toInitGloalVars) {
  10300. // SPIR-V does not have string variables
  10301. if (isStringType(varDecl->getType()))
  10302. continue;
  10303. const auto varInfo =
  10304. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  10305. if (const auto *init = varDecl->getInit()) {
  10306. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  10307. init->getLocStart());
  10308. // Update counter variable associated with global variables
  10309. tryToAssignCounterVar(varDecl, init);
  10310. }
  10311. // If not explicitly initialized, initialize with their zero values if not
  10312. // resource objects
  10313. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  10314. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  10315. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  10316. }
  10317. }
  10318. // Create temporary variables for holding function call arguments
  10319. llvm::SmallVector<SpirvInstruction *, 4> params;
  10320. for (const auto *param : decl->params()) {
  10321. const auto paramType = param->getType();
  10322. std::string tempVarName = "param.var." + param->getNameAsString();
  10323. auto *tempVar =
  10324. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  10325. param->hasAttr<HLSLPreciseAttr>());
  10326. params.push_back(tempVar);
  10327. // Create the stage input variable for parameter not marked as pure out and
  10328. // initialize the corresponding temporary variable
  10329. // Also do not create input variables for output stream objects of geometry
  10330. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  10331. if (canActAsInParmVar(param)) {
  10332. if (spvContext.isHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  10333. // Record the temporary variable holding InputPatch. It may be used
  10334. // later in the patch constant function.
  10335. hullMainInputPatchParam = tempVar;
  10336. }
  10337. SpirvInstruction *loadedValue = nullptr;
  10338. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  10339. return false;
  10340. // Only initialize the temporary variable if the parameter is indeed used.
  10341. if (param->isUsed()) {
  10342. spvBuilder.createStore(tempVar, loadedValue, param->getLocation());
  10343. }
  10344. // Record the temporary variable holding SV_OutputControlPointID,
  10345. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  10346. // constant function.
  10347. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  10348. outputControlPointIdVal = loadedValue;
  10349. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  10350. primitiveIdVar = tempVar;
  10351. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  10352. viewIdVar = tempVar;
  10353. }
  10354. }
  10355. // Call the original entry function
  10356. const QualType retType = decl->getReturnType();
  10357. auto *retVal = spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  10358. decl->getLocStart());
  10359. // Create and write stage output variables for return value. Special case for
  10360. // Hull shaders since they operate differently in 2 ways:
  10361. // 1- Their return value is in fact an array and each invocation should write
  10362. // to the proper offset in the array.
  10363. // 2- The patch constant function must be called *once* after all invocations
  10364. // of the main entry point function is done.
  10365. if (spvContext.isHS()) {
  10366. // Create stage output variables out of the return type.
  10367. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  10368. outputControlPointIdVal, retVal))
  10369. return false;
  10370. if (!processHSEntryPointOutputAndPCF(
  10371. decl, retType, retVal, numOutputControlPoints,
  10372. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  10373. hullMainInputPatchParam))
  10374. return false;
  10375. } else {
  10376. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  10377. return false;
  10378. }
  10379. // Create and write stage output variables for parameters marked as
  10380. // out/inout
  10381. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  10382. const auto *param = decl->getParamDecl(i);
  10383. if (canActAsOutParmVar(param)) {
  10384. // Load the value from the parameter after function call
  10385. SpirvInstruction *loadedParam = nullptr;
  10386. // No need to write back the value if the parameter is not used at all in
  10387. // the original entry function.
  10388. //
  10389. // Write back of stage output variables in GS is manually controlled by
  10390. // .Append() intrinsic method. No need to load the parameter since we
  10391. // won't need to write back here.
  10392. if (param->isUsed() && !spvContext.isGS())
  10393. loadedParam = spvBuilder.createLoad(param->getType(), params[i],
  10394. param->getLocStart());
  10395. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  10396. return false;
  10397. }
  10398. }
  10399. // To prevent spirv-opt from removing all debug info, we emit at least
  10400. // a single OpLine to specify the end of the shader. This SourceLocation
  10401. // will provide the information.
  10402. spvBuilder.createReturn(decl->getLocEnd());
  10403. spvBuilder.endFunction();
  10404. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  10405. // We should invoke a translation of the PCF manually.
  10406. if (spvContext.isHS())
  10407. doDecl(patchConstFunc);
  10408. return true;
  10409. }
  10410. bool SpirvEmitter::processHSEntryPointOutputAndPCF(
  10411. const FunctionDecl *hullMainFuncDecl, QualType retType,
  10412. SpirvInstruction *retVal, uint32_t numOutputControlPoints,
  10413. SpirvInstruction *outputControlPointId, SpirvInstruction *primitiveId,
  10414. SpirvInstruction *viewId, SpirvInstruction *hullMainInputPatch) {
  10415. // This method may only be called for Hull shaders.
  10416. assert(spvContext.isHS());
  10417. auto loc = hullMainFuncDecl->getLocation();
  10418. auto locEnd = hullMainFuncDecl->getLocEnd();
  10419. // For Hull shaders, the real output is an array of size
  10420. // numOutputControlPoints. The results of the main should be written to the
  10421. // correct offset in the array (based on InvocationID).
  10422. if (!numOutputControlPoints) {
  10423. emitError("number of output control points cannot be zero", loc);
  10424. return false;
  10425. }
  10426. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  10427. // is not provided.
  10428. if (!outputControlPointId) {
  10429. emitError(
  10430. "SV_OutputControlPointID semantic must be provided in hull shader",
  10431. loc);
  10432. return false;
  10433. }
  10434. if (!patchConstFunc) {
  10435. emitError("patch constant function not defined in hull shader", loc);
  10436. return false;
  10437. }
  10438. SpirvInstruction *hullMainOutputPatch = nullptr;
  10439. // If the patch constant function (PCF) takes the result of the Hull main
  10440. // entry point, create a temporary function-scope variable and write the
  10441. // results to it, so it can be passed to the PCF.
  10442. if (const auto *param = patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  10443. hullMainOutputPatch = declIdMapper.createHullMainOutputPatch(
  10444. param, retType, numOutputControlPoints);
  10445. auto *tempLocation = spvBuilder.createAccessChain(
  10446. retType, hullMainOutputPatch, {outputControlPointId}, locEnd);
  10447. spvBuilder.createStore(tempLocation, retVal, locEnd);
  10448. }
  10449. // Now create a barrier before calling the Patch Constant Function (PCF).
  10450. // Flags are:
  10451. // Execution Barrier scope = Workgroup (2)
  10452. // Memory Barrier scope = Invocation (4)
  10453. // Memory Semantics Barrier scope = None (0)
  10454. spvBuilder.createBarrier(spv::Scope::Invocation,
  10455. spv::MemorySemanticsMask::MaskNone,
  10456. spv::Scope::Workgroup, {});
  10457. // The PCF should be called only once. Therefore, we check the invocationID,
  10458. // and we only allow ID 0 to call the PCF.
  10459. auto *condition = spvBuilder.createBinaryOp(
  10460. spv::Op::OpIEqual, astContext.BoolTy, outputControlPointId,
  10461. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0)),
  10462. loc);
  10463. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  10464. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  10465. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  10466. spvBuilder.addSuccessor(thenBB);
  10467. spvBuilder.addSuccessor(mergeBB);
  10468. spvBuilder.setMergeTarget(mergeBB);
  10469. spvBuilder.setInsertPoint(thenBB);
  10470. // Call the PCF. Since the function is not explicitly called, we must first
  10471. // register an ID for it.
  10472. SpirvFunction *pcfId = declIdMapper.getOrRegisterFn(patchConstFunc);
  10473. const QualType pcfRetType = patchConstFunc->getReturnType();
  10474. std::vector<SpirvInstruction *> pcfParams;
  10475. // A lambda for creating a stage input variable and its associated temporary
  10476. // variable for function call. Also initializes the temporary variable using
  10477. // the contents loaded from the stage input variable. Returns the <result-id>
  10478. // of the temporary variable.
  10479. const auto createParmVarAndInitFromStageInputVar =
  10480. [this](const ParmVarDecl *param) {
  10481. const QualType type = param->getType();
  10482. std::string tempVarName = "param.var." + param->getNameAsString();
  10483. auto paramLoc = param->getLocation();
  10484. auto *tempVar = spvBuilder.addFnVar(type, paramLoc, tempVarName,
  10485. param->hasAttr<HLSLPreciseAttr>());
  10486. SpirvInstruction *loadedValue = nullptr;
  10487. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  10488. spvBuilder.createStore(tempVar, loadedValue, paramLoc);
  10489. return tempVar;
  10490. };
  10491. for (const auto *param : patchConstFunc->parameters()) {
  10492. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  10493. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  10494. // necessarily mean that they are present. There is also no requirement
  10495. // for the order of parameters passed to PCF.
  10496. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  10497. pcfParams.push_back(hullMainInputPatch);
  10498. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  10499. // Since the output patch used in hull shaders is translated to
  10500. // a variable with Workgroup storage class, there is no need
  10501. // to pass the variable as function parameter in SPIR-V.
  10502. continue;
  10503. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  10504. if (!primitiveId) {
  10505. primitiveId = createParmVarAndInitFromStageInputVar(param);
  10506. }
  10507. pcfParams.push_back(primitiveId);
  10508. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  10509. if (!viewId) {
  10510. viewId = createParmVarAndInitFromStageInputVar(param);
  10511. }
  10512. pcfParams.push_back(viewId);
  10513. } else {
  10514. emitError("patch constant function parameter '%0' unknown",
  10515. param->getLocation())
  10516. << param->getName();
  10517. }
  10518. }
  10519. auto *pcfResultId = spvBuilder.createFunctionCall(
  10520. pcfRetType, pcfId, {pcfParams}, hullMainFuncDecl->getLocStart());
  10521. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  10522. /*forPCF*/ true))
  10523. return false;
  10524. spvBuilder.createBranch(mergeBB, locEnd);
  10525. spvBuilder.addSuccessor(mergeBB);
  10526. spvBuilder.setInsertPoint(mergeBB);
  10527. return true;
  10528. }
  10529. bool SpirvEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  10530. if (!root)
  10531. return false;
  10532. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10533. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10534. if (!caseStmt && !compoundStmt)
  10535. return true;
  10536. if (caseStmt) {
  10537. const Expr *caseExpr = caseStmt->getLHS();
  10538. return caseExpr && caseExpr->isEvaluatable(astContext);
  10539. }
  10540. // Recurse down if facing a compound statement.
  10541. for (auto *st : compoundStmt->body())
  10542. if (!allSwitchCasesAreIntegerLiterals(st))
  10543. return false;
  10544. return true;
  10545. }
  10546. void SpirvEmitter::discoverAllCaseStmtInSwitchStmt(
  10547. const Stmt *root, SpirvBasicBlock **defaultBB,
  10548. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> *targets) {
  10549. if (!root)
  10550. return;
  10551. // A switch case can only appear in DefaultStmt, CaseStmt, or
  10552. // CompoundStmt. For the rest, we can just return.
  10553. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  10554. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10555. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10556. if (!defaultStmt && !caseStmt && !compoundStmt)
  10557. return;
  10558. // Recurse down if facing a compound statement.
  10559. if (compoundStmt) {
  10560. for (auto *st : compoundStmt->body())
  10561. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  10562. return;
  10563. }
  10564. std::string caseLabel;
  10565. uint32_t caseValue = 0;
  10566. if (defaultStmt) {
  10567. // This is the default branch.
  10568. caseLabel = "switch.default";
  10569. } else if (caseStmt) {
  10570. // This is a non-default case.
  10571. // When using OpSwitch, we only allow integer literal cases. e.g:
  10572. // case <literal_integer>: {...; break;}
  10573. const Expr *caseExpr = caseStmt->getLHS();
  10574. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  10575. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  10576. if (bitWidth != 32)
  10577. emitError(
  10578. "non-32bit integer case value in switch statement unimplemented",
  10579. caseExpr->getExprLoc());
  10580. Expr::EvalResult evalResult;
  10581. caseExpr->EvaluateAsRValue(evalResult, astContext);
  10582. const int64_t value = evalResult.Val.getInt().getSExtValue();
  10583. caseValue = static_cast<uint32_t>(value);
  10584. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  10585. llvm::itostr(std::abs(value));
  10586. }
  10587. auto *caseBB = spvBuilder.createBasicBlock(caseLabel);
  10588. spvBuilder.addSuccessor(caseBB);
  10589. stmtBasicBlock[root] = caseBB;
  10590. // Add all cases to the 'targets' vector.
  10591. if (caseStmt)
  10592. targets->emplace_back(caseValue, caseBB);
  10593. // The default label is not part of the 'targets' vector that is passed
  10594. // to the OpSwitch instruction.
  10595. // If default statement was discovered, return its label via defaultBB.
  10596. if (defaultStmt)
  10597. *defaultBB = caseBB;
  10598. // Process cases nested in other cases. It happens when we have fall through
  10599. // cases. For example:
  10600. // case 1: case 2: ...; break;
  10601. // will result in the CaseSmt for case 2 nested in the one for case 1.
  10602. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  10603. : defaultStmt->getSubStmt(),
  10604. defaultBB, targets);
  10605. }
  10606. void SpirvEmitter::flattenSwitchStmtAST(const Stmt *root,
  10607. std::vector<const Stmt *> *flatSwitch) {
  10608. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10609. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10610. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  10611. if (!compoundStmt) {
  10612. flatSwitch->push_back(root);
  10613. }
  10614. if (compoundStmt) {
  10615. for (const auto *st : compoundStmt->body())
  10616. flattenSwitchStmtAST(st, flatSwitch);
  10617. } else if (caseStmt) {
  10618. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  10619. } else if (defaultStmt) {
  10620. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  10621. }
  10622. }
  10623. void SpirvEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  10624. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  10625. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  10626. assert(caseStmt || defaultStmt);
  10627. auto *caseBB = stmtBasicBlock[stmt];
  10628. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  10629. // We are about to handle the case passed in as parameter. If the current
  10630. // basic block is not terminated, it means the previous case is a fall
  10631. // through case. We need to link it to the case to be processed.
  10632. spvBuilder.createBranch(caseBB, stmt->getLocStart());
  10633. spvBuilder.addSuccessor(caseBB);
  10634. }
  10635. spvBuilder.setInsertPoint(caseBB);
  10636. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  10637. }
  10638. void SpirvEmitter::processSwitchStmtUsingSpirvOpSwitch(
  10639. const SwitchStmt *switchStmt) {
  10640. const SourceLocation srcLoc = switchStmt->getSwitchLoc();
  10641. // First handle the condition variable DeclStmt if one exists.
  10642. // For example: handle 'int a = b' in the following:
  10643. // switch (int a = b) {...}
  10644. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10645. doDeclStmt(condVarDeclStmt);
  10646. auto *selector = doExpr(switchStmt->getCond());
  10647. // We need a merge block regardless of the number of switch cases.
  10648. // Since OpSwitch always requires a default label, if the switch statement
  10649. // does not have a default branch, we use the merge block as the default
  10650. // target.
  10651. auto *mergeBB = spvBuilder.createBasicBlock("switch.merge");
  10652. spvBuilder.setMergeTarget(mergeBB);
  10653. breakStack.push(mergeBB);
  10654. auto *defaultBB = mergeBB;
  10655. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  10656. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> targets;
  10657. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  10658. // Create the OpSelectionMerge and OpSwitch.
  10659. spvBuilder.createSwitch(mergeBB, selector, defaultBB, targets, srcLoc);
  10660. // Handle the switch body.
  10661. doStmt(switchStmt->getBody());
  10662. if (!spvBuilder.isCurrentBasicBlockTerminated())
  10663. spvBuilder.createBranch(mergeBB, switchStmt->getLocEnd());
  10664. spvBuilder.setInsertPoint(mergeBB);
  10665. breakStack.pop();
  10666. }
  10667. void SpirvEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  10668. std::vector<const Stmt *> flatSwitch;
  10669. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  10670. // First handle the condition variable DeclStmt if one exists.
  10671. // For example: handle 'int a = b' in the following:
  10672. // switch (int a = b) {...}
  10673. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10674. doDeclStmt(condVarDeclStmt);
  10675. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  10676. // the flattened switch AST.
  10677. // For instance, for the following flat vector:
  10678. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10679. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  10680. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10681. // The indexes are: {0, 2, 5, 6, 9}
  10682. std::vector<uint32_t> caseStmtLocs;
  10683. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  10684. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  10685. caseStmtLocs.push_back(i);
  10686. IfStmt *prevIfStmt = nullptr;
  10687. IfStmt *rootIfStmt = nullptr;
  10688. CompoundStmt *defaultBody = nullptr;
  10689. // For each case, start at its index in the vector, and go forward
  10690. // accumulating statements until BreakStmt or end of vector is reached.
  10691. for (auto curCaseIndex : caseStmtLocs) {
  10692. const Stmt *curCase = flatSwitch[curCaseIndex];
  10693. // CompoundStmt to hold all statements for this case.
  10694. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  10695. // Accumulate all non-case/default/break statements as the body for the
  10696. // current case.
  10697. std::vector<Stmt *> statements;
  10698. for (unsigned i = curCaseIndex + 1;
  10699. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  10700. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  10701. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  10702. }
  10703. if (!statements.empty())
  10704. cs->setStmts(astContext, statements.data(), statements.size());
  10705. // For non-default cases, generate the IfStmt that compares the switch
  10706. // value to the case value.
  10707. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  10708. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  10709. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  10710. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  10711. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  10712. bo->setOpcode(BO_EQ);
  10713. bo->setType(astContext.getLogicalOperationType());
  10714. curIf->setCond(bo);
  10715. curIf->setThen(cs);
  10716. // No conditional variable associated with this faux if statement.
  10717. curIf->setConditionVariable(astContext, nullptr);
  10718. // Each If statement is the "else" of the previous if statement.
  10719. if (prevIfStmt)
  10720. prevIfStmt->setElse(curIf);
  10721. else
  10722. rootIfStmt = curIf;
  10723. prevIfStmt = curIf;
  10724. } else {
  10725. // Record the DefaultStmt body as it will be used as the body of the
  10726. // "else" block in the if-elseif-...-else pattern.
  10727. defaultBody = cs;
  10728. }
  10729. }
  10730. // If a default case exists, it is the "else" of the last if statement.
  10731. if (prevIfStmt)
  10732. prevIfStmt->setElse(defaultBody);
  10733. // Since all else-if and else statements are the child nodes of the first
  10734. // IfStmt, we only need to call doStmt for the first IfStmt.
  10735. if (rootIfStmt)
  10736. doStmt(rootIfStmt);
  10737. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  10738. // no if statements. The switch in that case only executes the body of the
  10739. // default case.
  10740. else if (defaultBody)
  10741. doStmt(defaultBody);
  10742. }
  10743. SpirvInstruction *SpirvEmitter::extractVecFromVec4(SpirvInstruction *from,
  10744. uint32_t targetVecSize,
  10745. QualType targetElemType,
  10746. SourceLocation loc) {
  10747. assert(targetVecSize > 0 && targetVecSize < 5);
  10748. const QualType retType =
  10749. targetVecSize == 1
  10750. ? targetElemType
  10751. : astContext.getExtVectorType(targetElemType, targetVecSize);
  10752. switch (targetVecSize) {
  10753. case 1:
  10754. return spvBuilder.createCompositeExtract(retType, from, {0}, loc);
  10755. break;
  10756. case 2:
  10757. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1}, loc);
  10758. break;
  10759. case 3:
  10760. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1, 2}, loc);
  10761. break;
  10762. case 4:
  10763. return from;
  10764. default:
  10765. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  10766. }
  10767. }
  10768. void SpirvEmitter::addFunctionToWorkQueue(hlsl::DXIL::ShaderKind shaderKind,
  10769. const clang::FunctionDecl *fnDecl,
  10770. bool isEntryFunction) {
  10771. // Only update the workQueue and the function info map if the given
  10772. // FunctionDecl hasn't been added already.
  10773. if (functionInfoMap.find(fnDecl) == functionInfoMap.end()) {
  10774. // Note: The function is just discovered and is being added to the
  10775. // workQueue, therefore it does not have the entryFunction SPIR-V
  10776. // instruction yet (use nullptr).
  10777. auto *fnInfo = new (spvContext) FunctionInfo(
  10778. shaderKind, fnDecl, /*entryFunction*/ nullptr, isEntryFunction);
  10779. functionInfoMap[fnDecl] = fnInfo;
  10780. workQueue.push_back(fnInfo);
  10781. }
  10782. }
  10783. SpirvInstruction *
  10784. SpirvEmitter::processTraceRayInline(const CXXMemberCallExpr *expr) {
  10785. const auto object = expr->getImplicitObjectArgument();
  10786. uint32_t templateFlags = hlsl::GetHLSLResourceTemplateUInt(object->getType());
  10787. const auto constFlags = spvBuilder.getConstantInt(
  10788. astContext.UnsignedIntTy, llvm::APInt(32, templateFlags));
  10789. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10790. const auto args = expr->getArgs();
  10791. if (expr->getNumArgs() != 4) {
  10792. emitError("invalid number of arguments to RayQueryInitialize",
  10793. expr->getExprLoc());
  10794. }
  10795. // HLSL Func
  10796. // void RayQuery::TraceRayInline(
  10797. // RaytracingAccelerationStructure AccelerationStructure,
  10798. // uint RayFlags,
  10799. // uint InstanceInclusionMask,
  10800. // RayDesc Ray);
  10801. // void OpRayQueryInitializeKHR ( <id> RayQuery,
  10802. // <id> Acceleration Structure
  10803. // <id> RayFlags
  10804. // <id> CullMask
  10805. // <id> RayOrigin
  10806. // <id> RayTmin
  10807. // <id> RayDirection
  10808. // <id> Ray Tmax)
  10809. const auto accelStructure = doExpr(args[0]);
  10810. SpirvInstruction *rayFlags = nullptr;
  10811. if ((rayFlags = tryToEvaluateAsConst(args[1]))) {
  10812. rayFlags->setRValue();
  10813. } else {
  10814. rayFlags = doExpr(args[1]);
  10815. }
  10816. if (auto constFlags = dyn_cast<SpirvConstantInteger>(rayFlags)) {
  10817. auto interRayFlags = constFlags->getValue().getZExtValue();
  10818. templateFlags |= interRayFlags;
  10819. }
  10820. bool hasCullFlags =
  10821. templateFlags & (uint32_t(hlsl::DXIL::RayFlag::SkipTriangles) |
  10822. uint32_t(hlsl::DXIL::RayFlag::SkipProceduralPrimitives));
  10823. auto loc = args[1]->getLocStart();
  10824. rayFlags =
  10825. spvBuilder.createBinaryOp(spv::Op::OpBitwiseOr, astContext.UnsignedIntTy,
  10826. constFlags, rayFlags, loc);
  10827. const auto cullMask = doExpr(args[2]);
  10828. // Extract the ray description to match SPIR-V
  10829. const auto floatType = astContext.FloatTy;
  10830. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  10831. SpirvInstruction *rayDescArg = doExpr(args[3]);
  10832. loc = args[3]->getLocStart();
  10833. const auto origin =
  10834. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  10835. const auto tMin =
  10836. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  10837. const auto direction =
  10838. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  10839. const auto tMax =
  10840. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  10841. llvm::SmallVector<SpirvInstruction *, 8> traceArgs = {
  10842. rayqueryObj, accelStructure, rayFlags, cullMask,
  10843. origin, tMin, direction, tMax};
  10844. return spvBuilder.createRayQueryOpsKHR(spv::Op::OpRayQueryInitializeKHR,
  10845. QualType(), traceArgs, hasCullFlags,
  10846. expr->getExprLoc());
  10847. }
  10848. SpirvInstruction *
  10849. SpirvEmitter::processRayQueryIntrinsics(const CXXMemberCallExpr *expr,
  10850. hlsl::IntrinsicOp opcode) {
  10851. const auto object = expr->getImplicitObjectArgument();
  10852. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10853. const auto args = expr->getArgs();
  10854. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  10855. traceArgs.push_back(rayqueryObj);
  10856. for (uint32_t i = 0; i < expr->getNumArgs(); ++i) {
  10857. traceArgs.push_back(doExpr(args[i]));
  10858. }
  10859. spv::Op spvCode = spv::Op::Max;
  10860. QualType exprType = expr->getType();
  10861. exprType = exprType->isVoidType() ? QualType() : exprType;
  10862. const auto candidateIntersection =
  10863. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  10864. const auto committedIntersection =
  10865. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  10866. bool transposeMatrix = false;
  10867. bool logicalNot = false;
  10868. using namespace hlsl;
  10869. switch (opcode) {
  10870. case IntrinsicOp::MOP_Proceed:
  10871. spvCode = spv::Op::OpRayQueryProceedKHR;
  10872. break;
  10873. case IntrinsicOp::MOP_Abort:
  10874. spvCode = spv::Op::OpRayQueryTerminateKHR;
  10875. exprType = QualType();
  10876. break;
  10877. case IntrinsicOp::MOP_CandidateGeometryIndex:
  10878. traceArgs.push_back(candidateIntersection);
  10879. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10880. break;
  10881. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  10882. traceArgs.push_back(candidateIntersection);
  10883. spvCode = spv::Op::
  10884. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10885. break;
  10886. case IntrinsicOp::MOP_CandidateInstanceID:
  10887. traceArgs.push_back(candidateIntersection);
  10888. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10889. break;
  10890. case IntrinsicOp::MOP_CandidateInstanceIndex:
  10891. traceArgs.push_back(candidateIntersection);
  10892. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10893. break;
  10894. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  10895. traceArgs.push_back(candidateIntersection);
  10896. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10897. break;
  10898. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  10899. traceArgs.push_back(candidateIntersection);
  10900. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10901. break;
  10902. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  10903. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10904. traceArgs.push_back(candidateIntersection);
  10905. transposeMatrix = true;
  10906. break;
  10907. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  10908. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10909. traceArgs.push_back(candidateIntersection);
  10910. break;
  10911. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  10912. traceArgs.push_back(candidateIntersection);
  10913. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10914. break;
  10915. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  10916. spvCode = spv::Op::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
  10917. logicalNot = true;
  10918. break;
  10919. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  10920. traceArgs.push_back(candidateIntersection);
  10921. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10922. break;
  10923. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  10924. traceArgs.push_back(candidateIntersection);
  10925. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10926. break;
  10927. case IntrinsicOp::MOP_CandidateTriangleRayT:
  10928. traceArgs.push_back(candidateIntersection);
  10929. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10930. break;
  10931. case IntrinsicOp::MOP_CandidateType:
  10932. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10933. traceArgs.push_back(candidateIntersection);
  10934. break;
  10935. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  10936. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10937. traceArgs.push_back(candidateIntersection);
  10938. break;
  10939. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  10940. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10941. traceArgs.push_back(candidateIntersection);
  10942. transposeMatrix = true;
  10943. break;
  10944. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  10945. spvCode = spv::Op::OpRayQueryConfirmIntersectionKHR;
  10946. exprType = QualType();
  10947. break;
  10948. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  10949. spvCode = spv::Op::OpRayQueryGenerateIntersectionKHR;
  10950. exprType = QualType();
  10951. break;
  10952. case IntrinsicOp::MOP_CommittedGeometryIndex:
  10953. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10954. traceArgs.push_back(committedIntersection);
  10955. break;
  10956. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  10957. spvCode = spv::Op::
  10958. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10959. traceArgs.push_back(committedIntersection);
  10960. break;
  10961. case IntrinsicOp::MOP_CommittedInstanceID:
  10962. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10963. traceArgs.push_back(committedIntersection);
  10964. break;
  10965. case IntrinsicOp::MOP_CommittedInstanceIndex:
  10966. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10967. traceArgs.push_back(committedIntersection);
  10968. break;
  10969. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  10970. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10971. traceArgs.push_back(committedIntersection);
  10972. break;
  10973. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  10974. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10975. traceArgs.push_back(committedIntersection);
  10976. break;
  10977. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  10978. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10979. traceArgs.push_back(committedIntersection);
  10980. transposeMatrix = true;
  10981. break;
  10982. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  10983. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10984. traceArgs.push_back(committedIntersection);
  10985. break;
  10986. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  10987. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10988. traceArgs.push_back(committedIntersection);
  10989. break;
  10990. case IntrinsicOp::MOP_CommittedRayT:
  10991. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10992. traceArgs.push_back(committedIntersection);
  10993. break;
  10994. case IntrinsicOp::MOP_CommittedStatus:
  10995. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10996. traceArgs.push_back(committedIntersection);
  10997. break;
  10998. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  10999. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  11000. traceArgs.push_back(committedIntersection);
  11001. break;
  11002. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  11003. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  11004. traceArgs.push_back(committedIntersection);
  11005. break;
  11006. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  11007. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  11008. traceArgs.push_back(committedIntersection);
  11009. transposeMatrix = true;
  11010. break;
  11011. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  11012. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  11013. traceArgs.push_back(committedIntersection);
  11014. break;
  11015. case IntrinsicOp::MOP_RayFlags:
  11016. spvCode = spv::Op::OpRayQueryGetRayFlagsKHR;
  11017. break;
  11018. case IntrinsicOp::MOP_RayTMin:
  11019. spvCode = spv::Op::OpRayQueryGetRayTMinKHR;
  11020. break;
  11021. case IntrinsicOp::MOP_WorldRayDirection:
  11022. spvCode = spv::Op::OpRayQueryGetWorldRayDirectionKHR;
  11023. break;
  11024. case IntrinsicOp::MOP_WorldRayOrigin:
  11025. spvCode = spv::Op::OpRayQueryGetWorldRayOriginKHR;
  11026. break;
  11027. default:
  11028. emitError("intrinsic '%0' method unimplemented",
  11029. expr->getCallee()->getExprLoc())
  11030. << expr->getDirectCallee()->getName();
  11031. return nullptr;
  11032. }
  11033. if (transposeMatrix) {
  11034. assert(hlsl::IsHLSLMatType(exprType) && "intrinsic should be matrix");
  11035. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  11036. const RecordType *RT = cast<RecordType>(type);
  11037. const ClassTemplateSpecializationDecl *templateSpecDecl =
  11038. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  11039. ClassTemplateDecl *templateDecl =
  11040. templateSpecDecl->getSpecializedTemplate();
  11041. exprType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  11042. templateDecl, astContext.FloatTy, 4, 3);
  11043. }
  11044. const auto loc = expr->getExprLoc();
  11045. SpirvInstruction *retVal =
  11046. spvBuilder.createRayQueryOpsKHR(spvCode, exprType, traceArgs, false, loc);
  11047. if (transposeMatrix) {
  11048. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, expr->getType(),
  11049. retVal, loc);
  11050. }
  11051. if (logicalNot) {
  11052. retVal = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, expr->getType(),
  11053. retVal, loc);
  11054. }
  11055. retVal->setRValue();
  11056. return retVal;
  11057. }
  11058. bool SpirvEmitter::spirvToolsValidate(std::vector<uint32_t> *mod,
  11059. std::string *messages) {
  11060. spvtools::SpirvTools tools(featureManager.getTargetEnv());
  11061. tools.SetMessageConsumer(
  11062. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  11063. const spv_position_t & /*position*/,
  11064. const char *message) { *messages += message; });
  11065. spvtools::ValidatorOptions options;
  11066. options.SetBeforeHlslLegalization(needsLegalization ||
  11067. declIdMapper.requiresLegalization());
  11068. // GL: strict block layout rules
  11069. // VK: relaxed block layout rules
  11070. // DX: Skip block layout rules
  11071. if (spirvOptions.useScalarLayout || spirvOptions.useDxLayout) {
  11072. options.SetScalarBlockLayout(true);
  11073. } else if (spirvOptions.useGlLayout) {
  11074. // spirv-val by default checks this.
  11075. } else {
  11076. options.SetRelaxBlockLayout(true);
  11077. }
  11078. return tools.Validate(mod->data(), mod->size(), options);
  11079. }
  11080. bool SpirvEmitter::spirvToolsOptimize(std::vector<uint32_t> *mod,
  11081. std::string *messages) {
  11082. spvtools::Optimizer optimizer(featureManager.getTargetEnv());
  11083. optimizer.SetMessageConsumer(
  11084. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  11085. const spv_position_t & /*position*/,
  11086. const char *message) { *messages += message; });
  11087. spvtools::OptimizerOptions options;
  11088. options.set_run_validator(false);
  11089. if (spirvOptions.optConfig.empty()) {
  11090. // Add performance passes.
  11091. optimizer.RegisterPerformancePasses();
  11092. // Add compact ID pass.
  11093. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  11094. } else {
  11095. // Command line options use llvm::SmallVector and llvm::StringRef, whereas
  11096. // SPIR-V optimizer uses std::vector and std::string.
  11097. std::vector<std::string> stdFlags;
  11098. for (const auto &f : spirvOptions.optConfig)
  11099. stdFlags.push_back(f.str());
  11100. if (!optimizer.RegisterPassesFromFlags(stdFlags))
  11101. return false;
  11102. }
  11103. return optimizer.Run(mod->data(), mod->size(), mod, options);
  11104. }
  11105. bool SpirvEmitter::spirvToolsLegalize(std::vector<uint32_t> *mod,
  11106. std::string *messages) {
  11107. spvtools::Optimizer optimizer(featureManager.getTargetEnv());
  11108. optimizer.SetMessageConsumer(
  11109. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  11110. const spv_position_t & /*position*/,
  11111. const char *message) { *messages += message; });
  11112. spvtools::OptimizerOptions options;
  11113. options.set_run_validator(false);
  11114. optimizer.RegisterLegalizationPasses();
  11115. // Add flattening of resources if needed.
  11116. if (spirvOptions.flattenResourceArrays ||
  11117. declIdMapper.requiresFlatteningCompositeResources()) {
  11118. optimizer.RegisterPass(spvtools::CreateDescriptorScalarReplacementPass());
  11119. // ADCE should be run after desc_sroa in order to remove potentially
  11120. // illegal types such as structures containing opaque types.
  11121. optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
  11122. }
  11123. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  11124. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  11125. return optimizer.Run(mod->data(), mod->size(), mod, options);
  11126. }
  11127. SpirvInstruction *
  11128. SpirvEmitter::doUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *expr) {
  11129. // TODO: We support only `sizeof()`. Support other kinds.
  11130. if (expr->getKind() != clang::UnaryExprOrTypeTrait::UETT_SizeOf) {
  11131. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  11132. << expr->getStmtClassName();
  11133. return nullptr;
  11134. }
  11135. if (auto *constExpr = tryToEvaluateAsConst(expr)) {
  11136. constExpr->setRValue();
  11137. return constExpr;
  11138. }
  11139. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  11140. uint32_t size = 0, stride = 0;
  11141. std::tie(std::ignore, size) = alignmentCalc.getAlignmentAndSize(
  11142. expr->getArgumentType(), SpirvLayoutRule::Scalar,
  11143. /*isRowMajor*/ llvm::None, &stride);
  11144. auto *sizeConst = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  11145. llvm::APInt(32, size));
  11146. sizeConst->setRValue();
  11147. return sizeConst;
  11148. }
  11149. } // end namespace spirv
  11150. } // end namespace clang