CGHLSLMS.cpp 234 KB

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