CGHLSLMS.cpp 232 KB

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