CGHLSLMS.cpp 250 KB

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