2
0

CGHLSLMS.cpp 249 KB

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