CGHLSLMS.cpp 269 KB

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