CGHLSLMS.cpp 272 KB

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