CGHLSLMS.cpp 225 KB

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