HLOperationLower.cpp 269 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // HLOperationLower.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // Lower functions to lower HL operations to DXIL operations. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilModule.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  14. #include "dxc/HLSL/HLModule.h"
  15. #include "dxc/HLSL/DxilUtil.h"
  16. #include "dxc/HLSL/HLOperationLower.h"
  17. #include "dxc/HLSL/HLOperationLowerExtension.h"
  18. #include "dxc/HLSL/HLOperations.h"
  19. #include "dxc/HlslIntrinsicOp.h"
  20. #include "llvm/IR/GetElementPtrTypeIterator.h"
  21. #include "llvm/IR/IRBuilder.h"
  22. #include "llvm/IR/Instructions.h"
  23. #include "llvm/IR/Module.h"
  24. #include <unordered_set>
  25. using namespace llvm;
  26. using namespace hlsl;
  27. struct HLOperationLowerHelper {
  28. OP &hlslOP;
  29. Type *voidTy;
  30. Type *f32Ty;
  31. Type *i32Ty;
  32. llvm::Type *i1Ty;
  33. Type *i8Ty;
  34. DxilTypeSystem &dxilTypeSys;
  35. DxilFunctionProps *functionProps;
  36. bool bLegacyCBufferLoad;
  37. DataLayout dataLayout;
  38. HLOperationLowerHelper(HLModule &HLM);
  39. };
  40. HLOperationLowerHelper::HLOperationLowerHelper(HLModule &HLM)
  41. : hlslOP(*HLM.GetOP()), dxilTypeSys(HLM.GetTypeSystem()),
  42. dataLayout(DataLayout(HLM.GetHLOptions().bUseMinPrecision
  43. ? hlsl::DXIL::kLegacyLayoutString
  44. : hlsl::DXIL::kNewLayoutString)) {
  45. llvm::LLVMContext &Ctx = HLM.GetCtx();
  46. voidTy = Type::getVoidTy(Ctx);
  47. f32Ty = Type::getFloatTy(Ctx);
  48. i32Ty = Type::getInt32Ty(Ctx);
  49. i1Ty = Type::getInt1Ty(Ctx);
  50. i8Ty = Type::getInt8Ty(Ctx);
  51. Function *EntryFunc = HLM.GetEntryFunction();
  52. functionProps = nullptr;
  53. if (HLM.HasDxilFunctionProps(EntryFunc))
  54. functionProps = &HLM.GetDxilFunctionProps(EntryFunc);
  55. bLegacyCBufferLoad = HLM.GetHLOptions().bLegacyCBufferLoad;
  56. }
  57. struct HLObjectOperationLowerHelper {
  58. private:
  59. // For object intrinsics.
  60. HLModule &HLM;
  61. struct ResAttribute {
  62. DXIL::ResourceClass RC;
  63. DXIL::ResourceKind RK;
  64. Type *ResourceType;
  65. };
  66. std::unordered_map<Value *, ResAttribute> HandleMetaMap;
  67. std::unordered_set<LoadInst *> &UpdateCounterSet;
  68. std::unordered_set<Value *> &NonUniformSet;
  69. // Map from pointer of cbuffer to pointer of resource.
  70. // For cbuffer like this:
  71. // cbuffer A {
  72. // Texture2D T;
  73. // };
  74. // A global resource Texture2D T2 will be created for Texture2D T.
  75. // CBPtrToResourceMap[T] will return T2.
  76. std::unordered_map<Value *, Value *> CBPtrToResourceMap;
  77. public:
  78. HLObjectOperationLowerHelper(HLModule &HLM,
  79. std::unordered_set<LoadInst *> &UpdateCounter,
  80. std::unordered_set<Value *> &NonUniform)
  81. : HLM(HLM), UpdateCounterSet(UpdateCounter), NonUniformSet(NonUniform) {}
  82. DXIL::ResourceClass GetRC(Value *Handle) {
  83. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  84. return Res.RC;
  85. }
  86. DXIL::ResourceKind GetRK(Value *Handle) {
  87. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  88. return Res.RK;
  89. }
  90. Type *GetResourceType(Value *Handle) {
  91. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  92. return Res.ResourceType;
  93. }
  94. void MarkHasCounter(Type *Ty, Value *handle) {
  95. DXIL::ResourceClass RC = GetRC(handle);
  96. DXASSERT_LOCALVAR(RC, RC == DXIL::ResourceClass::UAV,
  97. "must UAV for counter");
  98. std::unordered_set<Value *> resSet;
  99. MarkHasCounterOnCreateHandle(handle, resSet);
  100. }
  101. void MarkNonUniform(Value *V) { NonUniformSet.insert(V); }
  102. Value *GetOrCreateResourceForCbPtr(GetElementPtrInst *CbPtr,
  103. GlobalVariable *CbGV, MDNode *MD) {
  104. // Change array idx to 0 to make sure all array ptr share same key.
  105. Value *Key = UniformCbPtr(CbPtr, CbGV);
  106. if (CBPtrToResourceMap.count(Key))
  107. return CBPtrToResourceMap[Key];
  108. Value *Resource = CreateResourceForCbPtr(CbPtr, CbGV, MD);
  109. CBPtrToResourceMap[Key] = Resource;
  110. return Resource;
  111. }
  112. Value *LowerCbResourcePtr(GetElementPtrInst *CbPtr, Value *ResPtr) {
  113. // Simple case.
  114. if (ResPtr->getType() == CbPtr->getType())
  115. return ResPtr;
  116. // Array case.
  117. DXASSERT_NOMSG(ResPtr->getType()->getPointerElementType()->isArrayTy());
  118. IRBuilder<> Builder(CbPtr);
  119. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  120. Value *arrayIdx = GEPIt.getOperand();
  121. // Only calc array idx and size.
  122. // Ignore struct type part.
  123. for (; GEPIt != E; ++GEPIt) {
  124. if (GEPIt->isArrayTy()) {
  125. arrayIdx = Builder.CreateMul(
  126. arrayIdx, Builder.getInt32(GEPIt->getArrayNumElements()));
  127. arrayIdx = Builder.CreateAdd(arrayIdx, GEPIt.getOperand());
  128. }
  129. }
  130. return Builder.CreateGEP(ResPtr, {Builder.getInt32(0), arrayIdx});
  131. }
  132. private:
  133. ResAttribute &FindCreateHandleResourceBase(Value *Handle) {
  134. if (HandleMetaMap.count(Handle))
  135. return HandleMetaMap[Handle];
  136. // Add invalid first to avoid dead loop.
  137. HandleMetaMap[Handle] = {DXIL::ResourceClass::Invalid,
  138. DXIL::ResourceKind::Invalid,
  139. StructType::get(Type::getVoidTy(HLM.GetCtx()))};
  140. if (Argument *Arg = dyn_cast<Argument>(Handle)) {
  141. MDNode *MD = HLM.GetDxilResourceAttrib(Arg);
  142. if (!MD) {
  143. Handle->getContext().emitError("cannot map resource to handle");
  144. return HandleMetaMap[Handle];
  145. }
  146. DxilResourceBase Res(DxilResource::Class::Invalid);
  147. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  148. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  149. Res.GetGlobalSymbol()->getType()};
  150. HandleMetaMap[Handle] = Attrib;
  151. return HandleMetaMap[Handle];
  152. }
  153. if (LoadInst *LI = dyn_cast<LoadInst>(Handle)) {
  154. Value *Ptr = LI->getPointerOperand();
  155. for (User *U : Ptr->users()) {
  156. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  157. DxilFunctionAnnotation *FnAnnot = HLM.GetFunctionAnnotation(CI->getCalledFunction());
  158. if (FnAnnot) {
  159. for (auto &arg : CI->arg_operands()) {
  160. if (arg == Ptr) {
  161. unsigned argNo = arg.getOperandNo();
  162. DxilParameterAnnotation &ParamAnnot = FnAnnot->GetParameterAnnotation(argNo);
  163. MDNode *MD = ParamAnnot.GetResourceAttribute();
  164. if (!MD) {
  165. Handle->getContext().emitError(
  166. "cannot map resource to handle");
  167. return HandleMetaMap[Handle];
  168. }
  169. DxilResourceBase Res(DxilResource::Class::Invalid);
  170. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  171. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  172. Res.GetGlobalSymbol()->getType()};
  173. HandleMetaMap[Handle] = Attrib;
  174. return HandleMetaMap[Handle];
  175. }
  176. }
  177. }
  178. }
  179. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  180. Value *V = SI->getValueOperand();
  181. ResAttribute Attrib = FindCreateHandleResourceBase(V);
  182. HandleMetaMap[Handle] = Attrib;
  183. return HandleMetaMap[Handle];
  184. }
  185. }
  186. // Cannot find.
  187. Handle->getContext().emitError("cannot map resource to handle");
  188. return HandleMetaMap[Handle];
  189. }
  190. if (CallInst *CI = dyn_cast<CallInst>(Handle)) {
  191. MDNode *MD = HLM.GetDxilResourceAttrib(CI->getCalledFunction());
  192. if (!MD) {
  193. Handle->getContext().emitError("cannot map resource to handle");
  194. return HandleMetaMap[Handle];
  195. }
  196. DxilResourceBase Res(DxilResource::Class::Invalid);
  197. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  198. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  199. Res.GetGlobalSymbol()->getType()};
  200. HandleMetaMap[Handle] = Attrib;
  201. return HandleMetaMap[Handle];
  202. }
  203. if (SelectInst *Sel = dyn_cast<SelectInst>(Handle)) {
  204. ResAttribute &ResT = FindCreateHandleResourceBase(Sel->getTrueValue());
  205. // Use MDT here, ResourceClass, ResourceID match is done at
  206. // DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect.
  207. HandleMetaMap[Handle] = ResT;
  208. FindCreateHandleResourceBase(Sel->getFalseValue());
  209. return ResT;
  210. }
  211. if (PHINode *Phi = dyn_cast<PHINode>(Handle)) {
  212. if (Phi->getNumOperands() == 0) {
  213. Handle->getContext().emitError("cannot map resource to handle");
  214. return HandleMetaMap[Handle];
  215. }
  216. ResAttribute &Res0 = FindCreateHandleResourceBase(Phi->getOperand(0));
  217. // Use Res0 here, ResourceClass, ResourceID match is done at
  218. // DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect.
  219. HandleMetaMap[Handle] = Res0;
  220. for (unsigned i = 1; i < Phi->getNumOperands(); i++) {
  221. FindCreateHandleResourceBase(Phi->getOperand(i));
  222. }
  223. return Res0;
  224. }
  225. Handle->getContext().emitError("cannot map resource to handle");
  226. return HandleMetaMap[Handle];
  227. }
  228. CallInst *FindCreateHandle(Value *handle,
  229. std::unordered_set<Value *> &resSet) {
  230. // Already checked.
  231. if (resSet.count(handle))
  232. return nullptr;
  233. resSet.insert(handle);
  234. if (CallInst *CI = dyn_cast<CallInst>(handle))
  235. return CI;
  236. if (SelectInst *Sel = dyn_cast<SelectInst>(handle)) {
  237. if (CallInst *CI = FindCreateHandle(Sel->getTrueValue(), resSet))
  238. return CI;
  239. if (CallInst *CI = FindCreateHandle(Sel->getFalseValue(), resSet))
  240. return CI;
  241. return nullptr;
  242. }
  243. if (PHINode *Phi = dyn_cast<PHINode>(handle)) {
  244. for (unsigned i = 0; i < Phi->getNumOperands(); i++) {
  245. if (CallInst *CI = FindCreateHandle(Phi->getOperand(i), resSet))
  246. return CI;
  247. }
  248. return nullptr;
  249. }
  250. return nullptr;
  251. }
  252. void MarkHasCounterOnCreateHandle(Value *handle,
  253. std::unordered_set<Value *> &resSet) {
  254. // Already checked.
  255. if (resSet.count(handle))
  256. return;
  257. resSet.insert(handle);
  258. if (CallInst *CI = dyn_cast<CallInst>(handle)) {
  259. Value *Res =
  260. CI->getArgOperand(HLOperandIndex::kCreateHandleResourceOpIdx);
  261. LoadInst *LdRes = dyn_cast<LoadInst>(Res);
  262. if (!LdRes) {
  263. CI->getContext().emitError(CI, "cannot map resource to handle");
  264. return;
  265. }
  266. UpdateCounterSet.insert(LdRes);
  267. return;
  268. }
  269. if (SelectInst *Sel = dyn_cast<SelectInst>(handle)) {
  270. MarkHasCounterOnCreateHandle(Sel->getTrueValue(), resSet);
  271. MarkHasCounterOnCreateHandle(Sel->getFalseValue(), resSet);
  272. }
  273. if (PHINode *Phi = dyn_cast<PHINode>(handle)) {
  274. for (unsigned i = 0; i < Phi->getNumOperands(); i++) {
  275. MarkHasCounterOnCreateHandle(Phi->getOperand(i), resSet);
  276. }
  277. }
  278. }
  279. Value *UniformCbPtr(GetElementPtrInst *CbPtr, GlobalVariable *CbGV) {
  280. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  281. std::vector<Value *> idxList(CbPtr->idx_begin(), CbPtr->idx_end());
  282. unsigned i = 0;
  283. IRBuilder<> Builder(HLM.GetCtx());
  284. Value *zero = Builder.getInt32(0);
  285. for (; GEPIt != E; ++GEPIt, ++i) {
  286. if (GEPIt->isArrayTy()) {
  287. // Change array idx to 0 to make sure all array ptr share same key.
  288. idxList[i] = zero;
  289. }
  290. }
  291. Value *Key = Builder.CreateInBoundsGEP(CbGV, idxList);
  292. return Key;
  293. }
  294. Value *CreateResourceForCbPtr(GetElementPtrInst *CbPtr, GlobalVariable *CbGV,
  295. MDNode *MD) {
  296. Type *CbTy = CbPtr->getPointerOperandType();
  297. DXASSERT_LOCALVAR(CbTy, CbTy == CbGV->getType(), "else arg not point to var");
  298. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  299. unsigned i = 0;
  300. IRBuilder<> Builder(HLM.GetCtx());
  301. unsigned arraySize = 1;
  302. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  303. std::string Name;
  304. for (; GEPIt != E; ++GEPIt, ++i) {
  305. if (GEPIt->isArrayTy()) {
  306. arraySize *= GEPIt->getArrayNumElements();
  307. } else if (GEPIt->isStructTy()) {
  308. DxilStructAnnotation *typeAnnot =
  309. typeSys.GetStructAnnotation(cast<StructType>(*GEPIt));
  310. DXASSERT_NOMSG(typeAnnot);
  311. unsigned idx = cast<ConstantInt>(GEPIt.getOperand())->getLimitedValue();
  312. DXASSERT_NOMSG(typeAnnot->GetNumFields() > idx);
  313. DxilFieldAnnotation &fieldAnnot = typeAnnot->GetFieldAnnotation(idx);
  314. if (!Name.empty())
  315. Name += ".";
  316. Name += fieldAnnot.GetFieldName();
  317. }
  318. }
  319. Type *Ty = CbPtr->getResultElementType();
  320. if (arraySize > 1) {
  321. Ty = ArrayType::get(Ty, arraySize);
  322. }
  323. return CreateResourceGV(Ty, Name, MD);
  324. }
  325. Value *CreateResourceGV(Type *Ty, StringRef Name, MDNode *MD) {
  326. Module &M = *HLM.GetModule();
  327. Constant *GV = M.getOrInsertGlobal(Name, Ty);
  328. // Create resource and set GV as globalSym.
  329. HLM.AddResourceWithGlobalVariableAndMDNode(GV, MD);
  330. return GV;
  331. }
  332. };
  333. using IntrinsicLowerFuncTy = Value *(CallInst *CI, IntrinsicOp IOP,
  334. DXIL::OpCode opcode,
  335. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated);
  336. struct IntrinsicLower {
  337. // Intrinsic opcode.
  338. IntrinsicOp IntriOpcode;
  339. // Lower function.
  340. IntrinsicLowerFuncTy &LowerFunc;
  341. // DXIL opcode if can direct map.
  342. DXIL::OpCode DxilOpcode;
  343. };
  344. // IOP intrinsics.
  345. namespace {
  346. Value *TrivialDxilOperation(Function *dxilFunc, OP::OpCode opcode, ArrayRef<Value *> refArgs,
  347. Type *Ty, Type *RetTy, OP *hlslOP,
  348. IRBuilder<> &Builder) {
  349. unsigned argNum = refArgs.size();
  350. std::vector<Value *> args = refArgs;
  351. if (Ty->isVectorTy()) {
  352. Value *retVal = llvm::UndefValue::get(RetTy);
  353. unsigned vecSize = Ty->getVectorNumElements();
  354. for (unsigned i = 0; i < vecSize; i++) {
  355. // Update vector args, skip known opcode arg.
  356. for (unsigned argIdx = HLOperandIndex::kUnaryOpSrc0Idx; argIdx < argNum;
  357. argIdx++) {
  358. if (refArgs[argIdx]->getType()->isVectorTy()) {
  359. Value *arg = refArgs[argIdx];
  360. args[argIdx] = Builder.CreateExtractElement(arg, i);
  361. }
  362. }
  363. Value *EltOP =
  364. Builder.CreateCall(dxilFunc, args, hlslOP->GetOpCodeName(opcode));
  365. retVal = Builder.CreateInsertElement(retVal, EltOP, i);
  366. }
  367. return retVal;
  368. } else {
  369. Value *retVal =
  370. Builder.CreateCall(dxilFunc, args, hlslOP->GetOpCodeName(opcode));
  371. return retVal;
  372. }
  373. }
  374. // Generates a DXIL operation over an overloaded type (Ty), returning a
  375. // RetTy value; when Ty is a vector, it will replicate per-element operations
  376. // into RetTy to rebuild it.
  377. Value *TrivialDxilOperation(OP::OpCode opcode, ArrayRef<Value *> refArgs,
  378. Type *Ty, Type *RetTy, OP *hlslOP,
  379. IRBuilder<> &Builder) {
  380. Type *EltTy = Ty->getScalarType();
  381. Function *dxilFunc = hlslOP->GetOpFunc(opcode, EltTy);
  382. return TrivialDxilOperation(dxilFunc, opcode, refArgs, Ty, RetTy, hlslOP, Builder);
  383. }
  384. Value *TrivialDxilOperation(OP::OpCode opcode, ArrayRef<Value *> refArgs,
  385. Type *Ty, Instruction *Inst, OP *hlslOP) {
  386. DXASSERT(refArgs.size() > 0, "else opcode isn't in signature");
  387. DXASSERT(refArgs[0] == nullptr,
  388. "else caller has already filled the value in");
  389. IRBuilder<> B(Inst);
  390. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  391. const_cast<llvm::Value **>(refArgs.data())[0] =
  392. opArg; // actually stack memory from caller
  393. return TrivialDxilOperation(opcode, refArgs, Ty, Inst->getType(), hlslOP, B);
  394. }
  395. Value *TrivialDxilUnaryOperationRet(OP::OpCode opcode, Value *src, Type *RetTy,
  396. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  397. Type *Ty = src->getType();
  398. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  399. Value *args[] = {opArg, src};
  400. return TrivialDxilOperation(opcode, args, Ty, RetTy, hlslOP, Builder);
  401. }
  402. Value *TrivialDxilUnaryOperation(OP::OpCode opcode, Value *src,
  403. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  404. return TrivialDxilUnaryOperationRet(opcode, src, src->getType(), hlslOP,
  405. Builder);
  406. }
  407. Value *TrivialDxilBinaryOperation(OP::OpCode opcode, Value *src0, Value *src1,
  408. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  409. Type *Ty = src0->getType();
  410. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  411. Value *args[] = {opArg, src0, src1};
  412. return TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  413. }
  414. Value *TrivialDxilTrinaryOperation(OP::OpCode opcode, Value *src0, Value *src1,
  415. Value *src2, hlsl::OP *hlslOP,
  416. IRBuilder<> &Builder) {
  417. Type *Ty = src0->getType();
  418. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  419. Value *args[] = {opArg, src0, src1, src2};
  420. return TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  421. }
  422. Value *TrivialUnaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  423. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  424. Value *src0 = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  425. IRBuilder<> Builder(CI);
  426. hlsl::OP *hlslOP = &helper.hlslOP;
  427. Value *retVal = TrivialDxilUnaryOperationRet(opcode, src0, CI->getType(), hlslOP, Builder);
  428. return retVal;
  429. }
  430. Value *TrivialBinaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  431. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  432. hlsl::OP *hlslOP = &helper.hlslOP;
  433. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  434. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  435. IRBuilder<> Builder(CI);
  436. Value *binOp =
  437. TrivialDxilBinaryOperation(opcode, src0, src1, hlslOP, Builder);
  438. return binOp;
  439. }
  440. Value *TrivialTrinaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  441. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  442. hlsl::OP *hlslOP = &helper.hlslOP;
  443. Value *src0 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  444. Value *src1 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  445. Value *src2 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  446. IRBuilder<> Builder(CI);
  447. Value *triOp =
  448. TrivialDxilTrinaryOperation(opcode, src0, src1, src2, hlslOP, Builder);
  449. return triOp;
  450. }
  451. Value *TrivialIsSpecialFloat(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  452. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  453. hlsl::OP *hlslOP = &helper.hlslOP;
  454. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  455. IRBuilder<> Builder(CI);
  456. Type *Ty = src->getType();
  457. Type *RetTy = Type::getInt1Ty(CI->getContext());
  458. if (Ty->isVectorTy())
  459. RetTy = VectorType::get(RetTy, Ty->getVectorNumElements());
  460. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  461. Value *args[] = {opArg, src};
  462. return TrivialDxilOperation(opcode, args, Ty, RetTy, hlslOP, Builder);
  463. }
  464. Value *TranslateNonUniformResourceIndex(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  465. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  466. for (User *U : CI->users()) {
  467. if (CastInst *I = dyn_cast<CastInst>(U)) {
  468. pObjHelper->MarkNonUniform(I);
  469. }
  470. }
  471. Value *V = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  472. pObjHelper->MarkNonUniform(V);
  473. CI->replaceAllUsesWith(V);
  474. return nullptr;
  475. }
  476. Value *TrivialBarrier(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  477. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  478. hlsl::OP *OP = &helper.hlslOP;
  479. Function *dxilFunc = OP->GetOpFunc(OP::OpCode::Barrier, CI->getType());
  480. Constant *opArg = OP->GetU32Const((unsigned)OP::OpCode::Barrier);
  481. unsigned uglobal = static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  482. unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  483. unsigned t = static_cast<unsigned>(DXIL::BarrierMode::SyncThreadGroup);
  484. // unsigned ut = static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  485. unsigned barrierMode;
  486. switch (IOP) {
  487. case IntrinsicOp::IOP_AllMemoryBarrier:
  488. barrierMode = uglobal | g;
  489. break;
  490. case IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  491. barrierMode = uglobal | g | t;
  492. break;
  493. case IntrinsicOp::IOP_GroupMemoryBarrier:
  494. barrierMode = g;
  495. break;
  496. case IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  497. barrierMode = g | t;
  498. break;
  499. case IntrinsicOp::IOP_DeviceMemoryBarrier:
  500. barrierMode = uglobal;
  501. break;
  502. case IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  503. barrierMode = uglobal | t;
  504. break;
  505. default:
  506. DXASSERT(0, "invalid opcode for barrier");
  507. break;
  508. }
  509. Value *src0 = OP->GetU32Const(static_cast<unsigned>(barrierMode));
  510. Value *args[] = {opArg, src0};
  511. IRBuilder<> Builder(CI);
  512. Builder.CreateCall(dxilFunc, args);
  513. return nullptr;
  514. }
  515. Value *TranslateD3DColorToUByte4(CallInst *CI, IntrinsicOp IOP,
  516. OP::OpCode opcode,
  517. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  518. hlsl::OP *hlslOP = &helper.hlslOP;
  519. IRBuilder<> Builder(CI);
  520. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  521. Type *Ty = val->getType();
  522. Constant *toByteConst = ConstantFP::get(Ty->getScalarType(), 255);
  523. if (Ty != Ty->getScalarType()) {
  524. toByteConst =
  525. ConstantVector::getSplat(Ty->getVectorNumElements(), toByteConst);
  526. }
  527. Value *byte4 = Builder.CreateFMul(toByteConst, val);
  528. byte4 =
  529. TrivialDxilUnaryOperation(OP::OpCode::Round_z, byte4, hlslOP, Builder);
  530. return Builder.CreateBitCast(byte4, CI->getType());
  531. }
  532. Value *TranslateAddUint64(CallInst *CI, IntrinsicOp IOP,
  533. OP::OpCode opcode,
  534. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  535. hlsl::OP *hlslOP = &helper.hlslOP;
  536. IRBuilder<> Builder(CI);
  537. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  538. Type *Ty = val->getType();
  539. VectorType *VT = dyn_cast<VectorType>(Ty);
  540. if (!VT) {
  541. CI->getContext().emitError(
  542. CI, "AddUint64 can only be applied to uint2 and uint4 operands");
  543. return UndefValue::get(Ty);
  544. }
  545. unsigned size = VT->getNumElements();
  546. if (size != 2 && size != 4) {
  547. CI->getContext().emitError(
  548. CI, "AddUint64 can only be applied to uint2 and uint4 operands");
  549. return UndefValue::get(Ty);
  550. }
  551. Value *op0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  552. Value *op1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  553. Value *RetVal = UndefValue::get(Ty);
  554. Function *AddC = hlslOP->GetOpFunc(DXIL::OpCode::UAddc, helper.i32Ty);
  555. Value *opArg = Builder.getInt32(static_cast<unsigned>(DXIL::OpCode::UAddc));
  556. for (unsigned i=0; i<size; i+=2) {
  557. Value *low0 = Builder.CreateExtractElement(op0, i);
  558. Value *low1 = Builder.CreateExtractElement(op1, i);
  559. Value *lowWithC = Builder.CreateCall(AddC, { opArg, low0, low1});
  560. Value *low = Builder.CreateExtractValue(lowWithC, 0);
  561. RetVal = Builder.CreateInsertElement(RetVal, low, i);
  562. Value *carry = Builder.CreateExtractValue(lowWithC, 1);
  563. // Ext i1 to i32
  564. carry = Builder.CreateZExt(carry, helper.i32Ty);
  565. Value *hi0 = Builder.CreateExtractElement(op0, i+1);
  566. Value *hi1 = Builder.CreateExtractElement(op1, i+1);
  567. Value *hi = Builder.CreateAdd(hi0, hi1);
  568. hi = Builder.CreateAdd(hi, carry);
  569. RetVal = Builder.CreateInsertElement(RetVal, hi, i+1);
  570. }
  571. return RetVal;
  572. }
  573. bool IsValidLoadInput(Value *V) {
  574. // Must be load input.
  575. // TODO: report this error on front-end
  576. if (!isa<CallInst>(V)) {
  577. V->getContext().emitError("attribute evaluation can only be done on values "
  578. "taken directly from inputs");
  579. return false;
  580. }
  581. CallInst *CI = cast<CallInst>(V);
  582. // Must be immediate.
  583. ConstantInt *opArg =
  584. cast<ConstantInt>(CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
  585. DXIL::OpCode op = static_cast<DXIL::OpCode>(opArg->getLimitedValue());
  586. if (op != DXIL::OpCode::LoadInput) {
  587. V->getContext().emitError("attribute evaluation can only be done on values "
  588. "taken directly from inputs");
  589. return false;
  590. }
  591. return true;
  592. }
  593. // Apply current shuffle vector mask on top of previous shuffle mask.
  594. // For example, if previous mask is (12,11,10,13) and current mask is (3,1,0,2)
  595. // new mask would be (13,11,12,10)
  596. Constant *AccumulateMask(Constant *curMask, Constant *prevMask) {
  597. if (curMask == nullptr) {
  598. return prevMask;
  599. }
  600. unsigned size = cast<VectorType>(curMask->getType())->getNumElements();
  601. SmallVector<uint32_t, 16> Elts;
  602. for (unsigned i = 0; i != size; ++i) {
  603. ConstantInt *Index = cast<ConstantInt>(curMask->getAggregateElement(i));
  604. ConstantInt *IVal =
  605. cast<ConstantInt>(prevMask->getAggregateElement(Index->getSExtValue()));
  606. Elts.emplace_back(IVal->getSExtValue());
  607. }
  608. return ConstantDataVector::get(curMask->getContext(), Elts);
  609. }
  610. Constant *GetLoadInputsForEvaluate(Value *V, std::vector<CallInst*> &loadList) {
  611. Constant *shufMask = nullptr;
  612. if (V->getType()->isVectorTy()) {
  613. // Must be insert element inst. Keeping track of masks for shuffle vector
  614. Value *Vec = V;
  615. while (ShuffleVectorInst *shuf = dyn_cast<ShuffleVectorInst>(Vec)) {
  616. shufMask = AccumulateMask(shufMask, shuf->getMask());
  617. Vec = shuf->getOperand(0);
  618. }
  619. // TODO: We are assuming that the operand of insertelement is a LoadInput.
  620. // This will fail on the case where we pass in matrix member using array subscript.
  621. while (!isa<UndefValue>(Vec)) {
  622. InsertElementInst *insertInst = cast<InsertElementInst>(Vec);
  623. Vec = insertInst->getOperand(0);
  624. Value *Elt = insertInst->getOperand(1);
  625. if (IsValidLoadInput(Elt)) {
  626. loadList.emplace_back(cast<CallInst>(Elt));
  627. }
  628. }
  629. } else {
  630. if (IsValidLoadInput(V)) {
  631. loadList.emplace_back(cast<CallInst>(V));
  632. }
  633. }
  634. return shufMask;
  635. }
  636. // Swizzle could reduce the dimensionality of the Type, but
  637. // for temporary insertelement instructions should maintain the existing size of the loadinput.
  638. // So we have to analyze the type of src in order to determine the actual size required.
  639. Type *GetInsertElementTypeForEvaluate(Value *src) {
  640. if (InsertElementInst *IE = dyn_cast<InsertElementInst>(src)) {
  641. return src->getType();
  642. }
  643. else if (ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(src)) {
  644. return SV->getOperand(0)->getType();
  645. }
  646. src->getContext().emitError("Invalid type call for EvaluateAttribute function");
  647. return nullptr;
  648. }
  649. Value *TranslateEvalSample(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  650. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  651. hlsl::OP *hlslOP = &helper.hlslOP;
  652. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  653. Value *sampleIdx = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  654. IRBuilder<> Builder(CI);
  655. std::vector<CallInst*> loadList;
  656. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  657. unsigned size = loadList.size();
  658. OP::OpCode opcode = OP::OpCode::EvalSampleIndex;
  659. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  660. Type *Ty = GetInsertElementTypeForEvaluate(val);
  661. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  662. Value *result = UndefValue::get(Ty);
  663. for (unsigned i = 0; i < size; i++) {
  664. CallInst *loadInput = loadList[size-1-i];
  665. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  666. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  667. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  668. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, sampleIdx });
  669. result = Builder.CreateInsertElement(result, Elt, i);
  670. }
  671. if (shufMask)
  672. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  673. return result;
  674. }
  675. Value *TranslateEvalSnapped(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  676. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  677. hlsl::OP *hlslOP = &helper.hlslOP;
  678. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  679. Value *offset = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  680. IRBuilder<> Builder(CI);
  681. Value *offsetX = Builder.CreateExtractElement(offset, (uint64_t)0);
  682. Value *offsetY = Builder.CreateExtractElement(offset, 1);
  683. std::vector<CallInst*> loadList;
  684. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  685. unsigned size = loadList.size();
  686. OP::OpCode opcode = OP::OpCode::EvalSnapped;
  687. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  688. Type *Ty = GetInsertElementTypeForEvaluate(val);
  689. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  690. Value *result = UndefValue::get(Ty);
  691. for (unsigned i = 0; i < size; i++) {
  692. CallInst *loadInput = loadList[size-1-i];
  693. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  694. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  695. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  696. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, offsetX, offsetY });
  697. result = Builder.CreateInsertElement(result, Elt, i);
  698. }
  699. if (shufMask)
  700. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  701. return result;
  702. }
  703. Value *TranslateEvalCentroid(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  704. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  705. hlsl::OP *hlslOP = &helper.hlslOP;
  706. Value *src = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  707. std::vector<CallInst*> loadList;
  708. Constant *shufMask = GetLoadInputsForEvaluate(src, loadList);
  709. unsigned size = loadList.size();
  710. IRBuilder<> Builder(CI);
  711. OP::OpCode opcode = OP::OpCode::EvalCentroid;
  712. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  713. Type *Ty = GetInsertElementTypeForEvaluate(src);
  714. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  715. Value *result = UndefValue::get(Ty);
  716. for (unsigned i = 0; i < size; i++) {
  717. CallInst *loadInput = loadList[size-1-i];
  718. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  719. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  720. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  721. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx });
  722. result = Builder.CreateInsertElement(result, Elt, i);
  723. }
  724. if (shufMask)
  725. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  726. return result;
  727. }
  728. Value *TranslateGetAttributeAtVertex(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  729. HLOperationLowerHelper &helper,
  730. HLObjectOperationLowerHelper *pObjHelper,
  731. bool &Translated) {
  732. DXASSERT(op == OP::OpCode::AttributeAtVertex, "Wrong opcode to translate");
  733. hlsl::OP *hlslOP = &helper.hlslOP;
  734. IRBuilder<> Builder(CI);
  735. Type *Ty = CI->getType();
  736. Value *val = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc0OpIdx);
  737. Value *vertexIdx = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc1OpIdx);
  738. Value *vertexI8Idx = Builder.CreateTrunc(vertexIdx, Type::getInt8Ty(CI->getContext()));
  739. // Check the range of VertexID
  740. Value *vertex0 = Builder.getInt8(0);
  741. Value *vertex1 = Builder.getInt8(1);
  742. Value *vertex2 = Builder.getInt8(2);
  743. if (vertexI8Idx != vertex0 && vertexI8Idx != vertex1 && vertexI8Idx != vertex2) {
  744. CI->getContext().emitError(CI, "VertexID at GetAttributeAtVertex can only range from 0 to 2");
  745. return UndefValue::get(Ty);
  746. }
  747. std::vector<CallInst*> loadList;
  748. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  749. unsigned size = loadList.size();
  750. Value *opArg = hlslOP->GetU32Const((unsigned)op);
  751. Function *evalFunc = hlslOP->GetOpFunc(op, Ty->getScalarType());
  752. Value *result = UndefValue::get(Ty);
  753. for (unsigned i = 0; i < size; ++i) {
  754. CallInst *loadInput = loadList[size - 1 - i];
  755. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  756. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  757. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  758. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, vertexI8Idx });
  759. result = Builder.CreateInsertElement(result, Elt, i);
  760. }
  761. if (shufMask)
  762. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  763. return result;
  764. }
  765. Value *TrivialNoArgOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  766. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  767. hlsl::OP *hlslOP = &helper.hlslOP;
  768. Type *Ty = Type::getVoidTy(CI->getContext());
  769. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  770. Value *args[] = {opArg};
  771. IRBuilder<> Builder(CI);
  772. Value *dxilOp = TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  773. return dxilOp;
  774. }
  775. Value *TranslateGetRTSamplePos(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  776. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  777. hlsl::OP *hlslOP = &helper.hlslOP;
  778. OP::OpCode opcode = OP::OpCode::RenderTargetGetSamplePosition;
  779. IRBuilder<> Builder(CI);
  780. Type *Ty = Type::getVoidTy(CI->getContext());
  781. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  782. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  783. Value *args[] = {opArg, val};
  784. Value *samplePos =
  785. TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  786. Value *result = UndefValue::get(CI->getType());
  787. Value *samplePosX = Builder.CreateExtractValue(samplePos, 0);
  788. Value *samplePosY = Builder.CreateExtractValue(samplePos, 1);
  789. result = Builder.CreateInsertElement(result, samplePosX, (uint64_t)0);
  790. result = Builder.CreateInsertElement(result, samplePosY, 1);
  791. return result;
  792. }
  793. // val QuadReadLaneAt(val, uint);
  794. Value *TranslateQuadReadLaneAt(CallInst *CI, IntrinsicOp IOP,
  795. OP::OpCode opcode,
  796. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  797. hlsl::OP *hlslOP = &helper.hlslOP;
  798. Value *refArgs[] = {nullptr, CI->getOperand(1), CI->getOperand(2)};
  799. return TrivialDxilOperation(DXIL::OpCode::QuadReadLaneAt, refArgs,
  800. CI->getOperand(1)->getType(), CI, hlslOP);
  801. }
  802. // Wave intrinsics of the form fn(val,QuadOpKind)->val
  803. Value *TranslateQuadReadAcross(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  804. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  805. hlsl::OP *hlslOP = &helper.hlslOP;
  806. DXIL::QuadOpKind opKind;
  807. switch (IOP) {
  808. case IntrinsicOp::IOP_QuadReadAcrossX: opKind = DXIL::QuadOpKind::ReadAcrossX; break;
  809. case IntrinsicOp::IOP_QuadReadAcrossY: opKind = DXIL::QuadOpKind::ReadAcrossY; break;
  810. default: DXASSERT_NOMSG(IOP == IntrinsicOp::IOP_QuadReadAcrossDiagonal);
  811. case IntrinsicOp::IOP_QuadReadAcrossDiagonal: opKind = DXIL::QuadOpKind::ReadAcrossDiagonal; break;
  812. }
  813. Constant *OpArg = hlslOP->GetI8Const((unsigned)opKind);
  814. Value *refArgs[] = {nullptr, CI->getOperand(1), OpArg};
  815. return TrivialDxilOperation(DXIL::OpCode::QuadOp, refArgs,
  816. CI->getOperand(1)->getType(), CI, hlslOP);
  817. }
  818. // WaveAllEqual(val<n>)->bool<n>
  819. Value *TranslateWaveAllEqual(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  820. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  821. hlsl::OP *hlslOP = &helper.hlslOP;
  822. Value *src = CI->getArgOperand(HLOperandIndex::kWaveAllEqualValueOpIdx);
  823. IRBuilder<> Builder(CI);
  824. Type *Ty = src->getType();
  825. Type *RetTy = Type::getInt1Ty(CI->getContext());
  826. if (Ty->isVectorTy())
  827. RetTy = VectorType::get(RetTy, Ty->getVectorNumElements());
  828. Constant *opArg = hlslOP->GetU32Const((unsigned)DXIL::OpCode::WaveActiveAllEqual);
  829. Value *args[] = {opArg, src};
  830. return TrivialDxilOperation(DXIL::OpCode::WaveActiveAllEqual, args, Ty, RetTy,
  831. hlslOP, Builder);
  832. }
  833. // Wave intrinsics of the form fn(valA)->valB, where no overloading takes place
  834. Value *TranslateWaveA2B(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  835. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  836. hlsl::OP *hlslOP = &helper.hlslOP;
  837. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  838. return TrivialDxilOperation(opcode, refArgs, helper.voidTy, CI, hlslOP);
  839. }
  840. // Wave ballot intrinsic.
  841. Value *TranslateWaveBallot(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  842. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  843. // The high-level operation is uint4 ballot(i1).
  844. // The DXIL operation is struct.u4 ballot(i1).
  845. // To avoid updating users with more than a simple replace, we translate into
  846. // a call into struct.u4, then reassemble the vector.
  847. // Scalarization and constant propagation take care of cleanup.
  848. IRBuilder<> B(CI);
  849. // Make the DXIL call itself.
  850. hlsl::OP *hlslOP = &helper.hlslOP;
  851. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  852. Value *refArgs[] = { opArg, CI->getOperand(1) };
  853. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  854. Value *dxilVal = B.CreateCall(dxilFunc, refArgs, hlslOP->GetOpCodeName(opcode));
  855. // Assign from the call results into a vector.
  856. Type *ResTy = CI->getType();
  857. DXASSERT_NOMSG(ResTy->isVectorTy() && ResTy->getVectorNumElements() == 4);
  858. DXASSERT_NOMSG(dxilVal->getType()->isStructTy() &&
  859. dxilVal->getType()->getNumContainedTypes() == 4);
  860. // 'x' component is the first vector element, highest bits.
  861. Value *ResVal = llvm::UndefValue::get(ResTy);
  862. for (unsigned Idx = 0; Idx < 4; ++Idx) {
  863. ResVal = B.CreateInsertElement(
  864. ResVal, B.CreateExtractValue(dxilVal, ArrayRef<unsigned>(Idx)), Idx);
  865. }
  866. return ResVal;
  867. }
  868. static bool WaveIntrinsicNeedsSign(OP::OpCode opcode) {
  869. return opcode == OP::OpCode::WaveActiveOp ||
  870. opcode == OP::OpCode::WavePrefixOp;
  871. }
  872. static unsigned WaveIntrinsicToSignedOpKind(IntrinsicOp IOP) {
  873. if (IOP == IntrinsicOp::IOP_WaveActiveUMax ||
  874. IOP == IntrinsicOp::IOP_WaveActiveUMin ||
  875. IOP == IntrinsicOp::IOP_WaveActiveUSum ||
  876. IOP == IntrinsicOp::IOP_WaveActiveUProduct ||
  877. IOP == IntrinsicOp::IOP_WavePrefixUSum ||
  878. IOP == IntrinsicOp::IOP_WavePrefixUProduct)
  879. return (unsigned)DXIL::SignedOpKind::Unsigned;
  880. return (unsigned)DXIL::SignedOpKind::Signed;
  881. }
  882. static unsigned WaveIntrinsicToOpKind(IntrinsicOp IOP) {
  883. switch (IOP) {
  884. // Bit operations.
  885. case IntrinsicOp::IOP_WaveActiveBitOr:
  886. return (unsigned)DXIL::WaveBitOpKind::Or;
  887. case IntrinsicOp::IOP_WaveActiveBitAnd:
  888. return (unsigned)DXIL::WaveBitOpKind::And;
  889. case IntrinsicOp::IOP_WaveActiveBitXor:
  890. return (unsigned)DXIL::WaveBitOpKind::Xor;
  891. // Prefix operations.
  892. case IntrinsicOp::IOP_WavePrefixSum:
  893. case IntrinsicOp::IOP_WavePrefixUSum:
  894. return (unsigned)DXIL::WaveOpKind::Sum;
  895. case IntrinsicOp::IOP_WavePrefixProduct:
  896. case IntrinsicOp::IOP_WavePrefixUProduct:
  897. return (unsigned)DXIL::WaveOpKind::Product;
  898. // Numeric operations.
  899. case IntrinsicOp::IOP_WaveActiveMax:
  900. case IntrinsicOp::IOP_WaveActiveUMax:
  901. return (unsigned)DXIL::WaveOpKind::Max;
  902. case IntrinsicOp::IOP_WaveActiveMin:
  903. case IntrinsicOp::IOP_WaveActiveUMin:
  904. return (unsigned)DXIL::WaveOpKind::Min;
  905. case IntrinsicOp::IOP_WaveActiveSum:
  906. case IntrinsicOp::IOP_WaveActiveUSum:
  907. return (unsigned)DXIL::WaveOpKind::Sum;
  908. case IntrinsicOp::IOP_WaveActiveProduct:
  909. case IntrinsicOp::IOP_WaveActiveUProduct:
  910. default:
  911. DXASSERT(IOP == IntrinsicOp::IOP_WaveActiveProduct ||
  912. IOP == IntrinsicOp::IOP_WaveActiveUProduct,
  913. "else caller passed incorrect value");
  914. return (unsigned)DXIL::WaveOpKind::Product;
  915. }
  916. }
  917. // Wave intrinsics of the form fn(valA)->valA
  918. Value *TranslateWaveA2A(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  919. HLOperationLowerHelper &helper,
  920. HLObjectOperationLowerHelper *pObjHelper,
  921. bool &Translated) {
  922. hlsl::OP *hlslOP = &helper.hlslOP;
  923. Constant *kindValInt = hlslOP->GetI8Const(WaveIntrinsicToOpKind(IOP));
  924. Constant *signValInt = hlslOP->GetI8Const(WaveIntrinsicToSignedOpKind(IOP));
  925. Value *refArgs[] = {nullptr, CI->getOperand(1), kindValInt, signValInt};
  926. unsigned refArgCount = _countof(refArgs);
  927. if (!WaveIntrinsicNeedsSign(opcode))
  928. refArgCount--;
  929. return TrivialDxilOperation(opcode,
  930. llvm::ArrayRef<Value *>(refArgs, refArgCount),
  931. CI->getOperand(1)->getType(), CI, hlslOP);
  932. }
  933. // Wave intrinsics of the form fn()->val
  934. Value *TranslateWaveToVal(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  935. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  936. hlsl::OP *hlslOP = &helper.hlslOP;
  937. Value *refArgs[] = {nullptr};
  938. return TrivialDxilOperation(opcode, refArgs, helper.voidTy, CI, hlslOP);
  939. }
  940. // Wave intrinsics of the form fn(val,lane)->val
  941. Value *TranslateWaveReadLaneAt(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  942. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  943. hlsl::OP *hlslOP = &helper.hlslOP;
  944. Value *refArgs[] = {nullptr, CI->getOperand(1), CI->getOperand(2)};
  945. return TrivialDxilOperation(DXIL::OpCode::WaveReadLaneAt, refArgs,
  946. CI->getOperand(1)->getType(), CI, hlslOP);
  947. }
  948. // Wave intrinsics of the form fn(val)->val
  949. Value *TranslateWaveReadLaneFirst(CallInst *CI, IntrinsicOp IOP,
  950. OP::OpCode opcode,
  951. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  952. hlsl::OP *hlslOP = &helper.hlslOP;
  953. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  954. return TrivialDxilOperation(DXIL::OpCode::WaveReadLaneFirst, refArgs,
  955. CI->getOperand(1)->getType(), CI, hlslOP);
  956. }
  957. Value *TranslateIAbs(CallInst *CI) {
  958. Type *Ty = CI->getType();
  959. Type *EltTy = Ty->getScalarType();
  960. unsigned bitWidth = EltTy->getIntegerBitWidth();
  961. uint64_t mask = ((uint64_t)1) << (bitWidth - 1);
  962. Constant *opMask = ConstantInt::get(EltTy, mask);
  963. if (Ty != EltTy) {
  964. unsigned size = Ty->getVectorNumElements();
  965. opMask = llvm::ConstantVector::getSplat(size, opMask);
  966. }
  967. IRBuilder<> Builder(CI);
  968. return Builder.CreateXor(CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx),
  969. opMask);
  970. }
  971. Value *TransalteAbs(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  972. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  973. hlsl::OP *hlslOP = &helper.hlslOP;
  974. Type *pOverloadTy = CI->getType()->getScalarType();
  975. if (pOverloadTy->isFloatingPointTy()) {
  976. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  977. return TrivialDxilOperation(DXIL::OpCode::FAbs, refArgs, CI->getType(), CI,
  978. hlslOP);
  979. } else
  980. return TranslateIAbs(CI);
  981. }
  982. Value *GenerateCmpNEZero(Value *val, IRBuilder<> Builder) {
  983. Type *Ty = val->getType();
  984. Type *EltTy = Ty->getScalarType();
  985. Constant *zero = nullptr;
  986. if (EltTy->isFloatingPointTy())
  987. zero = ConstantFP::get(EltTy, 0);
  988. else
  989. zero = ConstantInt::get(EltTy, 0);
  990. if (Ty != EltTy) {
  991. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  992. }
  993. if (EltTy->isFloatingPointTy())
  994. return Builder.CreateFCmpUNE(val, zero);
  995. else
  996. return Builder.CreateICmpNE(val, zero);
  997. }
  998. Value *TranslateAllForValue(Value *val, IRBuilder<> &Builder) {
  999. Value *cond = GenerateCmpNEZero(val, Builder);
  1000. Type *Ty = val->getType();
  1001. Type *EltTy = Ty->getScalarType();
  1002. if (Ty != EltTy) {
  1003. Value *Result = Builder.CreateExtractElement(cond, (uint64_t)0);
  1004. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  1005. Value *Elt = Builder.CreateExtractElement(cond, i);
  1006. Result = Builder.CreateAnd(Result, Elt);
  1007. }
  1008. return Result;
  1009. } else
  1010. return cond;
  1011. }
  1012. Value *TranslateAll(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1013. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1014. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1015. IRBuilder<> Builder(CI);
  1016. return TranslateAllForValue(val, Builder);
  1017. }
  1018. Value *TranslateAny(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1019. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1020. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1021. IRBuilder<> Builder(CI);
  1022. Value *cond = GenerateCmpNEZero(val, Builder);
  1023. Type *Ty = val->getType();
  1024. Type *EltTy = Ty->getScalarType();
  1025. if (Ty != EltTy) {
  1026. Value *Result = Builder.CreateExtractElement(cond, (uint64_t)0);
  1027. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  1028. Value *Elt = Builder.CreateExtractElement(cond, i);
  1029. Result = Builder.CreateOr(Result, Elt);
  1030. }
  1031. return Result;
  1032. } else
  1033. return cond;
  1034. }
  1035. Value *TranslateBitcast(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1036. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1037. Type *Ty = CI->getType();
  1038. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1039. IRBuilder<> Builder(CI);
  1040. return Builder.CreateBitCast(op, Ty);
  1041. }
  1042. Value *TranslateDoubleAsUint(Value *x, Value *lo, Value *hi,
  1043. IRBuilder<> &Builder, hlsl::OP *hlslOP) {
  1044. Type *Ty = x->getType();
  1045. Type *outTy = lo->getType()->getPointerElementType();
  1046. DXIL::OpCode opcode = DXIL::OpCode::SplitDouble;
  1047. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  1048. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(opcode));
  1049. if (Ty->isVectorTy()) {
  1050. Value *retValLo = llvm::UndefValue::get(outTy);
  1051. Value *retValHi = llvm::UndefValue::get(outTy);
  1052. unsigned vecSize = Ty->getVectorNumElements();
  1053. for (unsigned i = 0; i < vecSize; i++) {
  1054. Value *Elt = Builder.CreateExtractElement(x, i);
  1055. Value *EltOP = Builder.CreateCall(dxilFunc, {opArg, Elt},
  1056. hlslOP->GetOpCodeName(opcode));
  1057. Value *EltLo = Builder.CreateExtractValue(EltOP, 0);
  1058. retValLo = Builder.CreateInsertElement(retValLo, EltLo, i);
  1059. Value *EltHi = Builder.CreateExtractValue(EltOP, 1);
  1060. retValHi = Builder.CreateInsertElement(retValHi, EltHi, i);
  1061. }
  1062. Builder.CreateStore(retValLo, lo);
  1063. Builder.CreateStore(retValHi, hi);
  1064. } else {
  1065. Value *retVal =
  1066. Builder.CreateCall(dxilFunc, {opArg, x}, hlslOP->GetOpCodeName(opcode));
  1067. Value *retValLo = Builder.CreateExtractValue(retVal, 0);
  1068. Value *retValHi = Builder.CreateExtractValue(retVal, 1);
  1069. Builder.CreateStore(retValLo, lo);
  1070. Builder.CreateStore(retValHi, hi);
  1071. }
  1072. return nullptr;
  1073. }
  1074. Value *TranslateAsUint(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1075. HLOperationLowerHelper &helper,
  1076. HLObjectOperationLowerHelper *pObjHelper,
  1077. bool &Translated) {
  1078. if (CI->getNumArgOperands() == 2) {
  1079. return TranslateBitcast(CI, IOP, opcode, helper, pObjHelper, Translated);
  1080. } else {
  1081. DXASSERT_NOMSG(CI->getNumArgOperands() == 4);
  1082. hlsl::OP *hlslOP = &helper.hlslOP;
  1083. Value *x = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1084. DXASSERT_NOMSG(x->getType()->getScalarType()->isDoubleTy());
  1085. Value *lo = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1086. Value *hi = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1087. IRBuilder<> Builder(CI);
  1088. return TranslateDoubleAsUint(x, lo, hi, Builder, hlslOP);
  1089. }
  1090. }
  1091. Value *TranslateAsDouble(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1092. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1093. hlsl::OP *hlslOP = &helper.hlslOP;
  1094. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1095. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1096. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(opcode));
  1097. IRBuilder<> Builder(CI);
  1098. return TrivialDxilOperation(opcode, { opArg, x, y }, CI->getType(), CI->getType(), hlslOP, Builder);
  1099. }
  1100. Value *TranslateAtan2(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1101. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1102. hlsl::OP *hlslOP = &helper.hlslOP;
  1103. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1104. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1105. IRBuilder<> Builder(CI);
  1106. Value *tan = Builder.CreateFDiv(y, x);
  1107. return TrivialDxilUnaryOperation(OP::OpCode::Atan, tan, hlslOP, Builder);
  1108. }
  1109. Value *TranslateClamp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1110. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1111. hlsl::OP *hlslOP = &helper.hlslOP;
  1112. Type *Ty = CI->getType();
  1113. Type *EltTy = Ty->getScalarType();
  1114. DXIL::OpCode maxOp = DXIL::OpCode::FMax;
  1115. DXIL::OpCode minOp = DXIL::OpCode::FMin;
  1116. if (IOP == IntrinsicOp::IOP_uclamp) {
  1117. maxOp = DXIL::OpCode::UMax;
  1118. minOp = DXIL::OpCode::UMin;
  1119. } else if (EltTy->isIntegerTy()) {
  1120. maxOp = DXIL::OpCode::IMax;
  1121. minOp = DXIL::OpCode::IMin;
  1122. }
  1123. Value *x = CI->getArgOperand(HLOperandIndex::kClampOpXIdx);
  1124. Value *maxVal = CI->getArgOperand(HLOperandIndex::kClampOpMaxIdx);
  1125. Value *minVal = CI->getArgOperand(HLOperandIndex::kClampOpMinIdx);
  1126. IRBuilder<> Builder(CI);
  1127. // min(max(x, minVal), maxVal).
  1128. Value *maxXMinVal =
  1129. TrivialDxilBinaryOperation(maxOp, x, minVal, hlslOP, Builder);
  1130. return TrivialDxilBinaryOperation(minOp, maxXMinVal, maxVal, hlslOP, Builder);
  1131. }
  1132. Value *TranslateClip(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1133. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1134. hlsl::OP *hlslOP = &helper.hlslOP;
  1135. Function *discard =
  1136. hlslOP->GetOpFunc(OP::OpCode::Discard, Type::getVoidTy(CI->getContext()));
  1137. IRBuilder<> Builder(CI);
  1138. Value *cond = nullptr;
  1139. Value *arg = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1140. if (VectorType *VT = dyn_cast<VectorType>(arg->getType())) {
  1141. Value *elt = Builder.CreateExtractElement(arg, (uint64_t)0);
  1142. cond = Builder.CreateFCmpOLT(elt, hlslOP->GetFloatConst(0));
  1143. for (unsigned i = 1; i < VT->getNumElements(); i++) {
  1144. Value *elt = Builder.CreateExtractElement(arg, i);
  1145. Value *eltCond = Builder.CreateFCmpOLT(elt, hlslOP->GetFloatConst(0));
  1146. cond = Builder.CreateOr(cond, eltCond);
  1147. }
  1148. } else
  1149. cond = Builder.CreateFCmpOLT(arg, hlslOP->GetFloatConst(0));
  1150. Constant *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::Discard);
  1151. Builder.CreateCall(discard, {opArg, cond});
  1152. return nullptr;
  1153. }
  1154. Value *TranslateCross(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1155. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1156. VectorType *VT = cast<VectorType>(CI->getType());
  1157. DXASSERT_NOMSG(VT->getNumElements() == 3);
  1158. Value *op0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1159. Value *op1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1160. IRBuilder<> Builder(CI);
  1161. Value *op0_x = Builder.CreateExtractElement(op0, (uint64_t)0);
  1162. Value *op0_y = Builder.CreateExtractElement(op0, 1);
  1163. Value *op0_z = Builder.CreateExtractElement(op0, 2);
  1164. Value *op1_x = Builder.CreateExtractElement(op1, (uint64_t)0);
  1165. Value *op1_y = Builder.CreateExtractElement(op1, 1);
  1166. Value *op1_z = Builder.CreateExtractElement(op1, 2);
  1167. auto MulSub = [&](Value *x0, Value *y0, Value *x1, Value *y1) -> Value * {
  1168. Value *xy = Builder.CreateFMul(x0, y1);
  1169. Value *yx = Builder.CreateFMul(y0, x1);
  1170. return Builder.CreateFSub(xy, yx);
  1171. };
  1172. Value *yz_zy = MulSub(op0_y, op0_z, op1_y, op1_z);
  1173. Value *zx_xz = MulSub(op0_z, op0_x, op1_z, op1_x);
  1174. Value *xy_yx = MulSub(op0_x, op0_y, op1_x, op1_y);
  1175. Value *cross = UndefValue::get(VT);
  1176. cross = Builder.CreateInsertElement(cross, yz_zy, (uint64_t)0);
  1177. cross = Builder.CreateInsertElement(cross, zx_xz, 1);
  1178. cross = Builder.CreateInsertElement(cross, xy_yx, 2);
  1179. return cross;
  1180. }
  1181. Value *TranslateDegrees(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1182. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1183. IRBuilder<> Builder(CI);
  1184. Type *Ty = CI->getType();
  1185. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1186. // 180/pi.
  1187. // TODO: include M_PI from math.h.
  1188. const double M_PI = 3.14159265358979323846;
  1189. Constant *toDegreeConst = ConstantFP::get(Ty->getScalarType(), 180 / M_PI);
  1190. if (Ty != Ty->getScalarType()) {
  1191. toDegreeConst =
  1192. ConstantVector::getSplat(Ty->getVectorNumElements(), toDegreeConst);
  1193. }
  1194. return Builder.CreateFMul(toDegreeConst, val);
  1195. }
  1196. Value *TranslateDst(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1197. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1198. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1199. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1200. Type *Ty = src1->getType();
  1201. IRBuilder<> Builder(CI);
  1202. Value *Result = UndefValue::get(Ty);
  1203. Constant *oneConst = ConstantFP::get(Ty->getScalarType(), 1);
  1204. // dest.x = 1;
  1205. Result = Builder.CreateInsertElement(Result, oneConst, (uint64_t)0);
  1206. // dest.y = src0.y * src1.y;
  1207. Value *src0_y = Builder.CreateExtractElement(src0, 1);
  1208. Value *src1_y = Builder.CreateExtractElement(src1, 1);
  1209. Value *yMuly = Builder.CreateFMul(src0_y, src1_y);
  1210. Result = Builder.CreateInsertElement(Result, yMuly, 1);
  1211. // dest.z = src0.z;
  1212. Value *src0_z = Builder.CreateExtractElement(src0, 2);
  1213. Result = Builder.CreateInsertElement(Result, src0_z, 2);
  1214. // dest.w = src1.w;
  1215. Value *src1_w = Builder.CreateExtractElement(src1, 3);
  1216. Result = Builder.CreateInsertElement(Result, src1_w, 3);
  1217. return Result;
  1218. }
  1219. Value *TranslateFirstbitHi(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1220. HLOperationLowerHelper &helper,
  1221. HLObjectOperationLowerHelper *pObjHelper,
  1222. bool &Translated) {
  1223. Value *firstbitHi =
  1224. TrivialUnaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1225. // firstbitHi == -1? -1 : (bitWidth-1 -firstbitHi);
  1226. IRBuilder<> Builder(CI);
  1227. Constant *neg1 = Builder.getInt32(-1);
  1228. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1229. Type *Ty = src->getType();
  1230. IntegerType *EltTy = cast<IntegerType>(Ty->getScalarType());
  1231. Constant *bitWidth = Builder.getInt32(EltTy->getBitWidth()-1);
  1232. if (Ty == Ty->getScalarType()) {
  1233. Value *sub = Builder.CreateSub(bitWidth, firstbitHi);
  1234. Value *cond = Builder.CreateICmpEQ(neg1, firstbitHi);
  1235. return Builder.CreateSelect(cond, neg1, sub);
  1236. } else {
  1237. Value *result = UndefValue::get(CI->getType());
  1238. unsigned vecSize = Ty->getVectorNumElements();
  1239. for (unsigned i = 0; i < vecSize; i++) {
  1240. Value *EltFirstBit = Builder.CreateExtractElement(firstbitHi, i);
  1241. Value *sub = Builder.CreateSub(bitWidth, EltFirstBit);
  1242. Value *cond = Builder.CreateICmpEQ(neg1, EltFirstBit);
  1243. Value *Elt = Builder.CreateSelect(cond, neg1, sub);
  1244. result = Builder.CreateInsertElement(result, Elt, i);
  1245. }
  1246. return result;
  1247. }
  1248. }
  1249. Value *TranslateFirstbitLo(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1250. HLOperationLowerHelper &helper,
  1251. HLObjectOperationLowerHelper *pObjHelper,
  1252. bool &Translated) {
  1253. Value *firstbitLo =
  1254. TrivialUnaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1255. return firstbitLo;
  1256. }
  1257. Value *TranslateLit(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1258. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1259. Value *n_dot_l = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1260. Value *n_dot_h = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1261. Value *m = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1262. IRBuilder<> Builder(CI);
  1263. Type *Ty = m->getType();
  1264. Value *Result = UndefValue::get(VectorType::get(Ty, 4));
  1265. // Result = (ambient, diffuse, specular, 1)
  1266. // ambient = 1.
  1267. Constant *oneConst = ConstantFP::get(Ty, 1);
  1268. Result = Builder.CreateInsertElement(Result, oneConst, (uint64_t)0);
  1269. // Result.w = 1.
  1270. Result = Builder.CreateInsertElement(Result, oneConst, 3);
  1271. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l.
  1272. Constant *zeroConst = ConstantFP::get(Ty, 0);
  1273. Value *nlCmp = Builder.CreateFCmpOLT(n_dot_l, zeroConst);
  1274. Value *diffuse = Builder.CreateSelect(nlCmp, zeroConst, n_dot_l);
  1275. Result = Builder.CreateInsertElement(Result, diffuse, 1);
  1276. // specular = ((n_dot_l < 0) || (n_dot_h < 0)) ? 0: (n_dot_h * m).
  1277. Value *nhCmp = Builder.CreateFCmpOLT(n_dot_h, zeroConst);
  1278. Value *specCond = Builder.CreateOr(nlCmp, nhCmp);
  1279. Value *nhMulM = Builder.CreateFMul(n_dot_h, m);
  1280. Value *spec = Builder.CreateSelect(specCond, zeroConst, nhMulM);
  1281. Result = Builder.CreateInsertElement(Result, spec, 2);
  1282. return Result;
  1283. }
  1284. Value *TranslateRadians(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1285. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1286. IRBuilder<> Builder(CI);
  1287. Type *Ty = CI->getType();
  1288. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1289. // pi/180.
  1290. // TODO: include M_PI from math.h.
  1291. const double M_PI = 3.14159265358979323846;
  1292. Constant *toRadianConst = ConstantFP::get(Ty->getScalarType(), M_PI / 180);
  1293. if (Ty != Ty->getScalarType()) {
  1294. toRadianConst =
  1295. ConstantVector::getSplat(Ty->getVectorNumElements(), toRadianConst);
  1296. }
  1297. return Builder.CreateFMul(toRadianConst, val);
  1298. }
  1299. Value *TranslateF16ToF32(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1300. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1301. IRBuilder<> Builder(CI);
  1302. Value *x = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1303. Type *Ty = CI->getType();
  1304. Function *f16tof32 =
  1305. helper.hlslOP.GetOpFunc(opcode, helper.voidTy);
  1306. return TrivialDxilOperation(
  1307. f16tof32, opcode, {Builder.getInt32(static_cast<unsigned>(opcode)), x},
  1308. x->getType(), Ty, &helper.hlslOP, Builder);
  1309. }
  1310. Value *TranslateF32ToF16(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1311. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1312. IRBuilder<> Builder(CI);
  1313. Value *x = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1314. Type *Ty = CI->getType();
  1315. Function *f32tof16 =
  1316. helper.hlslOP.GetOpFunc(opcode, helper.voidTy);
  1317. return TrivialDxilOperation(
  1318. f32tof16, opcode, {Builder.getInt32(static_cast<unsigned>(opcode)), x},
  1319. x->getType(), Ty, &helper.hlslOP, Builder);
  1320. }
  1321. Value *TranslateLength(CallInst *CI, Value *val, hlsl::OP *hlslOP) {
  1322. IRBuilder<> Builder(CI);
  1323. if (VectorType *VT = dyn_cast<VectorType>(val->getType())) {
  1324. Value *Elt = Builder.CreateExtractElement(val, (uint64_t)0);
  1325. unsigned size = VT->getNumElements();
  1326. if (size > 1) {
  1327. Value *Sum = Builder.CreateFMul(Elt, Elt);
  1328. for (unsigned i = 1; i < size; i++) {
  1329. Elt = Builder.CreateExtractElement(val, i);
  1330. Value *Mul = Builder.CreateFMul(Elt, Elt);
  1331. Sum = Builder.CreateFAdd(Sum, Mul);
  1332. }
  1333. DXIL::OpCode sqrt = DXIL::OpCode::Sqrt;
  1334. Function *dxilSqrt = hlslOP->GetOpFunc(sqrt, VT->getElementType());
  1335. Value *opArg = hlslOP->GetI32Const((unsigned)sqrt);
  1336. return Builder.CreateCall(dxilSqrt, {opArg, Sum},
  1337. hlslOP->GetOpCodeName(sqrt));
  1338. } else {
  1339. val = Elt;
  1340. }
  1341. }
  1342. DXIL::OpCode fabs = DXIL::OpCode::FAbs;
  1343. Function *dxilFAbs = hlslOP->GetOpFunc(fabs, val->getType());
  1344. Value *opArg = hlslOP->GetI32Const((unsigned)fabs);
  1345. return Builder.CreateCall(dxilFAbs, {opArg, val},
  1346. hlslOP->GetOpCodeName(fabs));
  1347. }
  1348. Value *TranslateLength(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1349. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1350. hlsl::OP *hlslOP = &helper.hlslOP;
  1351. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1352. return TranslateLength(CI, val, hlslOP);
  1353. }
  1354. Value *TranslateModF(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1355. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1356. hlsl::OP *hlslOP = &helper.hlslOP;
  1357. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1358. Value *outIntPtr = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1359. IRBuilder<> Builder(CI);
  1360. Value *Result =
  1361. TrivialDxilUnaryOperation(OP::OpCode::Round_z, val, hlslOP, Builder);
  1362. Value *intPortion = Builder.CreateFSub(val, Result);
  1363. Builder.CreateStore(intPortion, outIntPtr);
  1364. return Result;
  1365. }
  1366. Value *TranslateDistance(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1367. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1368. hlsl::OP *hlslOP = &helper.hlslOP;
  1369. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1370. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1371. IRBuilder<> Builder(CI);
  1372. Value *sub = Builder.CreateFSub(src0, src1);
  1373. return TranslateLength(CI, sub, hlslOP);
  1374. }
  1375. Value *TranslateExp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1376. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1377. hlsl::OP *hlslOP = &helper.hlslOP;
  1378. IRBuilder<> Builder(CI);
  1379. Type *Ty = CI->getType();
  1380. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1381. // TODO: include M_LOG2E from math.h.
  1382. const double M_LOG2E = 1.44269504088896340736;
  1383. Constant *log2eConst = ConstantFP::get(Ty->getScalarType(), M_LOG2E);
  1384. if (Ty != Ty->getScalarType()) {
  1385. log2eConst =
  1386. ConstantVector::getSplat(Ty->getVectorNumElements(), log2eConst);
  1387. }
  1388. val = Builder.CreateFMul(log2eConst, val);
  1389. Value *exp = TrivialDxilUnaryOperation(OP::OpCode::Exp, val, hlslOP, Builder);
  1390. return exp;
  1391. }
  1392. Value *TranslateLog(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1393. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1394. hlsl::OP *hlslOP = &helper.hlslOP;
  1395. IRBuilder<> Builder(CI);
  1396. Type *Ty = CI->getType();
  1397. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1398. // TODO: include M_LN2 from math.h.
  1399. const double M_LN2 = 0.693147180559945309417;
  1400. Constant *ln2Const = ConstantFP::get(Ty->getScalarType(), M_LN2);
  1401. if (Ty != Ty->getScalarType()) {
  1402. ln2Const = ConstantVector::getSplat(Ty->getVectorNumElements(), ln2Const);
  1403. }
  1404. Value *log = TrivialDxilUnaryOperation(OP::OpCode::Log, val, hlslOP, Builder);
  1405. return Builder.CreateFMul(ln2Const, log);
  1406. }
  1407. Value *TranslateLog10(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1408. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1409. hlsl::OP *hlslOP = &helper.hlslOP;
  1410. IRBuilder<> Builder(CI);
  1411. Type *Ty = CI->getType();
  1412. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1413. // TODO: include M_LN2 from math.h.
  1414. const double M_LN2 = 0.693147180559945309417;
  1415. const double M_LN10 = 2.30258509299404568402;
  1416. Constant *log2_10Const = ConstantFP::get(Ty->getScalarType(), M_LN2 / M_LN10);
  1417. if (Ty != Ty->getScalarType()) {
  1418. log2_10Const =
  1419. ConstantVector::getSplat(Ty->getVectorNumElements(), log2_10Const);
  1420. }
  1421. Value *log = TrivialDxilUnaryOperation(OP::OpCode::Log, val, hlslOP, Builder);
  1422. return Builder.CreateFMul(log2_10Const, log);
  1423. }
  1424. Value *TranslateFMod(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1425. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1426. hlsl::OP *hlslOP = &helper.hlslOP;
  1427. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1428. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1429. IRBuilder<> Builder(CI);
  1430. Value *div = Builder.CreateFDiv(src0, src1);
  1431. Value *negDiv = Builder.CreateFNeg(div);
  1432. Value *ge = Builder.CreateFCmpOGE(div, negDiv);
  1433. Value *absDiv =
  1434. TrivialDxilUnaryOperation(OP::OpCode::FAbs, div, hlslOP, Builder);
  1435. Value *frc =
  1436. TrivialDxilUnaryOperation(OP::OpCode::Frc, absDiv, hlslOP, Builder);
  1437. Value *negFrc = Builder.CreateFNeg(frc);
  1438. Value *realFrc = Builder.CreateSelect(ge, frc, negFrc);
  1439. return Builder.CreateFMul(realFrc, src1);
  1440. }
  1441. Value *TranslateFUIBinary(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1442. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1443. bool isFloat = CI->getType()->getScalarType()->isFloatingPointTy();
  1444. if (isFloat) {
  1445. switch (IOP) {
  1446. case IntrinsicOp::IOP_max:
  1447. opcode = OP::OpCode::FMax;
  1448. break;
  1449. case IntrinsicOp::IOP_min:
  1450. default:
  1451. DXASSERT(IOP == IntrinsicOp::IOP_min, "");
  1452. opcode = OP::OpCode::FMin;
  1453. break;
  1454. }
  1455. }
  1456. return TrivialBinaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1457. }
  1458. Value *TranslateFUITrinary(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1459. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1460. bool isFloat = CI->getType()->getScalarType()->isFloatingPointTy();
  1461. if (isFloat) {
  1462. switch (IOP) {
  1463. case IntrinsicOp::IOP_mad:
  1464. default:
  1465. DXASSERT(IOP == IntrinsicOp::IOP_mad, "");
  1466. opcode = OP::OpCode::FMad;
  1467. break;
  1468. }
  1469. }
  1470. return TrivialTrinaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1471. }
  1472. Value *TranslateFrexp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1473. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1474. hlsl::OP *hlslOP = &helper.hlslOP;
  1475. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1476. Value *expPtr = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1477. IRBuilder<> Builder(CI);
  1478. Type *i32Ty = Type::getInt32Ty(CI->getContext());
  1479. Constant *exponentMaskConst = ConstantInt::get(i32Ty, 0x7f800000);
  1480. Constant *mantisaMaskConst = ConstantInt::get(i32Ty, 0x007fffff);
  1481. Constant *exponentShiftConst = ConstantInt::get(i32Ty, 23);
  1482. Constant *mantisaOrConst = ConstantInt::get(i32Ty, 0x3f000000);
  1483. Constant *exponentBiasConst = ConstantInt::get(i32Ty, -(int)0x3f000000);
  1484. Constant *zeroVal = hlslOP->GetFloatConst(0);
  1485. // int iVal = asint(val);
  1486. Type *dstTy = i32Ty;
  1487. Type *Ty = val->getType();
  1488. if (Ty->isVectorTy()) {
  1489. unsigned vecSize = Ty->getVectorNumElements();
  1490. dstTy = VectorType::get(i32Ty, vecSize);
  1491. exponentMaskConst = ConstantVector::getSplat(vecSize, exponentMaskConst);
  1492. mantisaMaskConst = ConstantVector::getSplat(vecSize, mantisaMaskConst);
  1493. exponentShiftConst = ConstantVector::getSplat(vecSize, exponentShiftConst);
  1494. mantisaOrConst = ConstantVector::getSplat(vecSize, mantisaOrConst);
  1495. exponentBiasConst = ConstantVector::getSplat(vecSize, exponentBiasConst);
  1496. zeroVal = ConstantVector::getSplat(vecSize, zeroVal);
  1497. }
  1498. // bool ne = val != 0;
  1499. Value *notZero = Builder.CreateFCmpUNE(val, zeroVal);
  1500. notZero = Builder.CreateZExt(notZero, dstTy);
  1501. Value *intVal = Builder.CreateBitCast(val, dstTy);
  1502. // temp = intVal & exponentMask;
  1503. Value *temp = Builder.CreateAnd(intVal, exponentMaskConst);
  1504. // temp = temp + exponentBias;
  1505. temp = Builder.CreateAdd(temp, exponentBiasConst);
  1506. // temp = temp & ne;
  1507. temp = Builder.CreateAnd(temp, notZero);
  1508. // temp = temp >> exponentShift;
  1509. temp = Builder.CreateAShr(temp, exponentShiftConst);
  1510. // exp = float(temp);
  1511. Value *exp = Builder.CreateSIToFP(temp, Ty);
  1512. Builder.CreateStore(exp, expPtr);
  1513. // temp = iVal & mantisaMask;
  1514. temp = Builder.CreateAnd(intVal, mantisaMaskConst);
  1515. // temp = temp | mantisaOr;
  1516. temp = Builder.CreateOr(temp, mantisaOrConst);
  1517. // mantisa = temp & ne;
  1518. Value *mantisa = Builder.CreateAnd(temp, notZero);
  1519. return Builder.CreateBitCast(mantisa, Ty);
  1520. }
  1521. Value *TranslateLdExp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1522. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1523. hlsl::OP *hlslOP = &helper.hlslOP;
  1524. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1525. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1526. IRBuilder<> Builder(CI);
  1527. Value *exp =
  1528. TrivialDxilUnaryOperation(OP::OpCode::Exp, src1, hlslOP, Builder);
  1529. return Builder.CreateFMul(exp, src0);
  1530. }
  1531. Value *TranslateFWidth(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1532. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1533. hlsl::OP *hlslOP = &helper.hlslOP;
  1534. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1535. IRBuilder<> Builder(CI);
  1536. Value *ddx =
  1537. TrivialDxilUnaryOperation(OP::OpCode::DerivCoarseX, src, hlslOP, Builder);
  1538. Value *absDdx =
  1539. TrivialDxilUnaryOperation(OP::OpCode::FAbs, ddx, hlslOP, Builder);
  1540. Value *ddy =
  1541. TrivialDxilUnaryOperation(OP::OpCode::DerivCoarseY, src, hlslOP, Builder);
  1542. Value *absDdy =
  1543. TrivialDxilUnaryOperation(OP::OpCode::FAbs, ddy, hlslOP, Builder);
  1544. return Builder.CreateFAdd(absDdx, absDdy);
  1545. }
  1546. Value *TranslateNormalize(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1547. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1548. hlsl::OP *hlslOP = &helper.hlslOP;
  1549. Type *Ty = CI->getType();
  1550. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1551. IRBuilder<> Builder(CI);
  1552. Value *length = TranslateLength(CI, op, hlslOP);
  1553. if (Ty != length->getType()) {
  1554. VectorType *VT = cast<VectorType>(Ty);
  1555. Value *vecLength = UndefValue::get(VT);
  1556. for (unsigned i = 0; i < VT->getNumElements(); i++)
  1557. vecLength = Builder.CreateInsertElement(vecLength, length, i);
  1558. length = vecLength;
  1559. }
  1560. return Builder.CreateFDiv(op, length);
  1561. }
  1562. Value *TranslateLerp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1563. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1564. // x + s(y-x)
  1565. Value *x = CI->getArgOperand(HLOperandIndex::kLerpOpXIdx);
  1566. Value *y = CI->getArgOperand(HLOperandIndex::kLerpOpYIdx);
  1567. IRBuilder<> Builder(CI);
  1568. Value *ySubx = Builder.CreateFSub(y, x);
  1569. Value *s = CI->getArgOperand(HLOperandIndex::kLerpOpSIdx);
  1570. Value *sMulSub = Builder.CreateFMul(s, ySubx);
  1571. return Builder.CreateFAdd(x, sMulSub);
  1572. }
  1573. Value *TrivialDotOperation(OP::OpCode opcode, Value *src0,
  1574. Value *src1, hlsl::OP *hlslOP,
  1575. IRBuilder<> &Builder) {
  1576. Type *Ty = src0->getType()->getScalarType();
  1577. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty);
  1578. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1579. SmallVector<Value *, 9> args;
  1580. args.emplace_back(opArg);
  1581. unsigned vecSize = src0->getType()->getVectorNumElements();
  1582. for (unsigned i = 0; i < vecSize; i++)
  1583. args.emplace_back(Builder.CreateExtractElement(src0, i));
  1584. for (unsigned i = 0; i < vecSize; i++)
  1585. args.emplace_back(Builder.CreateExtractElement(src1, i));
  1586. Value *dotOP = Builder.CreateCall(dxilFunc, args);
  1587. return dotOP;
  1588. }
  1589. Value *TranslateIDot(Value *arg0, Value *arg1, unsigned vecSize, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  1590. Value *Elt0 = Builder.CreateExtractElement(arg0, (uint64_t)0);
  1591. Value *Elt1 = Builder.CreateExtractElement(arg1, (uint64_t)0);
  1592. Value *Result = Builder.CreateMul(Elt0, Elt1);
  1593. switch (vecSize) {
  1594. case 4:
  1595. Elt0 = Builder.CreateExtractElement(arg0, 3);
  1596. Elt1 = Builder.CreateExtractElement(arg1, 3);
  1597. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1598. // Pass thru.
  1599. case 3:
  1600. Elt0 = Builder.CreateExtractElement(arg0, 2);
  1601. Elt1 = Builder.CreateExtractElement(arg1, 2);
  1602. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1603. // Pass thru.
  1604. case 2:
  1605. Elt0 = Builder.CreateExtractElement(arg0, 1);
  1606. Elt1 = Builder.CreateExtractElement(arg1, 1);
  1607. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1608. break;
  1609. default:
  1610. case 1:
  1611. DXASSERT(vecSize == 1, "invalid vector size.");
  1612. }
  1613. return Result;
  1614. }
  1615. Value *TranslateFDot(Value *arg0, Value *arg1, unsigned vecSize,
  1616. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  1617. switch (vecSize) {
  1618. case 2:
  1619. return TrivialDotOperation(OP::OpCode::Dot2, arg0, arg1, hlslOP, Builder);
  1620. break;
  1621. case 3:
  1622. return TrivialDotOperation(OP::OpCode::Dot3, arg0, arg1, hlslOP, Builder);
  1623. break;
  1624. case 4:
  1625. return TrivialDotOperation(OP::OpCode::Dot4, arg0, arg1, hlslOP, Builder);
  1626. break;
  1627. default:
  1628. DXASSERT(vecSize == 1, "wrong vector size");
  1629. {
  1630. Value *vecMul = Builder.CreateFMul(arg0, arg1);
  1631. return Builder.CreateExtractElement(vecMul, (uint64_t)0);
  1632. }
  1633. break;
  1634. }
  1635. }
  1636. Value *TranslateDot(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1637. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1638. hlsl::OP *hlslOP = &helper.hlslOP;
  1639. Value *arg0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1640. Type *Ty = arg0->getType();
  1641. unsigned vecSize = Ty->getVectorNumElements();
  1642. Value *arg1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1643. IRBuilder<> Builder(CI);
  1644. if (Ty->getScalarType()->isFloatingPointTy()) {
  1645. return TranslateFDot(arg0, arg1, vecSize, hlslOP, Builder);
  1646. } else {
  1647. return TranslateIDot(arg0, arg1, vecSize, hlslOP, Builder);
  1648. }
  1649. }
  1650. Value *TranslateReflect(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1651. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1652. hlsl::OP *hlslOP = &helper.hlslOP;
  1653. // v = i - 2 * n * dot(i•n).
  1654. IRBuilder<> Builder(CI);
  1655. Value *i = CI->getArgOperand(HLOperandIndex::kReflectOpIIdx);
  1656. Value *n = CI->getArgOperand(HLOperandIndex::kReflectOpNIdx);
  1657. VectorType *VT = cast<VectorType>(i->getType());
  1658. unsigned vecSize = VT->getNumElements();
  1659. Value *dot = TranslateFDot(i, n, vecSize, hlslOP, Builder);
  1660. // 2 * dot (i, n).
  1661. dot = Builder.CreateFMul(hlslOP->GetFloatConst(2), dot);
  1662. // 2 * n * dot(i, n).
  1663. Value *vecDot = Builder.CreateVectorSplat(vecSize, dot);
  1664. Value *nMulDot = Builder.CreateFMul(vecDot, n);
  1665. // i - 2 * n * dot(i, n).
  1666. return Builder.CreateFSub(i, nMulDot);
  1667. }
  1668. Value *TranslateRefract(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1669. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1670. hlsl::OP *hlslOP = &helper.hlslOP;
  1671. // d = dot(i•n);
  1672. // t = 1 - eta * eta * ( 1 - d*d);
  1673. // cond = t >= 1;
  1674. // r = eta * i - (eta * d + sqrt(t)) * n;
  1675. // return cond ? r : 0;
  1676. IRBuilder<> Builder(CI);
  1677. Value *i = CI->getArgOperand(HLOperandIndex::kRefractOpIIdx);
  1678. Value *n = CI->getArgOperand(HLOperandIndex::kRefractOpNIdx);
  1679. Value *eta = CI->getArgOperand(HLOperandIndex::kRefractOpEtaIdx);
  1680. VectorType *VT = cast<VectorType>(i->getType());
  1681. unsigned vecSize = VT->getNumElements();
  1682. Value *dot = TranslateFDot(i, n, vecSize, hlslOP, Builder);
  1683. // eta * eta;
  1684. Value *eta2 = Builder.CreateFMul(eta, eta);
  1685. // d*d;
  1686. Value *dot2 = Builder.CreateFMul(dot, dot);
  1687. Constant *one = ConstantFP::get(eta->getType(), 1);
  1688. Constant *zero = ConstantFP::get(eta->getType(), 0);
  1689. // 1- d*d;
  1690. dot2 = Builder.CreateFSub(one, dot2);
  1691. // eta * eta * (1-d*d);
  1692. eta2 = Builder.CreateFMul(dot2, eta2);
  1693. // t = 1 - eta * eta * ( 1 - d*d);
  1694. Value *t = Builder.CreateFSub(one, eta2);
  1695. // cond = t >= 0;
  1696. Value *cond = Builder.CreateFCmpOGE(t, zero);
  1697. // eta * i;
  1698. Value *vecEta = UndefValue::get(VT);
  1699. for (unsigned i = 0; i < vecSize; i++)
  1700. vecEta = Builder.CreateInsertElement(vecEta, eta, i);
  1701. Value *etaMulI = Builder.CreateFMul(i, vecEta);
  1702. // sqrt(t);
  1703. Value *sqrt = TrivialDxilUnaryOperation(OP::OpCode::Sqrt, t, hlslOP, Builder);
  1704. // eta * d;
  1705. Value *etaMulD = Builder.CreateFMul(eta, dot);
  1706. // eta * d + sqrt(t);
  1707. Value *etaSqrt = Builder.CreateFAdd(etaMulD, sqrt);
  1708. // (eta * d + sqrt(t)) * n;
  1709. Value *vecEtaSqrt = Builder.CreateVectorSplat(vecSize, etaSqrt);
  1710. Value *r = Builder.CreateFMul(vecEtaSqrt, n);
  1711. // r = eta * i - (eta * d + sqrt(t)) * n;
  1712. r = Builder.CreateFSub(etaMulI, r);
  1713. Value *refract =
  1714. Builder.CreateSelect(cond, r, ConstantVector::getSplat(vecSize, zero));
  1715. return refract;
  1716. }
  1717. Value *TranslateSmoothStep(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1718. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1719. hlsl::OP *hlslOP = &helper.hlslOP;
  1720. // s = saturate((x-min)/(max-min)).
  1721. IRBuilder<> Builder(CI);
  1722. Value *minVal = CI->getArgOperand(HLOperandIndex::kSmoothStepOpMinIdx);
  1723. Value *maxVal = CI->getArgOperand(HLOperandIndex::kSmoothStepOpMaxIdx);
  1724. Value *maxSubMin = Builder.CreateFSub(maxVal, minVal);
  1725. Value *x = CI->getArgOperand(HLOperandIndex::kSmoothStepOpXIdx);
  1726. Value *xSubMin = Builder.CreateFSub(x, minVal);
  1727. Value *satVal = Builder.CreateFDiv(xSubMin, maxSubMin);
  1728. Value *s = TrivialDxilUnaryOperation(DXIL::OpCode::Saturate, satVal, hlslOP,
  1729. Builder);
  1730. // return s * s *(3-2*s).
  1731. Constant *c2 = ConstantFP::get(CI->getType(),2);
  1732. Constant *c3 = ConstantFP::get(CI->getType(),3);
  1733. if (s->getType()->isVectorTy()) {
  1734. unsigned vecSize = s->getType()->getVectorNumElements();
  1735. c2 = ConstantVector::getSplat(vecSize, c2);
  1736. c3 = ConstantVector::getSplat(vecSize, c3);
  1737. }
  1738. Value *sMul2 = Builder.CreateFMul(s, c2);
  1739. Value *result = Builder.CreateFSub(c3, sMul2);
  1740. result = Builder.CreateFMul(s, result);
  1741. result = Builder.CreateFMul(s, result);
  1742. return result;
  1743. }
  1744. Value *TranslateMSad4(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1745. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1746. hlsl::OP *hlslOP = &helper.hlslOP;
  1747. Value *ref = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1748. Value *src = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1749. Value *accum = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1750. Type *Ty = CI->getType();
  1751. IRBuilder<> Builder(CI);
  1752. Value *vecRef = UndefValue::get(Ty);
  1753. for (unsigned i = 0; i < 4; i++)
  1754. vecRef = Builder.CreateInsertElement(vecRef, ref, i);
  1755. Value *srcX = Builder.CreateExtractElement(src, (uint64_t)0);
  1756. Value *srcY = Builder.CreateExtractElement(src, 1);
  1757. Value *byteSrc = UndefValue::get(Ty);
  1758. byteSrc = Builder.CreateInsertElement(byteSrc, srcX, (uint64_t)0);
  1759. // ushr r0.yzw, srcX, l(0, 8, 16, 24)
  1760. // bfi r1.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), srcX, r0.yyzw
  1761. Value *bfiOpArg =
  1762. hlslOP->GetU32Const(static_cast<unsigned>(DXIL::OpCode::Bfi));
  1763. Value *imm8 = hlslOP->GetU32Const(8);
  1764. Value *imm16 = hlslOP->GetU32Const(16);
  1765. Value *imm24 = hlslOP->GetU32Const(24);
  1766. Ty = ref->getType();
  1767. // Get x[31:8].
  1768. Value *srcXShift = Builder.CreateLShr(srcX, imm8);
  1769. // y[0~7] x[31:8].
  1770. Value *byteSrcElt = TrivialDxilOperation(
  1771. DXIL::OpCode::Bfi, {bfiOpArg, imm8, imm24, srcY, srcXShift}, Ty, Ty,
  1772. hlslOP, Builder);
  1773. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 1);
  1774. // Get x[31:16].
  1775. srcXShift = Builder.CreateLShr(srcXShift, imm8);
  1776. // y[0~15] x[31:16].
  1777. byteSrcElt = TrivialDxilOperation(DXIL::OpCode::Bfi,
  1778. {bfiOpArg, imm16, imm16, srcY, srcXShift},
  1779. Ty, Ty, hlslOP, Builder);
  1780. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 2);
  1781. // Get x[31:24].
  1782. srcXShift = Builder.CreateLShr(srcXShift, imm8);
  1783. // y[0~23] x[31:24].
  1784. byteSrcElt = TrivialDxilOperation(DXIL::OpCode::Bfi,
  1785. {bfiOpArg, imm24, imm8, srcY, srcXShift},
  1786. Ty, Ty, hlslOP, Builder);
  1787. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 3);
  1788. // Msad on vecref and byteSrc.
  1789. return TrivialDxilTrinaryOperation(DXIL::OpCode::Msad, vecRef, byteSrc, accum,
  1790. hlslOP, Builder);
  1791. }
  1792. Value *TranslateRCP(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1793. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1794. Type *Ty = CI->getType();
  1795. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1796. IRBuilder<> Builder(CI);
  1797. Constant *one = ConstantFP::get(Ty->getScalarType(), 1.0);
  1798. if (Ty != Ty->getScalarType()) {
  1799. one = ConstantVector::getSplat(Ty->getVectorNumElements(), one);
  1800. }
  1801. return Builder.CreateFDiv(one, op);
  1802. }
  1803. Value *TranslateSign(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1804. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1805. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1806. Type *Ty = val->getType();
  1807. Type *EltTy = Ty->getScalarType();
  1808. IRBuilder<> Builder(CI);
  1809. if (EltTy->isIntegerTy()) {
  1810. Constant *zero = ConstantInt::get(Ty->getScalarType(), 0);
  1811. if (Ty != EltTy) {
  1812. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1813. }
  1814. Value *zeroLtVal = Builder.CreateICmpSLT(zero, val);
  1815. zeroLtVal = Builder.CreateZExt(zeroLtVal, CI->getType());
  1816. Value *valLtZero = Builder.CreateICmpSLT(val, zero);
  1817. valLtZero = Builder.CreateZExt(valLtZero, CI->getType());
  1818. return Builder.CreateSub(zeroLtVal, valLtZero);
  1819. } else {
  1820. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0.0);
  1821. if (Ty != EltTy) {
  1822. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1823. }
  1824. Value *zeroLtVal = Builder.CreateFCmpOLT(zero, val);
  1825. zeroLtVal = Builder.CreateZExt(zeroLtVal, CI->getType());
  1826. Value *valLtZero = Builder.CreateFCmpOLT(val, zero);
  1827. valLtZero = Builder.CreateZExt(valLtZero, CI->getType());
  1828. return Builder.CreateSub(zeroLtVal, valLtZero);
  1829. }
  1830. }
  1831. Value *TranslateStep(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1832. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1833. Value *edge = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1834. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1835. Type *Ty = CI->getType();
  1836. IRBuilder<> Builder(CI);
  1837. Constant *one = ConstantFP::get(Ty->getScalarType(), 1.0);
  1838. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0);
  1839. Value *cond = Builder.CreateFCmpOLT(x, edge);
  1840. if (Ty != Ty->getScalarType()) {
  1841. one = ConstantVector::getSplat(Ty->getVectorNumElements(), one);
  1842. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1843. }
  1844. return Builder.CreateSelect(cond, zero, one);
  1845. }
  1846. Value *TranslatePow(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1847. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1848. hlsl::OP *hlslOP = &helper.hlslOP;
  1849. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1850. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1851. IRBuilder<> Builder(CI);
  1852. // t = log(x);
  1853. Value *logX =
  1854. TrivialDxilUnaryOperation(DXIL::OpCode::Log, x, hlslOP, Builder);
  1855. // t = y * t;
  1856. Value *mulY = Builder.CreateFMul(logX, y);
  1857. // pow = exp(t);
  1858. return TrivialDxilUnaryOperation(DXIL::OpCode::Exp, mulY, hlslOP, Builder);
  1859. }
  1860. Value *TranslateFaceforward(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1861. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1862. hlsl::OP *hlslOP = &helper.hlslOP;
  1863. Type *Ty = CI->getType();
  1864. Value *n = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1865. Value *i = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1866. Value *ng = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1867. IRBuilder<> Builder(CI);
  1868. unsigned vecSize = Ty->getVectorNumElements();
  1869. // -n x sign(dot(i, ng)).
  1870. Value *dotOp = TranslateFDot(i, ng, vecSize, hlslOP, Builder);
  1871. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0);
  1872. Value *dotLtZero = Builder.CreateFCmpOLT(dotOp, zero);
  1873. Value *negN = Builder.CreateFNeg(n);
  1874. Value *faceforward = Builder.CreateSelect(dotLtZero, n, negN);
  1875. return faceforward;
  1876. }
  1877. }
  1878. // MOP intrinsics
  1879. namespace {
  1880. Value *TranslateGetSamplePosition(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1881. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1882. hlsl::OP *hlslOP = &helper.hlslOP;
  1883. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1884. IRBuilder<> Builder(CI);
  1885. Value *sampleIdx =
  1886. CI->getArgOperand(HLOperandIndex::kGetSamplePositionSampleIdxOpIndex);
  1887. OP::OpCode opcode = OP::OpCode::Texture2DMSGetSamplePosition;
  1888. llvm::Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1889. Function *dxilFunc =
  1890. hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  1891. Value *args[] = {opArg, handle, sampleIdx};
  1892. Value *samplePos = Builder.CreateCall(dxilFunc, args);
  1893. Value *result = UndefValue::get(CI->getType());
  1894. Value *samplePosX = Builder.CreateExtractValue(samplePos, 0);
  1895. Value *samplePosY = Builder.CreateExtractValue(samplePos, 1);
  1896. result = Builder.CreateInsertElement(result, samplePosX, (uint64_t)0);
  1897. result = Builder.CreateInsertElement(result, samplePosY, 1);
  1898. return result;
  1899. }
  1900. Value *TranslateGetDimensions(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1901. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1902. hlsl::OP *hlslOP = &helper.hlslOP;
  1903. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1904. DxilResource::Kind RK = pObjHelper->GetRK(handle);
  1905. IRBuilder<> Builder(CI);
  1906. OP::OpCode opcode = OP::OpCode::GetDimensions;
  1907. llvm::Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1908. Function *dxilFunc =
  1909. hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  1910. Type *i32Ty = Type::getInt32Ty(CI->getContext());
  1911. Value *mipLevel = UndefValue::get(i32Ty);
  1912. unsigned widthOpIdx = HLOperandIndex::kGetDimensionsMipWidthOpIndex;
  1913. switch (RK) {
  1914. case DxilResource::Kind::Texture1D:
  1915. case DxilResource::Kind::Texture1DArray:
  1916. case DxilResource::Kind::Texture2D:
  1917. case DxilResource::Kind::Texture2DArray:
  1918. case DxilResource::Kind::TextureCube:
  1919. case DxilResource::Kind::TextureCubeArray:
  1920. case DxilResource::Kind::Texture3D: {
  1921. Value *opMipLevel =
  1922. CI->getArgOperand(HLOperandIndex::kGetDimensionsMipLevelOpIndex);
  1923. // mipLevel is in parameter, should not be pointer.
  1924. if (!opMipLevel->getType()->isPointerTy())
  1925. mipLevel = opMipLevel;
  1926. else {
  1927. // No mip level.
  1928. widthOpIdx = HLOperandIndex::kGetDimensionsNoMipWidthOpIndex;
  1929. mipLevel = ConstantInt::get(i32Ty, 0);
  1930. }
  1931. } break;
  1932. default:
  1933. widthOpIdx = HLOperandIndex::kGetDimensionsNoMipWidthOpIndex;
  1934. break;
  1935. }
  1936. Value *args[] = {opArg, handle, mipLevel};
  1937. Value *dims = Builder.CreateCall(dxilFunc, args);
  1938. unsigned dimensionIdx = 0;
  1939. Value *width = Builder.CreateExtractValue(dims, dimensionIdx++);
  1940. Value *widthPtr = CI->getArgOperand(widthOpIdx);
  1941. if (widthPtr->getType()->getPointerElementType()->isFloatingPointTy())
  1942. width = Builder.CreateSIToFP(width,
  1943. widthPtr->getType()->getPointerElementType());
  1944. Builder.CreateStore(width, widthPtr);
  1945. if (RK == DxilResource::Kind::StructuredBuffer) {
  1946. // Set stride.
  1947. Value *stridePtr = CI->getArgOperand(widthOpIdx + 1);
  1948. const DataLayout &DL = helper.dataLayout;
  1949. Value *buf = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1950. Type *bufTy = buf->getType();
  1951. Type *bufRetTy = bufTy->getStructElementType(0);
  1952. unsigned stride = DL.getTypeAllocSize(bufRetTy);
  1953. Builder.CreateStore(hlslOP->GetU32Const(stride), stridePtr);
  1954. } else {
  1955. if (widthOpIdx == HLOperandIndex::kGetDimensionsMipWidthOpIndex ||
  1956. // Samples is in w channel too.
  1957. RK == DXIL::ResourceKind::Texture2DMS) {
  1958. // Has mip.
  1959. for (unsigned argIdx = widthOpIdx + 1;
  1960. argIdx < CI->getNumArgOperands() - 1; argIdx++) {
  1961. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx++);
  1962. Value *ptr = CI->getArgOperand(argIdx);
  1963. if (ptr->getType()->getPointerElementType()->isFloatingPointTy())
  1964. dim = Builder.CreateSIToFP(dim,
  1965. ptr->getType()->getPointerElementType());
  1966. Builder.CreateStore(dim, ptr);
  1967. }
  1968. // NumOfLevel is in w channel.
  1969. dimensionIdx = 3;
  1970. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx);
  1971. Value *ptr = CI->getArgOperand(CI->getNumArgOperands() - 1);
  1972. if (ptr->getType()->getPointerElementType()->isFloatingPointTy())
  1973. dim =
  1974. Builder.CreateSIToFP(dim, ptr->getType()->getPointerElementType());
  1975. Builder.CreateStore(dim, ptr);
  1976. } else {
  1977. for (unsigned argIdx = widthOpIdx + 1; argIdx < CI->getNumArgOperands();
  1978. argIdx++) {
  1979. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx++);
  1980. Value *ptr = CI->getArgOperand(argIdx);
  1981. if (ptr->getType()->getPointerElementType()->isFloatingPointTy())
  1982. dim = Builder.CreateSIToFP(dim,
  1983. ptr->getType()->getPointerElementType());
  1984. Builder.CreateStore(dim, ptr);
  1985. }
  1986. }
  1987. }
  1988. return nullptr;
  1989. }
  1990. Value *GenerateUpdateCounter(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1991. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1992. hlsl::OP *hlslOP = &helper.hlslOP;
  1993. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1994. pObjHelper->MarkHasCounter(handle->getType(), handle);
  1995. bool bInc = IOP == IntrinsicOp::MOP_IncrementCounter;
  1996. IRBuilder<> Builder(CI);
  1997. OP::OpCode OpCode = OP::OpCode::BufferUpdateCounter;
  1998. Value *OpCodeArg = hlslOP->GetU32Const((unsigned)OpCode);
  1999. Value *IncVal = hlslOP->GetI8Const(bInc ? 1 : -1);
  2000. // Create BufferUpdateCounter call.
  2001. Value *Args[] = {OpCodeArg, handle, IncVal};
  2002. Function *F =
  2003. hlslOP->GetOpFunc(OpCode, Type::getVoidTy(handle->getContext()));
  2004. return Builder.CreateCall(F, Args);
  2005. }
  2006. Value *ScalarizeResRet(Type *RetTy, Value *ResRet, IRBuilder<> &Builder) {
  2007. // Extract value part.
  2008. Value *retVal = llvm::UndefValue::get(RetTy);
  2009. if (RetTy->isVectorTy()) {
  2010. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++) {
  2011. Value *retComp = Builder.CreateExtractValue(ResRet, i);
  2012. retVal = Builder.CreateInsertElement(retVal, retComp, i);
  2013. }
  2014. } else {
  2015. retVal = Builder.CreateExtractValue(ResRet, 0);
  2016. }
  2017. return retVal;
  2018. }
  2019. Value *ScalarizeElements(Type *RetTy, ArrayRef<Value*> Elts, IRBuilder<> &Builder) {
  2020. // Extract value part.
  2021. Value *retVal = llvm::UndefValue::get(RetTy);
  2022. if (RetTy->isVectorTy()) {
  2023. unsigned vecSize = RetTy->getVectorNumElements();
  2024. DXASSERT(vecSize <= Elts.size(), "vector size mismatch");
  2025. for (unsigned i = 0; i < vecSize; i++) {
  2026. Value *retComp = Elts[i];
  2027. retVal = Builder.CreateInsertElement(retVal, retComp, i);
  2028. }
  2029. } else {
  2030. retVal = Elts[0];
  2031. }
  2032. return retVal;
  2033. }
  2034. void UpdateStatus(Value *ResRet, Value *status, IRBuilder<> &Builder,
  2035. hlsl::OP *hlslOp) {
  2036. if (status && !isa<UndefValue>(status)) {
  2037. Value *statusVal = Builder.CreateExtractValue(ResRet, DXIL::kResRetStatusIndex);
  2038. Value *checkAccessOp = hlslOp->GetI32Const(
  2039. static_cast<unsigned>(DXIL::OpCode::CheckAccessFullyMapped));
  2040. Function *checkAccessFn = hlslOp->GetOpFunc(
  2041. DXIL::OpCode::CheckAccessFullyMapped, statusVal->getType());
  2042. // CheckAccess on status.
  2043. Value *bStatus =
  2044. Builder.CreateCall(checkAccessFn, {checkAccessOp, statusVal});
  2045. Value *extStatus =
  2046. Builder.CreateZExt(bStatus, Type::getInt32Ty(status->getContext()));
  2047. Builder.CreateStore(extStatus, status);
  2048. }
  2049. }
  2050. Value *SplatToVector(Value *Elt, Type *DstTy, IRBuilder<> &Builder) {
  2051. Value *Result = UndefValue::get(DstTy);
  2052. for (unsigned i = 0; i < DstTy->getVectorNumElements(); i++)
  2053. Result = Builder.CreateInsertElement(Result, Elt, i);
  2054. return Result;
  2055. }
  2056. // Sample intrinsics.
  2057. struct SampleHelper {
  2058. SampleHelper(CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper);
  2059. OP::OpCode opcode;
  2060. Value *texHandle;
  2061. Value *samplerHandle;
  2062. static const unsigned kMaxCoordDimensions = 4;
  2063. Value *coord[kMaxCoordDimensions];
  2064. Value *special; // For CompareValue, Bias, LOD.
  2065. // SampleGrad only.
  2066. static const unsigned kMaxDDXYDimensions = 3;
  2067. Value *ddx[kMaxDDXYDimensions];
  2068. Value *ddy[kMaxDDXYDimensions];
  2069. // Optional.
  2070. static const unsigned kMaxOffsetDimensions = 3;
  2071. Value *offset[kMaxOffsetDimensions];
  2072. Value *clamp;
  2073. Value *status;
  2074. void TranslateCoord(CallInst *CI, unsigned coordIdx,
  2075. unsigned coordDimensions) {
  2076. Value *coordArg = CI->getArgOperand(coordIdx);
  2077. IRBuilder<> Builder(CI);
  2078. for (unsigned i = 0; i < coordDimensions; i++)
  2079. coord[i] = Builder.CreateExtractElement(coordArg, i);
  2080. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2081. for (unsigned i = coordDimensions; i < kMaxCoordDimensions; i++)
  2082. coord[i] = undefF;
  2083. }
  2084. void TranslateOffset(CallInst *CI, unsigned offsetIdx,
  2085. unsigned offsetDimensions) {
  2086. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2087. if (CI->getNumArgOperands() > offsetIdx) {
  2088. Value *offsetArg = CI->getArgOperand(offsetIdx);
  2089. IRBuilder<> Builder(CI);
  2090. for (unsigned i = 0; i < offsetDimensions; i++)
  2091. offset[i] = Builder.CreateExtractElement(offsetArg, i);
  2092. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2093. offset[i] = undefI;
  2094. } else {
  2095. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2096. offset[i] = undefI;
  2097. }
  2098. }
  2099. void SetClamp(CallInst *CI, unsigned clampIdx) {
  2100. if (CI->getNumArgOperands() > clampIdx) {
  2101. clamp = CI->getArgOperand(clampIdx);
  2102. if (clamp->getType()->isVectorTy()) {
  2103. IRBuilder<> Builder(CI);
  2104. clamp = Builder.CreateExtractElement(clamp, (uint64_t)0);
  2105. }
  2106. } else
  2107. clamp = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2108. }
  2109. void SetStatus(CallInst *CI, unsigned statusIdx) {
  2110. if (CI->getNumArgOperands() == (statusIdx + 1))
  2111. status = CI->getArgOperand(statusIdx);
  2112. else
  2113. status = nullptr;
  2114. }
  2115. void SetDDXY(CallInst *CI, MutableArrayRef<Value *> ddxy, Value *ddxyArg,
  2116. unsigned ddxySize) {
  2117. IRBuilder<> Builder(CI);
  2118. for (unsigned i = 0; i < ddxySize; i++)
  2119. ddxy[i] = Builder.CreateExtractElement(ddxyArg, i);
  2120. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2121. for (unsigned i = ddxySize; i < kMaxDDXYDimensions; i++)
  2122. ddxy[i] = undefF;
  2123. }
  2124. };
  2125. SampleHelper::SampleHelper(
  2126. CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper)
  2127. : opcode(op) {
  2128. const unsigned thisIdx =
  2129. HLOperandIndex::kHandleOpIdx; // opcode takes arg0, this pointer is arg1.
  2130. const unsigned kSamplerArgIndex = HLOperandIndex::kSampleSamplerArgIndex;
  2131. IRBuilder<> Builder(CI);
  2132. texHandle = CI->getArgOperand(thisIdx);
  2133. samplerHandle = CI->getArgOperand(kSamplerArgIndex);
  2134. DXIL::ResourceKind RK = pObjHelper->GetRK(texHandle);
  2135. if (RK == DXIL::ResourceKind::Invalid) {
  2136. opcode = DXIL::OpCode::NumOpCodes;
  2137. return;
  2138. }
  2139. unsigned coordDimensions = DxilResource::GetNumCoords(RK);
  2140. unsigned offsetDimensions = DxilResource::GetNumOffsets(RK);
  2141. const unsigned kCoordArgIdx = HLOperandIndex::kSampleCoordArgIndex;
  2142. TranslateCoord(CI, kCoordArgIdx, coordDimensions);
  2143. special = nullptr;
  2144. switch (op) {
  2145. case OP::OpCode::Sample:
  2146. TranslateOffset(CI, HLOperandIndex::kSampleOffsetArgIndex,
  2147. offsetDimensions);
  2148. SetClamp(CI, HLOperandIndex::kSampleClampArgIndex);
  2149. SetStatus(CI, HLOperandIndex::kSampleStatusArgIndex);
  2150. break;
  2151. case OP::OpCode::SampleLevel:
  2152. special = CI->getArgOperand(HLOperandIndex::kSampleLLevelArgIndex);
  2153. TranslateOffset(CI, HLOperandIndex::kSampleLOffsetArgIndex,
  2154. offsetDimensions);
  2155. SetStatus(CI, HLOperandIndex::kSampleLStatusArgIndex);
  2156. break;
  2157. case OP::OpCode::SampleBias:
  2158. special = CI->getArgOperand(HLOperandIndex::kSampleBBiasArgIndex);
  2159. TranslateOffset(CI, HLOperandIndex::kSampleBOffsetArgIndex,
  2160. offsetDimensions);
  2161. SetClamp(CI, HLOperandIndex::kSampleBClampArgIndex);
  2162. SetStatus(CI, HLOperandIndex::kSampleBStatusArgIndex);
  2163. break;
  2164. case OP::OpCode::SampleCmp:
  2165. special = CI->getArgOperand(HLOperandIndex::kSampleCmpCmpValArgIndex);
  2166. TranslateOffset(CI, HLOperandIndex::kSampleCmpOffsetArgIndex,
  2167. offsetDimensions);
  2168. SetClamp(CI, HLOperandIndex::kSampleCmpClampArgIndex);
  2169. SetStatus(CI, HLOperandIndex::kSampleCmpStatusArgIndex);
  2170. break;
  2171. case OP::OpCode::SampleCmpLevelZero:
  2172. special = CI->getArgOperand(HLOperandIndex::kSampleCmpLZCmpValArgIndex);
  2173. TranslateOffset(CI, HLOperandIndex::kSampleCmpLZOffsetArgIndex,
  2174. offsetDimensions);
  2175. SetStatus(CI, HLOperandIndex::kSampleCmpLZStatusArgIndex);
  2176. break;
  2177. case OP::OpCode::SampleGrad:
  2178. SetDDXY(CI, ddx, CI->getArgOperand(HLOperandIndex::kSampleGDDXArgIndex),
  2179. offsetDimensions);
  2180. SetDDXY(CI, ddy, CI->getArgOperand(HLOperandIndex::kSampleGDDYArgIndex),
  2181. offsetDimensions);
  2182. TranslateOffset(CI, HLOperandIndex::kSampleGOffsetArgIndex,
  2183. offsetDimensions);
  2184. SetClamp(CI, HLOperandIndex::kSampleGClampArgIndex);
  2185. SetStatus(CI, HLOperandIndex::kSampleGStatusArgIndex);
  2186. break;
  2187. case OP::OpCode::CalculateLOD:
  2188. // Only need coord for LOD calculation.
  2189. break;
  2190. default:
  2191. DXASSERT(0, "invalid opcode for Sample");
  2192. break;
  2193. }
  2194. }
  2195. Value *TranslateCalculateLOD(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2196. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2197. hlsl::OP *hlslOP = &helper.hlslOP;
  2198. SampleHelper sampleHelper(CI, OP::OpCode::CalculateLOD, pObjHelper);
  2199. if (sampleHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2200. Translated = false;
  2201. return nullptr;
  2202. }
  2203. bool bClamped = IOP == IntrinsicOp::MOP_CalculateLevelOfDetail;
  2204. IRBuilder<> Builder(CI);
  2205. Value *opArg =
  2206. hlslOP->GetU32Const(static_cast<unsigned>(OP::OpCode::CalculateLOD));
  2207. Value *clamped = hlslOP->GetI1Const(bClamped);
  2208. Value *args[] = {opArg,
  2209. sampleHelper.texHandle,
  2210. sampleHelper.samplerHandle,
  2211. sampleHelper.coord[0],
  2212. sampleHelper.coord[1],
  2213. sampleHelper.coord[2],
  2214. clamped};
  2215. Function *dxilFunc = hlslOP->GetOpFunc(OP::OpCode::CalculateLOD,
  2216. Type::getFloatTy(opArg->getContext()));
  2217. Value *LOD = Builder.CreateCall(dxilFunc, args);
  2218. return LOD;
  2219. }
  2220. Value *TranslateCheckAccess(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2221. HLOperationLowerHelper &helper,
  2222. HLObjectOperationLowerHelper *pObjHelper,
  2223. bool &Translated) {
  2224. // Translate CheckAccess into uint->bool, later optimization should remove it.
  2225. // Real checkaccess is generated in UpdateStatus.
  2226. IRBuilder<> Builder(CI);
  2227. Value *V = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  2228. return Builder.CreateTrunc(V, helper.i1Ty);
  2229. }
  2230. void GenerateDxilSample(CallInst *CI, Function *F, ArrayRef<Value *> sampleArgs,
  2231. Value *status, hlsl::OP *hlslOp) {
  2232. IRBuilder<> Builder(CI);
  2233. CallInst *call = Builder.CreateCall(F, sampleArgs);
  2234. // extract value part
  2235. Value *retVal = ScalarizeResRet(CI->getType(), call, Builder);
  2236. // Replace ret val.
  2237. CI->replaceAllUsesWith(retVal);
  2238. // get status
  2239. if (status) {
  2240. UpdateStatus(call, status, Builder, hlslOp);
  2241. }
  2242. }
  2243. Value *TranslateSample(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2244. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2245. hlsl::OP *hlslOP = &helper.hlslOP;
  2246. SampleHelper sampleHelper(CI, opcode, pObjHelper);
  2247. if (sampleHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2248. Translated = false;
  2249. return nullptr;
  2250. }
  2251. Type *Ty = CI->getType();
  2252. Function *F = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  2253. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  2254. switch (opcode) {
  2255. case OP::OpCode::Sample: {
  2256. Value *sampleArgs[] = {
  2257. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2258. // Coord.
  2259. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2260. sampleHelper.coord[3],
  2261. // Offset.
  2262. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2263. // Clamp.
  2264. sampleHelper.clamp};
  2265. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status, hlslOP);
  2266. } break;
  2267. case OP::OpCode::SampleLevel: {
  2268. Value *sampleArgs[] = {
  2269. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2270. // Coord.
  2271. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2272. sampleHelper.coord[3],
  2273. // Offset.
  2274. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2275. // LOD.
  2276. sampleHelper.special};
  2277. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status, hlslOP);
  2278. } break;
  2279. case OP::OpCode::SampleGrad: {
  2280. Value *sampleArgs[] = {
  2281. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2282. // Coord.
  2283. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2284. sampleHelper.coord[3],
  2285. // Offset.
  2286. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2287. // Ddx.
  2288. sampleHelper.ddx[0], sampleHelper.ddx[1], sampleHelper.ddx[2],
  2289. // Ddy.
  2290. sampleHelper.ddy[0], sampleHelper.ddy[1], sampleHelper.ddy[2],
  2291. // Clamp.
  2292. sampleHelper.clamp};
  2293. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status, hlslOP);
  2294. } break;
  2295. case OP::OpCode::SampleBias: {
  2296. // Clamp bias for immediate.
  2297. Value *bias = sampleHelper.special;
  2298. if (ConstantFP *FP = dyn_cast<ConstantFP>(bias)) {
  2299. float v = FP->getValueAPF().convertToFloat();
  2300. if (v > DXIL::kMaxMipLodBias)
  2301. bias = ConstantFP::get(FP->getType(), DXIL::kMaxMipLodBias);
  2302. if (v < DXIL::kMinMipLodBias)
  2303. bias = ConstantFP::get(FP->getType(), DXIL::kMinMipLodBias);
  2304. }
  2305. Value *sampleArgs[] = {
  2306. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2307. // Coord.
  2308. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2309. sampleHelper.coord[3],
  2310. // Offset.
  2311. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2312. // Bias.
  2313. bias,
  2314. // Clamp.
  2315. sampleHelper.clamp};
  2316. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status, hlslOP);
  2317. } break;
  2318. case OP::OpCode::SampleCmp: {
  2319. Value *sampleArgs[] = {
  2320. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2321. // Coord.
  2322. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2323. sampleHelper.coord[3],
  2324. // Offset.
  2325. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2326. // CmpVal.
  2327. sampleHelper.special,
  2328. // Clamp.
  2329. sampleHelper.clamp};
  2330. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status, hlslOP);
  2331. } break;
  2332. case OP::OpCode::SampleCmpLevelZero:
  2333. default: {
  2334. DXASSERT(opcode == OP::OpCode::SampleCmpLevelZero, "invalid sample opcode");
  2335. Value *sampleArgs[] = {
  2336. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2337. // Coord.
  2338. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2339. sampleHelper.coord[3],
  2340. // Offset.
  2341. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2342. // CmpVal.
  2343. sampleHelper.special};
  2344. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status, hlslOP);
  2345. } break;
  2346. }
  2347. // CI is replaced in GenerateDxilSample.
  2348. return nullptr;
  2349. }
  2350. // Gather intrinsics.
  2351. struct GatherHelper {
  2352. enum class GatherChannel {
  2353. GatherAll,
  2354. GatherRed,
  2355. GatherGreen,
  2356. GatherBlue,
  2357. GatherAlpha,
  2358. };
  2359. GatherHelper(CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper,
  2360. GatherHelper::GatherChannel ch);
  2361. OP::OpCode opcode;
  2362. Value *texHandle;
  2363. Value *samplerHandle;
  2364. static const unsigned kMaxCoordDimensions = 4;
  2365. Value *coord[kMaxCoordDimensions];
  2366. unsigned channel;
  2367. Value *special; // For CompareValue, Bias, LOD.
  2368. // Optional.
  2369. static const unsigned kMaxOffsetDimensions = 2;
  2370. Value *offset[kMaxOffsetDimensions];
  2371. // For the overload send different offset for each sample.
  2372. // Only save 3 sampleOffsets because use offset for normal overload as first
  2373. // sample offset.
  2374. static const unsigned kSampleOffsetDimensions = 3;
  2375. Value *sampleOffsets[kSampleOffsetDimensions][kMaxOffsetDimensions];
  2376. Value *status;
  2377. bool hasSampleOffsets;
  2378. void TranslateCoord(CallInst *CI, unsigned coordIdx,
  2379. unsigned coordDimensions) {
  2380. Value *coordArg = CI->getArgOperand(coordIdx);
  2381. IRBuilder<> Builder(CI);
  2382. for (unsigned i = 0; i < coordDimensions; i++)
  2383. coord[i] = Builder.CreateExtractElement(coordArg, i);
  2384. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2385. for (unsigned i = coordDimensions; i < kMaxCoordDimensions; i++)
  2386. coord[i] = undefF;
  2387. }
  2388. void SetStatus(CallInst *CI, unsigned statusIdx) {
  2389. if (CI->getNumArgOperands() == (statusIdx + 1))
  2390. status = CI->getArgOperand(statusIdx);
  2391. else
  2392. status = nullptr;
  2393. }
  2394. void TranslateOffset(CallInst *CI, unsigned offsetIdx,
  2395. unsigned offsetDimensions) {
  2396. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2397. if (CI->getNumArgOperands() > offsetIdx) {
  2398. Value *offsetArg = CI->getArgOperand(offsetIdx);
  2399. IRBuilder<> Builder(CI);
  2400. for (unsigned i = 0; i < offsetDimensions; i++)
  2401. offset[i] = Builder.CreateExtractElement(offsetArg, i);
  2402. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2403. offset[i] = undefI;
  2404. } else {
  2405. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2406. offset[i] = undefI;
  2407. }
  2408. }
  2409. void TranslateSampleOffset(CallInst *CI, unsigned offsetIdx,
  2410. unsigned offsetDimensions) {
  2411. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2412. if (CI->getNumArgOperands() >= (offsetIdx + kSampleOffsetDimensions)) {
  2413. hasSampleOffsets = true;
  2414. IRBuilder<> Builder(CI);
  2415. for (unsigned ch = 0; ch < kSampleOffsetDimensions; ch++) {
  2416. Value *offsetArg = CI->getArgOperand(offsetIdx + ch);
  2417. for (unsigned i = 0; i < offsetDimensions; i++)
  2418. sampleOffsets[ch][i] = Builder.CreateExtractElement(offsetArg, i);
  2419. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2420. sampleOffsets[ch][i] = undefI;
  2421. }
  2422. }
  2423. }
  2424. // Update the offset args for gather with sample offset at sampleIdx.
  2425. void UpdateOffsetInGatherArgs(MutableArrayRef<Value *> gatherArgs,
  2426. unsigned sampleIdx) {
  2427. unsigned offsetBase = DXIL::OperandIndex::kTextureGatherOffset0OpIdx;
  2428. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2429. // -1 because offset for sample 0 is in GatherHelper::offset.
  2430. gatherArgs[offsetBase + i] = sampleOffsets[sampleIdx - 1][i];
  2431. }
  2432. };
  2433. GatherHelper::GatherHelper(
  2434. CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper,
  2435. GatherHelper::GatherChannel ch)
  2436. : opcode(op), special(nullptr), hasSampleOffsets(false) {
  2437. const unsigned thisIdx =
  2438. HLOperandIndex::kHandleOpIdx; // opcode takes arg0, this pointer is arg1.
  2439. const unsigned kSamplerArgIndex = HLOperandIndex::kSampleSamplerArgIndex;
  2440. switch (ch) {
  2441. case GatherChannel::GatherAll:
  2442. channel = 0;
  2443. break;
  2444. case GatherChannel::GatherRed:
  2445. channel = 0;
  2446. break;
  2447. case GatherChannel::GatherGreen:
  2448. channel = 1;
  2449. break;
  2450. case GatherChannel::GatherBlue:
  2451. channel = 2;
  2452. break;
  2453. case GatherChannel::GatherAlpha:
  2454. channel = 3;
  2455. break;
  2456. }
  2457. IRBuilder<> Builder(CI);
  2458. texHandle = CI->getArgOperand(thisIdx);
  2459. samplerHandle = CI->getArgOperand(kSamplerArgIndex);
  2460. DXIL::ResourceKind RK = pObjHelper->GetRK(texHandle);
  2461. if (RK == DXIL::ResourceKind::Invalid) {
  2462. opcode = DXIL::OpCode::NumOpCodes;
  2463. return;
  2464. }
  2465. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2466. unsigned offsetSize = DxilResource::GetNumOffsets(RK);
  2467. const unsigned kCoordArgIdx = HLOperandIndex::kSampleCoordArgIndex;
  2468. TranslateCoord(CI, kCoordArgIdx, coordSize);
  2469. switch (op) {
  2470. case OP::OpCode::TextureGather: {
  2471. TranslateOffset(CI, HLOperandIndex::kGatherOffsetArgIndex, offsetSize);
  2472. // Gather all don't have sample offset version overload.
  2473. if (ch != GatherChannel::GatherAll)
  2474. TranslateSampleOffset(CI, HLOperandIndex::kGatherSampleOffsetArgIndex,
  2475. offsetSize);
  2476. unsigned statusIdx =
  2477. hasSampleOffsets ? HLOperandIndex::kGatherStatusWithSampleOffsetArgIndex
  2478. : HLOperandIndex::kGatherStatusArgIndex;
  2479. SetStatus(CI, statusIdx);
  2480. } break;
  2481. case OP::OpCode::TextureGatherCmp: {
  2482. special = CI->getArgOperand(HLOperandIndex::kGatherCmpCmpValArgIndex);
  2483. TranslateOffset(CI, HLOperandIndex::kGatherCmpOffsetArgIndex, offsetSize);
  2484. // Gather all don't have sample offset version overload.
  2485. if (ch != GatherChannel::GatherAll)
  2486. TranslateSampleOffset(CI, HLOperandIndex::kGatherCmpSampleOffsetArgIndex,
  2487. offsetSize);
  2488. unsigned statusIdx =
  2489. hasSampleOffsets
  2490. ? HLOperandIndex::kGatherCmpStatusWithSampleOffsetArgIndex
  2491. : HLOperandIndex::kGatherCmpStatusArgIndex;
  2492. SetStatus(CI, statusIdx);
  2493. } break;
  2494. default:
  2495. DXASSERT(0, "invalid opcode for Gather");
  2496. break;
  2497. }
  2498. }
  2499. void GenerateDxilGather(CallInst *CI, Function *F,
  2500. MutableArrayRef<Value *> gatherArgs,
  2501. GatherHelper &helper, hlsl::OP *hlslOp) {
  2502. IRBuilder<> Builder(CI);
  2503. CallInst *call = Builder.CreateCall(F, gatherArgs);
  2504. if (!helper.hasSampleOffsets) {
  2505. // extract value part
  2506. Value *retVal = ScalarizeResRet(CI->getType(), call, Builder);
  2507. // Replace ret val.
  2508. CI->replaceAllUsesWith(retVal);
  2509. } else {
  2510. Value *retVal = UndefValue::get(CI->getType());
  2511. Value *elt = Builder.CreateExtractValue(call, (uint64_t)0);
  2512. retVal = Builder.CreateInsertElement(retVal, elt, (uint64_t)0);
  2513. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 1);
  2514. CallInst *callY = Builder.CreateCall(F, gatherArgs);
  2515. elt = Builder.CreateExtractValue(callY, (uint64_t)1);
  2516. retVal = Builder.CreateInsertElement(retVal, elt, 1);
  2517. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 2);
  2518. CallInst *callZ = Builder.CreateCall(F, gatherArgs);
  2519. elt = Builder.CreateExtractValue(callZ, (uint64_t)2);
  2520. retVal = Builder.CreateInsertElement(retVal, elt, 2);
  2521. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 3);
  2522. CallInst *callW = Builder.CreateCall(F, gatherArgs);
  2523. elt = Builder.CreateExtractValue(callW, (uint64_t)3);
  2524. retVal = Builder.CreateInsertElement(retVal, elt, 3);
  2525. // Replace ret val.
  2526. CI->replaceAllUsesWith(retVal);
  2527. // TODO: UpdateStatus for each gather call.
  2528. }
  2529. // Get status
  2530. if (helper.status) {
  2531. UpdateStatus(call, helper.status, Builder, hlslOp);
  2532. }
  2533. }
  2534. Value *TranslateGather(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2535. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2536. hlsl::OP *hlslOP = &helper.hlslOP;
  2537. GatherHelper::GatherChannel ch = GatherHelper::GatherChannel::GatherAll;
  2538. switch (IOP) {
  2539. case IntrinsicOp::MOP_Gather:
  2540. case IntrinsicOp::MOP_GatherCmp:
  2541. ch = GatherHelper::GatherChannel::GatherAll;
  2542. break;
  2543. case IntrinsicOp::MOP_GatherRed:
  2544. case IntrinsicOp::MOP_GatherCmpRed:
  2545. ch = GatherHelper::GatherChannel::GatherRed;
  2546. break;
  2547. case IntrinsicOp::MOP_GatherGreen:
  2548. case IntrinsicOp::MOP_GatherCmpGreen:
  2549. ch = GatherHelper::GatherChannel::GatherGreen;
  2550. break;
  2551. case IntrinsicOp::MOP_GatherBlue:
  2552. case IntrinsicOp::MOP_GatherCmpBlue:
  2553. ch = GatherHelper::GatherChannel::GatherBlue;
  2554. break;
  2555. case IntrinsicOp::MOP_GatherAlpha:
  2556. case IntrinsicOp::MOP_GatherCmpAlpha:
  2557. ch = GatherHelper::GatherChannel::GatherAlpha;
  2558. break;
  2559. default:
  2560. DXASSERT(0, "invalid gather intrinsic");
  2561. break;
  2562. }
  2563. GatherHelper gatherHelper(CI, opcode, pObjHelper, ch);
  2564. if (gatherHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2565. Translated = false;
  2566. return nullptr;
  2567. }
  2568. Type *Ty = CI->getType();
  2569. Function *F = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  2570. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  2571. Value *channelArg = hlslOP->GetU32Const(gatherHelper.channel);
  2572. switch (opcode) {
  2573. case OP::OpCode::TextureGather: {
  2574. Value *gatherArgs[] = {
  2575. opArg, gatherHelper.texHandle, gatherHelper.samplerHandle,
  2576. // Coord.
  2577. gatherHelper.coord[0], gatherHelper.coord[1], gatherHelper.coord[2],
  2578. gatherHelper.coord[3],
  2579. // Offset.
  2580. gatherHelper.offset[0], gatherHelper.offset[1],
  2581. // Channel.
  2582. channelArg};
  2583. GenerateDxilGather(CI, F, gatherArgs, gatherHelper, hlslOP);
  2584. } break;
  2585. case OP::OpCode::TextureGatherCmp: {
  2586. Value *gatherArgs[] = {
  2587. opArg, gatherHelper.texHandle, gatherHelper.samplerHandle,
  2588. // Coord.
  2589. gatherHelper.coord[0], gatherHelper.coord[1], gatherHelper.coord[2],
  2590. gatherHelper.coord[3],
  2591. // Offset.
  2592. gatherHelper.offset[0], gatherHelper.offset[1],
  2593. // Channel.
  2594. channelArg,
  2595. // CmpVal.
  2596. gatherHelper.special};
  2597. GenerateDxilGather(CI, F, gatherArgs, gatherHelper, hlslOP);
  2598. } break;
  2599. default:
  2600. DXASSERT(0, "invalid opcode for Gather");
  2601. break;
  2602. }
  2603. // CI is replaced in GenerateDxilGather.
  2604. return nullptr;
  2605. }
  2606. // Load/Store intrinsics.
  2607. struct ResLoadHelper {
  2608. ResLoadHelper(CallInst *CI, DxilResource::Kind RK, DxilResourceBase::Class RC,
  2609. Value *h, IntrinsicOp IOP, bool bForSubscript=false);
  2610. ResLoadHelper(CallInst *CI, DxilResource::Kind RK, DxilResourceBase::Class RC,
  2611. Value *h, Value *mip);
  2612. // For double subscript.
  2613. ResLoadHelper(Instruction *ldInst, Value *h, Value *idx, Value *mip)
  2614. : opcode(OP::OpCode::TextureLoad),
  2615. intrinsicOpCode(IntrinsicOp::Num_Intrinsics), handle(h), retVal(ldInst),
  2616. addr(idx), offset(nullptr), status(nullptr), mipLevel(mip) {}
  2617. OP::OpCode opcode;
  2618. IntrinsicOp intrinsicOpCode;
  2619. unsigned dxilMajor;
  2620. unsigned dxilMinor;
  2621. Value *handle;
  2622. Value *retVal;
  2623. Value *addr;
  2624. Value *offset;
  2625. Value *status;
  2626. Value *mipLevel;
  2627. };
  2628. ResLoadHelper::ResLoadHelper(CallInst *CI, DxilResource::Kind RK,
  2629. DxilResourceBase::Class RC, Value *hdl, IntrinsicOp IOP, bool bForSubscript)
  2630. : intrinsicOpCode(IOP), handle(hdl), offset(nullptr), status(nullptr) {
  2631. switch (RK) {
  2632. case DxilResource::Kind::RawBuffer:
  2633. case DxilResource::Kind::StructuredBuffer:
  2634. opcode = OP::OpCode::RawBufferLoad;
  2635. break;
  2636. case DxilResource::Kind::TypedBuffer:
  2637. opcode = OP::OpCode::BufferLoad;
  2638. break;
  2639. case DxilResource::Kind::Invalid:
  2640. DXASSERT(0, "invalid resource kind");
  2641. break;
  2642. default:
  2643. opcode = OP::OpCode::TextureLoad;
  2644. break;
  2645. }
  2646. retVal = CI;
  2647. const unsigned kAddrIdx = HLOperandIndex::kBufLoadAddrOpIdx;
  2648. addr = CI->getArgOperand(kAddrIdx);
  2649. unsigned argc = CI->getNumArgOperands();
  2650. if (opcode == OP::OpCode::TextureLoad) {
  2651. // mip at last channel
  2652. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2653. if (RC == DxilResourceBase::Class::SRV) {
  2654. if (bForSubscript) {
  2655. // Use 0 when access by [].
  2656. mipLevel = IRBuilder<>(CI).getInt32(0);
  2657. } else {
  2658. if (coordSize == 1 && !addr->getType()->isVectorTy()) {
  2659. // Use addr when access by Load.
  2660. mipLevel = addr;
  2661. } else {
  2662. mipLevel = IRBuilder<>(CI).CreateExtractElement(addr, coordSize);
  2663. }
  2664. }
  2665. } else {
  2666. // Set mip level to undef for UAV.
  2667. mipLevel = UndefValue::get(Type::getInt32Ty(addr->getContext()));
  2668. }
  2669. if (RC == DxilResourceBase::Class::SRV) {
  2670. unsigned offsetIdx = HLOperandIndex::kTexLoadOffsetOpIdx;
  2671. unsigned statusIdx = HLOperandIndex::kTexLoadStatusOpIdx;
  2672. if (RK == DxilResource::Kind::Texture2DMS ||
  2673. RK == DxilResource::Kind::Texture2DMSArray) {
  2674. offsetIdx = HLOperandIndex::kTex2DMSLoadOffsetOpIdx;
  2675. statusIdx = HLOperandIndex::kTex2DMSLoadStatusOpIdx;
  2676. mipLevel =
  2677. CI->getArgOperand(HLOperandIndex::kTex2DMSLoadSampleIdxOpIdx);
  2678. }
  2679. if (argc > offsetIdx)
  2680. offset = CI->getArgOperand(offsetIdx);
  2681. if (argc > statusIdx)
  2682. status = CI->getArgOperand(statusIdx);
  2683. } else {
  2684. const unsigned kStatusIdx = HLOperandIndex::kRWTexLoadStatusOpIdx;
  2685. if (argc > kStatusIdx)
  2686. status = CI->getArgOperand(kStatusIdx);
  2687. }
  2688. } else {
  2689. const unsigned kStatusIdx = HLOperandIndex::kBufLoadStatusOpIdx;
  2690. if (argc > kStatusIdx)
  2691. status = CI->getArgOperand(kStatusIdx);
  2692. }
  2693. }
  2694. ResLoadHelper::ResLoadHelper(CallInst *CI, DxilResource::Kind RK,
  2695. DxilResourceBase::Class RC, Value *hdl, Value *mip)
  2696. : handle(hdl), offset(nullptr), status(nullptr) {
  2697. DXASSERT(RK != DxilResource::Kind::RawBuffer &&
  2698. RK != DxilResource::Kind::TypedBuffer &&
  2699. RK != DxilResource::Kind::Invalid,
  2700. "invalid resource kind");
  2701. opcode = OP::OpCode::TextureLoad;
  2702. retVal = CI;
  2703. mipLevel = mip;
  2704. const unsigned kAddrIdx = HLOperandIndex::kMipLoadAddrOpIdx;
  2705. addr = CI->getArgOperand(kAddrIdx);
  2706. unsigned argc = CI->getNumArgOperands();
  2707. const unsigned kOffsetIdx = HLOperandIndex::kMipLoadOffsetOpIdx;
  2708. const unsigned kStatusIdx = HLOperandIndex::kMipLoadStatusOpIdx;
  2709. if (argc > kOffsetIdx)
  2710. offset = CI->getArgOperand(kOffsetIdx);
  2711. if (argc > kStatusIdx)
  2712. status = CI->getArgOperand(kStatusIdx);
  2713. }
  2714. void TranslateStructBufSubscript(CallInst *CI, Value *handle, Value *status,
  2715. hlsl::OP *OP, const DataLayout &DL);
  2716. // Create { v0, v1 } from { v0.lo, v0.hi, v1.lo, v1.hi }
  2717. void Make64bitResultForLoad(Type *EltTy, ArrayRef<Value *> resultElts32,
  2718. unsigned size, MutableArrayRef<Value *> resultElts,
  2719. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  2720. Type *i64Ty = Builder.getInt64Ty();
  2721. Type *doubleTy = Builder.getDoubleTy();
  2722. if (EltTy == doubleTy) {
  2723. Function *makeDouble =
  2724. hlslOP->GetOpFunc(DXIL::OpCode::MakeDouble, doubleTy);
  2725. Value *makeDoubleOpArg =
  2726. Builder.getInt32((unsigned)DXIL::OpCode::MakeDouble);
  2727. for (unsigned i = 0; i < size; i++) {
  2728. Value *lo = resultElts32[2 * i];
  2729. Value *hi = resultElts32[2 * i + 1];
  2730. Value *V = Builder.CreateCall(makeDouble, {makeDoubleOpArg, lo, hi});
  2731. resultElts[i] = V;
  2732. }
  2733. } else {
  2734. for (unsigned i = 0; i < size; i++) {
  2735. Value *lo = resultElts32[2 * i];
  2736. Value *hi = resultElts32[2 * i + 1];
  2737. lo = Builder.CreateZExt(lo, i64Ty);
  2738. hi = Builder.CreateZExt(hi, i64Ty);
  2739. hi = Builder.CreateShl(hi, 32);
  2740. resultElts[i] = Builder.CreateOr(lo, hi);
  2741. }
  2742. }
  2743. }
  2744. static uint8_t GetRawBufferMaskFromIOP(IntrinsicOp IOP, hlsl::OP *OP) {
  2745. switch (IOP) {
  2746. // one component
  2747. case IntrinsicOp::MOP_Load:
  2748. return DXIL::kCompMask_X;
  2749. // two component
  2750. case IntrinsicOp::MOP_Load2:
  2751. return DXIL::kCompMask_X | DXIL::kCompMask_Y;
  2752. // three component
  2753. case IntrinsicOp::MOP_Load3:
  2754. return DXIL::kCompMask_X | DXIL::kCompMask_Y | DXIL::kCompMask_Z;
  2755. // four component
  2756. case IntrinsicOp::MOP_Load4:
  2757. return DXIL::kCompMask_All;
  2758. default:
  2759. DXASSERT(false, "Invalid Intrinsic for computing load mask.");
  2760. return 0;
  2761. }
  2762. }
  2763. static Constant *GetRawBufferMaskForETy(Type *Ty, unsigned NumComponents, hlsl::OP *OP) {
  2764. Type *ETy = Ty->getScalarType();
  2765. bool is64 = ETy->isDoubleTy() || ETy == Type::getInt64Ty(ETy->getContext());
  2766. unsigned mask = 0;
  2767. if (is64) {
  2768. switch (NumComponents) {
  2769. case 0:
  2770. break;
  2771. case 1:
  2772. mask = DXIL::kCompMask_X | DXIL::kCompMask_Y;
  2773. break;
  2774. case 2:
  2775. mask = DXIL::kCompMask_All;
  2776. break;
  2777. default:
  2778. DXASSERT(false, "Cannot load more than 2 components for 64bit types.");
  2779. }
  2780. }
  2781. else {
  2782. switch (NumComponents) {
  2783. case 0:
  2784. break;
  2785. case 1:
  2786. mask = DXIL::kCompMask_X;
  2787. break;
  2788. case 2:
  2789. mask = DXIL::kCompMask_X | DXIL::kCompMask_Y;
  2790. break;
  2791. case 3:
  2792. mask = DXIL::kCompMask_X | DXIL::kCompMask_Y | DXIL::kCompMask_Z;
  2793. break;
  2794. case 4:
  2795. mask = DXIL::kCompMask_All;
  2796. break;
  2797. default:
  2798. DXASSERT(false, "Cannot load more than 2 components for 64bit types.");
  2799. }
  2800. }
  2801. return OP->GetI8Const(mask);
  2802. }
  2803. void TranslateLoad(ResLoadHelper &helper, HLResource::Kind RK,
  2804. IRBuilder<> &Builder, hlsl::OP *OP, const DataLayout &DL) {
  2805. Type *Ty = helper.retVal->getType();
  2806. if (Ty->isPointerTy()) {
  2807. TranslateStructBufSubscript(cast<CallInst>(helper.retVal), helper.handle,
  2808. helper.status, OP, DL);
  2809. return;
  2810. }
  2811. OP::OpCode opcode = helper.opcode;
  2812. Type *i32Ty = Builder.getInt32Ty();
  2813. Type *i64Ty = Builder.getInt64Ty();
  2814. Type *doubleTy = Builder.getDoubleTy();
  2815. Type *EltTy = Ty->getScalarType();
  2816. Constant *Alignment = OP->GetI32Const(OP->GetAllocSizeForType(EltTy));
  2817. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  2818. if (is64) {
  2819. EltTy = i32Ty;
  2820. }
  2821. Function *F = OP->GetOpFunc(opcode, EltTy);
  2822. llvm::Constant *opArg = OP->GetU32Const((unsigned)opcode);
  2823. llvm::Value *undefI = llvm::UndefValue::get(i32Ty);
  2824. SmallVector<Value *, 12> loadArgs;
  2825. loadArgs.emplace_back(opArg); // opcode
  2826. loadArgs.emplace_back(helper.handle); // resource handle
  2827. if (opcode == OP::OpCode::TextureLoad) {
  2828. // set mip level
  2829. loadArgs.emplace_back(helper.mipLevel);
  2830. }
  2831. if (opcode == OP::OpCode::TextureLoad) {
  2832. // texture coord
  2833. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2834. bool isVectorAddr = helper.addr->getType()->isVectorTy();
  2835. for (unsigned i = 0; i < 3; i++) {
  2836. if (i < coordSize) {
  2837. loadArgs.emplace_back(
  2838. isVectorAddr ? Builder.CreateExtractElement(helper.addr, i) : helper.addr);
  2839. }
  2840. else
  2841. loadArgs.emplace_back(undefI);
  2842. }
  2843. } else {
  2844. if (helper.addr->getType()->isVectorTy()) {
  2845. Value *scalarOffset =
  2846. Builder.CreateExtractElement(helper.addr, (uint64_t)0);
  2847. // TODO: calculate the real address based on opcode
  2848. loadArgs.emplace_back(scalarOffset); // offset
  2849. } else {
  2850. // TODO: calculate the real address based on opcode
  2851. loadArgs.emplace_back(helper.addr); // offset
  2852. }
  2853. }
  2854. // offset 0
  2855. if (opcode == OP::OpCode::TextureLoad) {
  2856. if (helper.offset && !isa<llvm::UndefValue>(helper.offset)) {
  2857. unsigned offsetSize = DxilResource::GetNumOffsets(RK);
  2858. for (unsigned i = 0; i < 3; i++) {
  2859. if (i < offsetSize)
  2860. loadArgs.emplace_back(Builder.CreateExtractElement(helper.offset, i));
  2861. else
  2862. loadArgs.emplace_back(undefI);
  2863. }
  2864. } else {
  2865. loadArgs.emplace_back(undefI);
  2866. loadArgs.emplace_back(undefI);
  2867. loadArgs.emplace_back(undefI);
  2868. }
  2869. }
  2870. // Offset 1
  2871. if (RK == DxilResource::Kind::RawBuffer) {
  2872. // elementOffset, mask, alignment
  2873. loadArgs.emplace_back(undefI);
  2874. Type *rtnTy = helper.retVal->getType();
  2875. unsigned numComponents = 1;
  2876. if (VectorType *VTy = dyn_cast<VectorType>(rtnTy)) {
  2877. rtnTy = VTy->getElementType();
  2878. numComponents = VTy->getNumElements();
  2879. }
  2880. loadArgs.emplace_back(GetRawBufferMaskForETy(rtnTy, numComponents, OP));
  2881. loadArgs.emplace_back(Alignment);
  2882. }
  2883. else if (RK == DxilResource::Kind::TypedBuffer) {
  2884. loadArgs.emplace_back(undefI);
  2885. }
  2886. else if (RK == DxilResource::Kind::StructuredBuffer) {
  2887. // elementOffset, mask, alignment
  2888. loadArgs.emplace_back(
  2889. OP->GetU32Const(0)); // For case use built-in types in structure buffer.
  2890. loadArgs.emplace_back(OP->GetU8Const(0)); // When is this case hit?
  2891. loadArgs.emplace_back(Alignment);
  2892. }
  2893. Value *ResRet =
  2894. Builder.CreateCall(F, loadArgs, OP->GetOpCodeName(opcode));
  2895. Value *retValNew = nullptr;
  2896. if (!is64) {
  2897. retValNew = ScalarizeResRet(Ty, ResRet, Builder);
  2898. } else {
  2899. unsigned size = 1;
  2900. if (Ty->isVectorTy()) {
  2901. size = Ty->getVectorNumElements();
  2902. }
  2903. DXASSERT(size <= 2, "typed buffer only allow 4 dwords");
  2904. EltTy = Ty->getScalarType();
  2905. Value *Elts[2];
  2906. Make64bitResultForLoad(Ty->getScalarType(),
  2907. {
  2908. Builder.CreateExtractValue(ResRet, 0),
  2909. Builder.CreateExtractValue(ResRet, 1),
  2910. Builder.CreateExtractValue(ResRet, 2),
  2911. Builder.CreateExtractValue(ResRet, 3),
  2912. },
  2913. size, Elts, OP, Builder);
  2914. retValNew = ScalarizeElements(Ty, Elts, Builder);
  2915. }
  2916. // replace
  2917. helper.retVal->replaceAllUsesWith(retValNew);
  2918. // Save new ret val.
  2919. helper.retVal = retValNew;
  2920. // get status
  2921. UpdateStatus(ResRet, helper.status, Builder, OP);
  2922. }
  2923. Value *TranslateResourceLoad(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2924. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2925. hlsl::OP *hlslOP = &helper.hlslOP;
  2926. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  2927. IRBuilder<> Builder(CI);
  2928. DXIL::ResourceClass RC = pObjHelper->GetRC(handle);
  2929. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  2930. ResLoadHelper loadHelper(CI, RK, RC, handle, IOP);
  2931. TranslateLoad(loadHelper, RK, Builder, hlslOP, helper.dataLayout);
  2932. // CI is replaced in TranslateLoad.
  2933. return nullptr;
  2934. }
  2935. // Split { v0, v1 } to { v0.lo, v0.hi, v1.lo, v1.hi }
  2936. void Split64bitValForStore(Type *EltTy, ArrayRef<Value *> vals, unsigned size,
  2937. MutableArrayRef<Value *> vals32, hlsl::OP *hlslOP,
  2938. IRBuilder<> &Builder) {
  2939. Type *i32Ty = Builder.getInt32Ty();
  2940. Type *doubleTy = Builder.getDoubleTy();
  2941. Value *undefI32 = UndefValue::get(i32Ty);
  2942. if (EltTy == doubleTy) {
  2943. Function *dToU = hlslOP->GetOpFunc(DXIL::OpCode::SplitDouble, doubleTy);
  2944. Value *dToUOpArg = Builder.getInt32((unsigned)DXIL::OpCode::SplitDouble);
  2945. for (unsigned i = 0; i < size; i++) {
  2946. if (isa<UndefValue>(vals[i])) {
  2947. vals32[2 * i] = undefI32;
  2948. vals32[2 * i + 1] = undefI32;
  2949. } else {
  2950. Value *retVal = Builder.CreateCall(dToU, {dToUOpArg, vals[i]});
  2951. Value *lo = Builder.CreateExtractValue(retVal, 0);
  2952. Value *hi = Builder.CreateExtractValue(retVal, 1);
  2953. vals32[2 * i] = lo;
  2954. vals32[2 * i + 1] = hi;
  2955. }
  2956. }
  2957. } else {
  2958. for (unsigned i = 0; i < size; i++) {
  2959. if (isa<UndefValue>(vals[i])) {
  2960. vals32[2 * i] = undefI32;
  2961. vals32[2 * i + 1] = undefI32;
  2962. } else {
  2963. Value *lo = Builder.CreateTrunc(vals[i], i32Ty);
  2964. Value *hi = Builder.CreateLShr(vals[i], 32);
  2965. hi = Builder.CreateTrunc(hi, i32Ty);
  2966. vals32[2 * i] = lo;
  2967. vals32[2 * i + 1] = hi;
  2968. }
  2969. }
  2970. }
  2971. }
  2972. void TranslateStore(DxilResource::Kind RK, Value *handle, Value *val,
  2973. Value *offset, IRBuilder<> &Builder, hlsl::OP *OP) {
  2974. Type *Ty = val->getType();
  2975. OP::OpCode opcode;
  2976. switch (RK) {
  2977. case DxilResource::Kind::RawBuffer:
  2978. case DxilResource::Kind::StructuredBuffer:
  2979. opcode = OP::OpCode::RawBufferStore;
  2980. break;
  2981. case DxilResource::Kind::TypedBuffer:
  2982. opcode = OP::OpCode::BufferStore;
  2983. break;
  2984. case DxilResource::Kind::Invalid:
  2985. DXASSERT(0, "invalid resource kind");
  2986. break;
  2987. default:
  2988. opcode = OP::OpCode::TextureStore;
  2989. break;
  2990. }
  2991. Type *i32Ty = Builder.getInt32Ty();
  2992. Type *i64Ty = Builder.getInt64Ty();
  2993. Type *doubleTy = Builder.getDoubleTy();
  2994. Type *EltTy = Ty->getScalarType();
  2995. Constant *Alignment = OP->GetI32Const(OP->GetAllocSizeForType(EltTy));
  2996. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  2997. if (is64) {
  2998. EltTy = i32Ty;
  2999. }
  3000. Function *F = OP->GetOpFunc(opcode, EltTy);
  3001. llvm::Constant *opArg = OP->GetU32Const((unsigned)opcode);
  3002. llvm::Value *undefI =
  3003. llvm::UndefValue::get(llvm::Type::getInt32Ty(Ty->getContext()));
  3004. llvm::Value *undefVal = llvm::UndefValue::get(Ty->getScalarType());
  3005. SmallVector<Value *, 13> storeArgs;
  3006. storeArgs.emplace_back(opArg); // opcode
  3007. storeArgs.emplace_back(handle); // resource handle
  3008. if (RK == DxilResource::Kind::RawBuffer ||
  3009. RK == DxilResource::Kind::TypedBuffer) {
  3010. // Offset 0
  3011. if (offset->getType()->isVectorTy()) {
  3012. Value *scalarOffset = Builder.CreateExtractElement(offset, (uint64_t)0);
  3013. storeArgs.emplace_back(scalarOffset); // offset
  3014. } else {
  3015. storeArgs.emplace_back(offset); // offset
  3016. }
  3017. // Offset 1
  3018. storeArgs.emplace_back(undefI);
  3019. } else {
  3020. // texture store
  3021. unsigned coordSize = DxilResource::GetNumCoords(RK);
  3022. // Set x first.
  3023. if (offset->getType()->isVectorTy())
  3024. storeArgs.emplace_back(Builder.CreateExtractElement(offset, (uint64_t)0));
  3025. else
  3026. storeArgs.emplace_back(offset);
  3027. for (unsigned i = 1; i < 3; i++) {
  3028. if (i < coordSize)
  3029. storeArgs.emplace_back(Builder.CreateExtractElement(offset, i));
  3030. else
  3031. storeArgs.emplace_back(undefI);
  3032. }
  3033. // TODO: support mip for texture ST
  3034. }
  3035. // values
  3036. bool isTyped = opcode == OP::OpCode::TextureStore ||
  3037. RK == DxilResource::Kind::TypedBuffer;
  3038. uint8_t mask = 0;
  3039. if (Ty->isVectorTy()) {
  3040. unsigned vecSize = Ty->getVectorNumElements();
  3041. Value *emptyVal = undefVal;
  3042. if (isTyped) {
  3043. mask = DXIL::kCompMask_All;
  3044. emptyVal = Builder.CreateExtractElement(val, (uint64_t)0);
  3045. }
  3046. for (unsigned i = 0; i < 4; i++) {
  3047. if (i < vecSize) {
  3048. storeArgs.emplace_back(Builder.CreateExtractElement(val, i));
  3049. mask |= (1<<i);
  3050. } else {
  3051. storeArgs.emplace_back(emptyVal);
  3052. }
  3053. }
  3054. } else {
  3055. if (isTyped) {
  3056. mask = DXIL::kCompMask_All;
  3057. storeArgs.emplace_back(val);
  3058. storeArgs.emplace_back(val);
  3059. storeArgs.emplace_back(val);
  3060. storeArgs.emplace_back(val);
  3061. } else {
  3062. storeArgs.emplace_back(val);
  3063. storeArgs.emplace_back(undefVal);
  3064. storeArgs.emplace_back(undefVal);
  3065. storeArgs.emplace_back(undefVal);
  3066. mask = DXIL::kCompMask_X;
  3067. }
  3068. }
  3069. if (is64) {
  3070. unsigned size = 1;
  3071. if (Ty->isVectorTy()) {
  3072. size = Ty->getVectorNumElements();
  3073. }
  3074. DXASSERT(size <= 2, "raw/typed buffer only allow 4 dwords");
  3075. unsigned val0OpIdx = opcode == DXIL::OpCode::TextureStore
  3076. ? DXIL::OperandIndex::kTextureStoreVal0OpIdx
  3077. : DXIL::OperandIndex::kBufferStoreVal0OpIdx;
  3078. Value *V0 = storeArgs[val0OpIdx];
  3079. Value *V1 = storeArgs[val0OpIdx+1];
  3080. Value *vals32[4];
  3081. EltTy = Ty->getScalarType();
  3082. Split64bitValForStore(EltTy, {V0, V1}, size, vals32, OP, Builder);
  3083. // Fill the uninit vals.
  3084. if (size == 1) {
  3085. vals32[2] = vals32[0];
  3086. vals32[3] = vals32[1];
  3087. }
  3088. // Change valOp to 32 version.
  3089. for (unsigned i = 0; i < 4; i++) {
  3090. storeArgs[val0OpIdx + i] = vals32[i];
  3091. }
  3092. // change mask for double
  3093. if (opcode == DXIL::OpCode::RawBufferStore) {
  3094. mask = size == 1 ?
  3095. DXIL::kCompMask_X | DXIL::kCompMask_Y : DXIL::kCompMask_All;
  3096. }
  3097. }
  3098. storeArgs.emplace_back(OP->GetU8Const(mask)); // mask
  3099. if (opcode == DXIL::OpCode::RawBufferStore)
  3100. storeArgs.emplace_back(Alignment); // alignment only for raw buffer
  3101. Builder.CreateCall(F, storeArgs);
  3102. }
  3103. Value *TranslateResourceStore(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3104. HLOperationLowerHelper &helper,
  3105. HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3106. hlsl::OP *hlslOP = &helper.hlslOP;
  3107. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3108. IRBuilder<> Builder(CI);
  3109. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  3110. Value *val = CI->getArgOperand(HLOperandIndex::kStoreValOpIdx);
  3111. Value *offset = CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx);
  3112. TranslateStore(RK, handle, val, offset, Builder, hlslOP);
  3113. return nullptr;
  3114. }
  3115. }
  3116. // Atomic intrinsics.
  3117. namespace {
  3118. // Atomic intrinsics.
  3119. struct AtomicHelper {
  3120. AtomicHelper(CallInst *CI, OP::OpCode op, Value *h);
  3121. AtomicHelper(CallInst *CI, OP::OpCode op, Value *h, Value *bufIdx,
  3122. Value *baseOffset);
  3123. OP::OpCode opcode;
  3124. Value *handle;
  3125. Value *addr;
  3126. Value *offset; // Offset for structrued buffer.
  3127. Value *value;
  3128. Value *originalValue;
  3129. Value *compareValue;
  3130. };
  3131. // For MOP version of Interlocked*.
  3132. AtomicHelper::AtomicHelper(CallInst *CI, OP::OpCode op, Value *h)
  3133. : opcode(op), handle(h), offset(nullptr), originalValue(nullptr) {
  3134. addr = CI->getArgOperand(HLOperandIndex::kObjectInterlockedDestOpIndex);
  3135. if (op == OP::OpCode::AtomicCompareExchange) {
  3136. compareValue = CI->getArgOperand(
  3137. HLOperandIndex::kObjectInterlockedCmpCompareValueOpIndex);
  3138. value =
  3139. CI->getArgOperand(HLOperandIndex::kObjectInterlockedCmpValueOpIndex);
  3140. if (CI->getNumArgOperands() ==
  3141. (HLOperandIndex::kObjectInterlockedCmpOriginalValueOpIndex + 1))
  3142. originalValue = CI->getArgOperand(
  3143. HLOperandIndex::kObjectInterlockedCmpOriginalValueOpIndex);
  3144. } else {
  3145. value = CI->getArgOperand(HLOperandIndex::kObjectInterlockedValueOpIndex);
  3146. if (CI->getNumArgOperands() ==
  3147. (HLOperandIndex::kObjectInterlockedOriginalValueOpIndex + 1))
  3148. originalValue = CI->getArgOperand(
  3149. HLOperandIndex::kObjectInterlockedOriginalValueOpIndex);
  3150. }
  3151. }
  3152. // For IOP version of Interlocked*.
  3153. AtomicHelper::AtomicHelper(CallInst *CI, OP::OpCode op, Value *h, Value *bufIdx,
  3154. Value *baseOffset)
  3155. : opcode(op), handle(h), addr(bufIdx),
  3156. offset(baseOffset), originalValue(nullptr) {
  3157. if (op == OP::OpCode::AtomicCompareExchange) {
  3158. compareValue =
  3159. CI->getArgOperand(HLOperandIndex::kInterlockedCmpCompareValueOpIndex);
  3160. value = CI->getArgOperand(HLOperandIndex::kInterlockedCmpValueOpIndex);
  3161. if (CI->getNumArgOperands() ==
  3162. (HLOperandIndex::kInterlockedCmpOriginalValueOpIndex + 1))
  3163. originalValue = CI->getArgOperand(
  3164. HLOperandIndex::kInterlockedCmpOriginalValueOpIndex);
  3165. } else {
  3166. value = CI->getArgOperand(HLOperandIndex::kInterlockedValueOpIndex);
  3167. if (CI->getNumArgOperands() ==
  3168. (HLOperandIndex::kInterlockedOriginalValueOpIndex + 1))
  3169. originalValue =
  3170. CI->getArgOperand(HLOperandIndex::kInterlockedOriginalValueOpIndex);
  3171. }
  3172. }
  3173. void TranslateAtomicBinaryOperation(AtomicHelper &helper,
  3174. DXIL::AtomicBinOpCode atomicOp,
  3175. IRBuilder<> &Builder, hlsl::OP *hlslOP) {
  3176. Value *handle = helper.handle;
  3177. Value *addr = helper.addr;
  3178. Value *val = helper.value;
  3179. Type *Ty = val->getType();
  3180. Value *undefI = UndefValue::get(Type::getInt32Ty(Ty->getContext()));
  3181. Function *dxilAtomic = hlslOP->GetOpFunc(helper.opcode, Ty->getScalarType());
  3182. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(helper.opcode));
  3183. Value *atomicOpArg = hlslOP->GetU32Const(static_cast<unsigned>(atomicOp));
  3184. Value *args[] = {opArg, handle, atomicOpArg,
  3185. undefI, undefI, undefI, // coordinates
  3186. val};
  3187. // Setup coordinates.
  3188. if (addr->getType()->isVectorTy()) {
  3189. unsigned vectorNumElements = addr->getType()->getVectorNumElements();
  3190. DXASSERT(vectorNumElements <= 3, "up to 3 elements for atomic binary op");
  3191. _Analysis_assume_(vectorNumElements <= 3);
  3192. for (unsigned i = 0; i < vectorNumElements; i++) {
  3193. Value *Elt = Builder.CreateExtractElement(addr, i);
  3194. args[DXIL::OperandIndex::kAtomicBinOpCoord0OpIdx + i] = Elt;
  3195. }
  3196. } else
  3197. args[DXIL::OperandIndex::kAtomicBinOpCoord0OpIdx] = addr;
  3198. // Set offset for structured buffer.
  3199. if (helper.offset)
  3200. args[DXIL::OperandIndex::kAtomicBinOpCoord1OpIdx] = helper.offset;
  3201. Value *origVal =
  3202. Builder.CreateCall(dxilAtomic, args, hlslOP->GetAtomicOpName(atomicOp));
  3203. if (helper.originalValue) {
  3204. Builder.CreateStore(origVal, helper.originalValue);
  3205. }
  3206. }
  3207. Value *TranslateMopAtomicBinaryOperation(CallInst *CI, IntrinsicOp IOP,
  3208. OP::OpCode opcode,
  3209. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3210. hlsl::OP *hlslOP = &helper.hlslOP;
  3211. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3212. IRBuilder<> Builder(CI);
  3213. switch (IOP) {
  3214. case IntrinsicOp::MOP_InterlockedAdd: {
  3215. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3216. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Add, Builder,
  3217. hlslOP);
  3218. } break;
  3219. case IntrinsicOp::MOP_InterlockedAnd: {
  3220. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3221. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::And, Builder,
  3222. hlslOP);
  3223. } break;
  3224. case IntrinsicOp::MOP_InterlockedExchange: {
  3225. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3226. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Exchange,
  3227. Builder, hlslOP);
  3228. } break;
  3229. case IntrinsicOp::MOP_InterlockedMax: {
  3230. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3231. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMax, Builder,
  3232. hlslOP);
  3233. } break;
  3234. case IntrinsicOp::MOP_InterlockedMin: {
  3235. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3236. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMin, Builder,
  3237. hlslOP);
  3238. } break;
  3239. case IntrinsicOp::MOP_InterlockedUMax: {
  3240. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3241. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMax, Builder,
  3242. hlslOP);
  3243. } break;
  3244. case IntrinsicOp::MOP_InterlockedUMin: {
  3245. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3246. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMin, Builder,
  3247. hlslOP);
  3248. } break;
  3249. case IntrinsicOp::MOP_InterlockedOr: {
  3250. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3251. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Or, Builder,
  3252. hlslOP);
  3253. } break;
  3254. case IntrinsicOp::MOP_InterlockedXor: {
  3255. default:
  3256. DXASSERT(IOP == IntrinsicOp::MOP_InterlockedXor,
  3257. "invalid MOP atomic intrinsic");
  3258. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3259. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Xor, Builder,
  3260. hlslOP);
  3261. } break;
  3262. }
  3263. return nullptr;
  3264. }
  3265. void TranslateAtomicCmpXChg(AtomicHelper &helper, IRBuilder<> &Builder,
  3266. hlsl::OP *hlslOP) {
  3267. Value *handle = helper.handle;
  3268. Value *addr = helper.addr;
  3269. Value *val = helper.value;
  3270. Value *cmpVal = helper.compareValue;
  3271. Type *Ty = val->getType();
  3272. Value *undefI = UndefValue::get(Type::getInt32Ty(Ty->getContext()));
  3273. Function *dxilAtomic = hlslOP->GetOpFunc(helper.opcode, Ty->getScalarType());
  3274. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(helper.opcode));
  3275. Value *args[] = {opArg, handle, undefI, undefI, undefI, // coordinates
  3276. cmpVal, val};
  3277. // Setup coordinates.
  3278. if (addr->getType()->isVectorTy()) {
  3279. unsigned vectorNumElements = addr->getType()->getVectorNumElements();
  3280. DXASSERT(vectorNumElements <= 3, "up to 3 elements in atomic op");
  3281. _Analysis_assume_(vectorNumElements <= 3);
  3282. for (unsigned i = 0; i < vectorNumElements; i++) {
  3283. Value *Elt = Builder.CreateExtractElement(addr, i);
  3284. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord0OpIdx + i] = Elt;
  3285. }
  3286. } else
  3287. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord0OpIdx] = addr;
  3288. // Set offset for structured buffer.
  3289. if (helper.offset)
  3290. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord1OpIdx] = helper.offset;
  3291. Value *origVal = Builder.CreateCall(dxilAtomic, args);
  3292. if (helper.originalValue) {
  3293. Builder.CreateStore(origVal, helper.originalValue);
  3294. }
  3295. }
  3296. Value *TranslateMopAtomicCmpXChg(CallInst *CI, IntrinsicOp IOP,
  3297. OP::OpCode opcode,
  3298. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3299. hlsl::OP *hlslOP = &helper.hlslOP;
  3300. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3301. IRBuilder<> Builder(CI);
  3302. AtomicHelper atomicHelper(CI, OP::OpCode::AtomicCompareExchange, handle);
  3303. TranslateAtomicCmpXChg(atomicHelper, Builder, hlslOP);
  3304. return nullptr;
  3305. }
  3306. void TranslateSharedMemAtomicBinOp(CallInst *CI, IntrinsicOp IOP, Value *addr) {
  3307. AtomicRMWInst::BinOp Op;
  3308. switch (IOP) {
  3309. case IntrinsicOp::IOP_InterlockedAdd:
  3310. Op = AtomicRMWInst::BinOp::Add;
  3311. break;
  3312. case IntrinsicOp::IOP_InterlockedAnd:
  3313. Op = AtomicRMWInst::BinOp::And;
  3314. break;
  3315. case IntrinsicOp::IOP_InterlockedExchange:
  3316. Op = AtomicRMWInst::BinOp::Xchg;
  3317. break;
  3318. case IntrinsicOp::IOP_InterlockedMax:
  3319. Op = AtomicRMWInst::BinOp::Max;
  3320. break;
  3321. case IntrinsicOp::IOP_InterlockedUMax:
  3322. Op = AtomicRMWInst::BinOp::UMax;
  3323. break;
  3324. case IntrinsicOp::IOP_InterlockedMin:
  3325. Op = AtomicRMWInst::BinOp::Min;
  3326. break;
  3327. case IntrinsicOp::IOP_InterlockedUMin:
  3328. Op = AtomicRMWInst::BinOp::UMin;
  3329. break;
  3330. case IntrinsicOp::IOP_InterlockedOr:
  3331. Op = AtomicRMWInst::BinOp::Or;
  3332. break;
  3333. case IntrinsicOp::IOP_InterlockedXor:
  3334. default:
  3335. DXASSERT(IOP == IntrinsicOp::IOP_InterlockedXor, "Invalid Intrinsic");
  3336. Op = AtomicRMWInst::BinOp::Xor;
  3337. break;
  3338. }
  3339. Value *val = CI->getArgOperand(HLOperandIndex::kInterlockedValueOpIndex);
  3340. IRBuilder<> Builder(CI);
  3341. Value *Result = Builder.CreateAtomicRMW(
  3342. Op, addr, val, AtomicOrdering::SequentiallyConsistent);
  3343. if (CI->getNumArgOperands() >
  3344. HLOperandIndex::kInterlockedOriginalValueOpIndex)
  3345. Builder.CreateStore(
  3346. Result,
  3347. CI->getArgOperand(HLOperandIndex::kInterlockedOriginalValueOpIndex));
  3348. }
  3349. Value *TranslateIopAtomicBinaryOperation(CallInst *CI, IntrinsicOp IOP,
  3350. DXIL::OpCode opcode,
  3351. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3352. Value *addr = CI->getArgOperand(HLOperandIndex::kInterlockedDestOpIndex);
  3353. // Get the original addr from cast.
  3354. if (CastInst *castInst = dyn_cast<CastInst>(addr))
  3355. addr = castInst->getOperand(0);
  3356. else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(addr)) {
  3357. if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  3358. addr = CE->getOperand(0);
  3359. }
  3360. }
  3361. unsigned addressSpace = addr->getType()->getPointerAddressSpace();
  3362. if (addressSpace == DXIL::kTGSMAddrSpace)
  3363. TranslateSharedMemAtomicBinOp(CI, IOP, addr);
  3364. else {
  3365. // buffer atomic translated in TranslateSubscript.
  3366. // Do nothing here.
  3367. // Mark not translated.
  3368. Translated = false;
  3369. }
  3370. return nullptr;
  3371. }
  3372. void TranslateSharedMemAtomicCmpXChg(CallInst *CI, Value *addr) {
  3373. Value *val = CI->getArgOperand(HLOperandIndex::kInterlockedCmpValueOpIndex);
  3374. Value *cmpVal =
  3375. CI->getArgOperand(HLOperandIndex::kInterlockedCmpCompareValueOpIndex);
  3376. IRBuilder<> Builder(CI);
  3377. Value *Result = Builder.CreateAtomicCmpXchg(
  3378. addr, cmpVal, val, AtomicOrdering::SequentiallyConsistent,
  3379. AtomicOrdering::SequentiallyConsistent);
  3380. if (CI->getNumArgOperands() >
  3381. HLOperandIndex::kInterlockedCmpOriginalValueOpIndex) {
  3382. Value *originVal = Builder.CreateExtractValue(Result, 0);
  3383. Builder.CreateStore(
  3384. originVal,
  3385. CI->getArgOperand(HLOperandIndex::kInterlockedCmpOriginalValueOpIndex));
  3386. }
  3387. }
  3388. Value *TranslateIopAtomicCmpXChg(CallInst *CI, IntrinsicOp IOP,
  3389. DXIL::OpCode opcode,
  3390. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3391. Value *addr = CI->getArgOperand(HLOperandIndex::kInterlockedDestOpIndex);
  3392. // Get the original addr from cast.
  3393. if (CastInst *castInst = dyn_cast<CastInst>(addr))
  3394. addr = castInst->getOperand(0);
  3395. unsigned addressSpace = addr->getType()->getPointerAddressSpace();
  3396. if (addressSpace == DXIL::kTGSMAddrSpace)
  3397. TranslateSharedMemAtomicCmpXChg(CI, addr);
  3398. else {
  3399. // buffer atomic translated in TranslateSubscript.
  3400. // Do nothing here.
  3401. // Mark not translated.
  3402. Translated = false;
  3403. }
  3404. return nullptr;
  3405. }
  3406. }
  3407. // Process Tess Factor.
  3408. namespace {
  3409. // Clamp to [0.0f..1.0f], NaN->0.0f.
  3410. Value *CleanupTessFactorScale(Value *input, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3411. float fMin = 0;
  3412. float fMax = 1;
  3413. Type *f32Ty = input->getType()->getScalarType();
  3414. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3415. Value *maxFactor = ConstantFP::get(f32Ty, fMax);
  3416. Type *Ty = input->getType();
  3417. if (Ty->isVectorTy())
  3418. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3419. Value *temp = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3420. if (Ty->isVectorTy())
  3421. maxFactor = SplatToVector(maxFactor, input->getType(), Builder);
  3422. return TrivialDxilBinaryOperation(DXIL::OpCode::FMin, temp, maxFactor, hlslOP, Builder);
  3423. }
  3424. // Clamp to [1.0f..Inf], NaN->1.0f.
  3425. Value *CleanupTessFactor(Value *input, hlsl::OP *hlslOP, IRBuilder<> &Builder)
  3426. {
  3427. float fMin = 1.0;
  3428. Type *f32Ty = input->getType()->getScalarType();
  3429. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3430. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3431. return TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3432. }
  3433. // Do partitioning-specific clamping.
  3434. Value *ClampTessFactor(Value *input, DXIL::TessellatorPartitioning partitionMode,
  3435. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3436. const unsigned kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR = 64;
  3437. const unsigned kTESSELLATOR_MAX_ODD_TESSELLATION_FACTOR = 63;
  3438. const unsigned kTESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR = 2;
  3439. const unsigned kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR = 1;
  3440. const unsigned kTESSELLATOR_MAX_TESSELLATION_FACTOR = 64;
  3441. float fMin;
  3442. float fMax;
  3443. switch (partitionMode) {
  3444. case DXIL::TessellatorPartitioning::Integer:
  3445. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3446. fMax = kTESSELLATOR_MAX_TESSELLATION_FACTOR;
  3447. break;
  3448. case DXIL::TessellatorPartitioning::Pow2:
  3449. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3450. fMax = kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR;
  3451. break;
  3452. case DXIL::TessellatorPartitioning::FractionalOdd:
  3453. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3454. fMax = kTESSELLATOR_MAX_ODD_TESSELLATION_FACTOR;
  3455. break;
  3456. case DXIL::TessellatorPartitioning::FractionalEven:
  3457. default:
  3458. DXASSERT(partitionMode == DXIL::TessellatorPartitioning::FractionalEven,
  3459. "invalid partition mode");
  3460. fMin = kTESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR;
  3461. fMax = kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR;
  3462. break;
  3463. }
  3464. Type *f32Ty = input->getType()->getScalarType();
  3465. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3466. Value *maxFactor = ConstantFP::get(f32Ty, fMax);
  3467. Type *Ty = input->getType();
  3468. if (Ty->isVectorTy())
  3469. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3470. Value *temp = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3471. if (Ty->isVectorTy())
  3472. maxFactor = SplatToVector(maxFactor, input->getType(), Builder);
  3473. return TrivialDxilBinaryOperation(DXIL::OpCode::FMin, temp, maxFactor, hlslOP, Builder);
  3474. }
  3475. // round up for integer/pow2 partitioning
  3476. // note that this code assumes the inputs should be in the range [1, inf),
  3477. // which should be enforced by the clamp above.
  3478. Value *RoundUpTessFactor(Value *input, DXIL::TessellatorPartitioning partitionMode,
  3479. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3480. switch (partitionMode) {
  3481. case DXIL::TessellatorPartitioning::Integer:
  3482. return TrivialDxilUnaryOperation(DXIL::OpCode::Round_pi, input, hlslOP, Builder);
  3483. case DXIL::TessellatorPartitioning::Pow2: {
  3484. const unsigned kExponentMask = 0x7f800000;
  3485. const unsigned kExponentLSB = 0x00800000;
  3486. const unsigned kMantissaMask = 0x007fffff;
  3487. Type *Ty = input->getType();
  3488. // (val = (asuint(val) & mantissamask) ?
  3489. // (asuint(val) & exponentmask) + exponentbump :
  3490. // asuint(val) & exponentmask;
  3491. Type *uintTy = Type::getInt32Ty(Ty->getContext());
  3492. if (Ty->isVectorTy())
  3493. uintTy = VectorType::get(uintTy, Ty->getVectorNumElements());
  3494. Value *uintVal = Builder.CreateCast(Instruction::CastOps::FPToUI, input, uintTy);
  3495. Value *mantMask = ConstantInt::get(uintTy->getScalarType(), kMantissaMask);
  3496. mantMask = SplatToVector(mantMask, uintTy, Builder);
  3497. Value *manVal = Builder.CreateAnd(uintVal, mantMask);
  3498. Value *expMask = ConstantInt::get(uintTy->getScalarType(), kExponentMask);
  3499. expMask = SplatToVector(expMask, uintTy, Builder);
  3500. Value *expVal = Builder.CreateAnd(uintVal, expMask);
  3501. Value *expLSB = ConstantInt::get(uintTy->getScalarType(), kExponentLSB);
  3502. expLSB = SplatToVector(expLSB, uintTy, Builder);
  3503. Value *newExpVal = Builder.CreateAdd(expVal, expLSB);
  3504. Value *manValNotZero = Builder.CreateICmpEQ(manVal, ConstantAggregateZero::get(uintTy));
  3505. Value *factors = Builder.CreateSelect(manValNotZero, newExpVal, expVal);
  3506. return Builder.CreateUIToFP(factors, Ty);
  3507. } break;
  3508. case DXIL::TessellatorPartitioning::FractionalEven:
  3509. case DXIL::TessellatorPartitioning::FractionalOdd:
  3510. return input;
  3511. default:
  3512. DXASSERT(0, "invalid partition mode");
  3513. return nullptr;
  3514. }
  3515. }
  3516. Value *TranslateProcessIsolineTessFactors(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3517. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3518. hlsl::OP *hlslOP = &helper.hlslOP;
  3519. // Get partition mode
  3520. DXASSERT(helper.functionProps, "");
  3521. DXASSERT(helper.functionProps->shaderKind == ShaderModel::Kind::Hull, "must be hull shader");
  3522. DXIL::TessellatorPartitioning partition = helper.functionProps->ShaderProps.HS.partition;
  3523. IRBuilder<> Builder(CI);
  3524. Value *rawDetailFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawDetailFactor);
  3525. rawDetailFactor = Builder.CreateExtractElement(rawDetailFactor, (uint64_t)0);
  3526. Value *rawDensityFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawDensityFactor);
  3527. rawDensityFactor = Builder.CreateExtractElement(rawDensityFactor, (uint64_t)0);
  3528. Value *init = UndefValue::get(VectorType::get(helper.f32Ty, 2));
  3529. init = Builder.CreateInsertElement(init, rawDetailFactor, (uint64_t)0);
  3530. init = Builder.CreateInsertElement(init, rawDetailFactor, (uint64_t)1);
  3531. Value *clamped = ClampTessFactor(init, partition, hlslOP, Builder);
  3532. Value *rounded = RoundUpTessFactor(clamped, partition, hlslOP, Builder);
  3533. Value *roundedDetailFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedDetailFactor);
  3534. Value *temp = UndefValue::get(VectorType::get(helper.f32Ty, 1));
  3535. Value *roundedX = Builder.CreateExtractElement(rounded, (uint64_t)0);
  3536. temp = Builder.CreateInsertElement(temp, roundedX, (uint64_t)0);
  3537. Builder.CreateStore(temp, roundedDetailFactor);
  3538. Value *roundedDensityFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedDensityFactor);
  3539. Value *roundedY = Builder.CreateExtractElement(rounded, 1);
  3540. temp = Builder.CreateInsertElement(temp, roundedY, (uint64_t)0);
  3541. Builder.CreateStore(temp, roundedDensityFactor);
  3542. return nullptr;
  3543. }
  3544. // 3 inputs, 1 result
  3545. Value *ApplyTriTessFactorOp(Value *input, DXIL::OpCode opcode, hlsl::OP *hlslOP,
  3546. IRBuilder<> &Builder) {
  3547. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3548. Value *input1 = Builder.CreateExtractElement(input, 1);
  3549. Value *input2 = Builder.CreateExtractElement(input, 2);
  3550. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3551. Value *temp =
  3552. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3553. Value *combined =
  3554. TrivialDxilBinaryOperation(opcode, temp, input2, hlslOP, Builder);
  3555. return combined;
  3556. } else {
  3557. // Avg.
  3558. Value *temp = Builder.CreateFAdd(input0, input1);
  3559. Value *combined = Builder.CreateFAdd(temp, input2);
  3560. Value *rcp = ConstantFP::get(input0->getType(), 1.0 / 3.0);
  3561. combined = Builder.CreateFMul(combined, rcp);
  3562. return combined;
  3563. }
  3564. }
  3565. // 4 inputs, 1 result
  3566. Value *ApplyQuadTessFactorOp(Value *input, DXIL::OpCode opcode,
  3567. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3568. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3569. Value *input1 = Builder.CreateExtractElement(input, 1);
  3570. Value *input2 = Builder.CreateExtractElement(input, 2);
  3571. Value *input3 = Builder.CreateExtractElement(input, 3);
  3572. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3573. Value *temp0 =
  3574. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3575. Value *temp1 =
  3576. TrivialDxilBinaryOperation(opcode, input2, input3, hlslOP, Builder);
  3577. Value *combined =
  3578. TrivialDxilBinaryOperation(opcode, temp0, temp1, hlslOP, Builder);
  3579. return combined;
  3580. } else {
  3581. // Avg.
  3582. Value *temp0 = Builder.CreateFAdd(input0, input1);
  3583. Value *temp1 = Builder.CreateFAdd(input2, input3);
  3584. Value *combined = Builder.CreateFAdd(temp0, temp1);
  3585. Value *rcp = ConstantFP::get(input0->getType(), 0.25);
  3586. combined = Builder.CreateFMul(combined, rcp);
  3587. return combined;
  3588. }
  3589. }
  3590. // 4 inputs, 2 result
  3591. Value *Apply2DQuadTessFactorOp(Value *input, DXIL::OpCode opcode,
  3592. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3593. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3594. Value *input1 = Builder.CreateExtractElement(input, 1);
  3595. Value *input2 = Builder.CreateExtractElement(input, 2);
  3596. Value *input3 = Builder.CreateExtractElement(input, 3);
  3597. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3598. Value *temp0 =
  3599. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3600. Value *temp1 =
  3601. TrivialDxilBinaryOperation(opcode, input2, input3, hlslOP, Builder);
  3602. Value *combined = UndefValue::get(VectorType::get(input0->getType(), 2));
  3603. combined = Builder.CreateInsertElement(combined, temp0, (uint64_t)0);
  3604. combined = Builder.CreateInsertElement(combined, temp1, 1);
  3605. return combined;
  3606. } else {
  3607. // Avg.
  3608. Value *temp0 = Builder.CreateFAdd(input0, input1);
  3609. Value *temp1 = Builder.CreateFAdd(input2, input3);
  3610. Value *combined = UndefValue::get(VectorType::get(input0->getType(), 2));
  3611. combined = Builder.CreateInsertElement(combined, temp0, (uint64_t)0);
  3612. combined = Builder.CreateInsertElement(combined, temp1, 1);
  3613. Constant *rcp = ConstantFP::get(input0->getType(), 0.5);
  3614. rcp = ConstantVector::getSplat(2, rcp);
  3615. combined = Builder.CreateFMul(combined, rcp);
  3616. return combined;
  3617. }
  3618. }
  3619. Value *ResolveSmallValue(Value **pClampedResult, Value *rounded, Value *averageUnscaled,
  3620. float cutoffVal, DXIL::TessellatorPartitioning partitionMode, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3621. Value *clampedResult = *pClampedResult;
  3622. Value *clampedVal = clampedResult;
  3623. Value *roundedVal = rounded;
  3624. // Do partitioning-specific clamping.
  3625. Value *clampedAvg = ClampTessFactor(averageUnscaled, partitionMode, hlslOP, Builder);
  3626. Constant *cutoffVals = ConstantFP::get(Type::getFloatTy(rounded->getContext()), cutoffVal);
  3627. if (clampedAvg->getType()->isVectorTy())
  3628. cutoffVals = ConstantVector::getSplat(clampedAvg->getType()->getVectorNumElements(), cutoffVals);
  3629. // Limit the value.
  3630. clampedAvg = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, clampedAvg, cutoffVals, hlslOP, Builder);
  3631. // Round up for integer/pow2 partitioning.
  3632. Value *roundedAvg = RoundUpTessFactor(clampedAvg, partitionMode, hlslOP, Builder);
  3633. if (rounded->getType() != cutoffVals->getType())
  3634. cutoffVals = ConstantVector::getSplat(rounded->getType()->getVectorNumElements(), cutoffVals);
  3635. // If the scaled value is less than three, then take the unscaled average.
  3636. Value *lt = Builder.CreateFCmpOLT(rounded, cutoffVals);
  3637. if (clampedAvg->getType() != clampedVal->getType())
  3638. clampedAvg = SplatToVector(clampedAvg, clampedVal->getType(), Builder);
  3639. *pClampedResult = Builder.CreateSelect(lt, clampedAvg, clampedVal);
  3640. if (roundedAvg->getType() != roundedVal->getType())
  3641. roundedAvg = SplatToVector(roundedAvg, roundedVal->getType(), Builder);
  3642. Value *result = Builder.CreateSelect(lt, roundedAvg, roundedVal);
  3643. return result;
  3644. }
  3645. void ResolveQuadAxes( Value **pFinalResult, Value **pClampedResult,
  3646. float cutoffVal, DXIL::TessellatorPartitioning partitionMode, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3647. Value *finalResult = *pFinalResult;
  3648. Value *clampedResult = *pClampedResult;
  3649. Value *clampR = clampedResult;
  3650. Value *finalR = finalResult;
  3651. Type *f32Ty = Type::getFloatTy(finalR->getContext());
  3652. Constant *cutoffVals = ConstantFP::get(f32Ty, cutoffVal);
  3653. Value *minValsX = cutoffVals;
  3654. Value *minValsY = RoundUpTessFactor(cutoffVals, partitionMode, hlslOP, Builder);
  3655. Value *clampRX = Builder.CreateExtractElement(clampR, (uint64_t)0);
  3656. Value *clampRY = Builder.CreateExtractElement(clampR, 1);
  3657. Value *maxValsX = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, clampRX, clampRY, hlslOP, Builder);
  3658. Value *finalRX = Builder.CreateExtractElement(finalR, (uint64_t)0);
  3659. Value *finalRY = Builder.CreateExtractElement(finalR, 1);
  3660. Value *maxValsY = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, finalRX, finalRY, hlslOP, Builder);
  3661. // Don't go over our threshold ("final" one is rounded).
  3662. Value * optionX = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, maxValsX, minValsX, hlslOP, Builder);
  3663. Value * optionY = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, maxValsY, minValsY, hlslOP, Builder);
  3664. Value *clampL = SplatToVector(optionX, clampR->getType(), Builder);
  3665. Value *finalL = SplatToVector(optionY, finalR->getType(), Builder);
  3666. cutoffVals = ConstantVector::getSplat(2, cutoffVals);
  3667. Value *lt = Builder.CreateFCmpOLT(clampedResult, cutoffVals);
  3668. *pClampedResult = Builder.CreateSelect(lt, clampL, clampR);
  3669. *pFinalResult = Builder.CreateSelect(lt, finalL, finalR);
  3670. }
  3671. Value *TranslateProcessTessFactors(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3672. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3673. hlsl::OP *hlslOP = &helper.hlslOP;
  3674. // Get partition mode
  3675. DXASSERT(helper.functionProps, "");
  3676. DXASSERT(helper.functionProps->shaderKind == ShaderModel::Kind::Hull, "must be hull shader");
  3677. DXIL::TessellatorPartitioning partition = helper.functionProps->ShaderProps.HS.partition;
  3678. IRBuilder<> Builder(CI);
  3679. DXIL::OpCode tessFactorOp = DXIL::OpCode::NumOpCodes;
  3680. switch (IOP) {
  3681. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3682. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3683. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3684. tessFactorOp = DXIL::OpCode::FMax;
  3685. break;
  3686. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3687. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3688. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3689. tessFactorOp = DXIL::OpCode::FMin;
  3690. break;
  3691. default:
  3692. // Default is Avg.
  3693. break;
  3694. }
  3695. Value *rawEdgeFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawEdgeFactor);
  3696. Value *insideScale = CI->getArgOperand(HLOperandIndex::kProcessTessFactorInsideScale);
  3697. // Clamp to [0.0f..1.0f], NaN->0.0f.
  3698. Value *scales = CleanupTessFactorScale(insideScale, hlslOP, Builder);
  3699. // Do partitioning-specific clamping.
  3700. Value *clamped = ClampTessFactor(rawEdgeFactor, partition, hlslOP, Builder);
  3701. // Round up for integer/pow2 partitioning.
  3702. Value *rounded = RoundUpTessFactor(clamped, partition, hlslOP, Builder);
  3703. // Store the output.
  3704. Value *roundedEdgeFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedEdgeFactor);
  3705. Builder.CreateStore(rounded, roundedEdgeFactor);
  3706. // Clamp to [1.0f..Inf], NaN->1.0f.
  3707. bool isQuad = false;
  3708. Value *clean = CleanupTessFactor(rawEdgeFactor, hlslOP, Builder);
  3709. Value *factors = nullptr;
  3710. switch (IOP) {
  3711. case IntrinsicOp::IOP_Process2DQuadTessFactorsAvg:
  3712. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3713. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3714. factors = Apply2DQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3715. break;
  3716. case IntrinsicOp::IOP_ProcessQuadTessFactorsAvg:
  3717. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3718. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3719. factors = ApplyQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3720. isQuad = true;
  3721. break;
  3722. case IntrinsicOp::IOP_ProcessTriTessFactorsAvg:
  3723. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3724. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3725. factors = ApplyTriTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3726. break;
  3727. default:
  3728. DXASSERT(0, "invalid opcode for ProcessTessFactor");
  3729. break;
  3730. }
  3731. Value *scaledI = nullptr;
  3732. if (scales->getType() == factors->getType())
  3733. scaledI = Builder.CreateFMul(factors, scales);
  3734. else {
  3735. Value *vecFactors = SplatToVector(factors, scales->getType(), Builder);
  3736. scaledI = Builder.CreateFMul(vecFactors, scales);
  3737. }
  3738. // Do partitioning-specific clamping.
  3739. Value *clampedI = ClampTessFactor(scaledI, partition, hlslOP, Builder);
  3740. // Round up for integer/pow2 partitioning.
  3741. Value *roundedI = RoundUpTessFactor(clampedI, partition, hlslOP, Builder);
  3742. Value *finalI = roundedI;
  3743. if (partition == DXIL::TessellatorPartitioning::FractionalOdd) {
  3744. // If not max, set to AVG.
  3745. if (tessFactorOp != DXIL::OpCode::FMax)
  3746. tessFactorOp = DXIL::OpCode::NumOpCodes;
  3747. bool b2D = false;
  3748. Value *avgFactorsI = nullptr;
  3749. switch (IOP) {
  3750. case IntrinsicOp::IOP_Process2DQuadTessFactorsAvg:
  3751. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3752. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3753. avgFactorsI = Apply2DQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3754. b2D = true;
  3755. break;
  3756. case IntrinsicOp::IOP_ProcessQuadTessFactorsAvg:
  3757. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3758. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3759. avgFactorsI = ApplyQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3760. break;
  3761. case IntrinsicOp::IOP_ProcessTriTessFactorsAvg:
  3762. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3763. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3764. avgFactorsI = ApplyTriTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3765. break;
  3766. default:
  3767. DXASSERT(0, "invalid opcode for ProcessTessFactor");
  3768. break;
  3769. }
  3770. finalI =
  3771. ResolveSmallValue(/*inout*/&clampedI, roundedI, avgFactorsI, /*cufoff*/ 3.0,
  3772. partition, hlslOP, Builder);
  3773. if (b2D)
  3774. ResolveQuadAxes(/*inout*/&finalI, /*inout*/&clampedI, /*cutoff*/3.0, partition, hlslOP, Builder);
  3775. }
  3776. Value *unroundedInsideFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorUnRoundedInsideFactor);
  3777. Type *outFactorTy = unroundedInsideFactor->getType()->getPointerElementType();
  3778. if (outFactorTy != clampedI->getType()) {
  3779. DXASSERT(isQuad, "quad only write one channel of out factor");
  3780. clampedI = Builder.CreateExtractElement(clampedI, (uint64_t)0);
  3781. // Splat clampedI to float2.
  3782. clampedI = SplatToVector(clampedI, outFactorTy, Builder);
  3783. }
  3784. Builder.CreateStore(clampedI, unroundedInsideFactor);
  3785. Value *roundedInsideFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedInsideFactor);
  3786. if (outFactorTy != finalI->getType()) {
  3787. DXASSERT(isQuad, "quad only write one channel of out factor");
  3788. finalI = Builder.CreateExtractElement(finalI, (uint64_t)0);
  3789. // Splat finalI to float2.
  3790. finalI = SplatToVector(finalI, outFactorTy, Builder);
  3791. }
  3792. Builder.CreateStore(finalI, roundedInsideFactor);
  3793. return nullptr;
  3794. }
  3795. }
  3796. // Lower table.
  3797. namespace {
  3798. Value *EmptyLower(CallInst *CI, IntrinsicOp IOP, DXIL::OpCode opcode,
  3799. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3800. DXASSERT(0, "unsupported intrinsic");
  3801. return nullptr;
  3802. }
  3803. Value *StreamOutputLower(CallInst *CI, IntrinsicOp IOP, DXIL::OpCode opcode,
  3804. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3805. // Translated in DxilGenerationPass::GenerateStreamOutputOperation.
  3806. // Do nothing here.
  3807. // Mark not translated.
  3808. Translated = false;
  3809. return nullptr;
  3810. }
  3811. // This table has to match IntrinsicOp orders
  3812. IntrinsicLower gLowerTable[static_cast<unsigned>(IntrinsicOp::Num_Intrinsics)] = {
  3813. {IntrinsicOp::IOP_AddUint64, TranslateAddUint64, DXIL::OpCode::UAddc},
  3814. {IntrinsicOp::IOP_AllMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3815. {IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3816. {IntrinsicOp::IOP_CheckAccessFullyMapped, TranslateCheckAccess, DXIL::OpCode::CheckAccessFullyMapped},
  3817. {IntrinsicOp::IOP_D3DCOLORtoUBYTE4, TranslateD3DColorToUByte4, DXIL::OpCode::NumOpCodes},
  3818. {IntrinsicOp::IOP_DeviceMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3819. {IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3820. {IntrinsicOp::IOP_EvaluateAttributeAtSample, TranslateEvalSample, DXIL::OpCode::NumOpCodes},
  3821. {IntrinsicOp::IOP_EvaluateAttributeCentroid, TranslateEvalCentroid, DXIL::OpCode::EvalCentroid},
  3822. {IntrinsicOp::IOP_EvaluateAttributeSnapped, TranslateEvalSnapped, DXIL::OpCode::NumOpCodes},
  3823. {IntrinsicOp::IOP_GetAttributeAtVertex, TranslateGetAttributeAtVertex, DXIL::OpCode::AttributeAtVertex},
  3824. {IntrinsicOp::IOP_GetRenderTargetSampleCount, TrivialNoArgOperation, DXIL::OpCode::RenderTargetGetSampleCount},
  3825. {IntrinsicOp::IOP_GetRenderTargetSamplePosition, TranslateGetRTSamplePos, DXIL::OpCode::NumOpCodes},
  3826. {IntrinsicOp::IOP_GroupMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3827. {IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3828. {IntrinsicOp::IOP_InterlockedAdd, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3829. {IntrinsicOp::IOP_InterlockedAnd, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3830. {IntrinsicOp::IOP_InterlockedCompareExchange, TranslateIopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3831. {IntrinsicOp::IOP_InterlockedCompareStore, TranslateIopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3832. {IntrinsicOp::IOP_InterlockedExchange, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3833. {IntrinsicOp::IOP_InterlockedMax, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3834. {IntrinsicOp::IOP_InterlockedMin, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3835. {IntrinsicOp::IOP_InterlockedOr, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3836. {IntrinsicOp::IOP_InterlockedXor, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3837. {IntrinsicOp::IOP_NonUniformResourceIndex, TranslateNonUniformResourceIndex, DXIL::OpCode::NumOpCodes},
  3838. {IntrinsicOp::IOP_Process2DQuadTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3839. {IntrinsicOp::IOP_Process2DQuadTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3840. {IntrinsicOp::IOP_Process2DQuadTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3841. {IntrinsicOp::IOP_ProcessIsolineTessFactors, TranslateProcessIsolineTessFactors, DXIL::OpCode::NumOpCodes},
  3842. {IntrinsicOp::IOP_ProcessQuadTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3843. {IntrinsicOp::IOP_ProcessQuadTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3844. {IntrinsicOp::IOP_ProcessQuadTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3845. {IntrinsicOp::IOP_ProcessTriTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3846. {IntrinsicOp::IOP_ProcessTriTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3847. {IntrinsicOp::IOP_ProcessTriTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3848. {IntrinsicOp::IOP_QuadReadAcrossDiagonal, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3849. {IntrinsicOp::IOP_QuadReadAcrossX, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3850. {IntrinsicOp::IOP_QuadReadAcrossY, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3851. {IntrinsicOp::IOP_QuadReadLaneAt, TranslateQuadReadLaneAt, DXIL::OpCode::NumOpCodes},
  3852. {IntrinsicOp::IOP_WaveActiveAllEqual, TranslateWaveAllEqual, DXIL::OpCode::WaveActiveAllEqual},
  3853. {IntrinsicOp::IOP_WaveActiveAllTrue, TranslateWaveA2B, DXIL::OpCode::WaveAllTrue},
  3854. {IntrinsicOp::IOP_WaveActiveAnyTrue, TranslateWaveA2B, DXIL::OpCode::WaveAnyTrue},
  3855. {IntrinsicOp::IOP_WaveActiveBallot, TranslateWaveBallot, DXIL::OpCode::WaveActiveBallot},
  3856. {IntrinsicOp::IOP_WaveActiveBitAnd, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3857. {IntrinsicOp::IOP_WaveActiveBitOr, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3858. {IntrinsicOp::IOP_WaveActiveBitXor, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3859. {IntrinsicOp::IOP_WaveActiveCountBits, TranslateWaveA2B, DXIL::OpCode::WaveAllBitCount},
  3860. {IntrinsicOp::IOP_WaveActiveMax, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3861. {IntrinsicOp::IOP_WaveActiveMin, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3862. {IntrinsicOp::IOP_WaveActiveProduct, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3863. {IntrinsicOp::IOP_WaveActiveSum, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3864. {IntrinsicOp::IOP_WaveGetLaneCount, TranslateWaveToVal, DXIL::OpCode::WaveGetLaneCount},
  3865. {IntrinsicOp::IOP_WaveGetLaneIndex, TranslateWaveToVal, DXIL::OpCode::WaveGetLaneIndex},
  3866. {IntrinsicOp::IOP_WaveIsFirstLane, TranslateWaveToVal, DXIL::OpCode::WaveIsFirstLane},
  3867. {IntrinsicOp::IOP_WavePrefixCountBits, TranslateWaveA2B, DXIL::OpCode::WavePrefixBitCount},
  3868. {IntrinsicOp::IOP_WavePrefixProduct, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp},
  3869. {IntrinsicOp::IOP_WavePrefixSum, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp},
  3870. {IntrinsicOp::IOP_WaveReadLaneAt, TranslateWaveReadLaneAt, DXIL::OpCode::WaveReadLaneAt},
  3871. {IntrinsicOp::IOP_WaveReadLaneFirst, TranslateWaveReadLaneFirst, DXIL::OpCode::WaveReadLaneFirst},
  3872. {IntrinsicOp::IOP_abort, EmptyLower, DXIL::OpCode::NumOpCodes},
  3873. {IntrinsicOp::IOP_abs, TransalteAbs, DXIL::OpCode::NumOpCodes},
  3874. {IntrinsicOp::IOP_acos, TrivialUnaryOperation, DXIL::OpCode::Acos},
  3875. {IntrinsicOp::IOP_all, TranslateAll, DXIL::OpCode::NumOpCodes},
  3876. {IntrinsicOp::IOP_any, TranslateAny, DXIL::OpCode::NumOpCodes},
  3877. {IntrinsicOp::IOP_asdouble, TranslateAsDouble, DXIL::OpCode::MakeDouble},
  3878. {IntrinsicOp::IOP_asfloat, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3879. {IntrinsicOp::IOP_asfloat16, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3880. {IntrinsicOp::IOP_asin, TrivialUnaryOperation, DXIL::OpCode::Asin},
  3881. {IntrinsicOp::IOP_asint, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3882. {IntrinsicOp::IOP_asint16, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3883. {IntrinsicOp::IOP_asuint, TranslateAsUint, DXIL::OpCode::SplitDouble},
  3884. {IntrinsicOp::IOP_asuint16, TranslateAsUint, DXIL::OpCode::NumOpCodes},
  3885. {IntrinsicOp::IOP_atan, TrivialUnaryOperation, DXIL::OpCode::Atan},
  3886. {IntrinsicOp::IOP_atan2, TranslateAtan2, DXIL::OpCode::NumOpCodes},
  3887. {IntrinsicOp::IOP_ceil, TrivialUnaryOperation, DXIL::OpCode::Round_pi},
  3888. {IntrinsicOp::IOP_clamp, TranslateClamp, DXIL::OpCode::NumOpCodes},
  3889. {IntrinsicOp::IOP_clip, TranslateClip, DXIL::OpCode::NumOpCodes},
  3890. {IntrinsicOp::IOP_cos, TrivialUnaryOperation, DXIL::OpCode::Cos},
  3891. {IntrinsicOp::IOP_cosh, TrivialUnaryOperation, DXIL::OpCode::Hcos},
  3892. {IntrinsicOp::IOP_countbits, TrivialUnaryOperation, DXIL::OpCode::Countbits},
  3893. {IntrinsicOp::IOP_cross, TranslateCross, DXIL::OpCode::NumOpCodes},
  3894. {IntrinsicOp::IOP_ddx, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseX},
  3895. {IntrinsicOp::IOP_ddx_coarse, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseX},
  3896. {IntrinsicOp::IOP_ddx_fine, TrivialUnaryOperation, DXIL::OpCode::DerivFineX},
  3897. {IntrinsicOp::IOP_ddy, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseY},
  3898. {IntrinsicOp::IOP_ddy_coarse, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseY},
  3899. {IntrinsicOp::IOP_ddy_fine, TrivialUnaryOperation, DXIL::OpCode::DerivFineY},
  3900. {IntrinsicOp::IOP_degrees, TranslateDegrees, DXIL::OpCode::NumOpCodes},
  3901. {IntrinsicOp::IOP_determinant, EmptyLower, DXIL::OpCode::NumOpCodes},
  3902. {IntrinsicOp::IOP_distance, TranslateDistance, DXIL::OpCode::NumOpCodes},
  3903. {IntrinsicOp::IOP_dot, TranslateDot, DXIL::OpCode::NumOpCodes},
  3904. {IntrinsicOp::IOP_dst, TranslateDst, DXIL::OpCode::NumOpCodes},
  3905. {IntrinsicOp::IOP_exp, TranslateExp, DXIL::OpCode::NumOpCodes},
  3906. {IntrinsicOp::IOP_exp2, TrivialUnaryOperation, DXIL::OpCode::Exp},
  3907. {IntrinsicOp::IOP_f16tof32, TranslateF16ToF32, DXIL::OpCode::LegacyF16ToF32},
  3908. {IntrinsicOp::IOP_f32tof16, TranslateF32ToF16, DXIL::OpCode::LegacyF32ToF16},
  3909. {IntrinsicOp::IOP_faceforward, TranslateFaceforward, DXIL::OpCode::NumOpCodes},
  3910. {IntrinsicOp::IOP_firstbithigh, TranslateFirstbitHi, DXIL::OpCode::FirstbitSHi},
  3911. {IntrinsicOp::IOP_firstbitlow, TranslateFirstbitLo, DXIL::OpCode::FirstbitLo},
  3912. {IntrinsicOp::IOP_floor, TrivialUnaryOperation, DXIL::OpCode::Round_ni},
  3913. {IntrinsicOp::IOP_fma, TrivialTrinaryOperation, DXIL::OpCode::Fma},
  3914. {IntrinsicOp::IOP_fmod, TranslateFMod, DXIL::OpCode::NumOpCodes},
  3915. {IntrinsicOp::IOP_frac, TrivialUnaryOperation, DXIL::OpCode::Frc},
  3916. {IntrinsicOp::IOP_frexp, TranslateFrexp, DXIL::OpCode::NumOpCodes},
  3917. {IntrinsicOp::IOP_fwidth, TranslateFWidth, DXIL::OpCode::NumOpCodes},
  3918. {IntrinsicOp::IOP_isfinite, TrivialIsSpecialFloat, DXIL::OpCode::IsFinite},
  3919. {IntrinsicOp::IOP_isinf, TrivialIsSpecialFloat, DXIL::OpCode::IsInf},
  3920. {IntrinsicOp::IOP_isnan, TrivialIsSpecialFloat, DXIL::OpCode::IsNaN},
  3921. {IntrinsicOp::IOP_ldexp, TranslateLdExp, DXIL::OpCode::NumOpCodes},
  3922. {IntrinsicOp::IOP_length, TranslateLength, DXIL::OpCode::NumOpCodes},
  3923. {IntrinsicOp::IOP_lerp, TranslateLerp, DXIL::OpCode::NumOpCodes},
  3924. {IntrinsicOp::IOP_lit, TranslateLit, DXIL::OpCode::NumOpCodes},
  3925. {IntrinsicOp::IOP_log, TranslateLog, DXIL::OpCode::NumOpCodes},
  3926. {IntrinsicOp::IOP_log10, TranslateLog10, DXIL::OpCode::NumOpCodes},
  3927. {IntrinsicOp::IOP_log2, TrivialUnaryOperation, DXIL::OpCode::Log},
  3928. {IntrinsicOp::IOP_mad, TranslateFUITrinary, DXIL::OpCode::IMad},
  3929. {IntrinsicOp::IOP_max, TranslateFUIBinary, DXIL::OpCode::IMax},
  3930. {IntrinsicOp::IOP_min, TranslateFUIBinary, DXIL::OpCode::IMin},
  3931. {IntrinsicOp::IOP_modf, TranslateModF, DXIL::OpCode::NumOpCodes},
  3932. {IntrinsicOp::IOP_msad4, TranslateMSad4, DXIL::OpCode::NumOpCodes},
  3933. {IntrinsicOp::IOP_mul, EmptyLower, DXIL::OpCode::NumOpCodes},
  3934. {IntrinsicOp::IOP_normalize, TranslateNormalize, DXIL::OpCode::NumOpCodes},
  3935. {IntrinsicOp::IOP_pow, TranslatePow, DXIL::OpCode::NumOpCodes},
  3936. {IntrinsicOp::IOP_radians, TranslateRadians, DXIL::OpCode::NumOpCodes},
  3937. {IntrinsicOp::IOP_rcp, TranslateRCP, DXIL::OpCode::NumOpCodes},
  3938. {IntrinsicOp::IOP_reflect, TranslateReflect, DXIL::OpCode::NumOpCodes},
  3939. {IntrinsicOp::IOP_refract, TranslateRefract, DXIL::OpCode::NumOpCodes},
  3940. {IntrinsicOp::IOP_reversebits, TrivialUnaryOperation, DXIL::OpCode::Bfrev},
  3941. {IntrinsicOp::IOP_round, TrivialUnaryOperation, DXIL::OpCode::Round_ne},
  3942. {IntrinsicOp::IOP_rsqrt, TrivialUnaryOperation, DXIL::OpCode::Rsqrt},
  3943. {IntrinsicOp::IOP_saturate, TrivialUnaryOperation, DXIL::OpCode::Saturate},
  3944. {IntrinsicOp::IOP_sign, TranslateSign, DXIL::OpCode::NumOpCodes},
  3945. {IntrinsicOp::IOP_sin, TrivialUnaryOperation, DXIL::OpCode::Sin},
  3946. {IntrinsicOp::IOP_sincos, EmptyLower, DXIL::OpCode::NumOpCodes},
  3947. {IntrinsicOp::IOP_sinh, TrivialUnaryOperation, DXIL::OpCode::Hsin},
  3948. {IntrinsicOp::IOP_smoothstep, TranslateSmoothStep, DXIL::OpCode::NumOpCodes},
  3949. {IntrinsicOp::IOP_source_mark, EmptyLower, DXIL::OpCode::NumOpCodes},
  3950. {IntrinsicOp::IOP_sqrt, TrivialUnaryOperation, DXIL::OpCode::Sqrt},
  3951. {IntrinsicOp::IOP_step, TranslateStep, DXIL::OpCode::NumOpCodes},
  3952. {IntrinsicOp::IOP_tan, TrivialUnaryOperation, DXIL::OpCode::Tan},
  3953. {IntrinsicOp::IOP_tanh, TrivialUnaryOperation, DXIL::OpCode::Htan},
  3954. {IntrinsicOp::IOP_tex1D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3955. {IntrinsicOp::IOP_tex1Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3956. {IntrinsicOp::IOP_tex1Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3957. {IntrinsicOp::IOP_tex1Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3958. {IntrinsicOp::IOP_tex1Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3959. {IntrinsicOp::IOP_tex2D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3960. {IntrinsicOp::IOP_tex2Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3961. {IntrinsicOp::IOP_tex2Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3962. {IntrinsicOp::IOP_tex2Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3963. {IntrinsicOp::IOP_tex2Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3964. {IntrinsicOp::IOP_tex3D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3965. {IntrinsicOp::IOP_tex3Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3966. {IntrinsicOp::IOP_tex3Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3967. {IntrinsicOp::IOP_tex3Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3968. {IntrinsicOp::IOP_tex3Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3969. {IntrinsicOp::IOP_texCUBE, EmptyLower, DXIL::OpCode::NumOpCodes},
  3970. {IntrinsicOp::IOP_texCUBEbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3971. {IntrinsicOp::IOP_texCUBEgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3972. {IntrinsicOp::IOP_texCUBElod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3973. {IntrinsicOp::IOP_texCUBEproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3974. {IntrinsicOp::IOP_transpose, EmptyLower, DXIL::OpCode::NumOpCodes},
  3975. {IntrinsicOp::IOP_trunc, TrivialUnaryOperation, DXIL::OpCode::Round_z},
  3976. {IntrinsicOp::MOP_Append, StreamOutputLower, DXIL::OpCode::EmitStream},
  3977. {IntrinsicOp::MOP_RestartStrip, StreamOutputLower, DXIL::OpCode::CutStream},
  3978. {IntrinsicOp::MOP_CalculateLevelOfDetail, TranslateCalculateLOD, DXIL::OpCode::NumOpCodes},
  3979. {IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped, TranslateCalculateLOD, DXIL::OpCode::NumOpCodes},
  3980. {IntrinsicOp::MOP_GetDimensions, TranslateGetDimensions, DXIL::OpCode::NumOpCodes},
  3981. {IntrinsicOp::MOP_Load, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3982. {IntrinsicOp::MOP_Sample, TranslateSample, DXIL::OpCode::Sample},
  3983. {IntrinsicOp::MOP_SampleBias, TranslateSample, DXIL::OpCode::SampleBias},
  3984. {IntrinsicOp::MOP_SampleCmp, TranslateSample, DXIL::OpCode::SampleCmp},
  3985. {IntrinsicOp::MOP_SampleCmpLevelZero, TranslateSample, DXIL::OpCode::SampleCmpLevelZero},
  3986. {IntrinsicOp::MOP_SampleGrad, TranslateSample, DXIL::OpCode::SampleGrad},
  3987. {IntrinsicOp::MOP_SampleLevel, TranslateSample, DXIL::OpCode::SampleLevel},
  3988. {IntrinsicOp::MOP_Gather, TranslateGather, DXIL::OpCode::TextureGather},
  3989. {IntrinsicOp::MOP_GatherAlpha, TranslateGather, DXIL::OpCode::TextureGather},
  3990. {IntrinsicOp::MOP_GatherBlue, TranslateGather, DXIL::OpCode::TextureGather},
  3991. {IntrinsicOp::MOP_GatherCmp, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3992. {IntrinsicOp::MOP_GatherCmpAlpha, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3993. {IntrinsicOp::MOP_GatherCmpBlue, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3994. {IntrinsicOp::MOP_GatherCmpGreen, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3995. {IntrinsicOp::MOP_GatherCmpRed, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3996. {IntrinsicOp::MOP_GatherGreen, TranslateGather, DXIL::OpCode::TextureGather},
  3997. {IntrinsicOp::MOP_GatherRed, TranslateGather, DXIL::OpCode::TextureGather},
  3998. {IntrinsicOp::MOP_GetSamplePosition, TranslateGetSamplePosition, DXIL::OpCode::NumOpCodes},
  3999. {IntrinsicOp::MOP_Load2, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  4000. {IntrinsicOp::MOP_Load3, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  4001. {IntrinsicOp::MOP_Load4, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  4002. {IntrinsicOp::MOP_InterlockedAdd, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4003. {IntrinsicOp::MOP_InterlockedAnd, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4004. {IntrinsicOp::MOP_InterlockedCompareExchange, TranslateMopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  4005. {IntrinsicOp::MOP_InterlockedCompareStore, TranslateMopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  4006. {IntrinsicOp::MOP_InterlockedExchange, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4007. {IntrinsicOp::MOP_InterlockedMax, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4008. {IntrinsicOp::MOP_InterlockedMin, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4009. {IntrinsicOp::MOP_InterlockedOr, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4010. {IntrinsicOp::MOP_InterlockedXor, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  4011. {IntrinsicOp::MOP_Store, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  4012. {IntrinsicOp::MOP_Store2, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  4013. {IntrinsicOp::MOP_Store3, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  4014. {IntrinsicOp::MOP_Store4, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  4015. {IntrinsicOp::MOP_DecrementCounter, GenerateUpdateCounter, DXIL::OpCode::NumOpCodes},
  4016. {IntrinsicOp::MOP_IncrementCounter, GenerateUpdateCounter, DXIL::OpCode::NumOpCodes},
  4017. {IntrinsicOp::MOP_Consume, EmptyLower, DXIL::OpCode::NumOpCodes},
  4018. // Manully added part.
  4019. { IntrinsicOp::IOP_InterlockedUMax, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  4020. { IntrinsicOp::IOP_InterlockedUMin, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  4021. { IntrinsicOp::IOP_WaveActiveUMax, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  4022. { IntrinsicOp::IOP_WaveActiveUMin, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  4023. { IntrinsicOp::IOP_WaveActiveUProduct, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  4024. { IntrinsicOp::IOP_WaveActiveUSum, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  4025. { IntrinsicOp::IOP_WavePrefixUProduct, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp },
  4026. { IntrinsicOp::IOP_WavePrefixUSum, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp },
  4027. { IntrinsicOp::IOP_uclamp, TranslateClamp, DXIL::OpCode::NumOpCodes },
  4028. { IntrinsicOp::IOP_ufirstbithigh, TranslateFirstbitHi, DXIL::OpCode::FirstbitHi },
  4029. { IntrinsicOp::IOP_umad, TranslateFUITrinary, DXIL::OpCode::UMad},
  4030. { IntrinsicOp::IOP_umax, TranslateFUIBinary, DXIL::OpCode::UMax},
  4031. { IntrinsicOp::IOP_umin, TranslateFUIBinary, DXIL::OpCode::UMin },
  4032. { IntrinsicOp::IOP_umul, TranslateFUIBinary, DXIL::OpCode::UMul },
  4033. { IntrinsicOp::MOP_InterlockedUMax, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  4034. { IntrinsicOp::MOP_InterlockedUMin, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  4035. };
  4036. }
  4037. static void TranslateBuiltinIntrinsic(CallInst *CI,
  4038. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  4039. unsigned opcode = hlsl::GetHLOpcode(CI);
  4040. const IntrinsicLower &lower = gLowerTable[opcode];
  4041. Value *Result =
  4042. lower.LowerFunc(CI, lower.IntriOpcode, lower.DxilOpcode, helper, pObjHelper, Translated);
  4043. if (Result)
  4044. CI->replaceAllUsesWith(Result);
  4045. }
  4046. // SharedMem.
  4047. namespace {
  4048. bool IsSharedMemPtr(Value *Ptr) {
  4049. return Ptr->getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
  4050. }
  4051. bool IsLocalVariablePtr(Value *Ptr) {
  4052. while (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
  4053. Ptr = GEP->getPointerOperand();
  4054. }
  4055. bool isAlloca = isa<AllocaInst>(Ptr);
  4056. if (isAlloca) return true;
  4057. GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
  4058. if (!GV) return false;
  4059. return GV->getLinkage() == GlobalValue::LinkageTypes::InternalLinkage;
  4060. }
  4061. }
  4062. // Constant buffer.
  4063. namespace {
  4064. unsigned GetEltTypeByteSizeForConstBuf(Type *EltType, const DataLayout &DL) {
  4065. DXASSERT(EltType->isIntegerTy() || EltType->isFloatingPointTy(),
  4066. "not an element type");
  4067. // TODO: Use real size after change constant buffer into linear layout.
  4068. if (DL.getTypeSizeInBits(EltType) <= 32) {
  4069. // Constant buffer is 4 bytes align.
  4070. return 4;
  4071. } else
  4072. return 8;
  4073. }
  4074. Value *GenerateCBLoad(Value *handle, Value *offset, Type *EltTy, OP *hlslOP,
  4075. IRBuilder<> &Builder) {
  4076. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoad);
  4077. // Align to 8 bytes for now.
  4078. Constant *align = hlslOP->GetU32Const(8);
  4079. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4080. if (EltTy != i1Ty) {
  4081. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoad, EltTy);
  4082. return Builder.CreateCall(CBLoad, {OpArg, handle, offset, align});
  4083. } else {
  4084. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4085. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoad, i32Ty);
  4086. Value *Result = Builder.CreateCall(CBLoad, {OpArg, handle, offset, align});
  4087. return Builder.CreateICmpEQ(Result, hlslOP->GetU32Const(0));
  4088. }
  4089. }
  4090. Value *TranslateConstBufMatLd(Type *matType, Value *handle, Value *offset,
  4091. bool colMajor, OP *OP, const DataLayout &DL,
  4092. IRBuilder<> &Builder) {
  4093. unsigned col, row;
  4094. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4095. unsigned matSize = col * row;
  4096. std::vector<Value *> elts(matSize);
  4097. Value *EltByteSize = ConstantInt::get(
  4098. offset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  4099. // TODO: use real size after change constant buffer into linear layout.
  4100. Value *baseOffset = offset;
  4101. for (unsigned i = 0; i < matSize; i++) {
  4102. elts[i] = GenerateCBLoad(handle, baseOffset, EltTy, OP, Builder);
  4103. baseOffset = Builder.CreateAdd(baseOffset, EltByteSize);
  4104. }
  4105. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  4106. }
  4107. void TranslateCBGep(GetElementPtrInst *GEP, Value *handle, Value *baseOffset,
  4108. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4109. DxilFieldAnnotation *prevFieldAnnotation,
  4110. const DataLayout &DL, DxilTypeSystem &dxilTypeSys);
  4111. Value *GenerateVecEltFromGEP(Value *ldData, GetElementPtrInst *GEP,
  4112. IRBuilder<> &Builder) {
  4113. DXASSERT(GEP->getNumIndices() == 2, "must have 2 level");
  4114. Value *baseIdx = (GEP->idx_begin())->get();
  4115. Value *zeroIdx = Builder.getInt32(0);
  4116. DXASSERT_LOCALVAR(baseIdx && zeroIdx, baseIdx == zeroIdx,
  4117. "base index must be 0");
  4118. Value *idx = (GEP->idx_begin() + 1)->get();
  4119. if (ConstantInt *cidx = dyn_cast<ConstantInt>(idx)) {
  4120. return Builder.CreateExtractElement(ldData, idx);
  4121. } else {
  4122. // Dynamic indexing.
  4123. // Copy vec to array.
  4124. Type *Ty = ldData->getType();
  4125. Type *EltTy = Ty->getVectorElementType();
  4126. unsigned vecSize = Ty->getVectorNumElements();
  4127. ArrayType *AT = ArrayType::get(EltTy, vecSize);
  4128. IRBuilder<> AllocaBuilder(
  4129. GEP->getParent()->getParent()->getEntryBlock().getFirstInsertionPt());
  4130. Value *tempArray = AllocaBuilder.CreateAlloca(AT);
  4131. Value *zero = Builder.getInt32(0);
  4132. for (unsigned int i = 0; i < vecSize; i++) {
  4133. Value *Elt = Builder.CreateExtractElement(ldData, Builder.getInt32(i));
  4134. Value *Ptr =
  4135. Builder.CreateInBoundsGEP(tempArray, {zero, Builder.getInt32(i)});
  4136. Builder.CreateStore(Elt, Ptr);
  4137. }
  4138. // Load from temp array.
  4139. Value *EltGEP = Builder.CreateInBoundsGEP(tempArray, {zero, idx});
  4140. return Builder.CreateLoad(EltGEP);
  4141. }
  4142. }
  4143. void TranslateCBAddressUser(Instruction *user, Value *handle, Value *baseOffset,
  4144. hlsl::OP *hlslOP,
  4145. DxilFieldAnnotation *prevFieldAnnotation,
  4146. DxilTypeSystem &dxilTypeSys, const DataLayout &DL) {
  4147. IRBuilder<> Builder(user);
  4148. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4149. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4150. unsigned opcode = GetHLOpcode(CI);
  4151. if (group == HLOpcodeGroup::HLMatLoadStore) {
  4152. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  4153. bool colMajor = matOp == HLMatLoadStoreOpcode::ColMatLoad;
  4154. DXASSERT(matOp == HLMatLoadStoreOpcode::ColMatLoad ||
  4155. matOp == HLMatLoadStoreOpcode::RowMatLoad,
  4156. "No store on cbuffer");
  4157. Type *matType = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  4158. ->getType()
  4159. ->getPointerElementType();
  4160. Value *newLd = TranslateConstBufMatLd(matType, handle, baseOffset,
  4161. colMajor, hlslOP, DL, Builder);
  4162. CI->replaceAllUsesWith(newLd);
  4163. CI->eraseFromParent();
  4164. } else if (group == HLOpcodeGroup::HLSubscript) {
  4165. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  4166. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  4167. Type *matType = basePtr->getType()->getPointerElementType();
  4168. unsigned col, row;
  4169. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4170. Value *EltByteSize = ConstantInt::get(
  4171. baseOffset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  4172. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4173. Type *resultType = CI->getType()->getPointerElementType();
  4174. unsigned resultSize = 1;
  4175. if (resultType->isVectorTy())
  4176. resultSize = resultType->getVectorNumElements();
  4177. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  4178. _Analysis_assume_(resultSize <= 16);
  4179. Value *idxList[16];
  4180. switch (subOp) {
  4181. case HLSubscriptOpcode::ColMatSubscript:
  4182. case HLSubscriptOpcode::RowMatSubscript: {
  4183. for (unsigned i = 0; i < resultSize; i++) {
  4184. Value *idx =
  4185. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  4186. Value *offset = Builder.CreateMul(idx, EltByteSize);
  4187. idxList[i] = Builder.CreateAdd(baseOffset, offset);
  4188. }
  4189. } break;
  4190. case HLSubscriptOpcode::RowMatElement:
  4191. case HLSubscriptOpcode::ColMatElement: {
  4192. Constant *EltIdxs = cast<Constant>(idx);
  4193. for (unsigned i = 0; i < resultSize; i++) {
  4194. Value *offset =
  4195. Builder.CreateMul(EltIdxs->getAggregateElement(i), EltByteSize);
  4196. idxList[i] = Builder.CreateAdd(baseOffset, offset);
  4197. }
  4198. } break;
  4199. default:
  4200. DXASSERT(0, "invalid operation on const buffer");
  4201. break;
  4202. }
  4203. Value *ldData = UndefValue::get(resultType);
  4204. if (resultType->isVectorTy()) {
  4205. for (unsigned i = 0; i < resultSize; i++) {
  4206. Value *eltData =
  4207. GenerateCBLoad(handle, idxList[i], EltTy, hlslOP, Builder);
  4208. ldData = Builder.CreateInsertElement(ldData, eltData, i);
  4209. }
  4210. } else {
  4211. ldData = GenerateCBLoad(handle, idxList[0], EltTy, hlslOP, Builder);
  4212. }
  4213. for (auto U = CI->user_begin(); U != CI->user_end();) {
  4214. Value *subsUser = *(U++);
  4215. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  4216. Value *subData = GenerateVecEltFromGEP(ldData, GEP, Builder);
  4217. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  4218. Value *gepUser = *(gepU++);
  4219. // Must be load here;
  4220. LoadInst *ldUser = cast<LoadInst>(gepUser);
  4221. ldUser->replaceAllUsesWith(subData);
  4222. ldUser->eraseFromParent();
  4223. }
  4224. GEP->eraseFromParent();
  4225. } else {
  4226. // Must be load here.
  4227. LoadInst *ldUser = cast<LoadInst>(subsUser);
  4228. ldUser->replaceAllUsesWith(ldData);
  4229. ldUser->eraseFromParent();
  4230. }
  4231. }
  4232. CI->eraseFromParent();
  4233. } else {
  4234. DXASSERT(0, "not implemented yet");
  4235. }
  4236. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  4237. Type *Ty = ldInst->getType();
  4238. Type *EltTy = Ty->getScalarType();
  4239. DXASSERT(!Ty->isAggregateType(), "should be flat in previous pass");
  4240. unsigned EltByteSize = GetEltTypeByteSizeForConstBuf(EltTy, DL);
  4241. Value *newLd = GenerateCBLoad(handle, baseOffset, EltTy, hlslOP, Builder);
  4242. if (Ty->isVectorTy()) {
  4243. Value *result = UndefValue::get(Ty);
  4244. result = Builder.CreateInsertElement(result, newLd, (uint64_t)0);
  4245. // Update offset by 4 bytes.
  4246. Value *offset =
  4247. Builder.CreateAdd(baseOffset, hlslOP->GetU32Const(EltByteSize));
  4248. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  4249. Value *elt = GenerateCBLoad(handle, offset, EltTy, hlslOP, Builder);
  4250. result = Builder.CreateInsertElement(result, elt, i);
  4251. // Update offset by 4 bytes.
  4252. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(EltByteSize));
  4253. }
  4254. newLd = result;
  4255. }
  4256. ldInst->replaceAllUsesWith(newLd);
  4257. ldInst->eraseFromParent();
  4258. } else {
  4259. // Must be GEP here
  4260. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  4261. TranslateCBGep(GEP, handle, baseOffset, hlslOP, Builder,
  4262. prevFieldAnnotation, DL, dxilTypeSys);
  4263. GEP->eraseFromParent();
  4264. }
  4265. }
  4266. void TranslateCBGep(GetElementPtrInst *GEP, Value *handle, Value *baseOffset,
  4267. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4268. DxilFieldAnnotation *prevFieldAnnotation,
  4269. const DataLayout &DL, DxilTypeSystem &dxilTypeSys) {
  4270. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4271. Value *offset = baseOffset;
  4272. // update offset
  4273. DxilFieldAnnotation *fieldAnnotation = prevFieldAnnotation;
  4274. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4275. for (; GEPIt != E; GEPIt++) {
  4276. Value *idx = GEPIt.getOperand();
  4277. unsigned immIdx = 0;
  4278. bool bImmIdx = false;
  4279. if (Constant *constIdx = dyn_cast<Constant>(idx)) {
  4280. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4281. bImmIdx = true;
  4282. }
  4283. if (GEPIt->isPointerTy()) {
  4284. Type *EltTy = GEPIt->getPointerElementType();
  4285. unsigned size = 0;
  4286. if (StructType *ST = dyn_cast<StructType>(EltTy)) {
  4287. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4288. size = annotation->GetCBufferSize();
  4289. } else {
  4290. DXASSERT(fieldAnnotation, "must be a field");
  4291. if (ArrayType *AT = dyn_cast<ArrayType>(EltTy)) {
  4292. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4293. *fieldAnnotation, EltTy, dxilTypeSys);
  4294. // Decide the nested array size.
  4295. unsigned nestedArraySize = 1;
  4296. Type *EltTy = AT->getArrayElementType();
  4297. // support multi level of array
  4298. while (EltTy->isArrayTy()) {
  4299. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4300. nestedArraySize *= EltAT->getNumElements();
  4301. EltTy = EltAT->getElementType();
  4302. }
  4303. // Align to 4 * 4 bytes.
  4304. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4305. size = nestedArraySize * alignedSize;
  4306. } else {
  4307. size = DL.getTypeAllocSize(EltTy);
  4308. }
  4309. }
  4310. // Align to 4 * 4 bytes.
  4311. size = (size + 15) & 0xfffffff0;
  4312. if (bImmIdx) {
  4313. unsigned tempOffset = size * immIdx;
  4314. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4315. } else {
  4316. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4317. offset = Builder.CreateAdd(offset, tempOffset);
  4318. }
  4319. } else if (GEPIt->isStructTy()) {
  4320. StructType *ST = cast<StructType>(*GEPIt);
  4321. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4322. fieldAnnotation = &annotation->GetFieldAnnotation(immIdx);
  4323. unsigned structOffset = fieldAnnotation->GetCBufferOffset();
  4324. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(structOffset));
  4325. } else if (GEPIt->isArrayTy()) {
  4326. DXASSERT(fieldAnnotation != nullptr, "must a field");
  4327. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4328. *fieldAnnotation, *GEPIt, dxilTypeSys);
  4329. // Decide the nested array size.
  4330. unsigned nestedArraySize = 1;
  4331. Type *EltTy = GEPIt->getArrayElementType();
  4332. // support multi level of array
  4333. while (EltTy->isArrayTy()) {
  4334. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4335. nestedArraySize *= EltAT->getNumElements();
  4336. EltTy = EltAT->getElementType();
  4337. }
  4338. // Align to 4 * 4 bytes.
  4339. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4340. unsigned size = nestedArraySize * alignedSize;
  4341. if (bImmIdx) {
  4342. unsigned tempOffset = size * immIdx;
  4343. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4344. } else {
  4345. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4346. offset = Builder.CreateAdd(offset, tempOffset);
  4347. }
  4348. } else if (GEPIt->isVectorTy()) {
  4349. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4350. if (bImmIdx) {
  4351. unsigned tempOffset = size * immIdx;
  4352. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4353. } else {
  4354. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4355. offset = Builder.CreateAdd(offset, tempOffset);
  4356. }
  4357. } else {
  4358. gep_type_iterator temp = GEPIt;
  4359. temp++;
  4360. DXASSERT(temp == E, "scalar type must be the last");
  4361. }
  4362. }
  4363. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  4364. Instruction *user = cast<Instruction>(*(U++));
  4365. TranslateCBAddressUser(user, handle, offset, hlslOP, fieldAnnotation,
  4366. dxilTypeSys, DL);
  4367. }
  4368. }
  4369. void TranslateCBOperations(Value *handle, Value *ptr, Value *offset, OP *hlslOP,
  4370. DxilTypeSystem &dxilTypeSys, const DataLayout &DL) {
  4371. auto User = ptr->user_begin();
  4372. auto UserE = ptr->user_end();
  4373. for (; User != UserE;) {
  4374. // Must be Instruction.
  4375. Instruction *I = cast<Instruction>(*(User++));
  4376. TranslateCBAddressUser(I, handle, offset, hlslOP,
  4377. /*prevFieldAnnotation*/ nullptr, dxilTypeSys, DL);
  4378. }
  4379. }
  4380. Value *GenerateCBLoadLegacy(Value *handle, Value *legacyIdx,
  4381. unsigned channelOffset, Type *EltTy, OP *hlslOP,
  4382. IRBuilder<> &Builder) {
  4383. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
  4384. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4385. Type *doubleTy = Type::getDoubleTy(EltTy->getContext());
  4386. Type *halfTy = Type::getHalfTy(EltTy->getContext());
  4387. Type *i64Ty = Type::getInt64Ty(EltTy->getContext());
  4388. Type *i16Ty = Type::getInt16Ty(EltTy->getContext());
  4389. bool isBool = EltTy == i1Ty;
  4390. bool is64 = (EltTy == doubleTy) | (EltTy == i64Ty);
  4391. bool is16 = (EltTy == halfTy || EltTy == i16Ty) && !hlslOP->UseMinPrecision();
  4392. bool isNormal = !isBool && !is64;
  4393. DXASSERT((is16 && channelOffset < 8) || channelOffset < 4,
  4394. "legacy cbuffer don't across 16 bytes register.");
  4395. if (isNormal) {
  4396. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4397. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4398. return Builder.CreateExtractValue(loadLegacy, channelOffset);
  4399. } else if (is64) {
  4400. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4401. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4402. DXASSERT((channelOffset&1)==0,"channel offset must be even for double");
  4403. unsigned eltIdx = channelOffset>>1;
  4404. Value *Result = Builder.CreateExtractValue(loadLegacy, eltIdx);
  4405. return Result;
  4406. } else {
  4407. DXASSERT(isBool, "bool should be i1");
  4408. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4409. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, i32Ty);
  4410. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4411. Value *Result = Builder.CreateExtractValue(loadLegacy, channelOffset);
  4412. return Builder.CreateICmpEQ(Result, hlslOP->GetU32Const(0));
  4413. }
  4414. }
  4415. Value *GenerateCBLoadLegacy(Value *handle, Value *legacyIdx,
  4416. unsigned channelOffset, Type *EltTy,
  4417. unsigned vecSize, OP *hlslOP,
  4418. IRBuilder<> &Builder) {
  4419. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
  4420. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4421. Type *doubleTy = Type::getDoubleTy(EltTy->getContext());
  4422. Type *i64Ty = Type::getInt64Ty(EltTy->getContext());
  4423. Type *halfTy = Type::getHalfTy(EltTy->getContext());
  4424. Type *shortTy = Type::getInt16Ty(EltTy->getContext());
  4425. bool isBool = EltTy == i1Ty;
  4426. bool is64 = (EltTy == doubleTy) | (EltTy == i64Ty);
  4427. bool is16 = (EltTy == shortTy || EltTy == halfTy) && !hlslOP->UseMinPrecision();
  4428. bool isNormal = !isBool && !is64 && !is16;
  4429. DXASSERT((is16 && channelOffset + vecSize <= 8) ||
  4430. (channelOffset + vecSize) <= 4,
  4431. "legacy cbuffer don't across 16 bytes register.");
  4432. if (isNormal) {
  4433. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4434. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4435. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4436. for (unsigned i = 0; i < vecSize; ++i) {
  4437. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4438. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4439. }
  4440. return Result;
  4441. } else if (is16) {
  4442. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4443. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4444. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4445. for (unsigned i = 0; i < vecSize; ++i) {
  4446. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset + i);
  4447. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4448. }
  4449. return Result;
  4450. } else if (is64) {
  4451. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4452. Value *loadLegacy = Builder.CreateCall(CBLoad, { OpArg, handle, legacyIdx });
  4453. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4454. unsigned smallVecSize = 2;
  4455. if (vecSize < smallVecSize)
  4456. smallVecSize = vecSize;
  4457. for (unsigned i = 0; i < smallVecSize; ++i) {
  4458. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4459. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4460. }
  4461. if (vecSize > 2) {
  4462. // Got to next cb register.
  4463. legacyIdx = Builder.CreateAdd(legacyIdx, hlslOP->GetU32Const(1));
  4464. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4465. for (unsigned i = 2; i < vecSize; ++i) {
  4466. Value *NewElt =
  4467. Builder.CreateExtractValue(loadLegacy, i-2);
  4468. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4469. }
  4470. }
  4471. return Result;
  4472. } else {
  4473. DXASSERT(isBool, "bool should be i1");
  4474. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4475. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, i32Ty);
  4476. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4477. Value *Result = UndefValue::get(VectorType::get(i32Ty, vecSize));
  4478. for (unsigned i = 0; i < vecSize; ++i) {
  4479. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4480. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4481. }
  4482. return Builder.CreateICmpEQ(Result, ConstantAggregateZero::get(Result->getType()));
  4483. }
  4484. }
  4485. Value *TranslateConstBufMatLdLegacy(Type *matType, Value *handle,
  4486. Value *legacyIdx, bool colMajor, OP *OP,
  4487. const DataLayout &DL,
  4488. IRBuilder<> &Builder) {
  4489. unsigned col, row;
  4490. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4491. unsigned matSize = col * row;
  4492. std::vector<Value *> elts(matSize);
  4493. unsigned EltByteSize = GetEltTypeByteSizeForConstBuf(EltTy, DL);
  4494. if (colMajor) {
  4495. unsigned colByteSize = 4 * EltByteSize;
  4496. unsigned colRegSize = (colByteSize + 15) >> 4;
  4497. for (unsigned c = 0; c < col; c++) {
  4498. Value *col = GenerateCBLoadLegacy(handle, legacyIdx, /*channelOffset*/ 0,
  4499. EltTy, row, OP, Builder);
  4500. for (unsigned r = 0; r < row; r++) {
  4501. unsigned matIdx = HLMatrixLower::GetColMajorIdx(r, c, row);
  4502. elts[matIdx] = Builder.CreateExtractElement(col, r);
  4503. }
  4504. // Update offset for a column.
  4505. legacyIdx = Builder.CreateAdd(legacyIdx, OP->GetU32Const(colRegSize));
  4506. }
  4507. } else {
  4508. unsigned rowByteSize = 4 * EltByteSize;
  4509. unsigned rowRegSize = (rowByteSize + 15) >> 4;
  4510. for (unsigned r = 0; r < row; r++) {
  4511. Value *row = GenerateCBLoadLegacy(handle, legacyIdx, /*channelOffset*/ 0,
  4512. EltTy, col, OP, Builder);
  4513. for (unsigned c = 0; c < col; c++) {
  4514. unsigned matIdx = HLMatrixLower::GetRowMajorIdx(r, c, col);
  4515. elts[matIdx] = Builder.CreateExtractElement(row, c);
  4516. }
  4517. // Update offset for a row.
  4518. legacyIdx = Builder.CreateAdd(legacyIdx, OP->GetU32Const(rowRegSize));
  4519. }
  4520. }
  4521. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  4522. }
  4523. void TranslateCBGepLegacy(GetElementPtrInst *GEP, Value *handle,
  4524. Value *legacyIdx, unsigned channelOffset,
  4525. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4526. DxilFieldAnnotation *prevFieldAnnotation,
  4527. const DataLayout &DL, DxilTypeSystem &dxilTypeSys,
  4528. HLObjectOperationLowerHelper *pObjHelper);
  4529. void TranslateResourceInCB(LoadInst *LI,
  4530. HLObjectOperationLowerHelper *pObjHelper,
  4531. GlobalVariable *CbGV) {
  4532. if (LI->user_empty()) {
  4533. LI->eraseFromParent();
  4534. return;
  4535. }
  4536. GetElementPtrInst *Ptr = cast<GetElementPtrInst>(LI->getPointerOperand());
  4537. CallInst *CI = cast<CallInst>(LI->user_back());
  4538. MDNode *MD = HLModule::GetDxilResourceAttrib(CI->getCalledFunction());
  4539. Value *ResPtr = pObjHelper->GetOrCreateResourceForCbPtr(Ptr, CbGV, MD);
  4540. // Lower Ptr to GV base Ptr.
  4541. Value *GvPtr = pObjHelper->LowerCbResourcePtr(Ptr, ResPtr);
  4542. IRBuilder<> Builder(LI);
  4543. Value *GvLd = Builder.CreateLoad(GvPtr);
  4544. LI->replaceAllUsesWith(GvLd);
  4545. LI->eraseFromParent();
  4546. }
  4547. void TranslateCBAddressUserLegacy(Instruction *user, Value *handle,
  4548. Value *legacyIdx, unsigned channelOffset,
  4549. hlsl::OP *hlslOP,
  4550. DxilFieldAnnotation *prevFieldAnnotation,
  4551. DxilTypeSystem &dxilTypeSys,
  4552. const DataLayout &DL,
  4553. HLObjectOperationLowerHelper *pObjHelper) {
  4554. IRBuilder<> Builder(user);
  4555. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4556. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4557. unsigned opcode = GetHLOpcode(CI);
  4558. if (group == HLOpcodeGroup::HLMatLoadStore) {
  4559. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  4560. bool colMajor = matOp == HLMatLoadStoreOpcode::ColMatLoad;
  4561. DXASSERT(matOp == HLMatLoadStoreOpcode::ColMatLoad ||
  4562. matOp == HLMatLoadStoreOpcode::RowMatLoad,
  4563. "No store on cbuffer");
  4564. Type *matType = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  4565. ->getType()
  4566. ->getPointerElementType();
  4567. Value *newLd = TranslateConstBufMatLdLegacy(
  4568. matType, handle, legacyIdx, colMajor, hlslOP, DL, Builder);
  4569. CI->replaceAllUsesWith(newLd);
  4570. CI->eraseFromParent();
  4571. } else if (group == HLOpcodeGroup::HLSubscript) {
  4572. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  4573. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  4574. Type *matType = basePtr->getType()->getPointerElementType();
  4575. unsigned col, row;
  4576. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4577. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4578. Type *resultType = CI->getType()->getPointerElementType();
  4579. unsigned resultSize = 1;
  4580. if (resultType->isVectorTy())
  4581. resultSize = resultType->getVectorNumElements();
  4582. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  4583. _Analysis_assume_(resultSize <= 16);
  4584. Value *idxList[16];
  4585. bool colMajor = subOp == HLSubscriptOpcode::ColMatSubscript ||
  4586. subOp == HLSubscriptOpcode::ColMatElement;
  4587. bool dynamicIndexing = !isa<ConstantInt>(idx) &&
  4588. !isa<ConstantAggregateZero>(idx) &&
  4589. !isa<ConstantDataSequential>(idx);
  4590. Value *ldData = UndefValue::get(resultType);
  4591. if (!dynamicIndexing) {
  4592. Value *matLd = TranslateConstBufMatLdLegacy(
  4593. matType, handle, legacyIdx, colMajor, hlslOP, DL, Builder);
  4594. // The matLd is keep original layout, just use the idx calc in
  4595. // EmitHLSLMatrixElement and EmitHLSLMatrixSubscript.
  4596. switch (subOp) {
  4597. case HLSubscriptOpcode::RowMatSubscript:
  4598. case HLSubscriptOpcode::ColMatSubscript: {
  4599. for (unsigned i = 0; i < resultSize; i++) {
  4600. idxList[i] =
  4601. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  4602. }
  4603. } break;
  4604. case HLSubscriptOpcode::RowMatElement:
  4605. case HLSubscriptOpcode::ColMatElement: {
  4606. Constant *EltIdxs = cast<Constant>(idx);
  4607. for (unsigned i = 0; i < resultSize; i++) {
  4608. idxList[i] = EltIdxs->getAggregateElement(i);
  4609. }
  4610. } break;
  4611. default:
  4612. DXASSERT(0, "invalid operation on const buffer");
  4613. break;
  4614. }
  4615. if (resultType->isVectorTy()) {
  4616. for (unsigned i = 0; i < resultSize; i++) {
  4617. Value *eltData = Builder.CreateExtractElement(matLd, idxList[i]);
  4618. ldData = Builder.CreateInsertElement(ldData, eltData, i);
  4619. }
  4620. } else {
  4621. Value *eltData = Builder.CreateExtractElement(matLd, idxList[0]);
  4622. ldData = eltData;
  4623. }
  4624. } else {
  4625. // Must be matSub here.
  4626. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4627. if (colMajor) {
  4628. // idx is c * row + r.
  4629. // For first col, c is 0, so idx is r.
  4630. Value *one = Builder.getInt32(1);
  4631. // row.x = c[0].[idx]
  4632. // row.y = c[1].[idx]
  4633. // row.z = c[2].[idx]
  4634. // row.w = c[3].[idx]
  4635. Value *Elts[4];
  4636. ArrayType *AT = ArrayType::get(EltTy, col);
  4637. IRBuilder<> AllocaBuilder(user->getParent()
  4638. ->getParent()
  4639. ->getEntryBlock()
  4640. .getFirstInsertionPt());
  4641. Value *tempArray = AllocaBuilder.CreateAlloca(AT);
  4642. Value *zero = AllocaBuilder.getInt32(0);
  4643. Value *cbufIdx = legacyIdx;
  4644. for (unsigned int c = 0; c < col; c++) {
  4645. Value *ColVal =
  4646. GenerateCBLoadLegacy(handle, cbufIdx, /*channelOffset*/ 0,
  4647. EltTy, row, hlslOP, Builder);
  4648. // Convert ColVal to array for indexing.
  4649. for (unsigned int r = 0; r < row; r++) {
  4650. Value *Elt =
  4651. Builder.CreateExtractElement(ColVal, Builder.getInt32(r));
  4652. Value *Ptr = Builder.CreateInBoundsGEP(
  4653. tempArray, {zero, Builder.getInt32(r)});
  4654. Builder.CreateStore(Elt, Ptr);
  4655. }
  4656. Value *Ptr = Builder.CreateInBoundsGEP(tempArray, {zero, idx});
  4657. Elts[c] = Builder.CreateLoad(Ptr);
  4658. // Update cbufIdx.
  4659. cbufIdx = Builder.CreateAdd(cbufIdx, one);
  4660. }
  4661. if (resultType->isVectorTy()) {
  4662. for (unsigned int c = 0; c < col; c++) {
  4663. ldData = Builder.CreateInsertElement(ldData, Elts[c], c);
  4664. }
  4665. } else {
  4666. ldData = Elts[0];
  4667. }
  4668. } else {
  4669. // idx is r * col + c;
  4670. // r = idx / col;
  4671. Value *cCol = ConstantInt::get(idx->getType(), col);
  4672. idx = Builder.CreateUDiv(idx, cCol);
  4673. idx = Builder.CreateAdd(idx, legacyIdx);
  4674. // Just return a row.
  4675. ldData = GenerateCBLoadLegacy(handle, idx, /*channelOffset*/ 0, EltTy,
  4676. row, hlslOP, Builder);
  4677. }
  4678. if (!resultType->isVectorTy()) {
  4679. ldData = Builder.CreateExtractElement(ldData, Builder.getInt32(0));
  4680. }
  4681. }
  4682. for (auto U = CI->user_begin(); U != CI->user_end();) {
  4683. Value *subsUser = *(U++);
  4684. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  4685. Value *subData = GenerateVecEltFromGEP(ldData, GEP, Builder);
  4686. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  4687. Value *gepUser = *(gepU++);
  4688. // Must be load here;
  4689. LoadInst *ldUser = cast<LoadInst>(gepUser);
  4690. ldUser->replaceAllUsesWith(subData);
  4691. ldUser->eraseFromParent();
  4692. }
  4693. GEP->eraseFromParent();
  4694. } else {
  4695. // Must be load here.
  4696. LoadInst *ldUser = cast<LoadInst>(subsUser);
  4697. ldUser->replaceAllUsesWith(ldData);
  4698. ldUser->eraseFromParent();
  4699. }
  4700. }
  4701. CI->eraseFromParent();
  4702. } else {
  4703. DXASSERT(0, "not implemented yet");
  4704. }
  4705. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  4706. Type *Ty = ldInst->getType();
  4707. Type *EltTy = Ty->getScalarType();
  4708. // Resource inside cbuffer is lowered after GenerateDxilOperations.
  4709. if (HLModule::IsHLSLObjectType(Ty)) {
  4710. CallInst *CI = cast<CallInst>(handle);
  4711. GlobalVariable *CbGV = cast<GlobalVariable>(
  4712. CI->getArgOperand(HLOperandIndex::kCreateHandleResourceOpIdx));
  4713. TranslateResourceInCB(ldInst, pObjHelper, CbGV);
  4714. return;
  4715. }
  4716. DXASSERT(!Ty->isAggregateType(), "should be flat in previous pass");
  4717. Value *newLd = nullptr;
  4718. if (Ty->isVectorTy())
  4719. newLd = GenerateCBLoadLegacy(handle, legacyIdx, channelOffset, EltTy,
  4720. Ty->getVectorNumElements(), hlslOP, Builder);
  4721. else
  4722. newLd = GenerateCBLoadLegacy(handle, legacyIdx, channelOffset, EltTy,
  4723. hlslOP, Builder);
  4724. ldInst->replaceAllUsesWith(newLd);
  4725. ldInst->eraseFromParent();
  4726. } else {
  4727. // Must be GEP here
  4728. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  4729. TranslateCBGepLegacy(GEP, handle, legacyIdx, channelOffset, hlslOP, Builder,
  4730. prevFieldAnnotation, DL, dxilTypeSys, pObjHelper);
  4731. GEP->eraseFromParent();
  4732. }
  4733. }
  4734. void TranslateCBGepLegacy(GetElementPtrInst *GEP, Value *handle,
  4735. Value *legacyIndex, unsigned channel,
  4736. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4737. DxilFieldAnnotation *prevFieldAnnotation,
  4738. const DataLayout &DL, DxilTypeSystem &dxilTypeSys,
  4739. HLObjectOperationLowerHelper *pObjHelper) {
  4740. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4741. // update offset
  4742. DxilFieldAnnotation *fieldAnnotation = prevFieldAnnotation;
  4743. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4744. for (; GEPIt != E; GEPIt++) {
  4745. Value *idx = GEPIt.getOperand();
  4746. unsigned immIdx = 0;
  4747. bool bImmIdx = false;
  4748. if (Constant *constIdx = dyn_cast<Constant>(idx)) {
  4749. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4750. bImmIdx = true;
  4751. }
  4752. if (GEPIt->isPointerTy()) {
  4753. Type *EltTy = GEPIt->getPointerElementType();
  4754. unsigned size = 0;
  4755. if (StructType *ST = dyn_cast<StructType>(EltTy)) {
  4756. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4757. size = annotation->GetCBufferSize();
  4758. } else {
  4759. DXASSERT(fieldAnnotation, "must be a field");
  4760. if (ArrayType *AT = dyn_cast<ArrayType>(EltTy)) {
  4761. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4762. *fieldAnnotation, EltTy, dxilTypeSys);
  4763. // Decide the nested array size.
  4764. unsigned nestedArraySize = 1;
  4765. Type *EltTy = AT->getArrayElementType();
  4766. // support multi level of array
  4767. while (EltTy->isArrayTy()) {
  4768. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4769. nestedArraySize *= EltAT->getNumElements();
  4770. EltTy = EltAT->getElementType();
  4771. }
  4772. // Align to 4 * 4 bytes.
  4773. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4774. size = nestedArraySize * alignedSize;
  4775. } else {
  4776. size = DL.getTypeAllocSize(EltTy);
  4777. }
  4778. }
  4779. // Skip 0 idx.
  4780. if (bImmIdx && immIdx == 0)
  4781. continue;
  4782. // Align to 4 * 4 bytes.
  4783. size = (size + 15) & 0xfffffff0;
  4784. // Take this as array idxing.
  4785. if (bImmIdx) {
  4786. unsigned tempOffset = size * immIdx;
  4787. unsigned idxInc = tempOffset >> 4;
  4788. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4789. } else {
  4790. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4791. Value *idxInc = Builder.CreateLShr(tempOffset, 4);
  4792. legacyIndex = Builder.CreateAdd(legacyIndex, idxInc);
  4793. }
  4794. // Array always start from x channel.
  4795. channel = 0;
  4796. } else if (GEPIt->isStructTy()) {
  4797. StructType *ST = cast<StructType>(*GEPIt);
  4798. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4799. fieldAnnotation = &annotation->GetFieldAnnotation(immIdx);
  4800. unsigned idxInc = 0;
  4801. unsigned structOffset = 0;
  4802. if (fieldAnnotation->GetCompType().Is16Bit() &&
  4803. !hlslOP->UseMinPrecision()) {
  4804. structOffset = fieldAnnotation->GetCBufferOffset() >> 1;
  4805. channel += structOffset;
  4806. idxInc = channel >> 3;
  4807. channel = channel & 0x7;
  4808. }
  4809. else {
  4810. structOffset = fieldAnnotation->GetCBufferOffset() >> 2;
  4811. channel += structOffset;
  4812. idxInc = channel >> 2;
  4813. channel = channel & 0x3;
  4814. }
  4815. if (idxInc)
  4816. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4817. } else if (GEPIt->isArrayTy()) {
  4818. DXASSERT(fieldAnnotation != nullptr, "must a field");
  4819. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4820. *fieldAnnotation, *GEPIt, dxilTypeSys);
  4821. // Decide the nested array size.
  4822. unsigned nestedArraySize = 1;
  4823. Type *EltTy = GEPIt->getArrayElementType();
  4824. // support multi level of array
  4825. while (EltTy->isArrayTy()) {
  4826. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4827. nestedArraySize *= EltAT->getNumElements();
  4828. EltTy = EltAT->getElementType();
  4829. }
  4830. // Align to 4 * 4 bytes.
  4831. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4832. unsigned size = nestedArraySize * alignedSize;
  4833. if (bImmIdx) {
  4834. unsigned tempOffset = size * immIdx;
  4835. unsigned idxInc = tempOffset >> 4;
  4836. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4837. } else {
  4838. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4839. Value *idxInc = Builder.CreateLShr(tempOffset, 4);
  4840. legacyIndex = Builder.CreateAdd(legacyIndex, idxInc);
  4841. }
  4842. // Array always start from x channel.
  4843. channel = 0;
  4844. } else if (GEPIt->isVectorTy()) {
  4845. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4846. // Indexing on vector.
  4847. if (bImmIdx) {
  4848. unsigned tempOffset = size * immIdx;
  4849. unsigned channelInc = tempOffset >> 2;
  4850. DXASSERT((channel + channelInc)<=4, "vector should not cross cb register");
  4851. channel += channelInc;
  4852. if (channel == 4) {
  4853. // Get to another row.
  4854. // Update index and channel.
  4855. channel = 0;
  4856. legacyIndex = Builder.CreateAdd(legacyIndex, Builder.getInt32(1));
  4857. }
  4858. } else {
  4859. Type *EltTy = GEPIt->getVectorElementType();
  4860. // Load the whole register.
  4861. Value *newLd = GenerateCBLoadLegacy(handle, legacyIndex,
  4862. /*channelOffset*/ 0, EltTy,
  4863. /*vecSize*/ 4, hlslOP, Builder);
  4864. // Copy to array.
  4865. IRBuilder<> AllocaBuilder(GEP->getParent()->getParent()->getEntryBlock().getFirstInsertionPt());
  4866. Value *tempArray = AllocaBuilder.CreateAlloca(ArrayType::get(EltTy, 4));
  4867. Value *zeroIdx = hlslOP->GetU32Const(0);
  4868. for (unsigned i = 0; i < 4; i++) {
  4869. Value *Elt = Builder.CreateExtractElement(newLd, i);
  4870. Value *EltGEP = Builder.CreateInBoundsGEP(tempArray, {zeroIdx, hlslOP->GetU32Const(i)});
  4871. Builder.CreateStore(Elt, EltGEP);
  4872. }
  4873. // Make sure this is the end of GEP.
  4874. gep_type_iterator temp = GEPIt;
  4875. temp++;
  4876. DXASSERT(temp == E, "scalar type must be the last");
  4877. // Replace the GEP with array GEP.
  4878. Value *ArrayGEP = Builder.CreateInBoundsGEP(tempArray, {zeroIdx, idx});
  4879. GEP->replaceAllUsesWith(ArrayGEP);
  4880. return;
  4881. }
  4882. } else {
  4883. gep_type_iterator temp = GEPIt;
  4884. temp++;
  4885. DXASSERT(temp == E, "scalar type must be the last");
  4886. }
  4887. }
  4888. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  4889. Instruction *user = cast<Instruction>(*(U++));
  4890. TranslateCBAddressUserLegacy(user, handle, legacyIndex, channel, hlslOP, fieldAnnotation,
  4891. dxilTypeSys, DL, pObjHelper);
  4892. }
  4893. }
  4894. void TranslateCBOperationsLegacy(Value *handle, Value *ptr, OP *hlslOP,
  4895. DxilTypeSystem &dxilTypeSys,
  4896. const DataLayout &DL,
  4897. HLObjectOperationLowerHelper *pObjHelper) {
  4898. auto User = ptr->user_begin();
  4899. auto UserE = ptr->user_end();
  4900. Value *zeroIdx = hlslOP->GetU32Const(0);
  4901. for (; User != UserE;) {
  4902. // Must be Instruction.
  4903. Instruction *I = cast<Instruction>(*(User++));
  4904. TranslateCBAddressUserLegacy(
  4905. I, handle, zeroIdx, /*channelOffset*/ 0, hlslOP,
  4906. /*prevFieldAnnotation*/ nullptr, dxilTypeSys, DL, pObjHelper);
  4907. }
  4908. }
  4909. }
  4910. // Structured buffer.
  4911. namespace {
  4912. // Calculate offset.
  4913. Value *GEPIdxToOffset(GetElementPtrInst *GEP, IRBuilder<> &Builder,
  4914. hlsl::OP *OP, const DataLayout &DL) {
  4915. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4916. Value *addr = nullptr;
  4917. // update offset
  4918. if (GEP->hasAllConstantIndices()) {
  4919. unsigned gepOffset =
  4920. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  4921. addr = OP->GetU32Const(gepOffset);
  4922. } else {
  4923. Value *offset = OP->GetU32Const(0);
  4924. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4925. for (; GEPIt != E; GEPIt++) {
  4926. Value *idx = GEPIt.getOperand();
  4927. unsigned immIdx = 0;
  4928. if (llvm::Constant *constIdx = dyn_cast<llvm::Constant>(idx)) {
  4929. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4930. if (immIdx == 0) {
  4931. continue;
  4932. }
  4933. }
  4934. if (GEPIt->isPointerTy()) {
  4935. unsigned size = DL.getTypeAllocSize(GEPIt->getPointerElementType());
  4936. if (immIdx) {
  4937. unsigned tempOffset = size * immIdx;
  4938. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4939. } else {
  4940. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4941. offset = Builder.CreateAdd(offset, tempOffset);
  4942. }
  4943. } else if (GEPIt->isStructTy()) {
  4944. unsigned structOffset = 0;
  4945. for (unsigned i = 0; i < immIdx; i++) {
  4946. structOffset += DL.getTypeAllocSize(GEPIt->getStructElementType(i));
  4947. }
  4948. offset = Builder.CreateAdd(offset, OP->GetU32Const(structOffset));
  4949. } else if (GEPIt->isArrayTy()) {
  4950. unsigned size = DL.getTypeAllocSize(GEPIt->getArrayElementType());
  4951. if (immIdx) {
  4952. unsigned tempOffset = size * immIdx;
  4953. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4954. } else {
  4955. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4956. offset = Builder.CreateAdd(offset, tempOffset);
  4957. }
  4958. } else if (GEPIt->isVectorTy()) {
  4959. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4960. if (immIdx) {
  4961. unsigned tempOffset = size * immIdx;
  4962. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4963. } else {
  4964. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4965. offset = Builder.CreateAdd(offset, tempOffset);
  4966. }
  4967. } else {
  4968. gep_type_iterator temp = GEPIt;
  4969. temp++;
  4970. DXASSERT(temp == E, "scalar type must be the last");
  4971. }
  4972. };
  4973. addr = offset;
  4974. }
  4975. // TODO: x4 for byte address
  4976. return addr;
  4977. }
  4978. void GenerateStructBufLd(Value *handle, Value *bufIdx, Value *offset,
  4979. Value *status, Type *EltTy,
  4980. MutableArrayRef<Value *> resultElts, hlsl::OP *OP,
  4981. IRBuilder<> &Builder, unsigned NumComponents, Constant *alignment) {
  4982. OP::OpCode opcode = OP::OpCode::RawBufferLoad;
  4983. DXASSERT(resultElts.size() <= 4,
  4984. "buffer load cannot load more than 4 values");
  4985. Type *i64Ty = Builder.getInt64Ty();
  4986. Type *doubleTy = Builder.getDoubleTy();
  4987. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  4988. if (!is64) {
  4989. Function *dxilF = OP->GetOpFunc(opcode, EltTy);
  4990. Constant *mask = GetRawBufferMaskForETy(EltTy, NumComponents, OP);
  4991. Value *Args[] = {OP->GetU32Const((unsigned)opcode), handle, bufIdx, offset, mask, alignment};
  4992. Value *Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4993. for (unsigned i = 0; i < resultElts.size(); i++) {
  4994. resultElts[i] = Builder.CreateExtractValue(Ld, i);
  4995. }
  4996. // status
  4997. UpdateStatus(Ld, status, Builder, OP);
  4998. return;
  4999. } else {
  5000. // 64 bit.
  5001. Function *dxilF = OP->GetOpFunc(opcode, Builder.getInt32Ty());
  5002. Constant *mask = GetRawBufferMaskForETy(EltTy, NumComponents < 2 ? NumComponents : 2, OP);
  5003. Value *Args[] = {OP->GetU32Const((unsigned)opcode), handle, bufIdx, offset, mask, alignment};
  5004. Value *Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  5005. Value *resultElts32[8];
  5006. unsigned size = resultElts.size();
  5007. unsigned eltBase = 0;
  5008. for (unsigned i = 0; i < size; i++) {
  5009. if (i == 2) {
  5010. // Update offset 4 by 4 bytes.
  5011. Args[DXIL::OperandIndex::kRawBufferLoadElementOffsetOpIdx] =
  5012. Builder.CreateAdd(offset, Builder.getInt32(4 * 4));
  5013. // Update Mask
  5014. Args[DXIL::OperandIndex::kRawBufferLoadMaskOpIdx] =
  5015. GetRawBufferMaskForETy(EltTy, NumComponents < 3 ? 0 : NumComponents - 2, OP);
  5016. Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  5017. eltBase = 4;
  5018. }
  5019. unsigned resBase = 2 * i;
  5020. resultElts32[resBase] = Builder.CreateExtractValue(Ld, resBase - eltBase);
  5021. resultElts32[resBase + 1] =
  5022. Builder.CreateExtractValue(Ld, resBase + 1 - eltBase);
  5023. }
  5024. Make64bitResultForLoad(EltTy, resultElts32, size, resultElts, OP, Builder);
  5025. // status
  5026. UpdateStatus(Ld, status, Builder, OP);
  5027. return;
  5028. }
  5029. }
  5030. void GenerateStructBufSt(Value *handle, Value *bufIdx, Value *offset,
  5031. Type *EltTy, hlsl::OP *OP, IRBuilder<> &Builder,
  5032. ArrayRef<Value *> vals, uint8_t mask, Constant *alignment) {
  5033. OP::OpCode opcode = OP::OpCode::RawBufferStore;
  5034. DXASSERT(vals.size() == 4, "buffer store need 4 values");
  5035. Type *i64Ty = Builder.getInt64Ty();
  5036. Type *doubleTy = Builder.getDoubleTy();
  5037. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  5038. if (!is64) {
  5039. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  5040. handle,
  5041. bufIdx,
  5042. offset,
  5043. vals[0],
  5044. vals[1],
  5045. vals[2],
  5046. vals[3],
  5047. OP->GetU8Const(mask),
  5048. alignment};
  5049. Function *dxilF = OP->GetOpFunc(opcode, EltTy);
  5050. Builder.CreateCall(dxilF, Args);
  5051. } else {
  5052. Type *i32Ty = Builder.getInt32Ty();
  5053. Function *dxilF = OP->GetOpFunc(opcode, i32Ty);
  5054. Value *undefI32 = UndefValue::get(i32Ty);
  5055. Value *vals32[8] = {undefI32, undefI32, undefI32, undefI32,
  5056. undefI32, undefI32, undefI32, undefI32};
  5057. unsigned maskLo = 0;
  5058. unsigned maskHi = 0;
  5059. unsigned size = 0;
  5060. switch (mask) {
  5061. case 1:
  5062. maskLo = 3;
  5063. size = 1;
  5064. break;
  5065. case 3:
  5066. maskLo = 15;
  5067. size = 2;
  5068. break;
  5069. case 7:
  5070. maskLo = 15;
  5071. maskHi = 3;
  5072. size = 3;
  5073. break;
  5074. case 15:
  5075. maskLo = 15;
  5076. maskHi = 15;
  5077. size = 4;
  5078. break;
  5079. default:
  5080. DXASSERT(0, "invalid mask");
  5081. }
  5082. Split64bitValForStore(EltTy, vals, size, vals32, OP, Builder);
  5083. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  5084. handle,
  5085. bufIdx,
  5086. offset,
  5087. vals32[0],
  5088. vals32[1],
  5089. vals32[2],
  5090. vals32[3],
  5091. OP->GetU8Const(maskLo),
  5092. alignment};
  5093. Builder.CreateCall(dxilF, Args);
  5094. if (maskHi) {
  5095. // Update offset 4 by 4 bytes.
  5096. offset = Builder.CreateAdd(offset, Builder.getInt32(4 * 4));
  5097. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  5098. handle,
  5099. bufIdx,
  5100. offset,
  5101. vals32[4],
  5102. vals32[5],
  5103. vals32[6],
  5104. vals32[7],
  5105. OP->GetU8Const(maskHi),
  5106. alignment};
  5107. Builder.CreateCall(dxilF, Args);
  5108. }
  5109. }
  5110. }
  5111. Value *TranslateStructBufMatLd(Type *matType, IRBuilder<> &Builder,
  5112. Value *handle, hlsl::OP *OP, Value *status,
  5113. Value *bufIdx, Value *baseOffset,
  5114. bool colMajor, const DataLayout &DL) {
  5115. unsigned col, row;
  5116. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  5117. Constant* alignment = OP->GetI32Const(DL.getTypeAllocSize(EltTy));
  5118. Value *offset = baseOffset;
  5119. if (baseOffset == nullptr)
  5120. offset = OP->GetU32Const(0);
  5121. unsigned matSize = col * row;
  5122. std::vector<Value *> elts(matSize);
  5123. unsigned rest = (matSize % 4);
  5124. if (rest) {
  5125. Value *ResultElts[4];
  5126. GenerateStructBufLd(handle, bufIdx, offset, status, EltTy, ResultElts, OP, Builder, 3, alignment);
  5127. for (unsigned i = 0; i < rest; i++)
  5128. elts[i] = ResultElts[i];
  5129. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * rest));
  5130. }
  5131. for (unsigned i = rest; i < matSize; i += 4) {
  5132. Value *ResultElts[4];
  5133. GenerateStructBufLd(handle, bufIdx, offset, status, EltTy, ResultElts, OP, Builder, 4, alignment);
  5134. elts[i] = ResultElts[0];
  5135. elts[i + 1] = ResultElts[1];
  5136. elts[i + 2] = ResultElts[2];
  5137. elts[i + 3] = ResultElts[3];
  5138. // Update offset by 4*4bytes.
  5139. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * 4));
  5140. }
  5141. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  5142. }
  5143. void TranslateStructBufMatSt(Type *matType, IRBuilder<> &Builder, Value *handle,
  5144. hlsl::OP *OP, Value *bufIdx, Value *baseOffset,
  5145. Value *val, bool colMajor, const DataLayout &DL) {
  5146. unsigned col, row;
  5147. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  5148. Constant *Alignment = OP->GetI32Const(DL.getTypeAllocSize(EltTy));
  5149. Value *offset = baseOffset;
  5150. if (baseOffset == nullptr)
  5151. offset = OP->GetU32Const(0);
  5152. unsigned matSize = col * row;
  5153. Value *undefElt = UndefValue::get(EltTy);
  5154. unsigned storeSize = matSize;
  5155. if (matSize % 4) {
  5156. storeSize = matSize + 4 - (matSize & 3);
  5157. }
  5158. std::vector<Value *> elts(storeSize, undefElt);
  5159. if (colMajor) {
  5160. for (unsigned i = 0; i < matSize; i++)
  5161. elts[i] = Builder.CreateExtractElement(val, i);
  5162. } else {
  5163. for (unsigned r = 0; r < row; r++)
  5164. for (unsigned c = 0; c < col; c++) {
  5165. unsigned rowMajorIdx = r * col + c;
  5166. unsigned colMajorIdx = c * row + r;
  5167. elts[rowMajorIdx] = Builder.CreateExtractElement(val, colMajorIdx);
  5168. }
  5169. }
  5170. for (unsigned i = 0; i < matSize; i += 4) {
  5171. uint8_t mask = 0;
  5172. for (unsigned j = 0; j < 4 && (i+j) < matSize; j++) {
  5173. if (elts[i+j] != undefElt)
  5174. mask |= (1<<j);
  5175. }
  5176. GenerateStructBufSt(handle, bufIdx, offset, EltTy, OP, Builder,
  5177. {elts[i], elts[i + 1], elts[i + 2], elts[i + 3]}, mask,
  5178. Alignment);
  5179. // Update offset by 4*4bytes.
  5180. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * 4));
  5181. }
  5182. }
  5183. void TranslateStructBufMatLdSt(CallInst *CI, Value *handle, hlsl::OP *OP,
  5184. Value *status, Value *bufIdx,
  5185. Value *baseOffset, const DataLayout &DL) {
  5186. IRBuilder<> Builder(CI);
  5187. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  5188. unsigned opcode = GetHLOpcode(CI);
  5189. DXASSERT_LOCALVAR(group, group == HLOpcodeGroup::HLMatLoadStore,
  5190. "only translate matrix loadStore here.");
  5191. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  5192. switch (matOp) {
  5193. case HLMatLoadStoreOpcode::ColMatLoad: {
  5194. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx);
  5195. Value *NewLd = TranslateStructBufMatLd(
  5196. ptr->getType()->getPointerElementType(), Builder, handle, OP, status,
  5197. bufIdx, baseOffset, /*colMajor*/ true, DL);
  5198. CI->replaceAllUsesWith(NewLd);
  5199. } break;
  5200. case HLMatLoadStoreOpcode::RowMatLoad: {
  5201. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx);
  5202. Value *NewLd = TranslateStructBufMatLd(
  5203. ptr->getType()->getPointerElementType(), Builder, handle, OP, status,
  5204. bufIdx, baseOffset, /*colMajor*/ false, DL);
  5205. CI->replaceAllUsesWith(NewLd);
  5206. } break;
  5207. case HLMatLoadStoreOpcode::ColMatStore: {
  5208. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx);
  5209. Value *val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  5210. TranslateStructBufMatSt(ptr->getType()->getPointerElementType(), Builder,
  5211. handle, OP, bufIdx, baseOffset, val,
  5212. /*colMajor*/ true, DL);
  5213. } break;
  5214. case HLMatLoadStoreOpcode::RowMatStore: {
  5215. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx);
  5216. Value *val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  5217. TranslateStructBufMatSt(ptr->getType()->getPointerElementType(), Builder,
  5218. handle, OP, bufIdx, baseOffset, val,
  5219. /*colMajor*/ false, DL);
  5220. } break;
  5221. }
  5222. CI->eraseFromParent();
  5223. }
  5224. void TranslateStructBufSubscriptUser(Instruction *user, Value *handle,
  5225. Value *bufIdx, Value *baseOffset,
  5226. Value *status, hlsl::OP *OP, const DataLayout &DL);
  5227. // subscript operator for matrix of struct element.
  5228. void TranslateStructBufMatSubscript(CallInst *CI, Value *handle,
  5229. hlsl::OP *hlslOP, Value *bufIdx,
  5230. Value *baseOffset, Value *status,
  5231. const DataLayout &DL) {
  5232. Value *zeroIdx = hlslOP->GetU32Const(0);
  5233. if (baseOffset == nullptr)
  5234. baseOffset = zeroIdx;
  5235. unsigned opcode = GetHLOpcode(CI);
  5236. IRBuilder<> subBuilder(CI);
  5237. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  5238. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  5239. Type *matType = basePtr->getType()->getPointerElementType();
  5240. unsigned col, row;
  5241. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  5242. Constant *alignment = hlslOP->GetI32Const(DL.getTypeAllocSize(EltTy));
  5243. Value *EltByteSize = ConstantInt::get(
  5244. baseOffset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  5245. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  5246. Type *resultType = CI->getType()->getPointerElementType();
  5247. unsigned resultSize = 1;
  5248. if (resultType->isVectorTy())
  5249. resultSize = resultType->getVectorNumElements();
  5250. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  5251. _Analysis_assume_(resultSize <= 16);
  5252. std::vector<Value *> idxList(resultSize);
  5253. switch (subOp) {
  5254. case HLSubscriptOpcode::ColMatSubscript:
  5255. case HLSubscriptOpcode::RowMatSubscript: {
  5256. for (unsigned i = 0; i < resultSize; i++) {
  5257. Value *offset =
  5258. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  5259. offset = subBuilder.CreateMul(offset, EltByteSize);
  5260. idxList[i] = subBuilder.CreateAdd(baseOffset, offset);
  5261. }
  5262. } break;
  5263. case HLSubscriptOpcode::RowMatElement:
  5264. case HLSubscriptOpcode::ColMatElement: {
  5265. Constant *EltIdxs = cast<Constant>(idx);
  5266. for (unsigned i = 0; i < resultSize; i++) {
  5267. Value *offset =
  5268. subBuilder.CreateMul(EltIdxs->getAggregateElement(i), EltByteSize);
  5269. idxList[i] = subBuilder.CreateAdd(baseOffset, offset);
  5270. }
  5271. } break;
  5272. default:
  5273. DXASSERT(0, "invalid operation on const buffer");
  5274. break;
  5275. }
  5276. Value *undefElt = UndefValue::get(EltTy);
  5277. for (auto U = CI->user_begin(); U != CI->user_end();) {
  5278. Value *subsUser = *(U++);
  5279. if (resultSize == 1) {
  5280. TranslateStructBufSubscriptUser(cast<Instruction>(subsUser), handle,
  5281. bufIdx, idxList[0], status, hlslOP, DL);
  5282. continue;
  5283. }
  5284. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  5285. Value *GEPOffset =
  5286. HLMatrixLower::LowerGEPOnMatIndexListToIndex(GEP, idxList);
  5287. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  5288. Instruction *gepUserInst = cast<Instruction>(*(gepU++));
  5289. TranslateStructBufSubscriptUser(gepUserInst, handle, bufIdx, GEPOffset,
  5290. status, hlslOP, DL);
  5291. }
  5292. GEP->eraseFromParent();
  5293. } else if (StoreInst *stUser = dyn_cast<StoreInst>(subsUser)) {
  5294. IRBuilder<> stBuilder(stUser);
  5295. Value *Val = stUser->getValueOperand();
  5296. if (Val->getType()->isVectorTy()) {
  5297. for (unsigned i = 0; i < resultSize; i++) {
  5298. Value *EltVal = stBuilder.CreateExtractElement(Val, i);
  5299. uint8_t mask = DXIL::kCompMask_X;
  5300. GenerateStructBufSt(handle, bufIdx, idxList[i], EltTy, hlslOP,
  5301. stBuilder, {EltVal, undefElt, undefElt, undefElt},
  5302. mask, alignment);
  5303. }
  5304. } else {
  5305. uint8_t mask = DXIL::kCompMask_X;
  5306. GenerateStructBufSt(handle, bufIdx, idxList[0], EltTy, hlslOP,
  5307. stBuilder, {Val, undefElt, undefElt, undefElt},
  5308. mask, alignment);
  5309. }
  5310. stUser->eraseFromParent();
  5311. } else {
  5312. // Must be load here.
  5313. LoadInst *ldUser = cast<LoadInst>(subsUser);
  5314. IRBuilder<> ldBuilder(ldUser);
  5315. Value *ldData = UndefValue::get(resultType);
  5316. if (resultType->isVectorTy()) {
  5317. for (unsigned i = 0; i < resultSize; i++) {
  5318. Value *ResultElt;
  5319. // TODO: This can be inefficient for row major matrix load
  5320. GenerateStructBufLd(handle, bufIdx, idxList[i],
  5321. /*status*/ nullptr, EltTy, ResultElt, hlslOP,
  5322. ldBuilder, 1, alignment);
  5323. ldData = ldBuilder.CreateInsertElement(ldData, ResultElt, i);
  5324. }
  5325. } else {
  5326. GenerateStructBufLd(handle, bufIdx, idxList[0], /*status*/ nullptr,
  5327. EltTy, ldData, hlslOP, ldBuilder, 4, alignment);
  5328. }
  5329. ldUser->replaceAllUsesWith(ldData);
  5330. ldUser->eraseFromParent();
  5331. }
  5332. }
  5333. CI->eraseFromParent();
  5334. }
  5335. void TranslateStructBufSubscriptUser(Instruction *user, Value *handle,
  5336. Value *bufIdx, Value *baseOffset,
  5337. Value *status, hlsl::OP *OP, const DataLayout &DL) {
  5338. IRBuilder<> Builder(user);
  5339. if (CallInst *userCall = dyn_cast<CallInst>(user)) {
  5340. HLOpcodeGroup group = // user call?
  5341. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5342. unsigned opcode = GetHLOpcode(userCall);
  5343. // For case element type of structure buffer is not structure type.
  5344. if (baseOffset == nullptr)
  5345. baseOffset = OP->GetU32Const(0);
  5346. if (group == HLOpcodeGroup::HLIntrinsic) {
  5347. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5348. switch (IOP) {
  5349. case IntrinsicOp::MOP_Load: {
  5350. if (userCall->getType()->isPointerTy()) {
  5351. // Struct will return pointers which like []
  5352. } else {
  5353. // Use builtin types on structuredBuffer.
  5354. }
  5355. DXASSERT(0, "not implement yet");
  5356. } break;
  5357. case IntrinsicOp::IOP_InterlockedAdd: {
  5358. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5359. baseOffset);
  5360. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Add,
  5361. Builder, OP);
  5362. } break;
  5363. case IntrinsicOp::IOP_InterlockedAnd: {
  5364. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5365. baseOffset);
  5366. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::And,
  5367. Builder, OP);
  5368. } break;
  5369. case IntrinsicOp::IOP_InterlockedExchange: {
  5370. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5371. baseOffset);
  5372. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Exchange,
  5373. Builder, OP);
  5374. } break;
  5375. case IntrinsicOp::IOP_InterlockedMax: {
  5376. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5377. baseOffset);
  5378. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMax,
  5379. Builder, OP);
  5380. } break;
  5381. case IntrinsicOp::IOP_InterlockedMin: {
  5382. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5383. baseOffset);
  5384. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMin,
  5385. Builder, OP);
  5386. } break;
  5387. case IntrinsicOp::IOP_InterlockedUMax: {
  5388. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5389. baseOffset);
  5390. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMax,
  5391. Builder, OP);
  5392. } break;
  5393. case IntrinsicOp::IOP_InterlockedUMin: {
  5394. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5395. baseOffset);
  5396. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMin,
  5397. Builder, OP);
  5398. } break;
  5399. case IntrinsicOp::IOP_InterlockedOr: {
  5400. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5401. baseOffset);
  5402. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Or,
  5403. Builder, OP);
  5404. } break;
  5405. case IntrinsicOp::IOP_InterlockedXor: {
  5406. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5407. baseOffset);
  5408. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Xor,
  5409. Builder, OP);
  5410. } break;
  5411. case IntrinsicOp::IOP_InterlockedCompareStore:
  5412. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5413. AtomicHelper helper(userCall, DXIL::OpCode::AtomicCompareExchange,
  5414. handle, bufIdx, baseOffset);
  5415. TranslateAtomicCmpXChg(helper, Builder, OP);
  5416. } break;
  5417. default:
  5418. DXASSERT(0, "invalid opcode");
  5419. break;
  5420. }
  5421. userCall->eraseFromParent();
  5422. } else if (group == HLOpcodeGroup::HLMatLoadStore)
  5423. // TODO: support 64 bit.
  5424. TranslateStructBufMatLdSt(userCall, handle, OP, status, bufIdx,
  5425. baseOffset, DL);
  5426. else if (group == HLOpcodeGroup::HLSubscript) {
  5427. TranslateStructBufMatSubscript(userCall, handle, OP, bufIdx, baseOffset, status, DL);
  5428. }
  5429. } else if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
  5430. LoadInst *ldInst = dyn_cast<LoadInst>(user);
  5431. StoreInst *stInst = dyn_cast<StoreInst>(user);
  5432. Type *Ty = isa<LoadInst>(user) ? ldInst->getType()
  5433. : stInst->getValueOperand()->getType();
  5434. Type *pOverloadTy = Ty->getScalarType();
  5435. Value *offset = baseOffset;
  5436. if (baseOffset == nullptr)
  5437. offset = OP->GetU32Const(0);
  5438. unsigned arraySize = 1;
  5439. Value *eltSize = nullptr;
  5440. if (pOverloadTy->isArrayTy()) {
  5441. arraySize = pOverloadTy->getArrayNumElements();
  5442. eltSize = OP->GetU32Const(
  5443. DL.getTypeAllocSize(pOverloadTy->getArrayElementType()));
  5444. pOverloadTy = pOverloadTy->getArrayElementType()->getScalarType();
  5445. }
  5446. if (ldInst) {
  5447. auto LdElement = [&](Value *offset, IRBuilder<> &Builder) -> Value * {
  5448. Value *ResultElts[4];
  5449. unsigned numComponents = 0;
  5450. if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  5451. numComponents = VTy->getNumElements();
  5452. }
  5453. else {
  5454. numComponents = 1;
  5455. }
  5456. Constant *alignment =
  5457. OP->GetI32Const(DL.getTypeAllocSize(Ty->getScalarType()));
  5458. GenerateStructBufLd(handle, bufIdx, offset, status, pOverloadTy,
  5459. ResultElts, OP, Builder, numComponents, alignment);
  5460. return ScalarizeElements(Ty, ResultElts, Builder);
  5461. };
  5462. Value *newLd = LdElement(offset, Builder);
  5463. if (arraySize > 1) {
  5464. newLd =
  5465. Builder.CreateInsertValue(UndefValue::get(Ty), newLd, (uint64_t)0);
  5466. for (unsigned i = 1; i < arraySize; i++) {
  5467. offset = Builder.CreateAdd(offset, eltSize);
  5468. Value *eltLd = LdElement(offset, Builder);
  5469. newLd = Builder.CreateInsertValue(newLd, eltLd, i);
  5470. }
  5471. }
  5472. ldInst->replaceAllUsesWith(newLd);
  5473. } else {
  5474. Value *val = stInst->getValueOperand();
  5475. auto StElement = [&](Value *offset, Value *val, IRBuilder<> &Builder) {
  5476. Value *undefVal = llvm::UndefValue::get(pOverloadTy);
  5477. Value *vals[] = {undefVal, undefVal, undefVal, undefVal};
  5478. uint8_t mask = 0;
  5479. if (Ty->isVectorTy()) {
  5480. unsigned vectorNumElements = Ty->getVectorNumElements();
  5481. DXASSERT(vectorNumElements <= 4, "up to 4 elements in vector");
  5482. _Analysis_assume_(vectorNumElements <= 4);
  5483. for (unsigned i = 0; i < vectorNumElements; i++) {
  5484. vals[i] = Builder.CreateExtractElement(val, i);
  5485. mask |= (1<<i);
  5486. }
  5487. } else {
  5488. vals[0] = val;
  5489. mask = DXIL::kCompMask_X;
  5490. }
  5491. Constant *alignment =
  5492. OP->GetI32Const(DL.getTypeAllocSize(Ty->getScalarType()));
  5493. GenerateStructBufSt(handle, bufIdx, offset, pOverloadTy, OP, Builder,
  5494. vals, mask, alignment);
  5495. };
  5496. if (arraySize > 1)
  5497. val = Builder.CreateExtractValue(val, 0);
  5498. StElement(offset, val, Builder);
  5499. if (arraySize > 1) {
  5500. val = stInst->getValueOperand();
  5501. for (unsigned i = 1; i < arraySize; i++) {
  5502. offset = Builder.CreateAdd(offset, eltSize);
  5503. Value *eltVal = Builder.CreateExtractValue(val, i);
  5504. StElement(offset, eltVal, Builder);
  5505. }
  5506. }
  5507. }
  5508. user->eraseFromParent();
  5509. } else {
  5510. // should only used by GEP
  5511. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  5512. Type *Ty = GEP->getType()->getPointerElementType();
  5513. Value *offset = GEPIdxToOffset(GEP, Builder, OP, DL);
  5514. DXASSERT_LOCALVAR(Ty, offset->getType() == Type::getInt32Ty(Ty->getContext()),
  5515. "else bitness is wrong");
  5516. if (baseOffset)
  5517. offset = Builder.CreateAdd(offset, baseOffset);
  5518. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  5519. Value *GEPUser = *(U++);
  5520. TranslateStructBufSubscriptUser(cast<Instruction>(GEPUser), handle,
  5521. bufIdx, offset, status, OP, DL);
  5522. }
  5523. // delete the inst
  5524. GEP->eraseFromParent();
  5525. }
  5526. }
  5527. void TranslateStructBufSubscript(CallInst *CI, Value *handle, Value *status,
  5528. hlsl::OP *OP, const DataLayout &DL) {
  5529. Value *bufIdx = CI->getArgOperand(HLOperandIndex::kSubscriptIndexOpIdx);
  5530. for (auto U = CI->user_begin(); U != CI->user_end();) {
  5531. Value *user = *(U++);
  5532. TranslateStructBufSubscriptUser(cast<Instruction>(user), handle, bufIdx,
  5533. /*baseOffset*/ nullptr, status, OP, DL);
  5534. }
  5535. }
  5536. }
  5537. // HLSubscript.
  5538. namespace {
  5539. Value *TranslateTypedBufLoad(CallInst *CI, DXIL::ResourceKind RK,
  5540. DXIL::ResourceClass RC, Value *handle,
  5541. LoadInst *ldInst, IRBuilder<> &Builder,
  5542. hlsl::OP *hlslOP, const DataLayout &DL) {
  5543. ResLoadHelper ldHelper(CI, RK, RC, handle, IntrinsicOp::MOP_Load, /*bForSubscript*/ true);
  5544. // Default sampleIdx for 2DMS textures.
  5545. if (RK == DxilResource::Kind::Texture2DMS ||
  5546. RK == DxilResource::Kind::Texture2DMSArray)
  5547. ldHelper.mipLevel = hlslOP->GetU32Const(0);
  5548. // use ldInst as retVal
  5549. ldHelper.retVal = ldInst;
  5550. TranslateLoad(ldHelper, RK, Builder, hlslOP, DL);
  5551. // delete the ld
  5552. ldInst->eraseFromParent();
  5553. return ldHelper.retVal;
  5554. }
  5555. Value *UpdateVectorElt(Value *VecVal, Value *EltVal, Value *EltIdx,
  5556. unsigned vectorSize, Instruction *InsertPt) {
  5557. IRBuilder<> Builder(InsertPt);
  5558. if (ConstantInt *CEltIdx = dyn_cast<ConstantInt>(EltIdx)) {
  5559. VecVal =
  5560. Builder.CreateInsertElement(VecVal, EltVal, CEltIdx->getLimitedValue());
  5561. } else {
  5562. BasicBlock *BB = InsertPt->getParent();
  5563. BasicBlock *EndBB = BB->splitBasicBlock(InsertPt);
  5564. TerminatorInst *TI = BB->getTerminator();
  5565. IRBuilder<> SwitchBuilder(TI);
  5566. LLVMContext &Ctx = InsertPt->getContext();
  5567. SwitchInst *Switch = SwitchBuilder.CreateSwitch(EltIdx, EndBB, vectorSize);
  5568. TI->eraseFromParent();
  5569. Function *F = EndBB->getParent();
  5570. IRBuilder<> endSwitchBuilder(EndBB->begin());
  5571. Type *Ty = VecVal->getType();
  5572. PHINode *VecPhi = endSwitchBuilder.CreatePHI(Ty, vectorSize + 1);
  5573. for (unsigned i = 0; i < vectorSize; i++) {
  5574. BasicBlock *CaseBB = BasicBlock::Create(Ctx, "case", F, EndBB);
  5575. Switch->addCase(SwitchBuilder.getInt32(i), CaseBB);
  5576. IRBuilder<> CaseBuilder(CaseBB);
  5577. Value *CaseVal = CaseBuilder.CreateInsertElement(VecVal, EltVal, i);
  5578. VecPhi->addIncoming(CaseVal, CaseBB);
  5579. CaseBuilder.CreateBr(EndBB);
  5580. }
  5581. VecPhi->addIncoming(VecVal, BB);
  5582. VecVal = VecPhi;
  5583. }
  5584. return VecVal;
  5585. }
  5586. void TranslateDefaultSubscript(CallInst *CI, HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  5587. auto U = CI->user_begin();
  5588. Value *ptr = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5589. hlsl::OP *hlslOP = &helper.hlslOP;
  5590. // Resource ptr.
  5591. Value *handle = ptr;
  5592. DXIL::ResourceClass RC = pObjHelper->GetRC(handle);
  5593. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5594. Type *Ty = CI->getType()->getPointerElementType();
  5595. for (auto It = CI->user_begin(); It != CI->user_end(); ) {
  5596. User *user = *(It++);
  5597. Instruction *I = cast<Instruction>(user);
  5598. IRBuilder<> Builder(I);
  5599. if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  5600. TranslateTypedBufLoad(CI, RK, RC, handle, ldInst, Builder, hlslOP, helper.dataLayout);
  5601. } else if (StoreInst *stInst = dyn_cast<StoreInst>(user)) {
  5602. Value *val = stInst->getValueOperand();
  5603. TranslateStore(RK, handle, val,
  5604. CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx),
  5605. Builder, hlslOP);
  5606. // delete the st
  5607. stInst->eraseFromParent();
  5608. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  5609. // Must be vector type here.
  5610. unsigned vectorSize = Ty->getVectorNumElements();
  5611. DXASSERT(GEP->getNumIndices() == 2, "");
  5612. Use *GEPIdx = GEP->idx_begin();
  5613. GEPIdx++;
  5614. Value *EltIdx = *GEPIdx;
  5615. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  5616. User *GEPUser = *(GEPIt++);
  5617. if (StoreInst *SI = dyn_cast<StoreInst>(GEPUser)) {
  5618. IRBuilder<> StBuilder(SI);
  5619. // Generate Ld.
  5620. LoadInst *tmpLd = StBuilder.CreateLoad(CI);
  5621. Value *ldVal = TranslateTypedBufLoad(CI, RK, RC, handle, tmpLd, StBuilder,
  5622. hlslOP, helper.dataLayout);
  5623. // Update vector.
  5624. ldVal = UpdateVectorElt(ldVal, SI->getValueOperand(), EltIdx,
  5625. vectorSize, SI);
  5626. // Generate St.
  5627. // Reset insert point, UpdateVectorElt may move SI to different block.
  5628. StBuilder.SetInsertPoint(SI);
  5629. TranslateStore(RK, handle, ldVal,
  5630. CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx),
  5631. StBuilder, hlslOP);
  5632. SI->eraseFromParent();
  5633. continue;
  5634. }
  5635. if (!isa<CallInst>(GEPUser)) {
  5636. // Invalid operations.
  5637. Translated = false;
  5638. CI->getContext().emitError(GEP, "Invalid operation on typed buffer");
  5639. return;
  5640. }
  5641. CallInst *userCall = cast<CallInst>(GEPUser);
  5642. HLOpcodeGroup group =
  5643. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5644. if (group != HLOpcodeGroup::HLIntrinsic) {
  5645. // Invalid operations.
  5646. Translated = false;
  5647. CI->getContext().emitError(userCall,
  5648. "Invalid operation on typed buffer");
  5649. return;
  5650. }
  5651. unsigned opcode = hlsl::GetHLOpcode(userCall);
  5652. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5653. switch (IOP) {
  5654. case IntrinsicOp::IOP_InterlockedAdd:
  5655. case IntrinsicOp::IOP_InterlockedAnd:
  5656. case IntrinsicOp::IOP_InterlockedExchange:
  5657. case IntrinsicOp::IOP_InterlockedMax:
  5658. case IntrinsicOp::IOP_InterlockedMin:
  5659. case IntrinsicOp::IOP_InterlockedUMax:
  5660. case IntrinsicOp::IOP_InterlockedUMin:
  5661. case IntrinsicOp::IOP_InterlockedOr:
  5662. case IntrinsicOp::IOP_InterlockedXor:
  5663. case IntrinsicOp::IOP_InterlockedCompareStore:
  5664. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5665. // Invalid operations.
  5666. Translated = false;
  5667. CI->getContext().emitError(
  5668. userCall, "Atomic operation on typed buffer is not supported");
  5669. return;
  5670. } break;
  5671. default:
  5672. // Invalid operations.
  5673. Translated = false;
  5674. CI->getContext().emitError(userCall,
  5675. "Invalid operation on typed buffer");
  5676. return;
  5677. break;
  5678. }
  5679. }
  5680. GEP->eraseFromParent();
  5681. } else {
  5682. CallInst *userCall = cast<CallInst>(user);
  5683. HLOpcodeGroup group =
  5684. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5685. unsigned opcode = hlsl::GetHLOpcode(userCall);
  5686. if (group == HLOpcodeGroup::HLIntrinsic) {
  5687. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5688. if (RC == DXIL::ResourceClass::SRV) {
  5689. // Invalid operations.
  5690. Translated = false;
  5691. switch (IOP) {
  5692. case IntrinsicOp::IOP_InterlockedAdd:
  5693. case IntrinsicOp::IOP_InterlockedAnd:
  5694. case IntrinsicOp::IOP_InterlockedExchange:
  5695. case IntrinsicOp::IOP_InterlockedMax:
  5696. case IntrinsicOp::IOP_InterlockedMin:
  5697. case IntrinsicOp::IOP_InterlockedUMax:
  5698. case IntrinsicOp::IOP_InterlockedUMin:
  5699. case IntrinsicOp::IOP_InterlockedOr:
  5700. case IntrinsicOp::IOP_InterlockedXor:
  5701. case IntrinsicOp::IOP_InterlockedCompareStore:
  5702. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5703. CI->getContext().emitError(
  5704. userCall, "Atomic operation targets must be groupshared on UAV");
  5705. return;
  5706. } break;
  5707. default:
  5708. CI->getContext().emitError(userCall,
  5709. "Invalid operation on typed buffer");
  5710. return;
  5711. break;
  5712. }
  5713. }
  5714. switch (IOP) {
  5715. case IntrinsicOp::IOP_InterlockedAdd: {
  5716. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedAdd);
  5717. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5718. helper.addr, /*offset*/ nullptr);
  5719. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Add,
  5720. Builder, hlslOP);
  5721. } break;
  5722. case IntrinsicOp::IOP_InterlockedAnd: {
  5723. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedAnd);
  5724. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5725. helper.addr, /*offset*/ nullptr);
  5726. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::And,
  5727. Builder, hlslOP);
  5728. } break;
  5729. case IntrinsicOp::IOP_InterlockedExchange: {
  5730. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedExchange);
  5731. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5732. helper.addr, /*offset*/ nullptr);
  5733. TranslateAtomicBinaryOperation(
  5734. atomHelper, DXIL::AtomicBinOpCode::Exchange, Builder, hlslOP);
  5735. } break;
  5736. case IntrinsicOp::IOP_InterlockedMax: {
  5737. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedMax);
  5738. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5739. helper.addr, /*offset*/ nullptr);
  5740. TranslateAtomicBinaryOperation(
  5741. atomHelper, DXIL::AtomicBinOpCode::IMax, Builder, hlslOP);
  5742. } break;
  5743. case IntrinsicOp::IOP_InterlockedMin: {
  5744. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedMin);
  5745. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5746. helper.addr, /*offset*/ nullptr);
  5747. TranslateAtomicBinaryOperation(
  5748. atomHelper, DXIL::AtomicBinOpCode::IMin, Builder, hlslOP);
  5749. } break;
  5750. case IntrinsicOp::IOP_InterlockedUMax: {
  5751. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedUMax);
  5752. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5753. helper.addr, /*offset*/ nullptr);
  5754. TranslateAtomicBinaryOperation(
  5755. atomHelper, DXIL::AtomicBinOpCode::UMax, Builder, hlslOP);
  5756. } break;
  5757. case IntrinsicOp::IOP_InterlockedUMin: {
  5758. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedUMin);
  5759. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5760. helper.addr, /*offset*/ nullptr);
  5761. TranslateAtomicBinaryOperation(
  5762. atomHelper, DXIL::AtomicBinOpCode::UMin, Builder, hlslOP);
  5763. } break;
  5764. case IntrinsicOp::IOP_InterlockedOr: {
  5765. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedOr);
  5766. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5767. helper.addr, /*offset*/ nullptr);
  5768. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Or,
  5769. Builder, hlslOP);
  5770. } break;
  5771. case IntrinsicOp::IOP_InterlockedXor: {
  5772. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedXor);
  5773. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5774. helper.addr, /*offset*/ nullptr);
  5775. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Xor,
  5776. Builder, hlslOP);
  5777. } break;
  5778. case IntrinsicOp::IOP_InterlockedCompareStore:
  5779. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5780. ResLoadHelper helper(CI, RK, RC, handle, IntrinsicOp::IOP_InterlockedCompareExchange);
  5781. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicCompareExchange,
  5782. handle, helper.addr, /*offset*/ nullptr);
  5783. TranslateAtomicCmpXChg(atomHelper, Builder, hlslOP);
  5784. } break;
  5785. default:
  5786. DXASSERT(0, "invalid opcode");
  5787. break;
  5788. }
  5789. } else {
  5790. DXASSERT(0, "invalid group");
  5791. }
  5792. userCall->eraseFromParent();
  5793. }
  5794. }
  5795. }
  5796. void TranslateHLSubscript(CallInst *CI, HLSubscriptOpcode opcode,
  5797. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  5798. if (CI->user_empty()) {
  5799. Translated = true;
  5800. return;
  5801. }
  5802. hlsl::OP *hlslOP = &helper.hlslOP;
  5803. Value *ptr = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5804. if (opcode == HLSubscriptOpcode::CBufferSubscript) {
  5805. HLModule::MergeGepUse(CI);
  5806. // Resource ptr.
  5807. Value *handle = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5808. if (helper.bLegacyCBufferLoad)
  5809. TranslateCBOperationsLegacy(handle, CI, hlslOP, helper.dxilTypeSys,
  5810. helper.dataLayout, pObjHelper);
  5811. else {
  5812. TranslateCBOperations(handle, CI, /*offset*/ hlslOP->GetU32Const(0),
  5813. hlslOP, helper.dxilTypeSys,
  5814. CI->getModule()->getDataLayout());
  5815. }
  5816. Translated = true;
  5817. return;
  5818. } else if (opcode == HLSubscriptOpcode::DoubleSubscript) {
  5819. // Resource ptr.
  5820. Value *handle = ptr;
  5821. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5822. Value *coord = CI->getArgOperand(HLOperandIndex::kSubscriptIndexOpIdx);
  5823. Value *mipLevel =
  5824. CI->getArgOperand(HLOperandIndex::kDoubleSubscriptMipLevelOpIdx);
  5825. auto U = CI->user_begin();
  5826. DXASSERT(CI->hasOneUse(), "subscript should only has one use");
  5827. // TODO: support store.
  5828. Instruction *ldInst = cast<Instruction>(*U);
  5829. ResLoadHelper ldHelper(ldInst, handle, coord, mipLevel);
  5830. IRBuilder<> Builder(CI);
  5831. TranslateLoad(ldHelper, RK, Builder, hlslOP, helper.dataLayout);
  5832. ldInst->eraseFromParent();
  5833. Translated = true;
  5834. return;
  5835. } else {
  5836. Type *HandleTy = hlslOP->GetHandleType();
  5837. if (ptr->getType() == HandleTy) {
  5838. // Resource ptr.
  5839. Value *handle = ptr;
  5840. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5841. if (RK == DxilResource::Kind::Invalid) {
  5842. Translated = false;
  5843. return;
  5844. }
  5845. Translated = true;
  5846. Type *ObjTy = pObjHelper->GetResourceType(handle);
  5847. Type *RetTy = ObjTy->getStructElementType(0);
  5848. if (RK == DxilResource::Kind::StructuredBuffer) {
  5849. TranslateStructBufSubscript(CI, handle, /*status*/ nullptr, hlslOP,
  5850. helper.dataLayout);
  5851. } else if (RetTy->isAggregateType() &&
  5852. RK == DxilResource::Kind::TypedBuffer) {
  5853. TranslateStructBufSubscript(CI, handle, /*status*/ nullptr, hlslOP,
  5854. helper.dataLayout);
  5855. // Clear offset for typed buf.
  5856. for (auto User : handle->users()) {
  5857. CallInst *CI = cast<CallInst>(User);
  5858. // Skip not lowered HL functions.
  5859. if (hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction()) != HLOpcodeGroup::NotHL)
  5860. continue;
  5861. switch (hlslOP->GetDxilOpFuncCallInst(CI)) {
  5862. case DXIL::OpCode::BufferLoad: {
  5863. CI->setArgOperand(DXIL::OperandIndex::kBufferLoadCoord1OpIdx,
  5864. UndefValue::get(helper.i32Ty));
  5865. } break;
  5866. case DXIL::OpCode::BufferStore: {
  5867. CI->setArgOperand(DXIL::OperandIndex::kBufferStoreCoord1OpIdx,
  5868. UndefValue::get(helper.i32Ty));
  5869. } break;
  5870. case DXIL::OpCode::AtomicBinOp: {
  5871. CI->setArgOperand(DXIL::OperandIndex::kAtomicBinOpCoord1OpIdx,
  5872. UndefValue::get(helper.i32Ty));
  5873. } break;
  5874. case DXIL::OpCode::AtomicCompareExchange: {
  5875. CI->setArgOperand(DXIL::OperandIndex::kAtomicCmpExchangeCoord1OpIdx,
  5876. UndefValue::get(helper.i32Ty));
  5877. } break;
  5878. case DXIL::OpCode::RawBufferLoad: {
  5879. // Structured buffer inside a typed buffer must be converted to typed buffer load.
  5880. // Typed buffer load is equivalent to raw buffer load, except there is no mask.
  5881. StructType *STy = cast<StructType>(CI->getFunctionType()->getReturnType());
  5882. Type *ETy = STy->getElementType(0);
  5883. SmallVector<Value *, 4> Args;
  5884. Args.emplace_back(hlslOP->GetI32Const((unsigned)DXIL::OpCode::BufferLoad));
  5885. Args.emplace_back(CI->getArgOperand(1)); // handle
  5886. Args.emplace_back(CI->getArgOperand(2)); // index
  5887. Args.emplace_back(UndefValue::get(helper.i32Ty)); // offset
  5888. IRBuilder<> builder(CI);
  5889. Function *newFunction = hlslOP->GetOpFunc(DXIL::OpCode::BufferLoad, ETy);
  5890. CallInst *newCall = builder.CreateCall(newFunction, Args);
  5891. CI->replaceAllUsesWith(newCall);
  5892. CI->eraseFromParent();
  5893. } break;
  5894. default:
  5895. DXASSERT(0, "Invalid operation on resource handle");
  5896. break;
  5897. }
  5898. }
  5899. } else {
  5900. TranslateDefaultSubscript(CI, helper, pObjHelper, Translated);
  5901. }
  5902. return;
  5903. }
  5904. }
  5905. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  5906. if (IsLocalVariablePtr(basePtr) || IsSharedMemPtr(basePtr)) {
  5907. // Translate matrix into vector of array for share memory or local
  5908. // variable should be done in HLMatrixLowerPass
  5909. DXASSERT_NOMSG(0);
  5910. Translated = true;
  5911. return;
  5912. }
  5913. // Other case should be take care in TranslateStructBufSubscript or
  5914. // TranslateCBOperations.
  5915. Translated = false;
  5916. return;
  5917. }
  5918. }
  5919. void TranslateSubscriptOperation(Function *F, HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper) {
  5920. for (auto U = F->user_begin(); U != F->user_end();) {
  5921. Value *user = *(U++);
  5922. if (!isa<Instruction>(user))
  5923. continue;
  5924. // must be call inst
  5925. CallInst *CI = cast<CallInst>(user);
  5926. unsigned opcode = GetHLOpcode(CI);
  5927. bool Translated = true;
  5928. TranslateHLSubscript(
  5929. CI, static_cast<HLSubscriptOpcode>(opcode), helper, pObjHelper, Translated);
  5930. if (Translated) {
  5931. // delete the call
  5932. DXASSERT(CI->use_empty(),
  5933. "else TranslateHLSubscript didn't replace/erase uses");
  5934. CI->eraseFromParent();
  5935. }
  5936. }
  5937. }
  5938. void TranslateHLBuiltinOperation(Function *F, HLOperationLowerHelper &helper,
  5939. hlsl::HLOpcodeGroup group, HLObjectOperationLowerHelper *pObjHelper) {
  5940. if (group == HLOpcodeGroup::HLIntrinsic) {
  5941. // map to dxil operations
  5942. for (auto U = F->user_begin(); U != F->user_end();) {
  5943. Value *User = *(U++);
  5944. if (!isa<Instruction>(User))
  5945. continue;
  5946. // must be call inst
  5947. CallInst *CI = cast<CallInst>(User);
  5948. // Keep the instruction to lower by other function.
  5949. bool Translated = true;
  5950. TranslateBuiltinIntrinsic(CI, helper, pObjHelper, Translated);
  5951. if (Translated) {
  5952. // delete the call
  5953. DXASSERT(CI->use_empty(),
  5954. "else TranslateBuiltinIntrinsic didn't replace/erase uses");
  5955. CI->eraseFromParent();
  5956. }
  5957. }
  5958. } else {
  5959. if (group == HLOpcodeGroup::HLMatLoadStore) {
  5960. // Both ld/st use arg1 for the pointer.
  5961. Type *PtrTy =
  5962. F->getFunctionType()->getParamType(HLOperandIndex::kMatLoadPtrOpIdx);
  5963. if (PtrTy->getPointerAddressSpace() == DXIL::kTGSMAddrSpace ||
  5964. // TODO: use DeviceAddressSpace for SRV/UAV and CBufferAddressSpace
  5965. // for CBuffer.
  5966. PtrTy->getPointerAddressSpace() == DXIL::kDefaultAddrSpace) {
  5967. // Translate matrix into vector of array for share memory or local
  5968. // variable should be done in HLMatrixLowerPass.
  5969. if (!F->user_empty())
  5970. F->getContext().emitError("Fail to lower matrix load/store.");
  5971. }
  5972. } else if (group == HLOpcodeGroup::HLSubscript) {
  5973. TranslateSubscriptOperation(F, helper, pObjHelper);
  5974. }
  5975. // map to math function or llvm ir
  5976. }
  5977. }
  5978. typedef std::unordered_map<llvm::Instruction *, llvm::Value *> HandleMap;
  5979. static void TranslateHLExtension(Function *F,
  5980. HLSLExtensionsCodegenHelper *helper,
  5981. OP& hlslOp) {
  5982. // Find all calls to the function F.
  5983. // Store the calls in a vector for now to be replaced the loop below.
  5984. // We use a two step "find then replace" to avoid removing uses while
  5985. // iterating.
  5986. SmallVector<CallInst *, 8> CallsToReplace;
  5987. for (User *U : F->users()) {
  5988. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  5989. CallsToReplace.push_back(CI);
  5990. }
  5991. }
  5992. // Get the lowering strategy to use for this intrinsic.
  5993. llvm::StringRef LowerStrategy = GetHLLowerStrategy(F);
  5994. ExtensionLowering lower(LowerStrategy, helper, hlslOp);
  5995. // Replace all calls that were successfully translated.
  5996. for (CallInst *CI : CallsToReplace) {
  5997. Value *Result = lower.Translate(CI);
  5998. if (Result && Result != CI) {
  5999. CI->replaceAllUsesWith(Result);
  6000. CI->eraseFromParent();
  6001. }
  6002. }
  6003. }
  6004. namespace hlsl {
  6005. void TranslateBuiltinOperations(
  6006. HLModule &HLM, HLSLExtensionsCodegenHelper *extCodegenHelper,
  6007. std::unordered_set<LoadInst *> &UpdateCounterSet,
  6008. std::unordered_set<Value *> &NonUniformSet) {
  6009. HLOperationLowerHelper helper(HLM);
  6010. HLObjectOperationLowerHelper objHelper = {HLM, UpdateCounterSet,
  6011. NonUniformSet};
  6012. Module *M = HLM.GetModule();
  6013. // generate dxil operation
  6014. for (iplist<Function>::iterator F : M->getFunctionList()) {
  6015. if (!F->isDeclaration()) {
  6016. continue;
  6017. }
  6018. if (F->user_empty())
  6019. continue;
  6020. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  6021. if (group == HLOpcodeGroup::NotHL) {
  6022. // Nothing to do.
  6023. continue;
  6024. }
  6025. if (group == HLOpcodeGroup::HLExtIntrinsic) {
  6026. TranslateHLExtension(F, extCodegenHelper, helper.hlslOP);
  6027. continue;
  6028. }
  6029. if (group == HLOpcodeGroup::HLCreateHandle) {
  6030. // Will lower in later pass.
  6031. continue;
  6032. }
  6033. TranslateHLBuiltinOperation(F, helper, group, &objHelper);
  6034. }
  6035. }
  6036. }