CGHLSLMS.cpp 213 KB

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