CGHLSLMS.cpp 226 KB

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