SPIRVEmitter.cpp 383 KB

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