CGHLSLMS.cpp 198 KB

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