CGHLSLMS.cpp 219 KB

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