HLOperationLower.cpp 281 KB

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