CGHLSLMS.cpp 215 KB

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