CGHLSLMS.cpp 221 KB

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