SPIRVEmitter.cpp 374 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356
  1. //===------- SPIRVEmitter.h - 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 "dxc/HlslIntrinsicOp.h"
  15. #include "spirv-tools/optimizer.hpp"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "InitListHandler.h"
  18. namespace clang {
  19. namespace spirv {
  20. namespace {
  21. /// Returns the type of the given decl. If the given decl is a FunctionDecl,
  22. /// returns its result type.
  23. inline QualType getTypeOrFnRetType(const ValueDecl *decl) {
  24. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  25. return funcDecl->getReturnType();
  26. }
  27. return decl->getType();
  28. }
  29. // Returns true if the given decl has the given semantic.
  30. bool hasSemantic(const DeclaratorDecl *decl,
  31. hlsl::DXIL::SemanticKind semanticKind) {
  32. using namespace hlsl;
  33. for (auto *annotation : decl->getUnusualAnnotations()) {
  34. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  35. llvm::StringRef semanticName;
  36. uint32_t semanticIndex = 0;
  37. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  38. &semanticIndex);
  39. const auto *semantic = Semantic::GetByName(semanticName);
  40. if (semantic->GetKind() == semanticKind)
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  47. for (const auto *param : pcf->parameters())
  48. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  49. return true;
  50. return false;
  51. }
  52. // TODO: Maybe we should move these type probing functions to TypeTranslator.
  53. /// Returns true if the given type is a bool or vector of bool type.
  54. bool isBoolOrVecOfBoolType(QualType type) {
  55. QualType elemType = {};
  56. return (TypeTranslator::isScalarType(type, &elemType) ||
  57. TypeTranslator::isVectorType(type, &elemType)) &&
  58. elemType->isBooleanType();
  59. }
  60. /// Returns true if the given type is a signed integer or vector of signed
  61. /// integer type.
  62. bool isSintOrVecOfSintType(QualType type) {
  63. QualType elemType = {};
  64. return (TypeTranslator::isScalarType(type, &elemType) ||
  65. TypeTranslator::isVectorType(type, &elemType)) &&
  66. elemType->isSignedIntegerType();
  67. }
  68. /// Returns true if the given type is an unsigned integer or vector of unsigned
  69. /// integer type.
  70. bool isUintOrVecOfUintType(QualType type) {
  71. QualType elemType = {};
  72. return (TypeTranslator::isScalarType(type, &elemType) ||
  73. TypeTranslator::isVectorType(type, &elemType)) &&
  74. elemType->isUnsignedIntegerType();
  75. }
  76. /// Returns true if the given type is a float or vector of float type.
  77. bool isFloatOrVecOfFloatType(QualType type) {
  78. QualType elemType = {};
  79. return (TypeTranslator::isScalarType(type, &elemType) ||
  80. TypeTranslator::isVectorType(type, &elemType)) &&
  81. elemType->isFloatingType();
  82. }
  83. /// Returns true if the given type is a bool or vector/matrix of bool type.
  84. bool isBoolOrVecMatOfBoolType(QualType type) {
  85. return isBoolOrVecOfBoolType(type) ||
  86. (hlsl::IsHLSLMatType(type) &&
  87. hlsl::GetHLSLMatElementType(type)->isBooleanType());
  88. }
  89. /// Returns true if the given type is a signed integer or vector/matrix of
  90. /// signed integer type.
  91. bool isSintOrVecMatOfSintType(QualType type) {
  92. return isSintOrVecOfSintType(type) ||
  93. (hlsl::IsHLSLMatType(type) &&
  94. hlsl::GetHLSLMatElementType(type)->isSignedIntegerType());
  95. }
  96. /// Returns true if the given type is an unsigned integer or vector/matrix of
  97. /// unsigned integer type.
  98. bool isUintOrVecMatOfUintType(QualType type) {
  99. return isUintOrVecOfUintType(type) ||
  100. (hlsl::IsHLSLMatType(type) &&
  101. hlsl::GetHLSLMatElementType(type)->isUnsignedIntegerType());
  102. }
  103. /// Returns true if the given type is a float or vector/matrix of float type.
  104. bool isFloatOrVecMatOfFloatType(QualType type) {
  105. return isFloatOrVecOfFloatType(type) ||
  106. (hlsl::IsHLSLMatType(type) &&
  107. hlsl::GetHLSLMatElementType(type)->isFloatingType());
  108. }
  109. inline bool isSpirvMatrixOp(spv::Op opcode) {
  110. return opcode == spv::Op::OpMatrixTimesMatrix ||
  111. opcode == spv::Op::OpMatrixTimesVector ||
  112. opcode == spv::Op::OpMatrixTimesScalar;
  113. }
  114. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  115. /// index. Otherwiser, returns false.
  116. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  117. // duplicate of doCXXMemberCallExpr.
  118. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  119. using namespace hlsl;
  120. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  121. const auto *callee = indexing->getDirectCallee();
  122. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  123. llvm::StringRef group;
  124. if (GetIntrinsicOp(callee, opcode, group)) {
  125. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  126. const auto *object = indexing->getImplicitObjectArgument();
  127. if (TypeTranslator::isStructuredBuffer(object->getType())) {
  128. *index = indexing->getArg(0);
  129. return indexing->getImplicitObjectArgument();
  130. }
  131. }
  132. }
  133. }
  134. return nullptr;
  135. }
  136. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  137. /// not in the Private or Function storage class.
  138. inline bool isExternalVar(const VarDecl *var) {
  139. // Class static variables should be put in the Private storage class.
  140. // groupshared variables are allowed to be declared as "static". But we still
  141. // need to put them in the Workgroup storage class. That is, when seeing
  142. // "static groupshared", ignore "static".
  143. return var->isExternallyVisible() ? !var->isStaticDataMember()
  144. : var->getAttr<HLSLGroupSharedAttr>();
  145. }
  146. /// Returns the referenced variable's DeclContext if the given expr is
  147. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  148. /// returns nullptr.
  149. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  150. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  151. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  152. if (const auto *bufferDecl =
  153. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  154. // Make sure we are not returning true for VarDecls inside
  155. // cbuffer/tbuffer.
  156. if (bufferDecl->isConstantBufferView())
  157. return varDecl->getType()->getAs<RecordType>()->getDecl();
  158. return nullptr;
  159. }
  160. /// Returns true if
  161. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  162. /// buffer and it is non-alias one, or
  163. /// * the given expr is an CallExpr returning a kind of structured or byte
  164. /// buffer.
  165. ///
  166. /// Note: legalization specific code
  167. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  168. expr = expr->IgnoreParenCasts();
  169. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  170. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  171. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  172. return isExternalVar(varDecl);
  173. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  174. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  175. return true;
  176. }
  177. return false;
  178. }
  179. bool spirvToolsLegalize(spv_target_env env, std::vector<uint32_t> *module,
  180. std::string *messages) {
  181. spvtools::Optimizer optimizer(env);
  182. optimizer.SetMessageConsumer(
  183. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  184. const spv_position_t & /*position*/,
  185. const char *message) { *messages += message; });
  186. optimizer.RegisterLegalizationPasses();
  187. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  188. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  189. return optimizer.Run(module->data(), module->size(), module);
  190. }
  191. bool spirvToolsOptimize(spv_target_env env, std::vector<uint32_t> *module,
  192. std::string *messages) {
  193. spvtools::Optimizer optimizer(env);
  194. optimizer.SetMessageConsumer(
  195. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  196. const spv_position_t & /*position*/,
  197. const char *message) { *messages += message; });
  198. optimizer.RegisterPerformancePasses();
  199. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  200. return optimizer.Run(module->data(), module->size(), module);
  201. }
  202. bool spirvToolsValidate(spv_target_env env, std::vector<uint32_t> *module,
  203. std::string *messages, bool relaxLogicalPointer) {
  204. spvtools::SpirvTools tools(env);
  205. tools.SetMessageConsumer(
  206. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  207. const spv_position_t & /*position*/,
  208. const char *message) { *messages += message; });
  209. spvtools::ValidatorOptions options;
  210. options.SetRelaxLogicalPointer(relaxLogicalPointer);
  211. return tools.Validate(module->data(), module->size(), options);
  212. }
  213. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  214. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  215. using namespace hlsl;
  216. using namespace spv;
  217. switch (opcode) {
  218. case IntrinsicOp::IOP_InterlockedAdd:
  219. case IntrinsicOp::MOP_InterlockedAdd:
  220. return Op::OpAtomicIAdd;
  221. case IntrinsicOp::IOP_InterlockedAnd:
  222. case IntrinsicOp::MOP_InterlockedAnd:
  223. return Op::OpAtomicAnd;
  224. case IntrinsicOp::IOP_InterlockedOr:
  225. case IntrinsicOp::MOP_InterlockedOr:
  226. return Op::OpAtomicOr;
  227. case IntrinsicOp::IOP_InterlockedXor:
  228. case IntrinsicOp::MOP_InterlockedXor:
  229. return Op::OpAtomicXor;
  230. case IntrinsicOp::IOP_InterlockedUMax:
  231. case IntrinsicOp::MOP_InterlockedUMax:
  232. return Op::OpAtomicUMax;
  233. case IntrinsicOp::IOP_InterlockedUMin:
  234. case IntrinsicOp::MOP_InterlockedUMin:
  235. return Op::OpAtomicUMin;
  236. case IntrinsicOp::IOP_InterlockedMax:
  237. case IntrinsicOp::MOP_InterlockedMax:
  238. return Op::OpAtomicSMax;
  239. case IntrinsicOp::IOP_InterlockedMin:
  240. case IntrinsicOp::MOP_InterlockedMin:
  241. return Op::OpAtomicSMin;
  242. case IntrinsicOp::IOP_InterlockedExchange:
  243. case IntrinsicOp::MOP_InterlockedExchange:
  244. return Op::OpAtomicExchange;
  245. }
  246. assert(false && "unimplemented hlsl intrinsic opcode");
  247. return Op::Max;
  248. }
  249. // Returns true if the given opcode is an accepted binary opcode in
  250. // OpSpecConstantOp.
  251. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  252. switch (op) {
  253. case spv::Op::OpIAdd:
  254. case spv::Op::OpISub:
  255. case spv::Op::OpIMul:
  256. case spv::Op::OpUDiv:
  257. case spv::Op::OpSDiv:
  258. case spv::Op::OpUMod:
  259. case spv::Op::OpSRem:
  260. case spv::Op::OpSMod:
  261. case spv::Op::OpShiftRightLogical:
  262. case spv::Op::OpShiftRightArithmetic:
  263. case spv::Op::OpShiftLeftLogical:
  264. case spv::Op::OpBitwiseOr:
  265. case spv::Op::OpBitwiseXor:
  266. case spv::Op::OpBitwiseAnd:
  267. case spv::Op::OpVectorShuffle:
  268. case spv::Op::OpCompositeExtract:
  269. case spv::Op::OpCompositeInsert:
  270. case spv::Op::OpLogicalOr:
  271. case spv::Op::OpLogicalAnd:
  272. case spv::Op::OpLogicalNot:
  273. case spv::Op::OpLogicalEqual:
  274. case spv::Op::OpLogicalNotEqual:
  275. case spv::Op::OpIEqual:
  276. case spv::Op::OpINotEqual:
  277. case spv::Op::OpULessThan:
  278. case spv::Op::OpSLessThan:
  279. case spv::Op::OpUGreaterThan:
  280. case spv::Op::OpSGreaterThan:
  281. case spv::Op::OpULessThanEqual:
  282. case spv::Op::OpSLessThanEqual:
  283. case spv::Op::OpUGreaterThanEqual:
  284. case spv::Op::OpSGreaterThanEqual:
  285. return true;
  286. }
  287. return false;
  288. }
  289. /// Returns true if the given expression is an accepted initializer for a spec
  290. /// constant.
  291. bool isAcceptedSpecConstantInit(const Expr *init) {
  292. // Allow numeric casts
  293. init = init->IgnoreParenCasts();
  294. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  295. isa<FloatingLiteral>(init))
  296. return true;
  297. // Allow the minus operator which is used to specify negative values
  298. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  299. return unaryOp->getOpcode() == UO_Minus &&
  300. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  301. return false;
  302. }
  303. /// Returns true if the given function parameter can act as shader stage
  304. /// input parameter.
  305. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  306. // If the parameter has no in/out/inout attribute, it is defaulted to
  307. // an in parameter.
  308. return !param->hasAttr<HLSLOutAttr>() &&
  309. // GS output streams are marked as inout, but it should not be
  310. // used as in parameter.
  311. !hlsl::IsHLSLStreamOutputType(param->getType());
  312. }
  313. /// Returns true if the given function parameter can act as shader stage
  314. /// output parameter.
  315. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  316. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>();
  317. }
  318. /// Returns true if the given expression is of builtin type and can be evaluated
  319. /// to a constant zero. Returns false otherwise.
  320. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  321. const auto type = expr->getType();
  322. if (!type->isBuiltinType())
  323. return false;
  324. Expr::EvalResult evalResult;
  325. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  326. !evalResult.HasSideEffects) {
  327. const auto &val = evalResult.Val;
  328. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  329. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  330. (type->isFloatingType() && val.getFloat().isZero()));
  331. }
  332. return false;
  333. }
  334. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  335. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  336. /// TextureBuffer itself.
  337. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  338. if (const auto *bufferDecl =
  339. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  340. // Filter ConstantBuffer/TextureBuffer
  341. if (!bufferDecl->isConstantBufferView())
  342. return bufferDecl;
  343. return nullptr;
  344. }
  345. /// Returns the real definition of the callee of the given CallExpr.
  346. ///
  347. /// If we are calling a forward-declared function, callee will be the
  348. /// FunctionDecl for the foward-declared function, not the actual
  349. /// definition. The foward-delcaration and defintion are two completely
  350. /// different AST nodes.
  351. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  352. const auto *callee = expr->getDirectCallee();
  353. if (callee->isThisDeclarationADefinition())
  354. return callee;
  355. // We need to update callee to the actual definition here
  356. if (!callee->isDefined(callee))
  357. return nullptr;
  358. return callee;
  359. }
  360. /// Returns the referenced definition. The given expr is expected to be a
  361. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  362. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  363. if (!expr)
  364. return nullptr;
  365. expr = expr->IgnoreParenCasts();
  366. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  367. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  368. }
  369. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  370. return getCalleeDefinition(callExpr);
  371. }
  372. return nullptr;
  373. }
  374. /// Returns the number of base classes if this type is a derived class/struct.
  375. /// Returns zero otherwise.
  376. inline uint32_t getNumBaseClasses(QualType type) {
  377. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  378. return cxxDecl->getNumBases();
  379. return 0;
  380. }
  381. /// Gets the index sequence of casting a derived object to a base object by
  382. /// following the cast chain.
  383. void getBaseClassIndices(const CastExpr *expr,
  384. llvm::SmallVectorImpl<uint32_t> *indices) {
  385. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  386. expr->getCastKind() == CK_HLSLDerivedToBase);
  387. indices->clear();
  388. QualType derivedType = expr->getSubExpr()->getType();
  389. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  390. // Go through the base cast chain: for each of the derived to base cast, find
  391. // the index of the base in question in the derived's bases.
  392. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  393. pathIt != pathIe; ++pathIt) {
  394. // The type of the base in question
  395. const auto baseType = (*pathIt)->getType();
  396. uint32_t index = 0;
  397. for (auto baseIt = derivedDecl->bases_begin(),
  398. baseIe = derivedDecl->bases_end();
  399. baseIt != baseIe; ++baseIt, ++index)
  400. if (baseIt->getType() == baseType) {
  401. indices->push_back(index);
  402. break;
  403. }
  404. assert(index < derivedDecl->getNumBases());
  405. // Continue to proceed the next base in the chain
  406. derivedType = baseType;
  407. derivedDecl = derivedType->getAsCXXRecordDecl();
  408. }
  409. }
  410. spv::Capability getCapabilityForGroupNonUniform(spv::Op opcode) {
  411. switch (opcode) {
  412. case spv::Op::OpGroupNonUniformElect:
  413. return spv::Capability::GroupNonUniform;
  414. case spv::Op::OpGroupNonUniformAny:
  415. case spv::Op::OpGroupNonUniformAll:
  416. case spv::Op::OpGroupNonUniformAllEqual:
  417. return spv::Capability::GroupNonUniformVote;
  418. case spv::Op::OpGroupNonUniformBallot:
  419. case spv::Op::OpGroupNonUniformBallotBitCount:
  420. case spv::Op::OpGroupNonUniformBroadcast:
  421. case spv::Op::OpGroupNonUniformBroadcastFirst:
  422. return spv::Capability::GroupNonUniformBallot;
  423. case spv::Op::OpGroupNonUniformIAdd:
  424. case spv::Op::OpGroupNonUniformFAdd:
  425. case spv::Op::OpGroupNonUniformIMul:
  426. case spv::Op::OpGroupNonUniformFMul:
  427. case spv::Op::OpGroupNonUniformSMax:
  428. case spv::Op::OpGroupNonUniformUMax:
  429. case spv::Op::OpGroupNonUniformFMax:
  430. case spv::Op::OpGroupNonUniformSMin:
  431. case spv::Op::OpGroupNonUniformUMin:
  432. case spv::Op::OpGroupNonUniformFMin:
  433. case spv::Op::OpGroupNonUniformBitwiseAnd:
  434. case spv::Op::OpGroupNonUniformBitwiseOr:
  435. case spv::Op::OpGroupNonUniformBitwiseXor:
  436. return spv::Capability::GroupNonUniformArithmetic;
  437. case spv::Op::OpGroupNonUniformQuadBroadcast:
  438. case spv::Op::OpGroupNonUniformQuadSwap:
  439. return spv::Capability::GroupNonUniformQuad;
  440. }
  441. assert(false && "unhandled opcode");
  442. return spv::Capability::Max;
  443. }
  444. } // namespace
  445. SPIRVEmitter::SPIRVEmitter(CompilerInstance &ci,
  446. const EmitSPIRVOptions &options)
  447. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  448. diags(ci.getDiagnostics()), spirvOptions(options),
  449. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction),
  450. shaderModel(*hlsl::ShaderModel::GetByName(
  451. ci.getCodeGenOpts().HLSLProfile.c_str())),
  452. theContext(), theBuilder(&theContext),
  453. declIdMapper(shaderModel, astContext, theBuilder, spirvOptions),
  454. typeTranslator(astContext, theBuilder, diags, options),
  455. entryFunctionId(0), curFunction(nullptr), curThis(0),
  456. seenPushConstantAt(), isSpecConstantMode(false), needsLegalization(false),
  457. needsSpirv1p3(false) {
  458. if (shaderModel.GetKind() == hlsl::ShaderModel::Kind::Invalid)
  459. emitError("unknown shader module: %0", {}) << shaderModel.GetName();
  460. if (options.invertY && !shaderModel.IsVS() && !shaderModel.IsDS() &&
  461. !shaderModel.IsGS())
  462. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  463. }
  464. void SPIRVEmitter::HandleTranslationUnit(ASTContext &context) {
  465. // Stop translating if there are errors in previous compilation stages.
  466. if (context.getDiagnostics().hasErrorOccurred())
  467. return;
  468. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  469. // The entry function is the seed of the queue.
  470. for (auto *decl : tu->decls()) {
  471. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  472. if (funcDecl->getName() == entryFunctionName) {
  473. workQueue.insert(funcDecl);
  474. }
  475. } else {
  476. // If ignoring unused resources, defer Decl handling inside
  477. // TranslationUnit to the time of first referencing.
  478. if (!spirvOptions.ignoreUnusedResources) {
  479. doDecl(decl);
  480. }
  481. }
  482. }
  483. // Translate all functions reachable from the entry function.
  484. // The queue can grow in the meanwhile; so need to keep evaluating
  485. // workQueue.size().
  486. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  487. doDecl(workQueue[i]);
  488. }
  489. if (context.getDiagnostics().hasErrorOccurred())
  490. return;
  491. spv_target_env targetEnv = SPV_ENV_VULKAN_1_0;
  492. if (needsSpirv1p3) {
  493. theBuilder.useSpirv1p3();
  494. targetEnv = SPV_ENV_VULKAN_1_1;
  495. }
  496. AddRequiredCapabilitiesForShaderModel();
  497. // Addressing and memory model are required in a valid SPIR-V module.
  498. theBuilder.setAddressingModel(spv::AddressingModel::Logical);
  499. theBuilder.setMemoryModel(spv::MemoryModel::GLSL450);
  500. theBuilder.addEntryPoint(getSpirvShaderStage(shaderModel), entryFunctionId,
  501. entryFunctionName, declIdMapper.collectStageVars());
  502. // Add Location decorations to stage input/output variables.
  503. if (!declIdMapper.decorateStageIOLocations())
  504. return;
  505. // Add descriptor set and binding decorations to resource variables.
  506. if (!declIdMapper.decorateResourceBindings())
  507. return;
  508. // Output the constructed module.
  509. std::vector<uint32_t> m = theBuilder.takeModule();
  510. if (!spirvOptions.codeGenHighLevel) {
  511. // Run legalization passes
  512. if (needsLegalization || declIdMapper.requiresLegalization()) {
  513. std::string messages;
  514. if (!spirvToolsLegalize(targetEnv, &m, &messages)) {
  515. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  516. emitNote("please file a bug report on "
  517. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  518. "with source code if possible",
  519. {});
  520. return;
  521. } else if (!messages.empty()) {
  522. emitWarning("SPIR-V legalization: %0", {}) << messages;
  523. }
  524. }
  525. // Run optimization passes
  526. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  527. std::string messages;
  528. if (!spirvToolsOptimize(targetEnv, &m, &messages)) {
  529. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  530. emitNote("please file a bug report on "
  531. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  532. "with source code if possible",
  533. {});
  534. return;
  535. }
  536. }
  537. }
  538. // Validate the generated SPIR-V code
  539. if (!spirvOptions.disableValidation) {
  540. std::string messages;
  541. if (!spirvToolsValidate(targetEnv, &m, &messages,
  542. declIdMapper.requiresLegalization())) {
  543. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  544. emitNote("please file a bug report on "
  545. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  546. "with source code if possible",
  547. {});
  548. return;
  549. }
  550. }
  551. theCompilerInstance.getOutStream()->write(
  552. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  553. }
  554. void SPIRVEmitter::doDecl(const Decl *decl) {
  555. if (decl->isImplicit() || isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  556. return;
  557. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  558. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  559. // to emit their cbuffer/tbuffer as a whole and access each individual one
  560. // using access chains.
  561. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  562. doHLSLBufferDecl(bufferDecl);
  563. } else {
  564. doVarDecl(varDecl);
  565. }
  566. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  567. doFunctionDecl(funcDecl);
  568. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  569. doHLSLBufferDecl(bufferDecl);
  570. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  571. doRecordDecl(recordDecl);
  572. } else {
  573. emitError("decl type %0 unimplemented", decl->getLocation())
  574. << decl->getDeclKindName();
  575. }
  576. }
  577. void SPIRVEmitter::doStmt(const Stmt *stmt,
  578. llvm::ArrayRef<const Attr *> attrs) {
  579. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  580. for (auto *st : compoundStmt->body())
  581. doStmt(st);
  582. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  583. doReturnStmt(retStmt);
  584. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  585. doDeclStmt(declStmt);
  586. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  587. doIfStmt(ifStmt, attrs);
  588. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  589. doSwitchStmt(switchStmt, attrs);
  590. } else if (const auto *caseStmt = dyn_cast<CaseStmt>(stmt)) {
  591. processCaseStmtOrDefaultStmt(stmt);
  592. } else if (const auto *defaultStmt = dyn_cast<DefaultStmt>(stmt)) {
  593. processCaseStmtOrDefaultStmt(stmt);
  594. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  595. doBreakStmt(breakStmt);
  596. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  597. doDoStmt(theDoStmt, attrs);
  598. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  599. doDiscardStmt(discardStmt);
  600. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  601. doContinueStmt(continueStmt);
  602. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  603. doWhileStmt(whileStmt, attrs);
  604. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  605. doForStmt(forStmt, attrs);
  606. } else if (const auto *nullStmt = dyn_cast<NullStmt>(stmt)) {
  607. // For the null statement ";". We don't need to do anything.
  608. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  609. // All cases for expressions used as statements
  610. doExpr(expr);
  611. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  612. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  613. } else {
  614. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  615. << stmt->getStmtClassName() << stmt->getSourceRange();
  616. }
  617. }
  618. SpirvEvalInfo SPIRVEmitter::doDeclRefExpr(const DeclRefExpr *expr) {
  619. const auto *decl = expr->getDecl();
  620. auto id = declIdMapper.getDeclEvalInfo(decl, false);
  621. if (spirvOptions.ignoreUnusedResources && !id) {
  622. // First time referencing a Decl inside TranslationUnit. Register
  623. // into DeclResultIdMapper and emit SPIR-V for it and then query
  624. // again.
  625. doDecl(decl);
  626. id = declIdMapper.getDeclEvalInfo(decl);
  627. }
  628. return id;
  629. }
  630. SpirvEvalInfo SPIRVEmitter::doExpr(const Expr *expr) {
  631. SpirvEvalInfo result(/*id*/ 0);
  632. // Provide a hint to the typeTranslator that if a literal is discovered, its
  633. // intended usage is as this expression type.
  634. TypeTranslator::LiteralTypeHint hint(typeTranslator, expr->getType());
  635. expr = expr->IgnoreParens();
  636. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  637. result = doDeclRefExpr(declRefExpr);
  638. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  639. result = doMemberExpr(memberExpr);
  640. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  641. result = doCastExpr(castExpr);
  642. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  643. result = doInitListExpr(initListExpr);
  644. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  645. const auto value =
  646. theBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  647. result = SpirvEvalInfo(value).setConstant().setRValue();
  648. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  649. const auto value = translateAPInt(intLiteral->getValue(), expr->getType());
  650. result = SpirvEvalInfo(value).setConstant().setRValue();
  651. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  652. const auto value =
  653. translateAPFloat(floatLiteral->getValue(), expr->getType());
  654. result = SpirvEvalInfo(value).setConstant().setRValue();
  655. } else if (const auto *compoundAssignOp =
  656. dyn_cast<CompoundAssignOperator>(expr)) {
  657. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  658. // checked before BinaryOperator.
  659. result = doCompoundAssignOperator(compoundAssignOp);
  660. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  661. result = doBinaryOperator(binOp);
  662. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  663. result = doUnaryOperator(unaryOp);
  664. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  665. result = doHLSLVectorElementExpr(vecElemExpr);
  666. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  667. result = doExtMatrixElementExpr(matElemExpr);
  668. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  669. result = doCallExpr(funcCall);
  670. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  671. result = doArraySubscriptExpr(subscriptExpr);
  672. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  673. result = doConditionalOperator(condExpr);
  674. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  675. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  676. } else if (isa<CXXThisExpr>(expr)) {
  677. assert(curThis);
  678. result = curThis;
  679. } else {
  680. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  681. << expr->getStmtClassName() << expr->getSourceRange();
  682. }
  683. return result;
  684. }
  685. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr) {
  686. // We are trying to load the value here, which is what an LValueToRValue
  687. // implicit cast is intended to do. We can ignore the cast if exists.
  688. expr = expr->IgnoreParenLValueCasts();
  689. return loadIfGLValue(expr, doExpr(expr));
  690. }
  691. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr,
  692. SpirvEvalInfo info) {
  693. // Do nothing if this is already rvalue
  694. if (info.isRValue())
  695. return info;
  696. // Check whether we are trying to load an externally visible structured/byte
  697. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  698. // the load and write the pointer directly to the alias variable then.
  699. //
  700. // Also for the case of alias function returns. If we are trying to load an
  701. // alias function return as a whole, it means we are assigning it to another
  702. // alias variable. Avoid the load and write the pointer directly.
  703. //
  704. // Note: legalization specific code
  705. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  706. return info.setRValue();
  707. }
  708. if (loadIfAliasVarRef(expr, info)) {
  709. // We are loading an alias variable as a whole here. This is likely for
  710. // wholesale assignments or function returns. Need to load the pointer.
  711. //
  712. // Note: legalization specific code
  713. return info;
  714. }
  715. uint32_t valType = 0;
  716. // TODO: Ouch. Very hacky. We need special path to get the value type if
  717. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  718. // type translation path won't work.
  719. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  720. valType = declIdMapper.getCTBufferPushConstantTypeId(declContext);
  721. } else {
  722. valType = typeTranslator.translateType(
  723. expr->getType(), info.getLayoutRule(), info.isRowMajor());
  724. }
  725. return info.setResultId(theBuilder.createLoad(valType, info)).setRValue();
  726. }
  727. SpirvEvalInfo SPIRVEmitter::loadIfAliasVarRef(const Expr *expr) {
  728. auto info = doExpr(expr);
  729. loadIfAliasVarRef(expr, info);
  730. return info;
  731. }
  732. bool SPIRVEmitter::loadIfAliasVarRef(const Expr *varExpr, SpirvEvalInfo &info) {
  733. if (info.containsAliasComponent() &&
  734. TypeTranslator::isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  735. // Aliased-to variables are all in the Uniform storage class with GLSL
  736. // std430 layout rules.
  737. const auto ptrType = typeTranslator.translateType(varExpr->getType());
  738. // Load the pointer of the aliased-to-variable if the expression has a
  739. // pointer to pointer type. That is, the expression itself is a lvalue.
  740. // (Note that we translate alias function return values as pointer types,
  741. // not pointer to pointer types.)
  742. if (varExpr->isGLValue())
  743. info.setResultId(theBuilder.createLoad(ptrType, info));
  744. info.setStorageClass(spv::StorageClass::Uniform)
  745. .setLayoutRule(LayoutRule::GLSLStd430)
  746. // Now it is a pointer to the global resource, which is lvalue.
  747. .setRValue(false)
  748. // Set to false to indicate that we've performed dereference over the
  749. // pointer-to-pointer and now should fallback to the normal path
  750. .setContainsAliasComponent(false);
  751. return true;
  752. }
  753. return false;
  754. }
  755. uint32_t SPIRVEmitter::castToType(uint32_t value, QualType fromType,
  756. QualType toType, SourceLocation srcLoc) {
  757. if (isFloatOrVecOfFloatType(toType))
  758. return castToFloat(value, fromType, toType, srcLoc);
  759. // Order matters here. Bool (vector) values will also be considered as uint
  760. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  761. // will also return true. We need to check bool before uint. The opposite is
  762. // not true.
  763. if (isBoolOrVecOfBoolType(toType))
  764. return castToBool(value, fromType, toType);
  765. if (isSintOrVecOfSintType(toType) || isUintOrVecOfUintType(toType))
  766. return castToInt(value, fromType, toType, srcLoc);
  767. emitError("casting to type %0 unimplemented", {}) << toType;
  768. return 0;
  769. }
  770. void SPIRVEmitter::doFunctionDecl(const FunctionDecl *decl) {
  771. assert(decl->isThisDeclarationADefinition());
  772. // A RAII class for maintaining the current function under traversal.
  773. class FnEnvRAII {
  774. public:
  775. // Creates a new instance which sets fnEnv to the newFn on creation,
  776. // and resets fnEnv to its original value on destruction.
  777. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  778. : oldFn(*fnEnv), fnSlot(fnEnv) {
  779. *fnEnv = newFn;
  780. }
  781. ~FnEnvRAII() { *fnSlot = oldFn; }
  782. private:
  783. const FunctionDecl *oldFn;
  784. const FunctionDecl **fnSlot;
  785. };
  786. FnEnvRAII fnEnvRAII(&curFunction, decl);
  787. // We are about to start translation for a new function. Clear the break stack
  788. // and the continue stack.
  789. breakStack = std::stack<uint32_t>();
  790. continueStack = std::stack<uint32_t>();
  791. std::string funcName = decl->getName();
  792. uint32_t funcId = 0;
  793. if (funcName == entryFunctionName) {
  794. // The entry function surely does not have pre-assigned <result-id> for
  795. // it like other functions that got added to the work queue following
  796. // function calls.
  797. funcId = theContext.takeNextId();
  798. funcName = "src." + funcName;
  799. // Create wrapper for the entry function
  800. if (!emitEntryFunctionWrapper(decl, funcId))
  801. return;
  802. } else {
  803. // Non-entry functions are added to the work queue following function
  804. // calls. We have already assigned <result-id>s for it when translating
  805. // its call site. Query it here.
  806. funcId = declIdMapper.getDeclEvalInfo(decl);
  807. }
  808. const uint32_t retType =
  809. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  810. // Construct the function signature.
  811. llvm::SmallVector<uint32_t, 4> paramTypes;
  812. bool isNonStaticMemberFn = false;
  813. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  814. isNonStaticMemberFn = !memberFn->isStatic();
  815. if (isNonStaticMemberFn) {
  816. // For non-static member function, the first parameter should be the
  817. // object on which we are invoking this method.
  818. const uint32_t valueType = typeTranslator.translateType(
  819. memberFn->getThisType(astContext)->getPointeeType());
  820. const uint32_t ptrType =
  821. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  822. paramTypes.push_back(ptrType);
  823. }
  824. // Prefix the function name with the struct name
  825. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  826. funcName = st->getName().str() + "." + funcName;
  827. }
  828. for (const auto *param : decl->params()) {
  829. const uint32_t valueType =
  830. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  831. const uint32_t ptrType =
  832. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  833. paramTypes.push_back(ptrType);
  834. }
  835. const uint32_t funcType = theBuilder.getFunctionType(retType, paramTypes);
  836. theBuilder.beginFunction(funcType, retType, funcName, funcId);
  837. if (isNonStaticMemberFn) {
  838. // Remember the parameter for the this object so later we can handle
  839. // CXXThisExpr correctly.
  840. curThis = theBuilder.addFnParam(paramTypes[0], "param.this");
  841. }
  842. // Create all parameters.
  843. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  844. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  845. (void)declIdMapper.createFnParam(paramDecl);
  846. }
  847. if (decl->hasBody()) {
  848. // The entry basic block.
  849. const uint32_t entryLabel = theBuilder.createBasicBlock("bb.entry");
  850. theBuilder.setInsertPoint(entryLabel);
  851. // Process all statments in the body.
  852. doStmt(decl->getBody());
  853. // We have processed all Stmts in this function and now in the last
  854. // basic block. Make sure we have a termination instruction.
  855. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  856. const auto retType = decl->getReturnType();
  857. if (retType->isVoidType()) {
  858. theBuilder.createReturn();
  859. } else {
  860. // If the source code does not provide a proper return value for some
  861. // control flow path, it's undefined behavior. We just return null
  862. // value here.
  863. theBuilder.createReturnValue(
  864. theBuilder.getConstantNull(typeTranslator.translateType(retType)));
  865. }
  866. }
  867. }
  868. theBuilder.endFunction();
  869. }
  870. bool SPIRVEmitter::validateVKAttributes(const NamedDecl *decl) {
  871. bool success = true;
  872. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  873. const auto varType = varDecl->getType();
  874. if ((TypeTranslator::isSubpassInput(varType) ||
  875. TypeTranslator::isSubpassInputMS(varType)) &&
  876. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  877. emitError("missing vk::input_attachment_index attribute",
  878. varDecl->getLocation());
  879. success = false;
  880. }
  881. }
  882. if (const auto *iaiAttr = decl->getAttr<VKInputAttachmentIndexAttr>()) {
  883. if (!shaderModel.IsPS()) {
  884. emitError("SubpassInput(MS) only allowed in pixel shader",
  885. decl->getLocation());
  886. success = false;
  887. }
  888. if (!decl->isExternallyVisible()) {
  889. emitError("SubpassInput(MS) must be externally visible",
  890. decl->getLocation());
  891. success = false;
  892. }
  893. // We only allow VKInputAttachmentIndexAttr to be attached to global
  894. // variables. So it should be fine to cast here.
  895. const auto elementType =
  896. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  897. if (!TypeTranslator::isScalarType(elementType) &&
  898. !TypeTranslator::isVectorType(elementType)) {
  899. emitError(
  900. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  901. decl->getLocation());
  902. // Return directly to avoid further type processing, which will hit
  903. // asserts in TypeTranslator.
  904. return false;
  905. }
  906. }
  907. // The frontend will make sure that
  908. // * vk::push_constant applies to global variables of struct type
  909. // * vk::binding applies to global variables or cbuffers/tbuffers
  910. // * vk::counter_binding applies to global variables of RW/Append/Consume
  911. // StructuredBuffer
  912. // * vk::location applies to function parameters/returns and struct fields
  913. // So the only case we need to check co-existence is vk::push_constant and
  914. // vk::binding.
  915. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  916. const auto loc = pcAttr->getLocation();
  917. if (seenPushConstantAt.isInvalid()) {
  918. seenPushConstantAt = loc;
  919. } else {
  920. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  921. // There must be no more than one push constant block statically used
  922. // per shader entry point.
  923. // But we are checking whether there are more than one push constant
  924. // blocks defined. Tracking usage requires more work.
  925. emitError("cannot have more than one push constant block", loc);
  926. emitNote("push constant block previously defined here",
  927. seenPushConstantAt);
  928. success = false;
  929. }
  930. if (decl->hasAttr<VKBindingAttr>()) {
  931. emitError("vk::push_constant attribute cannot be used together with "
  932. "vk::binding attribute",
  933. loc);
  934. success = false;
  935. }
  936. }
  937. return success;
  938. }
  939. void SPIRVEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  940. // This is a cbuffer/tbuffer decl.
  941. // Check and emit warnings for member intializers which are not
  942. // supported in Vulkan
  943. for (const auto *member : bufferDecl->decls()) {
  944. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  945. if (const auto *init = varMember->getInit())
  946. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  947. "ignored since no equivalent in Vulkan",
  948. init->getExprLoc())
  949. << bufferDecl->isCBuffer() << init->getSourceRange();
  950. for (const auto *annotation : varMember->getUnusualAnnotations())
  951. if (const auto *packing = dyn_cast<hlsl::ConstantPacking>(annotation))
  952. emitWarning("packoffset ignored since not supported", packing->Loc);
  953. // We cannot handle external initialization of column-major matrices now.
  954. if (typeTranslator.isOrContainsNonFpColMajorMatrix(varMember->getType(),
  955. varMember)) {
  956. emitError("externally initialized non-floating-point column-major "
  957. "matrices not supported yet",
  958. varMember->getLocation());
  959. }
  960. }
  961. }
  962. if (!validateVKAttributes(bufferDecl))
  963. return;
  964. (void)declIdMapper.createCTBuffer(bufferDecl);
  965. }
  966. void SPIRVEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  967. // Ignore implict records
  968. // Somehow we'll have implicit records with:
  969. // static const int Length = count;
  970. // that can mess up with the normal CodeGen.
  971. if (recordDecl->isImplicit())
  972. return;
  973. // Handle each static member with inline initializer.
  974. // Each static member has a corresponding VarDecl inside the
  975. // RecordDecl. For those defined in the translation unit,
  976. // their VarDecls do not have initializer.
  977. for (auto *subDecl : recordDecl->decls())
  978. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  979. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  980. doVarDecl(varDecl);
  981. }
  982. void SPIRVEmitter::doVarDecl(const VarDecl *decl) {
  983. if (!validateVKAttributes(decl))
  984. return;
  985. // We cannot handle external initialization of column-major matrices now.
  986. if (isExternalVar(decl) &&
  987. typeTranslator.isOrContainsNonFpColMajorMatrix(decl->getType(), decl)) {
  988. emitError("externally initialized non-floating-point column-major "
  989. "matrices not supported yet",
  990. decl->getLocation());
  991. }
  992. if (decl->hasAttr<VKConstantIdAttr>()) {
  993. // This is a VarDecl for specialization constant.
  994. createSpecConstant(decl);
  995. return;
  996. }
  997. if (decl->hasAttr<VKPushConstantAttr>()) {
  998. // This is a VarDecl for PushConstant block.
  999. (void)declIdMapper.createPushConstant(decl);
  1000. return;
  1001. }
  1002. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  1003. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  1004. (void)declIdMapper.createCTBuffer(decl);
  1005. return;
  1006. }
  1007. uint32_t varId = 0;
  1008. // The contents in externally visible variables can be updated via the
  1009. // pipeline. They should be handled differently from file and function scope
  1010. // variables.
  1011. // File scope variables (static "global" and "local" variables) belongs to
  1012. // the Private storage class, while function scope variables (normal "local"
  1013. // variables) belongs to the Function storage class.
  1014. if (isExternalVar(decl)) {
  1015. varId = declIdMapper.createExternVar(decl);
  1016. } else {
  1017. // We already know the variable is not externally visible here. If it does
  1018. // not have local storage, it should be file scope variable.
  1019. const bool isFileScopeVar = !decl->hasLocalStorage();
  1020. if (isFileScopeVar)
  1021. varId = declIdMapper.createFileVar(decl, llvm::None);
  1022. else
  1023. varId = declIdMapper.createFnVar(decl, llvm::None);
  1024. // Emit OpStore to initialize the variable
  1025. // TODO: revert back to use OpVariable initializer
  1026. // We should only evaluate the initializer once for a static variable.
  1027. if (isFileScopeVar) {
  1028. if (decl->isStaticLocal()) {
  1029. initOnce(decl->getType(), decl->getName(), varId, decl->getInit());
  1030. } else {
  1031. // Defer to initialize these global variables at the beginning of the
  1032. // entry function.
  1033. toInitGloalVars.push_back(decl);
  1034. }
  1035. }
  1036. // Function local variables. Just emit OpStore at the current insert point.
  1037. else if (const Expr *init = decl->getInit()) {
  1038. if (const auto constId = tryToEvaluateAsConst(init))
  1039. theBuilder.createStore(varId, constId);
  1040. else
  1041. storeValue(varId, loadIfGLValue(init), decl->getType());
  1042. // Update counter variable associated with local variables
  1043. tryToAssignCounterVar(decl, init);
  1044. }
  1045. // Variables that are not externally visible and of opaque types should
  1046. // request legalization.
  1047. if (!needsLegalization && TypeTranslator::isOpaqueType(decl->getType()))
  1048. needsLegalization = true;
  1049. }
  1050. if (TypeTranslator::isRelaxedPrecisionType(decl->getType(), spirvOptions)) {
  1051. theBuilder.decorate(varId, spv::Decoration::RelaxedPrecision);
  1052. }
  1053. // All variables that are of opaque struct types should request legalization.
  1054. if (!needsLegalization && TypeTranslator::isOpaqueStructType(decl->getType()))
  1055. needsLegalization = true;
  1056. }
  1057. spv::LoopControlMask SPIRVEmitter::translateLoopAttribute(const Stmt *stmt,
  1058. const Attr &attr) {
  1059. switch (attr.getKind()) {
  1060. case attr::HLSLLoop:
  1061. case attr::HLSLFastOpt:
  1062. return spv::LoopControlMask::DontUnroll;
  1063. case attr::HLSLUnroll:
  1064. return spv::LoopControlMask::Unroll;
  1065. case attr::HLSLAllowUAVCondition:
  1066. emitWarning("unsupported allow_uav_condition attribute ignored",
  1067. stmt->getLocStart());
  1068. break;
  1069. default:
  1070. llvm_unreachable("found unknown loop attribute");
  1071. }
  1072. return spv::LoopControlMask::MaskNone;
  1073. }
  1074. void SPIRVEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1075. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1076. theBuilder.createKill();
  1077. // Some statements that alter the control flow (break, continue, return, and
  1078. // discard), require creation of a new basic block to hold any statement that
  1079. // may follow them.
  1080. const uint32_t newBB = theBuilder.createBasicBlock();
  1081. theBuilder.setInsertPoint(newBB);
  1082. }
  1083. void SPIRVEmitter::doDoStmt(const DoStmt *theDoStmt,
  1084. llvm::ArrayRef<const Attr *> attrs) {
  1085. // do-while loops are composed of:
  1086. //
  1087. // do {
  1088. // <body>
  1089. // } while(<check>);
  1090. //
  1091. // SPIR-V requires loops to have a merge basic block as well as a continue
  1092. // basic block. Even though do-while loops do not have an explicit continue
  1093. // block as in for-loops, we still do need to create a continue block.
  1094. //
  1095. // Since SPIR-V requires structured control flow, we need two more basic
  1096. // blocks, <header> and <merge>. <header> is the block before control flow
  1097. // diverges, and <merge> is the block where control flow subsequently
  1098. // converges. The <check> can be performed in the <continue> basic block.
  1099. // The final CFG should normally be like the following. Exceptions
  1100. // will occur with non-local exits like loop breaks or early returns.
  1101. //
  1102. // +----------+
  1103. // | header | <-----------------------------------+
  1104. // +----------+ |
  1105. // | | (true)
  1106. // v |
  1107. // +------+ +--------------------+ |
  1108. // | body | ----> | continue (<check>) |-----------+
  1109. // +------+ +--------------------+
  1110. // |
  1111. // | (false)
  1112. // +-------+ |
  1113. // | merge | <-------------+
  1114. // +-------+
  1115. //
  1116. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1117. const spv::LoopControlMask loopControl =
  1118. attrs.empty() ? spv::LoopControlMask::MaskNone
  1119. : translateLoopAttribute(theDoStmt, *attrs.front());
  1120. // Create basic blocks
  1121. const uint32_t headerBB = theBuilder.createBasicBlock("do_while.header");
  1122. const uint32_t bodyBB = theBuilder.createBasicBlock("do_while.body");
  1123. const uint32_t continueBB = theBuilder.createBasicBlock("do_while.continue");
  1124. const uint32_t mergeBB = theBuilder.createBasicBlock("do_while.merge");
  1125. // Make sure any continue statements branch to the continue block, and any
  1126. // break statements branch to the merge block.
  1127. continueStack.push(continueBB);
  1128. breakStack.push(mergeBB);
  1129. // Branch from the current insert point to the header block.
  1130. theBuilder.createBranch(headerBB);
  1131. theBuilder.addSuccessor(headerBB);
  1132. // Process the <header> block
  1133. // The header block must always branch to the body.
  1134. theBuilder.setInsertPoint(headerBB);
  1135. theBuilder.createBranch(bodyBB, mergeBB, continueBB, loopControl);
  1136. theBuilder.addSuccessor(bodyBB);
  1137. // The current basic block has OpLoopMerge instruction. We need to set its
  1138. // continue and merge target.
  1139. theBuilder.setContinueTarget(continueBB);
  1140. theBuilder.setMergeTarget(mergeBB);
  1141. // Process the <body> block
  1142. theBuilder.setInsertPoint(bodyBB);
  1143. if (const Stmt *body = theDoStmt->getBody()) {
  1144. doStmt(body);
  1145. }
  1146. if (!theBuilder.isCurrentBasicBlockTerminated())
  1147. theBuilder.createBranch(continueBB);
  1148. theBuilder.addSuccessor(continueBB);
  1149. // Process the <continue> block. The check for whether the loop should
  1150. // continue lies in the continue block.
  1151. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1152. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1153. // OpBranchConditional must be specified.
  1154. theBuilder.setInsertPoint(continueBB);
  1155. uint32_t condition = 0;
  1156. if (const Expr *check = theDoStmt->getCond()) {
  1157. condition = doExpr(check);
  1158. } else {
  1159. condition = theBuilder.getConstantBool(true);
  1160. }
  1161. theBuilder.createConditionalBranch(condition, headerBB, mergeBB);
  1162. theBuilder.addSuccessor(headerBB);
  1163. theBuilder.addSuccessor(mergeBB);
  1164. // Set insertion point to the <merge> block for subsequent statements
  1165. theBuilder.setInsertPoint(mergeBB);
  1166. // Done with the current scope's continue block and merge block.
  1167. continueStack.pop();
  1168. breakStack.pop();
  1169. }
  1170. void SPIRVEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1171. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1172. const uint32_t continueTargetBB = continueStack.top();
  1173. theBuilder.createBranch(continueTargetBB);
  1174. theBuilder.addSuccessor(continueTargetBB);
  1175. // Some statements that alter the control flow (break, continue, return, and
  1176. // discard), require creation of a new basic block to hold any statement that
  1177. // may follow them. For example: StmtB and StmtC below are put inside a new
  1178. // basic block which is unreachable.
  1179. //
  1180. // while (true) {
  1181. // StmtA;
  1182. // continue;
  1183. // StmtB;
  1184. // StmtC;
  1185. // }
  1186. const uint32_t newBB = theBuilder.createBasicBlock();
  1187. theBuilder.setInsertPoint(newBB);
  1188. }
  1189. void SPIRVEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1190. llvm::ArrayRef<const Attr *> attrs) {
  1191. // While loops are composed of:
  1192. // while (<check>) { <body> }
  1193. //
  1194. // SPIR-V requires loops to have a merge basic block as well as a continue
  1195. // basic block. Even though while loops do not have an explicit continue
  1196. // block as in for-loops, we still do need to create a continue block.
  1197. //
  1198. // Since SPIR-V requires structured control flow, we need two more basic
  1199. // blocks, <header> and <merge>. <header> is the block before control flow
  1200. // diverges, and <merge> is the block where control flow subsequently
  1201. // converges. The <check> block can take the responsibility of the <header>
  1202. // block. The final CFG should normally be like the following. Exceptions
  1203. // will occur with non-local exits like loop breaks or early returns.
  1204. //
  1205. // +----------+
  1206. // | header | <------------------+
  1207. // | (check) | |
  1208. // +----------+ |
  1209. // | |
  1210. // +-------+-------+ |
  1211. // | false | true |
  1212. // | v |
  1213. // | +------+ +------------------+
  1214. // | | body | --> | continue (no-op) |
  1215. // v +------+ +------------------+
  1216. // +-------+
  1217. // | merge |
  1218. // +-------+
  1219. //
  1220. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1221. const spv::LoopControlMask loopControl =
  1222. attrs.empty() ? spv::LoopControlMask::MaskNone
  1223. : translateLoopAttribute(whileStmt, *attrs.front());
  1224. // Create basic blocks
  1225. const uint32_t checkBB = theBuilder.createBasicBlock("while.check");
  1226. const uint32_t bodyBB = theBuilder.createBasicBlock("while.body");
  1227. const uint32_t continueBB = theBuilder.createBasicBlock("while.continue");
  1228. const uint32_t mergeBB = theBuilder.createBasicBlock("while.merge");
  1229. // Make sure any continue statements branch to the continue block, and any
  1230. // break statements branch to the merge block.
  1231. continueStack.push(continueBB);
  1232. breakStack.push(mergeBB);
  1233. // Process the <check> block
  1234. theBuilder.createBranch(checkBB);
  1235. theBuilder.addSuccessor(checkBB);
  1236. theBuilder.setInsertPoint(checkBB);
  1237. // If we have:
  1238. // while (int a = foo()) {...}
  1239. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1240. // to occur.
  1241. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1242. doStmt(condVarDecl);
  1243. uint32_t condition = 0;
  1244. if (const Expr *check = whileStmt->getCond()) {
  1245. condition = doExpr(check);
  1246. } else {
  1247. condition = theBuilder.getConstantBool(true);
  1248. }
  1249. theBuilder.createConditionalBranch(condition, bodyBB,
  1250. /*false branch*/ mergeBB,
  1251. /*merge*/ mergeBB, continueBB,
  1252. spv::SelectionControlMask::MaskNone,
  1253. loopControl);
  1254. theBuilder.addSuccessor(bodyBB);
  1255. theBuilder.addSuccessor(mergeBB);
  1256. // The current basic block has OpLoopMerge instruction. We need to set its
  1257. // continue and merge target.
  1258. theBuilder.setContinueTarget(continueBB);
  1259. theBuilder.setMergeTarget(mergeBB);
  1260. // Process the <body> block
  1261. theBuilder.setInsertPoint(bodyBB);
  1262. if (const Stmt *body = whileStmt->getBody()) {
  1263. doStmt(body);
  1264. }
  1265. if (!theBuilder.isCurrentBasicBlockTerminated())
  1266. theBuilder.createBranch(continueBB);
  1267. theBuilder.addSuccessor(continueBB);
  1268. // Process the <continue> block. While loops do not have an explicit
  1269. // continue block. The continue block just branches to the <check> block.
  1270. theBuilder.setInsertPoint(continueBB);
  1271. theBuilder.createBranch(checkBB);
  1272. theBuilder.addSuccessor(checkBB);
  1273. // Set insertion point to the <merge> block for subsequent statements
  1274. theBuilder.setInsertPoint(mergeBB);
  1275. // Done with the current scope's continue and merge blocks.
  1276. continueStack.pop();
  1277. breakStack.pop();
  1278. }
  1279. void SPIRVEmitter::doForStmt(const ForStmt *forStmt,
  1280. llvm::ArrayRef<const Attr *> attrs) {
  1281. // for loops are composed of:
  1282. // for (<init>; <check>; <continue>) <body>
  1283. //
  1284. // To translate a for loop, we'll need to emit all <init> statements
  1285. // in the current basic block, and then have separate basic blocks for
  1286. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1287. // structured control flow, we need two more basic blocks, <header>
  1288. // and <merge>. <header> is the block before control flow diverges,
  1289. // while <merge> is the block where control flow subsequently converges.
  1290. // The <check> block can take the responsibility of the <header> block.
  1291. // The final CFG should normally be like the following. Exceptions will
  1292. // occur with non-local exits like loop breaks or early returns.
  1293. // +--------+
  1294. // | init |
  1295. // +--------+
  1296. // |
  1297. // v
  1298. // +----------+
  1299. // | header | <---------------+
  1300. // | (check) | |
  1301. // +----------+ |
  1302. // | |
  1303. // +-------+-------+ |
  1304. // | false | true |
  1305. // | v |
  1306. // | +------+ +----------+
  1307. // | | body | --> | continue |
  1308. // v +------+ +----------+
  1309. // +-------+
  1310. // | merge |
  1311. // +-------+
  1312. //
  1313. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1314. const spv::LoopControlMask loopControl =
  1315. attrs.empty() ? spv::LoopControlMask::MaskNone
  1316. : translateLoopAttribute(forStmt, *attrs.front());
  1317. // Create basic blocks
  1318. const uint32_t checkBB = theBuilder.createBasicBlock("for.check");
  1319. const uint32_t bodyBB = theBuilder.createBasicBlock("for.body");
  1320. const uint32_t continueBB = theBuilder.createBasicBlock("for.continue");
  1321. const uint32_t mergeBB = theBuilder.createBasicBlock("for.merge");
  1322. // Make sure any continue statements branch to the continue block, and any
  1323. // break statements branch to the merge block.
  1324. continueStack.push(continueBB);
  1325. breakStack.push(mergeBB);
  1326. // Process the <init> block
  1327. if (const Stmt *initStmt = forStmt->getInit()) {
  1328. doStmt(initStmt);
  1329. }
  1330. theBuilder.createBranch(checkBB);
  1331. theBuilder.addSuccessor(checkBB);
  1332. // Process the <check> block
  1333. theBuilder.setInsertPoint(checkBB);
  1334. uint32_t condition;
  1335. if (const Expr *check = forStmt->getCond()) {
  1336. condition = doExpr(check);
  1337. } else {
  1338. condition = theBuilder.getConstantBool(true);
  1339. }
  1340. theBuilder.createConditionalBranch(condition, bodyBB,
  1341. /*false branch*/ mergeBB,
  1342. /*merge*/ mergeBB, continueBB,
  1343. spv::SelectionControlMask::MaskNone,
  1344. loopControl);
  1345. theBuilder.addSuccessor(bodyBB);
  1346. theBuilder.addSuccessor(mergeBB);
  1347. // The current basic block has OpLoopMerge instruction. We need to set its
  1348. // continue and merge target.
  1349. theBuilder.setContinueTarget(continueBB);
  1350. theBuilder.setMergeTarget(mergeBB);
  1351. // Process the <body> block
  1352. theBuilder.setInsertPoint(bodyBB);
  1353. if (const Stmt *body = forStmt->getBody()) {
  1354. doStmt(body);
  1355. }
  1356. if (!theBuilder.isCurrentBasicBlockTerminated())
  1357. theBuilder.createBranch(continueBB);
  1358. theBuilder.addSuccessor(continueBB);
  1359. // Process the <continue> block
  1360. theBuilder.setInsertPoint(continueBB);
  1361. if (const Expr *cont = forStmt->getInc()) {
  1362. doExpr(cont);
  1363. }
  1364. theBuilder.createBranch(checkBB); // <continue> should jump back to header
  1365. theBuilder.addSuccessor(checkBB);
  1366. // Set insertion point to the <merge> block for subsequent statements
  1367. theBuilder.setInsertPoint(mergeBB);
  1368. // Done with the current scope's continue block and merge block.
  1369. continueStack.pop();
  1370. breakStack.pop();
  1371. }
  1372. void SPIRVEmitter::doIfStmt(const IfStmt *ifStmt,
  1373. llvm::ArrayRef<const Attr *> attrs) {
  1374. // if statements are composed of:
  1375. // if (<check>) { <then> } else { <else> }
  1376. //
  1377. // To translate if statements, we'll need to emit the <check> expressions
  1378. // in the current basic block, and then create separate basic blocks for
  1379. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1380. // SPIR-V's structured control flow requirements. Depending whether there
  1381. // exists the else branch, the final CFG should normally be like the
  1382. // following. Exceptions will occur with non-local exits like loop breaks
  1383. // or early returns.
  1384. // +-------+ +-------+
  1385. // | check | | check |
  1386. // +-------+ +-------+
  1387. // | |
  1388. // +-------+-------+ +-----+-----+
  1389. // | true | false | true | false
  1390. // v v or v |
  1391. // +------+ +------+ +------+ |
  1392. // | then | | else | | then | |
  1393. // +------+ +------+ +------+ |
  1394. // | | | v
  1395. // | +-------+ | | +-------+
  1396. // +-> | merge | <-+ +---> | merge |
  1397. // +-------+ +-------+
  1398. { // Try to see if we can const-eval the condition
  1399. bool condition = false;
  1400. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1401. if (condition) {
  1402. doStmt(ifStmt->getThen());
  1403. } else if (ifStmt->getElse()) {
  1404. doStmt(ifStmt->getElse());
  1405. }
  1406. return;
  1407. }
  1408. }
  1409. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1410. if (!attrs.empty()) {
  1411. const Attr *attribute = attrs.front();
  1412. switch (attribute->getKind()) {
  1413. case attr::HLSLBranch:
  1414. selectionControl = spv::SelectionControlMask::DontFlatten;
  1415. break;
  1416. case attr::HLSLFlatten:
  1417. selectionControl = spv::SelectionControlMask::Flatten;
  1418. break;
  1419. default:
  1420. emitWarning("unknown if statement attribute '%0' ignored",
  1421. attribute->getLocation())
  1422. << attribute->getSpelling();
  1423. break;
  1424. }
  1425. }
  1426. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1427. doDeclStmt(declStmt);
  1428. // First emit the instruction for evaluating the condition.
  1429. const uint32_t condition = doExpr(ifStmt->getCond());
  1430. // Then we need to emit the instruction for the conditional branch.
  1431. // We'll need the <label-id> for the then/else/merge block to do so.
  1432. const bool hasElse = ifStmt->getElse() != nullptr;
  1433. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  1434. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  1435. const uint32_t elseBB =
  1436. hasElse ? theBuilder.createBasicBlock("if.false") : mergeBB;
  1437. // Create the branch instruction. This will end the current basic block.
  1438. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB,
  1439. /*continue*/ 0, selectionControl);
  1440. theBuilder.addSuccessor(thenBB);
  1441. theBuilder.addSuccessor(elseBB);
  1442. // The current basic block has the OpSelectionMerge instruction. We need
  1443. // to record its merge target.
  1444. theBuilder.setMergeTarget(mergeBB);
  1445. // Handle the then branch
  1446. theBuilder.setInsertPoint(thenBB);
  1447. doStmt(ifStmt->getThen());
  1448. if (!theBuilder.isCurrentBasicBlockTerminated())
  1449. theBuilder.createBranch(mergeBB);
  1450. theBuilder.addSuccessor(mergeBB);
  1451. // Handle the else branch (if exists)
  1452. if (hasElse) {
  1453. theBuilder.setInsertPoint(elseBB);
  1454. doStmt(ifStmt->getElse());
  1455. if (!theBuilder.isCurrentBasicBlockTerminated())
  1456. theBuilder.createBranch(mergeBB);
  1457. theBuilder.addSuccessor(mergeBB);
  1458. }
  1459. // From now on, we'll emit instructions into the merge block.
  1460. theBuilder.setInsertPoint(mergeBB);
  1461. }
  1462. void SPIRVEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1463. if (const auto *retVal = stmt->getRetValue()) {
  1464. // Update counter variable associated with function returns
  1465. tryToAssignCounterVar(curFunction, retVal);
  1466. const auto retInfo = loadIfGLValue(retVal);
  1467. const auto retType = retVal->getType();
  1468. if (retInfo.getStorageClass() != spv::StorageClass::Function &&
  1469. retType->isStructureType()) {
  1470. // We are returning some value from a non-Function storage class. Need to
  1471. // create a temporary variable to "convert" the value to Function storage
  1472. // class and then return.
  1473. const uint32_t valType = typeTranslator.translateType(retType);
  1474. const uint32_t tempVar = theBuilder.addFnVar(valType, "temp.var.ret");
  1475. storeValue(tempVar, retInfo, retType);
  1476. theBuilder.createReturnValue(theBuilder.createLoad(valType, tempVar));
  1477. } else {
  1478. theBuilder.createReturnValue(retInfo);
  1479. }
  1480. } else {
  1481. theBuilder.createReturn();
  1482. }
  1483. // We are translating a ReturnStmt, we should be in some function's body.
  1484. assert(curFunction->hasBody());
  1485. // If this return statement is the last statement in the function, then
  1486. // whe have no more work to do.
  1487. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1488. return;
  1489. // Some statements that alter the control flow (break, continue, return, and
  1490. // discard), require creation of a new basic block to hold any statement that
  1491. // may follow them. In this case, the newly created basic block will contain
  1492. // any statement that may come after an early return.
  1493. const uint32_t newBB = theBuilder.createBasicBlock();
  1494. theBuilder.setInsertPoint(newBB);
  1495. }
  1496. void SPIRVEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1497. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1498. uint32_t breakTargetBB = breakStack.top();
  1499. theBuilder.addSuccessor(breakTargetBB);
  1500. theBuilder.createBranch(breakTargetBB);
  1501. // Some statements that alter the control flow (break, continue, return, and
  1502. // discard), require creation of a new basic block to hold any statement that
  1503. // may follow them. For example: StmtB and StmtC below are put inside a new
  1504. // basic block which is unreachable.
  1505. //
  1506. // while (true) {
  1507. // StmtA;
  1508. // break;
  1509. // StmtB;
  1510. // StmtC;
  1511. // }
  1512. const uint32_t newBB = theBuilder.createBasicBlock();
  1513. theBuilder.setInsertPoint(newBB);
  1514. }
  1515. void SPIRVEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1516. llvm::ArrayRef<const Attr *> attrs) {
  1517. // Switch statements are composed of:
  1518. // switch (<condition variable>) {
  1519. // <CaseStmt>
  1520. // <CaseStmt>
  1521. // <CaseStmt>
  1522. // <DefaultStmt> (optional)
  1523. // }
  1524. //
  1525. // +-------+
  1526. // | check |
  1527. // +-------+
  1528. // |
  1529. // +-------+-------+----------------+---------------+
  1530. // | 1 | 2 | 3 | (others)
  1531. // v v v v
  1532. // +-------+ +-------------+ +-------+ +------------+
  1533. // | case1 | | case2 | | case3 | ... | default |
  1534. // | | |(fallthrough)|---->| | | (optional) |
  1535. // +-------+ |+------------+ +-------+ +------------+
  1536. // | | |
  1537. // | | |
  1538. // | +-------+ | |
  1539. // | | | <--------------------+ |
  1540. // +-> | merge | |
  1541. // | | <-------------------------------------+
  1542. // +-------+
  1543. // If no attributes are given, or if "forcecase" attribute was provided,
  1544. // we'll do our best to use OpSwitch if possible.
  1545. // If any of the cases compares to a variable (rather than an integer
  1546. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1547. // numbers as parameters.
  1548. const bool isAttrForceCase =
  1549. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1550. const bool canUseSpirvOpSwitch =
  1551. (attrs.empty() || isAttrForceCase) &&
  1552. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1553. if (isAttrForceCase && !canUseSpirvOpSwitch)
  1554. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1555. "since one or more case values are not integer literals",
  1556. switchStmt->getLocStart());
  1557. if (canUseSpirvOpSwitch)
  1558. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1559. else
  1560. processSwitchStmtUsingIfStmts(switchStmt);
  1561. }
  1562. SpirvEvalInfo
  1563. SPIRVEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1564. llvm::SmallVector<uint32_t, 4> indices;
  1565. auto info = loadIfAliasVarRef(collectArrayStructIndices(expr, &indices));
  1566. if (!indices.empty()) {
  1567. (void)turnIntoElementPtr(info, expr->getType(), indices);
  1568. }
  1569. return info;
  1570. }
  1571. SpirvEvalInfo SPIRVEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1572. const auto opcode = expr->getOpcode();
  1573. // Handle assignment first since we need to evaluate rhs before lhs.
  1574. // For other binary operations, we need to evaluate lhs before rhs.
  1575. if (opcode == BO_Assign) {
  1576. // Update counter variable associated with lhs of assignments
  1577. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1578. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1579. /*isCompoundAssignment=*/false);
  1580. }
  1581. // Try to optimize floatMxN * float and floatN * float case
  1582. if (opcode == BO_Mul) {
  1583. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  1584. return result;
  1585. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  1586. return result;
  1587. }
  1588. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1589. expr->getLHS()->getType(), expr->getType(),
  1590. expr->getSourceRange());
  1591. }
  1592. SpirvEvalInfo SPIRVEmitter::doCallExpr(const CallExpr *callExpr) {
  1593. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1594. return doCXXOperatorCallExpr(operatorCall);
  1595. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1596. return doCXXMemberCallExpr(memberCall);
  1597. // Intrinsic functions such as 'dot' or 'mul'
  1598. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1599. return processIntrinsicCallExpr(callExpr);
  1600. }
  1601. // Normal standalone functions
  1602. return processCall(callExpr);
  1603. }
  1604. SpirvEvalInfo SPIRVEmitter::processCall(const CallExpr *callExpr) {
  1605. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1606. // Note that we always want the defintion because Stmts/Exprs in the
  1607. // function body references the parameters in the definition.
  1608. if (!callee) {
  1609. emitError("found undefined function", callExpr->getExprLoc());
  1610. return 0;
  1611. }
  1612. const auto numParams = callee->getNumParams();
  1613. bool isNonStaticMemberCall = false;
  1614. QualType objectType = {}; // Type of the object (if exists)
  1615. SpirvEvalInfo objectEvalInfo = 0; // EvalInfo for the object (if exists)
  1616. bool objectNeedsTempVar = false; // Temporary variable for lvalue object
  1617. llvm::SmallVector<uint32_t, 4> params; // Temporary variables
  1618. llvm::SmallVector<SpirvEvalInfo, 4> args; // Evaluated arguments
  1619. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1620. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1621. isNonStaticMemberCall = !memberFn->isStatic();
  1622. if (isNonStaticMemberCall) {
  1623. // For non-static member calls, evaluate the object and pass it as the
  1624. // first argument.
  1625. const auto *object = memberCall->getImplicitObjectArgument();
  1626. object = object->IgnoreParenNoopCasts(astContext);
  1627. // Update counter variable associated with the implicit object
  1628. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1629. objectType = object->getType();
  1630. objectEvalInfo = doExpr(object);
  1631. uint32_t objectId = objectEvalInfo;
  1632. // If not already a variable, we need to create a temporary variable and
  1633. // pass the object pointer to the function. Example:
  1634. // getObject().objectMethod();
  1635. bool needsTempVar = objectEvalInfo.isRValue();
  1636. // Try to see if we are calling methods on a global variable, which is put
  1637. // in the Private storage class. We also need to create temporary variable
  1638. // for it since the function signature expects all arguments in the
  1639. // Function storage class.
  1640. if (!needsTempVar)
  1641. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(object))
  1642. if (const auto *refDecl = declRefExpr->getFoundDecl())
  1643. if (const auto *varDecl = dyn_cast<VarDecl>(refDecl))
  1644. needsTempVar = objectNeedsTempVar = varDecl->hasGlobalStorage();
  1645. if (needsTempVar) {
  1646. objectId =
  1647. createTemporaryVar(objectType, TypeTranslator::getName(objectType),
  1648. // May need to load to use as initializer
  1649. loadIfGLValue(object, objectEvalInfo));
  1650. }
  1651. args.push_back(objectId);
  1652. // We do not need to create a new temporary variable for the this
  1653. // object. Use the evaluated argument.
  1654. params.push_back(args.back());
  1655. }
  1656. }
  1657. // Evaluate parameters
  1658. for (uint32_t i = 0; i < numParams; ++i) {
  1659. // We want the argument variable here so that we can write back to it
  1660. // later. We will do the OpLoad of this argument manually. So ingore
  1661. // the LValueToRValue implicit cast here.
  1662. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1663. const auto *param = callee->getParamDecl(i);
  1664. // We need to create variables for holding the values to be used as
  1665. // arguments. The variables themselves are of pointer types.
  1666. const uint32_t varType =
  1667. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1668. const std::string varName = "param.var." + param->getNameAsString();
  1669. const uint32_t tempVarId = theBuilder.addFnVar(varType, varName);
  1670. params.push_back(tempVarId);
  1671. args.push_back(doExpr(arg));
  1672. // Update counter variable associated with function parameters
  1673. tryToAssignCounterVar(param, arg);
  1674. // Manually load the argument here
  1675. const auto rhsVal = loadIfGLValue(arg, args.back());
  1676. // Initialize the temporary variables using the contents of the arguments
  1677. storeValue(tempVarId, rhsVal, param->getType());
  1678. }
  1679. // Push the callee into the work queue if it is not there.
  1680. if (!workQueue.count(callee)) {
  1681. workQueue.insert(callee);
  1682. }
  1683. const uint32_t retType =
  1684. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1685. // Get or forward declare the function <result-id>
  1686. const uint32_t funcId = declIdMapper.getOrRegisterFnResultId(callee);
  1687. const uint32_t retVal =
  1688. theBuilder.createFunctionCall(retType, funcId, params);
  1689. // If we created a temporary variable for the object this method is invoked
  1690. // upon, we need to copy the contents in the temporary variable back to the
  1691. // original object's variable in case there are side effects.
  1692. if (objectNeedsTempVar) {
  1693. const uint32_t typeId = typeTranslator.translateType(objectType);
  1694. const uint32_t value = theBuilder.createLoad(typeId, params.front());
  1695. storeValue(objectEvalInfo, value, objectType);
  1696. }
  1697. // Go through all parameters and write those marked as out/inout
  1698. for (uint32_t i = 0; i < numParams; ++i) {
  1699. const auto *param = callee->getParamDecl(i);
  1700. if (canActAsOutParmVar(param)) {
  1701. const auto *arg = callExpr->getArg(i);
  1702. const uint32_t index = i + isNonStaticMemberCall;
  1703. const uint32_t typeId = typeTranslator.translateType(param->getType());
  1704. const uint32_t value = theBuilder.createLoad(typeId, params[index]);
  1705. processAssignment(arg, value, false, args[index]);
  1706. }
  1707. }
  1708. // Inherit the SpirvEvalInfo from the function definition
  1709. return declIdMapper.getDeclEvalInfo(callee).setResultId(retVal);
  1710. }
  1711. SpirvEvalInfo SPIRVEmitter::doCastExpr(const CastExpr *expr) {
  1712. const Expr *subExpr = expr->getSubExpr();
  1713. const QualType subExprType = subExpr->getType();
  1714. const QualType toType = expr->getType();
  1715. // Unfortunately the front-end fails to deduce some types in certain cases.
  1716. // Provide a hint about literal type usage if possible.
  1717. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  1718. // 'literal int' to 'float' conversion. If a literal integer is to be used as
  1719. // a 32-bit float, the hint is a 32-bit integer.
  1720. if (toType->isFloatingType() &&
  1721. subExprType->isSpecificBuiltinType(BuiltinType::LitInt) &&
  1722. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1723. 32)
  1724. hint.setHint(astContext.IntTy);
  1725. // 'literal float' to 'float' conversion where intended type is float32.
  1726. if (toType->isFloatingType() &&
  1727. subExprType->isSpecificBuiltinType(BuiltinType::LitFloat) &&
  1728. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1729. 32)
  1730. hint.setHint(astContext.FloatTy);
  1731. // TODO: We could provide other useful hints. For instance:
  1732. // For the case of toType being a boolean, if the fromType is a literal float,
  1733. // we could provide a FloatTy hint and if the fromType is a literal integer,
  1734. // we could provide an IntTy hint. The front-end, however, seems to deduce the
  1735. // correct type in these cases; therefore we currently don't provide any
  1736. // additional hints.
  1737. switch (expr->getCastKind()) {
  1738. case CastKind::CK_LValueToRValue:
  1739. return loadIfGLValue(subExpr);
  1740. case CastKind::CK_NoOp:
  1741. return doExpr(subExpr);
  1742. case CastKind::CK_IntegralCast:
  1743. case CastKind::CK_FloatingToIntegral:
  1744. case CastKind::CK_HLSLCC_IntegralCast:
  1745. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1746. // Integer literals in the AST are represented using 64bit APInt
  1747. // themselves and then implicitly casted into the expected bitwidth.
  1748. // We need special treatment of integer literals here because generating
  1749. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1750. // capability. We should avoid introducing unnecessary capabilities to
  1751. // our best.
  1752. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1753. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1754. const auto valueId =
  1755. castToInt(doExpr(subExpr), subExprType, toType, subExpr->getExprLoc());
  1756. return SpirvEvalInfo(valueId).setRValue();
  1757. }
  1758. case CastKind::CK_FloatingCast:
  1759. case CastKind::CK_IntegralToFloating:
  1760. case CastKind::CK_HLSLCC_FloatingCast:
  1761. case CastKind::CK_HLSLCC_IntegralToFloating: {
  1762. // First try to see if we can do constant folding for floating point
  1763. // numbers like what we are doing for integers in the above.
  1764. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1765. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1766. const auto valueId = castToFloat(doExpr(subExpr), subExprType, toType,
  1767. subExpr->getExprLoc());
  1768. return SpirvEvalInfo(valueId).setRValue();
  1769. }
  1770. case CastKind::CK_IntegralToBoolean:
  1771. case CastKind::CK_FloatingToBoolean:
  1772. case CastKind::CK_HLSLCC_IntegralToBoolean:
  1773. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  1774. // First try to see if we can do constant folding.
  1775. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1776. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1777. const auto valueId = castToBool(doExpr(subExpr), subExprType, toType);
  1778. return SpirvEvalInfo(valueId).setRValue();
  1779. }
  1780. case CastKind::CK_HLSLVectorSplat: {
  1781. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  1782. return createVectorSplat(subExpr, size);
  1783. }
  1784. case CastKind::CK_HLSLVectorTruncationCast: {
  1785. const uint32_t toVecTypeId = typeTranslator.translateType(toType);
  1786. const uint32_t elemTypeId =
  1787. typeTranslator.translateType(hlsl::GetHLSLVecElementType(toType));
  1788. const auto toSize = hlsl::GetHLSLVecSize(toType);
  1789. const uint32_t composite = doExpr(subExpr);
  1790. llvm::SmallVector<uint32_t, 4> elements;
  1791. for (uint32_t i = 0; i < toSize; ++i) {
  1792. elements.push_back(
  1793. theBuilder.createCompositeExtract(elemTypeId, composite, {i}));
  1794. }
  1795. auto valueId = elements.front();
  1796. if (toSize > 1)
  1797. valueId = theBuilder.createCompositeConstruct(toVecTypeId, elements);
  1798. return SpirvEvalInfo(valueId).setRValue();
  1799. }
  1800. case CastKind::CK_HLSLVectorToScalarCast: {
  1801. // The underlying should already be a vector of size 1.
  1802. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  1803. return doExpr(subExpr);
  1804. }
  1805. case CastKind::CK_HLSLVectorToMatrixCast: {
  1806. // If target type is already an 1xN matrix type, we just return the
  1807. // underlying vector.
  1808. if (TypeTranslator::is1xNMatrix(toType))
  1809. return doExpr(subExpr);
  1810. // A vector can have no more than 4 elements. The only remaining case
  1811. // is casting from size-4 vector to size-2-by-2 matrix.
  1812. const auto vec = loadIfGLValue(subExpr);
  1813. QualType elemType = {};
  1814. uint32_t rowCount = 0, colCount = 0;
  1815. const bool isMat =
  1816. TypeTranslator::isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  1817. assert(isMat && rowCount == 2 && colCount == 2);
  1818. uint32_t vec2Type =
  1819. theBuilder.getVecType(typeTranslator.translateType(elemType), 2);
  1820. const auto subVec1 =
  1821. theBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1});
  1822. const auto subVec2 =
  1823. theBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3});
  1824. const auto mat = theBuilder.createCompositeConstruct(
  1825. theBuilder.getMatType(elemType, vec2Type, 2), {subVec1, subVec2});
  1826. return SpirvEvalInfo(mat).setRValue();
  1827. }
  1828. case CastKind::CK_HLSLMatrixSplat: {
  1829. // From scalar to matrix
  1830. uint32_t rowCount = 0, colCount = 0;
  1831. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  1832. // Handle degenerated cases first
  1833. if (rowCount == 1 && colCount == 1)
  1834. return doExpr(subExpr);
  1835. if (colCount == 1)
  1836. return createVectorSplat(subExpr, rowCount);
  1837. const auto vecSplat = createVectorSplat(subExpr, colCount);
  1838. if (rowCount == 1)
  1839. return vecSplat;
  1840. const uint32_t matType = typeTranslator.translateType(toType);
  1841. llvm::SmallVector<uint32_t, 4> vectors(size_t(rowCount), vecSplat);
  1842. if (vecSplat.isConstant()) {
  1843. const auto valueId = theBuilder.getConstantComposite(matType, vectors);
  1844. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1845. } else {
  1846. const auto valueId =
  1847. theBuilder.createCompositeConstruct(matType, vectors);
  1848. return SpirvEvalInfo(valueId).setRValue();
  1849. }
  1850. }
  1851. case CastKind::CK_HLSLMatrixTruncationCast: {
  1852. const QualType srcType = subExprType;
  1853. const uint32_t srcId = doExpr(subExpr);
  1854. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  1855. const uint32_t dstTypeId = typeTranslator.translateType(toType);
  1856. llvm::SmallVector<uint32_t, 4> indexes;
  1857. // It is possible that the source matrix is in fact a vector.
  1858. // For example: Truncate float1x3 --> float1x2.
  1859. // The front-end disallows float1x3 --> float2x1.
  1860. {
  1861. uint32_t srcVecSize = 0, dstVecSize = 0;
  1862. if (TypeTranslator::isVectorType(srcType, nullptr, &srcVecSize) &&
  1863. TypeTranslator::isVectorType(toType, nullptr, &dstVecSize)) {
  1864. for (uint32_t i = 0; i < dstVecSize; ++i)
  1865. indexes.push_back(i);
  1866. const auto valId =
  1867. theBuilder.createVectorShuffle(dstTypeId, srcId, srcId, indexes);
  1868. return SpirvEvalInfo(valId).setRValue();
  1869. }
  1870. }
  1871. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  1872. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  1873. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  1874. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  1875. const uint32_t srcRowType = theBuilder.getVecType(elemTypeId, srcCols);
  1876. // Indexes to pass to OpVectorShuffle
  1877. for (uint32_t i = 0; i < dstCols; ++i)
  1878. indexes.push_back(i);
  1879. llvm::SmallVector<uint32_t, 4> extractedVecs;
  1880. for (uint32_t row = 0; row < dstRows; ++row) {
  1881. // Extract a row
  1882. uint32_t rowId =
  1883. theBuilder.createCompositeExtract(srcRowType, srcId, {row});
  1884. // Extract the necessary columns from that row.
  1885. // The front-end ensures dstCols <= srcCols.
  1886. // If dstCols equals srcCols, we can use the whole row directly.
  1887. if (dstCols == 1) {
  1888. rowId = theBuilder.createCompositeExtract(elemTypeId, rowId, {0});
  1889. } else if (dstCols < srcCols) {
  1890. rowId = theBuilder.createVectorShuffle(
  1891. theBuilder.getVecType(elemTypeId, dstCols), rowId, rowId, indexes);
  1892. }
  1893. extractedVecs.push_back(rowId);
  1894. }
  1895. uint32_t valId = extractedVecs.front();
  1896. if (extractedVecs.size() > 1) {
  1897. valId = theBuilder.createCompositeConstruct(
  1898. typeTranslator.translateType(toType), extractedVecs);
  1899. }
  1900. return SpirvEvalInfo(valId).setRValue();
  1901. }
  1902. case CastKind::CK_HLSLMatrixToScalarCast: {
  1903. // The underlying should already be a matrix of 1x1.
  1904. assert(TypeTranslator::is1x1Matrix(subExprType));
  1905. return doExpr(subExpr);
  1906. }
  1907. case CastKind::CK_HLSLMatrixToVectorCast: {
  1908. // The underlying should already be a matrix of 1xN.
  1909. assert(TypeTranslator::is1xNMatrix(subExprType) ||
  1910. TypeTranslator::isMx1Matrix(subExprType));
  1911. return doExpr(subExpr);
  1912. }
  1913. case CastKind::CK_FunctionToPointerDecay:
  1914. // Just need to return the function id
  1915. return doExpr(subExpr);
  1916. case CastKind::CK_FlatConversion: {
  1917. uint32_t subExprId = 0;
  1918. QualType evalType = subExprType;
  1919. // Optimization: we can use OpConstantNull for cases where we want to
  1920. // initialize an entire data structure to zeros.
  1921. if (evaluatesToConstZero(subExpr, astContext)) {
  1922. subExprId =
  1923. theBuilder.getConstantNull(typeTranslator.translateType(toType));
  1924. return SpirvEvalInfo(subExprId).setRValue().setConstant();
  1925. }
  1926. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  1927. // Try to evaluate float literals as float rather than double.
  1928. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  1929. subExprId = tryToEvaluateAsFloat32(floatLiteral->getValue());
  1930. if (subExprId)
  1931. evalType = astContext.FloatTy;
  1932. }
  1933. // Evaluate 'literal float' initializer type as float rather than double.
  1934. // TODO: This could result in rounding error if the initializer is a
  1935. // non-literal expression that requires larger than 32 bits and has the
  1936. // 'literal float' type.
  1937. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  1938. evalType = astContext.FloatTy;
  1939. hint.setHint(astContext.FloatTy);
  1940. }
  1941. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  1942. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  1943. const bool isSigned = subExprType->isSignedIntegerType();
  1944. subExprId = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  1945. if (subExprId)
  1946. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  1947. }
  1948. // For assigning one array instance to another one with the same array type
  1949. // (regardless of constness and literalness), the rhs will be wrapped in a
  1950. // FlatConversion:
  1951. // |- <lhs>
  1952. // `- ImplicitCastExpr <FlatConversion>
  1953. // `- ImplicitCastExpr <LValueToRValue>
  1954. // `- <rhs>
  1955. // This FlatConversion does not affect CodeGen, so that we can ignore it.
  1956. else if (subExprType->isArrayType() &&
  1957. typeTranslator.isSameType(expr->getType(), subExprType)) {
  1958. return doExpr(subExpr);
  1959. }
  1960. if (!subExprId)
  1961. subExprId = doExpr(subExpr);
  1962. const auto valId =
  1963. processFlatConversion(toType, evalType, subExprId, expr->getExprLoc());
  1964. return SpirvEvalInfo(valId).setRValue();
  1965. }
  1966. case CastKind::CK_UncheckedDerivedToBase:
  1967. case CastKind::CK_HLSLDerivedToBase: {
  1968. // Find the index sequence of the base to which we are casting
  1969. llvm::SmallVector<uint32_t, 4> baseIndices;
  1970. getBaseClassIndices(expr, &baseIndices);
  1971. // Turn them in to SPIR-V constants
  1972. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  1973. baseIndices[i] = theBuilder.getConstantUint32(baseIndices[i]);
  1974. auto derivedInfo = doExpr(subExpr);
  1975. return turnIntoElementPtr(derivedInfo, expr->getType(), baseIndices);
  1976. }
  1977. default:
  1978. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  1979. << expr->getCastKindName() << expr->getSourceRange();
  1980. expr->dump();
  1981. return 0;
  1982. }
  1983. }
  1984. uint32_t SPIRVEmitter::processFlatConversion(const QualType type,
  1985. const QualType initType,
  1986. const uint32_t initId,
  1987. SourceLocation srcLoc) {
  1988. // Try to translate the canonical type first
  1989. const auto canonicalType = type.getCanonicalType();
  1990. if (canonicalType != type)
  1991. return processFlatConversion(canonicalType, initType, initId, srcLoc);
  1992. // Primitive types
  1993. {
  1994. QualType ty = {};
  1995. if (TypeTranslator::isScalarType(type, &ty)) {
  1996. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  1997. switch (builtinType->getKind()) {
  1998. case BuiltinType::Void: {
  1999. emitError("cannot create a constant of void type", srcLoc);
  2000. return 0;
  2001. }
  2002. case BuiltinType::Bool:
  2003. return castToBool(initId, initType, ty);
  2004. // Target type is an integer variant.
  2005. case BuiltinType::Int:
  2006. case BuiltinType::Short:
  2007. case BuiltinType::Min12Int:
  2008. case BuiltinType::UShort:
  2009. case BuiltinType::UInt:
  2010. case BuiltinType::Long:
  2011. case BuiltinType::LongLong:
  2012. case BuiltinType::ULong:
  2013. case BuiltinType::ULongLong:
  2014. return castToInt(initId, initType, ty, srcLoc);
  2015. // Target type is a float variant.
  2016. case BuiltinType::Double:
  2017. case BuiltinType::Float:
  2018. case BuiltinType::Half:
  2019. case BuiltinType::Min10Float:
  2020. return castToFloat(initId, initType, ty, srcLoc);
  2021. default:
  2022. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2023. << builtinType->getTypeClassName();
  2024. return 0;
  2025. }
  2026. }
  2027. }
  2028. }
  2029. // Vector types
  2030. {
  2031. QualType elemType = {};
  2032. uint32_t elemCount = {};
  2033. if (TypeTranslator::isVectorType(type, &elemType, &elemCount)) {
  2034. const uint32_t elemId =
  2035. processFlatConversion(elemType, initType, initId, srcLoc);
  2036. llvm::SmallVector<uint32_t, 4> constituents(size_t(elemCount), elemId);
  2037. return theBuilder.createCompositeConstruct(
  2038. typeTranslator.translateType(type), constituents);
  2039. }
  2040. }
  2041. // Matrix types
  2042. {
  2043. QualType elemType = {};
  2044. uint32_t rowCount = 0, colCount = 0;
  2045. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2046. // By default HLSL matrices are row major, while SPIR-V matrices are
  2047. // column major. We are mapping what HLSL semantically mean a row into a
  2048. // column here.
  2049. const uint32_t vecType = theBuilder.getVecType(
  2050. typeTranslator.translateType(elemType), colCount);
  2051. const uint32_t elemId =
  2052. processFlatConversion(elemType, initType, initId, srcLoc);
  2053. const llvm::SmallVector<uint32_t, 4> constituents(size_t(colCount),
  2054. elemId);
  2055. const uint32_t colId =
  2056. theBuilder.createCompositeConstruct(vecType, constituents);
  2057. const llvm::SmallVector<uint32_t, 4> rows(size_t(rowCount), colId);
  2058. return theBuilder.createCompositeConstruct(
  2059. typeTranslator.translateType(type), rows);
  2060. }
  2061. }
  2062. // Struct type
  2063. if (const auto *structType = type->getAs<RecordType>()) {
  2064. const auto *decl = structType->getDecl();
  2065. llvm::SmallVector<uint32_t, 4> fields;
  2066. for (const auto *field : decl->fields()) {
  2067. // There is a special case for FlatConversion. If T is a struct with only
  2068. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2069. // constructs a new T instance using the instance of S as its only member.
  2070. // Check whether we are handling that case here first.
  2071. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2072. fields.push_back(initId);
  2073. } else {
  2074. fields.push_back(
  2075. processFlatConversion(field->getType(), initType, initId, srcLoc));
  2076. }
  2077. }
  2078. return theBuilder.createCompositeConstruct(
  2079. typeTranslator.translateType(type), fields);
  2080. }
  2081. // Array type
  2082. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2083. const auto size =
  2084. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2085. const uint32_t elemId = processFlatConversion(arrayType->getElementType(),
  2086. initType, initId, srcLoc);
  2087. llvm::SmallVector<uint32_t, 4> constituents(size_t(size), elemId);
  2088. return theBuilder.createCompositeConstruct(
  2089. typeTranslator.translateType(type), constituents);
  2090. }
  2091. emitError("flat conversion of type %0 unimplemented", {})
  2092. << type->getTypeClassName();
  2093. type->dump();
  2094. return 0;
  2095. }
  2096. SpirvEvalInfo
  2097. SPIRVEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2098. const auto opcode = expr->getOpcode();
  2099. // Try to optimize floatMxN *= float and floatN *= float case
  2100. if (opcode == BO_MulAssign) {
  2101. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  2102. return result;
  2103. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  2104. return result;
  2105. }
  2106. const auto *rhs = expr->getRHS();
  2107. const auto *lhs = expr->getLHS();
  2108. SpirvEvalInfo lhsPtr = 0;
  2109. const auto result =
  2110. processBinaryOp(lhs, rhs, opcode, expr->getComputationLHSType(),
  2111. expr->getType(), expr->getSourceRange(), &lhsPtr);
  2112. return processAssignment(lhs, result, true, lhsPtr);
  2113. }
  2114. SpirvEvalInfo
  2115. SPIRVEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2116. const auto type = expr->getType();
  2117. // Enhancement for special case when the ConditionalOperator return type is a
  2118. // literal type. For example:
  2119. //
  2120. // float a = cond ? 1 : 2;
  2121. // int b = cond ? 1.5 : 2.5;
  2122. //
  2123. // There will be no indications about whether '1' and '2' should be used as
  2124. // 32-bit or 64-bit integers. Similarly, there will be no indication about
  2125. // whether '1.5' and '2.5' should be used as 32-bit or 64-bit floats.
  2126. //
  2127. // We want to avoid using 64-bit int and 64-bit float as much as possible.
  2128. //
  2129. // Note that if the literal is in fact large enough that it can't be
  2130. // represented in 32 bits (e.g. integer larger than 3e+9), we should *not*
  2131. // provide a hint.
  2132. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2133. const bool isLitInt = type->isSpecificBuiltinType(BuiltinType::LitInt);
  2134. const bool isLitFloat = type->isSpecificBuiltinType(BuiltinType::LitFloat);
  2135. // Return type of ConditionalOperator is a 'literal int' or 'literal float'
  2136. if (isLitInt || isLitFloat) {
  2137. // There is no hint about the intended usage of the literal type.
  2138. if (typeTranslator.getIntendedLiteralType(type) == type) {
  2139. // If either branch is a literal that is larger than 32-bits, do not
  2140. // provide a hint.
  2141. if (!isLiteralLargerThan32Bits(expr->getTrueExpr()) &&
  2142. !isLiteralLargerThan32Bits(expr->getFalseExpr())) {
  2143. if (isLitInt)
  2144. hint.setHint(astContext.IntTy);
  2145. else if (isLitFloat)
  2146. hint.setHint(astContext.FloatTy);
  2147. }
  2148. }
  2149. }
  2150. // According to HLSL doc, all sides of the ?: expression are always
  2151. // evaluated.
  2152. const uint32_t typeId = typeTranslator.translateType(type);
  2153. // If we are selecting between two SampleState objects, none of the three
  2154. // operands has a LValueToRValue implicit cast.
  2155. uint32_t condition = loadIfGLValue(expr->getCond());
  2156. const auto trueBranch = loadIfGLValue(expr->getTrueExpr());
  2157. const auto falseBranch = loadIfGLValue(expr->getFalseExpr());
  2158. // For cases where the return type is a scalar or a vector, we can use
  2159. // OpSelect to choose between the two. OpSelect's return type must be either
  2160. // scalar or vector.
  2161. if (TypeTranslator::isScalarType(type) ||
  2162. TypeTranslator::isVectorType(type)) {
  2163. // The SPIR-V OpSelect instruction must have a selection argument that is
  2164. // the same size as the return type. If the return type is a vector, the
  2165. // selection must be a vector of booleans (one per output component).
  2166. uint32_t count = 0;
  2167. if (TypeTranslator::isVectorType(expr->getType(), nullptr, &count) &&
  2168. !TypeTranslator::isVectorType(expr->getCond()->getType())) {
  2169. const uint32_t condVecType =
  2170. theBuilder.getVecType(theBuilder.getBoolType(), count);
  2171. const llvm::SmallVector<uint32_t, 4> components(size_t(count), condition);
  2172. condition = theBuilder.createCompositeConstruct(condVecType, components);
  2173. }
  2174. auto valueId =
  2175. theBuilder.createSelect(typeId, condition, trueBranch, falseBranch);
  2176. return SpirvEvalInfo(valueId).setRValue();
  2177. }
  2178. // If we can't use OpSelect, we need to create if-else control flow.
  2179. const uint32_t tempVar = theBuilder.addFnVar(typeId, "temp.var.ternary");
  2180. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  2181. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  2182. const uint32_t elseBB = theBuilder.createBasicBlock("if.false");
  2183. // Create the branch instruction. This will end the current basic block.
  2184. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  2185. theBuilder.addSuccessor(thenBB);
  2186. theBuilder.addSuccessor(elseBB);
  2187. theBuilder.setMergeTarget(mergeBB);
  2188. // Handle the then branch
  2189. theBuilder.setInsertPoint(thenBB);
  2190. theBuilder.createStore(tempVar, trueBranch);
  2191. theBuilder.createBranch(mergeBB);
  2192. theBuilder.addSuccessor(mergeBB);
  2193. // Handle the else branch
  2194. theBuilder.setInsertPoint(elseBB);
  2195. theBuilder.createStore(tempVar, falseBranch);
  2196. theBuilder.createBranch(mergeBB);
  2197. theBuilder.addSuccessor(mergeBB);
  2198. // From now on, emit instructions into the merge block.
  2199. theBuilder.setInsertPoint(mergeBB);
  2200. return SpirvEvalInfo(theBuilder.createLoad(typeId, tempVar)).setRValue();
  2201. }
  2202. uint32_t SPIRVEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2203. const CXXMemberCallExpr *expr) {
  2204. const auto *object = expr->getImplicitObjectArgument();
  2205. const auto objectId = loadIfAliasVarRef(object);
  2206. const auto type = object->getType();
  2207. const bool isByteAddressBuffer = TypeTranslator::isByteAddressBuffer(type) ||
  2208. TypeTranslator::isRWByteAddressBuffer(type);
  2209. const bool isStructuredBuffer =
  2210. TypeTranslator::isStructuredBuffer(type) ||
  2211. TypeTranslator::isAppendStructuredBuffer(type) ||
  2212. TypeTranslator::isConsumeStructuredBuffer(type);
  2213. assert(isByteAddressBuffer || isStructuredBuffer);
  2214. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2215. // with only one member that is a runtime array. We need to perform
  2216. // OpArrayLength on member 0.
  2217. const auto uintType = theBuilder.getUint32Type();
  2218. uint32_t length =
  2219. theBuilder.createBinaryOp(spv::Op::OpArrayLength, uintType, objectId, 0);
  2220. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2221. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2222. // array. Therefore we must multiply the results by 4.
  2223. if (isByteAddressBuffer) {
  2224. length = theBuilder.createBinaryOp(spv::Op::OpIMul, uintType, length,
  2225. theBuilder.getConstantUint32(4u));
  2226. }
  2227. theBuilder.createStore(doExpr(expr->getArg(0)), length);
  2228. if (isStructuredBuffer) {
  2229. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2230. // size of the struct) must also be written to the second argument.
  2231. uint32_t size = 0, stride = 0;
  2232. std::tie(std::ignore, size) = typeTranslator.getAlignmentAndSize(
  2233. type, LayoutRule::GLSLStd430, /*isRowMajor*/ false, &stride);
  2234. const auto sizeId = theBuilder.getConstantUint32(size);
  2235. theBuilder.createStore(doExpr(expr->getArg(1)), sizeId);
  2236. }
  2237. return 0;
  2238. }
  2239. uint32_t SPIRVEmitter::processRWByteAddressBufferAtomicMethods(
  2240. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2241. // The signature of RWByteAddressBuffer atomic methods are largely:
  2242. // void Interlocked*(in UINT dest, in UINT value);
  2243. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2244. const auto *object = expr->getImplicitObjectArgument();
  2245. const auto objectInfo = loadIfAliasVarRef(object);
  2246. const auto uintType = theBuilder.getUint32Type();
  2247. const uint32_t zero = theBuilder.getConstantUint32(0);
  2248. const uint32_t offset = doExpr(expr->getArg(0));
  2249. // Right shift by 2 to convert the byte offset to uint32_t offset
  2250. const uint32_t address =
  2251. theBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, uintType, offset,
  2252. theBuilder.getConstantUint32(2));
  2253. const auto ptrType =
  2254. theBuilder.getPointerType(uintType, objectInfo.getStorageClass());
  2255. const uint32_t ptr =
  2256. theBuilder.createAccessChain(ptrType, objectInfo, {zero, address});
  2257. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  2258. const bool isCompareExchange =
  2259. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2260. const bool isCompareStore =
  2261. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2262. if (isCompareExchange || isCompareStore) {
  2263. const uint32_t comparator = doExpr(expr->getArg(1));
  2264. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  2265. uintType, ptr, scope, zero, zero, doExpr(expr->getArg(2)), comparator);
  2266. if (isCompareExchange)
  2267. theBuilder.createStore(doExpr(expr->getArg(3)), originalVal);
  2268. } else {
  2269. const uint32_t value = doExpr(expr->getArg(1));
  2270. const uint32_t originalVal = theBuilder.createAtomicOp(
  2271. translateAtomicHlslOpcodeToSpirvOpcode(opcode), uintType, ptr, scope,
  2272. zero, value);
  2273. if (expr->getNumArgs() > 2)
  2274. theBuilder.createStore(doExpr(expr->getArg(2)), originalVal);
  2275. }
  2276. return 0;
  2277. }
  2278. uint32_t SPIRVEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2279. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2280. const auto sampleCount = theBuilder.createUnaryOp(
  2281. spv::Op::OpImageQuerySamples, theBuilder.getUint32Type(),
  2282. loadIfGLValue(object));
  2283. emitWarning(
  2284. "GetSamplePosition only supports standard sample settings with 1, 2, 4, "
  2285. "8, or 16 samples and will return float2(0, 0) for other cases",
  2286. expr->getCallee()->getExprLoc());
  2287. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)));
  2288. }
  2289. SpirvEvalInfo SPIRVEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2290. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2291. const uint32_t sample = expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : 0;
  2292. const uint32_t zero = theBuilder.getConstantInt32(0);
  2293. const uint32_t location = theBuilder.getConstantComposite(
  2294. theBuilder.getVecType(theBuilder.getInt32Type(), 2), {zero, zero});
  2295. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2296. /*varOffset*/ 0, /*lod*/ sample,
  2297. /*residencyCode*/ 0);
  2298. }
  2299. uint32_t
  2300. SPIRVEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2301. const auto *object = expr->getImplicitObjectArgument();
  2302. const auto objectId = loadIfGLValue(object);
  2303. const auto type = object->getType();
  2304. const auto *recType = type->getAs<RecordType>();
  2305. assert(recType);
  2306. const auto typeName = recType->getDecl()->getName();
  2307. const auto numArgs = expr->getNumArgs();
  2308. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2309. assert(TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2310. TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type));
  2311. // For Texture1D, arguments are either:
  2312. // a) width
  2313. // b) MipLevel, width, NumLevels
  2314. // For Texture1DArray, arguments are either:
  2315. // a) width, elements
  2316. // b) MipLevel, width, elements, NumLevels
  2317. // For Texture2D, arguments are either:
  2318. // a) width, height
  2319. // b) MipLevel, width, height, NumLevels
  2320. // For Texture2DArray, arguments are either:
  2321. // a) width, height, elements
  2322. // b) MipLevel, width, height, elements, NumLevels
  2323. // For Texture3D, arguments are either:
  2324. // a) width, height, depth
  2325. // b) MipLevel, width, height, depth, NumLevels
  2326. // For Texture2DMS, arguments are: width, height, NumSamples
  2327. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2328. // For TextureCube, arguments are either:
  2329. // a) width, height
  2330. // b) MipLevel, width, height, NumLevels
  2331. // For TextureCubeArray, arguments are either:
  2332. // a) width, height, elements
  2333. // b) MipLevel, width, height, elements, NumLevels
  2334. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2335. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2336. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2337. // The HLSL methods, however, have overloaded functions which have float
  2338. // output arguments. Since the AST naturally won't have casting AST nodes for
  2339. // such cases, we'll have to perform the cast ourselves.
  2340. const auto storeToOutputArg = [this](const Expr *outputArg,
  2341. uint32_t toStoreId) {
  2342. const auto outputArgType = outputArg->getType();
  2343. // Perform cast to float if necessary.
  2344. if (isFloatOrVecMatOfFloatType(outputArgType)) {
  2345. toStoreId = theBuilder.createUnaryOp(
  2346. spv::Op::OpConvertUToF, typeTranslator.translateType(outputArgType),
  2347. toStoreId);
  2348. }
  2349. theBuilder.createStore(doExpr(outputArg), toStoreId);
  2350. };
  2351. if ((typeName == "Texture1D" && numArgs > 1) ||
  2352. (typeName == "Texture2D" && numArgs > 2) ||
  2353. (typeName == "TextureCube" && numArgs > 2) ||
  2354. (typeName == "Texture3D" && numArgs > 3) ||
  2355. (typeName == "Texture1DArray" && numArgs > 2) ||
  2356. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2357. (typeName == "Texture2DArray" && numArgs > 3)) {
  2358. mipLevel = expr->getArg(0);
  2359. numLevels = expr->getArg(numArgs - 1);
  2360. }
  2361. if (TypeTranslator::isTextureMS(type)) {
  2362. numSamples = expr->getArg(numArgs - 1);
  2363. }
  2364. uint32_t querySize = numArgs;
  2365. // If numLevels arg is present, mipLevel must also be present. These are not
  2366. // queried via ImageQuerySizeLod.
  2367. if (numLevels)
  2368. querySize -= 2;
  2369. // If numLevels arg is present, mipLevel must also be present.
  2370. else if (numSamples)
  2371. querySize -= 1;
  2372. const uint32_t uintId = theBuilder.getUint32Type();
  2373. const uint32_t resultTypeId =
  2374. querySize == 1 ? uintId : theBuilder.getVecType(uintId, querySize);
  2375. // Only Texture types use ImageQuerySizeLod.
  2376. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2377. uint32_t lod = 0;
  2378. if (TypeTranslator::isTexture(type) && !numSamples) {
  2379. if (mipLevel) {
  2380. // For Texture types when mipLevel argument is present.
  2381. lod = doExpr(mipLevel);
  2382. } else {
  2383. // For Texture types when mipLevel argument is omitted.
  2384. lod = theBuilder.getConstantInt32(0);
  2385. }
  2386. }
  2387. const uint32_t query =
  2388. lod ? theBuilder.createBinaryOp(spv::Op::OpImageQuerySizeLod,
  2389. resultTypeId, objectId, lod)
  2390. : theBuilder.createUnaryOp(spv::Op::OpImageQuerySize, resultTypeId,
  2391. objectId);
  2392. if (querySize == 1) {
  2393. const uint32_t argIndex = mipLevel ? 1 : 0;
  2394. storeToOutputArg(expr->getArg(argIndex), query);
  2395. } else {
  2396. for (uint32_t i = 0; i < querySize; ++i) {
  2397. const uint32_t component =
  2398. theBuilder.createCompositeExtract(uintId, query, {i});
  2399. // If the first arg is the mipmap level, we must write the results
  2400. // starting from Arg(i+1), not Arg(i).
  2401. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2402. storeToOutputArg(expr->getArg(argIndex), component);
  2403. }
  2404. }
  2405. if (numLevels || numSamples) {
  2406. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2407. const spv::Op opcode =
  2408. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2409. const uint32_t numLevelsSamplesQuery =
  2410. theBuilder.createUnaryOp(opcode, uintId, objectId);
  2411. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery);
  2412. }
  2413. return 0;
  2414. }
  2415. uint32_t
  2416. SPIRVEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr) {
  2417. // Possible signatures are as follows:
  2418. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2419. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2420. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2421. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2422. // Return type is always a single float (LOD).
  2423. assert(expr->getNumArgs() == 2u);
  2424. const auto *object = expr->getImplicitObjectArgument();
  2425. const uint32_t objectId = loadIfGLValue(object);
  2426. const uint32_t samplerState = doExpr(expr->getArg(0));
  2427. const uint32_t coordinate = doExpr(expr->getArg(1));
  2428. const uint32_t sampledImageType = theBuilder.getSampledImageType(
  2429. typeTranslator.translateType(object->getType()));
  2430. const uint32_t sampledImage = theBuilder.createBinaryOp(
  2431. spv::Op::OpSampledImage, sampledImageType, objectId, samplerState);
  2432. // The result type of OpImageQueryLod must be a float2.
  2433. const uint32_t queryResultType =
  2434. theBuilder.getVecType(theBuilder.getFloat32Type(), 2u);
  2435. const uint32_t query = theBuilder.createBinaryOp(
  2436. spv::Op::OpImageQueryLod, queryResultType, sampledImage, coordinate);
  2437. // The first component of the float2 contains the mipmap array layer.
  2438. return theBuilder.createCompositeExtract(theBuilder.getFloat32Type(), query,
  2439. {0});
  2440. }
  2441. uint32_t SPIRVEmitter::processTextureGatherRGBACmpRGBA(
  2442. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2443. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2444. // two sets:
  2445. // * SamplerState s, float2 location, int2 offset
  2446. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2447. // int offset2, int2 offset3
  2448. //
  2449. // An additional 'out uint status' parameter can appear in both of the above.
  2450. //
  2451. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2452. // two sets:
  2453. // * SamplerState s, float2 location, float compare_value, int2 offset
  2454. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2455. // int2 offset2, int2 offset3, int2 offset4
  2456. //
  2457. // An additional 'out uint status' parameter can appear in both of the above.
  2458. //
  2459. // TextureCube's signature is somewhat different from the rest.
  2460. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2461. // * SamplerState s, float2 location, out uint status
  2462. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2463. // * SamplerState s, float2 location, float compare_value, out uint status
  2464. //
  2465. // Return type is always a 4-component vector.
  2466. const FunctionDecl *callee = expr->getDirectCallee();
  2467. const auto numArgs = expr->getNumArgs();
  2468. const auto *imageExpr = expr->getImplicitObjectArgument();
  2469. const QualType imageType = imageExpr->getType();
  2470. const auto imageTypeId = typeTranslator.translateType(imageType);
  2471. const auto retTypeId = typeTranslator.translateType(callee->getReturnType());
  2472. // If the last arg is an unsigned integer, it must be the status.
  2473. const bool hasStatusArg =
  2474. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2475. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2476. // it exists), and subtract 2 for SamplerState and location.
  2477. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2478. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2479. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2480. const uint32_t image = loadIfGLValue(imageExpr);
  2481. const uint32_t sampler = doExpr(expr->getArg(0));
  2482. const uint32_t coordinate = doExpr(expr->getArg(1));
  2483. const uint32_t compareVal = isCmp ? doExpr(expr->getArg(2)) : 0;
  2484. // Handle offsets (if any).
  2485. uint32_t constOffset = 0, varOffset = 0, constOffsets = 0;
  2486. if (numOffsetArgs == 1) {
  2487. // The offset arg is not optional.
  2488. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2489. } else if (numOffsetArgs == 4) {
  2490. const auto offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2491. const auto offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2492. const auto offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2493. const auto offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2494. // Make sure we can generate the ConstOffsets image operands in SPIR-V.
  2495. if (!offset0 || !offset1 || !offset2 || !offset3) {
  2496. emitError("all offset parameters to '%0' method call must be constants",
  2497. expr->getExprLoc())
  2498. << callee->getName() << expr->getSourceRange();
  2499. return 0;
  2500. }
  2501. const uint32_t v2i32 = theBuilder.getVecType(theBuilder.getInt32Type(), 2);
  2502. const uint32_t offsetType =
  2503. theBuilder.getArrayType(v2i32, theBuilder.getConstantUint32(4));
  2504. constOffsets = theBuilder.getConstantComposite(
  2505. offsetType, {offset0, offset1, offset2, offset3});
  2506. }
  2507. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2508. return theBuilder.createImageGather(
  2509. retTypeId, imageTypeId, image, sampler, coordinate,
  2510. theBuilder.getConstantInt32(component), compareVal, constOffset,
  2511. varOffset, constOffsets, /*sampleNumber*/ 0, status);
  2512. }
  2513. uint32_t SPIRVEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2514. // Signature for Texture2D/Texture2DArray:
  2515. //
  2516. // float4 GatherCmp(
  2517. // in SamplerComparisonState s,
  2518. // in float2 location,
  2519. // in float compare_value
  2520. // [,in int2 offset]
  2521. // [,out uint Status]
  2522. // );
  2523. //
  2524. // Signature for TextureCube/TextureCubeArray:
  2525. //
  2526. // float4 GatherCmp(
  2527. // in SamplerComparisonState s,
  2528. // in float2 location,
  2529. // in float compare_value,
  2530. // out uint Status
  2531. // );
  2532. //
  2533. // Other Texture types do not have the GatherCmp method.
  2534. const FunctionDecl *callee = expr->getDirectCallee();
  2535. const auto numArgs = expr->getNumArgs();
  2536. const bool hasStatusArg =
  2537. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2538. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2539. const auto *imageExpr = expr->getImplicitObjectArgument();
  2540. const uint32_t image = loadIfGLValue(imageExpr);
  2541. const uint32_t sampler = doExpr(expr->getArg(0));
  2542. const uint32_t coordinate = doExpr(expr->getArg(1));
  2543. const uint32_t comparator = doExpr(expr->getArg(2));
  2544. uint32_t constOffset = 0, varOffset = 0;
  2545. if (hasOffsetArg)
  2546. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2547. const auto retType = typeTranslator.translateType(callee->getReturnType());
  2548. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  2549. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2550. return theBuilder.createImageGather(
  2551. retType, imageType, image, sampler, coordinate, /*component*/ 0,
  2552. comparator, constOffset, varOffset, /*constOffsets*/ 0,
  2553. /*sampleNumber*/ 0, status);
  2554. }
  2555. SpirvEvalInfo SPIRVEmitter::processBufferTextureLoad(
  2556. const Expr *object, const uint32_t locationId, uint32_t constOffset,
  2557. uint32_t varOffset, uint32_t lod, uint32_t residencyCode) {
  2558. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2559. // The result type of an OpImageFetch must be a vec4 of float or int.
  2560. const auto type = object->getType();
  2561. assert(TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type) ||
  2562. TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2563. TypeTranslator::isSubpassInput(type) ||
  2564. TypeTranslator::isSubpassInputMS(type));
  2565. const bool doFetch =
  2566. TypeTranslator::isBuffer(type) || TypeTranslator::isTexture(type);
  2567. const uint32_t objectId = loadIfGLValue(object);
  2568. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2569. uint32_t sampleNumber = 0;
  2570. if (TypeTranslator::isTextureMS(type) ||
  2571. TypeTranslator::isSubpassInputMS(type)) {
  2572. sampleNumber = lod;
  2573. lod = 0;
  2574. }
  2575. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2576. QualType elemType = sampledType;
  2577. uint32_t elemCount = 1;
  2578. uint32_t elemTypeId = 0;
  2579. (void)TypeTranslator::isVectorType(sampledType, &elemType, &elemCount);
  2580. if (elemType->isFloatingType()) {
  2581. elemTypeId = theBuilder.getFloat32Type();
  2582. } else if (elemType->isSignedIntegerType()) {
  2583. elemTypeId = theBuilder.getInt32Type();
  2584. } else if (elemType->isUnsignedIntegerType()) {
  2585. elemTypeId = theBuilder.getUint32Type();
  2586. } else {
  2587. emitError("buffer/texture type unimplemented", object->getExprLoc());
  2588. return 0;
  2589. }
  2590. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2591. const uint32_t texelTypeId = theBuilder.getVecType(elemTypeId, 4u);
  2592. const uint32_t texel = theBuilder.createImageFetchOrRead(
  2593. doFetch, texelTypeId, type, objectId, locationId, lod, constOffset,
  2594. varOffset, /*constOffsets*/ 0, sampleNumber, residencyCode);
  2595. // If the result type is a vec1, vec2, or vec3, some extra processing
  2596. // (extraction) is required.
  2597. uint32_t retVal = extractVecFromVec4(texel, elemCount, elemTypeId);
  2598. return SpirvEvalInfo(retVal).setRValue();
  2599. }
  2600. SpirvEvalInfo SPIRVEmitter::processByteAddressBufferLoadStore(
  2601. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2602. uint32_t resultId = 0;
  2603. const auto object = expr->getImplicitObjectArgument();
  2604. const auto type = object->getType();
  2605. const auto objectInfo = loadIfAliasVarRef(object);
  2606. assert(numWords >= 1 && numWords <= 4);
  2607. if (doStore) {
  2608. assert(typeTranslator.isRWByteAddressBuffer(type));
  2609. assert(expr->getNumArgs() == 2);
  2610. } else {
  2611. assert(typeTranslator.isRWByteAddressBuffer(type) ||
  2612. typeTranslator.isByteAddressBuffer(type));
  2613. if (expr->getNumArgs() == 2) {
  2614. emitError(
  2615. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2616. expr->getExprLoc());
  2617. return 0;
  2618. }
  2619. }
  2620. const Expr *addressExpr = expr->getArg(0);
  2621. const uint32_t byteAddress = doExpr(addressExpr);
  2622. const uint32_t addressTypeId =
  2623. typeTranslator.translateType(addressExpr->getType());
  2624. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2625. // access). The AST always casts the address to unsinged integer, so shift
  2626. // by unsinged integer 2.
  2627. const uint32_t constUint2 = theBuilder.getConstantUint32(2);
  2628. const uint32_t address = theBuilder.createBinaryOp(
  2629. spv::Op::OpShiftRightLogical, addressTypeId, byteAddress, constUint2);
  2630. // Perform access chain into the RWByteAddressBuffer.
  2631. // First index must be zero (member 0 of the struct is a
  2632. // runtimeArray). The second index passed to OpAccessChain should be
  2633. // the address.
  2634. const uint32_t uintTypeId = theBuilder.getUint32Type();
  2635. const uint32_t ptrType =
  2636. theBuilder.getPointerType(uintTypeId, objectInfo.getStorageClass());
  2637. const uint32_t constUint0 = theBuilder.getConstantUint32(0);
  2638. if (doStore) {
  2639. const uint32_t valuesId = doExpr(expr->getArg(1));
  2640. uint32_t curStoreAddress = address;
  2641. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  2642. // Extract a 32-bit word from the input.
  2643. const uint32_t curValue = numWords == 1
  2644. ? valuesId
  2645. : theBuilder.createCompositeExtract(
  2646. uintTypeId, valuesId, {wordCounter});
  2647. // Update the output address if necessary.
  2648. if (wordCounter > 0) {
  2649. const uint32_t offset = theBuilder.getConstantUint32(wordCounter);
  2650. curStoreAddress = theBuilder.createBinaryOp(
  2651. spv::Op::OpIAdd, addressTypeId, address, offset);
  2652. }
  2653. // Store the word to the right address at the output.
  2654. const uint32_t storePtr = theBuilder.createAccessChain(
  2655. ptrType, objectInfo, {constUint0, curStoreAddress});
  2656. theBuilder.createStore(storePtr, curValue);
  2657. }
  2658. } else {
  2659. uint32_t loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2660. {constUint0, address});
  2661. resultId = theBuilder.createLoad(uintTypeId, loadPtr);
  2662. if (numWords > 1) {
  2663. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  2664. // return a vector result.
  2665. llvm::SmallVector<uint32_t, 4> values;
  2666. values.push_back(resultId);
  2667. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  2668. const uint32_t offset = theBuilder.getConstantUint32(wordCounter - 1);
  2669. const uint32_t newAddress = theBuilder.createBinaryOp(
  2670. spv::Op::OpIAdd, addressTypeId, address, offset);
  2671. loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2672. {constUint0, newAddress});
  2673. values.push_back(theBuilder.createLoad(uintTypeId, loadPtr));
  2674. }
  2675. const uint32_t resultType =
  2676. theBuilder.getVecType(addressTypeId, numWords);
  2677. resultId = theBuilder.createCompositeConstruct(resultType, values);
  2678. }
  2679. }
  2680. return SpirvEvalInfo(resultId).setRValue();
  2681. }
  2682. SpirvEvalInfo
  2683. SPIRVEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  2684. if (expr->getNumArgs() == 2) {
  2685. emitError(
  2686. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  2687. expr->getExprLoc());
  2688. return 0;
  2689. }
  2690. const auto *buffer = expr->getImplicitObjectArgument();
  2691. auto info = loadIfAliasVarRef(buffer);
  2692. const QualType structType =
  2693. hlsl::GetHLSLResourceResultType(buffer->getType());
  2694. const uint32_t zero = theBuilder.getConstantInt32(0);
  2695. const uint32_t index = doExpr(expr->getArg(0));
  2696. return turnIntoElementPtr(info, structType, {zero, index});
  2697. }
  2698. uint32_t SPIRVEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  2699. bool isInc, bool loadObject) {
  2700. const uint32_t i32Type = theBuilder.getInt32Type();
  2701. const uint32_t one = theBuilder.getConstantUint32(1); // As scope: Device
  2702. const uint32_t zero = theBuilder.getConstantUint32(0); // As memory sema: None
  2703. const uint32_t sOne = theBuilder.getConstantInt32(1);
  2704. const auto *object =
  2705. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2706. if (loadObject) {
  2707. // We don't need the object's <result-id> here since counter variable is a
  2708. // separate variable. But we still need the side effects of evaluating the
  2709. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  2710. // want to emit the code for foo(...).
  2711. (void)doExpr(object);
  2712. }
  2713. const auto *counterPair = getFinalACSBufferCounter(object);
  2714. if (!counterPair) {
  2715. emitFatalError("cannot find the associated counter variable",
  2716. object->getExprLoc());
  2717. return 0;
  2718. }
  2719. const uint32_t counterPtrType = theBuilder.getPointerType(
  2720. theBuilder.getInt32Type(), spv::StorageClass::Uniform);
  2721. const uint32_t counterPtr = theBuilder.createAccessChain(
  2722. counterPtrType, counterPair->get(theBuilder, typeTranslator), {zero});
  2723. uint32_t index = 0;
  2724. if (isInc) {
  2725. index = theBuilder.createAtomicOp(spv::Op::OpAtomicIAdd, i32Type,
  2726. counterPtr, one, zero, sOne);
  2727. } else {
  2728. // Note that OpAtomicISub returns the value before the subtraction;
  2729. // so we need to do substraction again with OpAtomicISub's return value.
  2730. const auto prev = theBuilder.createAtomicOp(spv::Op::OpAtomicISub, i32Type,
  2731. counterPtr, one, zero, sOne);
  2732. index = theBuilder.createBinaryOp(spv::Op::OpISub, i32Type, prev, sOne);
  2733. }
  2734. return index;
  2735. }
  2736. bool SPIRVEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  2737. const Expr *srcExpr) {
  2738. // We are handling associated counters here. Casts should not alter which
  2739. // associated counter to manipulate.
  2740. srcExpr = srcExpr->IgnoreParenCasts();
  2741. // For parameters of forward-declared functions. We must make sure the
  2742. // associated counter variable is created. But for forward-declared functions,
  2743. // the translation of the real definition may not be started yet.
  2744. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  2745. declIdMapper.createFnParamCounterVar(param);
  2746. // For implicit objects of methods. Similar to the above.
  2747. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  2748. declIdMapper.createFnParamCounterVar(thisObject);
  2749. // Handle AssocCounter#1 (see CounterVarFields comment)
  2750. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  2751. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2752. if (!srcPair) {
  2753. emitFatalError("cannot find the associated counter variable",
  2754. srcExpr->getExprLoc());
  2755. return false;
  2756. }
  2757. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2758. return true;
  2759. }
  2760. // Handle AssocCounter#3
  2761. llvm::SmallVector<uint32_t, 4> srcIndices;
  2762. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  2763. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2764. if (dstFields && srcFields) {
  2765. if (!dstFields->assign(*srcFields, theBuilder, typeTranslator)) {
  2766. emitFatalError("cannot handle associated counter variable assignment",
  2767. srcExpr->getExprLoc());
  2768. return false;
  2769. }
  2770. return true;
  2771. }
  2772. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  2773. // is a stand-alone decl in this method.
  2774. return false;
  2775. }
  2776. bool SPIRVEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  2777. const Expr *srcExpr) {
  2778. dstExpr = dstExpr->IgnoreParenCasts();
  2779. srcExpr = srcExpr->IgnoreParenCasts();
  2780. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  2781. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2782. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  2783. emitFatalError("cannot handle associated counter variable assignment",
  2784. srcExpr->getExprLoc());
  2785. return false;
  2786. }
  2787. // Handle AssocCounter#1 & AssocCounter#2
  2788. if (dstPair && srcPair) {
  2789. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2790. return true;
  2791. }
  2792. // Handle AssocCounter#3 & AssocCounter#4
  2793. llvm::SmallVector<uint32_t, 4> dstIndices;
  2794. llvm::SmallVector<uint32_t, 4> srcIndices;
  2795. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2796. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  2797. if (dstFields && srcFields) {
  2798. return dstFields->assign(*srcFields, dstIndices, srcIndices, theBuilder,
  2799. typeTranslator);
  2800. }
  2801. return false;
  2802. }
  2803. const CounterIdAliasPair *
  2804. SPIRVEmitter::getFinalACSBufferCounter(const Expr *expr) {
  2805. // AssocCounter#1: referencing some stand-alone variable
  2806. if (const auto *decl = getReferencedDef(expr))
  2807. return declIdMapper.getCounterIdAliasPair(decl);
  2808. // AssocCounter#2: referencing some non-struct field
  2809. llvm::SmallVector<uint32_t, 4> indices;
  2810. const auto *base =
  2811. collectArrayStructIndices(expr, &indices, /*rawIndex=*/true);
  2812. const auto *decl =
  2813. (base && isa<CXXThisExpr>(base))
  2814. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2815. : getReferencedDef(base);
  2816. return declIdMapper.getCounterIdAliasPair(decl, &indices);
  2817. }
  2818. const CounterVarFields *SPIRVEmitter::getIntermediateACSBufferCounter(
  2819. const Expr *expr, llvm::SmallVector<uint32_t, 4> *indices) {
  2820. const auto *base =
  2821. collectArrayStructIndices(expr, indices, /*rawIndex=*/true);
  2822. const auto *decl =
  2823. (base && isa<CXXThisExpr>(base))
  2824. // Use the decl we created to represent the implicit object
  2825. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2826. // Find the referenced decl from the original source code
  2827. : getReferencedDef(base);
  2828. return declIdMapper.getCounterVarFields(decl);
  2829. }
  2830. const ImplicitParamDecl *
  2831. SPIRVEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  2832. const auto found = thisDecls.find(method);
  2833. if (found != thisDecls.end())
  2834. return found->second;
  2835. const std::string name = method->getName().str() + ".this";
  2836. // Create a new identifier to convey the name
  2837. auto &identifier = astContext.Idents.get(name);
  2838. return thisDecls[method] = ImplicitParamDecl::Create(
  2839. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  2840. method->getThisType(astContext)->getPointeeType());
  2841. }
  2842. SpirvEvalInfo
  2843. SPIRVEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  2844. const bool isAppend = expr->getNumArgs() == 1;
  2845. const uint32_t zero = theBuilder.getConstantUint32(0);
  2846. const auto *object =
  2847. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2848. auto bufferInfo = loadIfAliasVarRef(object);
  2849. uint32_t index = incDecRWACSBufferCounter(
  2850. expr, isAppend,
  2851. // We have already translated the object in the above. Avoid duplication.
  2852. /*loadObject=*/false);
  2853. const auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  2854. (void)turnIntoElementPtr(bufferInfo, bufferElemTy, {zero, index});
  2855. if (isAppend) {
  2856. // Write out the value
  2857. storeValue(bufferInfo, doExpr(expr->getArg(0)), bufferElemTy);
  2858. return 0;
  2859. } else {
  2860. // Note that we are returning a pointer (lvalue) here inorder to further
  2861. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  2862. // cannot forcefully set all normal function calls as returning rvalue.
  2863. return bufferInfo;
  2864. }
  2865. }
  2866. uint32_t
  2867. SPIRVEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  2868. // TODO: handle multiple stream-output objects
  2869. const auto *object =
  2870. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2871. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  2872. const uint32_t value = doExpr(expr->getArg(0));
  2873. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  2874. theBuilder.createEmitVertex();
  2875. return 0;
  2876. }
  2877. uint32_t
  2878. SPIRVEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  2879. // TODO: handle multiple stream-output objects
  2880. theBuilder.createEndPrimitive();
  2881. return 0;
  2882. }
  2883. uint32_t SPIRVEmitter::emitGetSamplePosition(const uint32_t sampleCount,
  2884. const uint32_t sampleIndex) {
  2885. struct Float2 {
  2886. float x;
  2887. float y;
  2888. };
  2889. static const Float2 pos2[] = {
  2890. {4.0 / 16.0, 4.0 / 16.0},
  2891. {-4.0 / 16.0, -4.0 / 16.0},
  2892. };
  2893. static const Float2 pos4[] = {
  2894. {-2.0 / 16.0, -6.0 / 16.0},
  2895. {6.0 / 16.0, -2.0 / 16.0},
  2896. {-6.0 / 16.0, 2.0 / 16.0},
  2897. {2.0 / 16.0, 6.0 / 16.0},
  2898. };
  2899. static const Float2 pos8[] = {
  2900. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  2901. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  2902. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  2903. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  2904. };
  2905. static const Float2 pos16[] = {
  2906. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  2907. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  2908. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  2909. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  2910. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  2911. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  2912. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  2913. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  2914. };
  2915. // We are emitting the SPIR-V for the following HLSL source code:
  2916. //
  2917. // float2 position;
  2918. //
  2919. // if (count == 2) {
  2920. // position = pos2[index];
  2921. // }
  2922. // else if (count == 4) {
  2923. // position = pos4[index];
  2924. // }
  2925. // else if (count == 8) {
  2926. // position = pos8[index];
  2927. // }
  2928. // else if (count == 16) {
  2929. // position = pos16[index];
  2930. // }
  2931. // else {
  2932. // position = float2(0.0f, 0.0f);
  2933. // }
  2934. const uint32_t boolType = theBuilder.getBoolType();
  2935. const auto v2f32Type = theBuilder.getVecType(theBuilder.getFloat32Type(), 2);
  2936. const uint32_t ptrType =
  2937. theBuilder.getPointerType(v2f32Type, spv::StorageClass::Function);
  2938. // Creates a SPIR-V function scope variable of type float2[len].
  2939. const auto createArray = [this, v2f32Type](const Float2 *ptr, uint32_t len) {
  2940. llvm::SmallVector<uint32_t, 16> components;
  2941. for (uint32_t i = 0; i < len; ++i) {
  2942. const auto x = theBuilder.getConstantFloat32(ptr[i].x);
  2943. const auto y = theBuilder.getConstantFloat32(ptr[i].y);
  2944. components.push_back(theBuilder.getConstantComposite(v2f32Type, {x, y}));
  2945. }
  2946. const auto arrType =
  2947. theBuilder.getArrayType(v2f32Type, theBuilder.getConstantUint32(len));
  2948. const auto val = theBuilder.getConstantComposite(arrType, components);
  2949. const std::string varName =
  2950. "var.GetSamplePosition.data." + std::to_string(len);
  2951. const auto var = theBuilder.addFnVar(arrType, varName);
  2952. theBuilder.createStore(var, val);
  2953. return var;
  2954. };
  2955. const uint32_t pos2Arr = createArray(pos2, 2);
  2956. const uint32_t pos4Arr = createArray(pos4, 4);
  2957. const uint32_t pos8Arr = createArray(pos8, 8);
  2958. const uint32_t pos16Arr = createArray(pos16, 16);
  2959. const uint32_t resultVar =
  2960. theBuilder.addFnVar(v2f32Type, "var.GetSamplePosition.result");
  2961. const uint32_t then2BB =
  2962. theBuilder.createBasicBlock("if.GetSamplePosition.then2");
  2963. const uint32_t then4BB =
  2964. theBuilder.createBasicBlock("if.GetSamplePosition.then4");
  2965. const uint32_t then8BB =
  2966. theBuilder.createBasicBlock("if.GetSamplePosition.then8");
  2967. const uint32_t then16BB =
  2968. theBuilder.createBasicBlock("if.GetSamplePosition.then16");
  2969. const uint32_t else2BB =
  2970. theBuilder.createBasicBlock("if.GetSamplePosition.else2");
  2971. const uint32_t else4BB =
  2972. theBuilder.createBasicBlock("if.GetSamplePosition.else4");
  2973. const uint32_t else8BB =
  2974. theBuilder.createBasicBlock("if.GetSamplePosition.else8");
  2975. const uint32_t else16BB =
  2976. theBuilder.createBasicBlock("if.GetSamplePosition.else16");
  2977. const uint32_t merge2BB =
  2978. theBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  2979. const uint32_t merge4BB =
  2980. theBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  2981. const uint32_t merge8BB =
  2982. theBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  2983. const uint32_t merge16BB =
  2984. theBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  2985. // if (count == 2) {
  2986. const auto check2 =
  2987. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  2988. theBuilder.getConstantUint32(2));
  2989. theBuilder.createConditionalBranch(check2, then2BB, else2BB, merge2BB);
  2990. theBuilder.addSuccessor(then2BB);
  2991. theBuilder.addSuccessor(else2BB);
  2992. theBuilder.setMergeTarget(merge2BB);
  2993. // position = pos2[index];
  2994. // }
  2995. theBuilder.setInsertPoint(then2BB);
  2996. auto ac = theBuilder.createAccessChain(ptrType, pos2Arr, {sampleIndex});
  2997. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  2998. theBuilder.createBranch(merge2BB);
  2999. theBuilder.addSuccessor(merge2BB);
  3000. // else if (count == 4) {
  3001. theBuilder.setInsertPoint(else2BB);
  3002. const auto check4 =
  3003. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3004. theBuilder.getConstantUint32(4));
  3005. theBuilder.createConditionalBranch(check4, then4BB, else4BB, merge4BB);
  3006. theBuilder.addSuccessor(then4BB);
  3007. theBuilder.addSuccessor(else4BB);
  3008. theBuilder.setMergeTarget(merge4BB);
  3009. // position = pos4[index];
  3010. // }
  3011. theBuilder.setInsertPoint(then4BB);
  3012. ac = theBuilder.createAccessChain(ptrType, pos4Arr, {sampleIndex});
  3013. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3014. theBuilder.createBranch(merge4BB);
  3015. theBuilder.addSuccessor(merge4BB);
  3016. // else if (count == 8) {
  3017. theBuilder.setInsertPoint(else4BB);
  3018. const auto check8 =
  3019. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3020. theBuilder.getConstantUint32(8));
  3021. theBuilder.createConditionalBranch(check8, then8BB, else8BB, merge8BB);
  3022. theBuilder.addSuccessor(then8BB);
  3023. theBuilder.addSuccessor(else8BB);
  3024. theBuilder.setMergeTarget(merge8BB);
  3025. // position = pos8[index];
  3026. // }
  3027. theBuilder.setInsertPoint(then8BB);
  3028. ac = theBuilder.createAccessChain(ptrType, pos8Arr, {sampleIndex});
  3029. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3030. theBuilder.createBranch(merge8BB);
  3031. theBuilder.addSuccessor(merge8BB);
  3032. // else if (count == 16) {
  3033. theBuilder.setInsertPoint(else8BB);
  3034. const auto check16 =
  3035. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3036. theBuilder.getConstantUint32(16));
  3037. theBuilder.createConditionalBranch(check16, then16BB, else16BB, merge16BB);
  3038. theBuilder.addSuccessor(then16BB);
  3039. theBuilder.addSuccessor(else16BB);
  3040. theBuilder.setMergeTarget(merge16BB);
  3041. // position = pos16[index];
  3042. // }
  3043. theBuilder.setInsertPoint(then16BB);
  3044. ac = theBuilder.createAccessChain(ptrType, pos16Arr, {sampleIndex});
  3045. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3046. theBuilder.createBranch(merge16BB);
  3047. theBuilder.addSuccessor(merge16BB);
  3048. // else {
  3049. // position = float2(0.0f, 0.0f);
  3050. // }
  3051. theBuilder.setInsertPoint(else16BB);
  3052. const auto zero = theBuilder.getConstantFloat32(0);
  3053. const auto v2f32Zero =
  3054. theBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3055. theBuilder.createStore(resultVar, v2f32Zero);
  3056. theBuilder.createBranch(merge16BB);
  3057. theBuilder.addSuccessor(merge16BB);
  3058. theBuilder.setInsertPoint(merge16BB);
  3059. theBuilder.createBranch(merge8BB);
  3060. theBuilder.addSuccessor(merge8BB);
  3061. theBuilder.setInsertPoint(merge8BB);
  3062. theBuilder.createBranch(merge4BB);
  3063. theBuilder.addSuccessor(merge4BB);
  3064. theBuilder.setInsertPoint(merge4BB);
  3065. theBuilder.createBranch(merge2BB);
  3066. theBuilder.addSuccessor(merge2BB);
  3067. theBuilder.setInsertPoint(merge2BB);
  3068. return theBuilder.createLoad(v2f32Type, resultVar);
  3069. }
  3070. SpirvEvalInfo SPIRVEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3071. const FunctionDecl *callee = expr->getDirectCallee();
  3072. llvm::StringRef group;
  3073. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3074. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3075. return processIntrinsicMemberCall(expr,
  3076. static_cast<hlsl::IntrinsicOp>(opcode));
  3077. }
  3078. return processCall(expr);
  3079. }
  3080. void SPIRVEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3081. uint32_t index,
  3082. uint32_t *constOffset,
  3083. uint32_t *varOffset) {
  3084. // Ensure the given arg index is not out-of-range.
  3085. assert(index < expr->getNumArgs());
  3086. *constOffset = *varOffset = 0; // Initialize both first
  3087. if (*constOffset = tryToEvaluateAsConst(expr->getArg(index)))
  3088. return; // Constant offset
  3089. else
  3090. *varOffset = doExpr(expr->getArg(index));
  3091. };
  3092. SpirvEvalInfo
  3093. SPIRVEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3094. hlsl::IntrinsicOp opcode) {
  3095. using namespace hlsl;
  3096. uint32_t retVal = 0;
  3097. switch (opcode) {
  3098. case IntrinsicOp::MOP_Sample:
  3099. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3100. break;
  3101. case IntrinsicOp::MOP_Gather:
  3102. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3103. break;
  3104. case IntrinsicOp::MOP_SampleBias:
  3105. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3106. break;
  3107. case IntrinsicOp::MOP_SampleLevel:
  3108. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3109. break;
  3110. case IntrinsicOp::MOP_SampleGrad:
  3111. retVal = processTextureSampleGrad(expr);
  3112. break;
  3113. case IntrinsicOp::MOP_SampleCmp:
  3114. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3115. break;
  3116. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3117. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3118. break;
  3119. case IntrinsicOp::MOP_GatherRed:
  3120. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3121. break;
  3122. case IntrinsicOp::MOP_GatherGreen:
  3123. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3124. break;
  3125. case IntrinsicOp::MOP_GatherBlue:
  3126. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3127. break;
  3128. case IntrinsicOp::MOP_GatherAlpha:
  3129. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3130. break;
  3131. case IntrinsicOp::MOP_GatherCmp:
  3132. retVal = processTextureGatherCmp(expr);
  3133. break;
  3134. case IntrinsicOp::MOP_GatherCmpRed:
  3135. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3136. break;
  3137. case IntrinsicOp::MOP_Load:
  3138. return processBufferTextureLoad(expr);
  3139. case IntrinsicOp::MOP_Load2:
  3140. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3141. case IntrinsicOp::MOP_Load3:
  3142. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3143. case IntrinsicOp::MOP_Load4:
  3144. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3145. case IntrinsicOp::MOP_Store:
  3146. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3147. case IntrinsicOp::MOP_Store2:
  3148. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3149. case IntrinsicOp::MOP_Store3:
  3150. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3151. case IntrinsicOp::MOP_Store4:
  3152. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3153. case IntrinsicOp::MOP_GetDimensions:
  3154. retVal = processGetDimensions(expr);
  3155. break;
  3156. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3157. retVal = processTextureLevelOfDetail(expr);
  3158. break;
  3159. case IntrinsicOp::MOP_IncrementCounter:
  3160. retVal = theBuilder.createUnaryOp(
  3161. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3162. incDecRWACSBufferCounter(expr, /*isInc*/ true));
  3163. break;
  3164. case IntrinsicOp::MOP_DecrementCounter:
  3165. retVal = theBuilder.createUnaryOp(
  3166. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3167. incDecRWACSBufferCounter(expr, /*isInc*/ false));
  3168. break;
  3169. case IntrinsicOp::MOP_Append:
  3170. if (hlsl::IsHLSLStreamOutputType(
  3171. expr->getImplicitObjectArgument()->getType()))
  3172. return processStreamOutputAppend(expr);
  3173. else
  3174. return processACSBufferAppendConsume(expr);
  3175. case IntrinsicOp::MOP_Consume:
  3176. return processACSBufferAppendConsume(expr);
  3177. case IntrinsicOp::MOP_RestartStrip:
  3178. retVal = processStreamOutputRestart(expr);
  3179. break;
  3180. case IntrinsicOp::MOP_InterlockedAdd:
  3181. case IntrinsicOp::MOP_InterlockedAnd:
  3182. case IntrinsicOp::MOP_InterlockedOr:
  3183. case IntrinsicOp::MOP_InterlockedXor:
  3184. case IntrinsicOp::MOP_InterlockedUMax:
  3185. case IntrinsicOp::MOP_InterlockedUMin:
  3186. case IntrinsicOp::MOP_InterlockedMax:
  3187. case IntrinsicOp::MOP_InterlockedMin:
  3188. case IntrinsicOp::MOP_InterlockedExchange:
  3189. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3190. case IntrinsicOp::MOP_InterlockedCompareStore:
  3191. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3192. break;
  3193. case IntrinsicOp::MOP_GetSamplePosition:
  3194. retVal = processGetSamplePosition(expr);
  3195. break;
  3196. case IntrinsicOp::MOP_SubpassLoad:
  3197. retVal = processSubpassLoad(expr);
  3198. break;
  3199. case IntrinsicOp::MOP_GatherCmpGreen:
  3200. case IntrinsicOp::MOP_GatherCmpBlue:
  3201. case IntrinsicOp::MOP_GatherCmpAlpha:
  3202. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3203. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3204. expr->getCallee()->getExprLoc())
  3205. << expr->getMethodDecl()->getName();
  3206. return 0;
  3207. default:
  3208. emitError("intrinsic '%0' method unimplemented",
  3209. expr->getCallee()->getExprLoc())
  3210. << expr->getDirectCallee()->getName();
  3211. return 0;
  3212. }
  3213. return SpirvEvalInfo(retVal).setRValue();
  3214. }
  3215. uint32_t SPIRVEmitter::createImageSample(
  3216. QualType retType, uint32_t imageType, uint32_t image, uint32_t sampler,
  3217. uint32_t coordinate, uint32_t compareVal, uint32_t bias, uint32_t lod,
  3218. std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  3219. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  3220. uint32_t residencyCodeId) {
  3221. const auto retTypeId = typeTranslator.translateType(retType);
  3222. // SampleDref* instructions in SPIR-V always return a scalar.
  3223. // They also have the correct type in HLSL.
  3224. if (compareVal) {
  3225. return theBuilder.createImageSample(retTypeId, imageType, image, sampler,
  3226. coordinate, compareVal, bias, lod, grad,
  3227. constOffset, varOffset, constOffsets,
  3228. sample, minLod, residencyCodeId);
  3229. }
  3230. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3231. auto texelTypeId = retTypeId;
  3232. QualType elemType = {};
  3233. uint32_t elemTypeId = 0;
  3234. uint32_t retVecSize = 0;
  3235. if (TypeTranslator::isVectorType(retType, &elemType, &retVecSize) &&
  3236. retVecSize != 4) {
  3237. elemTypeId = typeTranslator.translateType(elemType);
  3238. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3239. } else if (TypeTranslator::isScalarType(retType)) {
  3240. retVecSize = 1;
  3241. elemTypeId = typeTranslator.translateType(retType);
  3242. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3243. }
  3244. // The Lod and Grad image operands requires explicit-lod instructions.
  3245. // Otherwise we use implicit-lod instructions.
  3246. const bool isExplicit = lod || (grad.first && grad.second);
  3247. // Implicit-lod instructions are only allowed in pixel shader.
  3248. if (!shaderModel.IsPS() && !isExplicit)
  3249. needsLegalization = true;
  3250. uint32_t retVal = theBuilder.createImageSample(
  3251. texelTypeId, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3252. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3253. residencyCodeId);
  3254. // Extract smaller vector from the vec4 result if necessary.
  3255. if (texelTypeId != retTypeId) {
  3256. retVal = extractVecFromVec4(retVal, retVecSize, elemTypeId);
  3257. }
  3258. return retVal;
  3259. }
  3260. uint32_t SPIRVEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3261. const bool isSample) {
  3262. // Signatures:
  3263. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3264. // DXGI_FORMAT Object.Sample(sampler_state S,
  3265. // float Location
  3266. // [, int Offset]
  3267. // [, float Clamp]
  3268. // [, out uint Status]);
  3269. //
  3270. // For TextureCube and TextureCubeArray:
  3271. // DXGI_FORMAT Object.Sample(sampler_state S,
  3272. // float Location
  3273. // [, float Clamp]
  3274. // [, out uint Status]);
  3275. //
  3276. // For Texture2D/Texture2DArray:
  3277. // <Template Type>4 Object.Gather(sampler_state S,
  3278. // float2|3|4 Location,
  3279. // int2 Offset
  3280. // [, uint Status]);
  3281. //
  3282. // For TextureCube/TextureCubeArray:
  3283. // <Template Type>4 Object.Gather(sampler_state S,
  3284. // float2|3|4 Location
  3285. // [, uint Status]);
  3286. //
  3287. // Other Texture types do not have a Gather method.
  3288. const auto numArgs = expr->getNumArgs();
  3289. const bool hasStatusArg =
  3290. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3291. uint32_t clamp = 0;
  3292. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3293. clamp = doExpr(expr->getArg(2));
  3294. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3295. clamp = doExpr(expr->getArg(3));
  3296. const bool hasClampArg = (clamp != 0);
  3297. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3298. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3299. // and subtract 2 for sampler_state and location.
  3300. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3301. const auto *imageExpr = expr->getImplicitObjectArgument();
  3302. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3303. const uint32_t image = loadIfGLValue(imageExpr);
  3304. const uint32_t sampler = doExpr(expr->getArg(0));
  3305. const uint32_t coordinate = doExpr(expr->getArg(1));
  3306. // .Sample()/.Gather() may have a third optional paramter for offset.
  3307. uint32_t constOffset = 0, varOffset = 0;
  3308. if (hasOffsetArg)
  3309. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3310. const auto retType = expr->getDirectCallee()->getReturnType();
  3311. const auto retTypeId = typeTranslator.translateType(retType);
  3312. if (isSample) {
  3313. return createImageSample(
  3314. retType, imageType, image, sampler, coordinate, /*compareVal*/ 0,
  3315. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  3316. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3317. } else {
  3318. return theBuilder.createImageGather(
  3319. retTypeId, imageType, image, sampler, coordinate,
  3320. // .Gather() doc says we return four components of red data.
  3321. theBuilder.getConstantInt32(0), /*compareVal*/ 0, constOffset,
  3322. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  3323. }
  3324. }
  3325. uint32_t
  3326. SPIRVEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3327. const bool isBias) {
  3328. // Signatures:
  3329. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3330. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3331. // float Location,
  3332. // float Bias
  3333. // [, int Offset]
  3334. // [, float clamp]
  3335. // [, out uint Status]);
  3336. //
  3337. // For TextureCube and TextureCubeArray:
  3338. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3339. // float Location,
  3340. // float Bias
  3341. // [, float clamp]
  3342. // [, out uint Status]);
  3343. //
  3344. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3345. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3346. // float Location,
  3347. // float LOD
  3348. // [, int Offset]
  3349. // [, out uint Status]);
  3350. //
  3351. // For TextureCube and TextureCubeArray:
  3352. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3353. // float Location,
  3354. // float LOD
  3355. // [, out uint Status]);
  3356. const auto numArgs = expr->getNumArgs();
  3357. const bool hasStatusArg =
  3358. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3359. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3360. uint32_t clamp = 0;
  3361. // The .SampleLevel() methods do not take the clamp argument.
  3362. if (isBias) {
  3363. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3364. clamp = doExpr(expr->getArg(3));
  3365. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3366. clamp = doExpr(expr->getArg(4));
  3367. }
  3368. const bool hasClampArg = clamp != 0;
  3369. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3370. // and 3 for sampler_state, location, and Bias/LOD.
  3371. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3372. const auto *imageExpr = expr->getImplicitObjectArgument();
  3373. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3374. const uint32_t image = loadIfGLValue(imageExpr);
  3375. const uint32_t sampler = doExpr(expr->getArg(0));
  3376. const uint32_t coordinate = doExpr(expr->getArg(1));
  3377. uint32_t lod = 0;
  3378. uint32_t bias = 0;
  3379. if (isBias) {
  3380. bias = doExpr(expr->getArg(2));
  3381. } else {
  3382. lod = doExpr(expr->getArg(2));
  3383. }
  3384. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3385. uint32_t constOffset = 0, varOffset = 0;
  3386. if (hasOffsetArg)
  3387. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3388. const auto retType = expr->getDirectCallee()->getReturnType();
  3389. return createImageSample(retType, imageType, image, sampler, coordinate,
  3390. /*compareVal*/ 0, bias, lod, std::make_pair(0, 0),
  3391. constOffset, varOffset, /*constOffsets*/ 0,
  3392. /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3393. }
  3394. uint32_t SPIRVEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3395. // Signature:
  3396. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3397. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3398. // float Location,
  3399. // float DDX,
  3400. // float DDY
  3401. // [, int Offset]
  3402. // [, float Clamp]
  3403. // [, out uint Status]);
  3404. //
  3405. // For TextureCube and TextureCubeArray:
  3406. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3407. // float Location,
  3408. // float DDX,
  3409. // float DDY
  3410. // [, float Clamp]
  3411. // [, out uint Status]);
  3412. const auto numArgs = expr->getNumArgs();
  3413. const bool hasStatusArg =
  3414. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3415. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3416. uint32_t clamp = 0;
  3417. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3418. clamp = doExpr(expr->getArg(4));
  3419. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3420. clamp = doExpr(expr->getArg(5));
  3421. const bool hasClampArg = clamp != 0;
  3422. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3423. // and 4 for sampler_state, location, DDX, and DDY;
  3424. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3425. const auto *imageExpr = expr->getImplicitObjectArgument();
  3426. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3427. const uint32_t image = loadIfGLValue(imageExpr);
  3428. const uint32_t sampler = doExpr(expr->getArg(0));
  3429. const uint32_t coordinate = doExpr(expr->getArg(1));
  3430. const uint32_t ddx = doExpr(expr->getArg(2));
  3431. const uint32_t ddy = doExpr(expr->getArg(3));
  3432. // If offset is present in .SampleGrad(), it is the fifth argument.
  3433. uint32_t constOffset = 0, varOffset = 0;
  3434. if (hasOffsetArg)
  3435. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3436. const auto retType = expr->getDirectCallee()->getReturnType();
  3437. return createImageSample(
  3438. retType, imageType, image, sampler, coordinate, /*compareVal*/ 0,
  3439. /*bias*/ 0, /*lod*/ 0, std::make_pair(ddx, ddy), constOffset, varOffset,
  3440. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3441. }
  3442. uint32_t
  3443. SPIRVEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3444. const bool isCmp) {
  3445. // .SampleCmp() Signature:
  3446. //
  3447. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3448. // float Object.SampleCmp(
  3449. // SamplerComparisonState S,
  3450. // float Location,
  3451. // float CompareValue
  3452. // [, int Offset]
  3453. // [, float Clamp]
  3454. // [, out uint Status]
  3455. // );
  3456. //
  3457. // For TextureCube and TextureCubeArray:
  3458. // float Object.SampleCmp(
  3459. // SamplerComparisonState S,
  3460. // float Location,
  3461. // float CompareValue
  3462. // [, float Clamp]
  3463. // [, out uint Status]
  3464. // );
  3465. //
  3466. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3467. // It never takes a clamp argument, which is good because lod and clamp may
  3468. // not be used together.
  3469. //
  3470. // .SampleCmpLevelZero() Signature:
  3471. //
  3472. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3473. // float Object.SampleCmpLevelZero(
  3474. // SamplerComparisonState S,
  3475. // float Location,
  3476. // float CompareValue
  3477. // [, int Offset]
  3478. // [, out uint Status]
  3479. // );
  3480. //
  3481. // For TextureCube and TextureCubeArray:
  3482. // float Object.SampleCmpLevelZero(
  3483. // SamplerComparisonState S,
  3484. // float Location,
  3485. // float CompareValue
  3486. // [, out uint Status]
  3487. // );
  3488. const auto numArgs = expr->getNumArgs();
  3489. const bool hasStatusArg =
  3490. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3491. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3492. uint32_t clamp = 0;
  3493. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3494. if (isCmp) {
  3495. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3496. clamp = doExpr(expr->getArg(3));
  3497. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3498. clamp = doExpr(expr->getArg(4));
  3499. }
  3500. const bool hasClampArg = clamp != 0;
  3501. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3502. // and 3 for sampler_state, location, and compare_value.
  3503. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3504. const auto *imageExpr = expr->getImplicitObjectArgument();
  3505. const uint32_t image = loadIfGLValue(imageExpr);
  3506. const uint32_t sampler = doExpr(expr->getArg(0));
  3507. const uint32_t coordinate = doExpr(expr->getArg(1));
  3508. const uint32_t compareVal = doExpr(expr->getArg(2));
  3509. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3510. uint32_t constOffset = 0, varOffset = 0;
  3511. if (hasOffsetArg)
  3512. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3513. const uint32_t lod = isCmp ? 0 : theBuilder.getConstantFloat32(0);
  3514. const auto retType = expr->getDirectCallee()->getReturnType();
  3515. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  3516. return createImageSample(retType, imageType, image, sampler, coordinate,
  3517. compareVal, /*bias*/ 0, lod, std::make_pair(0, 0),
  3518. constOffset, varOffset, /*constOffsets*/ 0,
  3519. /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3520. }
  3521. SpirvEvalInfo
  3522. SPIRVEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  3523. // Signature:
  3524. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3525. // ret Object.Load(int Location
  3526. // [, int Offset]
  3527. // [, uint status]);
  3528. //
  3529. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  3530. // ret Object.Load(int Location
  3531. // [, int SampleIndex]
  3532. // [, int Offset]
  3533. // [, uint status]);
  3534. //
  3535. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  3536. // RWTexture2DArray, RWTexture3D:
  3537. // ret Object.Load (int Location
  3538. // [, uint status]);
  3539. //
  3540. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  3541. // methods that take an additional Status argument. However, since these types
  3542. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  3543. // figuring out the Residency Code for them. Therefore having the Status
  3544. // argument for these types is not supported.
  3545. //
  3546. // For (RW)ByteAddressBuffer:
  3547. // ret Object.{Load,Load2,Load3,Load4} (int Location
  3548. // [, uint status]);
  3549. //
  3550. // For (RW)StructuredBuffer:
  3551. // ret Object.Load (int Location
  3552. // [, uint status]);
  3553. //
  3554. const auto *object = expr->getImplicitObjectArgument();
  3555. const auto objectType = object->getType();
  3556. if (typeTranslator.isRWByteAddressBuffer(objectType) ||
  3557. typeTranslator.isByteAddressBuffer(objectType))
  3558. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  3559. if (TypeTranslator::isStructuredBuffer(objectType))
  3560. return processStructuredBufferLoad(expr);
  3561. const auto numArgs = expr->getNumArgs();
  3562. const auto *location = expr->getArg(0);
  3563. const bool isTextureMS = TypeTranslator::isTextureMS(objectType);
  3564. const bool hasStatusArg =
  3565. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3566. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3567. if (TypeTranslator::isBuffer(objectType) ||
  3568. TypeTranslator::isRWBuffer(objectType) ||
  3569. TypeTranslator::isRWTexture(objectType))
  3570. return processBufferTextureLoad(object, doExpr(location), /*constOffset*/ 0,
  3571. /*varOffset*/ 0, /*lod*/ 0,
  3572. /*residencyCode*/ status);
  3573. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  3574. // and 1 for location.
  3575. const bool hasOffsetArg = numArgs - hasStatusArg - isTextureMS - 1 > 0;
  3576. if (TypeTranslator::isTexture(objectType)) {
  3577. // .Load() has a second optional paramter for offset.
  3578. const auto locationId = doExpr(location);
  3579. uint32_t constOffset = 0, varOffset = 0;
  3580. uint32_t coordinate = locationId, lod = 0;
  3581. if (isTextureMS) {
  3582. // SampleIndex is only available when the Object is of Texture2DMS or
  3583. // Texture2DMSArray types. Under those cases, Offset will be the third
  3584. // parameter (index 2).
  3585. lod = doExpr(expr->getArg(1));
  3586. if (hasOffsetArg)
  3587. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3588. } else {
  3589. // For Texture Load() functions, the location parameter is a vector
  3590. // that consists of both the coordinate and the mipmap level (via the
  3591. // last vector element). We need to split it here since the
  3592. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  3593. splitVecLastElement(location->getType(), locationId, &coordinate, &lod);
  3594. // For textures other than Texture2DMS(Array), offset should be the
  3595. // second parameter (index 1).
  3596. if (hasOffsetArg)
  3597. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  3598. }
  3599. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  3600. lod, status);
  3601. }
  3602. emitError("Load() of the given object type unimplemented",
  3603. object->getExprLoc());
  3604. return 0;
  3605. }
  3606. uint32_t SPIRVEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  3607. const auto objectType = expr->getImplicitObjectArgument()->getType();
  3608. if (TypeTranslator::isTexture(objectType) ||
  3609. TypeTranslator::isRWTexture(objectType) ||
  3610. TypeTranslator::isBuffer(objectType) ||
  3611. TypeTranslator::isRWBuffer(objectType)) {
  3612. return processBufferTextureGetDimensions(expr);
  3613. } else if (TypeTranslator::isByteAddressBuffer(objectType) ||
  3614. TypeTranslator::isRWByteAddressBuffer(objectType) ||
  3615. TypeTranslator::isStructuredBuffer(objectType) ||
  3616. TypeTranslator::isAppendStructuredBuffer(objectType) ||
  3617. TypeTranslator::isConsumeStructuredBuffer(objectType)) {
  3618. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  3619. } else {
  3620. emitError("GetDimensions() of the given object type unimplemented",
  3621. expr->getExprLoc());
  3622. return 0;
  3623. }
  3624. }
  3625. SpirvEvalInfo
  3626. SPIRVEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  3627. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  3628. const Expr *baseExpr = nullptr;
  3629. const Expr *indexExpr = nullptr;
  3630. const Expr *lodExpr = nullptr;
  3631. // For Textures, regular indexing (operator[]) uses slice 0.
  3632. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  3633. const uint32_t lod = TypeTranslator::isTexture(baseExpr->getType())
  3634. ? theBuilder.getConstantUint32(0)
  3635. : 0;
  3636. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3637. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3638. /*residencyCode*/ 0);
  3639. }
  3640. // .mips[][] or .sample[][] must use the correct slice.
  3641. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  3642. const uint32_t lod = doExpr(lodExpr);
  3643. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3644. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3645. /*residencyCode*/ 0);
  3646. }
  3647. }
  3648. llvm::SmallVector<uint32_t, 4> indices;
  3649. const Expr *baseExpr = collectArrayStructIndices(expr, &indices);
  3650. auto base = loadIfAliasVarRef(baseExpr);
  3651. if (indices.empty())
  3652. return base; // For indexing into size-1 vectors and 1xN matrices
  3653. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  3654. // to create a local variable to hold the rvalue.
  3655. //
  3656. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  3657. // all indices are contant integers.
  3658. if (base.isRValue()) {
  3659. base = createTemporaryVar(baseExpr->getType(), "vector", base);
  3660. }
  3661. return turnIntoElementPtr(base, expr->getType(), indices);
  3662. }
  3663. SpirvEvalInfo
  3664. SPIRVEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  3665. const Expr *baseExpr = expr->getBase();
  3666. const auto baseInfo = doExpr(baseExpr);
  3667. const auto accessor = expr->getEncodedElementAccess();
  3668. const uint32_t elemType = typeTranslator.translateType(
  3669. hlsl::GetHLSLMatElementType(baseExpr->getType()));
  3670. uint32_t rowCount = 0, colCount = 0;
  3671. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  3672. // Construct a temporary vector out of all elements accessed:
  3673. // 1. Create access chain for each element using OpAccessChain
  3674. // 2. Load each element using OpLoad
  3675. // 3. Create the vector using OpCompositeConstruct
  3676. llvm::SmallVector<uint32_t, 4> elements;
  3677. for (uint32_t i = 0; i < accessor.Count; ++i) {
  3678. uint32_t row = 0, col = 0, elem = 0;
  3679. accessor.GetPosition(i, &row, &col);
  3680. llvm::SmallVector<uint32_t, 2> indices;
  3681. // If the matrix only has one row/column, we are indexing into a vector
  3682. // then. Only one index is needed for such cases.
  3683. if (rowCount > 1)
  3684. indices.push_back(row);
  3685. if (colCount > 1)
  3686. indices.push_back(col);
  3687. if (baseExpr->isGLValue()) {
  3688. for (uint32_t i = 0; i < indices.size(); ++i)
  3689. indices[i] = theBuilder.getConstantInt32(indices[i]);
  3690. const uint32_t ptrType =
  3691. theBuilder.getPointerType(elemType, baseInfo.getStorageClass());
  3692. if (!indices.empty()) {
  3693. assert(!baseInfo.isRValue());
  3694. // Load the element via access chain
  3695. elem = theBuilder.createAccessChain(ptrType, baseInfo, indices);
  3696. } else {
  3697. // The matrix is of size 1x1. No need to use access chain, base should
  3698. // be the source pointer.
  3699. elem = baseInfo;
  3700. }
  3701. elem = theBuilder.createLoad(elemType, elem);
  3702. } else { // e.g., (mat1 + mat2)._m11
  3703. elem = theBuilder.createCompositeExtract(elemType, baseInfo, indices);
  3704. }
  3705. elements.push_back(elem);
  3706. }
  3707. auto valueId = elements.front();
  3708. if (elements.size() > 1) {
  3709. const uint32_t vecType = theBuilder.getVecType(elemType, elements.size());
  3710. valueId = theBuilder.createCompositeConstruct(vecType, elements);
  3711. }
  3712. return SpirvEvalInfo(valueId).setRValue();
  3713. }
  3714. SpirvEvalInfo
  3715. SPIRVEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  3716. const Expr *baseExpr = nullptr;
  3717. hlsl::VectorMemberAccessPositions accessor;
  3718. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  3719. const QualType baseType = baseExpr->getType();
  3720. assert(hlsl::IsHLSLVecType(baseType));
  3721. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  3722. const uint32_t type = typeTranslator.translateType(expr->getType());
  3723. const auto accessorSize = static_cast<size_t>(accessor.Count);
  3724. // Depending on the number of elements selected, we emit different
  3725. // instructions.
  3726. // For vectors of size greater than 1, if we are only selecting one element,
  3727. // typical access chain or composite extraction should be fine. But if we
  3728. // are selecting more than one elements, we must resolve to vector specific
  3729. // operations.
  3730. // For size-1 vectors, if we are selecting their single elements multiple
  3731. // times, we need composite construct instructions.
  3732. if (accessorSize == 1) {
  3733. auto baseInfo = doExpr(baseExpr);
  3734. if (baseSize == 1) {
  3735. // Selecting one element from a size-1 vector. The underlying vector is
  3736. // already treated as a scalar.
  3737. return baseInfo;
  3738. }
  3739. // If the base is an lvalue, we should emit an access chain instruction
  3740. // so that we can load/store the specified element. For rvalue base,
  3741. // we should use composite extraction. We should check the immediate base
  3742. // instead of the original base here since we can have something like
  3743. // v.xyyz to turn a lvalue v into rvalue.
  3744. if (!baseInfo.isRValue()) { // E.g., v.x;
  3745. const uint32_t ptrType =
  3746. theBuilder.getPointerType(type, baseInfo.getStorageClass());
  3747. const uint32_t index = theBuilder.getConstantInt32(accessor.Swz0);
  3748. // We need a lvalue here. Do not try to load.
  3749. return theBuilder.createAccessChain(ptrType, baseInfo, {index});
  3750. } else { // E.g., (v + w).x;
  3751. // The original base vector may not be a rvalue. Need to load it if
  3752. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  3753. // for that case.
  3754. return baseInfo.setResultId(
  3755. theBuilder.createCompositeExtract(type, baseInfo, {accessor.Swz0}));
  3756. }
  3757. }
  3758. if (baseSize == 1) {
  3759. // Selecting more than one element from a size-1 vector, for example,
  3760. // <scalar>.xx. Construct the vector.
  3761. auto info = loadIfGLValue(baseExpr);
  3762. llvm::SmallVector<uint32_t, 4> components(accessorSize, info);
  3763. return info
  3764. .setResultId(theBuilder.createCompositeConstruct(type, components))
  3765. .setRValue();
  3766. }
  3767. llvm::SmallVector<uint32_t, 4> selectors;
  3768. selectors.resize(accessorSize);
  3769. // Whether we are selecting elements in the original order
  3770. bool originalOrder = baseSize == accessorSize;
  3771. for (uint32_t i = 0; i < accessorSize; ++i) {
  3772. accessor.GetPosition(i, &selectors[i]);
  3773. // We can select more elements than the vector provides. This handles
  3774. // that case too.
  3775. originalOrder &= selectors[i] == i;
  3776. }
  3777. if (originalOrder)
  3778. return doExpr(baseExpr);
  3779. auto info = loadIfGLValue(baseExpr);
  3780. // Use base for both vectors. But we are only selecting values from the
  3781. // first one.
  3782. return info.setResultId(
  3783. theBuilder.createVectorShuffle(type, info, info, selectors));
  3784. }
  3785. SpirvEvalInfo SPIRVEmitter::doInitListExpr(const InitListExpr *expr) {
  3786. if (const uint32_t id = tryToEvaluateAsConst(expr))
  3787. return SpirvEvalInfo(id).setRValue();
  3788. return SpirvEvalInfo(InitListHandler(*this).process(expr)).setRValue();
  3789. }
  3790. SpirvEvalInfo SPIRVEmitter::doMemberExpr(const MemberExpr *expr) {
  3791. llvm::SmallVector<uint32_t, 4> indices;
  3792. const Expr *base = collectArrayStructIndices(expr, &indices);
  3793. auto info = loadIfAliasVarRef(base);
  3794. if (!indices.empty()) {
  3795. // Sometime we are accessing the member of a rvalue, e.g.,
  3796. // <some-function-returing-a-struct>().<some-field>
  3797. // Create a temporary variable to hold the rvalue so that we can use access
  3798. // chain to index into it.
  3799. if (info.isRValue()) {
  3800. SpirvEvalInfo tempVar = createTemporaryVar(
  3801. base->getType(), TypeTranslator::getName(base->getType()), info);
  3802. (void)turnIntoElementPtr(tempVar, expr->getType(), indices);
  3803. info.setResultId(theBuilder.createLoad(
  3804. typeTranslator.translateType(expr->getType()), tempVar));
  3805. } else {
  3806. (void)turnIntoElementPtr(info, expr->getType(), indices);
  3807. }
  3808. }
  3809. return info;
  3810. }
  3811. uint32_t SPIRVEmitter::createTemporaryVar(QualType type, llvm::StringRef name,
  3812. const SpirvEvalInfo &init) {
  3813. // We are creating a temporary variable in the Function storage class here,
  3814. // which means it has void layout rule.
  3815. const uint32_t varType = typeTranslator.translateType(type);
  3816. const std::string varName = "temp.var." + name.str();
  3817. const uint32_t varId = theBuilder.addFnVar(varType, varName);
  3818. storeValue(varId, init, type);
  3819. return varId;
  3820. }
  3821. SpirvEvalInfo SPIRVEmitter::doUnaryOperator(const UnaryOperator *expr) {
  3822. const auto opcode = expr->getOpcode();
  3823. const auto *subExpr = expr->getSubExpr();
  3824. const auto subType = subExpr->getType();
  3825. auto subValue = doExpr(subExpr);
  3826. const auto subTypeId = typeTranslator.translateType(subType);
  3827. switch (opcode) {
  3828. case UO_PreInc:
  3829. case UO_PreDec:
  3830. case UO_PostInc:
  3831. case UO_PostDec: {
  3832. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  3833. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  3834. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  3835. const uint32_t originValue = theBuilder.createLoad(subTypeId, subValue);
  3836. const uint32_t one = hlsl::IsHLSLMatType(subType)
  3837. ? getMatElemValueOne(subType)
  3838. : getValueOne(subType);
  3839. uint32_t incValue = 0;
  3840. if (TypeTranslator::isMxNMatrix(subType)) {
  3841. // For matrices, we can only increment/decrement each vector of it.
  3842. const auto actOnEachVec = [this, spvOp, one](uint32_t /*index*/,
  3843. uint32_t vecType,
  3844. uint32_t lhsVec) {
  3845. const auto valId =
  3846. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, one);
  3847. return SpirvEvalInfo(valId).setRValue();
  3848. };
  3849. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec);
  3850. } else {
  3851. incValue = theBuilder.createBinaryOp(spvOp, subTypeId, originValue, one);
  3852. }
  3853. theBuilder.createStore(subValue, incValue);
  3854. // Prefix increment/decrement operator returns a lvalue, while postfix
  3855. // increment/decrement returns a rvalue.
  3856. return isPre ? subValue : SpirvEvalInfo(originValue).setRValue();
  3857. }
  3858. case UO_Not: {
  3859. const auto valId =
  3860. theBuilder.createUnaryOp(spv::Op::OpNot, subTypeId, subValue);
  3861. return SpirvEvalInfo(valId).setRValue();
  3862. }
  3863. case UO_LNot: {
  3864. // Parsing will do the necessary casting to make sure we are applying the
  3865. // ! operator on boolean values.
  3866. const auto valId =
  3867. theBuilder.createUnaryOp(spv::Op::OpLogicalNot, subTypeId, subValue);
  3868. return SpirvEvalInfo(valId).setRValue();
  3869. }
  3870. case UO_Plus:
  3871. // No need to do anything for the prefix + operator.
  3872. return subValue;
  3873. case UO_Minus: {
  3874. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  3875. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  3876. : spv::Op::OpSNegate;
  3877. const auto valId = theBuilder.createUnaryOp(spvOp, subTypeId, subValue);
  3878. return SpirvEvalInfo(valId).setRValue();
  3879. }
  3880. default:
  3881. break;
  3882. }
  3883. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  3884. << expr->getOpcodeStr(opcode);
  3885. expr->dump();
  3886. return 0;
  3887. }
  3888. spv::Op SPIRVEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  3889. const bool isSintType = isSintOrVecMatOfSintType(type);
  3890. const bool isUintType = isUintOrVecMatOfUintType(type);
  3891. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  3892. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  3893. \
  3894. case BO_##kind: { \
  3895. if (isSintType || isUintType) { \
  3896. return spv::Op::Op##intBinOp; \
  3897. } \
  3898. if (isFloatType) { \
  3899. return spv::Op::Op##floatBinOp; \
  3900. } \
  3901. } break
  3902. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  3903. \
  3904. case BO_##kind: { \
  3905. if (isSintType) { \
  3906. return spv::Op::Op##sintBinOp; \
  3907. } \
  3908. if (isUintType) { \
  3909. return spv::Op::Op##uintBinOp; \
  3910. } \
  3911. if (isFloatType) { \
  3912. return spv::Op::Op##floatBinOp; \
  3913. } \
  3914. } break
  3915. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  3916. \
  3917. case BO_##kind: { \
  3918. if (isSintType) { \
  3919. return spv::Op::Op##sintBinOp; \
  3920. } \
  3921. if (isUintType) { \
  3922. return spv::Op::Op##uintBinOp; \
  3923. } \
  3924. } break
  3925. switch (op) {
  3926. case BO_EQ: {
  3927. if (isBoolOrVecMatOfBoolType(type))
  3928. return spv::Op::OpLogicalEqual;
  3929. if (isSintType || isUintType)
  3930. return spv::Op::OpIEqual;
  3931. if (isFloatType)
  3932. return spv::Op::OpFOrdEqual;
  3933. } break;
  3934. case BO_NE: {
  3935. if (isBoolOrVecMatOfBoolType(type))
  3936. return spv::Op::OpLogicalNotEqual;
  3937. if (isSintType || isUintType)
  3938. return spv::Op::OpINotEqual;
  3939. if (isFloatType)
  3940. return spv::Op::OpFOrdNotEqual;
  3941. } break;
  3942. // According to HLSL doc, all sides of the && and || expression are always
  3943. // evaluated.
  3944. case BO_LAnd:
  3945. return spv::Op::OpLogicalAnd;
  3946. case BO_LOr:
  3947. return spv::Op::OpLogicalOr;
  3948. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  3949. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  3950. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  3951. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  3952. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  3953. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  3954. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  3955. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  3956. // According to HLSL spec, "the modulus operator returns the remainder of
  3957. // a division." "The % operator is defined only in cases where either both
  3958. // sides are positive or both sides are negative."
  3959. //
  3960. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  3961. // the former, the sign of a non-0 result comes from Operand 1, while
  3962. // with the latter, from Operand 2.
  3963. //
  3964. // For operands with different signs, technically we can map % to either
  3965. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  3966. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  3967. // const expression evaluation if we map % to Op*Rem.
  3968. //
  3969. // Note there is no OpURem in SPIR-V.
  3970. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  3971. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  3972. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  3973. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  3974. FOrdLessThanEqual);
  3975. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  3976. FOrdGreaterThan);
  3977. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  3978. FOrdGreaterThanEqual);
  3979. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  3980. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  3981. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  3982. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  3983. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  3984. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  3985. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  3986. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  3987. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  3988. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  3989. default:
  3990. break;
  3991. }
  3992. #undef BIN_OP_CASE_INT_FLOAT
  3993. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  3994. #undef BIN_OP_CASE_SINT_UINT
  3995. emitError("translating binary operator '%0' unimplemented", {})
  3996. << BinaryOperator::getOpcodeStr(op);
  3997. return spv::Op::OpNop;
  3998. }
  3999. SpirvEvalInfo SPIRVEmitter::processAssignment(const Expr *lhs,
  4000. const SpirvEvalInfo &rhs,
  4001. const bool isCompoundAssignment,
  4002. SpirvEvalInfo lhsPtr) {
  4003. // Assigning to vector swizzling should be handled differently.
  4004. if (SpirvEvalInfo result = tryToAssignToVectorElements(lhs, rhs))
  4005. return result;
  4006. // Assigning to matrix swizzling should be handled differently.
  4007. if (SpirvEvalInfo result = tryToAssignToMatrixElements(lhs, rhs))
  4008. return result;
  4009. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4010. if (SpirvEvalInfo result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4011. return result;
  4012. // Normal assignment procedure
  4013. if (!lhsPtr)
  4014. lhsPtr = doExpr(lhs);
  4015. storeValue(lhsPtr, rhs, lhs->getType());
  4016. // Plain assignment returns a rvalue, while compound assignment returns
  4017. // lvalue.
  4018. return isCompoundAssignment ? lhsPtr : rhs;
  4019. }
  4020. void SPIRVEmitter::storeValue(const SpirvEvalInfo &lhsPtr,
  4021. const SpirvEvalInfo &rhsVal,
  4022. const QualType lhsValType) {
  4023. // Lambda for cases where we want to store per each array element.
  4024. const auto storeValueForEachArrayElement = [this, &lhsPtr,
  4025. &rhsVal](uint32_t arraySize,
  4026. QualType arrayElemType) {
  4027. for (uint32_t i = 0; i < arraySize; ++i) {
  4028. const auto subRhsValType =
  4029. typeTranslator.translateType(arrayElemType, rhsVal.getLayoutRule());
  4030. const auto subRhsVal =
  4031. theBuilder.createCompositeExtract(subRhsValType, rhsVal, {i});
  4032. const auto subLhsPtrType = theBuilder.getPointerType(
  4033. typeTranslator.translateType(arrayElemType, lhsPtr.getLayoutRule()),
  4034. lhsPtr.getStorageClass());
  4035. const auto subLhsPtr = theBuilder.createAccessChain(
  4036. subLhsPtrType, lhsPtr, {theBuilder.getConstantUint32(i)});
  4037. storeValue(lhsPtr.substResultId(subLhsPtr),
  4038. rhsVal.substResultId(subRhsVal), arrayElemType);
  4039. }
  4040. };
  4041. QualType matElemType = {};
  4042. uint32_t numRows = 0, numCols = 0;
  4043. const bool lhsIsMat =
  4044. typeTranslator.isMxNMatrix(lhsValType, &matElemType, &numRows, &numCols);
  4045. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4046. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4047. if (typeTranslator.isScalarType(lhsValType) ||
  4048. typeTranslator.isVectorType(lhsValType) || lhsIsFloatMat) {
  4049. theBuilder.createStore(lhsPtr, rhsVal);
  4050. } else if (TypeTranslator::isOpaqueType(lhsValType)) {
  4051. // Resource types are represented using RecordType in the AST.
  4052. // Handle them before the general RecordType.
  4053. //
  4054. // HLSL allows to put resource types that translating into SPIR-V opaque
  4055. // types in structs, or assign to variables of resource types. These can all
  4056. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4057. // let SPIRV-Tools opt to do the legalization work.
  4058. //
  4059. // Note: legalization specific code
  4060. theBuilder.createStore(lhsPtr, rhsVal);
  4061. needsLegalization = true;
  4062. } else if (TypeTranslator::isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4063. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4064. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4065. // up.
  4066. //
  4067. // Note: legalization specific code
  4068. theBuilder.createStore(lhsPtr, rhsVal);
  4069. needsLegalization = true;
  4070. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4071. // recursively like normal structs using the following logic.
  4072. //
  4073. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4074. // variables as function parameters/returns/variables, but happily accepts
  4075. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4076. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4077. // represented differently as struct T.
  4078. } else if (lhsPtr.getLayoutRule() == rhsVal.getLayoutRule()) {
  4079. // If lhs and rhs has the same memory layout, we should be safe to load
  4080. // from rhs and directly store into lhs and avoid decomposing rhs.
  4081. // Note: this check should happen after those setting needsLegalization.
  4082. // TODO: is this optimization always correct?
  4083. theBuilder.createStore(lhsPtr, rhsVal);
  4084. } else if (lhsIsNonFpMat) {
  4085. // Note: This check should happen before the RecordType check.
  4086. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  4087. // Each array element is a vector. Get the QualType for the vector.
  4088. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  4089. storeValueForEachArrayElement(numRows, elemType);
  4090. } else if (const auto *recordType = lhsValType->getAs<RecordType>()) {
  4091. uint32_t index = 0;
  4092. for (const auto *field : recordType->getDecl()->fields()) {
  4093. bool isRowMajor =
  4094. typeTranslator.isRowMajorMatrix(field->getType(), field);
  4095. const auto subRhsValType = typeTranslator.translateType(
  4096. field->getType(), rhsVal.getLayoutRule(), isRowMajor);
  4097. const auto subRhsVal =
  4098. theBuilder.createCompositeExtract(subRhsValType, rhsVal, {index});
  4099. const auto subLhsPtrType = theBuilder.getPointerType(
  4100. typeTranslator.translateType(field->getType(), lhsPtr.getLayoutRule(),
  4101. isRowMajor),
  4102. lhsPtr.getStorageClass());
  4103. const auto subLhsPtr = theBuilder.createAccessChain(
  4104. subLhsPtrType, lhsPtr, {theBuilder.getConstantUint32(index)});
  4105. storeValue(lhsPtr.substResultId(subLhsPtr),
  4106. rhsVal.substResultId(subRhsVal), field->getType());
  4107. ++index;
  4108. }
  4109. } else if (const auto *arrayType =
  4110. astContext.getAsConstantArrayType(lhsValType)) {
  4111. const auto elemType = arrayType->getElementType();
  4112. // TODO: handle extra large array size?
  4113. const auto size =
  4114. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4115. storeValueForEachArrayElement(size, elemType);
  4116. } else {
  4117. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4118. }
  4119. }
  4120. SpirvEvalInfo SPIRVEmitter::processBinaryOp(const Expr *lhs, const Expr *rhs,
  4121. const BinaryOperatorKind opcode,
  4122. const QualType computationType,
  4123. const QualType resultType,
  4124. SourceRange sourceRange,
  4125. SpirvEvalInfo *lhsInfo,
  4126. const spv::Op mandateGenOpcode) {
  4127. const QualType lhsType = lhs->getType();
  4128. const QualType rhsType = rhs->getType();
  4129. // Binary logical operations (such as ==, !=, etc) that return a boolean type
  4130. // may get a literal (e.g. 0, 1, etc.) as lhs or rhs args. Since only
  4131. // non-zero-ness of these literals matter, they can be translated as 32-bits.
  4132. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  4133. if (resultType->isBooleanType()) {
  4134. if (lhsType->isSpecificBuiltinType(BuiltinType::LitInt) ||
  4135. rhsType->isSpecificBuiltinType(BuiltinType::LitInt))
  4136. hint.setHint(astContext.IntTy);
  4137. if (lhsType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  4138. rhsType->isSpecificBuiltinType(BuiltinType::LitFloat))
  4139. hint.setHint(astContext.FloatTy);
  4140. }
  4141. // If the operands are of matrix type, we need to dispatch the operation
  4142. // onto each element vector iff the operands are not degenerated matrices
  4143. // and we don't have a matrix specific SPIR-V instruction for the operation.
  4144. if (!isSpirvMatrixOp(mandateGenOpcode) &&
  4145. TypeTranslator::isMxNMatrix(lhsType)) {
  4146. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange);
  4147. }
  4148. // Comma operator works differently from other binary operations as there is
  4149. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  4150. // respectively, and return the results of rhs.
  4151. if (opcode == BO_Comma) {
  4152. (void)doExpr(lhs);
  4153. return doExpr(rhs);
  4154. }
  4155. SpirvEvalInfo rhsVal = 0, lhsPtr = 0, lhsVal = 0;
  4156. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4157. // Evalute rhs before lhs
  4158. rhsVal = loadIfGLValue(rhs);
  4159. lhsVal = lhsPtr = doExpr(lhs);
  4160. // This is a compound assignment. We need to load the lhs value if lhs
  4161. // is not already rvalue and does not generate a vector shuffle.
  4162. if (!lhsPtr.isRValue() && !isVectorShuffle(lhs)) {
  4163. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4164. }
  4165. // For a compound assignments, the AST does not have the proper implicit
  4166. // cast if lhs and rhs have different types. So we need to manually cast lhs
  4167. // to the computation type.
  4168. if (computationType != lhsType)
  4169. lhsVal.setResultId(
  4170. castToType(lhsVal, lhsType, computationType, lhs->getExprLoc()));
  4171. } else {
  4172. // Evalute lhs before rhs
  4173. lhsPtr = doExpr(lhs);
  4174. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4175. rhsVal = loadIfGLValue(rhs);
  4176. }
  4177. if (lhsInfo)
  4178. *lhsInfo = lhsPtr;
  4179. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  4180. ? translateOp(opcode, computationType)
  4181. : mandateGenOpcode;
  4182. switch (opcode) {
  4183. case BO_Add:
  4184. case BO_Sub:
  4185. case BO_Mul:
  4186. case BO_Div:
  4187. case BO_Rem:
  4188. case BO_LT:
  4189. case BO_LE:
  4190. case BO_GT:
  4191. case BO_GE:
  4192. case BO_EQ:
  4193. case BO_NE:
  4194. case BO_And:
  4195. case BO_Or:
  4196. case BO_Xor:
  4197. case BO_Shl:
  4198. case BO_Shr:
  4199. case BO_LAnd:
  4200. case BO_LOr:
  4201. case BO_AddAssign:
  4202. case BO_SubAssign:
  4203. case BO_MulAssign:
  4204. case BO_DivAssign:
  4205. case BO_RemAssign:
  4206. case BO_AndAssign:
  4207. case BO_OrAssign:
  4208. case BO_XorAssign:
  4209. case BO_ShlAssign:
  4210. case BO_ShrAssign: {
  4211. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4212. // both operands are constant and at least one of them is a spec constant.
  4213. if (lhsVal.isConstant() && rhsVal.isConstant() &&
  4214. (lhsVal.isSpecConstant() || rhsVal.isSpecConstant()) &&
  4215. isAcceptedSpecConstantBinaryOp(spvOp)) {
  4216. const auto valId = theBuilder.createSpecConstantBinaryOp(
  4217. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4218. return SpirvEvalInfo(valId).setRValue().setSpecConstant();
  4219. }
  4220. // Normal binary operation
  4221. uint32_t valId = 0;
  4222. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4223. valId = theBuilder.createBinaryOp(
  4224. spvOp, typeTranslator.translateType(computationType), lhsVal, rhsVal);
  4225. // For a compound assignments, the AST does not have the proper implicit
  4226. // cast if lhs and rhs have different types. So we need to manually cast
  4227. // the result back to lhs' type.
  4228. if (computationType != lhsType)
  4229. valId = castToType(valId, computationType, lhsType, lhs->getExprLoc());
  4230. } else {
  4231. valId = theBuilder.createBinaryOp(
  4232. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4233. }
  4234. auto result = SpirvEvalInfo(valId).setRValue();
  4235. if (lhsVal.isRelaxedPrecision() || rhsVal.isRelaxedPrecision())
  4236. result.setRelaxedPrecision();
  4237. return result;
  4238. }
  4239. case BO_Assign:
  4240. llvm_unreachable("assignment should not be handled here");
  4241. }
  4242. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4243. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4244. return 0;
  4245. }
  4246. void SPIRVEmitter::initOnce(QualType varType, std::string varName,
  4247. uint32_t varPtr, const Expr *varInit) {
  4248. // For uninitialized resource objects, we do nothing since there is no
  4249. // meaningful zero values for them.
  4250. if (!varInit && hlsl::IsHLSLResourceType(varType))
  4251. return;
  4252. const uint32_t boolType = theBuilder.getBoolType();
  4253. varName = "init.done." + varName;
  4254. // Create a file/module visible variable to hold the initialization state.
  4255. const uint32_t initDoneVar =
  4256. theBuilder.addModuleVar(boolType, spv::StorageClass::Private, varName,
  4257. theBuilder.getConstantBool(false));
  4258. const uint32_t condition = theBuilder.createLoad(boolType, initDoneVar);
  4259. const uint32_t todoBB = theBuilder.createBasicBlock("if.init.todo");
  4260. const uint32_t doneBB = theBuilder.createBasicBlock("if.init.done");
  4261. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4262. // jump to the "todo" basic block.
  4263. theBuilder.createConditionalBranch(condition, doneBB, todoBB, doneBB);
  4264. theBuilder.addSuccessor(todoBB);
  4265. theBuilder.addSuccessor(doneBB);
  4266. theBuilder.setMergeTarget(doneBB);
  4267. theBuilder.setInsertPoint(todoBB);
  4268. // Do initialization and mark done
  4269. if (varInit) {
  4270. storeValue(
  4271. // Static function variable are of private storage class
  4272. SpirvEvalInfo(varPtr).setStorageClass(spv::StorageClass::Private),
  4273. doExpr(varInit), varInit->getType());
  4274. } else {
  4275. const auto typeId = typeTranslator.translateType(varType);
  4276. theBuilder.createStore(varPtr, theBuilder.getConstantNull(typeId));
  4277. }
  4278. theBuilder.createStore(initDoneVar, theBuilder.getConstantBool(true));
  4279. theBuilder.createBranch(doneBB);
  4280. theBuilder.addSuccessor(doneBB);
  4281. theBuilder.setInsertPoint(doneBB);
  4282. }
  4283. bool SPIRVEmitter::isVectorShuffle(const Expr *expr) {
  4284. // TODO: the following check is essentially duplicated from
  4285. // doHLSLVectorElementExpr. Should unify them.
  4286. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4287. const Expr *base = nullptr;
  4288. hlsl::VectorMemberAccessPositions accessor;
  4289. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4290. const auto accessorSize = accessor.Count;
  4291. if (accessorSize == 1) {
  4292. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4293. // such cases.
  4294. return false;
  4295. }
  4296. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4297. if (accessorSize != baseSize)
  4298. return true;
  4299. for (uint32_t i = 0; i < accessorSize; ++i) {
  4300. uint32_t position;
  4301. accessor.GetPosition(i, &position);
  4302. if (position != i)
  4303. return true;
  4304. }
  4305. // Selecting exactly the original vector. No vector shuffle generated.
  4306. return false;
  4307. }
  4308. return false;
  4309. }
  4310. bool SPIRVEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4311. const Expr **base,
  4312. const Expr **location,
  4313. const Expr **lod) {
  4314. if (!expr)
  4315. return false;
  4316. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4317. const CXXOperatorCallExpr *outerExpr = expr;
  4318. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4319. return false;
  4320. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4321. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4322. // Must have an inner operator[]
  4323. if (!innerExpr ||
  4324. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4325. return false;
  4326. }
  4327. const Expr *innerArg0 =
  4328. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4329. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4330. if (!memberExpr)
  4331. return false;
  4332. // Must be accessing the member named "mips" or "sample"
  4333. const auto &memberName =
  4334. memberExpr->getMemberNameInfo().getName().getAsString();
  4335. if (memberName != "mips" && memberName != "sample")
  4336. return false;
  4337. const Expr *object = memberExpr->getBase();
  4338. const auto objectType = object->getType();
  4339. if (!TypeTranslator::isTexture(objectType))
  4340. return false;
  4341. if (base)
  4342. *base = object;
  4343. if (lod)
  4344. *lod = innerExpr->getArg(1);
  4345. if (location)
  4346. *location = outerExpr->getArg(1);
  4347. return true;
  4348. }
  4349. bool SPIRVEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  4350. const Expr **base,
  4351. const Expr **index) {
  4352. if (!indexExpr)
  4353. return false;
  4354. // Must be operator[]
  4355. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4356. return false;
  4357. const Expr *object = indexExpr->getArg(0);
  4358. const auto objectType = object->getType();
  4359. if (TypeTranslator::isBuffer(objectType) ||
  4360. TypeTranslator::isRWBuffer(objectType) ||
  4361. TypeTranslator::isTexture(objectType) ||
  4362. TypeTranslator::isRWTexture(objectType)) {
  4363. if (base)
  4364. *base = object;
  4365. if (index)
  4366. *index = indexExpr->getArg(1);
  4367. return true;
  4368. }
  4369. return false;
  4370. }
  4371. void SPIRVEmitter::condenseVectorElementExpr(
  4372. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  4373. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  4374. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  4375. accessors.push_back(expr->getEncodedElementAccess());
  4376. // Recursively descending until we find the true base vector. In the
  4377. // meanwhile, collecting accessors in the reverse order.
  4378. *basePtr = expr->getBase();
  4379. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  4380. accessors.push_back(vecElemBase->getEncodedElementAccess());
  4381. *basePtr = vecElemBase->getBase();
  4382. }
  4383. *flattenedAccessor = accessors.back();
  4384. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  4385. const auto &currentAccessor = accessors[i];
  4386. // Apply the current level of accessor to the flattened accessor of all
  4387. // previous levels of ones.
  4388. hlsl::VectorMemberAccessPositions combinedAccessor;
  4389. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  4390. uint32_t currentPosition = 0;
  4391. currentAccessor.GetPosition(j, &currentPosition);
  4392. uint32_t previousPosition = 0;
  4393. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  4394. combinedAccessor.SetPosition(j, previousPosition);
  4395. }
  4396. combinedAccessor.Count = currentAccessor.Count;
  4397. combinedAccessor.IsValid =
  4398. flattenedAccessor->IsValid && currentAccessor.IsValid;
  4399. *flattenedAccessor = combinedAccessor;
  4400. }
  4401. }
  4402. SpirvEvalInfo SPIRVEmitter::createVectorSplat(const Expr *scalarExpr,
  4403. uint32_t size) {
  4404. bool isConstVal = false;
  4405. SpirvEvalInfo scalarVal = 0;
  4406. // Try to evaluate the element as constant first. If successful, then we
  4407. // can generate constant instructions for this vector splat.
  4408. if (scalarVal = tryToEvaluateAsConst(scalarExpr)) {
  4409. isConstVal = true;
  4410. } else {
  4411. scalarVal = doExpr(scalarExpr);
  4412. }
  4413. if (size == 1) {
  4414. // Just return the scalar value for vector splat with size 1.
  4415. // Note that can be used as an lvalue, so we need to carry over
  4416. // the lvalueness for non-constant cases.
  4417. return isConstVal ? scalarVal.setConstant().setRValue() : scalarVal;
  4418. }
  4419. const uint32_t vecType = theBuilder.getVecType(
  4420. typeTranslator.translateType(scalarExpr->getType()), size);
  4421. llvm::SmallVector<uint32_t, 4> elements(size_t(size), scalarVal);
  4422. // TODO: we are saying the constant has Function storage class here.
  4423. // Should find a more meaningful one.
  4424. if (isConstVal) {
  4425. const auto valueId = theBuilder.getConstantComposite(vecType, elements);
  4426. return SpirvEvalInfo(valueId).setConstant().setRValue();
  4427. } else {
  4428. const auto valueId = theBuilder.createCompositeConstruct(vecType, elements);
  4429. return SpirvEvalInfo(valueId).setRValue();
  4430. }
  4431. }
  4432. void SPIRVEmitter::splitVecLastElement(QualType vecType, uint32_t vec,
  4433. uint32_t *residual,
  4434. uint32_t *lastElement) {
  4435. assert(hlsl::IsHLSLVecType(vecType));
  4436. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  4437. assert(count > 1);
  4438. const uint32_t elemTypeId =
  4439. typeTranslator.translateType(hlsl::GetHLSLVecElementType(vecType));
  4440. if (count == 2) {
  4441. *residual = theBuilder.createCompositeExtract(elemTypeId, vec, 0);
  4442. } else {
  4443. llvm::SmallVector<uint32_t, 4> indices;
  4444. for (uint32_t i = 0; i < count - 1; ++i)
  4445. indices.push_back(i);
  4446. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count - 1);
  4447. *residual = theBuilder.createVectorShuffle(typeId, vec, vec, indices);
  4448. }
  4449. *lastElement =
  4450. theBuilder.createCompositeExtract(elemTypeId, vec, {count - 1});
  4451. }
  4452. SpirvEvalInfo
  4453. SPIRVEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  4454. const QualType type = expr->getType();
  4455. const SourceRange range = expr->getSourceRange();
  4456. // We can only translate floatN * float into OpVectorTimesScalar.
  4457. // So the result type must be floatN.
  4458. if (!hlsl::IsHLSLVecType(type) ||
  4459. !hlsl::GetHLSLVecElementType(type)->isFloatingType())
  4460. return 0;
  4461. const Expr *lhs = expr->getLHS();
  4462. const Expr *rhs = expr->getRHS();
  4463. // Multiplying a float vector with a float scalar will be represented in
  4464. // AST via a binary operation with two float vectors as operands; one of
  4465. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  4466. // vector * scalar
  4467. if (hlsl::IsHLSLVecType(lhs->getType())) {
  4468. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4469. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4470. const QualType vecType = expr->getType();
  4471. if (isa<CompoundAssignOperator>(expr)) {
  4472. SpirvEvalInfo lhsPtr = 0;
  4473. const auto result = processBinaryOp(
  4474. lhs, cast->getSubExpr(), expr->getOpcode(), vecType, vecType,
  4475. range, &lhsPtr, spv::Op::OpVectorTimesScalar);
  4476. return processAssignment(lhs, result, true, lhsPtr);
  4477. } else {
  4478. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4479. vecType, vecType, range, nullptr,
  4480. spv::Op::OpVectorTimesScalar);
  4481. }
  4482. }
  4483. }
  4484. }
  4485. // scalar * vector
  4486. if (hlsl::IsHLSLVecType(rhs->getType())) {
  4487. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4488. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4489. const QualType vecType = expr->getType();
  4490. // We need to switch the positions of lhs and rhs here because
  4491. // OpVectorTimesScalar requires the first operand to be a vector and
  4492. // the second to be a scalar.
  4493. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4494. vecType, vecType, range, nullptr,
  4495. spv::Op::OpVectorTimesScalar);
  4496. }
  4497. }
  4498. }
  4499. return 0;
  4500. }
  4501. SpirvEvalInfo
  4502. SPIRVEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  4503. const QualType type = expr->getType();
  4504. const SourceRange range = expr->getSourceRange();
  4505. // We can only translate floatMxN * float into OpMatrixTimesScalar.
  4506. // So the result type must be floatMxN.
  4507. if (!hlsl::IsHLSLMatType(type) ||
  4508. !hlsl::GetHLSLMatElementType(type)->isFloatingType())
  4509. return 0;
  4510. const Expr *lhs = expr->getLHS();
  4511. const Expr *rhs = expr->getRHS();
  4512. const QualType lhsType = lhs->getType();
  4513. const QualType rhsType = rhs->getType();
  4514. const auto selectOpcode = [](const QualType ty) {
  4515. return TypeTranslator::isMx1Matrix(ty) || TypeTranslator::is1xNMatrix(ty)
  4516. ? spv::Op::OpVectorTimesScalar
  4517. : spv::Op::OpMatrixTimesScalar;
  4518. };
  4519. // Multiplying a float matrix with a float scalar will be represented in
  4520. // AST via a binary operation with two float matrices as operands; one of
  4521. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  4522. // matrix * scalar
  4523. if (hlsl::IsHLSLMatType(lhsType)) {
  4524. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4525. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4526. const QualType matType = expr->getType();
  4527. const spv::Op opcode = selectOpcode(lhsType);
  4528. if (isa<CompoundAssignOperator>(expr)) {
  4529. SpirvEvalInfo lhsPtr = 0;
  4530. const auto result =
  4531. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4532. matType, matType, range, &lhsPtr, opcode);
  4533. return processAssignment(lhs, result, true, lhsPtr);
  4534. } else {
  4535. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4536. matType, matType, range, nullptr, opcode);
  4537. }
  4538. }
  4539. }
  4540. }
  4541. // scalar * matrix
  4542. if (hlsl::IsHLSLMatType(rhsType)) {
  4543. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4544. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4545. const QualType matType = expr->getType();
  4546. const spv::Op opcode = selectOpcode(rhsType);
  4547. // We need to switch the positions of lhs and rhs here because
  4548. // OpMatrixTimesScalar requires the first operand to be a matrix and
  4549. // the second to be a scalar.
  4550. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4551. matType, matType, range, nullptr, opcode);
  4552. }
  4553. }
  4554. }
  4555. return 0;
  4556. }
  4557. SpirvEvalInfo
  4558. SPIRVEmitter::tryToAssignToVectorElements(const Expr *lhs,
  4559. const SpirvEvalInfo &rhs) {
  4560. // Assigning to a vector swizzling lhs is tricky if we are neither
  4561. // writing to one element nor all elements in their original order.
  4562. // Under such cases, we need to create a new vector swizzling involving
  4563. // both the lhs and rhs vectors and then write the result of this swizzling
  4564. // into the base vector of lhs.
  4565. // For example, for vec4.yz = vec2, we nee to do the following:
  4566. //
  4567. // %vec4Val = OpLoad %v4float %vec4
  4568. // %vec2Val = OpLoad %v2float %vec2
  4569. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  4570. // OpStore %vec4 %shuffle
  4571. //
  4572. // When doing the vector shuffle, we use the lhs base vector as the first
  4573. // vector and the rhs vector as the second vector. Therefore, all elements
  4574. // in the second vector will be selected into the shuffle result.
  4575. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  4576. if (!lhsExpr)
  4577. return 0;
  4578. // Special case for <scalar-value>.x, which will have an AST of
  4579. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  4580. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  4581. // for such case.
  4582. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  4583. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  4584. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  4585. return processAssignment(baseCast->getSubExpr(), rhs, false);
  4586. const Expr *base = nullptr;
  4587. hlsl::VectorMemberAccessPositions accessor;
  4588. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  4589. const QualType baseType = base->getType();
  4590. assert(hlsl::IsHLSLVecType(baseType));
  4591. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  4592. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4593. const auto accessorSize = accessor.Count;
  4594. // Whether selecting the whole original vector
  4595. bool isSelectOrigin = accessorSize == baseSize;
  4596. // Assigning to one component
  4597. if (accessorSize == 1) {
  4598. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  4599. // Assigning to one component of a RWBuffer/RWTexture element
  4600. // We need to use OpImageWrite here.
  4601. // Compose the new vector value first
  4602. const uint32_t oldVec = doExpr(base);
  4603. const uint32_t newVec = theBuilder.createCompositeInsert(
  4604. baseTypeId, oldVec, {accessor.Swz0}, rhs);
  4605. const auto result = tryToAssignToRWBufferRWTexture(base, newVec);
  4606. assert(result); // Definitely RWBuffer/RWTexture assignment
  4607. return rhs; // TODO: incorrect for compound assignments
  4608. } else {
  4609. // Assigning to one normal vector component. Nothing special, just fall
  4610. // back to the normal CodeGen path.
  4611. return 0;
  4612. }
  4613. }
  4614. if (isSelectOrigin) {
  4615. for (uint32_t i = 0; i < accessorSize; ++i) {
  4616. uint32_t position;
  4617. accessor.GetPosition(i, &position);
  4618. if (position != i)
  4619. isSelectOrigin = false;
  4620. }
  4621. }
  4622. // Assigning to the original vector
  4623. if (isSelectOrigin) {
  4624. // Ignore this HLSLVectorElementExpr and dispatch to base
  4625. return processAssignment(base, rhs, false);
  4626. }
  4627. llvm::SmallVector<uint32_t, 4> selectors;
  4628. selectors.resize(baseSize);
  4629. // Assume we are selecting all original elements first.
  4630. for (uint32_t i = 0; i < baseSize; ++i) {
  4631. selectors[i] = i;
  4632. }
  4633. // Now fix up the elements that actually got overwritten by the rhs vector.
  4634. // Since we are using the rhs vector as the second vector, their index
  4635. // should be offset'ed by the size of the lhs base vector.
  4636. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4637. uint32_t position;
  4638. accessor.GetPosition(i, &position);
  4639. selectors[position] = baseSize + i;
  4640. }
  4641. const auto vec1 = doExpr(base);
  4642. const uint32_t vec1Val =
  4643. vec1.isRValue() ? vec1 : theBuilder.createLoad(baseTypeId, vec1);
  4644. const uint32_t shuffle =
  4645. theBuilder.createVectorShuffle(baseTypeId, vec1Val, rhs, selectors);
  4646. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  4647. theBuilder.createStore(vec1, shuffle);
  4648. // TODO: OK, this return value is incorrect for compound assignments, for
  4649. // which cases we should return lvalues. Should at least emit errors if
  4650. // this return value is used (can be checked via ASTContext.getParents).
  4651. return rhs;
  4652. }
  4653. SpirvEvalInfo
  4654. SPIRVEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  4655. const SpirvEvalInfo &rhs) {
  4656. const Expr *baseExpr = nullptr;
  4657. const Expr *indexExpr = nullptr;
  4658. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  4659. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  4660. const uint32_t locId = doExpr(indexExpr);
  4661. const QualType imageType = baseExpr->getType();
  4662. const uint32_t imageId = theBuilder.createLoad(
  4663. typeTranslator.translateType(imageType), doExpr(baseExpr));
  4664. theBuilder.createImageWrite(imageType, imageId, locId, rhs);
  4665. return rhs;
  4666. }
  4667. return 0;
  4668. }
  4669. SpirvEvalInfo
  4670. SPIRVEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  4671. const SpirvEvalInfo &rhs) {
  4672. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  4673. if (!lhsExpr)
  4674. return 0;
  4675. const Expr *baseMat = lhsExpr->getBase();
  4676. const auto base = doExpr(baseMat);
  4677. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  4678. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  4679. uint32_t rowCount = 0, colCount = 0;
  4680. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  4681. // For each lhs element written to:
  4682. // 1. Extract the corresponding rhs element using OpCompositeExtract
  4683. // 2. Create access chain for the lhs element using OpAccessChain
  4684. // 3. Write using OpStore
  4685. const auto accessor = lhsExpr->getEncodedElementAccess();
  4686. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4687. uint32_t row = 0, col = 0;
  4688. accessor.GetPosition(i, &row, &col);
  4689. llvm::SmallVector<uint32_t, 2> indices;
  4690. // If the matrix only have one row/column, we are indexing into a vector
  4691. // then. Only one index is needed for such cases.
  4692. if (rowCount > 1)
  4693. indices.push_back(row);
  4694. if (colCount > 1)
  4695. indices.push_back(col);
  4696. for (uint32_t i = 0; i < indices.size(); ++i)
  4697. indices[i] = theBuilder.getConstantInt32(indices[i]);
  4698. // If we are writing to only one element, the rhs should already be a
  4699. // scalar value.
  4700. uint32_t rhsElem = rhs;
  4701. if (accessor.Count > 1)
  4702. rhsElem = theBuilder.createCompositeExtract(elemTypeId, rhs, {i});
  4703. const uint32_t ptrType =
  4704. theBuilder.getPointerType(elemTypeId, base.getStorageClass());
  4705. // If the lhs is actually a matrix of size 1x1, we don't need the access
  4706. // chain. base is already the dest pointer.
  4707. uint32_t lhsElemPtr = base;
  4708. if (!indices.empty()) {
  4709. assert(!base.isRValue());
  4710. // Load the element via access chain
  4711. lhsElemPtr = theBuilder.createAccessChain(ptrType, lhsElemPtr, indices);
  4712. }
  4713. theBuilder.createStore(lhsElemPtr, rhsElem);
  4714. }
  4715. // TODO: OK, this return value is incorrect for compound assignments, for
  4716. // which cases we should return lvalues. Should at least emit errors if
  4717. // this return value is used (can be checked via ASTContext.getParents).
  4718. return rhs;
  4719. }
  4720. SpirvEvalInfo SPIRVEmitter::processEachVectorInMatrix(
  4721. const Expr *matrix, const uint32_t matrixVal,
  4722. llvm::function_ref<uint32_t(uint32_t, uint32_t, uint32_t)>
  4723. actOnEachVector) {
  4724. const auto matType = matrix->getType();
  4725. assert(TypeTranslator::isMxNMatrix(matType));
  4726. const uint32_t vecType = typeTranslator.getComponentVectorType(matType);
  4727. uint32_t rowCount = 0, colCount = 0;
  4728. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  4729. llvm::SmallVector<uint32_t, 4> vectors;
  4730. // Extract each component vector and do operation on it
  4731. for (uint32_t i = 0; i < rowCount; ++i) {
  4732. const uint32_t lhsVec =
  4733. theBuilder.createCompositeExtract(vecType, matrixVal, {i});
  4734. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  4735. }
  4736. // Construct the result matrix
  4737. const auto valId = theBuilder.createCompositeConstruct(
  4738. typeTranslator.translateType(matType), vectors);
  4739. return SpirvEvalInfo(valId).setRValue();
  4740. }
  4741. void SPIRVEmitter::createSpecConstant(const VarDecl *varDecl) {
  4742. class SpecConstantEnvRAII {
  4743. public:
  4744. // Creates a new instance which sets mode to true on creation,
  4745. // and resets mode to false on destruction.
  4746. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  4747. ~SpecConstantEnvRAII() { *modeSlot = false; }
  4748. private:
  4749. bool *modeSlot;
  4750. };
  4751. const QualType varType = varDecl->getType();
  4752. bool hasError = false;
  4753. if (!varDecl->isExternallyVisible()) {
  4754. emitError("specialization constant must be externally visible",
  4755. varDecl->getLocation());
  4756. hasError = true;
  4757. }
  4758. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  4759. switch (builtinType->getKind()) {
  4760. case BuiltinType::Bool:
  4761. case BuiltinType::Int:
  4762. case BuiltinType::UInt:
  4763. case BuiltinType::Float:
  4764. break;
  4765. default:
  4766. emitError("unsupported specialization constant type",
  4767. varDecl->getLocStart());
  4768. hasError = true;
  4769. }
  4770. }
  4771. const auto *init = varDecl->getInit();
  4772. if (!init) {
  4773. emitError("missing default value for specialization constant",
  4774. varDecl->getLocation());
  4775. hasError = true;
  4776. } else if (!isAcceptedSpecConstantInit(init)) {
  4777. emitError("unsupported specialization constant initializer",
  4778. init->getLocStart())
  4779. << init->getSourceRange();
  4780. hasError = true;
  4781. }
  4782. if (hasError)
  4783. return;
  4784. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  4785. const auto specConstant = doExpr(init);
  4786. // We are not creating a variable to hold the spec constant, instead, we
  4787. // translate the varDecl directly into the spec constant here.
  4788. theBuilder.decorateSpecId(
  4789. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId());
  4790. declIdMapper.registerSpecConstant(varDecl, specConstant);
  4791. }
  4792. SpirvEvalInfo
  4793. SPIRVEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  4794. const BinaryOperatorKind opcode,
  4795. SourceRange range) {
  4796. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  4797. const auto lhsType = lhs->getType();
  4798. assert(TypeTranslator::isMxNMatrix(lhsType));
  4799. const spv::Op spvOp = translateOp(opcode, lhsType);
  4800. uint32_t rhsVal, lhsPtr, lhsVal;
  4801. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4802. // Evalute rhs before lhs
  4803. rhsVal = doExpr(rhs);
  4804. lhsPtr = doExpr(lhs);
  4805. const uint32_t lhsTy = typeTranslator.translateType(lhsType);
  4806. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  4807. } else {
  4808. // Evalute lhs before rhs
  4809. lhsVal = lhsPtr = doExpr(lhs);
  4810. rhsVal = doExpr(rhs);
  4811. }
  4812. switch (opcode) {
  4813. case BO_Add:
  4814. case BO_Sub:
  4815. case BO_Mul:
  4816. case BO_Div:
  4817. case BO_Rem:
  4818. case BO_AddAssign:
  4819. case BO_SubAssign:
  4820. case BO_MulAssign:
  4821. case BO_DivAssign:
  4822. case BO_RemAssign: {
  4823. const uint32_t vecType = typeTranslator.getComponentVectorType(lhsType);
  4824. const auto actOnEachVec = [this, spvOp, rhsVal](uint32_t index,
  4825. uint32_t vecType,
  4826. uint32_t lhsVec) {
  4827. // For each vector of lhs, we need to load the corresponding vector of
  4828. // rhs and do the operation on them.
  4829. const uint32_t rhsVec =
  4830. theBuilder.createCompositeExtract(vecType, rhsVal, {index});
  4831. const auto valId =
  4832. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec);
  4833. return SpirvEvalInfo(valId).setRValue();
  4834. };
  4835. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec);
  4836. }
  4837. case BO_Assign:
  4838. llvm_unreachable("assignment should not be handled here");
  4839. default:
  4840. break;
  4841. }
  4842. emitError("binary operator '%0' over matrix type unimplemented",
  4843. lhs->getExprLoc())
  4844. << BinaryOperator::getOpcodeStr(opcode) << range;
  4845. return 0;
  4846. }
  4847. const Expr *SPIRVEmitter::collectArrayStructIndices(
  4848. const Expr *expr, llvm::SmallVectorImpl<uint32_t> *indices, bool rawIndex) {
  4849. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  4850. // First check whether this is referring to a static member. If it is, we
  4851. // create a DeclRefExpr for it.
  4852. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  4853. if (varDecl->isStaticDataMember())
  4854. return DeclRefExpr::Create(
  4855. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  4856. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  4857. varDecl->getType(), VK_LValue);
  4858. const Expr *base = collectArrayStructIndices(
  4859. indexing->getBase()->IgnoreParenNoopCasts(astContext), indices,
  4860. rawIndex);
  4861. // Append the index of the current level
  4862. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  4863. assert(fieldDecl);
  4864. // If we are accessing a derived struct, we need to account for the number
  4865. // of base structs, since they are placed as fields at the beginning of the
  4866. // derived struct.
  4867. const uint32_t index = getNumBaseClasses(indexing->getBase()->getType()) +
  4868. fieldDecl->getFieldIndex();
  4869. indices->push_back(rawIndex ? index : theBuilder.getConstantInt32(index));
  4870. return base;
  4871. }
  4872. // Provide a hint to the TypeTranslator that the integer literal used to
  4873. // index into the following cases should be translated as a 32-bit integer.
  4874. TypeTranslator::LiteralTypeHint hint(typeTranslator, astContext.IntTy);
  4875. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  4876. if (rawIndex)
  4877. return nullptr; // TODO: handle constant array index
  4878. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  4879. // cast. We need to ingore it to avoid creating OpLoad.
  4880. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  4881. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  4882. indices->push_back(doExpr(indexing->getIdx()));
  4883. return base;
  4884. }
  4885. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  4886. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  4887. if (rawIndex)
  4888. return nullptr; // TODO: handle constant array index
  4889. const Expr *thisBase =
  4890. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  4891. const auto thisBaseType = thisBase->getType();
  4892. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  4893. if (thisBaseType != base->getType() &&
  4894. TypeTranslator::isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  4895. // The immediate base is a kind of structured or byte buffer. It should
  4896. // be an alias variable. Break the normal index collecting chain.
  4897. // Return the immediate base as the base so that we can apply other
  4898. // hacks for legalization over it.
  4899. //
  4900. // Note: legalization specific code
  4901. indices->clear();
  4902. base = thisBase;
  4903. }
  4904. // If the base is a StructureType, we need to push an addtional index 0
  4905. // here. This is because we created an additional OpTypeRuntimeArray
  4906. // in the structure.
  4907. if (TypeTranslator::isStructuredBuffer(thisBaseType))
  4908. indices->push_back(theBuilder.getConstantInt32(0));
  4909. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  4910. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  4911. typeTranslator.is1x1Matrix(thisBaseType) ||
  4912. typeTranslator.is1xNMatrix(thisBaseType)) {
  4913. // If this is a size-1 vector or 1xN matrix, ignore the index.
  4914. } else {
  4915. indices->push_back(doExpr(indexing->getArg(1)));
  4916. }
  4917. return base;
  4918. }
  4919. {
  4920. const Expr *index = nullptr;
  4921. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  4922. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  4923. if (rawIndex)
  4924. return nullptr; // TODO: handle constant array index
  4925. // For object.Load(index), there should be no more indexing into the
  4926. // object.
  4927. indices->push_back(theBuilder.getConstantInt32(0));
  4928. indices->push_back(doExpr(index));
  4929. return object;
  4930. }
  4931. }
  4932. // This the deepest we can go. No more array or struct indexing.
  4933. return expr;
  4934. }
  4935. SpirvEvalInfo &SPIRVEmitter::turnIntoElementPtr(
  4936. SpirvEvalInfo &info, QualType elemType,
  4937. const llvm::SmallVector<uint32_t, 4> &indices) {
  4938. assert(!info.isRValue());
  4939. const uint32_t ptrType = theBuilder.getPointerType(
  4940. typeTranslator.translateType(elemType, info.getLayoutRule()),
  4941. info.getStorageClass());
  4942. return info.setResultId(theBuilder.createAccessChain(ptrType, info, indices));
  4943. }
  4944. uint32_t SPIRVEmitter::castToBool(const uint32_t fromVal, QualType fromType,
  4945. QualType toBoolType) {
  4946. if (TypeTranslator::isSameScalarOrVecType(fromType, toBoolType))
  4947. return fromVal;
  4948. const uint32_t boolType = typeTranslator.translateType(toBoolType);
  4949. { // Special case handling for converting to a matrix of booleans.
  4950. QualType elemType = {};
  4951. uint32_t rowCount = 0, colCount = 0;
  4952. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &rowCount,
  4953. &colCount)) {
  4954. const auto fromRowQualType =
  4955. astContext.getExtVectorType(elemType, colCount);
  4956. const auto fromRowQualTypeId =
  4957. typeTranslator.translateType(fromRowQualType);
  4958. const auto toBoolRowQualType =
  4959. astContext.getExtVectorType(astContext.BoolTy, colCount);
  4960. llvm::SmallVector<uint32_t, 4> rows;
  4961. for (uint32_t i = 0; i < rowCount; ++i) {
  4962. const auto row =
  4963. theBuilder.createCompositeExtract(fromRowQualTypeId, fromVal, {i});
  4964. rows.push_back(castToBool(row, fromRowQualType, toBoolRowQualType));
  4965. }
  4966. return theBuilder.createCompositeConstruct(boolType, rows);
  4967. }
  4968. }
  4969. // Converting to bool means comparing with value zero.
  4970. const spv::Op spvOp = translateOp(BO_NE, fromType);
  4971. const uint32_t zeroVal = getValueZero(fromType);
  4972. return theBuilder.createBinaryOp(spvOp, boolType, fromVal, zeroVal);
  4973. }
  4974. uint32_t SPIRVEmitter::castToInt(uint32_t fromVal, QualType fromType,
  4975. QualType toIntType, SourceLocation srcLoc) {
  4976. if (TypeTranslator::isSameScalarOrVecType(fromType, toIntType))
  4977. return fromVal;
  4978. uint32_t intType = typeTranslator.translateType(toIntType);
  4979. if (isBoolOrVecOfBoolType(fromType)) {
  4980. const uint32_t one = getValueOne(toIntType);
  4981. const uint32_t zero = getValueZero(toIntType);
  4982. return theBuilder.createSelect(intType, fromVal, one, zero);
  4983. }
  4984. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  4985. // First convert the source to the bitwidth of the destination if necessary.
  4986. uint32_t convertedType = 0;
  4987. fromVal = convertBitwidth(fromVal, fromType, toIntType, &convertedType);
  4988. // If bitwidth conversion was the only thing we needed to do, we're done.
  4989. if (convertedType == typeTranslator.translateType(toIntType))
  4990. return fromVal;
  4991. return theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, fromVal);
  4992. }
  4993. if (isFloatOrVecOfFloatType(fromType)) {
  4994. // First convert the source to the bitwidth of the destination if necessary.
  4995. fromVal = convertBitwidth(fromVal, fromType, toIntType);
  4996. if (isSintOrVecOfSintType(toIntType)) {
  4997. return theBuilder.createUnaryOp(spv::Op::OpConvertFToS, intType, fromVal);
  4998. } else if (isUintOrVecOfUintType(toIntType)) {
  4999. return theBuilder.createUnaryOp(spv::Op::OpConvertFToU, intType, fromVal);
  5000. } else {
  5001. emitError("casting from floating point to integer unimplemented", srcLoc);
  5002. }
  5003. }
  5004. {
  5005. QualType elemType = {};
  5006. uint32_t numRows = 0, numCols = 0;
  5007. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5008. // The source matrix and the target matrix must have the same dimensions.
  5009. QualType toElemType = {};
  5010. uint32_t toNumRows = 0, toNumCols = 0;
  5011. const bool isMat = TypeTranslator::isMxNMatrix(toIntType, &toElemType,
  5012. &toNumRows, &toNumCols);
  5013. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5014. (void)toNumRows;
  5015. (void)toNumCols;
  5016. // Casting to a matrix of integers: Cast each row and construct a
  5017. // composite.
  5018. llvm::SmallVector<uint32_t, 4> castedRows;
  5019. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5020. const auto fromVecQualType =
  5021. astContext.getExtVectorType(elemType, numCols);
  5022. const auto toIntVecQualType =
  5023. astContext.getExtVectorType(toElemType, numCols);
  5024. for (uint32_t row = 0; row < numRows; ++row) {
  5025. const auto rowId =
  5026. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5027. castedRows.push_back(
  5028. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5029. }
  5030. return theBuilder.createCompositeConstruct(intType, castedRows);
  5031. }
  5032. }
  5033. return 0;
  5034. }
  5035. uint32_t SPIRVEmitter::convertBitwidth(uint32_t fromVal, QualType fromType,
  5036. QualType toType, uint32_t *resultType) {
  5037. // At the moment, we will not make bitwidth conversions for literal int and
  5038. // literal float types because they always indicate 64-bit and do not
  5039. // represent what SPIR-V was actually resolved to.
  5040. // TODO: If the evaluated type is added to SpirvEvalInfo, change 'fromVal' to
  5041. // SpirvEvalInfo and use it to handle literal types more accurately.
  5042. if (fromType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  5043. fromType->isSpecificBuiltinType(BuiltinType::LitInt))
  5044. return fromVal;
  5045. const auto fromBitwidth = typeTranslator.getElementSpirvBitwidth(fromType);
  5046. const auto toBitwidth = typeTranslator.getElementSpirvBitwidth(toType);
  5047. if (fromBitwidth == toBitwidth) {
  5048. if (resultType)
  5049. *resultType = typeTranslator.translateType(fromType);
  5050. return fromVal;
  5051. }
  5052. // We want the 'fromType' with the 'toBitwidth'.
  5053. const uint32_t targetTypeId =
  5054. typeTranslator.getTypeWithCustomBitwidth(fromType, toBitwidth);
  5055. if (resultType)
  5056. *resultType = targetTypeId;
  5057. if (isFloatOrVecOfFloatType(fromType))
  5058. return theBuilder.createUnaryOp(spv::Op::OpFConvert, targetTypeId, fromVal);
  5059. if (isSintOrVecOfSintType(fromType))
  5060. return theBuilder.createUnaryOp(spv::Op::OpSConvert, targetTypeId, fromVal);
  5061. if (isUintOrVecOfUintType(fromType))
  5062. return theBuilder.createUnaryOp(spv::Op::OpUConvert, targetTypeId, fromVal);
  5063. llvm_unreachable("invalid type passed to convertBitwidth");
  5064. }
  5065. uint32_t SPIRVEmitter::castToFloat(uint32_t fromVal, QualType fromType,
  5066. QualType toFloatType,
  5067. SourceLocation srcLoc) {
  5068. if (TypeTranslator::isSameScalarOrVecType(fromType, toFloatType))
  5069. return fromVal;
  5070. const uint32_t floatType = typeTranslator.translateType(toFloatType);
  5071. if (isBoolOrVecOfBoolType(fromType)) {
  5072. const uint32_t one = getValueOne(toFloatType);
  5073. const uint32_t zero = getValueZero(toFloatType);
  5074. return theBuilder.createSelect(floatType, fromVal, one, zero);
  5075. }
  5076. if (isSintOrVecOfSintType(fromType)) {
  5077. // First convert the source to the bitwidth of the destination if necessary.
  5078. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5079. return theBuilder.createUnaryOp(spv::Op::OpConvertSToF, floatType, fromVal);
  5080. }
  5081. if (isUintOrVecOfUintType(fromType)) {
  5082. // First convert the source to the bitwidth of the destination if necessary.
  5083. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5084. return theBuilder.createUnaryOp(spv::Op::OpConvertUToF, floatType, fromVal);
  5085. }
  5086. if (isFloatOrVecOfFloatType(fromType)) {
  5087. // This is the case of float to float conversion with different bitwidths.
  5088. return convertBitwidth(fromVal, fromType, toFloatType);
  5089. }
  5090. // Casting matrix types
  5091. {
  5092. QualType elemType = {};
  5093. uint32_t numRows = 0, numCols = 0;
  5094. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5095. // The source matrix and the target matrix must have the same dimensions.
  5096. QualType toElemType = {};
  5097. uint32_t toNumRows = 0, toNumCols = 0;
  5098. const auto isMat = TypeTranslator::isMxNMatrix(toFloatType, &toElemType,
  5099. &toNumRows, &toNumCols);
  5100. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5101. (void)toNumRows;
  5102. (void)toNumCols;
  5103. // Casting to a matrix of floats: Cast each row and construct a
  5104. // composite.
  5105. llvm::SmallVector<uint32_t, 4> castedRows;
  5106. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5107. const auto fromVecQualType =
  5108. astContext.getExtVectorType(elemType, numCols);
  5109. const auto toIntVecQualType =
  5110. astContext.getExtVectorType(toElemType, numCols);
  5111. for (uint32_t row = 0; row < numRows; ++row) {
  5112. const auto rowId =
  5113. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5114. castedRows.push_back(
  5115. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5116. }
  5117. return theBuilder.createCompositeConstruct(floatType, castedRows);
  5118. }
  5119. }
  5120. emitError("casting to floating point unimplemented", srcLoc);
  5121. return 0;
  5122. }
  5123. SpirvEvalInfo SPIRVEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  5124. const FunctionDecl *callee = callExpr->getDirectCallee();
  5125. assert(hlsl::IsIntrinsicOp(callee) &&
  5126. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  5127. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  5128. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  5129. // Figure out which intrinsic function to translate.
  5130. llvm::StringRef group;
  5131. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  5132. hlsl::GetIntrinsicOp(callee, opcode, group);
  5133. GLSLstd450 glslOpcode = GLSLstd450Bad;
  5134. uint32_t retVal = 0;
  5135. #define INTRINSIC_SPIRV_OP_WITH_CAP_CASE(intrinsicOp, spirvOp, doEachVec, cap) \
  5136. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5137. theBuilder.requireCapability(cap); \
  5138. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5139. doEachVec); \
  5140. } break
  5141. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  5142. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5143. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5144. doEachVec); \
  5145. } break
  5146. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  5147. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5148. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  5149. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5150. } break
  5151. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  5152. doEachVec) \
  5153. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5154. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  5155. : GLSLstd450::GLSLstd450##glslIntOp; \
  5156. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5157. } break
  5158. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  5159. doEachVec) \
  5160. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5161. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5162. : GLSLstd450::GLSLstd450##glslUintOp; \
  5163. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5164. } break
  5165. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  5166. glslFloatOp, doEachVec) \
  5167. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5168. glslOpcode = isFloatType \
  5169. ? GLSLstd450::GLSLstd450##glslFloatOp \
  5170. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5171. : GLSLstd450::GLSLstd450##glslUintOp; \
  5172. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5173. } break
  5174. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  5175. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  5176. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  5177. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  5178. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  5179. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  5180. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  5181. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  5182. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  5183. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  5184. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  5185. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  5186. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  5187. break;
  5188. case hlsl::IntrinsicOp::IOP_tex1D:
  5189. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  5190. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  5191. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  5192. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  5193. case hlsl::IntrinsicOp::IOP_tex2D:
  5194. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  5195. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  5196. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  5197. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  5198. case hlsl::IntrinsicOp::IOP_tex3D:
  5199. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  5200. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  5201. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  5202. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  5203. case hlsl::IntrinsicOp::IOP_texCUBE:
  5204. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  5205. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  5206. case hlsl::IntrinsicOp::IOP_texCUBElod:
  5207. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  5208. emitError("deprecated %0 intrinsic function will not be supported",
  5209. callExpr->getExprLoc())
  5210. << callee->getName();
  5211. return 0;
  5212. }
  5213. case hlsl::IntrinsicOp::IOP_dot:
  5214. retVal = processIntrinsicDot(callExpr);
  5215. break;
  5216. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  5217. retVal = processIntrinsicMemoryBarrier(callExpr,
  5218. /*isDevice*/ false,
  5219. /*groupSync*/ false,
  5220. /*isAllBarrier*/ false);
  5221. break;
  5222. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  5223. retVal = processIntrinsicMemoryBarrier(callExpr,
  5224. /*isDevice*/ false,
  5225. /*groupSync*/ true,
  5226. /*isAllBarrier*/ false);
  5227. break;
  5228. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  5229. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5230. /*groupSync*/ false,
  5231. /*isAllBarrier*/ false);
  5232. break;
  5233. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  5234. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5235. /*groupSync*/ true,
  5236. /*isAllBarrier*/ false);
  5237. break;
  5238. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  5239. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5240. /*groupSync*/ false,
  5241. /*isAllBarrier*/ true);
  5242. break;
  5243. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  5244. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5245. /*groupSync*/ true,
  5246. /*isAllBarrier*/ true);
  5247. break;
  5248. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  5249. retVal =
  5250. theBuilder.createImageSparseTexelsResident(doExpr(callExpr->getArg(0)));
  5251. break;
  5252. case hlsl::IntrinsicOp::IOP_mul:
  5253. case hlsl::IntrinsicOp::IOP_umul:
  5254. retVal = processIntrinsicMul(callExpr);
  5255. break;
  5256. case hlsl::IntrinsicOp::IOP_all:
  5257. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  5258. break;
  5259. case hlsl::IntrinsicOp::IOP_any:
  5260. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  5261. break;
  5262. case hlsl::IntrinsicOp::IOP_asdouble:
  5263. case hlsl::IntrinsicOp::IOP_asfloat:
  5264. case hlsl::IntrinsicOp::IOP_asint:
  5265. case hlsl::IntrinsicOp::IOP_asuint:
  5266. retVal = processIntrinsicAsType(callExpr);
  5267. break;
  5268. case hlsl::IntrinsicOp::IOP_clip:
  5269. retVal = processIntrinsicClip(callExpr);
  5270. break;
  5271. case hlsl::IntrinsicOp::IOP_dst:
  5272. retVal = processIntrinsicDst(callExpr);
  5273. break;
  5274. case hlsl::IntrinsicOp::IOP_clamp:
  5275. case hlsl::IntrinsicOp::IOP_uclamp:
  5276. retVal = processIntrinsicClamp(callExpr);
  5277. break;
  5278. case hlsl::IntrinsicOp::IOP_frexp:
  5279. retVal = processIntrinsicFrexp(callExpr);
  5280. break;
  5281. case hlsl::IntrinsicOp::IOP_ldexp:
  5282. retVal = processIntrinsicLdexp(callExpr);
  5283. break;
  5284. case hlsl::IntrinsicOp::IOP_lit:
  5285. retVal = processIntrinsicLit(callExpr);
  5286. break;
  5287. case hlsl::IntrinsicOp::IOP_modf:
  5288. retVal = processIntrinsicModf(callExpr);
  5289. break;
  5290. case hlsl::IntrinsicOp::IOP_msad4:
  5291. retVal = processIntrinsicMsad4(callExpr);
  5292. break;
  5293. case hlsl::IntrinsicOp::IOP_sign: {
  5294. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  5295. retVal = processIntrinsicFloatSign(callExpr);
  5296. else
  5297. retVal =
  5298. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  5299. /*actPerRowForMatrices*/ true);
  5300. } break;
  5301. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  5302. retVal = processD3DCOLORtoUBYTE4(callExpr);
  5303. break;
  5304. case hlsl::IntrinsicOp::IOP_isfinite:
  5305. retVal = processIntrinsicIsFinite(callExpr);
  5306. break;
  5307. case hlsl::IntrinsicOp::IOP_sincos:
  5308. retVal = processIntrinsicSinCos(callExpr);
  5309. break;
  5310. case hlsl::IntrinsicOp::IOP_rcp:
  5311. retVal = processIntrinsicRcp(callExpr);
  5312. break;
  5313. case hlsl::IntrinsicOp::IOP_saturate:
  5314. retVal = processIntrinsicSaturate(callExpr);
  5315. break;
  5316. case hlsl::IntrinsicOp::IOP_log10:
  5317. retVal = processIntrinsicLog10(callExpr);
  5318. break;
  5319. case hlsl::IntrinsicOp::IOP_f16tof32:
  5320. retVal = processIntrinsicF16ToF32(callExpr);
  5321. break;
  5322. case hlsl::IntrinsicOp::IOP_f32tof16:
  5323. retVal = processIntrinsicF32ToF16(callExpr);
  5324. break;
  5325. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  5326. needsSpirv1p3 = true;
  5327. const uint32_t retType =
  5328. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5329. const uint32_t varId =
  5330. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize);
  5331. retVal = theBuilder.createLoad(retType, varId);
  5332. } break;
  5333. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  5334. needsSpirv1p3 = true;
  5335. const uint32_t retType =
  5336. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5337. const uint32_t varId =
  5338. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupLocalInvocationId);
  5339. retVal = theBuilder.createLoad(retType, varId);
  5340. } break;
  5341. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  5342. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  5343. break;
  5344. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  5345. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  5346. break;
  5347. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  5348. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  5349. break;
  5350. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  5351. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  5352. break;
  5353. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  5354. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  5355. break;
  5356. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  5357. retVal = processWaveReductionOrPrefix(
  5358. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5359. spv::GroupOperation::Reduce);
  5360. break;
  5361. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  5362. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  5363. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  5364. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  5365. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  5366. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  5367. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  5368. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  5369. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  5370. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  5371. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  5372. const auto retType = callExpr->getCallReturnType(astContext);
  5373. retVal = processWaveReductionOrPrefix(
  5374. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5375. spv::GroupOperation::Reduce);
  5376. } break;
  5377. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  5378. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  5379. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  5380. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  5381. const auto retType = callExpr->getCallReturnType(astContext);
  5382. retVal = processWaveReductionOrPrefix(
  5383. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5384. spv::GroupOperation::ExclusiveScan);
  5385. } break;
  5386. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  5387. retVal = processWaveReductionOrPrefix(
  5388. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5389. spv::GroupOperation::ExclusiveScan);
  5390. break;
  5391. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  5392. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  5393. retVal = processWaveBroadcast(callExpr);
  5394. break;
  5395. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  5396. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  5397. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  5398. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  5399. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  5400. break;
  5401. case hlsl::IntrinsicOp::IOP_abort:
  5402. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  5403. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  5404. emitError("no equivalent for %0 intrinsic function in Vulkan",
  5405. callExpr->getExprLoc())
  5406. << callee->getName();
  5407. return 0;
  5408. }
  5409. case hlsl::IntrinsicOp::IOP_transpose: {
  5410. const Expr *mat = callExpr->getArg(0);
  5411. const QualType matType = mat->getType();
  5412. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  5413. retVal =
  5414. processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose, false);
  5415. else
  5416. retVal = processNonFpMatrixTranspose(matType, doExpr(mat));
  5417. break;
  5418. }
  5419. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  5420. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_coarse, DPdxCoarse, false,
  5421. spv::Capability::DerivativeControl);
  5422. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_fine, DPdxFine, false,
  5423. spv::Capability::DerivativeControl);
  5424. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  5425. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_coarse, DPdyCoarse, false,
  5426. spv::Capability::DerivativeControl);
  5427. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_fine, DPdyFine, false,
  5428. spv::Capability::DerivativeControl);
  5429. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  5430. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  5431. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  5432. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  5433. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  5434. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  5435. INTRINSIC_OP_CASE(round, Round, true);
  5436. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  5437. INTRINSIC_OP_CASE(acos, Acos, true);
  5438. INTRINSIC_OP_CASE(asin, Asin, true);
  5439. INTRINSIC_OP_CASE(atan, Atan, true);
  5440. INTRINSIC_OP_CASE(atan2, Atan2, true);
  5441. INTRINSIC_OP_CASE(ceil, Ceil, true);
  5442. INTRINSIC_OP_CASE(cos, Cos, true);
  5443. INTRINSIC_OP_CASE(cosh, Cosh, true);
  5444. INTRINSIC_OP_CASE(cross, Cross, false);
  5445. INTRINSIC_OP_CASE(degrees, Degrees, true);
  5446. INTRINSIC_OP_CASE(distance, Distance, false);
  5447. INTRINSIC_OP_CASE(determinant, Determinant, false);
  5448. INTRINSIC_OP_CASE(exp, Exp, true);
  5449. INTRINSIC_OP_CASE(exp2, Exp2, true);
  5450. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  5451. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  5452. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  5453. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  5454. INTRINSIC_OP_CASE(floor, Floor, true);
  5455. INTRINSIC_OP_CASE(fma, Fma, true);
  5456. INTRINSIC_OP_CASE(frac, Fract, true);
  5457. INTRINSIC_OP_CASE(length, Length, false);
  5458. INTRINSIC_OP_CASE(lerp, FMix, true);
  5459. INTRINSIC_OP_CASE(log, Log, true);
  5460. INTRINSIC_OP_CASE(log2, Log2, true);
  5461. INTRINSIC_OP_CASE(mad, Fma, true);
  5462. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  5463. INTRINSIC_OP_CASE(umax, UMax, true);
  5464. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  5465. INTRINSIC_OP_CASE(umin, UMin, true);
  5466. INTRINSIC_OP_CASE(normalize, Normalize, false);
  5467. INTRINSIC_OP_CASE(pow, Pow, true);
  5468. INTRINSIC_OP_CASE(radians, Radians, true);
  5469. INTRINSIC_OP_CASE(reflect, Reflect, false);
  5470. INTRINSIC_OP_CASE(refract, Refract, false);
  5471. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  5472. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  5473. INTRINSIC_OP_CASE(step, Step, true);
  5474. INTRINSIC_OP_CASE(sin, Sin, true);
  5475. INTRINSIC_OP_CASE(sinh, Sinh, true);
  5476. INTRINSIC_OP_CASE(tan, Tan, true);
  5477. INTRINSIC_OP_CASE(tanh, Tanh, true);
  5478. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  5479. INTRINSIC_OP_CASE(trunc, Trunc, true);
  5480. default:
  5481. emitError("%0 intrinsic function unimplemented", callExpr->getExprLoc())
  5482. << callee->getName();
  5483. return 0;
  5484. }
  5485. #undef INTRINSIC_OP_CASE
  5486. #undef INTRINSIC_OP_CASE_INT_FLOAT
  5487. return SpirvEvalInfo(retVal).setRValue();
  5488. }
  5489. uint32_t
  5490. SPIRVEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  5491. hlsl::IntrinsicOp opcode) {
  5492. // The signature of intrinsic atomic methods are:
  5493. // void Interlocked*(in R dest, in T value);
  5494. // void Interlocked*(in R dest, in T value, out T original_value);
  5495. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  5496. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  5497. // parameter is not an unsigned integer, the frontend inserts an
  5498. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  5499. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  5500. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  5501. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  5502. // the following OpAtomicIAdd is invalid because the pointee type defined in
  5503. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  5504. // unsigned integer.
  5505. //
  5506. // %_ptr_Image_int = OpTypePointer Image %int
  5507. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  5508. // %2 = OpLoad %int %value
  5509. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  5510. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  5511. //
  5512. // In such cases, we bypass the forced IntegralCast.
  5513. // Moreover, the frontend does not add a cast AST node to cast uint to int
  5514. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  5515. const uint32_t zero = theBuilder.getConstantUint32(0);
  5516. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  5517. const auto *dest = expr->getArg(0);
  5518. const auto baseType = dest->getType();
  5519. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  5520. const auto doArg = [baseType, this](const CallExpr *callExpr,
  5521. uint32_t argIndex) {
  5522. const Expr *valueExpr = callExpr->getArg(argIndex);
  5523. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  5524. if (castExpr->getCastKind() == CK_IntegralCast &&
  5525. castExpr->getSubExpr()->getType() == baseType)
  5526. valueExpr = castExpr->getSubExpr();
  5527. uint32_t argId = doExpr(valueExpr);
  5528. if (valueExpr->getType() != baseType)
  5529. argId = castToInt(argId, valueExpr->getType(), baseType,
  5530. valueExpr->getExprLoc());
  5531. return argId;
  5532. };
  5533. const auto writeToOutputArg = [&baseType, dest, this](
  5534. uint32_t toWrite, const CallExpr *callExpr,
  5535. uint32_t outputArgIndex) {
  5536. const auto outputArg = callExpr->getArg(outputArgIndex);
  5537. const auto outputArgType = outputArg->getType();
  5538. if (baseType != outputArgType)
  5539. toWrite = castToInt(toWrite, baseType, outputArgType, dest->getExprLoc());
  5540. theBuilder.createStore(doExpr(outputArg), toWrite);
  5541. };
  5542. // If the argument is indexing into a texture/buffer, we need to create an
  5543. // OpImageTexelPointer instruction.
  5544. uint32_t ptr = 0;
  5545. if (const auto *callExpr = dyn_cast<CXXOperatorCallExpr>(dest)) {
  5546. const Expr *base = nullptr;
  5547. const Expr *index = nullptr;
  5548. if (isBufferTextureIndexing(callExpr, &base, &index)) {
  5549. const auto ptrType =
  5550. theBuilder.getPointerType(baseTypeId, spv::StorageClass::Image);
  5551. const auto baseId = doExpr(base);
  5552. const auto coordId = doExpr(index);
  5553. ptr = theBuilder.createImageTexelPointer(ptrType, baseId, coordId, zero);
  5554. }
  5555. }
  5556. if (!ptr)
  5557. ptr = doExpr(dest);
  5558. const bool isCompareExchange =
  5559. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  5560. const bool isCompareStore =
  5561. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  5562. if (isCompareExchange || isCompareStore) {
  5563. const uint32_t comparator = doArg(expr, 1);
  5564. const uint32_t valueId = doArg(expr, 2);
  5565. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  5566. baseTypeId, ptr, scope, zero, zero, valueId, comparator);
  5567. if (isCompareExchange)
  5568. writeToOutputArg(originalVal, expr, 3);
  5569. } else {
  5570. const uint32_t valueId = doArg(expr, 1);
  5571. // Since these atomic operations write through the provided pointer, the
  5572. // signed vs. unsigned opcode must be decided based on the pointee type
  5573. // of the first argument. However, the frontend decides the opcode based on
  5574. // the second argument (value). Therefore, the HLSL opcode provided by the
  5575. // frontend may be wrong. Therefore we need the following code to make sure
  5576. // we are using the correct SPIR-V opcode.
  5577. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  5578. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  5579. atomicOp = spv::Op::OpAtomicSMax;
  5580. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  5581. atomicOp = spv::Op::OpAtomicUMax;
  5582. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  5583. atomicOp = spv::Op::OpAtomicSMin;
  5584. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  5585. atomicOp = spv::Op::OpAtomicUMin;
  5586. const uint32_t originalVal = theBuilder.createAtomicOp(
  5587. atomicOp, baseTypeId, ptr, scope, zero, valueId);
  5588. if (expr->getNumArgs() > 2)
  5589. writeToOutputArg(originalVal, expr, 2);
  5590. }
  5591. return 0;
  5592. }
  5593. uint32_t SPIRVEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  5594. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  5595. "instructions due to lack of direct SPIR-V equivalent",
  5596. callExpr->getExprLoc());
  5597. // Compares a 4-byte reference value and an 8-byte source value and
  5598. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  5599. // of absolute differences of a different byte alignment between the
  5600. // reference value and the source value.
  5601. // If we have:
  5602. // uint v0; // reference
  5603. // uint2 v1; // source
  5604. // uint4 v2; // accum
  5605. // uint4 o0; // result of msad4
  5606. // uint4 r0, t0; // temporary values
  5607. //
  5608. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  5609. // to fxc:
  5610. // Step 1:
  5611. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  5612. // Step 2:
  5613. // [result], [ width ], [ offset ], [ insert ], [ base ]
  5614. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  5615. // mov t0.x, v1.x
  5616. // Step 3:
  5617. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  5618. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  5619. const auto boolType = theBuilder.getBoolType();
  5620. const auto intType = theBuilder.getInt32Type();
  5621. const auto uintType = theBuilder.getUint32Type();
  5622. const auto uint4Type = theBuilder.getVecType(uintType, 4);
  5623. const uint32_t reference = doExpr(callExpr->getArg(0));
  5624. const uint32_t source = doExpr(callExpr->getArg(1));
  5625. const uint32_t accum = doExpr(callExpr->getArg(2));
  5626. const auto uint0 = theBuilder.getConstantUint32(0);
  5627. const auto uint8 = theBuilder.getConstantUint32(8);
  5628. const auto uint16 = theBuilder.getConstantUint32(16);
  5629. const auto uint24 = theBuilder.getConstantUint32(24);
  5630. // Step 1.
  5631. const uint32_t v1x = theBuilder.createCompositeExtract(uintType, source, {0});
  5632. // r0.x = v1xS8 = v1.x shifted by 8 bits
  5633. uint32_t v1xS8 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5634. uintType, v1x, uint8);
  5635. // r0.y = v1xS16 = v1.x shifted by 16 bits
  5636. uint32_t v1xS16 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5637. uintType, v1x, uint16);
  5638. // r0.z = v1xS24 = v1.x shifted by 24 bits
  5639. uint32_t v1xS24 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5640. uintType, v1x, uint24);
  5641. // Step 2.
  5642. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  5643. const uint32_t v1y = theBuilder.createCompositeExtract(uintType, source, {1});
  5644. // Note that t0.x = v1.x, nothing we need to do for that.
  5645. const uint32_t t0y =
  5646. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  5647. /*offset*/ uint24,
  5648. /*width*/ uint8);
  5649. const uint32_t t0z =
  5650. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  5651. /*offset*/ uint16,
  5652. /*width*/ uint16);
  5653. const uint32_t t0w =
  5654. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  5655. /*offset*/ uint8,
  5656. /*width*/ uint24);
  5657. // Step 3. MSAD (Masked Sum of Absolute Differences)
  5658. // Now perform MSAD four times.
  5659. // Need to mimic this algorithm in SPIR-V!
  5660. //
  5661. // UINT msad( UINT ref, UINT src, UINT accum )
  5662. // {
  5663. // for (UINT i = 0; i < 4; i++)
  5664. // {
  5665. // BYTE refByte, srcByte, absDiff;
  5666. //
  5667. // refByte = (BYTE)(ref >> (i * 8));
  5668. // if (!refByte)
  5669. // {
  5670. // continue;
  5671. // }
  5672. //
  5673. // srcByte = (BYTE)(src >> (i * 8));
  5674. // if (refByte >= srcByte)
  5675. // {
  5676. // absDiff = refByte - srcByte;
  5677. // }
  5678. // else
  5679. // {
  5680. // absDiff = srcByte - refByte;
  5681. // }
  5682. //
  5683. // // The recommended overflow behavior for MSAD is
  5684. // // to do a 32-bit saturate. This is not
  5685. // // required, however, and wrapping is allowed.
  5686. // // So from an application point of view,
  5687. // // overflow behavior is undefined.
  5688. // if (UINT_MAX - accum < absDiff)
  5689. // {
  5690. // accum = UINT_MAX;
  5691. // break;
  5692. // }
  5693. // accum += absDiff;
  5694. // }
  5695. //
  5696. // return accum;
  5697. // }
  5698. llvm::SmallVector<uint32_t, 4> result;
  5699. const uint32_t accum0 =
  5700. theBuilder.createCompositeExtract(uintType, accum, {0});
  5701. const uint32_t accum1 =
  5702. theBuilder.createCompositeExtract(uintType, accum, {1});
  5703. const uint32_t accum2 =
  5704. theBuilder.createCompositeExtract(uintType, accum, {2});
  5705. const uint32_t accum3 =
  5706. theBuilder.createCompositeExtract(uintType, accum, {3});
  5707. const llvm::SmallVector<uint32_t, 4> sources = {v1x, t0y, t0z, t0w};
  5708. llvm::SmallVector<uint32_t, 4> accums = {accum0, accum1, accum2, accum3};
  5709. llvm::SmallVector<uint32_t, 4> refBytes;
  5710. llvm::SmallVector<uint32_t, 4> signedRefBytes;
  5711. llvm::SmallVector<uint32_t, 4> isRefByteZero;
  5712. for (uint32_t i = 0; i < 4; ++i) {
  5713. refBytes.push_back(theBuilder.createBitFieldExtract(
  5714. uintType, reference, /*offset*/ theBuilder.getConstantUint32(i * 8),
  5715. /*count*/ uint8, /*isSigned*/ false));
  5716. signedRefBytes.push_back(
  5717. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, refBytes.back()));
  5718. isRefByteZero.push_back(theBuilder.createBinaryOp(
  5719. spv::Op::OpIEqual, boolType, refBytes.back(), uint0));
  5720. }
  5721. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  5722. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  5723. // 'count' is always 8 because we are extracting 8 bits out of 32.
  5724. const uint32_t srcByte = theBuilder.createBitFieldExtract(
  5725. uintType, sources[msadNum],
  5726. /*offset*/ theBuilder.getConstantUint32(8 * byteCount),
  5727. /*count*/ uint8, /*isSigned*/ false);
  5728. const uint32_t signedSrcByte =
  5729. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte);
  5730. const uint32_t sub = theBuilder.createBinaryOp(
  5731. spv::Op::OpISub, intType, signedRefBytes[byteCount], signedSrcByte);
  5732. const uint32_t absSub = theBuilder.createExtInst(
  5733. intType, glsl, GLSLstd450::GLSLstd450SAbs, {sub});
  5734. const uint32_t diff = theBuilder.createSelect(
  5735. uintType, isRefByteZero[byteCount], uint0,
  5736. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub));
  5737. // As pointed out by the DXIL reference above, it is *not* required to
  5738. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  5739. // also allowed. For simplicity, we will wrap around at this point.
  5740. accums[msadNum] = theBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  5741. accums[msadNum], diff);
  5742. }
  5743. }
  5744. return theBuilder.createCompositeConstruct(uint4Type, accums);
  5745. }
  5746. uint32_t SPIRVEmitter::processWaveQuery(const CallExpr *callExpr,
  5747. spv::Op opcode) {
  5748. // Signatures:
  5749. // bool WaveIsFirstLane()
  5750. // uint WaveGetLaneCount()
  5751. // uint WaveGetLaneIndex()
  5752. assert(callExpr->getNumArgs() == 0);
  5753. needsSpirv1p3 = true;
  5754. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  5755. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  5756. const uint32_t retType =
  5757. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5758. return theBuilder.createGroupNonUniformOp(opcode, retType, subgroupScope);
  5759. }
  5760. uint32_t SPIRVEmitter::processWaveVote(const CallExpr *callExpr,
  5761. spv::Op opcode) {
  5762. // Signatures:
  5763. // bool WaveActiveAnyTrue( bool expr )
  5764. // bool WaveActiveAllTrue( bool expr )
  5765. // bool uint4 WaveActiveBallot( bool expr )
  5766. assert(callExpr->getNumArgs() == 1);
  5767. needsSpirv1p3 = true;
  5768. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  5769. const uint32_t predicate = doExpr(callExpr->getArg(0));
  5770. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  5771. const uint32_t retType =
  5772. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5773. return theBuilder.createGroupNonUniformUnaryOp(opcode, retType, subgroupScope,
  5774. predicate);
  5775. }
  5776. spv::Op SPIRVEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  5777. SourceLocation srcLoc) {
  5778. const bool isSintType = isSintOrVecMatOfSintType(type);
  5779. const bool isUintType = isUintOrVecMatOfUintType(type);
  5780. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  5781. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  5782. \
  5783. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  5784. if (isSintType || isUintType) { \
  5785. return spv::Op::OpGroupNonUniform##intWaveOp; \
  5786. } \
  5787. } break
  5788. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  5789. \
  5790. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  5791. if (isSintType || isUintType) { \
  5792. return spv::Op::OpGroupNonUniform##intWaveOp; \
  5793. } \
  5794. if (isFloatType) { \
  5795. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  5796. } \
  5797. } break
  5798. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  5799. floatWaveOp) \
  5800. \
  5801. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  5802. if (isSintType) { \
  5803. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  5804. } \
  5805. if (isUintType) { \
  5806. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  5807. } \
  5808. if (isFloatType) { \
  5809. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  5810. } \
  5811. } break
  5812. switch (op) {
  5813. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  5814. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  5815. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  5816. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  5817. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  5818. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  5819. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  5820. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  5821. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  5822. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  5823. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  5824. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  5825. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  5826. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  5827. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  5828. }
  5829. #undef WAVE_OP_CASE_INT_FLOAT
  5830. #undef WAVE_OP_CASE_INT
  5831. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  5832. emitError("translating wave operator '%0' unimplemented", srcLoc)
  5833. << static_cast<uint32_t>(op);
  5834. return spv::Op::OpNop;
  5835. }
  5836. uint32_t SPIRVEmitter::processWaveReductionOrPrefix(
  5837. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  5838. // Signatures:
  5839. // bool WaveActiveAllEqual( <type> expr )
  5840. // uint WaveActiveCountBits( bool bBit )
  5841. // <type> WaveActiveSum( <type> expr )
  5842. // <type> WaveActiveProduct( <type> expr )
  5843. // <int_type> WaveActiveBitAnd( <int_type> expr )
  5844. // <int_type> WaveActiveBitOr( <int_type> expr )
  5845. // <int_type> WaveActiveBitXor( <int_type> expr )
  5846. // <type> WaveActiveMin( <type> expr)
  5847. // <type> WaveActiveMax( <type> expr)
  5848. //
  5849. // uint WavePrefixCountBits(Bool bBit)
  5850. // <type> WavePrefixProduct(<type> value)
  5851. // <type> WavePrefixSum(<type> value)
  5852. assert(callExpr->getNumArgs() == 1);
  5853. needsSpirv1p3 = true;
  5854. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  5855. const uint32_t predicate = doExpr(callExpr->getArg(0));
  5856. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  5857. const uint32_t retType =
  5858. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5859. return theBuilder.createGroupNonUniformUnaryOp(
  5860. opcode, retType, subgroupScope, predicate,
  5861. llvm::Optional<spv::GroupOperation>(groupOp));
  5862. }
  5863. uint32_t SPIRVEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  5864. // Signatures:
  5865. // <type> WaveReadLaneFirst(<type> expr)
  5866. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  5867. const auto numArgs = callExpr->getNumArgs();
  5868. assert(numArgs == 1 || numArgs == 2);
  5869. needsSpirv1p3 = true;
  5870. theBuilder.requireCapability(spv::Capability::GroupNonUniformBallot);
  5871. const uint32_t value = doExpr(callExpr->getArg(0));
  5872. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  5873. const uint32_t retType =
  5874. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5875. if (numArgs == 2)
  5876. return theBuilder.createGroupNonUniformBinaryOp(
  5877. spv::Op::OpGroupNonUniformBroadcast, retType, subgroupScope, value,
  5878. doExpr(callExpr->getArg(1)));
  5879. else
  5880. return theBuilder.createGroupNonUniformUnaryOp(
  5881. spv::Op::OpGroupNonUniformBroadcastFirst, retType, subgroupScope,
  5882. value);
  5883. }
  5884. uint32_t SPIRVEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  5885. hlsl::IntrinsicOp op) {
  5886. // Signatures:
  5887. // <type> QuadReadAcrossX(<type> localValue)
  5888. // <type> QuadReadAcrossY(<type> localValue)
  5889. // <type> QuadReadAcrossDiagonal(<type> localValue)
  5890. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  5891. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  5892. needsSpirv1p3 = true;
  5893. theBuilder.requireCapability(spv::Capability::GroupNonUniformQuad);
  5894. const uint32_t value = doExpr(callExpr->getArg(0));
  5895. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  5896. const uint32_t retType =
  5897. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5898. uint32_t target = 0;
  5899. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  5900. switch (op) {
  5901. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  5902. target = theBuilder.getConstantUint32(0);
  5903. break;
  5904. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  5905. target = theBuilder.getConstantUint32(1);
  5906. break;
  5907. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  5908. target = theBuilder.getConstantUint32(2);
  5909. break;
  5910. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  5911. target = doExpr(callExpr->getArg(1));
  5912. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  5913. break;
  5914. default:
  5915. llvm_unreachable("case should not appear here");
  5916. }
  5917. return theBuilder.createGroupNonUniformBinaryOp(opcode, retType,
  5918. subgroupScope, value, target);
  5919. }
  5920. uint32_t SPIRVEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  5921. // Signature is: ret modf(x, ip)
  5922. // [in] x: the input floating-point value.
  5923. // [out] ip: the integer portion of x.
  5924. // [out] ret: the fractional portion of x.
  5925. // All of the above must be a scalar, vector, or matrix with the same
  5926. // component types. Component types can be float or int.
  5927. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  5928. // fractional part and the second member is the integer portion.
  5929. // ModfStruct {
  5930. // <scalar or vector of float> frac;
  5931. // <scalar or vector of float> ip;
  5932. // }
  5933. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  5934. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  5935. // argument is not treated the same way. Therefore, in such cases we'll have
  5936. // to manually convert the float result into int.
  5937. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  5938. const Expr *arg = callExpr->getArg(0);
  5939. const Expr *ipArg = callExpr->getArg(1);
  5940. const auto argType = arg->getType();
  5941. const auto ipType = ipArg->getType();
  5942. const auto returnType = callExpr->getType();
  5943. const auto returnTypeId = typeTranslator.translateType(returnType);
  5944. const auto ipTypeId = typeTranslator.translateType(ipType);
  5945. const uint32_t argId = doExpr(arg);
  5946. const uint32_t ipId = doExpr(ipArg);
  5947. // For scalar and vector argument types.
  5948. {
  5949. if (TypeTranslator::isScalarType(argType) ||
  5950. TypeTranslator::isVectorType(argType)) {
  5951. const auto argTypeId = typeTranslator.translateType(argType);
  5952. // The struct members *must* have the same type.
  5953. const auto modfStructTypeId = theBuilder.getStructType(
  5954. {argTypeId, argTypeId}, "ModfStructType", {"frac", "ip"});
  5955. const auto modf =
  5956. theBuilder.createExtInst(modfStructTypeId, glslInstSetId,
  5957. GLSLstd450::GLSLstd450ModfStruct, {argId});
  5958. auto ip = theBuilder.createCompositeExtract(argTypeId, modf, {1});
  5959. // This will do nothing if the input number (x) and the ip are both of the
  5960. // same type. Otherwise, it will convert the ip into int as necessary.
  5961. ip = castToInt(ip, argType, ipType, arg->getExprLoc());
  5962. theBuilder.createStore(ipId, ip);
  5963. return theBuilder.createCompositeExtract(argTypeId, modf, {0});
  5964. }
  5965. }
  5966. // For matrix argument types.
  5967. {
  5968. uint32_t rowCount = 0, colCount = 0;
  5969. QualType elemType = {};
  5970. if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  5971. const auto elemTypeId = typeTranslator.translateType(elemType);
  5972. const auto colTypeId = theBuilder.getVecType(elemTypeId, colCount);
  5973. const auto modfStructTypeId = theBuilder.getStructType(
  5974. {colTypeId, colTypeId}, "ModfStructType", {"frac", "ip"});
  5975. llvm::SmallVector<uint32_t, 4> fracs;
  5976. llvm::SmallVector<uint32_t, 4> ips;
  5977. for (uint32_t i = 0; i < rowCount; ++i) {
  5978. const auto curRow =
  5979. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  5980. const auto modf = theBuilder.createExtInst(
  5981. modfStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450ModfStruct,
  5982. {curRow});
  5983. auto ip = theBuilder.createCompositeExtract(colTypeId, modf, {1});
  5984. ips.push_back(ip);
  5985. fracs.push_back(
  5986. theBuilder.createCompositeExtract(colTypeId, modf, {0}));
  5987. }
  5988. uint32_t ip = theBuilder.createCompositeConstruct(
  5989. typeTranslator.translateType(argType), ips);
  5990. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  5991. // because this is internal to the intrinsic function. So, in such a
  5992. // case we need to cast manually.
  5993. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  5994. ip = castToInt(ip, argType, ipType, ipArg->getExprLoc());
  5995. theBuilder.createStore(ipId, ip);
  5996. return theBuilder.createCompositeConstruct(returnTypeId, fracs);
  5997. }
  5998. }
  5999. emitError("invalid argument type passed to Modf intrinsic function",
  6000. callExpr->getExprLoc());
  6001. return 0;
  6002. }
  6003. uint32_t SPIRVEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  6004. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  6005. //
  6006. // This function returns a lighting coefficient vector
  6007. // (ambient, diffuse, specular, 1) where:
  6008. // ambient = 1.
  6009. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  6010. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  6011. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6012. const uint32_t nDotL = doExpr(callExpr->getArg(0));
  6013. const uint32_t nDotH = doExpr(callExpr->getArg(1));
  6014. const uint32_t m = doExpr(callExpr->getArg(2));
  6015. const uint32_t floatType = theBuilder.getFloat32Type();
  6016. const uint32_t boolType = theBuilder.getBoolType();
  6017. const uint32_t floatZero = theBuilder.getConstantFloat32(0);
  6018. const uint32_t floatOne = theBuilder.getConstantFloat32(1);
  6019. const uint32_t retType = typeTranslator.translateType(callExpr->getType());
  6020. const uint32_t diffuse = theBuilder.createExtInst(
  6021. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL});
  6022. const uint32_t min = theBuilder.createExtInst(
  6023. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH});
  6024. const uint32_t isNeg = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6025. boolType, min, floatZero);
  6026. const uint32_t mul =
  6027. theBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m);
  6028. const uint32_t specular =
  6029. theBuilder.createSelect(floatType, isNeg, floatZero, mul);
  6030. return theBuilder.createCompositeConstruct(
  6031. retType, {floatOne, diffuse, specular, floatOne});
  6032. }
  6033. uint32_t SPIRVEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  6034. // Signature is: ret frexp(x, exp)
  6035. // [in] x: the input floating-point value.
  6036. // [out] exp: the calculated exponent.
  6037. // [out] ret: the calculated mantissa.
  6038. // All of the above must be a scalar, vector, or matrix of *float* type.
  6039. // The FrexpStruct SPIR-V instruction returns a struct. The first
  6040. // member is the significand (mantissa) and must be of the same type as the
  6041. // input parameter, and the second member is the exponent and must always be a
  6042. // scalar or vector of 32-bit *integer* type.
  6043. // FrexpStruct {
  6044. // <scalar or vector of int/float> mantissa;
  6045. // <scalar or vector of integers> exponent;
  6046. // }
  6047. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6048. const Expr *arg = callExpr->getArg(0);
  6049. const auto argType = arg->getType();
  6050. const auto intId = theBuilder.getInt32Type();
  6051. const auto returnTypeId = typeTranslator.translateType(callExpr->getType());
  6052. const uint32_t argId = doExpr(arg);
  6053. const uint32_t expId = doExpr(callExpr->getArg(1));
  6054. // For scalar and vector argument types.
  6055. {
  6056. uint32_t elemCount = 1;
  6057. if (TypeTranslator::isScalarType(argType) ||
  6058. TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6059. const auto argTypeId = typeTranslator.translateType(argType);
  6060. const auto expTypeId =
  6061. elemCount == 1 ? intId : theBuilder.getVecType(intId, elemCount);
  6062. const auto frexpStructTypeId = theBuilder.getStructType(
  6063. {argTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6064. const auto frexp =
  6065. theBuilder.createExtInst(frexpStructTypeId, glslInstSetId,
  6066. GLSLstd450::GLSLstd450FrexpStruct, {argId});
  6067. const auto exponentInt =
  6068. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6069. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6070. // expects a float, an conversion must take place before writing the
  6071. // results.
  6072. const auto exponentFloat = theBuilder.createUnaryOp(
  6073. spv::Op::OpConvertSToF, returnTypeId, exponentInt);
  6074. theBuilder.createStore(expId, exponentFloat);
  6075. return theBuilder.createCompositeExtract(argTypeId, frexp, {0});
  6076. }
  6077. }
  6078. // For matrix argument types.
  6079. {
  6080. uint32_t rowCount = 0, colCount = 0;
  6081. if (TypeTranslator::isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  6082. const auto floatId = theBuilder.getFloat32Type();
  6083. const auto expTypeId = theBuilder.getVecType(intId, colCount);
  6084. const auto colTypeId = theBuilder.getVecType(floatId, colCount);
  6085. const auto frexpStructTypeId = theBuilder.getStructType(
  6086. {colTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6087. llvm::SmallVector<uint32_t, 4> exponents;
  6088. llvm::SmallVector<uint32_t, 4> mantissas;
  6089. for (uint32_t i = 0; i < rowCount; ++i) {
  6090. const auto curRow =
  6091. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6092. const auto frexp = theBuilder.createExtInst(
  6093. frexpStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450FrexpStruct,
  6094. {curRow});
  6095. const auto exponentInt =
  6096. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6097. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6098. // expects a float, an conversion must take place before writing the
  6099. // results.
  6100. const auto exponentFloat = theBuilder.createUnaryOp(
  6101. spv::Op::OpConvertSToF, colTypeId, exponentInt);
  6102. exponents.push_back(exponentFloat);
  6103. mantissas.push_back(
  6104. theBuilder.createCompositeExtract(colTypeId, frexp, {0}));
  6105. }
  6106. const auto exponentsResultId =
  6107. theBuilder.createCompositeConstruct(returnTypeId, exponents);
  6108. theBuilder.createStore(expId, exponentsResultId);
  6109. return theBuilder.createCompositeConstruct(returnTypeId, mantissas);
  6110. }
  6111. }
  6112. emitError("invalid argument type passed to Frexp intrinsic function",
  6113. callExpr->getExprLoc());
  6114. return 0;
  6115. }
  6116. uint32_t SPIRVEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  6117. // Signature: ret ldexp(x, exp)
  6118. // This function uses the following formula: x * 2^exp.
  6119. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  6120. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  6121. // exponent. So we must calculate the result manually.
  6122. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6123. const Expr *x = callExpr->getArg(0);
  6124. const auto paramType = x->getType();
  6125. const uint32_t xId = doExpr(x);
  6126. const uint32_t expId = doExpr(callExpr->getArg(1));
  6127. // For scalar and vector argument types.
  6128. if (TypeTranslator::isScalarType(paramType) ||
  6129. TypeTranslator::isVectorType(paramType)) {
  6130. const auto paramTypeId = typeTranslator.translateType(paramType);
  6131. const auto twoExp = theBuilder.createExtInst(
  6132. paramTypeId, glsl, GLSLstd450::GLSLstd450Exp2, {expId});
  6133. return theBuilder.createBinaryOp(spv::Op::OpFMul, paramTypeId, xId, twoExp);
  6134. }
  6135. // For matrix argument types.
  6136. {
  6137. uint32_t rowCount = 0, colCount = 0;
  6138. if (TypeTranslator::isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  6139. const auto actOnEachVec = [this, glsl, expId](uint32_t index,
  6140. uint32_t vecType,
  6141. uint32_t xRowId) {
  6142. const auto expRowId =
  6143. theBuilder.createCompositeExtract(vecType, expId, {index});
  6144. const auto twoExp = theBuilder.createExtInst(
  6145. vecType, glsl, GLSLstd450::GLSLstd450Exp2, {expRowId});
  6146. return theBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowId,
  6147. twoExp);
  6148. };
  6149. return processEachVectorInMatrix(x, xId, actOnEachVec);
  6150. }
  6151. }
  6152. emitError("invalid argument type passed to ldexp intrinsic function",
  6153. callExpr->getExprLoc());
  6154. return 0;
  6155. }
  6156. uint32_t SPIRVEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  6157. // Signature is float4 dst(float4 src0, float4 src1)
  6158. // result.x = 1;
  6159. // result.y = src0.y * src1.y;
  6160. // result.z = src0.z;
  6161. // result.w = src1.w;
  6162. const auto floatId = theBuilder.getFloat32Type();
  6163. const auto arg0Id = doExpr(callExpr->getArg(0));
  6164. const auto arg1Id = doExpr(callExpr->getArg(1));
  6165. const auto arg0y = theBuilder.createCompositeExtract(floatId, arg0Id, {1});
  6166. const auto arg1y = theBuilder.createCompositeExtract(floatId, arg1Id, {1});
  6167. const auto arg0z = theBuilder.createCompositeExtract(floatId, arg0Id, {2});
  6168. const auto arg1w = theBuilder.createCompositeExtract(floatId, arg1Id, {3});
  6169. const auto arg0yMularg1y =
  6170. theBuilder.createBinaryOp(spv::Op::OpFMul, floatId, arg0y, arg1y);
  6171. return theBuilder.createCompositeConstruct(
  6172. typeTranslator.translateType(callExpr->getType()),
  6173. {theBuilder.getConstantFloat32(1.0), arg0yMularg1y, arg0z, arg1w});
  6174. }
  6175. uint32_t SPIRVEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  6176. // Discards the current pixel if the specified value is less than zero.
  6177. // TODO: If the argument can be const folded and evaluated, we could
  6178. // potentially avoid creating a branch. This would be a bit challenging for
  6179. // matrix/vector arguments.
  6180. assert(callExpr->getNumArgs() == 1u);
  6181. const Expr *arg = callExpr->getArg(0);
  6182. const auto argType = arg->getType();
  6183. const auto boolType = theBuilder.getBoolType();
  6184. uint32_t condition = 0;
  6185. // Could not determine the argument as a constant. We need to branch based on
  6186. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  6187. // element of the vector/matrix is less than zero.
  6188. const uint32_t argId = doExpr(arg);
  6189. QualType elemType = {};
  6190. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  6191. if (TypeTranslator::isScalarType(argType)) {
  6192. const auto zero = getValueZero(argType);
  6193. condition = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  6194. argId, zero);
  6195. } else if (TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6196. const auto zero = getValueZero(argType);
  6197. const auto boolVecType = theBuilder.getVecType(boolType, elemCount);
  6198. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6199. boolVecType, argId, zero);
  6200. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6201. } else if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount,
  6202. &colCount)) {
  6203. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6204. const uint32_t floatVecType = theBuilder.getVecType(elemTypeId, colCount);
  6205. const uint32_t elemZeroId = getValueZero(elemType);
  6206. llvm::SmallVector<uint32_t, 4> elements(size_t(colCount), elemZeroId);
  6207. const auto zero = theBuilder.getConstantComposite(floatVecType, elements);
  6208. llvm::SmallVector<uint32_t, 4> cmpResults;
  6209. for (uint32_t i = 0; i < rowCount; ++i) {
  6210. const uint32_t lhsVec =
  6211. theBuilder.createCompositeExtract(floatVecType, argId, {i});
  6212. const auto boolColType = theBuilder.getVecType(boolType, colCount);
  6213. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6214. boolColType, lhsVec, zero);
  6215. const auto any = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6216. cmpResults.push_back(any);
  6217. }
  6218. const auto boolRowType = theBuilder.getVecType(boolType, rowCount);
  6219. const auto results =
  6220. theBuilder.createCompositeConstruct(boolRowType, cmpResults);
  6221. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, results);
  6222. } else {
  6223. emitError("invalid argument type passed to clip intrinsic function",
  6224. callExpr->getExprLoc());
  6225. return 0;
  6226. }
  6227. // Then we need to emit the instruction for the conditional branch.
  6228. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  6229. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  6230. // Create the branch instruction. This will end the current basic block.
  6231. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  6232. theBuilder.addSuccessor(thenBB);
  6233. theBuilder.addSuccessor(mergeBB);
  6234. theBuilder.setMergeTarget(mergeBB);
  6235. // Handle the then branch
  6236. theBuilder.setInsertPoint(thenBB);
  6237. theBuilder.createKill();
  6238. theBuilder.addSuccessor(mergeBB);
  6239. // From now on, we'll emit instructions into the merge block.
  6240. theBuilder.setInsertPoint(mergeBB);
  6241. return 0;
  6242. }
  6243. uint32_t SPIRVEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  6244. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  6245. // one may be int, uint, or float.
  6246. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6247. const QualType returnType = callExpr->getType();
  6248. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6249. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  6250. if (isFloatOrVecMatOfFloatType(returnType))
  6251. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  6252. else if (isSintOrVecMatOfSintType(returnType))
  6253. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  6254. // Get the function parameters. Expect 3 parameters.
  6255. assert(callExpr->getNumArgs() == 3u);
  6256. const Expr *argX = callExpr->getArg(0);
  6257. const Expr *argMin = callExpr->getArg(1);
  6258. const Expr *argMax = callExpr->getArg(2);
  6259. const uint32_t argXId = doExpr(argX);
  6260. const uint32_t argMinId = doExpr(argMin);
  6261. const uint32_t argMaxId = doExpr(argMax);
  6262. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  6263. // the operation on each vector of the matrix.
  6264. if (TypeTranslator::isMxNMatrix(argX->getType())) {
  6265. const auto actOnEachVec = [this, glslInstSetId, glslOpcode, argMinId,
  6266. argMaxId](uint32_t index, uint32_t vecType,
  6267. uint32_t curRowId) {
  6268. const auto minRowId =
  6269. theBuilder.createCompositeExtract(vecType, argMinId, {index});
  6270. const auto maxRowId =
  6271. theBuilder.createCompositeExtract(vecType, argMaxId, {index});
  6272. return theBuilder.createExtInst(vecType, glslInstSetId, glslOpcode,
  6273. {curRowId, minRowId, maxRowId});
  6274. };
  6275. return processEachVectorInMatrix(argX, argXId, actOnEachVec);
  6276. }
  6277. return theBuilder.createExtInst(returnTypeId, glslInstSetId, glslOpcode,
  6278. {argXId, argMinId, argMaxId});
  6279. }
  6280. uint32_t SPIRVEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  6281. bool isDevice,
  6282. bool groupSync,
  6283. bool isAllBarrier) {
  6284. // * DeviceMemoryBarrier =
  6285. // OpMemoryBarrier (memScope=Device,
  6286. // sem=Image|Uniform|AcquireRelease)
  6287. //
  6288. // * DeviceMemoryBarrierWithGroupSync =
  6289. // OpControlBarrier(execScope = Workgroup,
  6290. // memScope=Device,
  6291. // sem=Image|Uniform|AcquireRelease)
  6292. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  6293. spv::MemorySemanticsMask::ImageMemory |
  6294. spv::MemorySemanticsMask::UniformMemory |
  6295. spv::MemorySemanticsMask::AcquireRelease;
  6296. // * GroupMemoryBarrier =
  6297. // OpMemoryBarrier (memScope=Workgroup,
  6298. // sem = Workgroup|AcquireRelease)
  6299. //
  6300. // * GroupMemoryBarrierWithGroupSync =
  6301. // OpControlBarrier (execScope = Workgroup,
  6302. // memScope = Workgroup,
  6303. // sem = Workgroup|AcquireRelease)
  6304. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  6305. spv::MemorySemanticsMask::WorkgroupMemory |
  6306. spv::MemorySemanticsMask::AcquireRelease;
  6307. // * AllMemoryBarrier =
  6308. // OpMemoryBarrier(memScope = Device,
  6309. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6310. //
  6311. // * AllMemoryBarrierWithGroupSync =
  6312. // OpControlBarrier(execScope = Workgroup,
  6313. // memScope = Device,
  6314. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6315. const spv::MemorySemanticsMask allMemoryBarrierSema =
  6316. spv::MemorySemanticsMask::ImageMemory |
  6317. spv::MemorySemanticsMask::UniformMemory |
  6318. spv::MemorySemanticsMask::WorkgroupMemory |
  6319. spv::MemorySemanticsMask::AtomicCounterMemory |
  6320. spv::MemorySemanticsMask::AcquireRelease;
  6321. // Get <result-id> for execution scope.
  6322. // If present, execution scope is always Workgroup!
  6323. const uint32_t execScopeId =
  6324. groupSync ? theBuilder.getConstantUint32(
  6325. static_cast<uint32_t>(spv::Scope::Workgroup))
  6326. : 0;
  6327. // Get <result-id> for memory scope
  6328. const spv::Scope memScope =
  6329. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  6330. const uint32_t memScopeId =
  6331. theBuilder.getConstantUint32(static_cast<uint32_t>(memScope));
  6332. // Get <result-id> for memory semantics
  6333. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  6334. : isDevice ? deviceMemoryBarrierSema
  6335. : groupMemoryBarrierSema;
  6336. const uint32_t memSema =
  6337. theBuilder.getConstantUint32(static_cast<uint32_t>(memSemaMask));
  6338. theBuilder.createBarrier(execScopeId, memScopeId, memSema);
  6339. return 0;
  6340. }
  6341. uint32_t SPIRVEmitter::processNonFpMatrixTranspose(QualType matType,
  6342. uint32_t matId) {
  6343. // Simplest way is to flatten the matrix construct a new matrix from the
  6344. // flattened elements. (for a mat4x4).
  6345. QualType elemType = {};
  6346. uint32_t numRows = 0, numCols = 0;
  6347. const bool isMat =
  6348. TypeTranslator::isMxNMatrix(matType, &elemType, &numRows, &numCols);
  6349. assert(isMat && !elemType->isFloatingType());
  6350. const auto rowQualType = astContext.getExtVectorType(elemType, numCols);
  6351. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  6352. const uint32_t rowTypeId = typeTranslator.translateType(rowQualType);
  6353. const uint32_t colTypeId = typeTranslator.translateType(colQualType);
  6354. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6355. // You cannot perform a composite construct of an array using a few vectors.
  6356. // The number of constutients passed to OpCompositeConstruct must be equal to
  6357. // the number of array elements.
  6358. llvm::SmallVector<uint32_t, 4> elems;
  6359. for (uint32_t i = 0; i < numRows; ++i)
  6360. for (uint32_t j = 0; j < numCols; ++j)
  6361. elems.push_back(
  6362. theBuilder.createCompositeExtract(elemTypeId, matId, {i, j}));
  6363. llvm::SmallVector<uint32_t, 4> cols;
  6364. for (uint32_t i = 0; i < numCols; ++i) {
  6365. // The elements in the ith vector of the "transposed" array are at offset i,
  6366. // i + <original-vector-size>, ...
  6367. llvm::SmallVector<uint32_t, 4> indexes;
  6368. for (uint32_t j = 0; j < numRows; ++j)
  6369. indexes.push_back(elems[i + (j * numCols)]);
  6370. cols.push_back(theBuilder.createCompositeConstruct(colTypeId, indexes));
  6371. }
  6372. const auto transposeTypeId =
  6373. theBuilder.getArrayType(colTypeId, theBuilder.getConstantUint32(numCols));
  6374. return theBuilder.createCompositeConstruct(transposeTypeId, cols);
  6375. }
  6376. uint32_t SPIRVEmitter::processNonFpDot(uint32_t vec1Id, uint32_t vec2Id,
  6377. uint32_t vecSize, QualType elemType) {
  6378. const auto elemTypeId = typeTranslator.translateType(elemType);
  6379. llvm::SmallVector<uint32_t, 4> muls;
  6380. for (uint32_t i = 0; i < vecSize; ++i) {
  6381. const auto elem1 =
  6382. theBuilder.createCompositeExtract(elemTypeId, vec1Id, {i});
  6383. const auto elem2 =
  6384. theBuilder.createCompositeExtract(elemTypeId, vec2Id, {i});
  6385. muls.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  6386. elemTypeId, elem1, elem2));
  6387. }
  6388. uint32_t sum = muls[0];
  6389. for (uint32_t i = 1; i < vecSize; ++i) {
  6390. sum = theBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemTypeId,
  6391. sum, muls[i]);
  6392. }
  6393. return sum;
  6394. }
  6395. uint32_t SPIRVEmitter::processNonFpScalarTimesMatrix(QualType scalarType,
  6396. uint32_t scalarId,
  6397. QualType matrixType,
  6398. uint32_t matrixId) {
  6399. assert(TypeTranslator::isScalarType(scalarType));
  6400. QualType elemType = {};
  6401. uint32_t numRows = 0, numCols = 0;
  6402. const bool isMat =
  6403. TypeTranslator::isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  6404. assert(isMat);
  6405. assert(typeTranslator.isSameType(scalarType, elemType));
  6406. // We need to multiply the scalar by each vector of the matrix.
  6407. // The front-end guarantees that the scalar and matrix element type are
  6408. // the same. For example, if the scalar is a float, the matrix is casted
  6409. // to a float matrix before being passed to mul(). It is also guaranteed
  6410. // that types such as bool are casted to float or int before being
  6411. // passed to mul().
  6412. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  6413. const auto rowTypeId = typeTranslator.translateType(rowType);
  6414. llvm::SmallVector<uint32_t, 4> splat(size_t(numCols), scalarId);
  6415. const auto scalarSplat =
  6416. theBuilder.createCompositeConstruct(rowTypeId, splat);
  6417. llvm::SmallVector<uint32_t, 4> mulRows;
  6418. for (uint32_t row = 0; row < numRows; ++row) {
  6419. const auto rowId =
  6420. theBuilder.createCompositeExtract(rowTypeId, matrixId, {row});
  6421. mulRows.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, scalarType),
  6422. rowTypeId, rowId, scalarSplat));
  6423. }
  6424. return theBuilder.createCompositeConstruct(
  6425. typeTranslator.translateType(matrixType), mulRows);
  6426. }
  6427. uint32_t SPIRVEmitter::processNonFpVectorTimesMatrix(QualType vecType,
  6428. uint32_t vecId,
  6429. QualType matType,
  6430. uint32_t matId,
  6431. uint32_t matTransposeId) {
  6432. // This function assumes that the vector element type and matrix elemet type
  6433. // are the same.
  6434. QualType vecElemType = {}, matElemType = {};
  6435. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6436. const bool isVec =
  6437. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6438. const bool isMat =
  6439. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6440. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6441. assert(isVec);
  6442. assert(isMat);
  6443. assert(vecSize == numRows);
  6444. // When processing vector times matrix, the vector is a row vector, and it
  6445. // should be multiplied by the matrix *columns*. The most efficient way to
  6446. // handle this in SPIR-V would be to first transpose the matrix, and then use
  6447. // OpAccessChain.
  6448. if (!matTransposeId)
  6449. matTransposeId = processNonFpMatrixTranspose(matType, matId);
  6450. const auto vecTypeId = typeTranslator.translateType(vecType);
  6451. llvm::SmallVector<uint32_t, 4> resultElems;
  6452. for (uint32_t col = 0; col < numCols; ++col) {
  6453. const auto colId =
  6454. theBuilder.createCompositeExtract(vecTypeId, matTransposeId, {col});
  6455. resultElems.push_back(processNonFpDot(vecId, colId, vecSize, vecElemType));
  6456. }
  6457. return theBuilder.createCompositeConstruct(
  6458. typeTranslator.translateType(
  6459. astContext.getExtVectorType(vecElemType, numCols)),
  6460. resultElems);
  6461. }
  6462. uint32_t SPIRVEmitter::processNonFpMatrixTimesVector(QualType matType,
  6463. uint32_t matId,
  6464. QualType vecType,
  6465. uint32_t vecId) {
  6466. // This function assumes that the vector element type and matrix elemet type
  6467. // are the same.
  6468. QualType vecElemType = {}, matElemType = {};
  6469. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6470. const bool isVec =
  6471. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6472. const bool isMat =
  6473. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6474. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6475. assert(isVec);
  6476. assert(isMat);
  6477. assert(vecSize == numCols);
  6478. // When processing matrix times vector, the vector is a column vector. So we
  6479. // simply get each row of the matrix and perform a dot product with the
  6480. // vector.
  6481. const auto vecTypeId = typeTranslator.translateType(vecType);
  6482. llvm::SmallVector<uint32_t, 4> resultElems;
  6483. for (uint32_t row = 0; row < numRows; ++row) {
  6484. const auto rowId =
  6485. theBuilder.createCompositeExtract(vecTypeId, matId, {row});
  6486. resultElems.push_back(processNonFpDot(rowId, vecId, vecSize, vecElemType));
  6487. }
  6488. return theBuilder.createCompositeConstruct(
  6489. typeTranslator.translateType(
  6490. astContext.getExtVectorType(vecElemType, numRows)),
  6491. resultElems);
  6492. }
  6493. uint32_t SPIRVEmitter::processNonFpMatrixTimesMatrix(QualType lhsType,
  6494. uint32_t lhsId,
  6495. QualType rhsType,
  6496. uint32_t rhsId) {
  6497. // This function assumes that the vector element type and matrix elemet type
  6498. // are the same.
  6499. QualType lhsElemType = {}, rhsElemType = {};
  6500. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  6501. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  6502. const bool lhsIsMat = TypeTranslator::isMxNMatrix(lhsType, &lhsElemType,
  6503. &lhsNumRows, &lhsNumCols);
  6504. const bool rhsIsMat = TypeTranslator::isMxNMatrix(rhsType, &rhsElemType,
  6505. &rhsNumRows, &rhsNumCols);
  6506. assert(typeTranslator.isSameType(lhsElemType, rhsElemType));
  6507. assert(lhsIsMat && rhsIsMat);
  6508. assert(lhsNumCols == rhsNumRows);
  6509. const uint32_t rhsTranspose = processNonFpMatrixTranspose(rhsType, rhsId);
  6510. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  6511. const auto vecTypeId = typeTranslator.translateType(vecType);
  6512. llvm::SmallVector<uint32_t, 4> resultRows;
  6513. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  6514. const auto rowId =
  6515. theBuilder.createCompositeExtract(vecTypeId, lhsId, {row});
  6516. resultRows.push_back(processNonFpVectorTimesMatrix(vecType, rowId, rhsType,
  6517. rhsId, rhsTranspose));
  6518. }
  6519. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  6520. const auto elemTypeId = typeTranslator.translateType(lhsElemType);
  6521. const auto resultNumRows = theBuilder.getConstantUint32(lhsNumRows);
  6522. const auto resultColType = theBuilder.getVecType(elemTypeId, rhsNumCols);
  6523. const auto resultType = theBuilder.getArrayType(resultColType, resultNumRows);
  6524. return theBuilder.createCompositeConstruct(resultType, resultRows);
  6525. }
  6526. uint32_t SPIRVEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  6527. const QualType returnType = callExpr->getType();
  6528. const uint32_t returnTypeId =
  6529. typeTranslator.translateType(callExpr->getType());
  6530. // Get the function parameters. Expect 2 parameters.
  6531. assert(callExpr->getNumArgs() == 2u);
  6532. const Expr *arg0 = callExpr->getArg(0);
  6533. const Expr *arg1 = callExpr->getArg(1);
  6534. const QualType arg0Type = arg0->getType();
  6535. const QualType arg1Type = arg1->getType();
  6536. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  6537. // vector, or matrix. The frontend ensures that the two arguments have the
  6538. // same component type. The only allowed component types are int and float.
  6539. // mul(scalar, vector)
  6540. {
  6541. uint32_t elemCount = 0;
  6542. if (TypeTranslator::isScalarType(arg0Type) &&
  6543. TypeTranslator::isVectorType(arg1Type, nullptr, &elemCount)) {
  6544. const uint32_t arg1Id = doExpr(arg1);
  6545. // We can use OpVectorTimesScalar if arguments are floats.
  6546. if (arg0Type->isFloatingType())
  6547. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  6548. returnTypeId, arg1Id, doExpr(arg0));
  6549. // Use OpIMul for integers
  6550. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId,
  6551. createVectorSplat(arg0, elemCount),
  6552. arg1Id);
  6553. }
  6554. }
  6555. // mul(vector, scalar)
  6556. {
  6557. uint32_t elemCount = 0;
  6558. if (TypeTranslator::isVectorType(arg0Type, nullptr, &elemCount) &&
  6559. TypeTranslator::isScalarType(arg1Type)) {
  6560. const uint32_t arg0Id = doExpr(arg0);
  6561. // We can use OpVectorTimesScalar if arguments are floats.
  6562. if (arg1Type->isFloatingType())
  6563. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  6564. returnTypeId, arg0Id, doExpr(arg1));
  6565. // Use OpIMul for integers
  6566. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId, arg0Id,
  6567. createVectorSplat(arg1, elemCount));
  6568. }
  6569. }
  6570. // mul(vector, vector)
  6571. if (TypeTranslator::isVectorType(arg0Type) &&
  6572. TypeTranslator::isVectorType(arg1Type))
  6573. return processIntrinsicDot(callExpr);
  6574. // All the following cases require handling arg0 and arg1 expressions first.
  6575. const uint32_t arg0Id = doExpr(arg0);
  6576. const uint32_t arg1Id = doExpr(arg1);
  6577. // mul(scalar, scalar)
  6578. if (TypeTranslator::isScalarType(arg0Type) &&
  6579. TypeTranslator::isScalarType(arg1Type))
  6580. return theBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type),
  6581. returnTypeId, arg0Id, arg1Id);
  6582. // mul(scalar, matrix)
  6583. {
  6584. QualType elemType = {};
  6585. if (TypeTranslator::isScalarType(arg0Type) &&
  6586. TypeTranslator::isMxNMatrix(arg1Type, &elemType)) {
  6587. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  6588. // and the scalar type are float.
  6589. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  6590. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  6591. returnTypeId, arg1Id, arg0Id);
  6592. else
  6593. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type,
  6594. arg1Id);
  6595. }
  6596. }
  6597. // mul(matrix, scalar)
  6598. {
  6599. QualType elemType = {};
  6600. if (TypeTranslator::isScalarType(arg1Type) &&
  6601. TypeTranslator::isMxNMatrix(arg0Type, &elemType)) {
  6602. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  6603. // and the scalar type are float.
  6604. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  6605. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  6606. returnTypeId, arg0Id, arg1Id);
  6607. else
  6608. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type,
  6609. arg0Id);
  6610. }
  6611. }
  6612. // mul(vector, matrix)
  6613. {
  6614. QualType vecElemType = {}, matElemType = {};
  6615. uint32_t elemCount = 0, numRows = 0;
  6616. if (TypeTranslator::isVectorType(arg0Type, &vecElemType, &elemCount) &&
  6617. TypeTranslator::isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  6618. assert(elemCount == numRows);
  6619. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  6620. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  6621. returnTypeId, arg1Id, arg0Id);
  6622. else
  6623. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type,
  6624. arg1Id);
  6625. }
  6626. }
  6627. // mul(matrix, vector)
  6628. {
  6629. QualType vecElemType = {}, matElemType = {};
  6630. uint32_t elemCount = 0, numCols = 0;
  6631. if (TypeTranslator::isMxNMatrix(arg0Type, &matElemType, nullptr,
  6632. &numCols) &&
  6633. TypeTranslator::isVectorType(arg1Type, &vecElemType, &elemCount)) {
  6634. assert(elemCount == numCols);
  6635. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  6636. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  6637. returnTypeId, arg1Id, arg0Id);
  6638. else
  6639. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type,
  6640. arg1Id);
  6641. }
  6642. }
  6643. // mul(matrix, matrix)
  6644. {
  6645. // The front-end ensures that the two matrix element types match.
  6646. QualType elemType = {};
  6647. uint32_t lhsCols = 0, rhsRows = 0;
  6648. if (TypeTranslator::isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  6649. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  6650. assert(lhsCols == rhsRows);
  6651. if (elemType->isFloatingType())
  6652. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  6653. returnTypeId, arg1Id, arg0Id);
  6654. else
  6655. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type,
  6656. arg1Id);
  6657. }
  6658. }
  6659. emitError("invalid argument type passed to mul intrinsic function",
  6660. callExpr->getExprLoc());
  6661. return 0;
  6662. }
  6663. uint32_t SPIRVEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  6664. const QualType returnType = callExpr->getType();
  6665. const uint32_t returnTypeId =
  6666. typeTranslator.translateType(callExpr->getType());
  6667. // Get the function parameters. Expect 2 vectors as parameters.
  6668. assert(callExpr->getNumArgs() == 2u);
  6669. const Expr *arg0 = callExpr->getArg(0);
  6670. const Expr *arg1 = callExpr->getArg(1);
  6671. const uint32_t arg0Id = doExpr(arg0);
  6672. const uint32_t arg1Id = doExpr(arg1);
  6673. QualType arg0Type = arg0->getType();
  6674. QualType arg1Type = arg1->getType();
  6675. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  6676. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  6677. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  6678. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  6679. assert(returnType == vec1ComponentType);
  6680. assert(vec0ComponentType == vec1ComponentType);
  6681. assert(vec0Size == vec1Size);
  6682. assert(vec0Size >= 1 && vec0Size <= 4);
  6683. // According to HLSL reference, the dot function only works on integers
  6684. // and floats.
  6685. assert(returnType->isFloatingType() || returnType->isIntegerType());
  6686. // Special case: dot product of two vectors, each of size 1. That is
  6687. // basically the same as regular multiplication of 2 scalars.
  6688. if (vec0Size == 1) {
  6689. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  6690. return theBuilder.createBinaryOp(spvOp, returnTypeId, arg0Id, arg1Id);
  6691. }
  6692. // If the vectors are of type Float, we can use OpDot.
  6693. if (returnType->isFloatingType()) {
  6694. return theBuilder.createBinaryOp(spv::Op::OpDot, returnTypeId, arg0Id,
  6695. arg1Id);
  6696. }
  6697. // Vector component type is Integer (signed or unsigned).
  6698. // Create all instructions necessary to perform a dot product on
  6699. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  6700. // Therefore, we use other SPIR-V instructions (addition and
  6701. // multiplication).
  6702. else {
  6703. uint32_t result = 0;
  6704. llvm::SmallVector<uint32_t, 4> multIds;
  6705. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  6706. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  6707. // Extract members from the two vectors and multiply them.
  6708. for (unsigned int i = 0; i < vec0Size; ++i) {
  6709. const uint32_t vec0member =
  6710. theBuilder.createCompositeExtract(returnTypeId, arg0Id, {i});
  6711. const uint32_t vec1member =
  6712. theBuilder.createCompositeExtract(returnTypeId, arg1Id, {i});
  6713. const uint32_t multId = theBuilder.createBinaryOp(multSpvOp, returnTypeId,
  6714. vec0member, vec1member);
  6715. multIds.push_back(multId);
  6716. }
  6717. // Add all the multiplications.
  6718. result = multIds[0];
  6719. for (unsigned int i = 1; i < vec0Size; ++i) {
  6720. const uint32_t additionId =
  6721. theBuilder.createBinaryOp(addSpvOp, returnTypeId, result, multIds[i]);
  6722. result = additionId;
  6723. }
  6724. return result;
  6725. }
  6726. }
  6727. uint32_t SPIRVEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  6728. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  6729. // float or double.
  6730. assert(callExpr->getNumArgs() == 1u);
  6731. const QualType returnType = callExpr->getType();
  6732. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6733. const Expr *arg = callExpr->getArg(0);
  6734. const uint32_t argId = doExpr(arg);
  6735. const QualType argType = arg->getType();
  6736. // For cases with matrix argument.
  6737. QualType elemType = {};
  6738. uint32_t numRows = 0, numCols = 0;
  6739. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  6740. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  6741. const auto actOnEachVec = [this, vecOne](uint32_t /*index*/,
  6742. uint32_t vecType,
  6743. uint32_t curRowId) {
  6744. return theBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne,
  6745. curRowId);
  6746. };
  6747. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  6748. }
  6749. // For cases with scalar or vector arguments.
  6750. return theBuilder.createBinaryOp(spv::Op::OpFDiv, returnTypeId,
  6751. getValueOne(argType), argId);
  6752. }
  6753. uint32_t SPIRVEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  6754. spv::Op spvOp) {
  6755. // 'all' and 'any' take only 1 parameter.
  6756. assert(callExpr->getNumArgs() == 1u);
  6757. const QualType returnType = callExpr->getType();
  6758. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6759. const Expr *arg = callExpr->getArg(0);
  6760. const QualType argType = arg->getType();
  6761. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  6762. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  6763. {
  6764. QualType scalarType = {};
  6765. if (TypeTranslator::isScalarType(argType, &scalarType) &&
  6766. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  6767. scalarType->isIntegerType()))
  6768. return castToBool(doExpr(arg), argType, returnType);
  6769. }
  6770. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  6771. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  6772. {
  6773. QualType elemType = {};
  6774. uint32_t size = 0;
  6775. if (TypeTranslator::isVectorType(argType, &elemType, &size)) {
  6776. const QualType castToBoolType =
  6777. astContext.getExtVectorType(returnType, size);
  6778. uint32_t castedToBoolId =
  6779. castToBool(doExpr(arg), argType, castToBoolType);
  6780. return theBuilder.createUnaryOp(spvOp, returnTypeId, castedToBoolId);
  6781. }
  6782. }
  6783. // Handle MxN matrices as arguments.
  6784. {
  6785. QualType elemType = {};
  6786. uint32_t matRowCount = 0, matColCount = 0;
  6787. if (TypeTranslator::isMxNMatrix(argType, &elemType, &matRowCount,
  6788. &matColCount)) {
  6789. uint32_t matrixId = doExpr(arg);
  6790. const uint32_t vecType = typeTranslator.getComponentVectorType(argType);
  6791. llvm::SmallVector<uint32_t, 4> rowResults;
  6792. for (uint32_t i = 0; i < matRowCount; ++i) {
  6793. // Extract the row which is a float vector of size matColCount.
  6794. const uint32_t rowFloatVec =
  6795. theBuilder.createCompositeExtract(vecType, matrixId, {i});
  6796. // Cast the float vector to boolean vector.
  6797. const auto rowFloatQualType =
  6798. astContext.getExtVectorType(elemType, matColCount);
  6799. const auto rowBoolQualType =
  6800. astContext.getExtVectorType(returnType, matColCount);
  6801. const uint32_t rowBoolVec =
  6802. castToBool(rowFloatVec, rowFloatQualType, rowBoolQualType);
  6803. // Perform OpAny/OpAll on the boolean vector.
  6804. rowResults.push_back(
  6805. theBuilder.createUnaryOp(spvOp, returnTypeId, rowBoolVec));
  6806. }
  6807. // Create a new vector that is the concatenation of results of all rows.
  6808. uint32_t boolId = theBuilder.getBoolType();
  6809. uint32_t vecOfBoolsId = theBuilder.getVecType(boolId, matRowCount);
  6810. const uint32_t rowResultsId =
  6811. theBuilder.createCompositeConstruct(vecOfBoolsId, rowResults);
  6812. // Run OpAny/OpAll on the newly-created vector.
  6813. return theBuilder.createUnaryOp(spvOp, returnTypeId, rowResultsId);
  6814. }
  6815. }
  6816. // All types should be handled already.
  6817. llvm_unreachable("Unknown argument type passed to all()/any().");
  6818. return 0;
  6819. }
  6820. uint32_t SPIRVEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  6821. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  6822. // Method 1: ret asint(arg)
  6823. // arg component type = {float, uint}
  6824. // arg template type = {scalar, vector, matrix}
  6825. // ret template type = same as arg template type.
  6826. // ret component type = int
  6827. // Method 2: ret asuint(arg)
  6828. // arg component type = {float, int}
  6829. // arg template type = {scalar, vector, matrix}
  6830. // ret template type = same as arg template type.
  6831. // ret component type = uint
  6832. // Method 3: ret asfloat(arg)
  6833. // arg component type = {float, uint, int}
  6834. // arg template type = {scalar, vector, matrix}
  6835. // ret template type = same as arg template type.
  6836. // ret component type = float
  6837. // Method 4: double asdouble(uint lowbits, uint highbits)
  6838. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  6839. // Method 6:
  6840. // void asuint(
  6841. // in double value,
  6842. // out uint lowbits,
  6843. // out uint highbits
  6844. // );
  6845. const QualType returnType = callExpr->getType();
  6846. const uint32_t numArgs = callExpr->getNumArgs();
  6847. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6848. const Expr *arg0 = callExpr->getArg(0);
  6849. const QualType argType = arg0->getType();
  6850. // Method 3 return type may be the same as arg type, so it would be a no-op.
  6851. if (typeTranslator.isSameType(returnType, argType))
  6852. return doExpr(arg0);
  6853. switch (numArgs) {
  6854. case 1: {
  6855. // Handling Method 1, 2, and 3.
  6856. const auto argId = doExpr(arg0);
  6857. QualType fromElemType = {};
  6858. uint32_t numRows = 0, numCols = 0;
  6859. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  6860. if (!TypeTranslator::isMxNMatrix(argType, &fromElemType, &numRows,
  6861. &numCols)) {
  6862. return theBuilder.createUnaryOp(spv::Op::OpBitcast, returnTypeId, argId);
  6863. }
  6864. // Input or output type is a matrix.
  6865. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  6866. llvm::SmallVector<uint32_t, 4> castedRows;
  6867. const auto fromVecQualType =
  6868. astContext.getExtVectorType(fromElemType, numCols);
  6869. const auto toVecQualType = astContext.getExtVectorType(toElemType, numCols);
  6870. const auto fromVecTypeId = typeTranslator.translateType(fromVecQualType);
  6871. const auto toVecTypeId = typeTranslator.translateType(toVecQualType);
  6872. for (uint32_t row = 0; row < numRows; ++row) {
  6873. const auto rowId =
  6874. theBuilder.createCompositeExtract(fromVecTypeId, argId, {row});
  6875. castedRows.push_back(
  6876. theBuilder.createUnaryOp(spv::Op::OpBitcast, toVecTypeId, rowId));
  6877. }
  6878. return theBuilder.createCompositeConstruct(returnTypeId, castedRows);
  6879. }
  6880. case 2: {
  6881. const uint32_t lowbits = doExpr(arg0);
  6882. const uint32_t highbits = doExpr(callExpr->getArg(1));
  6883. const uint32_t uintType = theBuilder.getUint32Type();
  6884. const uint32_t doubleType = theBuilder.getFloat64Type();
  6885. // Handling Method 4
  6886. if (argType->isUnsignedIntegerType()) {
  6887. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  6888. const uint32_t operand = theBuilder.createCompositeConstruct(
  6889. uintVec2Type, {lowbits, highbits});
  6890. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand);
  6891. }
  6892. // Handling Method 5
  6893. else {
  6894. const uint32_t uintVec4Type = theBuilder.getVecType(uintType, 4);
  6895. const uint32_t doubleVec2Type = theBuilder.getVecType(doubleType, 2);
  6896. const uint32_t operand = theBuilder.createVectorShuffle(
  6897. uintVec4Type, lowbits, highbits, {0, 2, 1, 3});
  6898. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  6899. operand);
  6900. }
  6901. }
  6902. case 3: {
  6903. // Handling Method 6.
  6904. const uint32_t value = doExpr(arg0);
  6905. const uint32_t lowbits = doExpr(callExpr->getArg(1));
  6906. const uint32_t highbits = doExpr(callExpr->getArg(2));
  6907. const uint32_t uintType = theBuilder.getUint32Type();
  6908. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  6909. const uint32_t vecResult =
  6910. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value);
  6911. theBuilder.createStore(
  6912. lowbits, theBuilder.createCompositeExtract(uintType, vecResult, {0}));
  6913. theBuilder.createStore(
  6914. highbits, theBuilder.createCompositeExtract(uintType, vecResult, {1}));
  6915. return 0;
  6916. }
  6917. default:
  6918. emitError("unrecognized signature for %0 intrinsic function",
  6919. callExpr->getExprLoc())
  6920. << callExpr->getDirectCallee()->getName();
  6921. return 0;
  6922. }
  6923. }
  6924. uint32_t SPIRVEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  6925. // Should take a float4 and return an int4 by doing:
  6926. // int4 result = input.zyxw * 255.001953;
  6927. // Maximum float precision makes the scaling factor 255.002.
  6928. const auto arg = callExpr->getArg(0);
  6929. const auto argId = doExpr(arg);
  6930. const auto argTypeId = typeTranslator.translateType(arg->getType());
  6931. const auto swizzle =
  6932. theBuilder.createVectorShuffle(argTypeId, argId, argId, {2, 1, 0, 3});
  6933. const auto scaled = theBuilder.createBinaryOp(
  6934. spv::Op::OpVectorTimesScalar, argTypeId, swizzle,
  6935. theBuilder.getConstantFloat32(255.002f));
  6936. return castToInt(scaled, arg->getType(), callExpr->getType(),
  6937. callExpr->getExprLoc());
  6938. }
  6939. uint32_t SPIRVEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  6940. // Since OpIsFinite needs the Kernel capability, translation is instead done
  6941. // using OpIsNan and OpIsInf:
  6942. // isFinite = !(isNan || isInf)
  6943. const auto arg = doExpr(callExpr->getArg(0));
  6944. const auto returnType = typeTranslator.translateType(callExpr->getType());
  6945. const auto isNan =
  6946. theBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg);
  6947. const auto isInf =
  6948. theBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg);
  6949. const auto isNanOrInf =
  6950. theBuilder.createBinaryOp(spv::Op::OpLogicalOr, returnType, isNan, isInf);
  6951. return theBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType,
  6952. isNanOrInf);
  6953. }
  6954. uint32_t SPIRVEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  6955. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  6956. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  6957. CallExpr *sincosExpr =
  6958. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  6959. sincosExpr->setType(callExpr->getArg(0)->getType());
  6960. sincosExpr->setNumArgs(astContext, 1);
  6961. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  6962. // Perform Sin and store results in argument 1.
  6963. const uint32_t sin =
  6964. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  6965. /*actPerRowForMatrices*/ true);
  6966. theBuilder.createStore(doExpr(callExpr->getArg(1)), sin);
  6967. // Perform Cos and store results in argument 2.
  6968. const uint32_t cos =
  6969. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  6970. /*actPerRowForMatrices*/ true);
  6971. theBuilder.createStore(doExpr(callExpr->getArg(2)), cos);
  6972. return 0;
  6973. }
  6974. uint32_t SPIRVEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  6975. const auto *arg = callExpr->getArg(0);
  6976. const auto argId = doExpr(arg);
  6977. const auto argType = arg->getType();
  6978. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  6979. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6980. if (argType->isFloatingType()) {
  6981. const uint32_t floatZero = getValueZero(argType);
  6982. const uint32_t floatOne = getValueOne(argType);
  6983. return theBuilder.createExtInst(returnType, glslInstSetId,
  6984. GLSLstd450::GLSLstd450FClamp,
  6985. {argId, floatZero, floatOne});
  6986. }
  6987. QualType elemType = {};
  6988. uint32_t vecSize = 0;
  6989. if (TypeTranslator::isVectorType(argType, &elemType, &vecSize)) {
  6990. const uint32_t vecZero = getVecValueZero(elemType, vecSize);
  6991. const uint32_t vecOne = getVecValueOne(elemType, vecSize);
  6992. return theBuilder.createExtInst(returnType, glslInstSetId,
  6993. GLSLstd450::GLSLstd450FClamp,
  6994. {argId, vecZero, vecOne});
  6995. }
  6996. uint32_t numRows = 0, numCols = 0;
  6997. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  6998. const uint32_t vecZero = getVecValueZero(elemType, numCols);
  6999. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  7000. const auto actOnEachVec = [this, vecZero, vecOne, glslInstSetId](
  7001. uint32_t /*index*/, uint32_t vecType,
  7002. uint32_t curRowId) {
  7003. return theBuilder.createExtInst(vecType, glslInstSetId,
  7004. GLSLstd450::GLSLstd450FClamp,
  7005. {curRowId, vecZero, vecOne});
  7006. };
  7007. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7008. }
  7009. emitError("invalid argument type passed to saturate intrinsic function",
  7010. callExpr->getExprLoc());
  7011. return 0;
  7012. }
  7013. uint32_t SPIRVEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  7014. // Import the GLSL.std.450 extended instruction set.
  7015. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7016. const Expr *arg = callExpr->getArg(0);
  7017. const QualType returnType = callExpr->getType();
  7018. const QualType argType = arg->getType();
  7019. assert(isFloatOrVecMatOfFloatType(argType));
  7020. const uint32_t argTypeId = typeTranslator.translateType(argType);
  7021. const uint32_t argId = doExpr(arg);
  7022. uint32_t floatSignResultId = 0;
  7023. // For matrices, we can perform the instruction on each vector of the matrix.
  7024. if (TypeTranslator::isMxNMatrix(argType)) {
  7025. const auto actOnEachVec = [this, glslInstSetId](uint32_t /*index*/,
  7026. uint32_t vecType,
  7027. uint32_t curRowId) {
  7028. return theBuilder.createExtInst(vecType, glslInstSetId,
  7029. GLSLstd450::GLSLstd450FSign, {curRowId});
  7030. };
  7031. floatSignResultId = processEachVectorInMatrix(arg, argId, actOnEachVec);
  7032. } else {
  7033. floatSignResultId = theBuilder.createExtInst(
  7034. argTypeId, glslInstSetId, GLSLstd450::GLSLstd450FSign, {argId});
  7035. }
  7036. return castToInt(floatSignResultId, arg->getType(), returnType,
  7037. arg->getExprLoc());
  7038. }
  7039. uint32_t SPIRVEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  7040. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  7041. // The frontend should guarantee that by inserting implicit casts.
  7042. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7043. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7044. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7045. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7046. const auto *arg = callExpr->getArg(0);
  7047. const uint32_t argId = doExpr(arg);
  7048. uint32_t elemCount = {};
  7049. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7050. // The input is a vector. We need to handle each element separately.
  7051. llvm::SmallVector<uint32_t, 4> elements;
  7052. for (uint32_t i = 0; i < elemCount; ++i) {
  7053. const uint32_t srcElem =
  7054. theBuilder.createCompositeExtract(u32TypeId, argId, {i});
  7055. const uint32_t convert = theBuilder.createExtInst(
  7056. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem);
  7057. elements.push_back(
  7058. theBuilder.createCompositeExtract(f32TypeId, convert, {0}));
  7059. }
  7060. return theBuilder.createCompositeConstruct(
  7061. theBuilder.getVecType(f32TypeId, elemCount), elements);
  7062. }
  7063. const uint32_t convert = theBuilder.createExtInst(
  7064. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, argId);
  7065. // f16tof32() converts the float16 stored in the low-half of the uint to
  7066. // a float. So just need to return the first component.
  7067. return theBuilder.createCompositeExtract(f32TypeId, convert, {0});
  7068. }
  7069. uint32_t SPIRVEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  7070. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  7071. // The frontend should guarantee that by inserting implicit casts.
  7072. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7073. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7074. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7075. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7076. const uint32_t zero = theBuilder.getConstantFloat32(0);
  7077. const auto *arg = callExpr->getArg(0);
  7078. const uint32_t argId = doExpr(arg);
  7079. uint32_t elemCount = {};
  7080. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7081. // The input is a vector. We need to handle each element separately.
  7082. llvm::SmallVector<uint32_t, 4> elements;
  7083. for (uint32_t i = 0; i < elemCount; ++i) {
  7084. const uint32_t srcElem =
  7085. theBuilder.createCompositeExtract(f32TypeId, argId, {i});
  7086. const uint32_t srcVec =
  7087. theBuilder.createCompositeConstruct(v2f32TypeId, {srcElem, zero});
  7088. elements.push_back(theBuilder.createExtInst(
  7089. u32TypeId, glsl, GLSLstd450::GLSLstd450PackHalf2x16, srcVec));
  7090. }
  7091. return theBuilder.createCompositeConstruct(
  7092. theBuilder.getVecType(u32TypeId, elemCount), elements);
  7093. }
  7094. // f16tof32() stores the float into the low-half of the uint. So we need
  7095. // to supply another zero to take the other half.
  7096. const uint32_t srcVec =
  7097. theBuilder.createCompositeConstruct(v2f32TypeId, {argId, zero});
  7098. return theBuilder.createExtInst(u32TypeId, glsl,
  7099. GLSLstd450::GLSLstd450PackHalf2x16, srcVec);
  7100. }
  7101. uint32_t SPIRVEmitter::processIntrinsicUsingSpirvInst(
  7102. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  7103. // Certain opcodes are only allowed in pixel shader
  7104. if (!shaderModel.IsPS())
  7105. switch (opcode) {
  7106. case spv::Op::OpDPdx:
  7107. case spv::Op::OpDPdy:
  7108. case spv::Op::OpDPdxFine:
  7109. case spv::Op::OpDPdyFine:
  7110. case spv::Op::OpDPdxCoarse:
  7111. case spv::Op::OpDPdyCoarse:
  7112. case spv::Op::OpFwidth:
  7113. case spv::Op::OpFwidthFine:
  7114. case spv::Op::OpFwidthCoarse:
  7115. needsLegalization = true;
  7116. }
  7117. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7118. if (callExpr->getNumArgs() == 1u) {
  7119. const Expr *arg = callExpr->getArg(0);
  7120. const uint32_t argId = doExpr(arg);
  7121. // If the instruction does not operate on matrices, we can perform the
  7122. // instruction on each vector of the matrix.
  7123. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7124. const auto actOnEachVec = [this, opcode](uint32_t /*index*/,
  7125. uint32_t vecType,
  7126. uint32_t curRowId) {
  7127. return theBuilder.createUnaryOp(opcode, vecType, {curRowId});
  7128. };
  7129. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7130. }
  7131. return theBuilder.createUnaryOp(opcode, returnType, {argId});
  7132. } else if (callExpr->getNumArgs() == 2u) {
  7133. const Expr *arg0 = callExpr->getArg(0);
  7134. const uint32_t arg0Id = doExpr(arg0);
  7135. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7136. // If the instruction does not operate on matrices, we can perform the
  7137. // instruction on each vector of the matrix.
  7138. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7139. const auto actOnEachVec = [this, opcode, arg1Id](uint32_t index,
  7140. uint32_t vecType,
  7141. uint32_t arg0RowId) {
  7142. const uint32_t arg1RowId =
  7143. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7144. return theBuilder.createBinaryOp(opcode, vecType, arg0RowId, arg1RowId);
  7145. };
  7146. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7147. }
  7148. return theBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id);
  7149. }
  7150. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7151. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7152. return 0;
  7153. }
  7154. uint32_t SPIRVEmitter::processIntrinsicUsingGLSLInst(
  7155. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices) {
  7156. // Import the GLSL.std.450 extended instruction set.
  7157. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7158. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7159. if (callExpr->getNumArgs() == 1u) {
  7160. const Expr *arg = callExpr->getArg(0);
  7161. const uint32_t argId = doExpr(arg);
  7162. // If the instruction does not operate on matrices, we can perform the
  7163. // instruction on each vector of the matrix.
  7164. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7165. const auto actOnEachVec = [this, glslInstSetId,
  7166. opcode](uint32_t /*index*/, uint32_t vecType,
  7167. uint32_t curRowId) {
  7168. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7169. {curRowId});
  7170. };
  7171. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7172. }
  7173. return theBuilder.createExtInst(returnType, glslInstSetId, opcode, {argId});
  7174. } else if (callExpr->getNumArgs() == 2u) {
  7175. const Expr *arg0 = callExpr->getArg(0);
  7176. const uint32_t arg0Id = doExpr(arg0);
  7177. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7178. // If the instruction does not operate on matrices, we can perform the
  7179. // instruction on each vector of the matrix.
  7180. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7181. const auto actOnEachVec = [this, glslInstSetId, opcode,
  7182. arg1Id](uint32_t index, uint32_t vecType,
  7183. uint32_t arg0RowId) {
  7184. const uint32_t arg1RowId =
  7185. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7186. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7187. {arg0RowId, arg1RowId});
  7188. };
  7189. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7190. }
  7191. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7192. {arg0Id, arg1Id});
  7193. } else if (callExpr->getNumArgs() == 3u) {
  7194. const Expr *arg0 = callExpr->getArg(0);
  7195. const uint32_t arg0Id = doExpr(arg0);
  7196. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7197. const uint32_t arg2Id = doExpr(callExpr->getArg(2));
  7198. // If the instruction does not operate on matrices, we can perform the
  7199. // instruction on each vector of the matrix.
  7200. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7201. const auto actOnEachVec = [this, glslInstSetId, opcode, arg0Id, arg1Id,
  7202. arg2Id](uint32_t index, uint32_t vecType,
  7203. uint32_t arg0RowId) {
  7204. const uint32_t arg1RowId =
  7205. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7206. const uint32_t arg2RowId =
  7207. theBuilder.createCompositeExtract(vecType, arg2Id, {index});
  7208. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7209. {arg0RowId, arg1RowId, arg2RowId});
  7210. };
  7211. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7212. }
  7213. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7214. {arg0Id, arg1Id, arg2Id});
  7215. }
  7216. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7217. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7218. return 0;
  7219. }
  7220. uint32_t SPIRVEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  7221. // Since there is no log10 instruction in SPIR-V, we can use:
  7222. // log10(x) = log2(x) * ( 1 / log2(10) )
  7223. // 1 / log2(10) = 0.30103
  7224. const auto scale = theBuilder.getConstantFloat32(0.30103f);
  7225. const auto log2 =
  7226. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450Log2, true);
  7227. const auto returnType = callExpr->getType();
  7228. const auto returnTypeId = typeTranslator.translateType(returnType);
  7229. spv::Op scaleOp = TypeTranslator::isScalarType(returnType)
  7230. ? spv::Op::OpFMul
  7231. : TypeTranslator::isVectorType(returnType)
  7232. ? spv::Op::OpVectorTimesScalar
  7233. : spv::Op::OpMatrixTimesScalar;
  7234. return theBuilder.createBinaryOp(scaleOp, returnTypeId, log2, scale);
  7235. }
  7236. uint32_t SPIRVEmitter::getValueZero(QualType type) {
  7237. {
  7238. QualType scalarType = {};
  7239. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7240. if (scalarType->isSignedIntegerType()) {
  7241. return theBuilder.getConstantInt32(0);
  7242. }
  7243. if (scalarType->isUnsignedIntegerType()) {
  7244. return theBuilder.getConstantUint32(0);
  7245. }
  7246. if (scalarType->isFloatingType()) {
  7247. return theBuilder.getConstantFloat32(0.0);
  7248. }
  7249. }
  7250. }
  7251. {
  7252. QualType elemType = {};
  7253. uint32_t size = {};
  7254. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7255. return getVecValueZero(elemType, size);
  7256. }
  7257. }
  7258. {
  7259. QualType elemType = {};
  7260. uint32_t rowCount = 0, colCount = 0;
  7261. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  7262. const auto row = getVecValueZero(elemType, colCount);
  7263. llvm::SmallVector<uint32_t, 4> rows((size_t)rowCount, row);
  7264. return theBuilder.createCompositeConstruct(
  7265. typeTranslator.translateType(type), rows);
  7266. }
  7267. }
  7268. emitError("getting value 0 for type %0 unimplemented", {})
  7269. << type.getAsString();
  7270. return 0;
  7271. }
  7272. uint32_t SPIRVEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  7273. const uint32_t elemZeroId = getValueZero(elemType);
  7274. if (size == 1)
  7275. return elemZeroId;
  7276. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemZeroId);
  7277. const uint32_t vecType =
  7278. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7279. return theBuilder.getConstantComposite(vecType, elements);
  7280. }
  7281. uint32_t SPIRVEmitter::getValueOne(QualType type) {
  7282. {
  7283. QualType scalarType = {};
  7284. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7285. // TODO: Support other types such as short, half, etc.
  7286. if (scalarType->isSignedIntegerType()) {
  7287. return theBuilder.getConstantInt32(1);
  7288. }
  7289. if (scalarType->isUnsignedIntegerType()) {
  7290. return theBuilder.getConstantUint32(1);
  7291. }
  7292. if (scalarType->isSpecificBuiltinType(BuiltinType::LitFloat))
  7293. scalarType = typeTranslator.getIntendedLiteralType(scalarType);
  7294. if (const auto *builtinType = scalarType->getAs<BuiltinType>()) {
  7295. // TODO: Add support for other types that are not covered yet.
  7296. switch (builtinType->getKind()) {
  7297. case BuiltinType::Double:
  7298. return theBuilder.getConstantFloat64(1.0);
  7299. case BuiltinType::Float:
  7300. return theBuilder.getConstantFloat32(1.0);
  7301. }
  7302. }
  7303. }
  7304. }
  7305. {
  7306. QualType elemType = {};
  7307. uint32_t size = {};
  7308. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7309. return getVecValueOne(elemType, size);
  7310. }
  7311. }
  7312. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  7313. return 0;
  7314. }
  7315. uint32_t SPIRVEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  7316. const uint32_t elemOneId = getValueOne(elemType);
  7317. if (size == 1)
  7318. return elemOneId;
  7319. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemOneId);
  7320. const uint32_t vecType =
  7321. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7322. return theBuilder.getConstantComposite(vecType, elements);
  7323. }
  7324. uint32_t SPIRVEmitter::getMatElemValueOne(QualType type) {
  7325. assert(hlsl::IsHLSLMatType(type));
  7326. const auto elemType = hlsl::GetHLSLMatElementType(type);
  7327. uint32_t rowCount = 0, colCount = 0;
  7328. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  7329. if (rowCount == 1 && colCount == 1)
  7330. return getValueOne(elemType);
  7331. if (colCount == 1)
  7332. return getVecValueOne(elemType, rowCount);
  7333. return getVecValueOne(elemType, colCount);
  7334. }
  7335. uint32_t SPIRVEmitter::translateAPValue(const APValue &value,
  7336. const QualType targetType) {
  7337. uint32_t result = 0;
  7338. // Provide a hint to the typeTranslator that if a literal is discovered, its
  7339. // intended usage is targetType.
  7340. TypeTranslator::LiteralTypeHint hint(typeTranslator, targetType);
  7341. if (targetType->isBooleanType()) {
  7342. result = theBuilder.getConstantBool(value.getInt().getBoolValue(),
  7343. isSpecConstantMode);
  7344. } else if (targetType->isIntegerType()) {
  7345. result = translateAPInt(value.getInt(), targetType);
  7346. } else if (targetType->isFloatingType()) {
  7347. result = translateAPFloat(value.getFloat(), targetType);
  7348. } else if (hlsl::IsHLSLVecType(targetType)) {
  7349. const uint32_t vecType = typeTranslator.translateType(targetType);
  7350. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  7351. const auto numElements = value.getVectorLength();
  7352. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  7353. // size so we need to translate it to scalar values.
  7354. if (numElements == 1) {
  7355. result = translateAPValue(value.getVectorElt(0), elemType);
  7356. } else {
  7357. llvm::SmallVector<uint32_t, 4> elements;
  7358. for (uint32_t i = 0; i < numElements; ++i) {
  7359. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  7360. }
  7361. result = theBuilder.getConstantComposite(vecType, elements);
  7362. }
  7363. }
  7364. if (result)
  7365. return result;
  7366. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  7367. value.dump();
  7368. return 0;
  7369. }
  7370. uint32_t SPIRVEmitter::translateAPInt(const llvm::APInt &intValue,
  7371. QualType targetType) {
  7372. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7373. const auto targetTypeBitWidth = astContext.getTypeSize(targetType);
  7374. const bool isSigned = targetType->isSignedIntegerType();
  7375. switch (targetTypeBitWidth) {
  7376. case 16: {
  7377. if (spirvOptions.enable16BitTypes) {
  7378. if (isSigned) {
  7379. return theBuilder.getConstantInt16(
  7380. static_cast<int16_t>(intValue.getSExtValue()));
  7381. } else {
  7382. return theBuilder.getConstantUint16(
  7383. static_cast<uint16_t>(intValue.getZExtValue()));
  7384. }
  7385. } else {
  7386. // If enable16BitTypes option is not true, treat as 32-bit integer.
  7387. if (isSigned)
  7388. return theBuilder.getConstantInt32(
  7389. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7390. else
  7391. return theBuilder.getConstantUint32(
  7392. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7393. }
  7394. }
  7395. case 32: {
  7396. if (isSigned) {
  7397. if (!intValue.isSignedIntN(32)) {
  7398. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7399. "inforamtion",
  7400. {})
  7401. << std::to_string(intValue.getSExtValue());
  7402. return 0;
  7403. }
  7404. return theBuilder.getConstantInt32(
  7405. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7406. } else {
  7407. if (!intValue.isIntN(32)) {
  7408. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7409. "inforamtion",
  7410. {})
  7411. << std::to_string(intValue.getZExtValue());
  7412. return 0;
  7413. }
  7414. return theBuilder.getConstantUint32(
  7415. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7416. }
  7417. }
  7418. case 64: {
  7419. if (isSigned)
  7420. return theBuilder.getConstantInt64(intValue.getSExtValue());
  7421. else
  7422. return theBuilder.getConstantUint64(intValue.getZExtValue());
  7423. }
  7424. }
  7425. emitError("APInt for target bitwidth %0 unimplemented", {})
  7426. << astContext.getIntWidth(targetType);
  7427. return 0;
  7428. }
  7429. bool SPIRVEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  7430. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  7431. const bool isSigned = expr->getType()->isSignedIntegerType();
  7432. const llvm::APInt &value = intLiteral->getValue();
  7433. return (isSigned && !value.isSignedIntN(32)) ||
  7434. (!isSigned && !value.isIntN(32));
  7435. }
  7436. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  7437. llvm::APFloat value = floatLiteral->getValue();
  7438. const auto &semantics = value.getSemantics();
  7439. // regular 'half' and 'float' can be represented in 32 bits.
  7440. if (&semantics == &llvm::APFloat::IEEEsingle ||
  7441. &semantics == &llvm::APFloat::IEEEhalf)
  7442. return true;
  7443. // See if 'double' value can be represented in 32 bits without losing info.
  7444. bool losesInfo = false;
  7445. const auto convertStatus =
  7446. value.convert(llvm::APFloat::IEEEsingle,
  7447. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7448. if (convertStatus != llvm::APFloat::opOK &&
  7449. convertStatus != llvm::APFloat::opInexact)
  7450. return true;
  7451. }
  7452. return false;
  7453. }
  7454. uint32_t SPIRVEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  7455. bool isSigned) {
  7456. if (isSigned && intValue.isSignedIntN(32)) {
  7457. return theBuilder.getConstantInt32(
  7458. static_cast<int32_t>(intValue.getSExtValue()));
  7459. }
  7460. if (!isSigned && intValue.isIntN(32)) {
  7461. return theBuilder.getConstantUint32(
  7462. static_cast<uint32_t>(intValue.getZExtValue()));
  7463. }
  7464. // Couldn't evaluate as a 32-bit int without losing information.
  7465. return 0;
  7466. }
  7467. uint32_t SPIRVEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  7468. const auto &semantics = floatValue.getSemantics();
  7469. // If the given value is already a 32-bit float, there is no need to convert.
  7470. if (&semantics == &llvm::APFloat::IEEEsingle) {
  7471. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7472. isSpecConstantMode);
  7473. }
  7474. // Try to see if this literal float can be represented in 32-bit.
  7475. // Since the convert function below may modify the fp value, we call it on a
  7476. // temporary copy.
  7477. llvm::APFloat eval = floatValue;
  7478. bool losesInfo = false;
  7479. const auto convertStatus =
  7480. eval.convert(llvm::APFloat::IEEEsingle,
  7481. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7482. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  7483. return theBuilder.getConstantFloat32(eval.convertToFloat());
  7484. // Couldn't evaluate as a 32-bit float without losing information.
  7485. return 0;
  7486. }
  7487. uint32_t SPIRVEmitter::translateAPFloat(llvm::APFloat floatValue,
  7488. QualType targetType) {
  7489. using llvm::APFloat;
  7490. const auto originalValue = floatValue;
  7491. const auto valueBitwidth = APFloat::getSizeInBits(floatValue.getSemantics());
  7492. // Find out the target bitwidth.
  7493. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7494. auto targetBitwidth =
  7495. APFloat::getSizeInBits(astContext.getFloatTypeSemantics(targetType));
  7496. // If 16-bit types are not enabled, treat them as 32-bit float.
  7497. if (targetBitwidth == 16 && !spirvOptions.enable16BitTypes)
  7498. targetBitwidth = 32;
  7499. if (targetBitwidth != valueBitwidth) {
  7500. bool losesInfo = false;
  7501. const llvm::fltSemantics &targetSemantics =
  7502. targetBitwidth == 16
  7503. ? APFloat::IEEEhalf
  7504. : targetBitwidth == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble;
  7505. const auto status = floatValue.convert(
  7506. targetSemantics, APFloat::roundingMode::rmTowardZero, &losesInfo);
  7507. if (status != APFloat::opStatus::opOK &&
  7508. status != APFloat::opStatus::opInexact) {
  7509. emitError(
  7510. "evaluating float literal %0 at a lower bitwidth loses information",
  7511. {})
  7512. // Converting from 16bit to 32/64-bit won't lose information.
  7513. // So only 32/64-bit values can reach here.
  7514. << std::to_string(valueBitwidth == 32
  7515. ? originalValue.convertToFloat()
  7516. : originalValue.convertToDouble());
  7517. return 0;
  7518. }
  7519. }
  7520. switch (targetBitwidth) {
  7521. case 16:
  7522. return theBuilder.getConstantFloat16(
  7523. static_cast<uint16_t>(floatValue.bitcastToAPInt().getZExtValue()));
  7524. case 32:
  7525. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7526. isSpecConstantMode);
  7527. case 64:
  7528. return theBuilder.getConstantFloat64(floatValue.convertToDouble());
  7529. default:
  7530. break;
  7531. }
  7532. emitError("APFloat for target bitwidth %0 unimplemented", {})
  7533. << targetBitwidth;
  7534. return 0;
  7535. }
  7536. uint32_t SPIRVEmitter::tryToEvaluateAsConst(const Expr *expr) {
  7537. Expr::EvalResult evalResult;
  7538. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  7539. !evalResult.HasSideEffects) {
  7540. return translateAPValue(evalResult.Val, expr->getType());
  7541. }
  7542. return 0;
  7543. }
  7544. spv::ExecutionModel
  7545. SPIRVEmitter::getSpirvShaderStage(const hlsl::ShaderModel &model) {
  7546. // DXIL Models are:
  7547. // Profile (DXIL Model) : HLSL Shader Kind : SPIR-V Shader Stage
  7548. // vs_<version> : Vertex Shader : Vertex Shader
  7549. // hs_<version> : Hull Shader : Tassellation Control Shader
  7550. // ds_<version> : Domain Shader : Tessellation Evaluation Shader
  7551. // gs_<version> : Geometry Shader : Geometry Shader
  7552. // ps_<version> : Pixel Shader : Fragment Shader
  7553. // cs_<version> : Compute Shader : Compute Shader
  7554. switch (model.GetKind()) {
  7555. case hlsl::ShaderModel::Kind::Vertex:
  7556. return spv::ExecutionModel::Vertex;
  7557. case hlsl::ShaderModel::Kind::Hull:
  7558. return spv::ExecutionModel::TessellationControl;
  7559. case hlsl::ShaderModel::Kind::Domain:
  7560. return spv::ExecutionModel::TessellationEvaluation;
  7561. case hlsl::ShaderModel::Kind::Geometry:
  7562. return spv::ExecutionModel::Geometry;
  7563. case hlsl::ShaderModel::Kind::Pixel:
  7564. return spv::ExecutionModel::Fragment;
  7565. case hlsl::ShaderModel::Kind::Compute:
  7566. return spv::ExecutionModel::GLCompute;
  7567. default:
  7568. break;
  7569. }
  7570. llvm_unreachable("unknown shader model");
  7571. }
  7572. void SPIRVEmitter::AddRequiredCapabilitiesForShaderModel() {
  7573. if (shaderModel.IsHS() || shaderModel.IsDS()) {
  7574. theBuilder.requireCapability(spv::Capability::Tessellation);
  7575. } else if (shaderModel.IsGS()) {
  7576. theBuilder.requireCapability(spv::Capability::Geometry);
  7577. } else {
  7578. theBuilder.requireCapability(spv::Capability::Shader);
  7579. }
  7580. }
  7581. bool SPIRVEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  7582. uint32_t *arraySize) {
  7583. bool success = true;
  7584. assert(shaderModel.IsGS());
  7585. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  7586. theBuilder.addExecutionMode(entryFunctionId,
  7587. spv::ExecutionMode::OutputVertices,
  7588. {static_cast<uint32_t>(vcAttr->getCount())});
  7589. }
  7590. uint32_t invocations = 1;
  7591. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  7592. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  7593. }
  7594. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::Invocations,
  7595. {invocations});
  7596. // Only one primitive type is permitted for the geometry shader.
  7597. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  7598. inLine = false, inTriangle = false, inLineAdj = false,
  7599. inTriangleAdj = false;
  7600. for (const auto *param : decl->params()) {
  7601. // Add an execution mode based on the output stream type. Do not an
  7602. // execution mode more than once.
  7603. if (param->hasAttr<HLSLInOutAttr>()) {
  7604. const auto paramType = param->getType();
  7605. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  7606. theBuilder.addExecutionMode(
  7607. entryFunctionId, spv::ExecutionMode::OutputTriangleStrip, {});
  7608. outTriangle = true;
  7609. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  7610. theBuilder.addExecutionMode(entryFunctionId,
  7611. spv::ExecutionMode::OutputLineStrip, {});
  7612. outLine = true;
  7613. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  7614. theBuilder.addExecutionMode(entryFunctionId,
  7615. spv::ExecutionMode::OutputPoints, {});
  7616. outPoint = true;
  7617. }
  7618. // An output stream parameter will not have the input primitive type
  7619. // attributes, so we can continue to the next parameter.
  7620. continue;
  7621. }
  7622. // Add an execution mode based on the input primitive type. Do not add an
  7623. // execution mode more than once.
  7624. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  7625. theBuilder.addExecutionMode(entryFunctionId,
  7626. spv::ExecutionMode::InputPoints, {});
  7627. *arraySize = 1;
  7628. inPoint = true;
  7629. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  7630. theBuilder.addExecutionMode(entryFunctionId,
  7631. spv::ExecutionMode::InputLines, {});
  7632. *arraySize = 2;
  7633. inLine = true;
  7634. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  7635. theBuilder.addExecutionMode(entryFunctionId,
  7636. spv::ExecutionMode::Triangles, {});
  7637. *arraySize = 3;
  7638. inTriangle = true;
  7639. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  7640. theBuilder.addExecutionMode(entryFunctionId,
  7641. spv::ExecutionMode::InputLinesAdjacency, {});
  7642. *arraySize = 4;
  7643. inLineAdj = true;
  7644. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  7645. theBuilder.addExecutionMode(
  7646. entryFunctionId, spv::ExecutionMode::InputTrianglesAdjacency, {});
  7647. *arraySize = 6;
  7648. inTriangleAdj = true;
  7649. }
  7650. }
  7651. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  7652. emitError("only one input primitive type can be specified in the geometry "
  7653. "shader",
  7654. {});
  7655. success = false;
  7656. }
  7657. if (outPoint + outTriangle + outLine > 1) {
  7658. emitError("only one output primitive type can be specified in the geometry "
  7659. "shader",
  7660. {});
  7661. success = false;
  7662. }
  7663. return success;
  7664. }
  7665. void SPIRVEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  7666. theBuilder.addExecutionMode(entryFunctionId,
  7667. spv::ExecutionMode::OriginUpperLeft, {});
  7668. if (auto *numThreadsAttr = decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  7669. theBuilder.addExecutionMode(entryFunctionId,
  7670. spv::ExecutionMode::EarlyFragmentTests, {});
  7671. }
  7672. }
  7673. void SPIRVEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  7674. // If not explicitly specified, x, y, and z should be defaulted to 1.
  7675. uint32_t x = 1, y = 1, z = 1;
  7676. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  7677. x = static_cast<uint32_t>(numThreadsAttr->getX());
  7678. y = static_cast<uint32_t>(numThreadsAttr->getY());
  7679. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  7680. }
  7681. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::LocalSize,
  7682. {x, y, z});
  7683. }
  7684. bool SPIRVEmitter::processTessellationShaderAttributes(
  7685. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  7686. assert(shaderModel.IsHS() || shaderModel.IsDS());
  7687. using namespace spv;
  7688. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  7689. const auto domainType = domain->getDomainType().lower();
  7690. const ExecutionMode hsExecMode =
  7691. llvm::StringSwitch<ExecutionMode>(domainType)
  7692. .Case("tri", ExecutionMode::Triangles)
  7693. .Case("quad", ExecutionMode::Quads)
  7694. .Case("isoline", ExecutionMode::Isolines)
  7695. .Default(ExecutionMode::Max);
  7696. if (hsExecMode == ExecutionMode::Max) {
  7697. emitError("unknown domain type specified for entry function",
  7698. domain->getLocation());
  7699. return false;
  7700. }
  7701. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  7702. }
  7703. // Early return for domain shaders as domain shaders only takes the 'domain'
  7704. // attribute.
  7705. if (shaderModel.IsDS())
  7706. return true;
  7707. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  7708. const auto scheme = partitioning->getScheme().lower();
  7709. if (scheme == "pow2") {
  7710. emitError("pow2 partitioning scheme is not supported since there is no "
  7711. "equivalent in Vulkan",
  7712. partitioning->getLocation());
  7713. return false;
  7714. }
  7715. const ExecutionMode hsExecMode =
  7716. llvm::StringSwitch<ExecutionMode>(scheme)
  7717. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  7718. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  7719. .Case("integer", ExecutionMode::SpacingEqual)
  7720. .Default(ExecutionMode::Max);
  7721. if (hsExecMode == ExecutionMode::Max) {
  7722. emitError("unknown partitioning scheme in hull shader",
  7723. partitioning->getLocation());
  7724. return false;
  7725. }
  7726. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  7727. }
  7728. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  7729. const auto topology = outputTopology->getTopology().lower();
  7730. const ExecutionMode hsExecMode =
  7731. llvm::StringSwitch<ExecutionMode>(topology)
  7732. .Case("point", ExecutionMode::PointMode)
  7733. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  7734. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  7735. .Default(ExecutionMode::Max);
  7736. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  7737. // default?
  7738. if (topology != "line") {
  7739. if (hsExecMode != spv::ExecutionMode::Max) {
  7740. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  7741. } else {
  7742. emitError("unknown output topology in hull shader",
  7743. outputTopology->getLocation());
  7744. return false;
  7745. }
  7746. }
  7747. }
  7748. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  7749. *numOutputControlPoints = controlPoints->getCount();
  7750. theBuilder.addExecutionMode(entryFunctionId,
  7751. spv::ExecutionMode::OutputVertices,
  7752. {*numOutputControlPoints});
  7753. }
  7754. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  7755. llvm::StringRef pcf_name = pcf->getFunctionName();
  7756. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  7757. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  7758. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  7759. funcDecl->getName() == pcf_name)
  7760. patchConstFunc = funcDecl;
  7761. }
  7762. return true;
  7763. }
  7764. bool SPIRVEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  7765. const uint32_t entryFuncId) {
  7766. // HS specific attributes
  7767. uint32_t numOutputControlPoints = 0;
  7768. uint32_t outputControlPointIdVal = 0; // SV_OutputControlPointID value
  7769. uint32_t primitiveIdVar = 0; // SV_PrimitiveID variable
  7770. uint32_t viewIdVar = 0; // SV_ViewID variable
  7771. uint32_t hullMainInputPatchParam = 0; // Temporary parameter for InputPatch<>
  7772. // The array size of per-vertex input/output variables
  7773. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  7774. uint32_t inputArraySize = 0;
  7775. uint32_t outputArraySize = 0;
  7776. // Construct the wrapper function signature.
  7777. const uint32_t voidType = theBuilder.getVoidType();
  7778. const uint32_t funcType = theBuilder.getFunctionType(voidType, {});
  7779. // The wrapper entry function surely does not have pre-assigned <result-id>
  7780. // for it like other functions that got added to the work queue following
  7781. // function calls. And the wrapper is the entry function.
  7782. entryFunctionId =
  7783. theBuilder.beginFunction(funcType, voidType, decl->getName());
  7784. // Note this should happen before using declIdMapper for other tasks.
  7785. declIdMapper.setEntryFunctionId(entryFunctionId);
  7786. // Handle attributes specific to each shader stage
  7787. if (shaderModel.IsPS()) {
  7788. processPixelShaderAttributes(decl);
  7789. } else if (shaderModel.IsCS()) {
  7790. processComputeShaderAttributes(decl);
  7791. } else if (shaderModel.IsHS()) {
  7792. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  7793. return false;
  7794. // The input array size for HS is specified in the InputPatch parameter.
  7795. for (const auto *param : decl->params())
  7796. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  7797. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  7798. break;
  7799. }
  7800. outputArraySize = numOutputControlPoints;
  7801. } else if (shaderModel.IsDS()) {
  7802. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  7803. return false;
  7804. // The input array size for HS is specified in the OutputPatch parameter.
  7805. for (const auto *param : decl->params())
  7806. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  7807. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  7808. break;
  7809. }
  7810. // The per-vertex output of DS is not an array.
  7811. } else if (shaderModel.IsGS()) {
  7812. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  7813. return false;
  7814. // The per-vertex output of GS is not an array.
  7815. }
  7816. // Go through all parameters and record the declaration of SV_ClipDistance
  7817. // and SV_CullDistance. We need to do this extra step because in HLSL we
  7818. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  7819. // or vector of float types, but we can only have one single float array
  7820. // for the ClipDistance/CullDistance builtin. So we need to group all
  7821. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  7822. // need to calculate the total size of the array and the offset of each
  7823. // variable within that array.
  7824. for (const auto *param : decl->params()) {
  7825. if (canActAsInParmVar(param))
  7826. if (!declIdMapper.glPerVertex.recordClipCullDistanceDecl(param, true))
  7827. return false;
  7828. if (canActAsOutParmVar(param))
  7829. if (!declIdMapper.glPerVertex.recordClipCullDistanceDecl(param, false))
  7830. return false;
  7831. }
  7832. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  7833. if (!declIdMapper.glPerVertex.recordClipCullDistanceDecl(decl, false))
  7834. return false;
  7835. // Calculate the total size of the ClipDistance/CullDistance array and the
  7836. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  7837. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  7838. if (!shaderModel.IsCS()) {
  7839. // Generate the gl_PerVertex structs or stand-alone builtins of
  7840. // Position, ClipDistance, and CullDistance.
  7841. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  7842. }
  7843. // Require the ClipDistance/CullDistance capability if necessary.
  7844. // It is legal to just use the ClipDistance/CullDistance builtin without
  7845. // requiring the ClipDistance/CullDistance capability, as long as we don't
  7846. // read or write the builtin variable.
  7847. // For our CodeGen, that corresponds to not seeing SV_ClipDistance or
  7848. // SV_CullDistance at all. If we see them, we will generate code to read
  7849. // them to initialize temporary variable for calling the source code entry
  7850. // function or write to them after calling the source code entry function.
  7851. declIdMapper.glPerVertex.requireCapabilityIfNecessary();
  7852. // The entry basic block.
  7853. const uint32_t entryLabel = theBuilder.createBasicBlock();
  7854. theBuilder.setInsertPoint(entryLabel);
  7855. // Initialize all global variables at the beginning of the wrapper
  7856. for (const VarDecl *varDecl : toInitGloalVars) {
  7857. const auto varInfo = declIdMapper.getDeclEvalInfo(varDecl);
  7858. if (const auto *init = varDecl->getInit()) {
  7859. storeValue(varInfo, doExpr(init), varDecl->getType());
  7860. // Update counter variable associated with global variables
  7861. tryToAssignCounterVar(varDecl, init);
  7862. }
  7863. // If not explicitly initialized, initialize with their zero values if not
  7864. // resource objects
  7865. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  7866. const auto typeId = typeTranslator.translateType(varDecl->getType());
  7867. theBuilder.createStore(varInfo, theBuilder.getConstantNull(typeId));
  7868. }
  7869. }
  7870. // Create temporary variables for holding function call arguments
  7871. llvm::SmallVector<uint32_t, 4> params;
  7872. for (const auto *param : decl->params()) {
  7873. const auto paramType = param->getType();
  7874. const uint32_t typeId = typeTranslator.translateType(paramType);
  7875. std::string tempVarName = "param.var." + param->getNameAsString();
  7876. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  7877. params.push_back(tempVar);
  7878. // Create the stage input variable for parameter not marked as pure out and
  7879. // initialize the corresponding temporary variable
  7880. // Also do not create input variables for output stream objects of geometry
  7881. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  7882. if (canActAsInParmVar(param)) {
  7883. if (shaderModel.IsHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  7884. // Record the temporary variable holding InputPatch. It may be used
  7885. // later in the patch constant function.
  7886. hullMainInputPatchParam = tempVar;
  7887. }
  7888. uint32_t loadedValue = 0;
  7889. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  7890. return false;
  7891. theBuilder.createStore(tempVar, loadedValue);
  7892. // Record the temporary variable holding SV_OutputControlPointID,
  7893. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  7894. // constant function.
  7895. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  7896. outputControlPointIdVal = loadedValue;
  7897. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  7898. primitiveIdVar = tempVar;
  7899. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  7900. viewIdVar = tempVar;
  7901. }
  7902. }
  7903. // Call the original entry function
  7904. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  7905. const uint32_t retVal =
  7906. theBuilder.createFunctionCall(retType, entryFuncId, params);
  7907. // Create and write stage output variables for return value. Special case for
  7908. // Hull shaders since they operate differently in 2 ways:
  7909. // 1- Their return value is in fact an array and each invocation should write
  7910. // to the proper offset in the array.
  7911. // 2- The patch constant function must be called *once* after all invocations
  7912. // of the main entry point function is done.
  7913. if (shaderModel.IsHS()) {
  7914. // Create stage output variables out of the return type.
  7915. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  7916. outputControlPointIdVal, retVal))
  7917. return false;
  7918. if (!processHSEntryPointOutputAndPCF(
  7919. decl, retType, retVal, numOutputControlPoints,
  7920. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  7921. hullMainInputPatchParam))
  7922. return false;
  7923. } else {
  7924. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  7925. return false;
  7926. }
  7927. // Create and write stage output variables for parameters marked as
  7928. // out/inout
  7929. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  7930. const auto *param = decl->getParamDecl(i);
  7931. if (canActAsOutParmVar(param)) {
  7932. // Load the value from the parameter after function call
  7933. const uint32_t typeId = typeTranslator.translateType(param->getType());
  7934. uint32_t loadedParam = 0;
  7935. // Write back of stage output variables in GS is manually controlled by
  7936. // .Append() intrinsic method. No need to load the parameter since we
  7937. // won't need to write back here.
  7938. if (!shaderModel.IsGS())
  7939. loadedParam = theBuilder.createLoad(typeId, params[i]);
  7940. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  7941. return false;
  7942. }
  7943. }
  7944. theBuilder.createReturn();
  7945. theBuilder.endFunction();
  7946. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  7947. // We should invoke a translation of the PCF manually.
  7948. if (shaderModel.IsHS())
  7949. doDecl(patchConstFunc);
  7950. return true;
  7951. }
  7952. bool SPIRVEmitter::processHSEntryPointOutputAndPCF(
  7953. const FunctionDecl *hullMainFuncDecl, uint32_t retType, uint32_t retVal,
  7954. uint32_t numOutputControlPoints, uint32_t outputControlPointId,
  7955. uint32_t primitiveId, uint32_t viewId, uint32_t hullMainInputPatch) {
  7956. // This method may only be called for Hull shaders.
  7957. assert(shaderModel.IsHS());
  7958. // For Hull shaders, the real output is an array of size
  7959. // numOutputControlPoints. The results of the main should be written to the
  7960. // correct offset in the array (based on InvocationID).
  7961. if (!numOutputControlPoints) {
  7962. emitError("number of output control points cannot be zero",
  7963. hullMainFuncDecl->getLocation());
  7964. return false;
  7965. }
  7966. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  7967. // is not provided.
  7968. if (!outputControlPointId) {
  7969. emitError(
  7970. "SV_OutputControlPointID semantic must be provided in hull shader",
  7971. hullMainFuncDecl->getLocation());
  7972. return false;
  7973. }
  7974. if (!patchConstFunc) {
  7975. emitError("patch constant function not defined in hull shader",
  7976. hullMainFuncDecl->getLocation());
  7977. return false;
  7978. }
  7979. uint32_t hullMainOutputPatch = 0;
  7980. // If the patch constant function (PCF) takes the result of the Hull main
  7981. // entry point, create a temporary function-scope variable and write the
  7982. // results to it, so it can be passed to the PCF.
  7983. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  7984. const uint32_t hullMainRetType = theBuilder.getArrayType(
  7985. retType, theBuilder.getConstantUint32(numOutputControlPoints));
  7986. hullMainOutputPatch =
  7987. theBuilder.addFnVar(hullMainRetType, "temp.var.hullMainRetVal");
  7988. const auto tempLocation = theBuilder.createAccessChain(
  7989. theBuilder.getPointerType(retType, spv::StorageClass::Function),
  7990. hullMainOutputPatch, {outputControlPointId});
  7991. theBuilder.createStore(tempLocation, retVal);
  7992. }
  7993. // Now create a barrier before calling the Patch Constant Function (PCF).
  7994. // Flags are:
  7995. // Execution Barrier scope = Workgroup (2)
  7996. // Memory Barrier scope = Device (1)
  7997. // Memory Semantics Barrier scope = None (0)
  7998. theBuilder.createBarrier(theBuilder.getConstantUint32(2),
  7999. theBuilder.getConstantUint32(1),
  8000. theBuilder.getConstantUint32(0));
  8001. // The PCF should be called only once. Therefore, we check the invocationID,
  8002. // and we only allow ID 0 to call the PCF.
  8003. const uint32_t condition = theBuilder.createBinaryOp(
  8004. spv::Op::OpIEqual, theBuilder.getBoolType(), outputControlPointId,
  8005. theBuilder.getConstantUint32(0));
  8006. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  8007. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  8008. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  8009. theBuilder.addSuccessor(thenBB);
  8010. theBuilder.addSuccessor(mergeBB);
  8011. theBuilder.setMergeTarget(mergeBB);
  8012. theBuilder.setInsertPoint(thenBB);
  8013. // Call the PCF. Since the function is not explicitly called, we must first
  8014. // register an ID for it.
  8015. const uint32_t pcfId = declIdMapper.getOrRegisterFnResultId(patchConstFunc);
  8016. const uint32_t pcfRetType =
  8017. typeTranslator.translateType(patchConstFunc->getReturnType());
  8018. std::vector<uint32_t> pcfParams;
  8019. // A lambda for creating a stage input variable and its associated temporary
  8020. // variable for function call. Also initializes the temporary variable using
  8021. // the contents loaded from the stage input variable. Returns the <result-id>
  8022. // of the temporary variable.
  8023. const auto createParmVarAndInitFromStageInputVar =
  8024. [this](const ParmVarDecl *param) {
  8025. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8026. std::string tempVarName = "param.var." + param->getNameAsString();
  8027. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8028. uint32_t loadedValue = 0;
  8029. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  8030. theBuilder.createStore(tempVar, loadedValue);
  8031. return tempVar;
  8032. };
  8033. for (const auto *param : patchConstFunc->parameters()) {
  8034. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  8035. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  8036. // necessarily mean that they are present. There is also no requirement
  8037. // for the order of parameters passed to PCF.
  8038. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8039. pcfParams.push_back(hullMainInputPatch);
  8040. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8041. pcfParams.push_back(hullMainOutputPatch);
  8042. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  8043. if (!primitiveId) {
  8044. primitiveId = createParmVarAndInitFromStageInputVar(param);
  8045. }
  8046. pcfParams.push_back(primitiveId);
  8047. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  8048. if (!viewId) {
  8049. viewId = createParmVarAndInitFromStageInputVar(param);
  8050. }
  8051. pcfParams.push_back(viewId);
  8052. } else {
  8053. emitError("patch constant function parameter '%0' unknown",
  8054. param->getLocation())
  8055. << param->getName();
  8056. }
  8057. }
  8058. const uint32_t pcfResultId =
  8059. theBuilder.createFunctionCall(pcfRetType, pcfId, {pcfParams});
  8060. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  8061. /*forPCF*/ true))
  8062. return false;
  8063. theBuilder.createBranch(mergeBB);
  8064. theBuilder.addSuccessor(mergeBB);
  8065. theBuilder.setInsertPoint(mergeBB);
  8066. return true;
  8067. }
  8068. bool SPIRVEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  8069. if (!root)
  8070. return false;
  8071. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8072. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8073. if (!caseStmt && !compoundStmt)
  8074. return true;
  8075. if (caseStmt) {
  8076. const Expr *caseExpr = caseStmt->getLHS();
  8077. return caseExpr && caseExpr->isEvaluatable(astContext);
  8078. }
  8079. // Recurse down if facing a compound statement.
  8080. for (auto *st : compoundStmt->body())
  8081. if (!allSwitchCasesAreIntegerLiterals(st))
  8082. return false;
  8083. return true;
  8084. }
  8085. void SPIRVEmitter::discoverAllCaseStmtInSwitchStmt(
  8086. const Stmt *root, uint32_t *defaultBB,
  8087. std::vector<std::pair<uint32_t, uint32_t>> *targets) {
  8088. if (!root)
  8089. return;
  8090. // A switch case can only appear in DefaultStmt, CaseStmt, or
  8091. // CompoundStmt. For the rest, we can just return.
  8092. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8093. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8094. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8095. if (!defaultStmt && !caseStmt && !compoundStmt)
  8096. return;
  8097. // Recurse down if facing a compound statement.
  8098. if (compoundStmt) {
  8099. for (auto *st : compoundStmt->body())
  8100. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  8101. return;
  8102. }
  8103. std::string caseLabel;
  8104. uint32_t caseValue = 0;
  8105. if (defaultStmt) {
  8106. // This is the default branch.
  8107. caseLabel = "switch.default";
  8108. } else if (caseStmt) {
  8109. // This is a non-default case.
  8110. // When using OpSwitch, we only allow integer literal cases. e.g:
  8111. // case <literal_integer>: {...; break;}
  8112. const Expr *caseExpr = caseStmt->getLHS();
  8113. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  8114. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  8115. if (bitWidth != 32)
  8116. emitError(
  8117. "non-32bit integer case value in switch statement unimplemented",
  8118. caseExpr->getExprLoc());
  8119. Expr::EvalResult evalResult;
  8120. caseExpr->EvaluateAsRValue(evalResult, astContext);
  8121. const int64_t value = evalResult.Val.getInt().getSExtValue();
  8122. caseValue = static_cast<uint32_t>(value);
  8123. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  8124. llvm::itostr(std::abs(value));
  8125. }
  8126. const uint32_t caseBB = theBuilder.createBasicBlock(caseLabel);
  8127. theBuilder.addSuccessor(caseBB);
  8128. stmtBasicBlock[root] = caseBB;
  8129. // Add all cases to the 'targets' vector.
  8130. if (caseStmt)
  8131. targets->emplace_back(caseValue, caseBB);
  8132. // The default label is not part of the 'targets' vector that is passed
  8133. // to the OpSwitch instruction.
  8134. // If default statement was discovered, return its label via defaultBB.
  8135. if (defaultStmt)
  8136. *defaultBB = caseBB;
  8137. // Process cases nested in other cases. It happens when we have fall through
  8138. // cases. For example:
  8139. // case 1: case 2: ...; break;
  8140. // will result in the CaseSmt for case 2 nested in the one for case 1.
  8141. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  8142. : defaultStmt->getSubStmt(),
  8143. defaultBB, targets);
  8144. }
  8145. void SPIRVEmitter::flattenSwitchStmtAST(const Stmt *root,
  8146. std::vector<const Stmt *> *flatSwitch) {
  8147. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8148. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8149. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8150. if (!compoundStmt) {
  8151. flatSwitch->push_back(root);
  8152. }
  8153. if (compoundStmt) {
  8154. for (const auto *st : compoundStmt->body())
  8155. flattenSwitchStmtAST(st, flatSwitch);
  8156. } else if (caseStmt) {
  8157. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  8158. } else if (defaultStmt) {
  8159. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  8160. }
  8161. }
  8162. void SPIRVEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  8163. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  8164. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  8165. assert(caseStmt || defaultStmt);
  8166. uint32_t caseBB = stmtBasicBlock[stmt];
  8167. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  8168. // We are about to handle the case passed in as parameter. If the current
  8169. // basic block is not terminated, it means the previous case is a fall
  8170. // through case. We need to link it to the case to be processed.
  8171. theBuilder.createBranch(caseBB);
  8172. theBuilder.addSuccessor(caseBB);
  8173. }
  8174. theBuilder.setInsertPoint(caseBB);
  8175. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  8176. }
  8177. void SPIRVEmitter::processSwitchStmtUsingSpirvOpSwitch(
  8178. const SwitchStmt *switchStmt) {
  8179. // First handle the condition variable DeclStmt if one exists.
  8180. // For example: handle 'int a = b' in the following:
  8181. // switch (int a = b) {...}
  8182. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8183. doDeclStmt(condVarDeclStmt);
  8184. const uint32_t selector = doExpr(switchStmt->getCond());
  8185. // We need a merge block regardless of the number of switch cases.
  8186. // Since OpSwitch always requires a default label, if the switch statement
  8187. // does not have a default branch, we use the merge block as the default
  8188. // target.
  8189. const uint32_t mergeBB = theBuilder.createBasicBlock("switch.merge");
  8190. theBuilder.setMergeTarget(mergeBB);
  8191. breakStack.push(mergeBB);
  8192. uint32_t defaultBB = mergeBB;
  8193. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  8194. std::vector<std::pair<uint32_t, uint32_t>> targets;
  8195. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  8196. // Create the OpSelectionMerge and OpSwitch.
  8197. theBuilder.createSwitch(mergeBB, selector, defaultBB, targets);
  8198. // Handle the switch body.
  8199. doStmt(switchStmt->getBody());
  8200. if (!theBuilder.isCurrentBasicBlockTerminated())
  8201. theBuilder.createBranch(mergeBB);
  8202. theBuilder.setInsertPoint(mergeBB);
  8203. breakStack.pop();
  8204. }
  8205. void SPIRVEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  8206. std::vector<const Stmt *> flatSwitch;
  8207. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  8208. // First handle the condition variable DeclStmt if one exists.
  8209. // For example: handle 'int a = b' in the following:
  8210. // switch (int a = b) {...}
  8211. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8212. doDeclStmt(condVarDeclStmt);
  8213. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  8214. // the flattened switch AST.
  8215. // For instance, for the following flat vector:
  8216. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8217. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  8218. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8219. // The indexes are: {0, 2, 5, 6, 9}
  8220. std::vector<uint32_t> caseStmtLocs;
  8221. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  8222. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  8223. caseStmtLocs.push_back(i);
  8224. IfStmt *prevIfStmt = nullptr;
  8225. IfStmt *rootIfStmt = nullptr;
  8226. CompoundStmt *defaultBody = nullptr;
  8227. // For each case, start at its index in the vector, and go forward
  8228. // accumulating statements until BreakStmt or end of vector is reached.
  8229. for (auto curCaseIndex : caseStmtLocs) {
  8230. const Stmt *curCase = flatSwitch[curCaseIndex];
  8231. // CompoundStmt to hold all statements for this case.
  8232. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  8233. // Accumulate all non-case/default/break statements as the body for the
  8234. // current case.
  8235. std::vector<Stmt *> statements;
  8236. for (int i = curCaseIndex + 1;
  8237. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  8238. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  8239. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  8240. }
  8241. if (!statements.empty())
  8242. cs->setStmts(astContext, statements.data(), statements.size());
  8243. // For non-default cases, generate the IfStmt that compares the switch
  8244. // value to the case value.
  8245. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  8246. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  8247. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  8248. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  8249. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  8250. bo->setOpcode(BO_EQ);
  8251. bo->setType(astContext.getLogicalOperationType());
  8252. curIf->setCond(bo);
  8253. curIf->setThen(cs);
  8254. // No conditional variable associated with this faux if statement.
  8255. curIf->setConditionVariable(astContext, nullptr);
  8256. // Each If statement is the "else" of the previous if statement.
  8257. if (prevIfStmt)
  8258. prevIfStmt->setElse(curIf);
  8259. else
  8260. rootIfStmt = curIf;
  8261. prevIfStmt = curIf;
  8262. } else {
  8263. // Record the DefaultStmt body as it will be used as the body of the
  8264. // "else" block in the if-elseif-...-else pattern.
  8265. defaultBody = cs;
  8266. }
  8267. }
  8268. // If a default case exists, it is the "else" of the last if statement.
  8269. if (prevIfStmt)
  8270. prevIfStmt->setElse(defaultBody);
  8271. // Since all else-if and else statements are the child nodes of the first
  8272. // IfStmt, we only need to call doStmt for the first IfStmt.
  8273. if (rootIfStmt)
  8274. doStmt(rootIfStmt);
  8275. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  8276. // no if statements. The switch in that case only executes the body of the
  8277. // default case.
  8278. else if (defaultBody)
  8279. doStmt(defaultBody);
  8280. }
  8281. uint32_t SPIRVEmitter::extractVecFromVec4(uint32_t fromId,
  8282. uint32_t targetVecSize,
  8283. uint32_t targetElemTypeId) {
  8284. assert(targetVecSize > 0 && targetVecSize < 5);
  8285. const uint32_t retType =
  8286. targetVecSize == 1
  8287. ? targetElemTypeId
  8288. : theBuilder.getVecType(targetElemTypeId, targetVecSize);
  8289. switch (targetVecSize) {
  8290. case 1:
  8291. return theBuilder.createCompositeExtract(retType, fromId, {0});
  8292. break;
  8293. case 2:
  8294. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1});
  8295. break;
  8296. case 3:
  8297. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1, 2});
  8298. break;
  8299. case 4:
  8300. return fromId;
  8301. default:
  8302. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  8303. }
  8304. }
  8305. } // end namespace spirv
  8306. } // end namespace clang