HLOperationLower.cpp 269 KB

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