CGHLSLMS.cpp 259 KB

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