CGHLSLMS.cpp 238 KB

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