CGHLSLMS.cpp 239 KB

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