CGHLSLMS.cpp 245 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640
  1. //===----- CGHLSLMS.cpp - Interface to HLSL Runtime ----------------===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // CGHLSLMS.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This provides a class for HLSL code generation. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "CGHLSLRuntime.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGRecordLayout.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/HLSL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/HLSL/DxilOperations.h"
  22. #include "dxc/HLSL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/IRBuilder.h"
  32. #include "llvm/IR/GetElementPtrTypeIterator.h"
  33. #include "llvm/Transforms/Utils/Cloning.h"
  34. #include "llvm/IR/InstIterator.h"
  35. #include <memory>
  36. #include <unordered_map>
  37. #include <unordered_set>
  38. #include "dxc/HLSL/DxilRootSignature.h"
  39. #include "dxc/HLSL/DxilCBuffer.h"
  40. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  41. #include "dxc/Support/WinIncludes.h" // stream support
  42. #include "dxc/dxcapi.h" // stream support
  43. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  44. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  45. using namespace clang;
  46. using namespace CodeGen;
  47. using namespace hlsl;
  48. using namespace llvm;
  49. using std::unique_ptr;
  50. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  51. namespace {
  52. /// Use this class to represent HLSL cbuffer in high-level DXIL.
  53. class HLCBuffer : public DxilCBuffer {
  54. public:
  55. HLCBuffer() = default;
  56. virtual ~HLCBuffer() = default;
  57. void AddConst(std::unique_ptr<DxilResourceBase> &pItem);
  58. std::vector<std::unique_ptr<DxilResourceBase>> &GetConstants();
  59. private:
  60. std::vector<std::unique_ptr<DxilResourceBase>> constants; // constants inside const buffer
  61. };
  62. //------------------------------------------------------------------------------
  63. //
  64. // HLCBuffer methods.
  65. //
  66. void HLCBuffer::AddConst(std::unique_ptr<DxilResourceBase> &pItem) {
  67. pItem->SetID(constants.size());
  68. constants.push_back(std::move(pItem));
  69. }
  70. std::vector<std::unique_ptr<DxilResourceBase>> &HLCBuffer::GetConstants() {
  71. return constants;
  72. }
  73. class CGMSHLSLRuntime : public CGHLSLRuntime {
  74. private:
  75. /// Convenience reference to LLVM Context
  76. llvm::LLVMContext &Context;
  77. /// Convenience reference to the current module
  78. llvm::Module &TheModule;
  79. HLModule *m_pHLModule;
  80. llvm::Type *CBufferType;
  81. uint32_t globalCBIndex;
  82. // TODO: make sure how minprec works
  83. llvm::DataLayout dataLayout;
  84. // decl map to constant id for program
  85. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  86. // Map for resource type to resource metadata value.
  87. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  88. bool m_bDebugInfo;
  89. bool m_bIsLib;
  90. HLCBuffer &GetGlobalCBuffer() {
  91. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  92. }
  93. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  94. uint32_t AddSampler(VarDecl *samplerDecl);
  95. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  96. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  97. DxilResource *hlslRes, const RecordDecl *RD);
  98. uint32_t AddCBuffer(HLSLBufferDecl *D);
  99. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  100. // Save the entryFunc so don't need to find it with original name.
  101. struct EntryFunctionInfo {
  102. clang::SourceLocation SL = clang::SourceLocation();
  103. llvm::Function *Func = nullptr;
  104. };
  105. EntryFunctionInfo Entry;
  106. // Map to save patch constant functions
  107. struct PatchConstantInfo {
  108. clang::SourceLocation SL = clang::SourceLocation();
  109. llvm::Function *Func = nullptr;
  110. std::uint32_t NumOverloads = 0;
  111. };
  112. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  113. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  114. patchConstantFunctionPropsMap;
  115. bool IsPatchConstantFunction(const Function *F);
  116. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  117. HSEntryPatchConstantFuncAttr;
  118. // Map to save entry functions.
  119. StringMap<EntryFunctionInfo> entryFunctionMap;
  120. // Map to save static global init exp.
  121. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  122. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  123. staticConstGlobalInitListMap;
  124. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  125. // List for functions with clip plane.
  126. std::vector<Function *> clipPlaneFuncList;
  127. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  128. DxilRootSignatureVersion rootSigVer;
  129. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  130. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  131. QualType Ty);
  132. // Flatten the val into scalar val and push into elts and eltTys.
  133. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  134. SmallVector<QualType, 4> &eltTys, QualType Ty,
  135. Value *val);
  136. // Push every value on InitListExpr into EltValList and EltTyList.
  137. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  138. SmallVector<Value *, 4> &EltValList,
  139. SmallVector<QualType, 4> &EltTyList);
  140. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  141. SmallVector<Value *, 4> &idxList,
  142. clang::QualType Type, llvm::Type *Ty,
  143. SmallVector<Value *, 4> &GepList,
  144. SmallVector<QualType, 4> &EltTyList);
  145. void LoadFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  146. ArrayRef<QualType> EltTyList,
  147. SmallVector<Value *, 4> &EltList);
  148. void StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  149. ArrayRef<QualType> GepTyList,
  150. ArrayRef<Value *> EltValList,
  151. ArrayRef<QualType> SrcTyList);
  152. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  153. llvm::Value *DestPtr,
  154. SmallVector<Value *, 4> &idxList,
  155. clang::QualType SrcType,
  156. clang::QualType DestType,
  157. llvm::Type *Ty);
  158. void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *SrcVal,
  159. llvm::Value *DestPtr,
  160. SmallVector<Value *, 4> &idxList,
  161. QualType Type, QualType SrcType,
  162. llvm::Type *Ty);
  163. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  164. llvm::Function *Fn);
  165. void CheckParameterAnnotation(SourceLocation SLoc,
  166. const DxilParameterAnnotation &paramInfo,
  167. bool isPatchConstantFunction);
  168. void CheckParameterAnnotation(SourceLocation SLoc,
  169. DxilParamInputQual paramQual,
  170. llvm::StringRef semFullName,
  171. bool isPatchConstantFunction);
  172. void SetEntryFunction();
  173. SourceLocation SetSemantic(const NamedDecl *decl,
  174. DxilParameterAnnotation &paramInfo);
  175. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  176. bool bKeepUndefined);
  177. hlsl::CompType GetCompType(const BuiltinType *BT);
  178. // save intrinsic opcode
  179. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  180. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  181. // Type annotation related.
  182. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  183. const RecordDecl *RD,
  184. DxilTypeSystem &dxilTypeSys);
  185. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  186. unsigned &arrayEltSize);
  187. MDNode *GetOrAddResTypeMD(QualType resTy);
  188. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  189. QualType fieldTy,
  190. bool bDefaultRowMajor);
  191. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  192. public:
  193. CGMSHLSLRuntime(CodeGenModule &CGM);
  194. bool IsHlslObjectType(llvm::Type * Ty) override;
  195. /// Add resouce to the program
  196. void addResource(Decl *D) override;
  197. void SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc);
  198. void SetPatchConstantFunctionWithAttr(
  199. const EntryFunctionInfo &EntryFunc,
  200. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr);
  201. void FinishCodeGen() override;
  202. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  203. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  204. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  205. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  206. const CallExpr *E,
  207. ReturnValueSlot ReturnValue) override;
  208. void EmitHLSLOutParamConversionInit(
  209. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  210. llvm::SmallVector<LValue, 8> &castArgList,
  211. llvm::SmallVector<const Stmt *, 8> &argList,
  212. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  213. override;
  214. void EmitHLSLOutParamConversionCopyBack(
  215. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
  216. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  217. llvm::Type *RetType,
  218. ArrayRef<Value *> paramList) override;
  219. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  220. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  221. Value *Ptr, Value *Idx, QualType Ty) override;
  222. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  223. ArrayRef<Value *> paramList,
  224. QualType Ty) override;
  225. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  226. QualType Ty) override;
  227. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  228. QualType Ty) override;
  229. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  230. llvm::Value *DestPtr,
  231. clang::QualType Ty) override;
  232. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  233. llvm::Value *DestPtr,
  234. clang::QualType Ty) override;
  235. void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *Val,
  236. Value *DestPtr,
  237. QualType Ty,
  238. QualType SrcTy) override;
  239. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  240. QualType DstType) override;
  241. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  242. clang::QualType SrcTy,
  243. llvm::Value *DestPtr,
  244. clang::QualType DestTy) override;
  245. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  246. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  247. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  248. llvm::TerminatorInst *TI,
  249. ArrayRef<const Attr *> Attrs) override;
  250. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  251. /// Get or add constant to the program
  252. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  253. };
  254. }
  255. void clang::CompileRootSignature(
  256. StringRef rootSigStr, DiagnosticsEngine &Diags, SourceLocation SLoc,
  257. hlsl::DxilRootSignatureVersion rootSigVer,
  258. hlsl::RootSignatureHandle *pRootSigHandle) {
  259. std::string OSStr;
  260. llvm::raw_string_ostream OS(OSStr);
  261. hlsl::DxilVersionedRootSignatureDesc *D = nullptr;
  262. if (ParseHLSLRootSignature(rootSigStr.data(), rootSigStr.size(), rootSigVer,
  263. &D, SLoc, Diags)) {
  264. CComPtr<IDxcBlob> pSignature;
  265. CComPtr<IDxcBlobEncoding> pErrors;
  266. hlsl::SerializeRootSignature(D, &pSignature, &pErrors, false);
  267. if (pSignature == nullptr) {
  268. assert(pErrors != nullptr && "else serialize failed with no msg");
  269. ReportHLSLRootSigError(Diags, SLoc, (char *)pErrors->GetBufferPointer(),
  270. pErrors->GetBufferSize());
  271. hlsl::DeleteRootSignature(D);
  272. } else {
  273. pRootSigHandle->Assign(D, pSignature);
  274. }
  275. }
  276. }
  277. //------------------------------------------------------------------------------
  278. //
  279. // CGMSHLSLRuntime methods.
  280. //
  281. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  282. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()), Entry(),
  283. TheModule(CGM.getModule()),
  284. dataLayout(CGM.getLangOpts().UseMinPrecision
  285. ? hlsl::DXIL::kLegacyLayoutString
  286. : hlsl::DXIL::kNewLayoutString),
  287. CBufferType(
  288. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")) {
  289. const hlsl::ShaderModel *SM =
  290. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  291. // Only accept valid, 6.0 shader model.
  292. if (!SM->IsValid() || SM->GetMajor() != 6) {
  293. DiagnosticsEngine &Diags = CGM.getDiags();
  294. unsigned DiagID =
  295. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  296. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  297. return;
  298. }
  299. m_bIsLib = SM->IsLib();
  300. // TODO: add AllResourceBound.
  301. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  302. if (SM->IsSM51Plus()) {
  303. DiagnosticsEngine &Diags = CGM.getDiags();
  304. unsigned DiagID =
  305. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  306. "Gfa option cannot be used in SM_5_1+ unless "
  307. "all_resources_bound flag is specified");
  308. Diags.Report(DiagID);
  309. }
  310. }
  311. // Create HLModule.
  312. const bool skipInit = true;
  313. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  314. // Set Option.
  315. HLOptions opts;
  316. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  317. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  318. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  319. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  320. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  321. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  322. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  323. m_pHLModule->SetHLOptions(opts);
  324. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  325. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  326. // set profile
  327. m_pHLModule->SetShaderModel(SM);
  328. // set entry name
  329. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  330. // set root signature version.
  331. if (CGM.getLangOpts().RootSigMinor == 0) {
  332. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  333. }
  334. else {
  335. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  336. "else CGMSHLSLRuntime Constructor needs to be updated");
  337. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  338. }
  339. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  340. "else CGMSHLSLRuntime Constructor needs to be updated");
  341. // add globalCB
  342. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  343. std::string globalCBName = "$Globals";
  344. CB->SetGlobalSymbol(nullptr);
  345. CB->SetGlobalName(globalCBName);
  346. globalCBIndex = m_pHLModule->GetCBuffers().size();
  347. CB->SetID(globalCBIndex);
  348. CB->SetRangeSize(1);
  349. CB->SetLowerBound(UINT_MAX);
  350. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  351. // set Float Denorm Mode
  352. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  353. }
  354. bool CGMSHLSLRuntime::IsHlslObjectType(llvm::Type *Ty) {
  355. return HLModule::IsHLSLObjectType(Ty);
  356. }
  357. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  358. unsigned opcode) {
  359. m_IntrinsicMap.emplace_back(F,opcode);
  360. }
  361. void CGMSHLSLRuntime::CheckParameterAnnotation(
  362. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  363. bool isPatchConstantFunction) {
  364. if (!paramInfo.HasSemanticString()) {
  365. return;
  366. }
  367. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  368. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  369. if (paramQual == DxilParamInputQual::Inout) {
  370. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  371. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  372. return;
  373. }
  374. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  375. }
  376. void CGMSHLSLRuntime::CheckParameterAnnotation(
  377. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  378. bool isPatchConstantFunction) {
  379. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  380. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  381. paramQual, SM->GetKind(), isPatchConstantFunction);
  382. llvm::StringRef semName;
  383. unsigned semIndex;
  384. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  385. const Semantic *pSemantic =
  386. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  387. if (pSemantic->IsInvalid()) {
  388. DiagnosticsEngine &Diags = CGM.getDiags();
  389. const ShaderModel *shader = m_pHLModule->GetShaderModel();
  390. unsigned DiagID =
  391. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  392. Diags.Report(SLoc, DiagID) << semName << shader->GetKindName() << shader->GetMajor() << shader->GetMinor();
  393. }
  394. }
  395. SourceLocation
  396. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  397. DxilParameterAnnotation &paramInfo) {
  398. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  399. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  400. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  401. paramInfo.SetSemanticString(sd->SemanticName);
  402. return it->Loc;
  403. }
  404. }
  405. return SourceLocation();
  406. }
  407. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  408. if (domain == "isoline")
  409. return DXIL::TessellatorDomain::IsoLine;
  410. if (domain == "tri")
  411. return DXIL::TessellatorDomain::Tri;
  412. if (domain == "quad")
  413. return DXIL::TessellatorDomain::Quad;
  414. return DXIL::TessellatorDomain::Undefined;
  415. }
  416. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  417. if (partition == "integer")
  418. return DXIL::TessellatorPartitioning::Integer;
  419. if (partition == "pow2")
  420. return DXIL::TessellatorPartitioning::Pow2;
  421. if (partition == "fractional_even")
  422. return DXIL::TessellatorPartitioning::FractionalEven;
  423. if (partition == "fractional_odd")
  424. return DXIL::TessellatorPartitioning::FractionalOdd;
  425. return DXIL::TessellatorPartitioning::Undefined;
  426. }
  427. static DXIL::TessellatorOutputPrimitive
  428. StringToTessOutputPrimitive(StringRef primitive) {
  429. if (primitive == "point")
  430. return DXIL::TessellatorOutputPrimitive::Point;
  431. if (primitive == "line")
  432. return DXIL::TessellatorOutputPrimitive::Line;
  433. if (primitive == "triangle_cw")
  434. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  435. if (primitive == "triangle_ccw")
  436. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  437. return DXIL::TessellatorOutputPrimitive::Undefined;
  438. }
  439. static unsigned RoundToAlign(unsigned num, unsigned mod) {
  440. // round num to next highest mod
  441. if (mod != 0)
  442. return mod * ((num + mod - 1) / mod);
  443. return num;
  444. }
  445. // Align cbuffer offset in legacy mode (16 bytes per row).
  446. static unsigned AlignBufferOffsetInLegacy(unsigned offset, unsigned size,
  447. unsigned scalarSizeInBytes,
  448. bool bNeedNewRow) {
  449. if (unsigned remainder = (offset & 0xf)) {
  450. // Start from new row
  451. if (remainder + size > 16 || bNeedNewRow) {
  452. return offset + 16 - remainder;
  453. }
  454. // If not, naturally align data
  455. return RoundToAlign(offset, scalarSizeInBytes);
  456. }
  457. return offset;
  458. }
  459. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size,
  460. QualType Ty, bool bDefaultRowMajor) {
  461. bool needNewAlign = Ty->isArrayType();
  462. if (IsHLSLMatType(Ty)) {
  463. bool bColMajor = !bDefaultRowMajor;
  464. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  465. switch (AT->getAttrKind()) {
  466. case AttributedType::Kind::attr_hlsl_column_major:
  467. bColMajor = true;
  468. break;
  469. case AttributedType::Kind::attr_hlsl_row_major:
  470. bColMajor = false;
  471. break;
  472. default:
  473. // Do nothing
  474. break;
  475. }
  476. }
  477. unsigned row, col;
  478. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  479. needNewAlign |= bColMajor && col > 1;
  480. needNewAlign |= !bColMajor && row > 1;
  481. }
  482. unsigned scalarSizeInBytes = 4;
  483. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  484. if (hlsl::IsHLSLVecMatType(Ty)) {
  485. BT = CGHLSLRuntime::GetHLSLVecMatElementType(Ty)->getAs<clang::BuiltinType>();
  486. }
  487. if (BT) {
  488. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  489. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  490. scalarSizeInBytes = 8;
  491. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  492. BT->getKind() == clang::BuiltinType::Kind::Short ||
  493. BT->getKind() == clang::BuiltinType::Kind::UShort)
  494. scalarSizeInBytes = 2;
  495. }
  496. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes, needNewAlign);
  497. }
  498. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  499. bool bDefaultRowMajor,
  500. CodeGen::CodeGenModule &CGM,
  501. llvm::DataLayout &layout) {
  502. QualType paramTy = Ty.getCanonicalType();
  503. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  504. paramTy = RefType->getPointeeType();
  505. // Get size.
  506. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  507. unsigned size = layout.getTypeAllocSize(Type);
  508. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  509. }
  510. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  511. bool b64Bit) {
  512. bool bColMajor = !defaultRowMajor;
  513. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  514. switch (AT->getAttrKind()) {
  515. case AttributedType::Kind::attr_hlsl_column_major:
  516. bColMajor = true;
  517. break;
  518. case AttributedType::Kind::attr_hlsl_row_major:
  519. bColMajor = false;
  520. break;
  521. default:
  522. // Do nothing
  523. break;
  524. }
  525. }
  526. unsigned row, col;
  527. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  528. unsigned EltSize = b64Bit ? 8 : 4;
  529. // Align to 4 * 4bytes.
  530. unsigned alignment = 4 * 4;
  531. if (bColMajor) {
  532. unsigned rowSize = EltSize * row;
  533. // 3x64bit or 4x64bit align to 32 bytes.
  534. if (rowSize > alignment)
  535. alignment <<= 1;
  536. return alignment * (col - 1) + row * EltSize;
  537. } else {
  538. unsigned rowSize = EltSize * col;
  539. // 3x64bit or 4x64bit align to 32 bytes.
  540. if (rowSize > alignment)
  541. alignment <<= 1;
  542. return alignment * (row - 1) + col * EltSize;
  543. }
  544. }
  545. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  546. bool bUNorm) {
  547. CompType::Kind kind = CompType::Kind::Invalid;
  548. switch (BTy->getKind()) {
  549. case BuiltinType::UInt:
  550. kind = CompType::Kind::U32;
  551. break;
  552. case BuiltinType::UShort:
  553. kind = CompType::Kind::U16;
  554. break;
  555. case BuiltinType::ULongLong:
  556. kind = CompType::Kind::U64;
  557. break;
  558. case BuiltinType::Int:
  559. kind = CompType::Kind::I32;
  560. break;
  561. case BuiltinType::Min12Int:
  562. case BuiltinType::Short:
  563. kind = CompType::Kind::I16;
  564. break;
  565. case BuiltinType::LongLong:
  566. kind = CompType::Kind::I64;
  567. break;
  568. case BuiltinType::Min10Float:
  569. case BuiltinType::Half:
  570. if (bSNorm)
  571. kind = CompType::Kind::SNormF16;
  572. else if (bUNorm)
  573. kind = CompType::Kind::UNormF16;
  574. else
  575. kind = CompType::Kind::F16;
  576. break;
  577. case BuiltinType::Float:
  578. if (bSNorm)
  579. kind = CompType::Kind::SNormF32;
  580. else if (bUNorm)
  581. kind = CompType::Kind::UNormF32;
  582. else
  583. kind = CompType::Kind::F32;
  584. break;
  585. case BuiltinType::Double:
  586. if (bSNorm)
  587. kind = CompType::Kind::SNormF64;
  588. else if (bUNorm)
  589. kind = CompType::Kind::UNormF64;
  590. else
  591. kind = CompType::Kind::F64;
  592. break;
  593. case BuiltinType::Bool:
  594. kind = CompType::Kind::I1;
  595. break;
  596. }
  597. return kind;
  598. }
  599. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  600. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  601. // compare)
  602. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  603. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  604. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  605. .Default(DxilSampler::SamplerKind::Invalid);
  606. }
  607. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy) {
  608. const RecordType *RT = resTy->getAs<RecordType>();
  609. if (!RT)
  610. return nullptr;
  611. RecordDecl *RD = RT->getDecl();
  612. SourceLocation loc = RD->getLocation();
  613. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  614. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  615. auto it = resMetadataMap.find(Ty);
  616. if (it != resMetadataMap.end())
  617. return it->second;
  618. // Save resource type metadata.
  619. switch (resClass) {
  620. case DXIL::ResourceClass::UAV: {
  621. DxilResource UAV;
  622. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  623. SetUAVSRV(loc, resClass, &UAV, RD);
  624. // Set global symbol to save type.
  625. UAV.SetGlobalSymbol(UndefValue::get(Ty));
  626. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  627. resMetadataMap[Ty] = MD;
  628. return MD;
  629. } break;
  630. case DXIL::ResourceClass::SRV: {
  631. DxilResource SRV;
  632. SetUAVSRV(loc, resClass, &SRV, RD);
  633. // Set global symbol to save type.
  634. SRV.SetGlobalSymbol(UndefValue::get(Ty));
  635. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  636. resMetadataMap[Ty] = MD;
  637. return MD;
  638. } break;
  639. case DXIL::ResourceClass::Sampler: {
  640. DxilSampler S;
  641. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  642. S.SetSamplerKind(kind);
  643. // Set global symbol to save type.
  644. S.SetGlobalSymbol(UndefValue::get(Ty));
  645. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  646. resMetadataMap[Ty] = MD;
  647. return MD;
  648. }
  649. default:
  650. // Skip OutputStream for GS.
  651. return nullptr;
  652. }
  653. }
  654. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  655. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  656. bool bDefaultRowMajor) {
  657. QualType Ty = fieldTy;
  658. if (Ty->isReferenceType())
  659. Ty = Ty.getNonReferenceType();
  660. // Get element type.
  661. if (Ty->isArrayType()) {
  662. while (isa<clang::ArrayType>(Ty)) {
  663. const clang::ArrayType *ATy = dyn_cast<clang::ArrayType>(Ty);
  664. Ty = ATy->getElementType();
  665. }
  666. }
  667. QualType EltTy = Ty;
  668. if (hlsl::IsHLSLMatType(Ty)) {
  669. DxilMatrixAnnotation Matrix;
  670. Matrix.Orientation = bDefaultRowMajor ? MatrixOrientation::RowMajor
  671. : MatrixOrientation::ColumnMajor;
  672. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  673. switch (AT->getAttrKind()) {
  674. case AttributedType::Kind::attr_hlsl_column_major:
  675. Matrix.Orientation = MatrixOrientation::ColumnMajor;
  676. break;
  677. case AttributedType::Kind::attr_hlsl_row_major:
  678. Matrix.Orientation = MatrixOrientation::RowMajor;
  679. break;
  680. default:
  681. // Do nothing
  682. break;
  683. }
  684. }
  685. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  686. fieldAnnotation.SetMatrixAnnotation(Matrix);
  687. EltTy = hlsl::GetHLSLMatElementType(Ty);
  688. }
  689. if (hlsl::IsHLSLVecType(Ty))
  690. EltTy = hlsl::GetHLSLVecElementType(Ty);
  691. if (IsHLSLResourceType(Ty)) {
  692. MDNode *MD = GetOrAddResTypeMD(Ty);
  693. fieldAnnotation.SetResourceAttribute(MD);
  694. }
  695. bool bSNorm = false;
  696. bool bUNorm = false;
  697. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  698. switch (AT->getAttrKind()) {
  699. case AttributedType::Kind::attr_hlsl_snorm:
  700. bSNorm = true;
  701. break;
  702. case AttributedType::Kind::attr_hlsl_unorm:
  703. bUNorm = true;
  704. break;
  705. default:
  706. // Do nothing
  707. break;
  708. }
  709. }
  710. if (EltTy->isBuiltinType()) {
  711. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  712. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  713. fieldAnnotation.SetCompType(kind);
  714. } else if (EltTy->isEnumeralType()) {
  715. const EnumType *ETy = EltTy->getAs<EnumType>();
  716. QualType type = ETy->getDecl()->getIntegerType();
  717. if (const BuiltinType *BTy =
  718. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  719. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  720. } else
  721. DXASSERT(!bSNorm && !bUNorm,
  722. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  723. }
  724. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  725. FieldDecl *fieldDecl) {
  726. // Keep undefined for interpMode here.
  727. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  728. fieldDecl->hasAttr<HLSLLinearAttr>(),
  729. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  730. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  731. fieldDecl->hasAttr<HLSLSampleAttr>()};
  732. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  733. fieldAnnotation.SetInterpolationMode(InterpMode);
  734. }
  735. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  736. const RecordDecl *RD,
  737. DxilTypeSystem &dxilTypeSys) {
  738. unsigned fieldIdx = 0;
  739. unsigned offset = 0;
  740. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  741. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  742. if (CXXRD->getNumBases()) {
  743. // Add base as field.
  744. for (const auto &I : CXXRD->bases()) {
  745. const CXXRecordDecl *BaseDecl =
  746. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  747. std::string fieldSemName = "";
  748. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  749. // Align offset.
  750. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  751. dataLayout);
  752. unsigned CBufferOffset = offset;
  753. unsigned arrayEltSize = 0;
  754. // Process field to make sure the size of field is ready.
  755. unsigned size =
  756. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  757. // Update offset.
  758. offset += size;
  759. if (size > 0) {
  760. DxilFieldAnnotation &fieldAnnotation =
  761. annotation->GetFieldAnnotation(fieldIdx++);
  762. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  763. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  764. }
  765. }
  766. }
  767. }
  768. for (auto fieldDecl : RD->fields()) {
  769. std::string fieldSemName = "";
  770. QualType fieldTy = fieldDecl->getType();
  771. // Align offset.
  772. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  773. unsigned CBufferOffset = offset;
  774. bool userOffset = false;
  775. // Try to get info from fieldDecl.
  776. for (const hlsl::UnusualAnnotation *it :
  777. fieldDecl->getUnusualAnnotations()) {
  778. switch (it->getKind()) {
  779. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  780. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  781. fieldSemName = sd->SemanticName;
  782. } break;
  783. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  784. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  785. CBufferOffset = cp->Subcomponent << 2;
  786. CBufferOffset += cp->ComponentOffset;
  787. // Change to byte.
  788. CBufferOffset <<= 2;
  789. userOffset = true;
  790. } break;
  791. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  792. // register assignment only works on global constant.
  793. DiagnosticsEngine &Diags = CGM.getDiags();
  794. unsigned DiagID = Diags.getCustomDiagID(
  795. DiagnosticsEngine::Error,
  796. "location semantics cannot be specified on members.");
  797. Diags.Report(it->Loc, DiagID);
  798. return 0;
  799. } break;
  800. default:
  801. llvm_unreachable("only semantic for input/output");
  802. break;
  803. }
  804. }
  805. unsigned arrayEltSize = 0;
  806. // Process field to make sure the size of field is ready.
  807. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  808. // Update offset.
  809. offset += size;
  810. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  811. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  812. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  813. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  814. fieldAnnotation.SetPrecise();
  815. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  816. fieldAnnotation.SetFieldName(fieldDecl->getName());
  817. if (!fieldSemName.empty())
  818. fieldAnnotation.SetSemanticString(fieldSemName);
  819. }
  820. annotation->SetCBufferSize(offset);
  821. if (offset == 0) {
  822. annotation->MarkEmptyStruct();
  823. }
  824. return offset;
  825. }
  826. static bool IsElementInputOutputType(QualType Ty) {
  827. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  828. }
  829. // Return the size for constant buffer of each decl.
  830. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  831. DxilTypeSystem &dxilTypeSys,
  832. unsigned &arrayEltSize) {
  833. QualType paramTy = Ty.getCanonicalType();
  834. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  835. paramTy = RefType->getPointeeType();
  836. // Get size.
  837. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  838. unsigned size = dataLayout.getTypeAllocSize(Type);
  839. if (IsHLSLMatType(Ty)) {
  840. unsigned col, row;
  841. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Type, col, row);
  842. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  843. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  844. b64Bit);
  845. }
  846. // Skip element types.
  847. if (IsElementInputOutputType(paramTy))
  848. return size;
  849. else if (IsHLSLStreamOutputType(Ty)) {
  850. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  851. arrayEltSize);
  852. } else if (IsHLSLInputPatchType(Ty))
  853. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  854. arrayEltSize);
  855. else if (IsHLSLOutputPatchType(Ty))
  856. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  857. arrayEltSize);
  858. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  859. RecordDecl *RD = RT->getDecl();
  860. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  861. // Skip if already created.
  862. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  863. unsigned structSize = annotation->GetCBufferSize();
  864. return structSize;
  865. }
  866. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  867. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  868. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  869. // For this pointer.
  870. RecordDecl *RD = RT->getDecl();
  871. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  872. // Skip if already created.
  873. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  874. unsigned structSize = annotation->GetCBufferSize();
  875. return structSize;
  876. }
  877. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  878. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  879. } else if (IsHLSLResourceType(Ty)) {
  880. // Save result type info.
  881. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  882. // Resource don't count for cbuffer size.
  883. return 0;
  884. } else {
  885. unsigned arraySize = 0;
  886. QualType arrayElementTy = Ty;
  887. if (Ty->isConstantArrayType()) {
  888. const ConstantArrayType *arrayTy =
  889. CGM.getContext().getAsConstantArrayType(Ty);
  890. DXASSERT(arrayTy != nullptr, "Must array type here");
  891. arraySize = arrayTy->getSize().getLimitedValue();
  892. arrayElementTy = arrayTy->getElementType();
  893. }
  894. else if (Ty->isIncompleteArrayType()) {
  895. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  896. arrayElementTy = arrayTy->getElementType();
  897. } else
  898. DXASSERT(0, "Must array type here");
  899. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  900. // Only set arrayEltSize once.
  901. if (arrayEltSize == 0)
  902. arrayEltSize = elementSize;
  903. // Align to 4 * 4bytes.
  904. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  905. return alignedSize * (arraySize - 1) + elementSize;
  906. }
  907. }
  908. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  909. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  910. // compare)
  911. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  912. return DxilResource::Kind::Texture1D;
  913. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  914. return DxilResource::Kind::Texture2D;
  915. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  916. return DxilResource::Kind::Texture2DMS;
  917. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  918. return DxilResource::Kind::Texture3D;
  919. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  920. return DxilResource::Kind::TextureCube;
  921. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  922. return DxilResource::Kind::Texture1DArray;
  923. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  924. return DxilResource::Kind::Texture2DArray;
  925. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  926. return DxilResource::Kind::Texture2DMSArray;
  927. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  928. return DxilResource::Kind::TextureCubeArray;
  929. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  930. return DxilResource::Kind::RawBuffer;
  931. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  932. return DxilResource::Kind::StructuredBuffer;
  933. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  934. return DxilResource::Kind::StructuredBuffer;
  935. // TODO: this is not efficient.
  936. bool isBuffer = keyword == "Buffer";
  937. isBuffer |= keyword == "RWBuffer";
  938. isBuffer |= keyword == "RasterizerOrderedBuffer";
  939. if (isBuffer)
  940. return DxilResource::Kind::TypedBuffer;
  941. if (keyword == "RaytracingAccelerationStructure")
  942. return DxilResource::Kind::RTAccelerationStructure;
  943. return DxilResource::Kind::Invalid;
  944. }
  945. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  946. // Add hlsl intrinsic attr
  947. unsigned intrinsicOpcode;
  948. StringRef intrinsicGroup;
  949. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  950. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  951. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  952. // Save resource type annotation.
  953. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  954. const CXXRecordDecl *RD = MD->getParent();
  955. // For nested case like sample_slice_type.
  956. if (const CXXRecordDecl *PRD =
  957. dyn_cast<CXXRecordDecl>(RD->getDeclContext())) {
  958. RD = PRD;
  959. }
  960. QualType recordTy = MD->getASTContext().getRecordType(RD);
  961. hlsl::DxilResourceBase::Class resClass = TypeToClass(recordTy);
  962. llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
  963. llvm::FunctionType *FT = F->getFunctionType();
  964. // Save resource type metadata.
  965. switch (resClass) {
  966. case DXIL::ResourceClass::UAV: {
  967. MDNode *MD = GetOrAddResTypeMD(recordTy);
  968. DXASSERT(MD, "else invalid resource type");
  969. resMetadataMap[Ty] = MD;
  970. } break;
  971. case DXIL::ResourceClass::SRV: {
  972. MDNode *Meta = GetOrAddResTypeMD(recordTy);
  973. DXASSERT(Meta, "else invalid resource type");
  974. resMetadataMap[Ty] = Meta;
  975. if (FT->getNumParams() > 1) {
  976. QualType paramTy = MD->getParamDecl(0)->getType();
  977. // Add sampler type.
  978. if (TypeToClass(paramTy) == DXIL::ResourceClass::Sampler) {
  979. llvm::Type *Ty = FT->getParamType(1)->getPointerElementType();
  980. MDNode *MD = GetOrAddResTypeMD(paramTy);
  981. DXASSERT(MD, "else invalid resource type");
  982. resMetadataMap[Ty] = MD;
  983. }
  984. }
  985. } break;
  986. default:
  987. // Skip OutputStream for GS.
  988. break;
  989. }
  990. }
  991. if (intrinsicOpcode == (unsigned)IntrinsicOp::IOP_TraceRay) {
  992. QualType recordTy = FD->getParamDecl(0)->getType();
  993. llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
  994. MDNode *MD = GetOrAddResTypeMD(recordTy);
  995. DXASSERT(MD, "else invalid resource type");
  996. resMetadataMap[Ty] = MD;
  997. }
  998. StringRef lower;
  999. if (hlsl::GetIntrinsicLowering(FD, lower))
  1000. hlsl::SetHLLowerStrategy(F, lower);
  1001. // Don't need to add FunctionQual for intrinsic function.
  1002. return;
  1003. }
  1004. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  1005. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  1006. }
  1007. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  1008. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  1009. }
  1010. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1011. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1012. }
  1013. // Set entry function
  1014. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1015. bool isEntry = FD->getNameAsString() == entryName;
  1016. if (isEntry) {
  1017. Entry.Func = F;
  1018. Entry.SL = FD->getLocation();
  1019. }
  1020. DiagnosticsEngine &Diags = CGM.getDiags();
  1021. std::unique_ptr<DxilFunctionProps> funcProps =
  1022. llvm::make_unique<DxilFunctionProps>();
  1023. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1024. bool isCS = false;
  1025. bool isGS = false;
  1026. bool isHS = false;
  1027. bool isDS = false;
  1028. bool isVS = false;
  1029. bool isPS = false;
  1030. bool isRay = false;
  1031. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1032. // Stage is already validate in HandleDeclAttributeForHLSL.
  1033. // Here just check first letter (or two).
  1034. switch (Attr->getStage()[0]) {
  1035. case 'c':
  1036. switch (Attr->getStage()[1]) {
  1037. case 'o':
  1038. isCS = true;
  1039. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1040. break;
  1041. case 'l':
  1042. isRay = true;
  1043. funcProps->shaderKind = DXIL::ShaderKind::ClosestHit;
  1044. break;
  1045. case 'a':
  1046. isRay = true;
  1047. funcProps->shaderKind = DXIL::ShaderKind::Callable;
  1048. break;
  1049. default:
  1050. break;
  1051. }
  1052. break;
  1053. case 'v':
  1054. isVS = true;
  1055. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1056. break;
  1057. case 'h':
  1058. isHS = true;
  1059. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1060. break;
  1061. case 'd':
  1062. isDS = true;
  1063. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1064. break;
  1065. case 'g':
  1066. isGS = true;
  1067. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1068. break;
  1069. case 'p':
  1070. isPS = true;
  1071. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1072. break;
  1073. case 'r':
  1074. isRay = true;
  1075. funcProps->shaderKind = DXIL::ShaderKind::RayGeneration;
  1076. break;
  1077. case 'i':
  1078. isRay = true;
  1079. funcProps->shaderKind = DXIL::ShaderKind::Intersection;
  1080. break;
  1081. case 'a':
  1082. isRay = true;
  1083. funcProps->shaderKind = DXIL::ShaderKind::AnyHit;
  1084. break;
  1085. case 'm':
  1086. isRay = true;
  1087. funcProps->shaderKind = DXIL::ShaderKind::Miss;
  1088. break;
  1089. default:
  1090. break;
  1091. }
  1092. if (funcProps->shaderKind == DXIL::ShaderKind::Invalid) {
  1093. unsigned DiagID = Diags.getCustomDiagID(
  1094. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1095. Diags.Report(Attr->getLocation(), DiagID);
  1096. }
  1097. if (isEntry && isRay) {
  1098. unsigned DiagID = Diags.getCustomDiagID(
  1099. DiagnosticsEngine::Error, "Ray function cannot be used as a global entry point");
  1100. Diags.Report(Attr->getLocation(), DiagID);
  1101. }
  1102. }
  1103. // Save patch constant function to patchConstantFunctionMap.
  1104. bool isPatchConstantFunction = false;
  1105. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1106. isPatchConstantFunction = true;
  1107. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1108. PCI.SL = FD->getLocation();
  1109. PCI.Func = F;
  1110. ++PCI.NumOverloads;
  1111. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1112. QualType Ty = parmDecl->getType();
  1113. if (IsHLSLOutputPatchType(Ty)) {
  1114. funcProps->ShaderProps.HS.outputControlPoints =
  1115. GetHLSLOutputPatchCount(parmDecl->getType());
  1116. } else if (IsHLSLInputPatchType(Ty)) {
  1117. funcProps->ShaderProps.HS.inputControlPoints =
  1118. GetHLSLInputPatchCount(parmDecl->getType());
  1119. }
  1120. }
  1121. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1122. }
  1123. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1124. if (isEntry) {
  1125. funcProps->shaderKind = SM->GetKind();
  1126. }
  1127. // Geometry shader.
  1128. if (const HLSLMaxVertexCountAttr *Attr =
  1129. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1130. isGS = true;
  1131. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1132. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1133. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1134. if (isEntry && !SM->IsGS()) {
  1135. unsigned DiagID =
  1136. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1137. "attribute maxvertexcount only valid for GS.");
  1138. Diags.Report(Attr->getLocation(), DiagID);
  1139. return;
  1140. }
  1141. }
  1142. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1143. unsigned instanceCount = Attr->getCount();
  1144. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1145. if (isEntry && !SM->IsGS()) {
  1146. unsigned DiagID =
  1147. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1148. "attribute maxvertexcount only valid for GS.");
  1149. Diags.Report(Attr->getLocation(), DiagID);
  1150. return;
  1151. }
  1152. } else {
  1153. // Set default instance count.
  1154. if (isGS)
  1155. funcProps->ShaderProps.GS.instanceCount = 1;
  1156. }
  1157. // Computer shader.
  1158. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1159. isCS = true;
  1160. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1161. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1162. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1163. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1164. if (isEntry && !SM->IsCS()) {
  1165. unsigned DiagID = Diags.getCustomDiagID(
  1166. DiagnosticsEngine::Error, "attribute numthreads only valid for CS.");
  1167. Diags.Report(Attr->getLocation(), DiagID);
  1168. return;
  1169. }
  1170. }
  1171. // Hull shader.
  1172. if (const HLSLPatchConstantFuncAttr *Attr =
  1173. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1174. if (isEntry && !SM->IsHS()) {
  1175. unsigned DiagID = Diags.getCustomDiagID(
  1176. DiagnosticsEngine::Error,
  1177. "attribute patchconstantfunc only valid for HS.");
  1178. Diags.Report(Attr->getLocation(), DiagID);
  1179. return;
  1180. }
  1181. isHS = true;
  1182. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1183. HSEntryPatchConstantFuncAttr[F] = Attr;
  1184. } else {
  1185. // TODO: This is a duplicate check. We also have this check in
  1186. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1187. if (isEntry && SM->IsHS()) {
  1188. unsigned DiagID = Diags.getCustomDiagID(
  1189. DiagnosticsEngine::Error,
  1190. "HS entry point must have the patchconstantfunc attribute");
  1191. Diags.Report(FD->getLocation(), DiagID);
  1192. return;
  1193. }
  1194. }
  1195. if (const HLSLOutputControlPointsAttr *Attr =
  1196. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1197. if (isHS) {
  1198. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1199. } else if (isEntry && !SM->IsHS()) {
  1200. unsigned DiagID = Diags.getCustomDiagID(
  1201. DiagnosticsEngine::Error,
  1202. "attribute outputcontrolpoints only valid for HS.");
  1203. Diags.Report(Attr->getLocation(), DiagID);
  1204. return;
  1205. }
  1206. }
  1207. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1208. if (isHS) {
  1209. DXIL::TessellatorPartitioning partition =
  1210. StringToPartitioning(Attr->getScheme());
  1211. funcProps->ShaderProps.HS.partition = partition;
  1212. } else if (isEntry && !SM->IsHS()) {
  1213. unsigned DiagID =
  1214. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1215. "attribute partitioning only valid for HS.");
  1216. Diags.Report(Attr->getLocation(), DiagID);
  1217. }
  1218. }
  1219. if (const HLSLOutputTopologyAttr *Attr =
  1220. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1221. if (isHS) {
  1222. DXIL::TessellatorOutputPrimitive primitive =
  1223. StringToTessOutputPrimitive(Attr->getTopology());
  1224. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1225. } else if (isEntry && !SM->IsHS()) {
  1226. unsigned DiagID =
  1227. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1228. "attribute outputtopology only valid for HS.");
  1229. Diags.Report(Attr->getLocation(), DiagID);
  1230. }
  1231. }
  1232. if (isHS) {
  1233. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1234. funcProps->ShaderProps.HS.inputControlPoints = DXIL::kHSDefaultInputControlPointCount;
  1235. }
  1236. if (const HLSLMaxTessFactorAttr *Attr =
  1237. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1238. if (isHS) {
  1239. // TODO: change getFactor to return float.
  1240. llvm::APInt intV(32, Attr->getFactor());
  1241. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1242. } else if (isEntry && !SM->IsHS()) {
  1243. unsigned DiagID =
  1244. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1245. "attribute maxtessfactor only valid for HS.");
  1246. Diags.Report(Attr->getLocation(), DiagID);
  1247. return;
  1248. }
  1249. }
  1250. // Hull or domain shader.
  1251. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1252. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1253. unsigned DiagID =
  1254. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1255. "attribute domain only valid for HS or DS.");
  1256. Diags.Report(Attr->getLocation(), DiagID);
  1257. return;
  1258. }
  1259. isDS = !isHS;
  1260. if (isDS)
  1261. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1262. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1263. if (isHS)
  1264. funcProps->ShaderProps.HS.domain = domain;
  1265. else
  1266. funcProps->ShaderProps.DS.domain = domain;
  1267. }
  1268. // Vertex shader.
  1269. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1270. if (isEntry && !SM->IsVS()) {
  1271. unsigned DiagID = Diags.getCustomDiagID(
  1272. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1273. Diags.Report(Attr->getLocation(), DiagID);
  1274. return;
  1275. }
  1276. isVS = true;
  1277. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1278. // available. Only set shader kind here.
  1279. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1280. }
  1281. // Pixel shader.
  1282. if (const HLSLEarlyDepthStencilAttr *Attr =
  1283. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1284. if (isEntry && !SM->IsPS()) {
  1285. unsigned DiagID = Diags.getCustomDiagID(
  1286. DiagnosticsEngine::Error,
  1287. "attribute earlydepthstencil only valid for PS.");
  1288. Diags.Report(Attr->getLocation(), DiagID);
  1289. return;
  1290. }
  1291. isPS = true;
  1292. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1293. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1294. }
  1295. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS + isRay;
  1296. // TODO: check this in front-end and report error.
  1297. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1298. if (isEntry) {
  1299. switch (funcProps->shaderKind) {
  1300. case ShaderModel::Kind::Compute:
  1301. case ShaderModel::Kind::Hull:
  1302. case ShaderModel::Kind::Domain:
  1303. case ShaderModel::Kind::Geometry:
  1304. case ShaderModel::Kind::Vertex:
  1305. case ShaderModel::Kind::Pixel:
  1306. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1307. "attribute profile not match entry function profile");
  1308. break;
  1309. }
  1310. }
  1311. DxilFunctionAnnotation *FuncAnnotation =
  1312. m_pHLModule->AddFunctionAnnotation(F);
  1313. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1314. // Param Info
  1315. unsigned streamIndex = 0;
  1316. unsigned inputPatchCount = 0;
  1317. unsigned outputPatchCount = 0;
  1318. unsigned ArgNo = 0;
  1319. unsigned ParmIdx = 0;
  1320. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1321. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1322. DxilParameterAnnotation &paramAnnotation =
  1323. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1324. // Construct annoation for this pointer.
  1325. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1326. bDefaultRowMajor);
  1327. }
  1328. // Ret Info
  1329. QualType retTy = FD->getReturnType();
  1330. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1331. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1332. // SRet.
  1333. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1334. } else {
  1335. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1336. }
  1337. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1338. // keep Undefined here, we cannot decide for struct
  1339. retTyAnnotation.SetInterpolationMode(
  1340. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1341. .GetKind());
  1342. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1343. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1344. if (isEntry) {
  1345. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1346. /*isPatchConstantFunction*/ false);
  1347. }
  1348. if (isRay && !retTy->isVoidType()) {
  1349. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1350. DiagnosticsEngine::Error, "return type for ray tracing shaders must be void"));
  1351. }
  1352. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1353. if (FD->hasAttr<HLSLPreciseAttr>())
  1354. retTyAnnotation.SetPrecise();
  1355. if (isRay) {
  1356. funcProps->ShaderProps.Ray.payloadSizeInBytes = 0;
  1357. funcProps->ShaderProps.Ray.attributeSizeInBytes = 0;
  1358. }
  1359. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx) {
  1360. DxilParameterAnnotation &paramAnnotation =
  1361. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1362. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1363. ConstructFieldAttributedAnnotation(paramAnnotation, parmDecl->getType(),
  1364. bDefaultRowMajor);
  1365. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1366. paramAnnotation.SetPrecise();
  1367. // keep Undefined here, we cannot decide for struct
  1368. InterpolationMode paramIM =
  1369. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1370. paramAnnotation.SetInterpolationMode(paramIM);
  1371. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1372. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1373. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1374. dxilInputQ = DxilParamInputQual::Inout;
  1375. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1376. dxilInputQ = DxilParamInputQual::Out;
  1377. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1378. dxilInputQ = DxilParamInputQual::Inout;
  1379. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1380. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1381. outputPatchCount++;
  1382. if (dxilInputQ != DxilParamInputQual::In) {
  1383. unsigned DiagID = Diags.getCustomDiagID(
  1384. DiagnosticsEngine::Error,
  1385. "OutputPatch should not be out/inout parameter");
  1386. Diags.Report(parmDecl->getLocation(), DiagID);
  1387. continue;
  1388. }
  1389. dxilInputQ = DxilParamInputQual::OutputPatch;
  1390. if (isDS)
  1391. funcProps->ShaderProps.DS.inputControlPoints =
  1392. GetHLSLOutputPatchCount(parmDecl->getType());
  1393. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1394. inputPatchCount++;
  1395. if (dxilInputQ != DxilParamInputQual::In) {
  1396. unsigned DiagID = Diags.getCustomDiagID(
  1397. DiagnosticsEngine::Error,
  1398. "InputPatch should not be out/inout parameter");
  1399. Diags.Report(parmDecl->getLocation(), DiagID);
  1400. continue;
  1401. }
  1402. dxilInputQ = DxilParamInputQual::InputPatch;
  1403. if (isHS) {
  1404. funcProps->ShaderProps.HS.inputControlPoints =
  1405. GetHLSLInputPatchCount(parmDecl->getType());
  1406. } else if (isGS) {
  1407. inputPrimitive = (DXIL::InputPrimitive)(
  1408. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1409. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1410. }
  1411. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1412. // TODO: validation this at ASTContext::getFunctionType in
  1413. // AST/ASTContext.cpp
  1414. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1415. "stream output parameter must be inout");
  1416. switch (streamIndex) {
  1417. case 0:
  1418. dxilInputQ = DxilParamInputQual::OutStream0;
  1419. break;
  1420. case 1:
  1421. dxilInputQ = DxilParamInputQual::OutStream1;
  1422. break;
  1423. case 2:
  1424. dxilInputQ = DxilParamInputQual::OutStream2;
  1425. break;
  1426. case 3:
  1427. default:
  1428. // TODO: validation this at ASTContext::getFunctionType in
  1429. // AST/ASTContext.cpp
  1430. DXASSERT(streamIndex == 3, "stream number out of bound");
  1431. dxilInputQ = DxilParamInputQual::OutStream3;
  1432. break;
  1433. }
  1434. DXIL::PrimitiveTopology &streamTopology =
  1435. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1436. if (IsHLSLPointStreamType(parmDecl->getType()))
  1437. streamTopology = DXIL::PrimitiveTopology::PointList;
  1438. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1439. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1440. else {
  1441. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1442. "invalid StreamType");
  1443. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1444. }
  1445. if (streamIndex > 0) {
  1446. bool bAllPoint =
  1447. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1448. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1449. DXIL::PrimitiveTopology::PointList;
  1450. if (!bAllPoint) {
  1451. unsigned DiagID = Diags.getCustomDiagID(
  1452. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1453. "used they must be pointlists.");
  1454. Diags.Report(FD->getLocation(), DiagID);
  1455. }
  1456. }
  1457. streamIndex++;
  1458. }
  1459. unsigned GsInputArrayDim = 0;
  1460. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1461. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1462. GsInputArrayDim = 3;
  1463. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1464. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1465. GsInputArrayDim = 6;
  1466. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1467. inputPrimitive = DXIL::InputPrimitive::Point;
  1468. GsInputArrayDim = 1;
  1469. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1470. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1471. GsInputArrayDim = 4;
  1472. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1473. inputPrimitive = DXIL::InputPrimitive::Line;
  1474. GsInputArrayDim = 2;
  1475. }
  1476. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1477. // Set to InputPrimitive for GS.
  1478. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1479. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1480. DXIL::InputPrimitive::Undefined) {
  1481. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1482. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1483. unsigned DiagID = Diags.getCustomDiagID(
  1484. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1485. "specifier of previous input parameters");
  1486. Diags.Report(parmDecl->getLocation(), DiagID);
  1487. }
  1488. }
  1489. if (GsInputArrayDim != 0) {
  1490. QualType Ty = parmDecl->getType();
  1491. if (!Ty->isConstantArrayType()) {
  1492. unsigned DiagID = Diags.getCustomDiagID(
  1493. DiagnosticsEngine::Error,
  1494. "input types for geometry shader must be constant size arrays");
  1495. Diags.Report(parmDecl->getLocation(), DiagID);
  1496. } else {
  1497. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1498. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1499. StringRef primtiveNames[] = {
  1500. "invalid", // 0
  1501. "point", // 1
  1502. "line", // 2
  1503. "triangle", // 3
  1504. "lineadj", // 4
  1505. "invalid", // 5
  1506. "triangleadj", // 6
  1507. };
  1508. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1509. "Invalid array dim");
  1510. unsigned DiagID = Diags.getCustomDiagID(
  1511. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1512. Diags.Report(parmDecl->getLocation(), DiagID)
  1513. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1514. }
  1515. }
  1516. }
  1517. // Validate Ray Tracing function parameter (some validation may be pushed into front end)
  1518. if (isRay) {
  1519. switch (funcProps->shaderKind) {
  1520. case DXIL::ShaderKind::RayGeneration:
  1521. case DXIL::ShaderKind::Intersection:
  1522. // RayGeneration and Intersection shaders are not allowed to have any input parameters
  1523. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1524. DiagnosticsEngine::Error, "parameters are not allowed for %0 shader"))
  1525. << (funcProps->shaderKind == DXIL::ShaderKind::RayGeneration ?
  1526. "raygeneration" : "intersection");
  1527. break;
  1528. case DXIL::ShaderKind::AnyHit:
  1529. case DXIL::ShaderKind::ClosestHit:
  1530. if (0 == ArgNo && dxilInputQ != DxilParamInputQual::Inout) {
  1531. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1532. DiagnosticsEngine::Error,
  1533. "ray payload parameter must be inout"));
  1534. } else if (1 == ArgNo && dxilInputQ != DxilParamInputQual::In) {
  1535. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1536. DiagnosticsEngine::Error,
  1537. "intersection attributes parameter must be in"));
  1538. } else if (ArgNo > 1) {
  1539. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1540. DiagnosticsEngine::Error,
  1541. "too many parameters, expected payload and attributes parameters only."));
  1542. }
  1543. if (ArgNo < 2) {
  1544. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1545. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1546. DiagnosticsEngine::Error,
  1547. "payload and attribute structures must be user defined types with only numeric contents."));
  1548. } else {
  1549. DataLayout DL(&this->TheModule);
  1550. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1551. if (0 == ArgNo)
  1552. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1553. else
  1554. funcProps->ShaderProps.Ray.attributeSizeInBytes = size;
  1555. }
  1556. }
  1557. break;
  1558. case DXIL::ShaderKind::Miss:
  1559. if (ArgNo > 0) {
  1560. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1561. DiagnosticsEngine::Error,
  1562. "only one parameter (ray payload) allowed for miss shader"));
  1563. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1564. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1565. DiagnosticsEngine::Error,
  1566. "ray payload parameter must be declared inout"));
  1567. }
  1568. if (ArgNo < 1) {
  1569. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1570. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1571. DiagnosticsEngine::Error,
  1572. "ray payload parameter must be a user defined type with only numeric contents."));
  1573. } else {
  1574. DataLayout DL(&this->TheModule);
  1575. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1576. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1577. }
  1578. }
  1579. break;
  1580. case DXIL::ShaderKind::Callable:
  1581. if (ArgNo > 0) {
  1582. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1583. DiagnosticsEngine::Error,
  1584. "only one parameter allowed for callable shader"));
  1585. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1586. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1587. DiagnosticsEngine::Error,
  1588. "callable parameter must be declared inout"));
  1589. }
  1590. if (ArgNo < 1) {
  1591. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1592. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1593. DiagnosticsEngine::Error,
  1594. "callable parameter must be a user defined type with only numeric contents."));
  1595. } else {
  1596. DataLayout DL(&this->TheModule);
  1597. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1598. funcProps->ShaderProps.Ray.paramSizeInBytes = size;
  1599. }
  1600. }
  1601. break;
  1602. }
  1603. }
  1604. paramAnnotation.SetParamInputQual(dxilInputQ);
  1605. if (isEntry) {
  1606. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  1607. /*isPatchConstantFunction*/ false);
  1608. }
  1609. }
  1610. if (inputPatchCount > 1) {
  1611. unsigned DiagID = Diags.getCustomDiagID(
  1612. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  1613. Diags.Report(FD->getLocation(), DiagID);
  1614. }
  1615. if (outputPatchCount > 1) {
  1616. unsigned DiagID = Diags.getCustomDiagID(
  1617. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  1618. Diags.Report(FD->getLocation(), DiagID);
  1619. }
  1620. // If Shader is a ray shader that requires parameters, make sure size is non-zero
  1621. if (isRay) {
  1622. bool bNeedsAttributes = false;
  1623. bool bNeedsPayload = false;
  1624. switch (funcProps->shaderKind) {
  1625. case DXIL::ShaderKind::AnyHit:
  1626. case DXIL::ShaderKind::ClosestHit:
  1627. bNeedsAttributes = true;
  1628. case DXIL::ShaderKind::Miss:
  1629. bNeedsPayload = true;
  1630. case DXIL::ShaderKind::Callable:
  1631. if (0 == funcProps->ShaderProps.Ray.payloadSizeInBytes) {
  1632. unsigned DiagID = bNeedsPayload ?
  1633. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1634. "shader must include inout payload structure parameter.") :
  1635. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1636. "shader must include inout parameter structure.");
  1637. Diags.Report(FD->getLocation(), DiagID);
  1638. }
  1639. }
  1640. if (bNeedsAttributes &&
  1641. 0 == funcProps->ShaderProps.Ray.attributeSizeInBytes) {
  1642. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1643. DiagnosticsEngine::Error,
  1644. "shader must include attributes structure parameter."));
  1645. }
  1646. }
  1647. // Type annotation for parameters and return type.
  1648. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1649. unsigned arrayEltSize = 0;
  1650. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  1651. // Type annotation for this pointer.
  1652. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  1653. const CXXRecordDecl *RD = MFD->getParent();
  1654. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  1655. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1656. }
  1657. for (const ValueDecl *param : FD->params()) {
  1658. QualType Ty = param->getType();
  1659. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1660. }
  1661. // Only add functionProps when exist.
  1662. if (profileAttributes || isEntry)
  1663. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  1664. if (isPatchConstantFunction)
  1665. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  1666. // Save F to entry map.
  1667. if (profileAttributes) {
  1668. if (entryFunctionMap.count(FD->getName())) {
  1669. DiagnosticsEngine &Diags = CGM.getDiags();
  1670. unsigned DiagID = Diags.getCustomDiagID(
  1671. DiagnosticsEngine::Error,
  1672. "redefinition of %0");
  1673. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  1674. }
  1675. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  1676. Entry.SL = FD->getLocation();
  1677. Entry.Func= F;
  1678. }
  1679. // Add target-dependent experimental function attributes
  1680. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  1681. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  1682. }
  1683. }
  1684. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  1685. // Support clip plane need debug info which not available when create function attribute.
  1686. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1687. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  1688. // Initialize to null.
  1689. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  1690. // Create global for each clip plane, and use the clip plane val as init val.
  1691. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  1692. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  1693. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  1694. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  1695. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  1696. if (m_bDebugInfo) {
  1697. CodeGenFunction CGF(CGM);
  1698. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1699. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  1700. }
  1701. } else {
  1702. // Must be a MemberExpr.
  1703. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  1704. CodeGenFunction CGF(CGM);
  1705. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  1706. Value *addr = LV.getAddress();
  1707. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  1708. if (m_bDebugInfo) {
  1709. CodeGenFunction CGF(CGM);
  1710. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1711. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  1712. }
  1713. }
  1714. };
  1715. if (Expr *clipPlane = Attr->getClipPlane1())
  1716. AddClipPlane(clipPlane, 0);
  1717. if (Expr *clipPlane = Attr->getClipPlane2())
  1718. AddClipPlane(clipPlane, 1);
  1719. if (Expr *clipPlane = Attr->getClipPlane3())
  1720. AddClipPlane(clipPlane, 2);
  1721. if (Expr *clipPlane = Attr->getClipPlane4())
  1722. AddClipPlane(clipPlane, 3);
  1723. if (Expr *clipPlane = Attr->getClipPlane5())
  1724. AddClipPlane(clipPlane, 4);
  1725. if (Expr *clipPlane = Attr->getClipPlane6())
  1726. AddClipPlane(clipPlane, 5);
  1727. clipPlaneFuncList.emplace_back(F);
  1728. }
  1729. }
  1730. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  1731. llvm::TerminatorInst *TI,
  1732. ArrayRef<const Attr *> Attrs) {
  1733. // Build hints.
  1734. bool bNoBranchFlatten = true;
  1735. bool bBranch = false;
  1736. bool bFlatten = false;
  1737. std::vector<DXIL::ControlFlowHint> hints;
  1738. for (const auto *Attr : Attrs) {
  1739. if (isa<HLSLBranchAttr>(Attr)) {
  1740. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1741. bNoBranchFlatten = false;
  1742. bBranch = true;
  1743. }
  1744. else if (isa<HLSLFlattenAttr>(Attr)) {
  1745. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1746. bNoBranchFlatten = false;
  1747. bFlatten = true;
  1748. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  1749. if (isa<SwitchStmt>(&S)) {
  1750. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  1751. }
  1752. }
  1753. // Ignore fastopt, allow_uav_condition and call for now.
  1754. }
  1755. if (bNoBranchFlatten) {
  1756. // CHECK control flow option.
  1757. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  1758. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1759. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  1760. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1761. }
  1762. if (bFlatten && bBranch) {
  1763. DiagnosticsEngine &Diags = CGM.getDiags();
  1764. unsigned DiagID = Diags.getCustomDiagID(
  1765. DiagnosticsEngine::Error,
  1766. "can't use branch and flatten attributes together");
  1767. Diags.Report(S.getLocStart(), DiagID);
  1768. }
  1769. if (hints.size()) {
  1770. // Add meta data to the instruction.
  1771. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  1772. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  1773. }
  1774. }
  1775. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) {
  1776. if (D.hasAttr<HLSLPreciseAttr>()) {
  1777. AllocaInst *AI = cast<AllocaInst>(V);
  1778. HLModule::MarkPreciseAttributeWithMetadata(AI);
  1779. }
  1780. // Add type annotation for local variable.
  1781. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  1782. unsigned arrayEltSize = 0;
  1783. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  1784. }
  1785. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  1786. CompType compType,
  1787. bool bKeepUndefined) {
  1788. InterpolationMode Interp(
  1789. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  1790. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  1791. decl->hasAttr<HLSLSampleAttr>());
  1792. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  1793. if (Interp.IsUndefined() && !bKeepUndefined) {
  1794. // Type-based default: linear for floats, constant for others.
  1795. if (compType.IsFloatTy())
  1796. Interp = InterpolationMode::Kind::Linear;
  1797. else
  1798. Interp = InterpolationMode::Kind::Constant;
  1799. }
  1800. return Interp;
  1801. }
  1802. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  1803. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  1804. switch (BT->getKind()) {
  1805. case BuiltinType::Bool:
  1806. ElementType = hlsl::CompType::getI1();
  1807. break;
  1808. case BuiltinType::Double:
  1809. ElementType = hlsl::CompType::getF64();
  1810. break;
  1811. case BuiltinType::Float:
  1812. ElementType = hlsl::CompType::getF32();
  1813. break;
  1814. case BuiltinType::Min10Float:
  1815. case BuiltinType::Half:
  1816. ElementType = hlsl::CompType::getF16();
  1817. break;
  1818. case BuiltinType::Int:
  1819. ElementType = hlsl::CompType::getI32();
  1820. break;
  1821. case BuiltinType::LongLong:
  1822. ElementType = hlsl::CompType::getI64();
  1823. break;
  1824. case BuiltinType::Min12Int:
  1825. case BuiltinType::Short:
  1826. ElementType = hlsl::CompType::getI16();
  1827. break;
  1828. case BuiltinType::UInt:
  1829. ElementType = hlsl::CompType::getU32();
  1830. break;
  1831. case BuiltinType::ULongLong:
  1832. ElementType = hlsl::CompType::getU64();
  1833. break;
  1834. case BuiltinType::UShort:
  1835. ElementType = hlsl::CompType::getU16();
  1836. break;
  1837. default:
  1838. llvm_unreachable("unsupported type");
  1839. break;
  1840. }
  1841. return ElementType;
  1842. }
  1843. /// Add resouce to the program
  1844. void CGMSHLSLRuntime::addResource(Decl *D) {
  1845. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  1846. GetOrCreateCBuffer(BD);
  1847. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1848. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  1849. // skip decl has init which is resource.
  1850. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  1851. return;
  1852. // skip static global.
  1853. if (!VD->hasExternalFormalLinkage()) {
  1854. if (VD->hasInit() && VD->getType().isConstQualified()) {
  1855. Expr* InitExp = VD->getInit();
  1856. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1857. // Only save const static global of struct type.
  1858. if (GV->getType()->getElementType()->isStructTy()) {
  1859. staticConstGlobalInitMap[InitExp] = GV;
  1860. }
  1861. }
  1862. return;
  1863. }
  1864. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  1865. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1866. m_pHLModule->AddGroupSharedVariable(GV);
  1867. return;
  1868. }
  1869. switch (resClass) {
  1870. case hlsl::DxilResourceBase::Class::Sampler:
  1871. AddSampler(VD);
  1872. break;
  1873. case hlsl::DxilResourceBase::Class::UAV:
  1874. case hlsl::DxilResourceBase::Class::SRV:
  1875. AddUAVSRV(VD, resClass);
  1876. break;
  1877. case hlsl::DxilResourceBase::Class::Invalid: {
  1878. // normal global constant, add to global CB
  1879. HLCBuffer &globalCB = GetGlobalCBuffer();
  1880. AddConstant(VD, globalCB);
  1881. break;
  1882. }
  1883. case DXIL::ResourceClass::CBuffer:
  1884. DXASSERT(0, "cbuffer should not be here");
  1885. break;
  1886. }
  1887. }
  1888. }
  1889. // TODO: collect such helper utility functions in one place.
  1890. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  1891. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  1892. // compare)
  1893. if (keyword == "SamplerState")
  1894. return DxilResourceBase::Class::Sampler;
  1895. if (keyword == "SamplerComparisonState")
  1896. return DxilResourceBase::Class::Sampler;
  1897. if (keyword == "ConstantBuffer")
  1898. return DxilResourceBase::Class::CBuffer;
  1899. if (keyword == "TextureBuffer")
  1900. return DxilResourceBase::Class::SRV;
  1901. bool isSRV = keyword == "Buffer";
  1902. isSRV |= keyword == "ByteAddressBuffer";
  1903. isSRV |= keyword == "RaytracingAccelerationStructure";
  1904. isSRV |= keyword == "StructuredBuffer";
  1905. isSRV |= keyword == "Texture1D";
  1906. isSRV |= keyword == "Texture1DArray";
  1907. isSRV |= keyword == "Texture2D";
  1908. isSRV |= keyword == "Texture2DArray";
  1909. isSRV |= keyword == "Texture3D";
  1910. isSRV |= keyword == "TextureCube";
  1911. isSRV |= keyword == "TextureCubeArray";
  1912. isSRV |= keyword == "Texture2DMS";
  1913. isSRV |= keyword == "Texture2DMSArray";
  1914. if (isSRV)
  1915. return DxilResourceBase::Class::SRV;
  1916. bool isUAV = keyword == "RWBuffer";
  1917. isUAV |= keyword == "RWByteAddressBuffer";
  1918. isUAV |= keyword == "RWStructuredBuffer";
  1919. isUAV |= keyword == "RWTexture1D";
  1920. isUAV |= keyword == "RWTexture1DArray";
  1921. isUAV |= keyword == "RWTexture2D";
  1922. isUAV |= keyword == "RWTexture2DArray";
  1923. isUAV |= keyword == "RWTexture3D";
  1924. isUAV |= keyword == "RWTextureCube";
  1925. isUAV |= keyword == "RWTextureCubeArray";
  1926. isUAV |= keyword == "RWTexture2DMS";
  1927. isUAV |= keyword == "RWTexture2DMSArray";
  1928. isUAV |= keyword == "AppendStructuredBuffer";
  1929. isUAV |= keyword == "ConsumeStructuredBuffer";
  1930. isUAV |= keyword == "RasterizerOrderedBuffer";
  1931. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  1932. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  1933. isUAV |= keyword == "RasterizerOrderedTexture1D";
  1934. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  1935. isUAV |= keyword == "RasterizerOrderedTexture2D";
  1936. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  1937. isUAV |= keyword == "RasterizerOrderedTexture3D";
  1938. if (isUAV)
  1939. return DxilResourceBase::Class::UAV;
  1940. return DxilResourceBase::Class::Invalid;
  1941. }
  1942. // This should probably be refactored to ASTContextHLSL, and follow types
  1943. // rather than do string comparisons.
  1944. DXIL::ResourceClass
  1945. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  1946. clang::QualType Ty) {
  1947. Ty = Ty.getCanonicalType();
  1948. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  1949. return GetResourceClassForType(context, arrayType->getElementType());
  1950. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  1951. return KeywordToClass(RT->getDecl()->getName());
  1952. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1953. if (const ClassTemplateSpecializationDecl *templateDecl =
  1954. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  1955. return KeywordToClass(templateDecl->getName());
  1956. }
  1957. }
  1958. return hlsl::DxilResourceBase::Class::Invalid;
  1959. }
  1960. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  1961. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  1962. }
  1963. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  1964. llvm::Constant *val = CGM.GetAddrOfGlobalVar(samplerDecl);
  1965. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  1966. hlslRes->SetLowerBound(UINT_MAX);
  1967. hlslRes->SetGlobalSymbol(cast<llvm::GlobalVariable>(val));
  1968. hlslRes->SetGlobalName(samplerDecl->getName());
  1969. QualType VarTy = samplerDecl->getType();
  1970. if (const clang::ArrayType *arrayType =
  1971. CGM.getContext().getAsArrayType(VarTy)) {
  1972. if (arrayType->isConstantArrayType()) {
  1973. uint32_t arraySize =
  1974. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  1975. hlslRes->SetRangeSize(arraySize);
  1976. } else {
  1977. hlslRes->SetRangeSize(UINT_MAX);
  1978. }
  1979. // use elementTy
  1980. VarTy = arrayType->getElementType();
  1981. // Support more dim.
  1982. while (const clang::ArrayType *arrayType =
  1983. CGM.getContext().getAsArrayType(VarTy)) {
  1984. unsigned rangeSize = hlslRes->GetRangeSize();
  1985. if (arrayType->isConstantArrayType()) {
  1986. uint32_t arraySize =
  1987. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  1988. if (rangeSize != UINT_MAX)
  1989. hlslRes->SetRangeSize(rangeSize * arraySize);
  1990. } else
  1991. hlslRes->SetRangeSize(UINT_MAX);
  1992. // use elementTy
  1993. VarTy = arrayType->getElementType();
  1994. }
  1995. } else
  1996. hlslRes->SetRangeSize(1);
  1997. const RecordType *RT = VarTy->getAs<RecordType>();
  1998. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  1999. hlslRes->SetSamplerKind(kind);
  2000. for (hlsl::UnusualAnnotation *it : samplerDecl->getUnusualAnnotations()) {
  2001. switch (it->getKind()) {
  2002. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2003. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2004. hlslRes->SetLowerBound(ra->RegisterNumber);
  2005. hlslRes->SetSpaceID(ra->RegisterSpace);
  2006. break;
  2007. }
  2008. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2009. // Ignore Semantics
  2010. break;
  2011. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2012. // Should be handled by front-end
  2013. llvm_unreachable("packoffset on sampler");
  2014. break;
  2015. default:
  2016. llvm_unreachable("unknown UnusualAnnotation on sampler");
  2017. break;
  2018. }
  2019. }
  2020. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  2021. return m_pHLModule->AddSampler(std::move(hlslRes));
  2022. }
  2023. static void CollectScalarTypes(std::vector<llvm::Type *> &scalarTys, llvm::Type *Ty) {
  2024. if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  2025. for (llvm::Type *EltTy : ST->elements()) {
  2026. CollectScalarTypes(scalarTys, EltTy);
  2027. }
  2028. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  2029. llvm::Type *EltTy = AT->getElementType();
  2030. for (unsigned i=0;i<AT->getNumElements();i++) {
  2031. CollectScalarTypes(scalarTys, EltTy);
  2032. }
  2033. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  2034. llvm::Type *EltTy = VT->getElementType();
  2035. for (unsigned i=0;i<VT->getNumElements();i++) {
  2036. CollectScalarTypes(scalarTys, EltTy);
  2037. }
  2038. } else {
  2039. scalarTys.emplace_back(Ty);
  2040. }
  2041. }
  2042. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  2043. if (Ty->isRecordType()) {
  2044. if (hlsl::IsHLSLMatType(Ty)) {
  2045. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  2046. unsigned row = 0;
  2047. unsigned col = 0;
  2048. hlsl::GetRowsAndCols(Ty, row, col);
  2049. unsigned size = col*row;
  2050. for (unsigned i = 0; i < size; i++) {
  2051. CollectScalarTypes(ScalarTys, EltTy);
  2052. }
  2053. } else if (hlsl::IsHLSLVecType(Ty)) {
  2054. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  2055. unsigned row = 0;
  2056. unsigned col = 0;
  2057. hlsl::GetRowsAndColsForAny(Ty, row, col);
  2058. unsigned size = col;
  2059. for (unsigned i = 0; i < size; i++) {
  2060. CollectScalarTypes(ScalarTys, EltTy);
  2061. }
  2062. } else {
  2063. const RecordType *RT = Ty->getAsStructureType();
  2064. // For CXXRecord.
  2065. if (!RT)
  2066. RT = Ty->getAs<RecordType>();
  2067. RecordDecl *RD = RT->getDecl();
  2068. for (FieldDecl *field : RD->fields())
  2069. CollectScalarTypes(ScalarTys, field->getType());
  2070. }
  2071. } else if (Ty->isArrayType()) {
  2072. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  2073. QualType EltTy = AT->getElementType();
  2074. // Set it to 5 for unsized array.
  2075. unsigned size = 5;
  2076. if (AT->isConstantArrayType()) {
  2077. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  2078. }
  2079. for (unsigned i=0;i<size;i++) {
  2080. CollectScalarTypes(ScalarTys, EltTy);
  2081. }
  2082. } else {
  2083. ScalarTys.emplace_back(Ty);
  2084. }
  2085. }
  2086. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  2087. hlsl::DxilResourceBase::Class resClass,
  2088. DxilResource *hlslRes, const RecordDecl *RD) {
  2089. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  2090. hlslRes->SetKind(kind);
  2091. // Get the result type from handle field.
  2092. FieldDecl *FD = *(RD->field_begin());
  2093. DXASSERT(FD->getName() == "h", "must be handle field");
  2094. QualType resultTy = FD->getType();
  2095. // Type annotation for result type of resource.
  2096. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2097. unsigned arrayEltSize = 0;
  2098. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  2099. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  2100. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  2101. const ClassTemplateSpecializationDecl *templateDecl =
  2102. dyn_cast<ClassTemplateSpecializationDecl>(RD);
  2103. const clang::TemplateArgument &sampleCountArg =
  2104. templateDecl->getTemplateArgs()[1];
  2105. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  2106. hlslRes->SetSampleCount(sampleCount);
  2107. }
  2108. if (kind != hlsl::DxilResource::Kind::StructuredBuffer) {
  2109. QualType Ty = resultTy;
  2110. QualType EltTy = Ty;
  2111. if (hlsl::IsHLSLVecType(Ty)) {
  2112. EltTy = hlsl::GetHLSLVecElementType(Ty);
  2113. } else if (hlsl::IsHLSLMatType(Ty)) {
  2114. EltTy = hlsl::GetHLSLMatElementType(Ty);
  2115. } else if (resultTy->isAggregateType()) {
  2116. // Struct or array in a none-struct resource.
  2117. std::vector<QualType> ScalarTys;
  2118. CollectScalarTypes(ScalarTys, resultTy);
  2119. unsigned size = ScalarTys.size();
  2120. if (size == 0) {
  2121. DiagnosticsEngine &Diags = CGM.getDiags();
  2122. unsigned DiagID = Diags.getCustomDiagID(
  2123. DiagnosticsEngine::Error,
  2124. "object's templated type must have at least one element");
  2125. Diags.Report(loc, DiagID);
  2126. return false;
  2127. }
  2128. if (size > 4) {
  2129. DiagnosticsEngine &Diags = CGM.getDiags();
  2130. unsigned DiagID = Diags.getCustomDiagID(
  2131. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  2132. "must fit in four 32-bit quantities");
  2133. Diags.Report(loc, DiagID);
  2134. return false;
  2135. }
  2136. EltTy = ScalarTys[0];
  2137. for (QualType ScalarTy : ScalarTys) {
  2138. if (ScalarTy != EltTy) {
  2139. DiagnosticsEngine &Diags = CGM.getDiags();
  2140. unsigned DiagID = Diags.getCustomDiagID(
  2141. DiagnosticsEngine::Error,
  2142. "all template type components must have the same type");
  2143. Diags.Report(loc, DiagID);
  2144. return false;
  2145. }
  2146. }
  2147. }
  2148. EltTy = EltTy.getCanonicalType();
  2149. bool bSNorm = false;
  2150. bool bUNorm = false;
  2151. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  2152. switch (AT->getAttrKind()) {
  2153. case AttributedType::Kind::attr_hlsl_snorm:
  2154. bSNorm = true;
  2155. break;
  2156. case AttributedType::Kind::attr_hlsl_unorm:
  2157. bUNorm = true;
  2158. break;
  2159. default:
  2160. // Do nothing
  2161. break;
  2162. }
  2163. }
  2164. if (EltTy->isBuiltinType()) {
  2165. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  2166. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  2167. // 64bits types are implemented with u32.
  2168. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2169. kind == CompType::Kind::SNormF64 ||
  2170. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2171. kind = CompType::Kind::U32;
  2172. }
  2173. hlslRes->SetCompType(kind);
  2174. } else {
  2175. DXASSERT(!bSNorm && !bUNorm, "snorm/unorm on invalid type");
  2176. }
  2177. }
  2178. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2179. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2180. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2181. const ClassTemplateSpecializationDecl *templateDecl =
  2182. dyn_cast<ClassTemplateSpecializationDecl>(RD);
  2183. const clang::TemplateArgument &retTyArg =
  2184. templateDecl->getTemplateArgs()[0];
  2185. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2186. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2187. hlslRes->SetElementStride(strideInBytes);
  2188. }
  2189. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2190. if (hlslRes->IsGloballyCoherent()) {
  2191. DiagnosticsEngine &Diags = CGM.getDiags();
  2192. unsigned DiagID = Diags.getCustomDiagID(
  2193. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2194. "Unordered Access View buffers.");
  2195. Diags.Report(loc, DiagID);
  2196. return false;
  2197. }
  2198. hlslRes->SetRW(false);
  2199. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2200. } else {
  2201. hlslRes->SetRW(true);
  2202. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2203. }
  2204. return true;
  2205. }
  2206. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2207. hlsl::DxilResourceBase::Class resClass) {
  2208. llvm::GlobalVariable *val =
  2209. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2210. QualType VarTy = decl->getType().getCanonicalType();
  2211. unique_ptr<HLResource> hlslRes(new HLResource);
  2212. hlslRes->SetLowerBound(UINT_MAX);
  2213. hlslRes->SetGlobalSymbol(val);
  2214. hlslRes->SetGlobalName(decl->getName());
  2215. if (const clang::ArrayType *arrayType =
  2216. CGM.getContext().getAsArrayType(VarTy)) {
  2217. if (arrayType->isConstantArrayType()) {
  2218. uint32_t arraySize =
  2219. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2220. hlslRes->SetRangeSize(arraySize);
  2221. } else
  2222. hlslRes->SetRangeSize(UINT_MAX);
  2223. // use elementTy
  2224. VarTy = arrayType->getElementType();
  2225. // Support more dim.
  2226. while (const clang::ArrayType *arrayType =
  2227. CGM.getContext().getAsArrayType(VarTy)) {
  2228. unsigned rangeSize = hlslRes->GetRangeSize();
  2229. if (arrayType->isConstantArrayType()) {
  2230. uint32_t arraySize =
  2231. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2232. if (rangeSize != UINT_MAX)
  2233. hlslRes->SetRangeSize(rangeSize * arraySize);
  2234. } else
  2235. hlslRes->SetRangeSize(UINT_MAX);
  2236. // use elementTy
  2237. VarTy = arrayType->getElementType();
  2238. }
  2239. } else
  2240. hlslRes->SetRangeSize(1);
  2241. for (hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  2242. switch (it->getKind()) {
  2243. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2244. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2245. hlslRes->SetLowerBound(ra->RegisterNumber);
  2246. hlslRes->SetSpaceID(ra->RegisterSpace);
  2247. break;
  2248. }
  2249. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2250. // Ignore Semantics
  2251. break;
  2252. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2253. // Should be handled by front-end
  2254. llvm_unreachable("packoffset on uav/srv");
  2255. break;
  2256. default:
  2257. llvm_unreachable("unknown UnusualAnnotation on uav/srv");
  2258. break;
  2259. }
  2260. }
  2261. const RecordType *RT = VarTy->getAs<RecordType>();
  2262. RecordDecl *RD = RT->getDecl();
  2263. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2264. hlslRes->SetGloballyCoherent(true);
  2265. }
  2266. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), RD))
  2267. return 0;
  2268. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2269. return m_pHLModule->AddSRV(std::move(hlslRes));
  2270. } else {
  2271. return m_pHLModule->AddUAV(std::move(hlslRes));
  2272. }
  2273. }
  2274. static bool IsResourceInType(const clang::ASTContext &context,
  2275. clang::QualType Ty) {
  2276. Ty = Ty.getCanonicalType();
  2277. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2278. return IsResourceInType(context, arrayType->getElementType());
  2279. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2280. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2281. return true;
  2282. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2283. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2284. for (auto field : typeRecordDecl->fields()) {
  2285. if (IsResourceInType(context, field->getType()))
  2286. return true;
  2287. }
  2288. }
  2289. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2290. if (const ClassTemplateSpecializationDecl *templateDecl =
  2291. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2292. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2293. return true;
  2294. }
  2295. }
  2296. return false; // no resources found
  2297. }
  2298. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2299. if (constDecl->getStorageClass() == SC_Static) {
  2300. // For static inside cbuffer, take as global static.
  2301. // Don't add to cbuffer.
  2302. CGM.EmitGlobal(constDecl);
  2303. // Add type annotation for static global types.
  2304. // May need it when cast from cbuf.
  2305. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2306. unsigned arraySize = 0;
  2307. AddTypeAnnotation(constDecl->getType(), dxilTypeSys, arraySize);
  2308. return;
  2309. }
  2310. // Search defined structure for resource objects and fail
  2311. if (CB.GetRangeSize() > 1 &&
  2312. IsResourceInType(CGM.getContext(), constDecl->getType())) {
  2313. DiagnosticsEngine &Diags = CGM.getDiags();
  2314. unsigned DiagID = Diags.getCustomDiagID(
  2315. DiagnosticsEngine::Error,
  2316. "object types not supported in cbuffer/tbuffer view arrays.");
  2317. Diags.Report(constDecl->getLocation(), DiagID);
  2318. return;
  2319. }
  2320. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2321. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2322. uint32_t offset = 0;
  2323. bool userOffset = false;
  2324. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2325. switch (it->getKind()) {
  2326. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2327. if (!isGlobalCB) {
  2328. // TODO: check cannot mix packoffset elements with nonpackoffset
  2329. // elements in a cbuffer.
  2330. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  2331. offset = cp->Subcomponent << 2;
  2332. offset += cp->ComponentOffset;
  2333. // Change to byte.
  2334. offset <<= 2;
  2335. userOffset = true;
  2336. } else {
  2337. DiagnosticsEngine &Diags = CGM.getDiags();
  2338. unsigned DiagID = Diags.getCustomDiagID(
  2339. DiagnosticsEngine::Error,
  2340. "packoffset is only allowed in a constant buffer.");
  2341. Diags.Report(it->Loc, DiagID);
  2342. }
  2343. break;
  2344. }
  2345. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2346. if (isGlobalCB) {
  2347. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  2348. offset = ra->RegisterNumber << 2;
  2349. // Change to byte.
  2350. offset <<= 2;
  2351. userOffset = true;
  2352. }
  2353. break;
  2354. }
  2355. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2356. // skip semantic on constant
  2357. break;
  2358. }
  2359. }
  2360. std::unique_ptr<DxilResourceBase> pHlslConst = llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2361. pHlslConst->SetLowerBound(UINT_MAX);
  2362. pHlslConst->SetGlobalSymbol(cast<llvm::GlobalVariable>(constVal));
  2363. pHlslConst->SetGlobalName(constDecl->getName());
  2364. if (userOffset) {
  2365. pHlslConst->SetLowerBound(offset);
  2366. }
  2367. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2368. // Just add type annotation here.
  2369. // Offset will be allocated later.
  2370. QualType Ty = constDecl->getType();
  2371. if (CB.GetRangeSize() != 1) {
  2372. while (Ty->isArrayType()) {
  2373. Ty = Ty->getAsArrayTypeUnsafe()->getElementType();
  2374. }
  2375. }
  2376. unsigned arrayEltSize = 0;
  2377. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2378. pHlslConst->SetRangeSize(size);
  2379. CB.AddConst(pHlslConst);
  2380. // Save fieldAnnotation for the const var.
  2381. DxilFieldAnnotation fieldAnnotation;
  2382. if (userOffset)
  2383. fieldAnnotation.SetCBufferOffset(offset);
  2384. // Get the nested element type.
  2385. if (Ty->isArrayType()) {
  2386. while (const ConstantArrayType *arrayTy =
  2387. CGM.getContext().getAsConstantArrayType(Ty)) {
  2388. Ty = arrayTy->getElementType();
  2389. }
  2390. }
  2391. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  2392. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  2393. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  2394. }
  2395. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  2396. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  2397. // setup the CB
  2398. CB->SetGlobalSymbol(nullptr);
  2399. CB->SetGlobalName(D->getNameAsString());
  2400. CB->SetLowerBound(UINT_MAX);
  2401. if (!D->isCBuffer()) {
  2402. CB->SetKind(DXIL::ResourceKind::TBuffer);
  2403. }
  2404. // the global variable will only used once by the createHandle?
  2405. // SetHandle(llvm::Value *pHandle);
  2406. for (hlsl::UnusualAnnotation *it : D->getUnusualAnnotations()) {
  2407. switch (it->getKind()) {
  2408. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2409. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2410. uint32_t regNum = ra->RegisterNumber;
  2411. uint32_t regSpace = ra->RegisterSpace;
  2412. CB->SetSpaceID(regSpace);
  2413. CB->SetLowerBound(regNum);
  2414. break;
  2415. }
  2416. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2417. // skip semantic on constant buffer
  2418. break;
  2419. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2420. llvm_unreachable("no packoffset on constant buffer");
  2421. break;
  2422. }
  2423. }
  2424. // Add constant
  2425. if (D->isConstantBufferView()) {
  2426. VarDecl *constDecl = cast<VarDecl>(*D->decls_begin());
  2427. CB->SetRangeSize(1);
  2428. QualType Ty = constDecl->getType();
  2429. if (Ty->isArrayType()) {
  2430. if (!Ty->isIncompleteArrayType()) {
  2431. unsigned arraySize = 1;
  2432. while (Ty->isArrayType()) {
  2433. Ty = Ty->getCanonicalTypeUnqualified();
  2434. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  2435. arraySize *= AT->getSize().getLimitedValue();
  2436. Ty = AT->getElementType();
  2437. }
  2438. CB->SetRangeSize(arraySize);
  2439. } else {
  2440. CB->SetRangeSize(UINT_MAX);
  2441. }
  2442. }
  2443. AddConstant(constDecl, *CB.get());
  2444. } else {
  2445. auto declsEnds = D->decls_end();
  2446. CB->SetRangeSize(1);
  2447. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  2448. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it)) {
  2449. AddConstant(constDecl, *CB.get());
  2450. } else if (isa<EmptyDecl>(*it)) {
  2451. // Nothing to do for this declaration.
  2452. } else if (isa<CXXRecordDecl>(*it)) {
  2453. // Nothing to do for this declaration.
  2454. } else if (isa<FunctionDecl>(*it)) {
  2455. // A function within an cbuffer is effectively a top-level function,
  2456. // as it only refers to globally scoped declarations.
  2457. this->CGM.EmitTopLevelDecl(*it);
  2458. } else {
  2459. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  2460. GetOrCreateCBuffer(inner);
  2461. }
  2462. }
  2463. }
  2464. CB->SetID(m_pHLModule->GetCBuffers().size());
  2465. return m_pHLModule->AddCBuffer(std::move(CB));
  2466. }
  2467. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  2468. if (constantBufMap.count(D) != 0) {
  2469. uint32_t cbIndex = constantBufMap[D];
  2470. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  2471. }
  2472. uint32_t cbID = AddCBuffer(D);
  2473. constantBufMap[D] = cbID;
  2474. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  2475. }
  2476. bool CGMSHLSLRuntime::IsPatchConstantFunction(const Function *F) {
  2477. DXASSERT_NOMSG(F != nullptr);
  2478. for (auto && p : patchConstantFunctionMap) {
  2479. if (p.second.Func == F) return true;
  2480. }
  2481. return false;
  2482. }
  2483. void CGMSHLSLRuntime::SetEntryFunction() {
  2484. if (Entry.Func == nullptr) {
  2485. DiagnosticsEngine &Diags = CGM.getDiags();
  2486. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2487. "cannot find entry function %0");
  2488. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLEntryFunction;
  2489. return;
  2490. }
  2491. m_pHLModule->SetEntryFunction(Entry.Func);
  2492. }
  2493. // Here the size is CB size. So don't need check type.
  2494. static unsigned AlignCBufferOffset(unsigned offset, unsigned size, llvm::Type *Ty) {
  2495. DXASSERT(!(offset & 1), "otherwise we have an invalid offset.");
  2496. bool bNeedNewRow = Ty->isArrayTy();
  2497. unsigned scalarSizeInBytes = Ty->getScalarSizeInBits() / 8;
  2498. return AlignBufferOffsetInLegacy(offset, size, scalarSizeInBytes, bNeedNewRow);
  2499. }
  2500. static unsigned AllocateDxilConstantBuffer(HLCBuffer &CB) {
  2501. unsigned offset = 0;
  2502. // Scan user allocated constants first.
  2503. // Update offset.
  2504. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2505. if (C->GetLowerBound() == UINT_MAX)
  2506. continue;
  2507. unsigned size = C->GetRangeSize();
  2508. unsigned nextOffset = size + C->GetLowerBound();
  2509. if (offset < nextOffset)
  2510. offset = nextOffset;
  2511. }
  2512. // Alloc after user allocated constants.
  2513. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2514. if (C->GetLowerBound() != UINT_MAX)
  2515. continue;
  2516. unsigned size = C->GetRangeSize();
  2517. llvm::Type *Ty = C->GetGlobalSymbol()->getType()->getPointerElementType();
  2518. // Align offset.
  2519. offset = AlignCBufferOffset(offset, size, Ty);
  2520. if (C->GetLowerBound() == UINT_MAX) {
  2521. C->SetLowerBound(offset);
  2522. }
  2523. offset += size;
  2524. }
  2525. return offset;
  2526. }
  2527. static void AllocateDxilConstantBuffers(HLModule *pHLModule) {
  2528. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2529. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2530. unsigned size = AllocateDxilConstantBuffer(CB);
  2531. CB.SetSize(size);
  2532. }
  2533. }
  2534. static void ReplaceUseInFunction(Value *V, Value *NewV, Function *F,
  2535. IRBuilder<> &Builder) {
  2536. for (auto U = V->user_begin(); U != V->user_end(); ) {
  2537. User *user = *(U++);
  2538. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2539. if (I->getParent()->getParent() == F) {
  2540. // replace use with GEP if in F
  2541. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  2542. if (I->getOperand(i) == V)
  2543. I->setOperand(i, NewV);
  2544. }
  2545. }
  2546. } else {
  2547. // For constant operator, create local clone which use GEP.
  2548. // Only support GEP and bitcast.
  2549. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2550. std::vector<Value *> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  2551. Value *NewGEP = Builder.CreateInBoundsGEP(NewV, idxList);
  2552. ReplaceUseInFunction(GEPOp, NewGEP, F, Builder);
  2553. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2554. // Change the init val into NewV with Store.
  2555. GV->setInitializer(nullptr);
  2556. Builder.CreateStore(NewV, GV);
  2557. } else {
  2558. // Must be bitcast here.
  2559. BitCastOperator *BC = cast<BitCastOperator>(user);
  2560. Value *NewBC = Builder.CreateBitCast(NewV, BC->getType());
  2561. ReplaceUseInFunction(BC, NewBC, F, Builder);
  2562. }
  2563. }
  2564. }
  2565. }
  2566. void MarkUsedFunctionForConst(Value *V, std::unordered_set<Function*> &usedFunc) {
  2567. for (auto U = V->user_begin(); U != V->user_end();) {
  2568. User *user = *(U++);
  2569. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2570. Function *F = I->getParent()->getParent();
  2571. usedFunc.insert(F);
  2572. } else {
  2573. // For constant operator, create local clone which use GEP.
  2574. // Only support GEP and bitcast.
  2575. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2576. MarkUsedFunctionForConst(GEPOp, usedFunc);
  2577. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2578. MarkUsedFunctionForConst(GV, usedFunc);
  2579. } else {
  2580. // Must be bitcast here.
  2581. BitCastOperator *BC = cast<BitCastOperator>(user);
  2582. MarkUsedFunctionForConst(BC, usedFunc);
  2583. }
  2584. }
  2585. }
  2586. }
  2587. static Function * GetOrCreateHLCreateHandle(HLModule &HLM, llvm::Type *HandleTy,
  2588. ArrayRef<Value*> paramList, MDNode *MD) {
  2589. SmallVector<llvm::Type *, 4> paramTyList;
  2590. for (Value *param : paramList) {
  2591. paramTyList.emplace_back(param->getType());
  2592. }
  2593. llvm::FunctionType *funcTy =
  2594. llvm::FunctionType::get(HandleTy, paramTyList, false);
  2595. llvm::Module &M = *HLM.GetModule();
  2596. Function *CreateHandle = GetOrCreateHLFunctionWithBody(M, funcTy, HLOpcodeGroup::HLCreateHandle,
  2597. /*opcode*/ 0, "");
  2598. if (CreateHandle->empty()) {
  2599. // Add body.
  2600. BasicBlock *BB =
  2601. BasicBlock::Create(CreateHandle->getContext(), "Entry", CreateHandle);
  2602. IRBuilder<> Builder(BB);
  2603. // Just return undef to make a body.
  2604. Builder.CreateRet(UndefValue::get(HandleTy));
  2605. // Mark resource attribute.
  2606. HLM.MarkDxilResourceAttrib(CreateHandle, MD);
  2607. }
  2608. return CreateHandle;
  2609. }
  2610. static bool CreateCBufferVariable(HLCBuffer &CB,
  2611. HLModule &HLM, llvm::Type *HandleTy) {
  2612. bool bUsed = false;
  2613. // Build Struct for CBuffer.
  2614. SmallVector<llvm::Type*, 4> Elements;
  2615. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2616. Value *GV = C->GetGlobalSymbol();
  2617. if (GV->hasNUsesOrMore(1))
  2618. bUsed = true;
  2619. // Global variable must be pointer type.
  2620. llvm::Type *Ty = GV->getType()->getPointerElementType();
  2621. Elements.emplace_back(Ty);
  2622. }
  2623. // Don't create CBuffer variable for unused cbuffer.
  2624. if (!bUsed)
  2625. return false;
  2626. llvm::Module &M = *HLM.GetModule();
  2627. bool isCBArray = CB.GetRangeSize() != 1;
  2628. llvm::GlobalVariable *cbGV = nullptr;
  2629. llvm::Type *cbTy = nullptr;
  2630. unsigned cbIndexDepth = 0;
  2631. if (!isCBArray) {
  2632. llvm::StructType *CBStructTy =
  2633. llvm::StructType::create(Elements, CB.GetGlobalName());
  2634. cbGV = new llvm::GlobalVariable(M, CBStructTy, /*IsConstant*/ true,
  2635. llvm::GlobalValue::ExternalLinkage,
  2636. /*InitVal*/ nullptr, CB.GetGlobalName());
  2637. cbTy = cbGV->getType();
  2638. } else {
  2639. // For array of ConstantBuffer, create array of struct instead of struct of
  2640. // array.
  2641. DXASSERT(CB.GetConstants().size() == 1,
  2642. "ConstantBuffer should have 1 constant");
  2643. Value *GV = CB.GetConstants()[0]->GetGlobalSymbol();
  2644. llvm::Type *CBEltTy =
  2645. GV->getType()->getPointerElementType()->getArrayElementType();
  2646. cbIndexDepth = 1;
  2647. while (CBEltTy->isArrayTy()) {
  2648. CBEltTy = CBEltTy->getArrayElementType();
  2649. cbIndexDepth++;
  2650. }
  2651. // Add one level struct type to match normal case.
  2652. llvm::StructType *CBStructTy =
  2653. llvm::StructType::create({CBEltTy}, CB.GetGlobalName());
  2654. llvm::ArrayType *CBArrayTy =
  2655. llvm::ArrayType::get(CBStructTy, CB.GetRangeSize());
  2656. cbGV = new llvm::GlobalVariable(M, CBArrayTy, /*IsConstant*/ true,
  2657. llvm::GlobalValue::ExternalLinkage,
  2658. /*InitVal*/ nullptr, CB.GetGlobalName());
  2659. cbTy = llvm::PointerType::get(CBStructTy,
  2660. cbGV->getType()->getPointerAddressSpace());
  2661. }
  2662. CB.SetGlobalSymbol(cbGV);
  2663. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2664. llvm::Type *idxTy = opcodeTy;
  2665. Constant *zeroIdx = ConstantInt::get(opcodeTy, 0);
  2666. MDNode *MD = HLM.DxilCBufferToMDNode(CB);
  2667. Value *HandleArgs[] = { zeroIdx, cbGV, zeroIdx };
  2668. Function *CreateHandleFunc = GetOrCreateHLCreateHandle(HLM, HandleTy, HandleArgs, MD);
  2669. llvm::FunctionType *SubscriptFuncTy =
  2670. llvm::FunctionType::get(cbTy, { opcodeTy, HandleTy, idxTy}, false);
  2671. Function *subscriptFunc =
  2672. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2673. (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2674. Constant *opArg = ConstantInt::get(opcodeTy, (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2675. Value *args[] = { opArg, nullptr, zeroIdx };
  2676. llvm::LLVMContext &Context = M.getContext();
  2677. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Context);
  2678. Value *zero = ConstantInt::get(i32Ty, (uint64_t)0);
  2679. std::vector<Value *> indexArray(CB.GetConstants().size());
  2680. std::vector<std::unordered_set<Function*>> constUsedFuncList(CB.GetConstants().size());
  2681. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2682. Value *idx = ConstantInt::get(i32Ty, C->GetID());
  2683. indexArray[C->GetID()] = idx;
  2684. Value *GV = C->GetGlobalSymbol();
  2685. MarkUsedFunctionForConst(GV, constUsedFuncList[C->GetID()]);
  2686. }
  2687. for (Function &F : M.functions()) {
  2688. if (F.isDeclaration())
  2689. continue;
  2690. if (GetHLOpcodeGroupByName(&F) != HLOpcodeGroup::NotHL)
  2691. continue;
  2692. IRBuilder<> Builder(F.getEntryBlock().getFirstInsertionPt());
  2693. // create HL subscript to make all the use of cbuffer start from it.
  2694. HandleArgs[HLOperandIndex::kCreateHandleResourceOpIdx] = cbGV;
  2695. CallInst *Handle = Builder.CreateCall(CreateHandleFunc, HandleArgs);
  2696. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2697. Instruction *cbSubscript =
  2698. cast<Instruction>(Builder.CreateCall(subscriptFunc, {args}));
  2699. // Replace constant var with GEP pGV
  2700. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2701. Value *GV = C->GetGlobalSymbol();
  2702. if (constUsedFuncList[C->GetID()].count(&F) == 0)
  2703. continue;
  2704. Value *idx = indexArray[C->GetID()];
  2705. if (!isCBArray) {
  2706. Instruction *GEP = cast<Instruction>(
  2707. Builder.CreateInBoundsGEP(cbSubscript, {zero, idx}));
  2708. // TODO: make sure the debug info is synced to GEP.
  2709. // GEP->setDebugLoc(GV);
  2710. ReplaceUseInFunction(GV, GEP, &F, Builder);
  2711. // Delete if no use in F.
  2712. if (GEP->user_empty())
  2713. GEP->eraseFromParent();
  2714. } else {
  2715. for (auto U = GV->user_begin(); U != GV->user_end();) {
  2716. User *user = *(U++);
  2717. if (user->user_empty())
  2718. continue;
  2719. Instruction *I = dyn_cast<Instruction>(user);
  2720. if (I && I->getParent()->getParent() != &F)
  2721. continue;
  2722. IRBuilder<> *instBuilder = &Builder;
  2723. unique_ptr<IRBuilder<>> B;
  2724. if (I) {
  2725. B = llvm::make_unique<IRBuilder<>>(I);
  2726. instBuilder = B.get();
  2727. }
  2728. GEPOperator *GEPOp = cast<GEPOperator>(user);
  2729. std::vector<Value *> idxList;
  2730. DXASSERT(GEPOp->getNumIndices() >= 1 + cbIndexDepth,
  2731. "must indexing ConstantBuffer array");
  2732. idxList.reserve(GEPOp->getNumIndices() - (cbIndexDepth - 1));
  2733. gep_type_iterator GI = gep_type_begin(*GEPOp),
  2734. E = gep_type_end(*GEPOp);
  2735. idxList.push_back(GI.getOperand());
  2736. // change array index with 0 for struct index.
  2737. idxList.push_back(zero);
  2738. GI++;
  2739. Value *arrayIdx = GI.getOperand();
  2740. GI++;
  2741. for (unsigned curIndex = 1; GI != E && curIndex < cbIndexDepth;
  2742. ++GI, ++curIndex) {
  2743. arrayIdx = instBuilder->CreateMul(
  2744. arrayIdx, Builder.getInt32(GI->getArrayNumElements()));
  2745. arrayIdx = instBuilder->CreateAdd(arrayIdx, GI.getOperand());
  2746. }
  2747. for (; GI != E; ++GI) {
  2748. idxList.push_back(GI.getOperand());
  2749. }
  2750. HandleArgs[HLOperandIndex::kCreateHandleIndexOpIdx] = arrayIdx;
  2751. CallInst *Handle =
  2752. instBuilder->CreateCall(CreateHandleFunc, HandleArgs);
  2753. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2754. args[HLOperandIndex::kSubscriptIndexOpIdx] = arrayIdx;
  2755. Instruction *cbSubscript =
  2756. cast<Instruction>(instBuilder->CreateCall(subscriptFunc, {args}));
  2757. Instruction *NewGEP = cast<Instruction>(
  2758. instBuilder->CreateInBoundsGEP(cbSubscript, idxList));
  2759. ReplaceUseInFunction(GEPOp, NewGEP, &F, *instBuilder);
  2760. }
  2761. }
  2762. }
  2763. // Delete if no use in F.
  2764. if (cbSubscript->user_empty()) {
  2765. cbSubscript->eraseFromParent();
  2766. Handle->eraseFromParent();
  2767. }
  2768. }
  2769. return true;
  2770. }
  2771. static void ConstructCBufferAnnotation(
  2772. HLCBuffer &CB, DxilTypeSystem &dxilTypeSys,
  2773. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2774. Value *GV = CB.GetGlobalSymbol();
  2775. llvm::StructType *CBStructTy =
  2776. dyn_cast<llvm::StructType>(GV->getType()->getPointerElementType());
  2777. if (!CBStructTy) {
  2778. // For Array of ConstantBuffer.
  2779. llvm::ArrayType *CBArrayTy =
  2780. cast<llvm::ArrayType>(GV->getType()->getPointerElementType());
  2781. CBStructTy = cast<llvm::StructType>(CBArrayTy->getArrayElementType());
  2782. }
  2783. DxilStructAnnotation *CBAnnotation =
  2784. dxilTypeSys.AddStructAnnotation(CBStructTy);
  2785. CBAnnotation->SetCBufferSize(CB.GetSize());
  2786. // Set fieldAnnotation for each constant var.
  2787. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2788. Constant *GV = C->GetGlobalSymbol();
  2789. DxilFieldAnnotation &fieldAnnotation =
  2790. CBAnnotation->GetFieldAnnotation(C->GetID());
  2791. fieldAnnotation = AnnotationMap[GV];
  2792. // This is after CBuffer allocation.
  2793. fieldAnnotation.SetCBufferOffset(C->GetLowerBound());
  2794. fieldAnnotation.SetFieldName(C->GetGlobalName());
  2795. }
  2796. }
  2797. static void ConstructCBuffer(
  2798. HLModule *pHLModule,
  2799. llvm::Type *CBufferType,
  2800. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2801. DxilTypeSystem &dxilTypeSys = pHLModule->GetTypeSystem();
  2802. llvm::Type *HandleTy = pHLModule->GetOP()->GetHandleType();
  2803. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2804. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2805. if (CB.GetConstants().size() == 0) {
  2806. // Create Fake variable for cbuffer which is empty.
  2807. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  2808. *pHLModule->GetModule(), CBufferType, true,
  2809. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  2810. CB.SetGlobalSymbol(pGV);
  2811. } else {
  2812. bool bCreated =
  2813. CreateCBufferVariable(CB, *pHLModule, HandleTy);
  2814. if (bCreated)
  2815. ConstructCBufferAnnotation(CB, dxilTypeSys, AnnotationMap);
  2816. else {
  2817. // Create Fake variable for cbuffer which is unused.
  2818. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  2819. *pHLModule->GetModule(), CBufferType, true,
  2820. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  2821. CB.SetGlobalSymbol(pGV);
  2822. }
  2823. }
  2824. // Clear the constants which useless now.
  2825. CB.GetConstants().clear();
  2826. }
  2827. }
  2828. static void ReplaceBoolVectorSubscript(CallInst *CI) {
  2829. Value *Ptr = CI->getArgOperand(0);
  2830. Value *Idx = CI->getArgOperand(1);
  2831. Value *IdxList[] = {ConstantInt::get(Idx->getType(), 0), Idx};
  2832. for (auto It = CI->user_begin(), E = CI->user_end(); It != E;) {
  2833. Instruction *user = cast<Instruction>(*(It++));
  2834. IRBuilder<> Builder(user);
  2835. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  2836. if (LoadInst *LI = dyn_cast<LoadInst>(user)) {
  2837. Value *NewLd = Builder.CreateLoad(GEP);
  2838. Value *cast = Builder.CreateZExt(NewLd, LI->getType());
  2839. LI->replaceAllUsesWith(cast);
  2840. LI->eraseFromParent();
  2841. } else {
  2842. // Must be a store inst here.
  2843. StoreInst *SI = cast<StoreInst>(user);
  2844. Value *V = SI->getValueOperand();
  2845. Value *cast =
  2846. Builder.CreateICmpNE(V, llvm::ConstantInt::get(V->getType(), 0));
  2847. Builder.CreateStore(cast, GEP);
  2848. SI->eraseFromParent();
  2849. }
  2850. }
  2851. CI->eraseFromParent();
  2852. }
  2853. static void ReplaceBoolVectorSubscript(Function *F) {
  2854. for (auto It = F->user_begin(), E = F->user_end(); It != E; ) {
  2855. User *user = *(It++);
  2856. CallInst *CI = cast<CallInst>(user);
  2857. ReplaceBoolVectorSubscript(CI);
  2858. }
  2859. }
  2860. // Add function body for intrinsic if possible.
  2861. static Function *CreateOpFunction(llvm::Module &M, Function *F,
  2862. llvm::FunctionType *funcTy,
  2863. HLOpcodeGroup group, unsigned opcode) {
  2864. Function *opFunc = nullptr;
  2865. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2866. if (group == HLOpcodeGroup::HLIntrinsic) {
  2867. IntrinsicOp intriOp = static_cast<IntrinsicOp>(opcode);
  2868. switch (intriOp) {
  2869. case IntrinsicOp::MOP_Append:
  2870. case IntrinsicOp::MOP_Consume: {
  2871. bool bAppend = intriOp == IntrinsicOp::MOP_Append;
  2872. llvm::Type *handleTy = funcTy->getParamType(HLOperandIndex::kHandleOpIdx);
  2873. // Don't generate body for OutputStream::Append.
  2874. if (bAppend && HLModule::IsStreamOutputPtrType(handleTy)) {
  2875. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2876. break;
  2877. }
  2878. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode,
  2879. bAppend ? "append" : "consume");
  2880. llvm::Type *counterTy = llvm::Type::getInt32Ty(M.getContext());
  2881. llvm::FunctionType *IncCounterFuncTy =
  2882. llvm::FunctionType::get(counterTy, {opcodeTy, handleTy}, false);
  2883. unsigned counterOpcode = bAppend ? (unsigned)IntrinsicOp::MOP_IncrementCounter:
  2884. (unsigned)IntrinsicOp::MOP_DecrementCounter;
  2885. Function *incCounterFunc =
  2886. GetOrCreateHLFunction(M, IncCounterFuncTy, group,
  2887. counterOpcode);
  2888. llvm::Type *idxTy = counterTy;
  2889. llvm::Type *valTy = bAppend ?
  2890. funcTy->getParamType(HLOperandIndex::kAppendValOpIndex):funcTy->getReturnType();
  2891. llvm::Type *subscriptTy = valTy;
  2892. if (!valTy->isPointerTy()) {
  2893. // Return type for subscript should be pointer type.
  2894. subscriptTy = llvm::PointerType::get(valTy, 0);
  2895. }
  2896. llvm::FunctionType *SubscriptFuncTy =
  2897. llvm::FunctionType::get(subscriptTy, {opcodeTy, handleTy, idxTy}, false);
  2898. Function *subscriptFunc =
  2899. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2900. (unsigned)HLSubscriptOpcode::DefaultSubscript);
  2901. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  2902. IRBuilder<> Builder(BB);
  2903. auto argIter = opFunc->args().begin();
  2904. // Skip the opcode arg.
  2905. argIter++;
  2906. Argument *thisArg = argIter++;
  2907. // int counter = IncrementCounter/DecrementCounter(Buf);
  2908. Value *incCounterOpArg =
  2909. ConstantInt::get(idxTy, counterOpcode);
  2910. Value *counter =
  2911. Builder.CreateCall(incCounterFunc, {incCounterOpArg, thisArg});
  2912. // Buf[counter];
  2913. Value *subscriptOpArg = ConstantInt::get(
  2914. idxTy, (unsigned)HLSubscriptOpcode::DefaultSubscript);
  2915. Value *subscript =
  2916. Builder.CreateCall(subscriptFunc, {subscriptOpArg, thisArg, counter});
  2917. if (bAppend) {
  2918. Argument *valArg = argIter;
  2919. // Buf[counter] = val;
  2920. if (valTy->isPointerTy()) {
  2921. unsigned size = M.getDataLayout().getTypeAllocSize(subscript->getType()->getPointerElementType());
  2922. Builder.CreateMemCpy(subscript, valArg, size, 1);
  2923. } else
  2924. Builder.CreateStore(valArg, subscript);
  2925. Builder.CreateRetVoid();
  2926. } else {
  2927. // return Buf[counter];
  2928. if (valTy->isPointerTy())
  2929. Builder.CreateRet(subscript);
  2930. else {
  2931. Value *retVal = Builder.CreateLoad(subscript);
  2932. Builder.CreateRet(retVal);
  2933. }
  2934. }
  2935. } break;
  2936. case IntrinsicOp::IOP_sincos: {
  2937. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode, "sincos");
  2938. llvm::Type *valTy = funcTy->getParamType(HLOperandIndex::kTrinaryOpSrc0Idx);
  2939. llvm::FunctionType *sinFuncTy =
  2940. llvm::FunctionType::get(valTy, {opcodeTy, valTy}, false);
  2941. unsigned sinOp = static_cast<unsigned>(IntrinsicOp::IOP_sin);
  2942. unsigned cosOp = static_cast<unsigned>(IntrinsicOp::IOP_cos);
  2943. Function *sinFunc = GetOrCreateHLFunction(M, sinFuncTy, group, sinOp);
  2944. Function *cosFunc = GetOrCreateHLFunction(M, sinFuncTy, group, cosOp);
  2945. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  2946. IRBuilder<> Builder(BB);
  2947. auto argIter = opFunc->args().begin();
  2948. // Skip the opcode arg.
  2949. argIter++;
  2950. Argument *valArg = argIter++;
  2951. Argument *sinPtrArg = argIter++;
  2952. Argument *cosPtrArg = argIter++;
  2953. Value *sinOpArg =
  2954. ConstantInt::get(opcodeTy, sinOp);
  2955. Value *sinVal = Builder.CreateCall(sinFunc, {sinOpArg, valArg});
  2956. Builder.CreateStore(sinVal, sinPtrArg);
  2957. Value *cosOpArg =
  2958. ConstantInt::get(opcodeTy, cosOp);
  2959. Value *cosVal = Builder.CreateCall(cosFunc, {cosOpArg, valArg});
  2960. Builder.CreateStore(cosVal, cosPtrArg);
  2961. // Ret.
  2962. Builder.CreateRetVoid();
  2963. } break;
  2964. default:
  2965. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2966. break;
  2967. }
  2968. }
  2969. else if (group == HLOpcodeGroup::HLExtIntrinsic) {
  2970. llvm::StringRef fnName = F->getName();
  2971. llvm::StringRef groupName = GetHLOpcodeGroupNameByAttr(F);
  2972. opFunc = GetOrCreateHLFunction(M, funcTy, group, &groupName, &fnName, opcode);
  2973. }
  2974. else {
  2975. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2976. }
  2977. // Add attribute
  2978. if (F->hasFnAttribute(Attribute::ReadNone))
  2979. opFunc->addFnAttr(Attribute::ReadNone);
  2980. if (F->hasFnAttribute(Attribute::ReadOnly))
  2981. opFunc->addFnAttr(Attribute::ReadOnly);
  2982. return opFunc;
  2983. }
  2984. static Value *CreateHandleFromResPtr(
  2985. Value *ResPtr, HLModule &HLM, llvm::Type *HandleTy,
  2986. std::unordered_map<llvm::Type *, MDNode *> &resMetaMap,
  2987. IRBuilder<> &Builder) {
  2988. llvm::Type *objTy = ResPtr->getType()->getPointerElementType();
  2989. DXASSERT(resMetaMap.count(objTy), "cannot find resource type");
  2990. MDNode *MD = resMetaMap[objTy];
  2991. // Load to make sure resource only have Ld/St use so mem2reg could remove
  2992. // temp resource.
  2993. Value *ldObj = Builder.CreateLoad(ResPtr);
  2994. Value *opcode = Builder.getInt32(0);
  2995. Value *args[] = {opcode, ldObj};
  2996. Function *CreateHandle = GetOrCreateHLCreateHandle(HLM, HandleTy, args, MD);
  2997. CallInst *Handle = Builder.CreateCall(CreateHandle, args);
  2998. return Handle;
  2999. }
  3000. static void AddOpcodeParamForIntrinsic(HLModule &HLM, Function *F,
  3001. unsigned opcode, llvm::Type *HandleTy,
  3002. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  3003. llvm::Module &M = *HLM.GetModule();
  3004. llvm::FunctionType *oldFuncTy = F->getFunctionType();
  3005. SmallVector<llvm::Type *, 4> paramTyList;
  3006. // Add the opcode param
  3007. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3008. paramTyList.emplace_back(opcodeTy);
  3009. paramTyList.append(oldFuncTy->param_begin(), oldFuncTy->param_end());
  3010. for (unsigned i = 1; i < paramTyList.size(); i++) {
  3011. llvm::Type *Ty = paramTyList[i];
  3012. if (Ty->isPointerTy()) {
  3013. Ty = Ty->getPointerElementType();
  3014. if (HLModule::IsHLSLObjectType(Ty) &&
  3015. // StreamOutput don't need handle.
  3016. !HLModule::IsStreamOutputType(Ty)) {
  3017. // Use handle type for object type.
  3018. // This will make sure temp object variable only used by createHandle.
  3019. paramTyList[i] = HandleTy;
  3020. }
  3021. }
  3022. }
  3023. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3024. if (group == HLOpcodeGroup::HLSubscript &&
  3025. opcode == static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)) {
  3026. llvm::FunctionType *FT = F->getFunctionType();
  3027. llvm::Type *VecArgTy = FT->getParamType(0);
  3028. llvm::VectorType *VType =
  3029. cast<llvm::VectorType>(VecArgTy->getPointerElementType());
  3030. llvm::Type *Ty = VType->getElementType();
  3031. DXASSERT(Ty->isIntegerTy(), "Only bool could use VectorSubscript");
  3032. llvm::IntegerType *ITy = cast<IntegerType>(Ty);
  3033. DXASSERT_LOCALVAR(ITy, ITy->getBitWidth() == 1, "Only bool could use VectorSubscript");
  3034. // The return type is i8*.
  3035. // Replace all uses with i1*.
  3036. ReplaceBoolVectorSubscript(F);
  3037. return;
  3038. }
  3039. bool isDoubleSubscriptFunc = group == HLOpcodeGroup::HLSubscript &&
  3040. opcode == static_cast<unsigned>(HLSubscriptOpcode::DoubleSubscript);
  3041. llvm::Type *RetTy = oldFuncTy->getReturnType();
  3042. if (isDoubleSubscriptFunc) {
  3043. CallInst *doubleSub = cast<CallInst>(*F->user_begin());
  3044. // Change currentIdx type into coord type.
  3045. auto U = doubleSub->user_begin();
  3046. Value *user = *U;
  3047. CallInst *secSub = cast<CallInst>(user);
  3048. unsigned coordIdx = HLOperandIndex::kSubscriptIndexOpIdx;
  3049. // opcode operand not add yet, so the index need -1.
  3050. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  3051. coordIdx -= 1;
  3052. Value *coord = secSub->getArgOperand(coordIdx);
  3053. llvm::Type *coordTy = coord->getType();
  3054. paramTyList[HLOperandIndex::kSubscriptIndexOpIdx] = coordTy;
  3055. // Add the sampleIdx or mipLevel parameter to the end.
  3056. paramTyList.emplace_back(opcodeTy);
  3057. // Change return type to be resource ret type.
  3058. // opcode operand not add yet, so the index need -1.
  3059. Value *objPtr = doubleSub->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx-1);
  3060. // Must be a GEP
  3061. GEPOperator *objGEP = cast<GEPOperator>(objPtr);
  3062. gep_type_iterator GEPIt = gep_type_begin(objGEP), E = gep_type_end(objGEP);
  3063. llvm::Type *resTy = nullptr;
  3064. while (GEPIt != E) {
  3065. if (HLModule::IsHLSLObjectType(*GEPIt)) {
  3066. resTy = *GEPIt;
  3067. break;
  3068. }
  3069. GEPIt++;
  3070. }
  3071. DXASSERT(resTy, "must find the resource type");
  3072. // Change object type to handle type.
  3073. paramTyList[HLOperandIndex::kSubscriptObjectOpIdx] = HandleTy;
  3074. // Change RetTy into pointer of resource reture type.
  3075. RetTy = cast<StructType>(resTy)->getElementType(0)->getPointerTo();
  3076. llvm::Type *sliceTy = objGEP->getType()->getPointerElementType();
  3077. DXIL::ResourceClass RC = HLM.GetResourceClass(sliceTy);
  3078. DXIL::ResourceKind RK = HLM.GetResourceKind(sliceTy);
  3079. HLM.AddResourceTypeAnnotation(resTy, RC, RK);
  3080. }
  3081. llvm::FunctionType *funcTy =
  3082. llvm::FunctionType::get(RetTy, paramTyList, false);
  3083. Function *opFunc = CreateOpFunction(M, F, funcTy, group, opcode);
  3084. StringRef lower = hlsl::GetHLLowerStrategy(F);
  3085. if (!lower.empty())
  3086. hlsl::SetHLLowerStrategy(opFunc, lower);
  3087. for (auto user = F->user_begin(); user != F->user_end();) {
  3088. // User must be a call.
  3089. CallInst *oldCI = cast<CallInst>(*(user++));
  3090. SmallVector<Value *, 4> opcodeParamList;
  3091. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  3092. opcodeParamList.emplace_back(opcodeConst);
  3093. opcodeParamList.append(oldCI->arg_operands().begin(),
  3094. oldCI->arg_operands().end());
  3095. IRBuilder<> Builder(oldCI);
  3096. if (isDoubleSubscriptFunc) {
  3097. // Change obj to the resource pointer.
  3098. Value *objVal = opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx];
  3099. GEPOperator *objGEP = cast<GEPOperator>(objVal);
  3100. SmallVector<Value *, 8> IndexList;
  3101. IndexList.append(objGEP->idx_begin(), objGEP->idx_end());
  3102. Value *lastIndex = IndexList.back();
  3103. ConstantInt *constIndex = cast<ConstantInt>(lastIndex);
  3104. DXASSERT_LOCALVAR(constIndex, constIndex->getLimitedValue() == 1, "last index must 1");
  3105. // Remove the last index.
  3106. IndexList.pop_back();
  3107. objVal = objGEP->getPointerOperand();
  3108. if (IndexList.size() > 1)
  3109. objVal = Builder.CreateInBoundsGEP(objVal, IndexList);
  3110. Value *Handle =
  3111. CreateHandleFromResPtr(objVal, HLM, HandleTy, resMetaMap, Builder);
  3112. // Change obj to the resource pointer.
  3113. opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  3114. // Set idx and mipIdx.
  3115. Value *mipIdx = opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx];
  3116. auto U = oldCI->user_begin();
  3117. Value *user = *U;
  3118. CallInst *secSub = cast<CallInst>(user);
  3119. unsigned idxOpIndex = HLOperandIndex::kSubscriptIndexOpIdx;
  3120. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  3121. idxOpIndex--;
  3122. Value *idx = secSub->getArgOperand(idxOpIndex);
  3123. DXASSERT(secSub->hasOneUse(), "subscript should only has one use");
  3124. // Add the sampleIdx or mipLevel parameter to the end.
  3125. opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx] = idx;
  3126. opcodeParamList.emplace_back(mipIdx);
  3127. // Insert new call before secSub to make sure idx is ready to use.
  3128. Builder.SetInsertPoint(secSub);
  3129. }
  3130. for (unsigned i = 1; i < opcodeParamList.size(); i++) {
  3131. Value *arg = opcodeParamList[i];
  3132. llvm::Type *Ty = arg->getType();
  3133. if (Ty->isPointerTy()) {
  3134. Ty = Ty->getPointerElementType();
  3135. if (HLModule::IsHLSLObjectType(Ty) &&
  3136. // StreamOutput don't need handle.
  3137. !HLModule::IsStreamOutputType(Ty)) {
  3138. // Use object type directly, not by pointer.
  3139. // This will make sure temp object variable only used by ld/st.
  3140. if (GEPOperator *argGEP = dyn_cast<GEPOperator>(arg)) {
  3141. std::vector<Value*> idxList(argGEP->idx_begin(), argGEP->idx_end());
  3142. // Create instruction to avoid GEPOperator.
  3143. GetElementPtrInst *GEP = GetElementPtrInst::CreateInBounds(argGEP->getPointerOperand(),
  3144. idxList);
  3145. Builder.Insert(GEP);
  3146. arg = GEP;
  3147. }
  3148. Value *Handle = CreateHandleFromResPtr(arg, HLM, HandleTy,
  3149. resMetaMap, Builder);
  3150. opcodeParamList[i] = Handle;
  3151. }
  3152. }
  3153. }
  3154. Value *CI = Builder.CreateCall(opFunc, opcodeParamList);
  3155. if (!isDoubleSubscriptFunc) {
  3156. // replace new call and delete the old call
  3157. oldCI->replaceAllUsesWith(CI);
  3158. oldCI->eraseFromParent();
  3159. } else {
  3160. // For double script.
  3161. // Replace single users use with new CI.
  3162. auto U = oldCI->user_begin();
  3163. Value *user = *U;
  3164. CallInst *secSub = cast<CallInst>(user);
  3165. secSub->replaceAllUsesWith(CI);
  3166. secSub->eraseFromParent();
  3167. oldCI->eraseFromParent();
  3168. }
  3169. }
  3170. // delete the function
  3171. F->eraseFromParent();
  3172. }
  3173. static void AddOpcodeParamForIntrinsics(HLModule &HLM
  3174. , std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  3175. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  3176. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  3177. for (auto mapIter : intrinsicMap) {
  3178. Function *F = mapIter.first;
  3179. if (F->user_empty()) {
  3180. // delete the function
  3181. F->eraseFromParent();
  3182. continue;
  3183. }
  3184. unsigned opcode = mapIter.second;
  3185. AddOpcodeParamForIntrinsic(HLM, F, opcode, HandleTy, resMetaMap);
  3186. }
  3187. }
  3188. static Value *CastLdValue(Value *Ptr, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3189. if (ToTy->isVectorTy()) {
  3190. unsigned vecSize = ToTy->getVectorNumElements();
  3191. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3192. Value *V = Builder.CreateLoad(Ptr);
  3193. // ScalarToVec1Splat
  3194. // Change scalar into vec1.
  3195. Value *Vec1 = UndefValue::get(ToTy);
  3196. return Builder.CreateInsertElement(Vec1, V, (uint64_t)0);
  3197. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3198. Value *V = Builder.CreateLoad(Ptr);
  3199. // VectorTrunc
  3200. // Change vector into vec1.
  3201. int mask[] = {0};
  3202. return Builder.CreateShuffleVector(V, V, mask);
  3203. } else if (FromTy->isArrayTy()) {
  3204. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3205. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3206. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3207. // ArrayToVector.
  3208. Value *NewLd = UndefValue::get(ToTy);
  3209. Value *zeroIdx = Builder.getInt32(0);
  3210. for (unsigned i = 0; i < vecSize; i++) {
  3211. Value *GEP = Builder.CreateInBoundsGEP(
  3212. Ptr, {zeroIdx, Builder.getInt32(i)});
  3213. Value *Elt = Builder.CreateLoad(GEP);
  3214. NewLd = Builder.CreateInsertElement(NewLd, Elt, i);
  3215. }
  3216. return NewLd;
  3217. }
  3218. }
  3219. } else if (FromTy == Builder.getInt1Ty()) {
  3220. Value *V = Builder.CreateLoad(Ptr);
  3221. // BoolCast
  3222. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3223. return Builder.CreateZExt(V, ToTy);
  3224. }
  3225. return nullptr;
  3226. }
  3227. static Value *CastStValue(Value *Ptr, Value *V, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3228. if (ToTy->isVectorTy()) {
  3229. unsigned vecSize = ToTy->getVectorNumElements();
  3230. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3231. // ScalarToVec1Splat
  3232. // Change vec1 back to scalar.
  3233. Value *Elt = Builder.CreateExtractElement(V, (uint64_t)0);
  3234. return Elt;
  3235. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3236. // VectorTrunc
  3237. // Change vec1 into vector.
  3238. // Should not happen.
  3239. // Reported error at Sema::ImpCastExprToType.
  3240. DXASSERT_NOMSG(0);
  3241. } else if (FromTy->isArrayTy()) {
  3242. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3243. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3244. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3245. // ArrayToVector.
  3246. Value *zeroIdx = Builder.getInt32(0);
  3247. for (unsigned i = 0; i < vecSize; i++) {
  3248. Value *Elt = Builder.CreateExtractElement(V, i);
  3249. Value *GEP = Builder.CreateInBoundsGEP(
  3250. Ptr, {zeroIdx, Builder.getInt32(i)});
  3251. Builder.CreateStore(Elt, GEP);
  3252. }
  3253. // The store already done.
  3254. // Return null to ignore use of the return value.
  3255. return nullptr;
  3256. }
  3257. }
  3258. } else if (FromTy == Builder.getInt1Ty()) {
  3259. // BoolCast
  3260. // Change i1 to ToTy.
  3261. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3262. Value *CastV = Builder.CreateICmpNE(V, ConstantInt::get(V->getType(), 0));
  3263. return CastV;
  3264. }
  3265. return nullptr;
  3266. }
  3267. static bool SimplifyBitCastLoad(LoadInst *LI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3268. IRBuilder<> Builder(LI);
  3269. // Cast FromLd to ToTy.
  3270. Value *CastV = CastLdValue(Ptr, FromTy, ToTy, Builder);
  3271. if (CastV) {
  3272. LI->replaceAllUsesWith(CastV);
  3273. return true;
  3274. } else {
  3275. return false;
  3276. }
  3277. }
  3278. static bool SimplifyBitCastStore(StoreInst *SI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3279. IRBuilder<> Builder(SI);
  3280. Value *V = SI->getValueOperand();
  3281. // Cast Val to FromTy.
  3282. Value *CastV = CastStValue(Ptr, V, FromTy, ToTy, Builder);
  3283. if (CastV) {
  3284. Builder.CreateStore(CastV, Ptr);
  3285. return true;
  3286. } else {
  3287. return false;
  3288. }
  3289. }
  3290. static bool SimplifyBitCastGEP(GEPOperator *GEP, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3291. if (ToTy->isVectorTy()) {
  3292. unsigned vecSize = ToTy->getVectorNumElements();
  3293. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3294. // ScalarToVec1Splat
  3295. GEP->replaceAllUsesWith(Ptr);
  3296. return true;
  3297. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3298. // VectorTrunc
  3299. DXASSERT_NOMSG(
  3300. !isa<llvm::VectorType>(GEP->getType()->getPointerElementType()));
  3301. IRBuilder<> Builder(FromTy->getContext());
  3302. if (Instruction *I = dyn_cast<Instruction>(GEP))
  3303. Builder.SetInsertPoint(I);
  3304. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  3305. Value *NewGEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  3306. GEP->replaceAllUsesWith(NewGEP);
  3307. return true;
  3308. } else if (FromTy->isArrayTy()) {
  3309. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3310. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3311. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3312. // ArrayToVector.
  3313. }
  3314. }
  3315. } else if (FromTy == llvm::Type::getInt1Ty(FromTy->getContext())) {
  3316. // BoolCast
  3317. }
  3318. return false;
  3319. }
  3320. typedef SmallPtrSet<Instruction *, 4> SmallInstSet;
  3321. static void SimplifyBitCast(BitCastOperator *BC, SmallInstSet &deadInsts) {
  3322. Value *Ptr = BC->getOperand(0);
  3323. llvm::Type *FromTy = Ptr->getType();
  3324. llvm::Type *ToTy = BC->getType();
  3325. if (!FromTy->isPointerTy() || !ToTy->isPointerTy())
  3326. return;
  3327. FromTy = FromTy->getPointerElementType();
  3328. ToTy = ToTy->getPointerElementType();
  3329. // Take care case like %2 = bitcast %struct.T* %1 to <1 x float>*.
  3330. if (FromTy->isStructTy()) {
  3331. IRBuilder<> Builder(FromTy->getContext());
  3332. if (Instruction *I = dyn_cast<Instruction>(BC))
  3333. Builder.SetInsertPoint(I);
  3334. Value *zeroIdx = Builder.getInt32(0);
  3335. unsigned nestLevel = 1;
  3336. while (llvm::StructType *ST = dyn_cast<llvm::StructType>(FromTy)) {
  3337. FromTy = ST->getElementType(0);
  3338. nestLevel++;
  3339. }
  3340. std::vector<Value *> idxList(nestLevel, zeroIdx);
  3341. Ptr = Builder.CreateGEP(Ptr, idxList);
  3342. }
  3343. for (User *U : BC->users()) {
  3344. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  3345. if (SimplifyBitCastLoad(LI, FromTy, ToTy, Ptr)) {
  3346. LI->dropAllReferences();
  3347. deadInsts.insert(LI);
  3348. }
  3349. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  3350. if (SimplifyBitCastStore(SI, FromTy, ToTy, Ptr)) {
  3351. SI->dropAllReferences();
  3352. deadInsts.insert(SI);
  3353. }
  3354. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3355. if (SimplifyBitCastGEP(GEP, FromTy, ToTy, Ptr))
  3356. if (Instruction *I = dyn_cast<Instruction>(GEP)) {
  3357. I->dropAllReferences();
  3358. deadInsts.insert(I);
  3359. }
  3360. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  3361. // Skip function call.
  3362. } else if (BitCastInst *Cast = dyn_cast<BitCastInst>(U)) {
  3363. // Skip bitcast.
  3364. } else {
  3365. DXASSERT(0, "not support yet");
  3366. }
  3367. }
  3368. }
  3369. typedef float(__cdecl *FloatUnaryEvalFuncType)(float);
  3370. typedef double(__cdecl *DoubleUnaryEvalFuncType)(double);
  3371. typedef float(__cdecl *FloatBinaryEvalFuncType)(float, float);
  3372. typedef double(__cdecl *DoubleBinaryEvalFuncType)(double, double);
  3373. static Value * EvalUnaryIntrinsic(ConstantFP *fpV,
  3374. FloatUnaryEvalFuncType floatEvalFunc,
  3375. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3376. llvm::Type *Ty = fpV->getType();
  3377. Value *Result = nullptr;
  3378. if (Ty->isDoubleTy()) {
  3379. double dV = fpV->getValueAPF().convertToDouble();
  3380. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV));
  3381. Result = dResult;
  3382. } else {
  3383. DXASSERT_NOMSG(Ty->isFloatTy());
  3384. float fV = fpV->getValueAPF().convertToFloat();
  3385. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV));
  3386. Result = dResult;
  3387. }
  3388. return Result;
  3389. }
  3390. static Value * EvalBinaryIntrinsic(ConstantFP *fpV0, ConstantFP *fpV1,
  3391. FloatBinaryEvalFuncType floatEvalFunc,
  3392. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3393. llvm::Type *Ty = fpV0->getType();
  3394. Value *Result = nullptr;
  3395. if (Ty->isDoubleTy()) {
  3396. double dV0 = fpV0->getValueAPF().convertToDouble();
  3397. double dV1 = fpV1->getValueAPF().convertToDouble();
  3398. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV0, dV1));
  3399. Result = dResult;
  3400. } else {
  3401. DXASSERT_NOMSG(Ty->isFloatTy());
  3402. float fV0 = fpV0->getValueAPF().convertToFloat();
  3403. float fV1 = fpV1->getValueAPF().convertToFloat();
  3404. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV0, fV1));
  3405. Result = dResult;
  3406. }
  3407. return Result;
  3408. }
  3409. static Value * EvalUnaryIntrinsic(CallInst *CI,
  3410. FloatUnaryEvalFuncType floatEvalFunc,
  3411. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3412. Value *V = CI->getArgOperand(0);
  3413. llvm::Type *Ty = CI->getType();
  3414. Value *Result = nullptr;
  3415. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  3416. Result = UndefValue::get(Ty);
  3417. Constant *CV = cast<Constant>(V);
  3418. IRBuilder<> Builder(CI);
  3419. for (unsigned i=0;i<VT->getNumElements();i++) {
  3420. ConstantFP *fpV = cast<ConstantFP>(CV->getAggregateElement(i));
  3421. Value *EltResult = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  3422. Result = Builder.CreateInsertElement(Result, EltResult, i);
  3423. }
  3424. } else {
  3425. ConstantFP *fpV = cast<ConstantFP>(V);
  3426. Result = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  3427. }
  3428. CI->replaceAllUsesWith(Result);
  3429. CI->eraseFromParent();
  3430. return Result;
  3431. }
  3432. static Value * EvalBinaryIntrinsic(CallInst *CI,
  3433. FloatBinaryEvalFuncType floatEvalFunc,
  3434. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3435. Value *V0 = CI->getArgOperand(0);
  3436. Value *V1 = CI->getArgOperand(1);
  3437. llvm::Type *Ty = CI->getType();
  3438. Value *Result = nullptr;
  3439. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  3440. Result = UndefValue::get(Ty);
  3441. Constant *CV0 = cast<Constant>(V0);
  3442. Constant *CV1 = cast<Constant>(V1);
  3443. IRBuilder<> Builder(CI);
  3444. for (unsigned i=0;i<VT->getNumElements();i++) {
  3445. ConstantFP *fpV0 = cast<ConstantFP>(CV0->getAggregateElement(i));
  3446. ConstantFP *fpV1 = cast<ConstantFP>(CV1->getAggregateElement(i));
  3447. Value *EltResult = EvalBinaryIntrinsic(fpV0, fpV1, floatEvalFunc, doubleEvalFunc);
  3448. Result = Builder.CreateInsertElement(Result, EltResult, i);
  3449. }
  3450. } else {
  3451. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3452. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3453. Result = EvalBinaryIntrinsic(fpV0, fpV1, floatEvalFunc, doubleEvalFunc);
  3454. }
  3455. CI->replaceAllUsesWith(Result);
  3456. CI->eraseFromParent();
  3457. return Result;
  3458. CI->eraseFromParent();
  3459. return Result;
  3460. }
  3461. static Value * TryEvalIntrinsic(CallInst *CI, IntrinsicOp intriOp) {
  3462. switch (intriOp) {
  3463. case IntrinsicOp::IOP_tan: {
  3464. return EvalUnaryIntrinsic(CI, tanf, tan);
  3465. } break;
  3466. case IntrinsicOp::IOP_tanh: {
  3467. return EvalUnaryIntrinsic(CI, tanhf, tanh);
  3468. } break;
  3469. case IntrinsicOp::IOP_sin: {
  3470. return EvalUnaryIntrinsic(CI, sinf, sin);
  3471. } break;
  3472. case IntrinsicOp::IOP_sinh: {
  3473. return EvalUnaryIntrinsic(CI, sinhf, sinh);
  3474. } break;
  3475. case IntrinsicOp::IOP_cos: {
  3476. return EvalUnaryIntrinsic(CI, cosf, cos);
  3477. } break;
  3478. case IntrinsicOp::IOP_cosh: {
  3479. return EvalUnaryIntrinsic(CI, coshf, cosh);
  3480. } break;
  3481. case IntrinsicOp::IOP_asin: {
  3482. return EvalUnaryIntrinsic(CI, asinf, asin);
  3483. } break;
  3484. case IntrinsicOp::IOP_acos: {
  3485. return EvalUnaryIntrinsic(CI, acosf, acos);
  3486. } break;
  3487. case IntrinsicOp::IOP_atan: {
  3488. return EvalUnaryIntrinsic(CI, atanf, atan);
  3489. } break;
  3490. case IntrinsicOp::IOP_atan2: {
  3491. Value *V0 = CI->getArgOperand(0);
  3492. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3493. Value *V1 = CI->getArgOperand(1);
  3494. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3495. llvm::Type *Ty = CI->getType();
  3496. Value *Result = nullptr;
  3497. if (Ty->isDoubleTy()) {
  3498. double dV0 = fpV0->getValueAPF().convertToDouble();
  3499. double dV1 = fpV1->getValueAPF().convertToDouble();
  3500. Value *atanV = ConstantFP::get(CI->getType(), atan(dV0 / dV1));
  3501. CI->replaceAllUsesWith(atanV);
  3502. Result = atanV;
  3503. } else {
  3504. DXASSERT_NOMSG(Ty->isFloatTy());
  3505. float fV0 = fpV0->getValueAPF().convertToFloat();
  3506. float fV1 = fpV1->getValueAPF().convertToFloat();
  3507. Value *atanV = ConstantFP::get(CI->getType(), atanf(fV0 / fV1));
  3508. CI->replaceAllUsesWith(atanV);
  3509. Result = atanV;
  3510. }
  3511. CI->eraseFromParent();
  3512. return Result;
  3513. } break;
  3514. case IntrinsicOp::IOP_sqrt: {
  3515. return EvalUnaryIntrinsic(CI, sqrtf, sqrt);
  3516. } break;
  3517. case IntrinsicOp::IOP_rsqrt: {
  3518. auto rsqrtF = [](float v) -> float { return 1.0 / sqrtf(v); };
  3519. auto rsqrtD = [](double v) -> double { return 1.0 / sqrt(v); };
  3520. return EvalUnaryIntrinsic(CI, rsqrtF, rsqrtD);
  3521. } break;
  3522. case IntrinsicOp::IOP_exp: {
  3523. return EvalUnaryIntrinsic(CI, expf, exp);
  3524. } break;
  3525. case IntrinsicOp::IOP_exp2: {
  3526. return EvalUnaryIntrinsic(CI, exp2f, exp2);
  3527. } break;
  3528. case IntrinsicOp::IOP_log: {
  3529. return EvalUnaryIntrinsic(CI, logf, log);
  3530. } break;
  3531. case IntrinsicOp::IOP_log10: {
  3532. return EvalUnaryIntrinsic(CI, log10f, log10);
  3533. } break;
  3534. case IntrinsicOp::IOP_log2: {
  3535. return EvalUnaryIntrinsic(CI, log2f, log2);
  3536. } break;
  3537. case IntrinsicOp::IOP_pow: {
  3538. return EvalBinaryIntrinsic(CI, powf, pow);
  3539. } break;
  3540. case IntrinsicOp::IOP_max: {
  3541. auto maxF = [](float a, float b) -> float { return a > b ? a:b; };
  3542. auto maxD = [](double a, double b) -> double { return a > b ? a:b; };
  3543. return EvalBinaryIntrinsic(CI, maxF, maxD);
  3544. } break;
  3545. case IntrinsicOp::IOP_min: {
  3546. auto minF = [](float a, float b) -> float { return a < b ? a:b; };
  3547. auto minD = [](double a, double b) -> double { return a < b ? a:b; };
  3548. return EvalBinaryIntrinsic(CI, minF, minD);
  3549. } break;
  3550. case IntrinsicOp::IOP_rcp: {
  3551. auto rcpF = [](float v) -> float { return 1.0 / v; };
  3552. auto rcpD = [](double v) -> double { return 1.0 / v; };
  3553. return EvalUnaryIntrinsic(CI, rcpF, rcpD);
  3554. } break;
  3555. case IntrinsicOp::IOP_ceil: {
  3556. return EvalUnaryIntrinsic(CI, ceilf, ceil);
  3557. } break;
  3558. case IntrinsicOp::IOP_floor: {
  3559. return EvalUnaryIntrinsic(CI, floorf, floor);
  3560. } break;
  3561. case IntrinsicOp::IOP_round: {
  3562. return EvalUnaryIntrinsic(CI, roundf, round);
  3563. } break;
  3564. case IntrinsicOp::IOP_trunc: {
  3565. return EvalUnaryIntrinsic(CI, truncf, trunc);
  3566. } break;
  3567. case IntrinsicOp::IOP_frac: {
  3568. auto fracF = [](float v) -> float {
  3569. int exp = 0;
  3570. return frexpf(v, &exp);
  3571. };
  3572. auto fracD = [](double v) -> double {
  3573. int exp = 0;
  3574. return frexp(v, &exp);
  3575. };
  3576. return EvalUnaryIntrinsic(CI, fracF, fracD);
  3577. } break;
  3578. case IntrinsicOp::IOP_isnan: {
  3579. Value *V = CI->getArgOperand(0);
  3580. ConstantFP *fV = cast<ConstantFP>(V);
  3581. bool isNan = fV->getValueAPF().isNaN();
  3582. Constant *cNan = ConstantInt::get(CI->getType(), isNan ? 1 : 0);
  3583. CI->replaceAllUsesWith(cNan);
  3584. CI->eraseFromParent();
  3585. return cNan;
  3586. } break;
  3587. default:
  3588. return nullptr;
  3589. }
  3590. }
  3591. static void SimpleTransformForHLDXIR(Instruction *I,
  3592. SmallInstSet &deadInsts) {
  3593. unsigned opcode = I->getOpcode();
  3594. switch (opcode) {
  3595. case Instruction::BitCast: {
  3596. BitCastOperator *BCI = cast<BitCastOperator>(I);
  3597. SimplifyBitCast(BCI, deadInsts);
  3598. } break;
  3599. case Instruction::Load: {
  3600. LoadInst *ldInst = cast<LoadInst>(I);
  3601. DXASSERT(!HLMatrixLower::IsMatrixType(ldInst->getType()),
  3602. "matrix load should use HL LdStMatrix");
  3603. Value *Ptr = ldInst->getPointerOperand();
  3604. if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(Ptr)) {
  3605. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3606. SimplifyBitCast(BCO, deadInsts);
  3607. }
  3608. }
  3609. } break;
  3610. case Instruction::Store: {
  3611. StoreInst *stInst = cast<StoreInst>(I);
  3612. Value *V = stInst->getValueOperand();
  3613. DXASSERT_LOCALVAR(V, !HLMatrixLower::IsMatrixType(V->getType()),
  3614. "matrix store should use HL LdStMatrix");
  3615. Value *Ptr = stInst->getPointerOperand();
  3616. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  3617. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3618. SimplifyBitCast(BCO, deadInsts);
  3619. }
  3620. }
  3621. } break;
  3622. case Instruction::LShr:
  3623. case Instruction::AShr:
  3624. case Instruction::Shl: {
  3625. llvm::BinaryOperator *BO = cast<llvm::BinaryOperator>(I);
  3626. Value *op2 = BO->getOperand(1);
  3627. IntegerType *Ty = cast<IntegerType>(BO->getType()->getScalarType());
  3628. unsigned bitWidth = Ty->getBitWidth();
  3629. // Clamp op2 to 0 ~ bitWidth-1
  3630. if (ConstantInt *cOp2 = dyn_cast<ConstantInt>(op2)) {
  3631. unsigned iOp2 = cOp2->getLimitedValue();
  3632. unsigned clampedOp2 = iOp2 & (bitWidth - 1);
  3633. if (iOp2 != clampedOp2) {
  3634. BO->setOperand(1, ConstantInt::get(op2->getType(), clampedOp2));
  3635. }
  3636. } else {
  3637. Value *mask = ConstantInt::get(op2->getType(), bitWidth - 1);
  3638. IRBuilder<> Builder(I);
  3639. op2 = Builder.CreateAnd(op2, mask);
  3640. BO->setOperand(1, op2);
  3641. }
  3642. } break;
  3643. }
  3644. }
  3645. // Do simple transform to make later lower pass easier.
  3646. static void SimpleTransformForHLDXIR(llvm::Module *pM) {
  3647. SmallInstSet deadInsts;
  3648. for (Function &F : pM->functions()) {
  3649. for (BasicBlock &BB : F.getBasicBlockList()) {
  3650. for (BasicBlock::iterator Iter = BB.begin(); Iter != BB.end(); ) {
  3651. Instruction *I = (Iter++);
  3652. if (deadInsts.count(I))
  3653. continue; // Skip dead instructions
  3654. SimpleTransformForHLDXIR(I, deadInsts);
  3655. }
  3656. }
  3657. }
  3658. for (Instruction * I : deadInsts)
  3659. I->dropAllReferences();
  3660. for (Instruction * I : deadInsts)
  3661. I->eraseFromParent();
  3662. deadInsts.clear();
  3663. for (GlobalVariable &GV : pM->globals()) {
  3664. if (dxilutil::IsStaticGlobal(&GV)) {
  3665. for (User *U : GV.users()) {
  3666. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(U)) {
  3667. SimplifyBitCast(BCO, deadInsts);
  3668. }
  3669. }
  3670. }
  3671. }
  3672. for (Instruction * I : deadInsts)
  3673. I->dropAllReferences();
  3674. for (Instruction * I : deadInsts)
  3675. I->eraseFromParent();
  3676. }
  3677. // Clone shader entry function to be called by other functions.
  3678. // The original function will be used as shader entry.
  3679. static void CloneShaderEntry(Function *ShaderF, StringRef EntryName,
  3680. HLModule &HLM) {
  3681. // Use mangled name for cloned one.
  3682. Function *F = Function::Create(ShaderF->getFunctionType(),
  3683. GlobalValue::LinkageTypes::ExternalLinkage,
  3684. "", HLM.GetModule());
  3685. F->takeName(ShaderF);
  3686. // Set to name before mangled.
  3687. ShaderF->setName(EntryName);
  3688. SmallVector<ReturnInst *, 2> Returns;
  3689. ValueToValueMapTy vmap;
  3690. // Map params.
  3691. auto entryParamIt = F->arg_begin();
  3692. for (Argument &param : ShaderF->args()) {
  3693. vmap[&param] = (entryParamIt++);
  3694. }
  3695. llvm::CloneFunctionInto(F, ShaderF, vmap, /*ModuleLevelChagnes*/ false,
  3696. Returns);
  3697. // Copy function annotation.
  3698. DxilFunctionAnnotation *shaderAnnot = HLM.GetFunctionAnnotation(ShaderF);
  3699. DxilFunctionAnnotation *annot = HLM.AddFunctionAnnotation(F);
  3700. DxilParameterAnnotation &retAnnot = shaderAnnot->GetRetTypeAnnotation();
  3701. DxilParameterAnnotation &cloneRetAnnot = annot->GetRetTypeAnnotation();
  3702. cloneRetAnnot = retAnnot;
  3703. // Clear semantic for cloned one.
  3704. cloneRetAnnot.SetSemanticString("");
  3705. cloneRetAnnot.SetSemanticIndexVec({});
  3706. for (unsigned i = 0; i < shaderAnnot->GetNumParameters(); i++) {
  3707. DxilParameterAnnotation &cloneParamAnnot = annot->GetParameterAnnotation(i);
  3708. DxilParameterAnnotation &paramAnnot =
  3709. shaderAnnot->GetParameterAnnotation(i);
  3710. cloneParamAnnot = paramAnnot;
  3711. // Clear semantic for cloned one.
  3712. cloneParamAnnot.SetSemanticString("");
  3713. cloneParamAnnot.SetSemanticIndexVec({});
  3714. }
  3715. }
  3716. // For case like:
  3717. //cbuffer A {
  3718. // float a;
  3719. // int b;
  3720. //}
  3721. //
  3722. //const static struct {
  3723. // float a;
  3724. // int b;
  3725. //} ST = { a, b };
  3726. // Replace user of ST with a and b.
  3727. static bool ReplaceConstStaticGlobalUser(GEPOperator *GEP,
  3728. std::vector<Constant *> &InitList,
  3729. IRBuilder<> &Builder) {
  3730. if (GEP->getNumIndices() < 2) {
  3731. // Don't use sub element.
  3732. return false;
  3733. }
  3734. SmallVector<Value *, 4> idxList;
  3735. auto iter = GEP->idx_begin();
  3736. idxList.emplace_back(*(iter++));
  3737. ConstantInt *subIdx = dyn_cast<ConstantInt>(*(iter++));
  3738. DXASSERT(subIdx, "else dynamic indexing on struct field");
  3739. unsigned subIdxImm = subIdx->getLimitedValue();
  3740. DXASSERT(subIdxImm < InitList.size(), "else struct index out of bound");
  3741. Constant *subPtr = InitList[subIdxImm];
  3742. // Move every idx to idxList except idx for InitList.
  3743. while (iter != GEP->idx_end()) {
  3744. idxList.emplace_back(*(iter++));
  3745. }
  3746. Value *NewGEP = Builder.CreateGEP(subPtr, idxList);
  3747. GEP->replaceAllUsesWith(NewGEP);
  3748. return true;
  3749. }
  3750. static void ReplaceConstStaticGlobals(
  3751. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  3752. &staticConstGlobalInitListMap,
  3753. std::unordered_map<GlobalVariable *, Function *>
  3754. &staticConstGlobalCtorMap) {
  3755. for (auto &iter : staticConstGlobalInitListMap) {
  3756. GlobalVariable *GV = iter.first;
  3757. std::vector<Constant *> &InitList = iter.second;
  3758. LLVMContext &Ctx = GV->getContext();
  3759. // Do the replace.
  3760. bool bPass = true;
  3761. for (User *U : GV->users()) {
  3762. IRBuilder<> Builder(Ctx);
  3763. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
  3764. Builder.SetInsertPoint(GEPInst);
  3765. bPass &= ReplaceConstStaticGlobalUser(cast<GEPOperator>(GEPInst), InitList, Builder);
  3766. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3767. bPass &= ReplaceConstStaticGlobalUser(GEP, InitList, Builder);
  3768. } else {
  3769. DXASSERT(false, "invalid user of const static global");
  3770. }
  3771. }
  3772. // Clear the Ctor which is useless now.
  3773. if (bPass) {
  3774. Function *Ctor = staticConstGlobalCtorMap[GV];
  3775. Ctor->getBasicBlockList().clear();
  3776. BasicBlock *Entry = BasicBlock::Create(Ctx, "", Ctor);
  3777. IRBuilder<> Builder(Entry);
  3778. Builder.CreateRetVoid();
  3779. }
  3780. }
  3781. }
  3782. bool BuildImmInit(Function *Ctor) {
  3783. GlobalVariable *GV = nullptr;
  3784. SmallVector<Constant *, 4> ImmList;
  3785. bool allConst = true;
  3786. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  3787. if (StoreInst *SI = dyn_cast<StoreInst>(&(*I))) {
  3788. Value *V = SI->getValueOperand();
  3789. if (!isa<Constant>(V) || V->getType()->isPointerTy()) {
  3790. allConst = false;
  3791. break;
  3792. }
  3793. ImmList.emplace_back(cast<Constant>(V));
  3794. Value *Ptr = SI->getPointerOperand();
  3795. if (GEPOperator *GepOp = dyn_cast<GEPOperator>(Ptr)) {
  3796. Ptr = GepOp->getPointerOperand();
  3797. if (GlobalVariable *pGV = dyn_cast<GlobalVariable>(Ptr)) {
  3798. if (GV == nullptr)
  3799. GV = pGV;
  3800. else
  3801. DXASSERT(GV == pGV, "else pointer mismatch");
  3802. }
  3803. }
  3804. } else {
  3805. if (!isa<ReturnInst>(*I)) {
  3806. allConst = false;
  3807. break;
  3808. }
  3809. }
  3810. }
  3811. if (!allConst)
  3812. return false;
  3813. if (!GV)
  3814. return false;
  3815. llvm::Type *Ty = GV->getType()->getElementType();
  3816. llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty);
  3817. // TODO: support other types.
  3818. if (!AT)
  3819. return false;
  3820. if (ImmList.size() != AT->getNumElements())
  3821. return false;
  3822. Constant *Init = llvm::ConstantArray::get(AT, ImmList);
  3823. GV->setInitializer(Init);
  3824. return true;
  3825. }
  3826. void ProcessCtorFunctions(llvm::Module &M, StringRef globalName,
  3827. Instruction *InsertPt) {
  3828. // add global call to entry func
  3829. GlobalVariable *GV = M.getGlobalVariable(globalName);
  3830. if (GV) {
  3831. if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
  3832. IRBuilder<> Builder(InsertPt);
  3833. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
  3834. ++i) {
  3835. if (isa<ConstantAggregateZero>(*i))
  3836. continue;
  3837. ConstantStruct *CS = cast<ConstantStruct>(*i);
  3838. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  3839. continue;
  3840. // Must have a function or null ptr.
  3841. if (!isa<Function>(CS->getOperand(1)))
  3842. continue;
  3843. Function *Ctor = cast<Function>(CS->getOperand(1));
  3844. DXASSERT(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0,
  3845. "function type must be void (void)");
  3846. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E;
  3847. ++I) {
  3848. if (CallInst *CI = dyn_cast<CallInst>(&(*I))) {
  3849. Function *F = CI->getCalledFunction();
  3850. // Try to build imm initilizer.
  3851. // If not work, add global call to entry func.
  3852. if (BuildImmInit(F) == false) {
  3853. Builder.CreateCall(F);
  3854. }
  3855. } else {
  3856. DXASSERT(isa<ReturnInst>(&(*I)),
  3857. "else invalid Global constructor function");
  3858. }
  3859. }
  3860. }
  3861. // remove the GV
  3862. GV->eraseFromParent();
  3863. }
  3864. }
  3865. }
  3866. void CGMSHLSLRuntime::SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc) {
  3867. auto AttrsIter = HSEntryPatchConstantFuncAttr.find(EntryFunc.Func);
  3868. DXASSERT(AttrsIter != HSEntryPatchConstantFuncAttr.end(),
  3869. "we have checked this in AddHLSLFunctionInfo()");
  3870. SetPatchConstantFunctionWithAttr(Entry, AttrsIter->second);
  3871. }
  3872. void CGMSHLSLRuntime::SetPatchConstantFunctionWithAttr(
  3873. const EntryFunctionInfo &EntryFunc,
  3874. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr) {
  3875. StringRef funcName = PatchConstantFuncAttr->getFunctionName();
  3876. auto Entry = patchConstantFunctionMap.find(funcName);
  3877. if (Entry == patchConstantFunctionMap.end()) {
  3878. DiagnosticsEngine &Diags = CGM.getDiags();
  3879. unsigned DiagID =
  3880. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3881. "Cannot find patchconstantfunc %0.");
  3882. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  3883. << funcName;
  3884. return;
  3885. }
  3886. if (Entry->second.NumOverloads != 1) {
  3887. DiagnosticsEngine &Diags = CGM.getDiags();
  3888. unsigned DiagID =
  3889. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  3890. "Multiple overloads of patchconstantfunc %0.");
  3891. unsigned NoteID =
  3892. Diags.getCustomDiagID(DiagnosticsEngine::Note,
  3893. "This overload was selected.");
  3894. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  3895. << funcName;
  3896. Diags.Report(Entry->second.SL, NoteID);
  3897. }
  3898. Function *patchConstFunc = Entry->second.Func;
  3899. DXASSERT(m_pHLModule->HasDxilFunctionProps(EntryFunc.Func),
  3900. " else AddHLSLFunctionInfo did not save the dxil function props for the "
  3901. "HS entry.");
  3902. DxilFunctionProps *HSProps = &m_pHLModule->GetDxilFunctionProps(EntryFunc.Func);
  3903. m_pHLModule->SetPatchConstantFunctionForHS(EntryFunc.Func, patchConstFunc);
  3904. DXASSERT_NOMSG(patchConstantFunctionPropsMap.count(patchConstFunc));
  3905. // Check no inout parameter for patch constant function.
  3906. DxilFunctionAnnotation *patchConstFuncAnnotation =
  3907. m_pHLModule->GetFunctionAnnotation(patchConstFunc);
  3908. for (unsigned i = 0; i < patchConstFuncAnnotation->GetNumParameters(); i++) {
  3909. if (patchConstFuncAnnotation->GetParameterAnnotation(i)
  3910. .GetParamInputQual() == DxilParamInputQual::Inout) {
  3911. DiagnosticsEngine &Diags = CGM.getDiags();
  3912. unsigned DiagID = Diags.getCustomDiagID(
  3913. DiagnosticsEngine::Error,
  3914. "Patch Constant function %0 should not have inout param.");
  3915. Diags.Report(Entry->second.SL, DiagID) << funcName;
  3916. }
  3917. }
  3918. // Input/Output control point validation.
  3919. if (patchConstantFunctionPropsMap.count(patchConstFunc)) {
  3920. const DxilFunctionProps &patchProps =
  3921. *patchConstantFunctionPropsMap[patchConstFunc];
  3922. if (patchProps.ShaderProps.HS.inputControlPoints != 0 &&
  3923. patchProps.ShaderProps.HS.inputControlPoints !=
  3924. HSProps->ShaderProps.HS.inputControlPoints) {
  3925. DiagnosticsEngine &Diags = CGM.getDiags();
  3926. unsigned DiagID =
  3927. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3928. "Patch constant function's input patch input "
  3929. "should have %0 elements, but has %1.");
  3930. Diags.Report(Entry->second.SL, DiagID)
  3931. << HSProps->ShaderProps.HS.inputControlPoints
  3932. << patchProps.ShaderProps.HS.inputControlPoints;
  3933. }
  3934. if (patchProps.ShaderProps.HS.outputControlPoints != 0 &&
  3935. patchProps.ShaderProps.HS.outputControlPoints !=
  3936. HSProps->ShaderProps.HS.outputControlPoints) {
  3937. DiagnosticsEngine &Diags = CGM.getDiags();
  3938. unsigned DiagID = Diags.getCustomDiagID(
  3939. DiagnosticsEngine::Error,
  3940. "Patch constant function's output patch input "
  3941. "should have %0 elements, but has %1.");
  3942. Diags.Report(Entry->second.SL, DiagID)
  3943. << HSProps->ShaderProps.HS.outputControlPoints
  3944. << patchProps.ShaderProps.HS.outputControlPoints;
  3945. }
  3946. }
  3947. }
  3948. void CGMSHLSLRuntime::FinishCodeGen() {
  3949. // Library don't have entry.
  3950. if (!m_bIsLib) {
  3951. SetEntryFunction();
  3952. // If at this point we haven't determined the entry function it's an error.
  3953. if (m_pHLModule->GetEntryFunction() == nullptr) {
  3954. assert(CGM.getDiags().hasErrorOccurred() &&
  3955. "else SetEntryFunction should have reported this condition");
  3956. return;
  3957. }
  3958. if (m_pHLModule->GetShaderModel()->IsHS()) {
  3959. SetPatchConstantFunction(Entry);
  3960. }
  3961. } else {
  3962. for (auto &it : entryFunctionMap) {
  3963. // skip clone if RT entry
  3964. if (m_pHLModule->GetDxilFunctionProps(it.second.Func).IsRay())
  3965. continue;
  3966. CloneShaderEntry(it.second.Func, it.getKey(), *m_pHLModule);
  3967. auto AttrIter = HSEntryPatchConstantFuncAttr.find(it.second.Func);
  3968. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  3969. SetPatchConstantFunctionWithAttr(it.second, AttrIter->second);
  3970. }
  3971. }
  3972. }
  3973. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  3974. staticConstGlobalCtorMap);
  3975. // Create copy for clip plane.
  3976. for (Function *F : clipPlaneFuncList) {
  3977. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(F);
  3978. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  3979. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  3980. Value *clipPlane = props.ShaderProps.VS.clipPlanes[i];
  3981. if (!clipPlane)
  3982. continue;
  3983. if (m_bDebugInfo) {
  3984. Builder.SetCurrentDebugLocation(debugInfoMap[clipPlane]);
  3985. }
  3986. llvm::Type *Ty = clipPlane->getType()->getPointerElementType();
  3987. // Constant *zeroInit = ConstantFP::get(Ty, 0);
  3988. GlobalVariable *GV = new llvm::GlobalVariable(
  3989. TheModule, Ty, /*IsConstant*/ false, // constant false to store.
  3990. llvm::GlobalValue::ExternalLinkage,
  3991. /*InitVal*/ nullptr, Twine("SV_ClipPlane") + Twine(i));
  3992. Value *initVal = Builder.CreateLoad(clipPlane);
  3993. Builder.CreateStore(initVal, GV);
  3994. props.ShaderProps.VS.clipPlanes[i] = GV;
  3995. }
  3996. }
  3997. // Allocate constant buffers.
  3998. AllocateDxilConstantBuffers(m_pHLModule);
  3999. // TODO: create temp variable for constant which has store use.
  4000. // Create Global variable and type annotation for each CBuffer.
  4001. ConstructCBuffer(m_pHLModule, CBufferType, m_ConstVarAnnotationMap);
  4002. if (!m_bIsLib) {
  4003. // need this for "llvm.global_dtors"?
  4004. ProcessCtorFunctions(TheModule ,"llvm.global_ctors",
  4005. Entry.Func->getEntryBlock().getFirstInsertionPt());
  4006. }
  4007. // translate opcode into parameter for intrinsic functions
  4008. AddOpcodeParamForIntrinsics(*m_pHLModule, m_IntrinsicMap, resMetadataMap);
  4009. // Pin entry point and constant buffers, mark everything else internal.
  4010. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4011. if (!m_bIsLib) {
  4012. if (&f == m_pHLModule->GetEntryFunction() ||
  4013. IsPatchConstantFunction(&f) || f.isDeclaration()) {
  4014. f.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  4015. } else {
  4016. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  4017. }
  4018. }
  4019. // Skip no inline functions.
  4020. if (f.hasFnAttribute(llvm::Attribute::NoInline))
  4021. continue;
  4022. // Always inline for used functions.
  4023. if (!f.user_empty())
  4024. f.addFnAttr(llvm::Attribute::AlwaysInline);
  4025. }
  4026. // Do simple transform to make later lower pass easier.
  4027. SimpleTransformForHLDXIR(m_pHLModule->GetModule());
  4028. // Handle lang extensions if provided.
  4029. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  4030. // Add semantic defines for extensions if any are available.
  4031. HLSLExtensionsCodegenHelper::SemanticDefineErrorList errors =
  4032. CGM.getCodeGenOpts().HLSLExtensionsCodegen->WriteSemanticDefines(m_pHLModule->GetModule());
  4033. DiagnosticsEngine &Diags = CGM.getDiags();
  4034. for (const HLSLExtensionsCodegenHelper::SemanticDefineError& error : errors) {
  4035. DiagnosticsEngine::Level level = DiagnosticsEngine::Error;
  4036. if (error.IsWarning())
  4037. level = DiagnosticsEngine::Warning;
  4038. unsigned DiagID = Diags.getCustomDiagID(level, "%0");
  4039. Diags.Report(SourceLocation::getFromRawEncoding(error.Location()), DiagID) << error.Message();
  4040. }
  4041. // Add root signature from a #define. Overrides root signature in function attribute.
  4042. {
  4043. using Status = HLSLExtensionsCodegenHelper::CustomRootSignature::Status;
  4044. HLSLExtensionsCodegenHelper::CustomRootSignature customRootSig;
  4045. Status status = CGM.getCodeGenOpts().HLSLExtensionsCodegen->GetCustomRootSignature(&customRootSig);
  4046. if (status == Status::FOUND) {
  4047. CompileRootSignature(customRootSig.RootSignature, Diags,
  4048. SourceLocation::getFromRawEncoding(customRootSig.EncodedSourceLocation),
  4049. rootSigVer, &m_pHLModule->GetRootSignature());
  4050. }
  4051. }
  4052. }
  4053. // At this point, we have a high-level DXIL module - record this.
  4054. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit", "hlsl-hlensure");
  4055. }
  4056. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  4057. const FunctionDecl *FD,
  4058. const CallExpr *E,
  4059. ReturnValueSlot ReturnValue) {
  4060. StringRef name = FD->getName();
  4061. const Decl *TargetDecl = E->getCalleeDecl();
  4062. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  4063. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  4064. TargetDecl);
  4065. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  4066. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  4067. Function *F = CI->getCalledFunction();
  4068. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  4069. if (group == HLOpcodeGroup::HLIntrinsic) {
  4070. bool allOperandImm = true;
  4071. for (auto &operand : CI->arg_operands()) {
  4072. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand) ||
  4073. isa<ConstantAggregateZero>(operand) || isa<ConstantDataVector>(operand);
  4074. if (!isImm) {
  4075. allOperandImm = false;
  4076. break;
  4077. } else if (operand->getType()->isHalfTy()) {
  4078. // Not support half Eval yet.
  4079. allOperandImm = false;
  4080. break;
  4081. }
  4082. }
  4083. if (allOperandImm) {
  4084. unsigned intrinsicOpcode;
  4085. StringRef intrinsicGroup;
  4086. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  4087. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  4088. if (Value *Result = TryEvalIntrinsic(CI, opcode)) {
  4089. RV = RValue::get(Result);
  4090. }
  4091. }
  4092. }
  4093. }
  4094. }
  4095. return RV;
  4096. }
  4097. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  4098. switch (stmtClass) {
  4099. case Stmt::CStyleCastExprClass:
  4100. case Stmt::ImplicitCastExprClass:
  4101. case Stmt::CXXFunctionalCastExprClass:
  4102. return HLOpcodeGroup::HLCast;
  4103. case Stmt::InitListExprClass:
  4104. return HLOpcodeGroup::HLInit;
  4105. case Stmt::BinaryOperatorClass:
  4106. case Stmt::CompoundAssignOperatorClass:
  4107. return HLOpcodeGroup::HLBinOp;
  4108. case Stmt::UnaryOperatorClass:
  4109. return HLOpcodeGroup::HLUnOp;
  4110. case Stmt::ExtMatrixElementExprClass:
  4111. return HLOpcodeGroup::HLSubscript;
  4112. case Stmt::CallExprClass:
  4113. return HLOpcodeGroup::HLIntrinsic;
  4114. case Stmt::ConditionalOperatorClass:
  4115. return HLOpcodeGroup::HLSelect;
  4116. default:
  4117. llvm_unreachable("not support operation");
  4118. }
  4119. }
  4120. // NOTE: This table must match BinaryOperator::Opcode
  4121. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  4122. HLBinaryOpcode::Invalid, // PtrMemD
  4123. HLBinaryOpcode::Invalid, // PtrMemI
  4124. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  4125. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  4126. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  4127. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  4128. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  4129. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  4130. HLBinaryOpcode::Invalid, // Assign,
  4131. // The assign part is done by matrix store
  4132. HLBinaryOpcode::Mul, // MulAssign
  4133. HLBinaryOpcode::Div, // DivAssign
  4134. HLBinaryOpcode::Rem, // RemAssign
  4135. HLBinaryOpcode::Add, // AddAssign
  4136. HLBinaryOpcode::Sub, // SubAssign
  4137. HLBinaryOpcode::Shl, // ShlAssign
  4138. HLBinaryOpcode::Shr, // ShrAssign
  4139. HLBinaryOpcode::And, // AndAssign
  4140. HLBinaryOpcode::Xor, // XorAssign
  4141. HLBinaryOpcode::Or, // OrAssign
  4142. HLBinaryOpcode::Invalid, // Comma
  4143. };
  4144. // NOTE: This table must match UnaryOperator::Opcode
  4145. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  4146. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  4147. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  4148. HLUnaryOpcode::Invalid, // AddrOf,
  4149. HLUnaryOpcode::Invalid, // Deref,
  4150. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  4151. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  4152. HLUnaryOpcode::Invalid, // Real,
  4153. HLUnaryOpcode::Invalid, // Imag,
  4154. HLUnaryOpcode::Invalid, // Extension
  4155. };
  4156. static bool IsRowMajorMatrix(QualType Ty, bool bDefaultRowMajor) {
  4157. if (const AttributedType *AT = Ty->getAs<AttributedType>()) {
  4158. if (AT->getAttrKind() == AttributedType::attr_hlsl_row_major)
  4159. return true;
  4160. else if (AT->getAttrKind() == AttributedType::attr_hlsl_column_major)
  4161. return false;
  4162. else
  4163. return bDefaultRowMajor;
  4164. } else {
  4165. return bDefaultRowMajor;
  4166. }
  4167. }
  4168. static bool IsUnsigned(QualType Ty) {
  4169. Ty = Ty.getCanonicalType().getNonReferenceType();
  4170. if (hlsl::IsHLSLVecMatType(Ty))
  4171. Ty = CGHLSLRuntime::GetHLSLVecMatElementType(Ty);
  4172. if (Ty->isExtVectorType())
  4173. Ty = Ty->getAs<clang::ExtVectorType>()->getElementType();
  4174. return Ty->isUnsignedIntegerType();
  4175. }
  4176. static unsigned GetHLOpcode(const Expr *E) {
  4177. switch (E->getStmtClass()) {
  4178. case Stmt::CompoundAssignOperatorClass:
  4179. case Stmt::BinaryOperatorClass: {
  4180. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  4181. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  4182. if (HasUnsignedOpcode(binOpcode)) {
  4183. if (IsUnsigned(binOp->getLHS()->getType())) {
  4184. binOpcode = GetUnsignedOpcode(binOpcode);
  4185. }
  4186. }
  4187. return static_cast<unsigned>(binOpcode);
  4188. }
  4189. case Stmt::UnaryOperatorClass: {
  4190. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  4191. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  4192. return static_cast<unsigned>(unOpcode);
  4193. }
  4194. case Stmt::ImplicitCastExprClass:
  4195. case Stmt::CStyleCastExprClass: {
  4196. const CastExpr *CE = cast<CastExpr>(E);
  4197. bool toUnsigned = IsUnsigned(E->getType());
  4198. bool fromUnsigned = IsUnsigned(CE->getSubExpr()->getType());
  4199. if (toUnsigned && fromUnsigned)
  4200. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  4201. else if (toUnsigned)
  4202. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  4203. else if (fromUnsigned)
  4204. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  4205. else
  4206. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  4207. }
  4208. default:
  4209. return 0;
  4210. }
  4211. }
  4212. static Value *
  4213. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  4214. unsigned opcode, llvm::Type *RetType,
  4215. ArrayRef<Value *> paramList, llvm::Module &M) {
  4216. SmallVector<llvm::Type *, 4> paramTyList;
  4217. // Add the opcode param
  4218. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  4219. paramTyList.emplace_back(opcodeTy);
  4220. for (Value *param : paramList) {
  4221. paramTyList.emplace_back(param->getType());
  4222. }
  4223. llvm::FunctionType *funcTy =
  4224. llvm::FunctionType::get(RetType, paramTyList, false);
  4225. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  4226. SmallVector<Value *, 4> opcodeParamList;
  4227. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  4228. opcodeParamList.emplace_back(opcodeConst);
  4229. opcodeParamList.append(paramList.begin(), paramList.end());
  4230. return Builder.CreateCall(opFunc, opcodeParamList);
  4231. }
  4232. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  4233. unsigned opcode, llvm::Type *RetType,
  4234. ArrayRef<Value *> paramList, llvm::Module &M) {
  4235. // It's a matrix init.
  4236. if (!RetType->isVoidTy())
  4237. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4238. paramList, M);
  4239. Value *arrayPtr = paramList[0];
  4240. llvm::ArrayType *AT =
  4241. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  4242. // Avoid the arrayPtr.
  4243. unsigned paramSize = paramList.size() - 1;
  4244. // Support simple case here.
  4245. if (paramSize == AT->getArrayNumElements()) {
  4246. bool typeMatch = true;
  4247. llvm::Type *EltTy = AT->getArrayElementType();
  4248. if (EltTy->isAggregateType()) {
  4249. // Aggregate Type use pointer in initList.
  4250. EltTy = llvm::PointerType::get(EltTy, 0);
  4251. }
  4252. for (unsigned i = 1; i < paramList.size(); i++) {
  4253. if (paramList[i]->getType() != EltTy) {
  4254. typeMatch = false;
  4255. break;
  4256. }
  4257. }
  4258. // Both size and type match.
  4259. if (typeMatch) {
  4260. bool isPtr = EltTy->isPointerTy();
  4261. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  4262. Constant *zero = ConstantInt::get(i32Ty, 0);
  4263. for (unsigned i = 1; i < paramList.size(); i++) {
  4264. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  4265. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  4266. Value *Elt = paramList[i];
  4267. if (isPtr) {
  4268. Elt = Builder.CreateLoad(Elt);
  4269. }
  4270. Builder.CreateStore(Elt, GEP);
  4271. }
  4272. // The return value will not be used.
  4273. return nullptr;
  4274. }
  4275. }
  4276. // Other case will be lowered in later pass.
  4277. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4278. paramList, M);
  4279. }
  4280. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  4281. SmallVector<QualType, 4> &eltTys,
  4282. QualType Ty, Value *val) {
  4283. CGBuilderTy &Builder = CGF.Builder;
  4284. llvm::Type *valTy = val->getType();
  4285. if (valTy->isPointerTy()) {
  4286. llvm::Type *valEltTy = valTy->getPointerElementType();
  4287. if (valEltTy->isVectorTy() ||
  4288. valEltTy->isSingleValueType()) {
  4289. Value *ldVal = Builder.CreateLoad(val);
  4290. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4291. } else if (HLMatrixLower::IsMatrixType(valEltTy)) {
  4292. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  4293. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4294. } else {
  4295. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  4296. Value *zero = ConstantInt::get(i32Ty, 0);
  4297. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  4298. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  4299. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  4300. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4301. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4302. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  4303. }
  4304. } else {
  4305. // Struct.
  4306. StructType *ST = cast<StructType>(valEltTy);
  4307. if (HLModule::IsHLSLObjectType(ST)) {
  4308. // Save object directly like basic type.
  4309. elts.emplace_back(Builder.CreateLoad(val));
  4310. eltTys.emplace_back(Ty);
  4311. } else {
  4312. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  4313. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  4314. // Take care base.
  4315. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4316. if (CXXRD->getNumBases()) {
  4317. for (const auto &I : CXXRD->bases()) {
  4318. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4319. I.getType()->castAs<RecordType>()->getDecl());
  4320. if (BaseDecl->field_empty())
  4321. continue;
  4322. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4323. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4324. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4325. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4326. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  4327. }
  4328. }
  4329. }
  4330. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4331. fieldIter != fieldEnd; ++fieldIter) {
  4332. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4333. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4334. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4335. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  4336. }
  4337. }
  4338. }
  4339. }
  4340. } else {
  4341. if (HLMatrixLower::IsMatrixType(valTy)) {
  4342. unsigned col, row;
  4343. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(valTy, col, row);
  4344. // All matrix Value should be row major.
  4345. // Init list is row major in scalar.
  4346. // So the order is match here, just cast to vector.
  4347. unsigned matSize = col * row;
  4348. bool isRowMajor = IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4349. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  4350. : HLCastOpcode::ColMatrixToVecCast;
  4351. // Cast to vector.
  4352. val = EmitHLSLMatrixOperationCallImp(
  4353. Builder, HLOpcodeGroup::HLCast,
  4354. static_cast<unsigned>(opcode),
  4355. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  4356. valTy = val->getType();
  4357. }
  4358. if (valTy->isVectorTy()) {
  4359. QualType EltTy = GetHLSLVecMatElementType(Ty);
  4360. unsigned vecSize = valTy->getVectorNumElements();
  4361. for (unsigned i = 0; i < vecSize; i++) {
  4362. Value *Elt = Builder.CreateExtractElement(val, i);
  4363. elts.emplace_back(Elt);
  4364. eltTys.emplace_back(EltTy);
  4365. }
  4366. } else {
  4367. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  4368. elts.emplace_back(val);
  4369. eltTys.emplace_back(Ty);
  4370. }
  4371. }
  4372. }
  4373. // Cast elements in initlist if not match the target type.
  4374. // idx is current element index in initlist, Ty is target type.
  4375. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  4376. if (Ty->isArrayType()) {
  4377. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  4378. // Must be ConstantArrayType here.
  4379. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  4380. QualType EltTy = AT->getElementType();
  4381. for (unsigned i = 0; i < arraySize; i++)
  4382. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4383. } else if (IsHLSLVecType(Ty)) {
  4384. QualType EltTy = GetHLSLVecElementType(Ty);
  4385. unsigned vecSize = GetHLSLVecSize(Ty);
  4386. for (unsigned i=0;i< vecSize;i++)
  4387. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4388. } else if (IsHLSLMatType(Ty)) {
  4389. QualType EltTy = GetHLSLMatElementType(Ty);
  4390. unsigned row, col;
  4391. GetHLSLMatRowColCount(Ty, row, col);
  4392. unsigned matSize = row*col;
  4393. for (unsigned i = 0; i < matSize; i++)
  4394. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4395. } else if (Ty->isRecordType()) {
  4396. if (HLModule::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  4397. // Skip hlsl object.
  4398. idx++;
  4399. } else {
  4400. const RecordType *RT = Ty->getAsStructureType();
  4401. // For CXXRecord.
  4402. if (!RT)
  4403. RT = Ty->getAs<RecordType>();
  4404. RecordDecl *RD = RT->getDecl();
  4405. // Take care base.
  4406. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4407. if (CXXRD->getNumBases()) {
  4408. for (const auto &I : CXXRD->bases()) {
  4409. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4410. I.getType()->castAs<RecordType>()->getDecl());
  4411. if (BaseDecl->field_empty())
  4412. continue;
  4413. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4414. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  4415. }
  4416. }
  4417. }
  4418. for (FieldDecl *field : RD->fields())
  4419. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  4420. }
  4421. }
  4422. else {
  4423. // Basic type.
  4424. Value *val = elts[idx];
  4425. llvm::Type *srcTy = val->getType();
  4426. llvm::Type *dstTy = CGF.ConvertType(Ty);
  4427. if (srcTy != dstTy) {
  4428. Instruction::CastOps castOp =
  4429. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  4430. IsUnsigned(eltTys[idx]), IsUnsigned(Ty), srcTy, dstTy));
  4431. elts[idx] = CGF.Builder.CreateCast(castOp, val, dstTy);
  4432. }
  4433. idx++;
  4434. }
  4435. }
  4436. static void StoreInitListToDestPtr(Value *DestPtr,
  4437. SmallVector<Value *, 4> &elts, unsigned &idx,
  4438. QualType Type, CodeGenTypes &Types, bool bDefaultRowMajor,
  4439. CGBuilderTy &Builder, llvm::Module &M) {
  4440. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  4441. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Ty->getContext());
  4442. if (Ty->isVectorTy()) {
  4443. Value *Result = UndefValue::get(Ty);
  4444. for (unsigned i = 0; i < Ty->getVectorNumElements(); i++)
  4445. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  4446. Builder.CreateStore(Result, DestPtr);
  4447. idx += Ty->getVectorNumElements();
  4448. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4449. bool isRowMajor =
  4450. IsRowMajorMatrix(Type, bDefaultRowMajor);
  4451. unsigned row, col;
  4452. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4453. std::vector<Value *> matInitList(col * row);
  4454. for (unsigned i = 0; i < col; i++) {
  4455. for (unsigned r = 0; r < row; r++) {
  4456. unsigned matIdx = i * row + r;
  4457. matInitList[matIdx] = elts[idx + matIdx];
  4458. }
  4459. }
  4460. idx += row * col;
  4461. Value *matVal =
  4462. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  4463. /*opcode*/ 0, Ty, matInitList, M);
  4464. // matVal return from HLInit is row major.
  4465. // If DestPtr is row major, just store it directly.
  4466. if (!isRowMajor) {
  4467. // ColMatStore need a col major value.
  4468. // Cast row major matrix into col major.
  4469. // Then store it.
  4470. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  4471. Builder, HLOpcodeGroup::HLCast,
  4472. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  4473. {matVal}, M);
  4474. EmitHLSLMatrixOperationCallImp(
  4475. Builder, HLOpcodeGroup::HLMatLoadStore,
  4476. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  4477. {DestPtr, colMatVal}, M);
  4478. } else {
  4479. EmitHLSLMatrixOperationCallImp(
  4480. Builder, HLOpcodeGroup::HLMatLoadStore,
  4481. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  4482. {DestPtr, matVal}, M);
  4483. }
  4484. } else if (Ty->isStructTy()) {
  4485. if (HLModule::IsHLSLObjectType(Ty)) {
  4486. Builder.CreateStore(elts[idx], DestPtr);
  4487. idx++;
  4488. } else {
  4489. Constant *zero = ConstantInt::get(i32Ty, 0);
  4490. const RecordType *RT = Type->getAsStructureType();
  4491. // For CXXRecord.
  4492. if (!RT)
  4493. RT = Type->getAs<RecordType>();
  4494. RecordDecl *RD = RT->getDecl();
  4495. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4496. // Take care base.
  4497. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4498. if (CXXRD->getNumBases()) {
  4499. for (const auto &I : CXXRD->bases()) {
  4500. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4501. I.getType()->castAs<RecordType>()->getDecl());
  4502. if (BaseDecl->field_empty())
  4503. continue;
  4504. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4505. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4506. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4507. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4508. StoreInitListToDestPtr(GEP, elts, idx, parentTy, Types,
  4509. bDefaultRowMajor, Builder, M);
  4510. }
  4511. }
  4512. }
  4513. for (FieldDecl *field : RD->fields()) {
  4514. unsigned i = RL.getLLVMFieldNo(field);
  4515. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4516. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4517. StoreInitListToDestPtr(GEP, elts, idx, field->getType(), Types,
  4518. bDefaultRowMajor, Builder, M);
  4519. }
  4520. }
  4521. } else if (Ty->isArrayTy()) {
  4522. Constant *zero = ConstantInt::get(i32Ty, 0);
  4523. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  4524. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  4525. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4526. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4527. StoreInitListToDestPtr(GEP, elts, idx, EltType, Types, bDefaultRowMajor,
  4528. Builder, M);
  4529. }
  4530. } else {
  4531. DXASSERT(Ty->isSingleValueType(), "invalid type");
  4532. llvm::Type *i1Ty = Builder.getInt1Ty();
  4533. Value *V = elts[idx];
  4534. if (V->getType() == i1Ty &&
  4535. DestPtr->getType()->getPointerElementType() != i1Ty) {
  4536. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  4537. }
  4538. Builder.CreateStore(V, DestPtr);
  4539. idx++;
  4540. }
  4541. }
  4542. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  4543. SmallVector<Value *, 4> &EltValList,
  4544. SmallVector<QualType, 4> &EltTyList) {
  4545. unsigned NumInitElements = E->getNumInits();
  4546. for (unsigned i = 0; i != NumInitElements; ++i) {
  4547. Expr *init = E->getInit(i);
  4548. QualType iType = init->getType();
  4549. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  4550. ScanInitList(CGF, initList, EltValList, EltTyList);
  4551. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  4552. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  4553. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  4554. } else {
  4555. AggValueSlot Slot =
  4556. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  4557. CGF.EmitAggExpr(init, Slot);
  4558. llvm::Value *aggPtr = Slot.getAddr();
  4559. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  4560. }
  4561. }
  4562. }
  4563. // Is Type of E match Ty.
  4564. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  4565. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  4566. unsigned NumInitElements = initList->getNumInits();
  4567. // Skip vector and matrix type.
  4568. if (Ty->isVectorType())
  4569. return false;
  4570. if (hlsl::IsHLSLVecMatType(Ty))
  4571. return false;
  4572. if (Ty->isStructureOrClassType()) {
  4573. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  4574. bool bMatch = true;
  4575. auto It = record->field_begin();
  4576. auto ItEnd = record->field_end();
  4577. unsigned i = 0;
  4578. for (auto it = record->field_begin(), end = record->field_end();
  4579. it != end; it++) {
  4580. if (i == NumInitElements) {
  4581. bMatch = false;
  4582. break;
  4583. }
  4584. Expr *init = initList->getInit(i++);
  4585. QualType EltTy = it->getType();
  4586. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  4587. if (!bMatch)
  4588. break;
  4589. }
  4590. bMatch &= i == NumInitElements;
  4591. if (bMatch && initList->getType()->isVoidType()) {
  4592. initList->setType(Ty);
  4593. }
  4594. return bMatch;
  4595. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  4596. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  4597. QualType EltTy = AT->getElementType();
  4598. unsigned size = AT->getSize().getZExtValue();
  4599. if (size != NumInitElements)
  4600. return false;
  4601. bool bMatch = true;
  4602. for (unsigned i = 0; i != NumInitElements; ++i) {
  4603. Expr *init = initList->getInit(i);
  4604. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  4605. if (!bMatch)
  4606. break;
  4607. }
  4608. if (bMatch && initList->getType()->isVoidType()) {
  4609. initList->setType(Ty);
  4610. }
  4611. return bMatch;
  4612. } else {
  4613. return false;
  4614. }
  4615. } else {
  4616. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  4617. llvm::Type *TargetTy = Types.ConvertType(Ty);
  4618. return ExpTy == TargetTy;
  4619. }
  4620. }
  4621. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  4622. InitListExpr *E) {
  4623. QualType Ty = E->getType();
  4624. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  4625. if (result) {
  4626. auto iter = staticConstGlobalInitMap.find(E);
  4627. if (iter != staticConstGlobalInitMap.end()) {
  4628. GlobalVariable * GV = iter->second;
  4629. auto &InitConstants = staticConstGlobalInitListMap[GV];
  4630. // Add Constant to InitList.
  4631. for (unsigned i=0;i<E->getNumInits();i++) {
  4632. Expr *Expr = E->getInit(i);
  4633. LValue LV = CGF.EmitLValue(Expr);
  4634. if (LV.isSimple()) {
  4635. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  4636. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  4637. InitConstants.emplace_back(SrcPtr);
  4638. continue;
  4639. }
  4640. }
  4641. // Only support simple LV and Constant Ptr case.
  4642. // Other case just go normal path.
  4643. InitConstants.clear();
  4644. break;
  4645. }
  4646. if (InitConstants.empty())
  4647. staticConstGlobalInitListMap.erase(GV);
  4648. else
  4649. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  4650. }
  4651. }
  4652. return result;
  4653. }
  4654. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  4655. // The destPtr when emiting aggregate init, for normal case, it will be null.
  4656. Value *DestPtr) {
  4657. if (DestPtr && E->getNumInits() == 1) {
  4658. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  4659. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  4660. if (ExpTy == TargetTy) {
  4661. Expr *Expr = E->getInit(0);
  4662. LValue LV = CGF.EmitLValue(Expr);
  4663. if (LV.isSimple()) {
  4664. Value *SrcPtr = LV.getAddress();
  4665. SmallVector<Value *, 4> idxList;
  4666. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  4667. E->getType(), SrcPtr->getType());
  4668. return nullptr;
  4669. }
  4670. }
  4671. }
  4672. SmallVector<Value *, 4> EltValList;
  4673. SmallVector<QualType, 4> EltTyList;
  4674. ScanInitList(CGF, E, EltValList, EltTyList);
  4675. QualType ResultTy = E->getType();
  4676. unsigned idx = 0;
  4677. // Create cast if need.
  4678. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  4679. DXASSERT(idx == EltValList.size(), "size must match");
  4680. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  4681. if (DestPtr) {
  4682. SmallVector<Value *, 4> ParamList;
  4683. DXASSERT(RetTy->isAggregateType(), "");
  4684. ParamList.emplace_back(DestPtr);
  4685. ParamList.append(EltValList.begin(), EltValList.end());
  4686. idx = 0;
  4687. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4688. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy, CGF.getTypes(),
  4689. bDefaultRowMajor, CGF.Builder, TheModule);
  4690. return nullptr;
  4691. }
  4692. if (IsHLSLVecType(ResultTy)) {
  4693. Value *Result = UndefValue::get(RetTy);
  4694. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  4695. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  4696. return Result;
  4697. } else {
  4698. // Must be matrix here.
  4699. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  4700. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  4701. /*opcode*/ 0, RetTy, EltValList,
  4702. TheModule);
  4703. }
  4704. }
  4705. static void FlatConstToList(Constant *C, SmallVector<Constant *, 4> &EltValList,
  4706. QualType Type, CodeGenTypes &Types,
  4707. bool bDefaultRowMajor) {
  4708. llvm::Type *Ty = C->getType();
  4709. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4710. // Type is only for matrix. Keep use Type to next level.
  4711. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  4712. FlatConstToList(C->getAggregateElement(i), EltValList, Type, Types,
  4713. bDefaultRowMajor);
  4714. }
  4715. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4716. bool isRowMajor = IsRowMajorMatrix(Type, bDefaultRowMajor);
  4717. // matrix type is struct { vector<Ty, row> [col] };
  4718. // Strip the struct level here.
  4719. Constant *matVal = C->getAggregateElement((unsigned)0);
  4720. const RecordType *RT = Type->getAs<RecordType>();
  4721. RecordDecl *RD = RT->getDecl();
  4722. QualType EltTy = RD->field_begin()->getType();
  4723. // When scan, init list scalars is row major.
  4724. if (isRowMajor) {
  4725. // Don't change the major for row major value.
  4726. FlatConstToList(matVal, EltValList, EltTy, Types, bDefaultRowMajor);
  4727. } else {
  4728. // Save to tmp list.
  4729. SmallVector<Constant *, 4> matEltList;
  4730. FlatConstToList(matVal, matEltList, EltTy, Types, bDefaultRowMajor);
  4731. unsigned row, col;
  4732. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4733. // Change col major value to row major.
  4734. for (unsigned r = 0; r < row; r++)
  4735. for (unsigned c = 0; c < col; c++) {
  4736. unsigned colMajorIdx = c * row + r;
  4737. EltValList.emplace_back(matEltList[colMajorIdx]);
  4738. }
  4739. }
  4740. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4741. QualType EltTy = Type->getAsArrayTypeUnsafe()->getElementType();
  4742. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  4743. FlatConstToList(C->getAggregateElement(i), EltValList, EltTy, Types,
  4744. bDefaultRowMajor);
  4745. }
  4746. } else if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  4747. RecordDecl *RD = Type->getAsStructureType()->getDecl();
  4748. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4749. // Take care base.
  4750. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4751. if (CXXRD->getNumBases()) {
  4752. for (const auto &I : CXXRD->bases()) {
  4753. const CXXRecordDecl *BaseDecl =
  4754. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4755. if (BaseDecl->field_empty())
  4756. continue;
  4757. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4758. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4759. FlatConstToList(C->getAggregateElement(i), EltValList, parentTy,
  4760. Types, bDefaultRowMajor);
  4761. }
  4762. }
  4763. }
  4764. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4765. fieldIter != fieldEnd; ++fieldIter) {
  4766. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4767. FlatConstToList(C->getAggregateElement(i), EltValList,
  4768. fieldIter->getType(), Types, bDefaultRowMajor);
  4769. }
  4770. } else {
  4771. EltValList.emplace_back(C);
  4772. }
  4773. }
  4774. static bool ScanConstInitList(CodeGenModule &CGM, InitListExpr *E,
  4775. SmallVector<Constant *, 4> &EltValList,
  4776. CodeGenTypes &Types, bool bDefaultRowMajor) {
  4777. unsigned NumInitElements = E->getNumInits();
  4778. for (unsigned i = 0; i != NumInitElements; ++i) {
  4779. Expr *init = E->getInit(i);
  4780. QualType iType = init->getType();
  4781. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  4782. if (!ScanConstInitList(CGM, initList, EltValList, Types,
  4783. bDefaultRowMajor))
  4784. return false;
  4785. } else if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(init)) {
  4786. if (VarDecl *D = dyn_cast<VarDecl>(ref->getDecl())) {
  4787. if (!D->hasInit())
  4788. return false;
  4789. if (Constant *initVal = CGM.EmitConstantInit(*D)) {
  4790. FlatConstToList(initVal, EltValList, iType, Types, bDefaultRowMajor);
  4791. } else {
  4792. return false;
  4793. }
  4794. } else {
  4795. return false;
  4796. }
  4797. } else if (hlsl::IsHLSLMatType(iType)) {
  4798. return false;
  4799. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  4800. if (Constant *initVal = CGM.EmitConstantExpr(init, iType)) {
  4801. FlatConstToList(initVal, EltValList, iType, Types, bDefaultRowMajor);
  4802. } else {
  4803. return false;
  4804. }
  4805. } else {
  4806. return false;
  4807. }
  4808. }
  4809. return true;
  4810. }
  4811. static Constant *BuildConstInitializer(QualType Type, unsigned &offset,
  4812. SmallVector<Constant *, 4> &EltValList,
  4813. CodeGenTypes &Types,
  4814. bool bDefaultRowMajor);
  4815. static Constant *BuildConstVector(llvm::VectorType *VT, unsigned &offset,
  4816. SmallVector<Constant *, 4> &EltValList,
  4817. QualType Type, CodeGenTypes &Types) {
  4818. SmallVector<Constant *, 4> Elts;
  4819. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  4820. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  4821. Elts.emplace_back(BuildConstInitializer(EltTy, offset, EltValList, Types,
  4822. // Vector don't need major.
  4823. /*bDefaultRowMajor*/ false));
  4824. }
  4825. return llvm::ConstantVector::get(Elts);
  4826. }
  4827. static Constant *BuildConstMatrix(llvm::Type *Ty, unsigned &offset,
  4828. SmallVector<Constant *, 4> &EltValList,
  4829. QualType Type, CodeGenTypes &Types,
  4830. bool bDefaultRowMajor) {
  4831. QualType EltTy = hlsl::GetHLSLMatElementType(Type);
  4832. unsigned col, row;
  4833. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4834. llvm::ArrayType *AT = cast<llvm::ArrayType>(Ty->getStructElementType(0));
  4835. // Save initializer elements first.
  4836. // Matrix initializer is row major.
  4837. SmallVector<Constant *, 16> elts;
  4838. for (unsigned i = 0; i < col * row; i++) {
  4839. elts.emplace_back(BuildConstInitializer(EltTy, offset, EltValList, Types,
  4840. bDefaultRowMajor));
  4841. }
  4842. bool isRowMajor = IsRowMajorMatrix(Type, bDefaultRowMajor);
  4843. SmallVector<Constant *, 16> majorElts(elts.begin(), elts.end());
  4844. if (!isRowMajor) {
  4845. // cast row major to col major.
  4846. for (unsigned c = 0; c < col; c++) {
  4847. SmallVector<Constant *, 4> rows;
  4848. for (unsigned r = 0; r < row; r++) {
  4849. unsigned rowMajorIdx = r * col + c;
  4850. unsigned colMajorIdx = c * row + r;
  4851. majorElts[colMajorIdx] = elts[rowMajorIdx];
  4852. }
  4853. }
  4854. }
  4855. // The type is vector<element, col>[row].
  4856. SmallVector<Constant *, 4> rows;
  4857. unsigned idx = 0;
  4858. for (unsigned r = 0; r < row; r++) {
  4859. SmallVector<Constant *, 4> cols;
  4860. for (unsigned c = 0; c < col; c++) {
  4861. cols.emplace_back(majorElts[idx++]);
  4862. }
  4863. rows.emplace_back(llvm::ConstantVector::get(cols));
  4864. }
  4865. Constant *mat = llvm::ConstantArray::get(AT, rows);
  4866. return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), mat);
  4867. }
  4868. static Constant *BuildConstArray(llvm::ArrayType *AT, unsigned &offset,
  4869. SmallVector<Constant *, 4> &EltValList,
  4870. QualType Type, CodeGenTypes &Types,
  4871. bool bDefaultRowMajor) {
  4872. SmallVector<Constant *, 4> Elts;
  4873. QualType EltType = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
  4874. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  4875. Elts.emplace_back(BuildConstInitializer(EltType, offset, EltValList, Types,
  4876. bDefaultRowMajor));
  4877. }
  4878. return llvm::ConstantArray::get(AT, Elts);
  4879. }
  4880. static Constant *BuildConstStruct(llvm::StructType *ST, unsigned &offset,
  4881. SmallVector<Constant *, 4> &EltValList,
  4882. QualType Type, CodeGenTypes &Types,
  4883. bool bDefaultRowMajor) {
  4884. SmallVector<Constant *, 4> Elts;
  4885. const RecordType *RT = Type->getAsStructureType();
  4886. if (!RT)
  4887. RT = Type->getAs<RecordType>();
  4888. const RecordDecl *RD = RT->getDecl();
  4889. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4890. if (CXXRD->getNumBases()) {
  4891. // Add base as field.
  4892. for (const auto &I : CXXRD->bases()) {
  4893. const CXXRecordDecl *BaseDecl =
  4894. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4895. // Skip empty struct.
  4896. if (BaseDecl->field_empty())
  4897. continue;
  4898. // Add base as a whole constant. Not as element.
  4899. Elts.emplace_back(BuildConstInitializer(I.getType(), offset, EltValList,
  4900. Types, bDefaultRowMajor));
  4901. }
  4902. }
  4903. }
  4904. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4905. fieldIter != fieldEnd; ++fieldIter) {
  4906. Elts.emplace_back(BuildConstInitializer(
  4907. fieldIter->getType(), offset, EltValList, Types, bDefaultRowMajor));
  4908. }
  4909. return llvm::ConstantStruct::get(ST, Elts);
  4910. }
  4911. static Constant *BuildConstInitializer(QualType Type, unsigned &offset,
  4912. SmallVector<Constant *, 4> &EltValList,
  4913. CodeGenTypes &Types,
  4914. bool bDefaultRowMajor) {
  4915. llvm::Type *Ty = Types.ConvertType(Type);
  4916. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4917. return BuildConstVector(VT, offset, EltValList, Type, Types);
  4918. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4919. return BuildConstArray(AT, offset, EltValList, Type, Types,
  4920. bDefaultRowMajor);
  4921. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4922. return BuildConstMatrix(Ty, offset, EltValList, Type, Types,
  4923. bDefaultRowMajor);
  4924. } else if (StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  4925. return BuildConstStruct(ST, offset, EltValList, Type, Types,
  4926. bDefaultRowMajor);
  4927. } else {
  4928. // Scalar basic types.
  4929. Constant *Val = EltValList[offset++];
  4930. if (Val->getType() == Ty) {
  4931. return Val;
  4932. } else {
  4933. IRBuilder<> Builder(Ty->getContext());
  4934. // Don't cast int to bool. bool only for scalar.
  4935. if (Ty == Builder.getInt1Ty() && Val->getType() == Builder.getInt32Ty())
  4936. return Val;
  4937. Instruction::CastOps castOp =
  4938. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  4939. IsUnsigned(Type), IsUnsigned(Type), Val->getType(), Ty));
  4940. return cast<Constant>(Builder.CreateCast(castOp, Val, Ty));
  4941. }
  4942. }
  4943. }
  4944. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  4945. InitListExpr *E) {
  4946. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4947. SmallVector<Constant *, 4> EltValList;
  4948. if (!ScanConstInitList(CGM, E, EltValList, CGM.getTypes(), bDefaultRowMajor))
  4949. return nullptr;
  4950. QualType Type = E->getType();
  4951. unsigned offset = 0;
  4952. return BuildConstInitializer(Type, offset, EltValList, CGM.getTypes(),
  4953. bDefaultRowMajor);
  4954. }
  4955. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  4956. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  4957. ArrayRef<Value *> paramList) {
  4958. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  4959. unsigned opcode = GetHLOpcode(E);
  4960. if (group == HLOpcodeGroup::HLInit)
  4961. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  4962. TheModule);
  4963. else
  4964. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  4965. paramList, TheModule);
  4966. }
  4967. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  4968. EmitHLSLMatrixOperationCallImp(
  4969. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  4970. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  4971. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  4972. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  4973. TheModule);
  4974. }
  4975. static llvm::Type *MergeIntType(llvm::IntegerType *T0, llvm::IntegerType *T1) {
  4976. if (T0->getBitWidth() > T1->getBitWidth())
  4977. return T0;
  4978. else
  4979. return T1;
  4980. }
  4981. static Value *CreateExt(CGBuilderTy &Builder, Value *Src, llvm::Type *DstTy,
  4982. bool bSigned) {
  4983. if (bSigned)
  4984. return Builder.CreateSExt(Src, DstTy);
  4985. else
  4986. return Builder.CreateZExt(Src, DstTy);
  4987. }
  4988. // For integer literal, try to get lowest precision.
  4989. static Value *CalcHLSLLiteralToLowestPrecision(CGBuilderTy &Builder, Value *Src,
  4990. bool bSigned) {
  4991. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4992. APInt v = CI->getValue();
  4993. switch (v.getActiveWords()) {
  4994. case 4:
  4995. return Builder.getInt32(v.getLimitedValue());
  4996. case 8:
  4997. return Builder.getInt64(v.getLimitedValue());
  4998. case 2:
  4999. // TODO: use low precision type when support it in dxil.
  5000. // return Builder.getInt16(v.getLimitedValue());
  5001. return Builder.getInt32(v.getLimitedValue());
  5002. case 1:
  5003. // TODO: use precision type when support it in dxil.
  5004. // return Builder.getInt8(v.getLimitedValue());
  5005. return Builder.getInt32(v.getLimitedValue());
  5006. default:
  5007. return nullptr;
  5008. }
  5009. } else if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  5010. if (SI->getType()->isIntegerTy()) {
  5011. Value *T = SI->getTrueValue();
  5012. Value *F = SI->getFalseValue();
  5013. Value *lowT = CalcHLSLLiteralToLowestPrecision(Builder, T, bSigned);
  5014. Value *lowF = CalcHLSLLiteralToLowestPrecision(Builder, F, bSigned);
  5015. if (lowT && lowF && lowT != T && lowF != F) {
  5016. llvm::IntegerType *TTy = cast<llvm::IntegerType>(lowT->getType());
  5017. llvm::IntegerType *FTy = cast<llvm::IntegerType>(lowF->getType());
  5018. llvm::Type *Ty = MergeIntType(TTy, FTy);
  5019. if (TTy != Ty) {
  5020. lowT = CreateExt(Builder, lowT, Ty, bSigned);
  5021. }
  5022. if (FTy != Ty) {
  5023. lowF = CreateExt(Builder, lowF, Ty, bSigned);
  5024. }
  5025. Value *Cond = SI->getCondition();
  5026. return Builder.CreateSelect(Cond, lowT, lowF);
  5027. }
  5028. }
  5029. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(Src)) {
  5030. Value *Src0 = BO->getOperand(0);
  5031. Value *Src1 = BO->getOperand(1);
  5032. Value *CastSrc0 = CalcHLSLLiteralToLowestPrecision(Builder, Src0, bSigned);
  5033. Value *CastSrc1 = CalcHLSLLiteralToLowestPrecision(Builder, Src1, bSigned);
  5034. if (Src0 != CastSrc0 && Src1 != CastSrc1 && CastSrc0 && CastSrc1 &&
  5035. CastSrc0->getType() == CastSrc1->getType()) {
  5036. llvm::IntegerType *Ty0 = cast<llvm::IntegerType>(CastSrc0->getType());
  5037. llvm::IntegerType *Ty1 = cast<llvm::IntegerType>(CastSrc0->getType());
  5038. llvm::Type *Ty = MergeIntType(Ty0, Ty1);
  5039. if (Ty0 != Ty) {
  5040. CastSrc0 = CreateExt(Builder, CastSrc0, Ty, bSigned);
  5041. }
  5042. if (Ty1 != Ty) {
  5043. CastSrc1 = CreateExt(Builder, CastSrc1, Ty, bSigned);
  5044. }
  5045. return Builder.CreateBinOp(BO->getOpcode(), CastSrc0, CastSrc1);
  5046. }
  5047. }
  5048. return nullptr;
  5049. }
  5050. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  5051. QualType SrcType,
  5052. QualType DstType) {
  5053. auto &Builder = CGF.Builder;
  5054. llvm::Type *DstTy = CGF.ConvertType(DstType);
  5055. bool bDstSigned = DstType->isSignedIntegerType();
  5056. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  5057. APInt v = CI->getValue();
  5058. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5059. v = v.trunc(IT->getBitWidth());
  5060. switch (IT->getBitWidth()) {
  5061. case 32:
  5062. return Builder.getInt32(v.getLimitedValue());
  5063. case 64:
  5064. return Builder.getInt64(v.getLimitedValue());
  5065. case 16:
  5066. return Builder.getInt16(v.getLimitedValue());
  5067. case 8:
  5068. return Builder.getInt8(v.getLimitedValue());
  5069. default:
  5070. return nullptr;
  5071. }
  5072. } else {
  5073. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  5074. int64_t val = v.getLimitedValue();
  5075. if (v.isNegative())
  5076. val = 0-v.abs().getLimitedValue();
  5077. if (DstTy->isDoubleTy())
  5078. return ConstantFP::get(DstTy, (double)val);
  5079. else if (DstTy->isFloatTy())
  5080. return ConstantFP::get(DstTy, (float)val);
  5081. else {
  5082. if (bDstSigned)
  5083. return Builder.CreateSIToFP(Src, DstTy);
  5084. else
  5085. return Builder.CreateUIToFP(Src, DstTy);
  5086. }
  5087. }
  5088. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  5089. APFloat v = CF->getValueAPF();
  5090. double dv = v.convertToDouble();
  5091. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5092. switch (IT->getBitWidth()) {
  5093. case 32:
  5094. return Builder.getInt32(dv);
  5095. case 64:
  5096. return Builder.getInt64(dv);
  5097. case 16:
  5098. return Builder.getInt16(dv);
  5099. case 8:
  5100. return Builder.getInt8(dv);
  5101. default:
  5102. return nullptr;
  5103. }
  5104. } else {
  5105. if (DstTy->isFloatTy()) {
  5106. float fv = dv;
  5107. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  5108. } else {
  5109. return Builder.CreateFPTrunc(Src, DstTy);
  5110. }
  5111. }
  5112. } else if (UndefValue *UV = dyn_cast<UndefValue>(Src)) {
  5113. return UndefValue::get(DstTy);
  5114. } else {
  5115. Instruction *I = cast<Instruction>(Src);
  5116. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  5117. Value *T = SI->getTrueValue();
  5118. Value *F = SI->getFalseValue();
  5119. Value *Cond = SI->getCondition();
  5120. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  5121. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  5122. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  5123. if (DstTy == Builder.getInt32Ty()) {
  5124. T = Builder.getInt32(lhs.getLimitedValue());
  5125. F = Builder.getInt32(rhs.getLimitedValue());
  5126. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5127. return Sel;
  5128. } else if (DstTy->isFloatingPointTy()) {
  5129. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  5130. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  5131. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5132. return Sel;
  5133. }
  5134. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  5135. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  5136. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  5137. double ld = lhs.convertToDouble();
  5138. double rd = rhs.convertToDouble();
  5139. if (DstTy->isFloatTy()) {
  5140. float lf = ld;
  5141. float rf = rd;
  5142. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  5143. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  5144. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5145. return Sel;
  5146. } else if (DstTy == Builder.getInt32Ty()) {
  5147. T = Builder.getInt32(ld);
  5148. F = Builder.getInt32(rd);
  5149. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5150. return Sel;
  5151. } else if (DstTy == Builder.getInt64Ty()) {
  5152. T = Builder.getInt64(ld);
  5153. F = Builder.getInt64(rd);
  5154. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5155. return Sel;
  5156. }
  5157. }
  5158. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(I)) {
  5159. // For integer binary operator, do the calc on lowest precision, then cast
  5160. // to dstTy.
  5161. if (I->getType()->isIntegerTy()) {
  5162. bool bSigned = DstType->isSignedIntegerType();
  5163. Value *CastResult =
  5164. CalcHLSLLiteralToLowestPrecision(Builder, BO, bSigned);
  5165. if (!CastResult)
  5166. return nullptr;
  5167. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5168. if (DstTy == CastResult->getType()) {
  5169. return CastResult;
  5170. } else {
  5171. if (bSigned)
  5172. return Builder.CreateSExtOrTrunc(CastResult, DstTy);
  5173. else
  5174. return Builder.CreateZExtOrTrunc(CastResult, DstTy);
  5175. }
  5176. } else {
  5177. if (bDstSigned)
  5178. return Builder.CreateSIToFP(CastResult, DstTy);
  5179. else
  5180. return Builder.CreateUIToFP(CastResult, DstTy);
  5181. }
  5182. }
  5183. }
  5184. // TODO: support other opcode if need.
  5185. return nullptr;
  5186. }
  5187. }
  5188. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  5189. llvm::Type *RetType,
  5190. llvm::Value *Ptr,
  5191. llvm::Value *Idx,
  5192. clang::QualType Ty) {
  5193. bool isRowMajor =
  5194. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5195. unsigned opcode =
  5196. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  5197. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  5198. Value *matBase = Ptr;
  5199. DXASSERT(matBase->getType()->isPointerTy(),
  5200. "matrix subscript should return pointer");
  5201. RetType =
  5202. llvm::PointerType::get(RetType->getPointerElementType(),
  5203. matBase->getType()->getPointerAddressSpace());
  5204. // Lower mat[Idx] into real idx.
  5205. SmallVector<Value *, 8> args;
  5206. args.emplace_back(Ptr);
  5207. unsigned row, col;
  5208. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  5209. if (isRowMajor) {
  5210. Value *cCol = ConstantInt::get(Idx->getType(), col);
  5211. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  5212. for (unsigned i = 0; i < col; i++) {
  5213. Value *c = ConstantInt::get(Idx->getType(), i);
  5214. // r * col + c
  5215. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  5216. args.emplace_back(matIdx);
  5217. }
  5218. } else {
  5219. for (unsigned i = 0; i < col; i++) {
  5220. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  5221. // c * row + r
  5222. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  5223. args.emplace_back(matIdx);
  5224. }
  5225. }
  5226. Value *matSub =
  5227. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  5228. opcode, RetType, args, TheModule);
  5229. return matSub;
  5230. }
  5231. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  5232. llvm::Type *RetType,
  5233. ArrayRef<Value *> paramList,
  5234. QualType Ty) {
  5235. bool isRowMajor =
  5236. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5237. unsigned opcode =
  5238. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  5239. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  5240. Value *matBase = paramList[0];
  5241. DXASSERT(matBase->getType()->isPointerTy(),
  5242. "matrix element should return pointer");
  5243. RetType =
  5244. llvm::PointerType::get(RetType->getPointerElementType(),
  5245. matBase->getType()->getPointerAddressSpace());
  5246. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  5247. // Lower _m00 into real idx.
  5248. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  5249. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  5250. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  5251. // For all zero idx. Still all zero idx.
  5252. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  5253. Constant *zero = zeros->getAggregateElement((unsigned)0);
  5254. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  5255. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  5256. } else {
  5257. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  5258. unsigned count = elts->getNumElements();
  5259. unsigned row, col;
  5260. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  5261. std::vector<Constant *> idxs(count >> 1);
  5262. for (unsigned i = 0; i < count; i += 2) {
  5263. unsigned rowIdx = elts->getElementAsInteger(i);
  5264. unsigned colIdx = elts->getElementAsInteger(i + 1);
  5265. unsigned matIdx = 0;
  5266. if (isRowMajor) {
  5267. matIdx = rowIdx * col + colIdx;
  5268. } else {
  5269. matIdx = colIdx * row + rowIdx;
  5270. }
  5271. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  5272. }
  5273. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  5274. }
  5275. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  5276. opcode, RetType, args, TheModule);
  5277. }
  5278. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  5279. QualType Ty) {
  5280. bool isRowMajor =
  5281. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5282. unsigned opcode =
  5283. isRowMajor
  5284. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  5285. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  5286. Value *matVal = EmitHLSLMatrixOperationCallImp(
  5287. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5288. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  5289. if (!isRowMajor) {
  5290. // ColMatLoad will return a col major matrix.
  5291. // All matrix Value should be row major.
  5292. // Cast it to row major.
  5293. matVal = EmitHLSLMatrixOperationCallImp(
  5294. Builder, HLOpcodeGroup::HLCast,
  5295. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  5296. matVal->getType(), {matVal}, TheModule);
  5297. }
  5298. return matVal;
  5299. }
  5300. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  5301. Value *DestPtr, QualType Ty) {
  5302. bool isRowMajor =
  5303. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5304. unsigned opcode =
  5305. isRowMajor
  5306. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  5307. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  5308. if (!isRowMajor) {
  5309. Value *ColVal = nullptr;
  5310. // If Val is casted from col major. Just use the original col major val.
  5311. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  5312. hlsl::HLOpcodeGroup group =
  5313. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  5314. if (group == HLOpcodeGroup::HLCast) {
  5315. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  5316. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  5317. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  5318. }
  5319. }
  5320. }
  5321. if (ColVal) {
  5322. Val = ColVal;
  5323. } else {
  5324. // All matrix Value should be row major.
  5325. // ColMatStore need a col major value.
  5326. // Cast it to row major.
  5327. Val = EmitHLSLMatrixOperationCallImp(
  5328. Builder, HLOpcodeGroup::HLCast,
  5329. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  5330. Val->getType(), {Val}, TheModule);
  5331. }
  5332. }
  5333. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5334. Val->getType(), {DestPtr, Val}, TheModule);
  5335. }
  5336. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  5337. QualType Ty) {
  5338. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  5339. }
  5340. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  5341. Value *DestPtr, QualType Ty) {
  5342. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  5343. }
  5344. // Copy data from srcPtr to destPtr.
  5345. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  5346. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  5347. if (idxList.size() > 1) {
  5348. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5349. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5350. }
  5351. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  5352. Builder.CreateStore(ld, DestPtr);
  5353. }
  5354. // Get Element val from SrvVal with extract value.
  5355. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  5356. CGBuilderTy &Builder) {
  5357. Value *Val = SrcVal;
  5358. // Skip beginning pointer type.
  5359. for (unsigned i = 1; i < idxList.size(); i++) {
  5360. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  5361. llvm::Type *Ty = Val->getType();
  5362. if (Ty->isAggregateType()) {
  5363. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  5364. }
  5365. }
  5366. return Val;
  5367. }
  5368. // Copy srcVal to destPtr.
  5369. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  5370. ArrayRef<Value*> idxList,
  5371. CGBuilderTy &Builder) {
  5372. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5373. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  5374. Builder.CreateStore(Val, DestGEP);
  5375. }
  5376. static void SimpleCopy(Value *Dest, Value *Src,
  5377. ArrayRef<Value *> idxList,
  5378. CGBuilderTy &Builder) {
  5379. if (Src->getType()->isPointerTy())
  5380. SimplePtrCopy(Dest, Src, idxList, Builder);
  5381. else
  5382. SimpleValCopy(Dest, Src, idxList, Builder);
  5383. }
  5384. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  5385. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  5386. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  5387. SmallVector<QualType, 4> &EltTyList) {
  5388. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5389. Constant *idx = Constant::getIntegerValue(
  5390. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5391. idxList.emplace_back(idx);
  5392. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  5393. GepList, EltTyList);
  5394. idxList.pop_back();
  5395. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5396. // Use matLd/St for matrix.
  5397. unsigned col, row;
  5398. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, col, row);
  5399. llvm::PointerType *EltPtrTy =
  5400. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  5401. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  5402. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5403. // Flatten matrix to elements.
  5404. for (unsigned r = 0; r < row; r++) {
  5405. for (unsigned c = 0; c < col; c++) {
  5406. ConstantInt *cRow = CGF.Builder.getInt32(r);
  5407. ConstantInt *cCol = CGF.Builder.getInt32(c);
  5408. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  5409. GepList.push_back(
  5410. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  5411. EltTyList.push_back(EltQualTy);
  5412. }
  5413. }
  5414. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5415. if (HLModule::IsHLSLObjectType(ST)) {
  5416. // Avoid split HLSL object.
  5417. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5418. GepList.push_back(GEP);
  5419. EltTyList.push_back(Type);
  5420. return;
  5421. }
  5422. const clang::RecordType *RT = Type->getAsStructureType();
  5423. RecordDecl *RD = RT->getDecl();
  5424. auto fieldIter = RD->field_begin();
  5425. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5426. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5427. if (CXXRD->getNumBases()) {
  5428. // Add base as field.
  5429. for (const auto &I : CXXRD->bases()) {
  5430. const CXXRecordDecl *BaseDecl =
  5431. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5432. // Skip empty struct.
  5433. if (BaseDecl->field_empty())
  5434. continue;
  5435. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5436. llvm::Type *parentType = CGF.ConvertType(parentTy);
  5437. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5438. Constant *idx = llvm::Constant::getIntegerValue(
  5439. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5440. idxList.emplace_back(idx);
  5441. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  5442. GepList, EltTyList);
  5443. idxList.pop_back();
  5444. }
  5445. }
  5446. }
  5447. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5448. fieldIter != fieldEnd; ++fieldIter) {
  5449. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5450. llvm::Type *ET = ST->getElementType(i);
  5451. Constant *idx = llvm::Constant::getIntegerValue(
  5452. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5453. idxList.emplace_back(idx);
  5454. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  5455. GepList, EltTyList);
  5456. idxList.pop_back();
  5457. }
  5458. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5459. llvm::Type *ET = AT->getElementType();
  5460. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5461. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5462. Constant *idx = Constant::getIntegerValue(
  5463. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5464. idxList.emplace_back(idx);
  5465. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  5466. EltTyList);
  5467. idxList.pop_back();
  5468. }
  5469. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  5470. // Flatten vector too.
  5471. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  5472. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  5473. Constant *idx = CGF.Builder.getInt32(i);
  5474. idxList.emplace_back(idx);
  5475. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5476. GepList.push_back(GEP);
  5477. EltTyList.push_back(EltTy);
  5478. idxList.pop_back();
  5479. }
  5480. } else {
  5481. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5482. GepList.push_back(GEP);
  5483. EltTyList.push_back(Type);
  5484. }
  5485. }
  5486. void CGMSHLSLRuntime::LoadFlattenedGepList(CodeGenFunction &CGF,
  5487. ArrayRef<Value *> GepList,
  5488. ArrayRef<QualType> EltTyList,
  5489. SmallVector<Value *, 4> &EltList) {
  5490. unsigned eltSize = GepList.size();
  5491. for (unsigned i = 0; i < eltSize; i++) {
  5492. Value *Ptr = GepList[i];
  5493. QualType Type = EltTyList[i];
  5494. // Everying is element type.
  5495. EltList.push_back(CGF.Builder.CreateLoad(Ptr));
  5496. }
  5497. }
  5498. void CGMSHLSLRuntime::StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  5499. ArrayRef<QualType> GepTyList, ArrayRef<Value *> EltValList, ArrayRef<QualType> SrcTyList) {
  5500. unsigned eltSize = GepList.size();
  5501. for (unsigned i = 0; i < eltSize; i++) {
  5502. Value *Ptr = GepList[i];
  5503. QualType DestType = GepTyList[i];
  5504. Value *Val = EltValList[i];
  5505. QualType SrcType = SrcTyList[i];
  5506. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  5507. // Everything is element type.
  5508. if (Ty != Val->getType()) {
  5509. Instruction::CastOps castOp =
  5510. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5511. IsUnsigned(SrcType), IsUnsigned(DestType), Val->getType(), Ty));
  5512. Val = CGF.Builder.CreateCast(castOp, Val, Ty);
  5513. }
  5514. CGF.Builder.CreateStore(Val, Ptr);
  5515. }
  5516. }
  5517. // Copy data from SrcPtr to DestPtr.
  5518. // For matrix, use MatLoad/MatStore.
  5519. // For matrix array, EmitHLSLAggregateCopy on each element.
  5520. // For struct or array, use memcpy.
  5521. // Other just load/store.
  5522. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  5523. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  5524. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  5525. clang::QualType DestType, llvm::Type *Ty) {
  5526. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5527. Constant *idx = Constant::getIntegerValue(
  5528. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5529. idxList.emplace_back(idx);
  5530. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  5531. PT->getElementType());
  5532. idxList.pop_back();
  5533. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5534. // Use matLd/St for matrix.
  5535. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5536. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5537. Value *ldMat = EmitHLSLMatrixLoad(CGF, srcGEP, SrcType);
  5538. EmitHLSLMatrixStore(CGF, ldMat, dstGEP, DestType);
  5539. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5540. if (HLModule::IsHLSLObjectType(ST)) {
  5541. // Avoid split HLSL object.
  5542. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  5543. return;
  5544. }
  5545. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5546. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5547. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  5548. // Memcpy struct.
  5549. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  5550. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5551. if (!HLMatrixLower::IsMatrixArrayPointer(llvm::PointerType::get(Ty,0))) {
  5552. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5553. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5554. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  5555. // Memcpy non-matrix array.
  5556. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  5557. } else {
  5558. llvm::Type *ET = AT->getElementType();
  5559. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  5560. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  5561. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5562. Constant *idx = Constant::getIntegerValue(
  5563. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5564. idxList.emplace_back(idx);
  5565. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  5566. EltDestType, ET);
  5567. idxList.pop_back();
  5568. }
  5569. }
  5570. } else {
  5571. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  5572. }
  5573. }
  5574. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  5575. llvm::Value *DestPtr,
  5576. clang::QualType Ty) {
  5577. SmallVector<Value *, 4> idxList;
  5578. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  5579. }
  5580. // To memcpy, need element type match.
  5581. // For struct type, the layout should match in cbuffer layout.
  5582. // struct { float2 x; float3 y; } will not match struct { float3 x; float2 y; }.
  5583. // struct { float2 x; float3 y; } will not match array of float.
  5584. static bool IsTypeMatchForMemcpy(llvm::Type *SrcTy, llvm::Type *DestTy) {
  5585. llvm::Type *SrcEltTy = dxilutil::GetArrayEltTy(SrcTy);
  5586. llvm::Type *DestEltTy = dxilutil::GetArrayEltTy(DestTy);
  5587. if (SrcEltTy == DestEltTy)
  5588. return true;
  5589. llvm::StructType *SrcST = dyn_cast<llvm::StructType>(SrcEltTy);
  5590. llvm::StructType *DestST = dyn_cast<llvm::StructType>(DestEltTy);
  5591. if (SrcST && DestST) {
  5592. // Only allow identical struct.
  5593. return SrcST->isLayoutIdentical(DestST);
  5594. } else if (!SrcST && !DestST) {
  5595. // For basic type, if one is array, one is not array, layout is different.
  5596. // If both array, type mismatch. If both basic, copy should be fine.
  5597. // So all return false.
  5598. return false;
  5599. } else {
  5600. // One struct, one basic type.
  5601. // Make sure all struct element match the basic type and basic type is
  5602. // vector4.
  5603. llvm::StructType *ST = SrcST ? SrcST : DestST;
  5604. llvm::Type *Ty = SrcST ? DestEltTy : SrcEltTy;
  5605. if (!Ty->isVectorTy())
  5606. return false;
  5607. if (Ty->getVectorNumElements() != 4)
  5608. return false;
  5609. for (llvm::Type *EltTy : ST->elements()) {
  5610. if (EltTy != Ty)
  5611. return false;
  5612. }
  5613. return true;
  5614. }
  5615. }
  5616. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  5617. clang::QualType SrcTy,
  5618. llvm::Value *DestPtr,
  5619. clang::QualType DestTy) {
  5620. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  5621. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  5622. if (SrcPtrTy == DestPtrTy) {
  5623. // Memcpy if type is match.
  5624. unsigned size = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5625. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  5626. return;
  5627. } else if (HLModule::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  5628. HLModule::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  5629. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5630. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  5631. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  5632. return;
  5633. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(DestPtr)) {
  5634. if (GV->isInternalLinkage(GV->getLinkage()) &&
  5635. IsTypeMatchForMemcpy(SrcPtrTy, DestPtrTy)) {
  5636. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5637. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  5638. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::min(sizeSrc, sizeDest), 1);
  5639. return;
  5640. }
  5641. }
  5642. // It is possiable to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  5643. // the same way. But split value to scalar will generate many instruction when
  5644. // src type is same as dest type.
  5645. SmallVector<Value *, 4> idxList;
  5646. SmallVector<Value *, 4> SrcGEPList;
  5647. SmallVector<QualType, 4> SrcEltTyList;
  5648. FlattenAggregatePtrToGepList(CGF, SrcPtr, idxList, SrcTy, SrcPtr->getType(),
  5649. SrcGEPList, SrcEltTyList);
  5650. SmallVector<Value *, 4> LdEltList;
  5651. LoadFlattenedGepList(CGF, SrcGEPList, SrcEltTyList, LdEltList);
  5652. idxList.clear();
  5653. SmallVector<Value *, 4> DestGEPList;
  5654. SmallVector<QualType, 4> DestEltTyList;
  5655. FlattenAggregatePtrToGepList(CGF, DestPtr, idxList, DestTy,
  5656. DestPtr->getType(), DestGEPList, DestEltTyList);
  5657. StoreFlattenedGepList(CGF, DestGEPList, DestEltTyList, LdEltList,
  5658. SrcEltTyList);
  5659. }
  5660. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  5661. llvm::Value *DestPtr,
  5662. clang::QualType Ty) {
  5663. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  5664. }
  5665. static void SimpleFlatValCopy(Value *DestPtr, Value *SrcVal, QualType Ty,
  5666. QualType SrcTy, ArrayRef<Value *> idxList,
  5667. CGBuilderTy &Builder) {
  5668. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5669. llvm::Type *ToTy = DestGEP->getType()->getPointerElementType();
  5670. llvm::Type *EltToTy = ToTy;
  5671. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(ToTy)) {
  5672. EltToTy = VT->getElementType();
  5673. }
  5674. if (EltToTy != SrcVal->getType()) {
  5675. Instruction::CastOps castOp =
  5676. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5677. IsUnsigned(SrcTy), IsUnsigned(Ty), SrcVal->getType(), ToTy));
  5678. SrcVal = Builder.CreateCast(castOp, SrcVal, EltToTy);
  5679. }
  5680. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(ToTy)) {
  5681. llvm::VectorType *VT1 = llvm::VectorType::get(EltToTy, 1);
  5682. Value *V1 =
  5683. Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal, (uint64_t)0);
  5684. std::vector<int> shufIdx(VT->getNumElements(), 0);
  5685. Value *Vec = Builder.CreateShuffleVector(V1, V1, shufIdx);
  5686. Builder.CreateStore(Vec, DestGEP);
  5687. } else
  5688. Builder.CreateStore(SrcVal, DestGEP);
  5689. }
  5690. void CGMSHLSLRuntime::EmitHLSLFlatConversionToAggregate(
  5691. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  5692. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  5693. llvm::Type *Ty) {
  5694. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5695. Constant *idx = Constant::getIntegerValue(
  5696. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5697. idxList.emplace_back(idx);
  5698. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList, Type,
  5699. SrcType, PT->getElementType());
  5700. idxList.pop_back();
  5701. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5702. // Use matLd/St for matrix.
  5703. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5704. unsigned row, col;
  5705. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, col, row);
  5706. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  5707. if (EltTy != SrcVal->getType()) {
  5708. Instruction::CastOps castOp =
  5709. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5710. IsUnsigned(SrcType), IsUnsigned(Type), SrcVal->getType(), EltTy));
  5711. SrcVal = CGF.Builder.CreateCast(castOp, SrcVal, EltTy);
  5712. }
  5713. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  5714. (uint64_t)0);
  5715. std::vector<int> shufIdx(col * row, 0);
  5716. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  5717. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  5718. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  5719. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  5720. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5721. DXASSERT(!HLModule::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  5722. const clang::RecordType *RT = Type->getAsStructureType();
  5723. RecordDecl *RD = RT->getDecl();
  5724. auto fieldIter = RD->field_begin();
  5725. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5726. // Take care base.
  5727. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5728. if (CXXRD->getNumBases()) {
  5729. for (const auto &I : CXXRD->bases()) {
  5730. const CXXRecordDecl *BaseDecl =
  5731. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5732. if (BaseDecl->field_empty())
  5733. continue;
  5734. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5735. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5736. llvm::Type *ET = ST->getElementType(i);
  5737. Constant *idx = llvm::Constant::getIntegerValue(
  5738. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5739. idxList.emplace_back(idx);
  5740. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList,
  5741. parentTy, SrcType, ET);
  5742. idxList.pop_back();
  5743. }
  5744. }
  5745. }
  5746. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5747. fieldIter != fieldEnd; ++fieldIter) {
  5748. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5749. llvm::Type *ET = ST->getElementType(i);
  5750. Constant *idx = llvm::Constant::getIntegerValue(
  5751. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5752. idxList.emplace_back(idx);
  5753. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList,
  5754. fieldIter->getType(), SrcType, ET);
  5755. idxList.pop_back();
  5756. }
  5757. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5758. llvm::Type *ET = AT->getElementType();
  5759. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5760. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5761. Constant *idx = Constant::getIntegerValue(
  5762. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5763. idxList.emplace_back(idx);
  5764. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList, EltType,
  5765. SrcType, ET);
  5766. idxList.pop_back();
  5767. }
  5768. } else {
  5769. SimpleFlatValCopy(DestPtr, SrcVal, Type, SrcType, idxList, CGF.Builder);
  5770. }
  5771. }
  5772. void CGMSHLSLRuntime::EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF,
  5773. Value *Val,
  5774. Value *DestPtr,
  5775. QualType Ty,
  5776. QualType SrcTy) {
  5777. if (SrcTy->isBuiltinType()) {
  5778. SmallVector<Value *, 4> idxList;
  5779. // Add first 0 for DestPtr.
  5780. Constant *idx = Constant::getIntegerValue(
  5781. IntegerType::get(Val->getContext(), 32), APInt(32, 0));
  5782. idxList.emplace_back(idx);
  5783. EmitHLSLFlatConversionToAggregate(
  5784. CGF, Val, DestPtr, idxList, Ty, SrcTy,
  5785. DestPtr->getType()->getPointerElementType());
  5786. }
  5787. else {
  5788. SmallVector<Value *, 4> idxList;
  5789. SmallVector<Value *, 4> DestGEPList;
  5790. SmallVector<QualType, 4> DestEltTyList;
  5791. FlattenAggregatePtrToGepList(CGF, DestPtr, idxList, Ty, DestPtr->getType(), DestGEPList, DestEltTyList);
  5792. SmallVector<Value *, 4> EltList;
  5793. SmallVector<QualType, 4> EltTyList;
  5794. FlattenValToInitList(CGF, EltList, EltTyList, SrcTy, Val);
  5795. StoreFlattenedGepList(CGF, DestGEPList, DestEltTyList, EltList, EltTyList);
  5796. }
  5797. }
  5798. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  5799. HLSLRootSignatureAttr *RSA,
  5800. Function *Fn) {
  5801. // Only parse root signature for entry function.
  5802. if (Fn != Entry.Func)
  5803. return;
  5804. StringRef StrRef = RSA->getSignatureName();
  5805. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  5806. SourceLocation SLoc = RSA->getLocation();
  5807. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, &m_pHLModule->GetRootSignature());
  5808. }
  5809. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  5810. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  5811. llvm::SmallVector<LValue, 8> &castArgList,
  5812. llvm::SmallVector<const Stmt *, 8> &argList,
  5813. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  5814. // Special case: skip first argument of CXXOperatorCall (it is "this").
  5815. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  5816. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  5817. const ParmVarDecl *Param = FD->getParamDecl(i);
  5818. const Expr *Arg = E->getArg(i+ArgsToSkip);
  5819. QualType ParamTy = Param->getType().getNonReferenceType();
  5820. bool RValOnRef = false;
  5821. if (!Param->isModifierOut()) {
  5822. if (!ParamTy->isAggregateType() || hlsl::IsHLSLMatType(ParamTy)) {
  5823. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  5824. // RValue on a reference type.
  5825. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  5826. // TODO: Evolving this to warn then fail in future language versions.
  5827. // Allow special case like cast uint to uint for back-compat.
  5828. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  5829. if (const ImplicitCastExpr *cast =
  5830. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  5831. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  5832. // update the arg
  5833. argList[i] = cast->getSubExpr();
  5834. continue;
  5835. }
  5836. }
  5837. }
  5838. }
  5839. // EmitLValue will report error.
  5840. // Mark RValOnRef to create tmpArg for it.
  5841. RValOnRef = true;
  5842. } else {
  5843. continue;
  5844. }
  5845. }
  5846. }
  5847. // get original arg
  5848. LValue argLV = CGF.EmitLValue(Arg);
  5849. if (!Param->isModifierOut() && !RValOnRef) {
  5850. bool isDefaultAddrSpace = true;
  5851. if (argLV.isSimple()) {
  5852. isDefaultAddrSpace =
  5853. argLV.getAddress()->getType()->getPointerAddressSpace() ==
  5854. DXIL::kDefaultAddrSpace;
  5855. }
  5856. bool isHLSLIntrinsic = false;
  5857. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  5858. isHLSLIntrinsic = Callee->hasAttr<HLSLIntrinsicAttr>();
  5859. }
  5860. // Copy in arg which is not default address space and not on hlsl intrinsic.
  5861. if (isDefaultAddrSpace || isHLSLIntrinsic)
  5862. continue;
  5863. }
  5864. // create temp Var
  5865. VarDecl *tmpArg =
  5866. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  5867. SourceLocation(), SourceLocation(),
  5868. /*IdentifierInfo*/ nullptr, ParamTy,
  5869. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  5870. StorageClass::SC_Auto);
  5871. // Aggregate type will be indirect param convert to pointer type.
  5872. // So don't update to ReferenceType, use RValue for it.
  5873. bool isAggregateType = (ParamTy->isArrayType() || ParamTy->isRecordType()) &&
  5874. !hlsl::IsHLSLVecMatType(ParamTy);
  5875. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  5876. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  5877. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  5878. isAggregateType ? VK_RValue : VK_LValue);
  5879. // update the arg
  5880. argList[i] = tmpRef;
  5881. // create alloc for the tmp arg
  5882. Value *tmpArgAddr = nullptr;
  5883. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  5884. Function *F = InsertBlock->getParent();
  5885. if (ParamTy->isBooleanType()) {
  5886. // Create i32 for bool.
  5887. ParamTy = CGM.getContext().IntTy;
  5888. }
  5889. // Make sure the alloca is in entry block to stop inline create stacksave.
  5890. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5891. tmpArgAddr = AllocaBuilder.CreateAlloca(CGF.ConvertType(ParamTy));
  5892. // add it to local decl map
  5893. TmpArgMap(tmpArg, tmpArgAddr);
  5894. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argLV.getAlignment(),
  5895. CGF.getContext());
  5896. // save for cast after call
  5897. if (Param->isModifierOut()) {
  5898. castArgList.emplace_back(tmpLV);
  5899. castArgList.emplace_back(argLV);
  5900. }
  5901. bool isObject = HLModule::IsHLSLObjectType(
  5902. tmpArgAddr->getType()->getPointerElementType());
  5903. // cast before the call
  5904. if (Param->isModifierIn() &&
  5905. // Don't copy object
  5906. !isObject) {
  5907. QualType ArgTy = Arg->getType();
  5908. Value *outVal = nullptr;
  5909. bool isAggrageteTy = ParamTy->isAggregateType();
  5910. isAggrageteTy &= !IsHLSLVecMatType(ParamTy);
  5911. if (!isAggrageteTy) {
  5912. if (!IsHLSLMatType(ParamTy)) {
  5913. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  5914. outVal = outRVal.getScalarVal();
  5915. } else {
  5916. Value *argAddr = argLV.getAddress();
  5917. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  5918. }
  5919. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  5920. Instruction::CastOps castOp =
  5921. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5922. IsUnsigned(argLV.getType()), IsUnsigned(tmpLV.getType()),
  5923. outVal->getType(), ToTy));
  5924. Value *castVal = CGF.Builder.CreateCast(castOp, outVal, ToTy);
  5925. if (!HLMatrixLower::IsMatrixType(ToTy))
  5926. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  5927. else
  5928. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  5929. } else {
  5930. SmallVector<Value *, 4> idxList;
  5931. EmitHLSLAggregateCopy(CGF, argLV.getAddress(), tmpLV.getAddress(),
  5932. idxList, ArgTy, ParamTy,
  5933. argLV.getAddress()->getType());
  5934. }
  5935. }
  5936. }
  5937. }
  5938. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  5939. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) {
  5940. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  5941. // cast after the call
  5942. LValue tmpLV = castArgList[i];
  5943. LValue argLV = castArgList[i + 1];
  5944. QualType ArgTy = argLV.getType().getNonReferenceType();
  5945. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5946. Value *tmpArgAddr = tmpLV.getAddress();
  5947. Value *outVal = nullptr;
  5948. bool isAggrageteTy = ArgTy->isAggregateType();
  5949. isAggrageteTy &= !IsHLSLVecMatType(ArgTy);
  5950. bool isObject = HLModule::IsHLSLObjectType(
  5951. tmpArgAddr->getType()->getPointerElementType());
  5952. if (!isObject) {
  5953. if (!isAggrageteTy) {
  5954. if (!IsHLSLMatType(ParamTy))
  5955. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  5956. else
  5957. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  5958. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  5959. llvm::Type *FromTy = outVal->getType();
  5960. Value *castVal = outVal;
  5961. if (ToTy == FromTy) {
  5962. // Don't need cast.
  5963. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  5964. if (ToTy->getScalarType() == ToTy) {
  5965. DXASSERT(FromTy->isVectorTy() &&
  5966. FromTy->getVectorNumElements() == 1,
  5967. "must be vector of 1 element");
  5968. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  5969. } else {
  5970. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  5971. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  5972. "must be vector of 1 element");
  5973. castVal = UndefValue::get(ToTy);
  5974. castVal =
  5975. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  5976. }
  5977. } else {
  5978. Instruction::CastOps castOp =
  5979. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5980. IsUnsigned(tmpLV.getType()), IsUnsigned(argLV.getType()),
  5981. outVal->getType(), ToTy));
  5982. castVal = CGF.Builder.CreateCast(castOp, outVal, ToTy);
  5983. }
  5984. if (!HLMatrixLower::IsMatrixType(ToTy))
  5985. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  5986. else {
  5987. Value *destPtr = argLV.getAddress();
  5988. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  5989. }
  5990. } else {
  5991. SmallVector<Value *, 4> idxList;
  5992. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  5993. idxList, ParamTy, ArgTy,
  5994. argLV.getAddress()->getType());
  5995. }
  5996. } else
  5997. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  5998. }
  5999. }
  6000. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  6001. return new CGMSHLSLRuntime(CGM);
  6002. }