2
0

SROA.cpp 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686
  1. //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// This transformation implements the well known scalar replacement of
  11. /// aggregates transformation. It tries to identify promotable elements of an
  12. /// aggregate alloca, and promote them to registers. It will also try to
  13. /// convert uses of an element (or set of elements) of an alloca into a vector
  14. /// or bitfield-style integer scalar if appropriate.
  15. ///
  16. /// It works to do this with minimal slicing of the alloca so that regions
  17. /// which are merely transferred in and out of external memory remain unchanged
  18. /// and are not decomposed to scalar code.
  19. ///
  20. /// Because this also performs alloca promotion, it can be thought of as also
  21. /// serving the purpose of SSA formation. The algorithm iterates on the
  22. /// function until all opportunities for promotion have been realized.
  23. ///
  24. //===----------------------------------------------------------------------===//
  25. #include "llvm/Transforms/Scalar.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SetVector.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/Analysis/AssumptionCache.h"
  31. #include "llvm/Analysis/Loads.h"
  32. #include "llvm/Analysis/PtrUseVisitor.h"
  33. #include "llvm/Analysis/ValueTracking.h"
  34. #include "llvm/IR/Constants.h"
  35. #include "llvm/IR/DIBuilder.h"
  36. #include "llvm/IR/DataLayout.h"
  37. #include "llvm/IR/DebugInfo.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Dominators.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/IRBuilder.h"
  42. #include "llvm/IR/InstVisitor.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/LLVMContext.h"
  46. #include "llvm/IR/Operator.h"
  47. #include "llvm/Pass.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/Debug.h"
  51. #include "llvm/Support/ErrorHandling.h"
  52. #include "llvm/Support/MathExtras.h"
  53. #include "llvm/Support/TimeValue.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Transforms/Utils/Local.h"
  56. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  57. #include "llvm/Transforms/Utils/SSAUpdater.h"
  58. #include "dxc/DXIL/DxilUtil.h" // HLSL Change - don't sroa resource type.
  59. #include "dxc/DXIL/DxilMetadataHelper.h" // HLSL Change - support strided debug variables
  60. #include "dxc/HLSL/HLMatrixType.h" // HLSL Change - don't sroa matrix types.
  61. #if __cplusplus >= 201103L && !defined(NDEBUG)
  62. // We only use this for a debug check in C++11
  63. #include <random>
  64. #endif
  65. using namespace llvm;
  66. #define DEBUG_TYPE "sroa"
  67. STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
  68. STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
  69. STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
  70. STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
  71. STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
  72. STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
  73. STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
  74. STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
  75. STATISTIC(NumDeleted, "Number of instructions deleted");
  76. STATISTIC(NumVectorized, "Number of vectorized aggregates");
  77. #if 0 // HLSL Change Starts - option pending
  78. /// Hidden option to force the pass to not use DomTree and mem2reg, instead
  79. /// forming SSA values through the SSAUpdater infrastructure.
  80. static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
  81. cl::Hidden);
  82. /// Hidden option to enable randomly shuffling the slices to help uncover
  83. /// instability in their order.
  84. static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
  85. cl::init(false), cl::Hidden);
  86. /// Hidden option to experiment with completely strict handling of inbounds
  87. /// GEPs.
  88. static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
  89. cl::Hidden);
  90. #else
  91. static const bool ForceSSAUpdater = false;
  92. static const bool SROAStrictInbounds = false;
  93. #endif // HLSL Change Ends
  94. namespace {
  95. /// \brief A custom IRBuilder inserter which prefixes all names if they are
  96. /// preserved.
  97. template <bool preserveNames = true>
  98. class IRBuilderPrefixedInserter
  99. : public IRBuilderDefaultInserter<preserveNames> {
  100. std::string Prefix;
  101. public:
  102. void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
  103. protected:
  104. void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
  105. BasicBlock::iterator InsertPt) const {
  106. IRBuilderDefaultInserter<preserveNames>::InsertHelper(
  107. I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
  108. }
  109. };
  110. // Specialization for not preserving the name is trivial.
  111. template <>
  112. class IRBuilderPrefixedInserter<false>
  113. : public IRBuilderDefaultInserter<false> {
  114. public:
  115. void SetNamePrefix(const Twine &P) {}
  116. };
  117. /// \brief Provide a typedef for IRBuilder that drops names in release builds.
  118. #ifndef NDEBUG
  119. typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
  120. IRBuilderTy;
  121. #else
  122. typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
  123. IRBuilderTy;
  124. #endif
  125. }
  126. namespace {
  127. /// \brief A used slice of an alloca.
  128. ///
  129. /// This structure represents a slice of an alloca used by some instruction. It
  130. /// stores both the begin and end offsets of this use, a pointer to the use
  131. /// itself, and a flag indicating whether we can classify the use as splittable
  132. /// or not when forming partitions of the alloca.
  133. class Slice {
  134. /// \brief The beginning offset of the range.
  135. uint64_t BeginOffset;
  136. /// \brief The ending offset, not included in the range.
  137. uint64_t EndOffset;
  138. /// \brief Storage for both the use of this slice and whether it can be
  139. /// split.
  140. PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
  141. public:
  142. Slice() : BeginOffset(), EndOffset() {}
  143. Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
  144. : BeginOffset(BeginOffset), EndOffset(EndOffset),
  145. UseAndIsSplittable(U, IsSplittable) {}
  146. uint64_t beginOffset() const { return BeginOffset; }
  147. uint64_t endOffset() const { return EndOffset; }
  148. bool isSplittable() const { return UseAndIsSplittable.getInt(); }
  149. void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
  150. Use *getUse() const { return UseAndIsSplittable.getPointer(); }
  151. bool isDead() const { return getUse() == nullptr; }
  152. void kill() { UseAndIsSplittable.setPointer(nullptr); }
  153. /// \brief Support for ordering ranges.
  154. ///
  155. /// This provides an ordering over ranges such that start offsets are
  156. /// always increasing, and within equal start offsets, the end offsets are
  157. /// decreasing. Thus the spanning range comes first in a cluster with the
  158. /// same start position.
  159. bool operator<(const Slice &RHS) const {
  160. if (beginOffset() < RHS.beginOffset())
  161. return true;
  162. if (beginOffset() > RHS.beginOffset())
  163. return false;
  164. if (isSplittable() != RHS.isSplittable())
  165. return !isSplittable();
  166. if (endOffset() > RHS.endOffset())
  167. return true;
  168. return false;
  169. }
  170. /// \brief Support comparison with a single offset to allow binary searches.
  171. friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
  172. uint64_t RHSOffset) {
  173. return LHS.beginOffset() < RHSOffset;
  174. }
  175. friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
  176. const Slice &RHS) {
  177. return LHSOffset < RHS.beginOffset();
  178. }
  179. bool operator==(const Slice &RHS) const {
  180. return isSplittable() == RHS.isSplittable() &&
  181. beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
  182. }
  183. bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
  184. };
  185. } // end anonymous namespace
  186. namespace llvm {
  187. template <typename T> struct isPodLike;
  188. template <> struct isPodLike<Slice> { static const bool value = true; };
  189. }
  190. namespace {
  191. /// \brief Representation of the alloca slices.
  192. ///
  193. /// This class represents the slices of an alloca which are formed by its
  194. /// various uses. If a pointer escapes, we can't fully build a representation
  195. /// for the slices used and we reflect that in this structure. The uses are
  196. /// stored, sorted by increasing beginning offset and with unsplittable slices
  197. /// starting at a particular offset before splittable slices.
  198. class AllocaSlices {
  199. public:
  200. /// \brief Construct the slices of a particular alloca.
  201. AllocaSlices(const DataLayout &DL, AllocaInst &AI,
  202. const bool SkipHLSLMat); // HLSL Change - not sroa matrix type.
  203. /// \brief Test whether a pointer to the allocation escapes our analysis.
  204. ///
  205. /// If this is true, the slices are never fully built and should be
  206. /// ignored.
  207. bool isEscaped() const { return PointerEscapingInstr; }
  208. /// \brief Support for iterating over the slices.
  209. /// @{
  210. typedef SmallVectorImpl<Slice>::iterator iterator;
  211. typedef iterator_range<iterator> range;
  212. iterator begin() { return Slices.begin(); }
  213. iterator end() { return Slices.end(); }
  214. typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
  215. typedef iterator_range<const_iterator> const_range;
  216. const_iterator begin() const { return Slices.begin(); }
  217. const_iterator end() const { return Slices.end(); }
  218. /// @}
  219. /// \brief Erase a range of slices.
  220. void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
  221. /// \brief Insert new slices for this alloca.
  222. ///
  223. /// This moves the slices into the alloca's slices collection, and re-sorts
  224. /// everything so that the usual ordering properties of the alloca's slices
  225. /// hold.
  226. void insert(ArrayRef<Slice> NewSlices) {
  227. int OldSize = Slices.size();
  228. Slices.append(NewSlices.begin(), NewSlices.end());
  229. auto SliceI = Slices.begin() + OldSize;
  230. std::sort(SliceI, Slices.end());
  231. std::inplace_merge(Slices.begin(), SliceI, Slices.end());
  232. }
  233. // Forward declare an iterator to befriend it.
  234. class partition_iterator;
  235. /// \brief A partition of the slices.
  236. ///
  237. /// An ephemeral representation for a range of slices which can be viewed as
  238. /// a partition of the alloca. This range represents a span of the alloca's
  239. /// memory which cannot be split, and provides access to all of the slices
  240. /// overlapping some part of the partition.
  241. ///
  242. /// Objects of this type are produced by traversing the alloca's slices, but
  243. /// are only ephemeral and not persistent.
  244. class Partition {
  245. private:
  246. friend class AllocaSlices;
  247. friend class AllocaSlices::partition_iterator;
  248. /// \brief The begining and ending offsets of the alloca for this partition.
  249. uint64_t BeginOffset, EndOffset;
  250. /// \brief The start end end iterators of this partition.
  251. iterator SI, SJ;
  252. /// \brief A collection of split slice tails overlapping the partition.
  253. SmallVector<Slice *, 4> SplitTails;
  254. /// \brief Raw constructor builds an empty partition starting and ending at
  255. /// the given iterator.
  256. Partition(iterator SI) : SI(SI), SJ(SI) {}
  257. public:
  258. /// \brief The start offset of this partition.
  259. ///
  260. /// All of the contained slices start at or after this offset.
  261. uint64_t beginOffset() const { return BeginOffset; }
  262. /// \brief The end offset of this partition.
  263. ///
  264. /// All of the contained slices end at or before this offset.
  265. uint64_t endOffset() const { return EndOffset; }
  266. /// \brief The size of the partition.
  267. ///
  268. /// Note that this can never be zero.
  269. uint64_t size() const {
  270. assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
  271. return EndOffset - BeginOffset;
  272. }
  273. /// \brief Test whether this partition contains no slices, and merely spans
  274. /// a region occupied by split slices.
  275. bool empty() const { return SI == SJ; }
  276. /// \name Iterate slices that start within the partition.
  277. /// These may be splittable or unsplittable. They have a begin offset >= the
  278. /// partition begin offset.
  279. /// @{
  280. // FIXME: We should probably define a "concat_iterator" helper and use that
  281. // to stitch together pointee_iterators over the split tails and the
  282. // contiguous iterators of the partition. That would give a much nicer
  283. // interface here. We could then additionally expose filtered iterators for
  284. // split, unsplit, and unsplittable splices based on the usage patterns.
  285. iterator begin() const { return SI; }
  286. iterator end() const { return SJ; }
  287. /// @}
  288. /// \brief Get the sequence of split slice tails.
  289. ///
  290. /// These tails are of slices which start before this partition but are
  291. /// split and overlap into the partition. We accumulate these while forming
  292. /// partitions.
  293. ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
  294. };
  295. /// \brief An iterator over partitions of the alloca's slices.
  296. ///
  297. /// This iterator implements the core algorithm for partitioning the alloca's
  298. /// slices. It is a forward iterator as we don't support backtracking for
  299. /// efficiency reasons, and re-use a single storage area to maintain the
  300. /// current set of split slices.
  301. ///
  302. /// It is templated on the slice iterator type to use so that it can operate
  303. /// with either const or non-const slice iterators.
  304. class partition_iterator
  305. : public iterator_facade_base<partition_iterator,
  306. std::forward_iterator_tag, Partition> {
  307. friend class AllocaSlices;
  308. /// \brief Most of the state for walking the partitions is held in a class
  309. /// with a nice interface for examining them.
  310. Partition P;
  311. /// \brief We need to keep the end of the slices to know when to stop.
  312. AllocaSlices::iterator SE;
  313. /// \brief We also need to keep track of the maximum split end offset seen.
  314. /// FIXME: Do we really?
  315. uint64_t MaxSplitSliceEndOffset;
  316. /// \brief Sets the partition to be empty at given iterator, and sets the
  317. /// end iterator.
  318. partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
  319. : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
  320. // If not already at the end, advance our state to form the initial
  321. // partition.
  322. if (SI != SE)
  323. advance();
  324. }
  325. /// \brief Advance the iterator to the next partition.
  326. ///
  327. /// Requires that the iterator not be at the end of the slices.
  328. void advance() {
  329. assert((P.SI != SE || !P.SplitTails.empty()) &&
  330. "Cannot advance past the end of the slices!");
  331. // Clear out any split uses which have ended.
  332. if (!P.SplitTails.empty()) {
  333. if (P.EndOffset >= MaxSplitSliceEndOffset) {
  334. // If we've finished all splits, this is easy.
  335. P.SplitTails.clear();
  336. MaxSplitSliceEndOffset = 0;
  337. } else {
  338. // Remove the uses which have ended in the prior partition. This
  339. // cannot change the max split slice end because we just checked that
  340. // the prior partition ended prior to that max.
  341. P.SplitTails.erase(
  342. std::remove_if(
  343. P.SplitTails.begin(), P.SplitTails.end(),
  344. [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
  345. P.SplitTails.end());
  346. assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
  347. [&](Slice *S) {
  348. return S->endOffset() == MaxSplitSliceEndOffset;
  349. }) &&
  350. "Could not find the current max split slice offset!");
  351. assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
  352. [&](Slice *S) {
  353. return S->endOffset() <= MaxSplitSliceEndOffset;
  354. }) &&
  355. "Max split slice end offset is not actually the max!");
  356. }
  357. }
  358. // If P.SI is already at the end, then we've cleared the split tail and
  359. // now have an end iterator.
  360. if (P.SI == SE) {
  361. assert(P.SplitTails.empty() && "Failed to clear the split slices!");
  362. return;
  363. }
  364. // If we had a non-empty partition previously, set up the state for
  365. // subsequent partitions.
  366. if (P.SI != P.SJ) {
  367. // Accumulate all the splittable slices which started in the old
  368. // partition into the split list.
  369. for (Slice &S : P)
  370. if (S.isSplittable() && S.endOffset() > P.EndOffset) {
  371. P.SplitTails.push_back(&S);
  372. MaxSplitSliceEndOffset =
  373. std::max(S.endOffset(), MaxSplitSliceEndOffset);
  374. }
  375. // Start from the end of the previous partition.
  376. P.SI = P.SJ;
  377. // If P.SI is now at the end, we at most have a tail of split slices.
  378. if (P.SI == SE) {
  379. P.BeginOffset = P.EndOffset;
  380. P.EndOffset = MaxSplitSliceEndOffset;
  381. return;
  382. }
  383. // If the we have split slices and the next slice is after a gap and is
  384. // not splittable immediately form an empty partition for the split
  385. // slices up until the next slice begins.
  386. if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
  387. !P.SI->isSplittable()) {
  388. P.BeginOffset = P.EndOffset;
  389. P.EndOffset = P.SI->beginOffset();
  390. return;
  391. }
  392. }
  393. // OK, we need to consume new slices. Set the end offset based on the
  394. // current slice, and step SJ past it. The beginning offset of the
  395. // parttion is the beginning offset of the next slice unless we have
  396. // pre-existing split slices that are continuing, in which case we begin
  397. // at the prior end offset.
  398. P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
  399. P.EndOffset = P.SI->endOffset();
  400. ++P.SJ;
  401. // There are two strategies to form a partition based on whether the
  402. // partition starts with an unsplittable slice or a splittable slice.
  403. if (!P.SI->isSplittable()) {
  404. // When we're forming an unsplittable region, it must always start at
  405. // the first slice and will extend through its end.
  406. assert(P.BeginOffset == P.SI->beginOffset());
  407. // Form a partition including all of the overlapping slices with this
  408. // unsplittable slice.
  409. while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
  410. if (!P.SJ->isSplittable())
  411. P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
  412. ++P.SJ;
  413. }
  414. // We have a partition across a set of overlapping unsplittable
  415. // partitions.
  416. return;
  417. }
  418. // If we're starting with a splittable slice, then we need to form
  419. // a synthetic partition spanning it and any other overlapping splittable
  420. // splices.
  421. assert(P.SI->isSplittable() && "Forming a splittable partition!");
  422. // Collect all of the overlapping splittable slices.
  423. while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
  424. P.SJ->isSplittable()) {
  425. P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
  426. ++P.SJ;
  427. }
  428. // Back upiP.EndOffset if we ended the span early when encountering an
  429. // unsplittable slice. This synthesizes the early end offset of
  430. // a partition spanning only splittable slices.
  431. if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
  432. assert(!P.SJ->isSplittable());
  433. P.EndOffset = P.SJ->beginOffset();
  434. }
  435. }
  436. public:
  437. bool operator==(const partition_iterator &RHS) const {
  438. assert(SE == RHS.SE &&
  439. "End iterators don't match between compared partition iterators!");
  440. // The observed positions of partitions is marked by the P.SI iterator and
  441. // the emptyness of the split slices. The latter is only relevant when
  442. // P.SI == SE, as the end iterator will additionally have an empty split
  443. // slices list, but the prior may have the same P.SI and a tail of split
  444. // slices.
  445. if (P.SI == RHS.P.SI &&
  446. P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
  447. assert(P.SJ == RHS.P.SJ &&
  448. "Same set of slices formed two different sized partitions!");
  449. assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
  450. "Same slice position with differently sized non-empty split "
  451. "slice tails!");
  452. return true;
  453. }
  454. return false;
  455. }
  456. partition_iterator &operator++() {
  457. advance();
  458. return *this;
  459. }
  460. Partition &operator*() { return P; }
  461. };
  462. /// \brief A forward range over the partitions of the alloca's slices.
  463. ///
  464. /// This accesses an iterator range over the partitions of the alloca's
  465. /// slices. It computes these partitions on the fly based on the overlapping
  466. /// offsets of the slices and the ability to split them. It will visit "empty"
  467. /// partitions to cover regions of the alloca only accessed via split
  468. /// slices.
  469. iterator_range<partition_iterator> partitions() {
  470. return make_range(partition_iterator(begin(), end()),
  471. partition_iterator(end(), end()));
  472. }
  473. /// \brief Access the dead users for this alloca.
  474. ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
  475. /// \brief Access the dead operands referring to this alloca.
  476. ///
  477. /// These are operands which have cannot actually be used to refer to the
  478. /// alloca as they are outside its range and the user doesn't correct for
  479. /// that. These mostly consist of PHI node inputs and the like which we just
  480. /// need to replace with undef.
  481. ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
  482. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  483. void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
  484. void printSlice(raw_ostream &OS, const_iterator I,
  485. StringRef Indent = " ") const;
  486. void printUse(raw_ostream &OS, const_iterator I,
  487. StringRef Indent = " ") const;
  488. void print(raw_ostream &OS) const;
  489. void dump(const_iterator I) const;
  490. void dump() const;
  491. #endif
  492. private:
  493. template <typename DerivedT, typename RetT = void> class BuilderBase;
  494. class SliceBuilder;
  495. friend class AllocaSlices::SliceBuilder;
  496. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  497. /// \brief Handle to alloca instruction to simplify method interfaces.
  498. AllocaInst &AI;
  499. #endif
  500. /// \brief The instruction responsible for this alloca not having a known set
  501. /// of slices.
  502. ///
  503. /// When an instruction (potentially) escapes the pointer to the alloca, we
  504. /// store a pointer to that here and abort trying to form slices of the
  505. /// alloca. This will be null if the alloca slices are analyzed successfully.
  506. Instruction *PointerEscapingInstr;
  507. /// \brief The slices of the alloca.
  508. ///
  509. /// We store a vector of the slices formed by uses of the alloca here. This
  510. /// vector is sorted by increasing begin offset, and then the unsplittable
  511. /// slices before the splittable ones. See the Slice inner class for more
  512. /// details.
  513. SmallVector<Slice, 8> Slices;
  514. /// \brief Instructions which will become dead if we rewrite the alloca.
  515. ///
  516. /// Note that these are not separated by slice. This is because we expect an
  517. /// alloca to be completely rewritten or not rewritten at all. If rewritten,
  518. /// all these instructions can simply be removed and replaced with undef as
  519. /// they come from outside of the allocated space.
  520. SmallVector<Instruction *, 8> DeadUsers;
  521. /// \brief Operands which will become dead if we rewrite the alloca.
  522. ///
  523. /// These are operands that in their particular use can be replaced with
  524. /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
  525. /// to PHI nodes and the like. They aren't entirely dead (there might be
  526. /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
  527. /// want to swap this particular input for undef to simplify the use lists of
  528. /// the alloca.
  529. SmallVector<Use *, 8> DeadOperands;
  530. };
  531. }
  532. static Value *foldSelectInst(SelectInst &SI) {
  533. // If the condition being selected on is a constant or the same value is
  534. // being selected between, fold the select. Yes this does (rarely) happen
  535. // early on.
  536. if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
  537. return SI.getOperand(1 + CI->isZero());
  538. if (SI.getOperand(1) == SI.getOperand(2))
  539. return SI.getOperand(1);
  540. return nullptr;
  541. }
  542. /// \brief A helper that folds a PHI node or a select.
  543. static Value *foldPHINodeOrSelectInst(Instruction &I) {
  544. if (PHINode *PN = dyn_cast<PHINode>(&I)) {
  545. // If PN merges together the same value, return that value.
  546. return PN->hasConstantValue();
  547. }
  548. return foldSelectInst(cast<SelectInst>(I));
  549. }
  550. /// \brief Builder for the alloca slices.
  551. ///
  552. /// This class builds a set of alloca slices by recursively visiting the uses
  553. /// of an alloca and making a slice for each load and store at each offset.
  554. class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
  555. friend class PtrUseVisitor<SliceBuilder>;
  556. friend class InstVisitor<SliceBuilder>;
  557. typedef PtrUseVisitor<SliceBuilder> Base;
  558. const bool SkipHLSLMat; // HLSL Change - not sroa matrix type.
  559. const uint64_t AllocSize;
  560. AllocaSlices &AS;
  561. SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
  562. SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
  563. /// \brief Set to de-duplicate dead instructions found in the use walk.
  564. SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
  565. public:
  566. SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS,
  567. const bool SkipHLSLMat)
  568. : PtrUseVisitor<SliceBuilder>(DL),
  569. SkipHLSLMat(SkipHLSLMat), // HLSL Change - not sroa matrix type.
  570. AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
  571. private:
  572. void markAsDead(Instruction &I) {
  573. if (VisitedDeadInsts.insert(&I).second)
  574. AS.DeadUsers.push_back(&I);
  575. }
  576. void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
  577. bool IsSplittable = false) {
  578. // Completely skip uses which have a zero size or start either before or
  579. // past the end of the allocation.
  580. if (Size == 0 || Offset.uge(AllocSize)) {
  581. DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
  582. << " which has zero size or starts outside of the "
  583. << AllocSize << " byte alloca:\n"
  584. << " alloca: " << AS.AI << "\n"
  585. << " use: " << I << "\n");
  586. return markAsDead(I);
  587. }
  588. uint64_t BeginOffset = Offset.getZExtValue();
  589. uint64_t EndOffset = BeginOffset + Size;
  590. // Clamp the end offset to the end of the allocation. Note that this is
  591. // formulated to handle even the case where "BeginOffset + Size" overflows.
  592. // This may appear superficially to be something we could ignore entirely,
  593. // but that is not so! There may be widened loads or PHI-node uses where
  594. // some instructions are dead but not others. We can't completely ignore
  595. // them, and so have to record at least the information here.
  596. assert(AllocSize >= BeginOffset); // Established above.
  597. if (Size > AllocSize - BeginOffset) {
  598. DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
  599. << " to remain within the " << AllocSize << " byte alloca:\n"
  600. << " alloca: " << AS.AI << "\n"
  601. << " use: " << I << "\n");
  602. EndOffset = AllocSize;
  603. }
  604. AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
  605. }
  606. void visitBitCastInst(BitCastInst &BC) {
  607. if (BC.use_empty())
  608. return markAsDead(BC);
  609. // HLSL Change Begin - not sroa matrix type.
  610. if (PointerType *PT = dyn_cast<PointerType>(BC.getType())) {
  611. Type *EltTy = PT->getElementType();
  612. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(EltTy)) ||
  613. hlsl::dxilutil::IsHLSLObjectType(EltTy)) {
  614. AS.PointerEscapingInstr = &BC;
  615. return;
  616. }
  617. if (PointerType *SrcPT = dyn_cast<PointerType>(BC.getSrcTy())) {
  618. Type *SrcEltTy = SrcPT->getElementType();
  619. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(SrcEltTy)) ||
  620. hlsl::dxilutil::IsHLSLObjectType(SrcEltTy)) {
  621. AS.PointerEscapingInstr = &BC;
  622. return;
  623. }
  624. }
  625. }
  626. // HLSL Change End.
  627. return Base::visitBitCastInst(BC);
  628. }
  629. void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  630. if (GEPI.use_empty())
  631. return markAsDead(GEPI);
  632. if (SROAStrictInbounds && GEPI.isInBounds()) {
  633. // FIXME: This is a manually un-factored variant of the basic code inside
  634. // of GEPs with checking of the inbounds invariant specified in the
  635. // langref in a very strict sense. If we ever want to enable
  636. // SROAStrictInbounds, this code should be factored cleanly into
  637. // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
  638. // by writing out the code here where we have tho underlying allocation
  639. // size readily available.
  640. APInt GEPOffset = Offset;
  641. const DataLayout &DL = GEPI.getModule()->getDataLayout();
  642. for (gep_type_iterator GTI = gep_type_begin(GEPI),
  643. GTE = gep_type_end(GEPI);
  644. GTI != GTE; ++GTI) {
  645. ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
  646. if (!OpC)
  647. break;
  648. // Handle a struct index, which adds its field offset to the pointer.
  649. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  650. unsigned ElementIdx = OpC->getZExtValue();
  651. const StructLayout *SL = DL.getStructLayout(STy);
  652. GEPOffset +=
  653. APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
  654. } else {
  655. // For array or vector indices, scale the index by the size of the
  656. // type.
  657. APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
  658. GEPOffset += Index * APInt(Offset.getBitWidth(),
  659. DL.getTypeAllocSize(GTI.getIndexedType()));
  660. }
  661. // If this index has computed an intermediate pointer which is not
  662. // inbounds, then the result of the GEP is a poison value and we can
  663. // delete it and all uses.
  664. if (GEPOffset.ugt(AllocSize))
  665. return markAsDead(GEPI);
  666. }
  667. }
  668. return Base::visitGetElementPtrInst(GEPI);
  669. }
  670. void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
  671. uint64_t Size, bool IsVolatile) {
  672. // We allow splitting of non-volatile loads and stores where the type is an
  673. // integer type. These may be used to implement 'memcpy' or other "transfer
  674. // of bits" patterns.
  675. bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
  676. insertUse(I, Offset, Size, IsSplittable);
  677. }
  678. void visitLoadInst(LoadInst &LI) {
  679. // HLSL Change Begin - not sroa matrix type.
  680. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(LI.getType())) ||
  681. hlsl::dxilutil::IsHLSLObjectType(LI.getType()))
  682. return PI.setEscapedAndAborted(&LI);
  683. // HLSL Change End.
  684. assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
  685. "All simple FCA loads should have been pre-split");
  686. if (!IsOffsetKnown)
  687. return PI.setAborted(&LI);
  688. const DataLayout &DL = LI.getModule()->getDataLayout();
  689. uint64_t Size = DL.getTypeStoreSize(LI.getType());
  690. return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
  691. }
  692. void visitStoreInst(StoreInst &SI) {
  693. Value *ValOp = SI.getValueOperand();
  694. if (ValOp == *U)
  695. return PI.setEscapedAndAborted(&SI);
  696. // HLSL Change Begin - not sroa matrix type.
  697. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(ValOp->getType())) ||
  698. hlsl::dxilutil::IsHLSLObjectType(ValOp->getType()))
  699. return PI.setEscapedAndAborted(&SI);
  700. // HLSL Change End.
  701. if (!IsOffsetKnown)
  702. return PI.setAborted(&SI);
  703. const DataLayout &DL = SI.getModule()->getDataLayout();
  704. uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
  705. // If this memory access can be shown to *statically* extend outside the
  706. // bounds of of the allocation, it's behavior is undefined, so simply
  707. // ignore it. Note that this is more strict than the generic clamping
  708. // behavior of insertUse. We also try to handle cases which might run the
  709. // risk of overflow.
  710. // FIXME: We should instead consider the pointer to have escaped if this
  711. // function is being instrumented for addressing bugs or race conditions.
  712. if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
  713. DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
  714. << " which extends past the end of the " << AllocSize
  715. << " byte alloca:\n"
  716. << " alloca: " << AS.AI << "\n"
  717. << " use: " << SI << "\n");
  718. return markAsDead(SI);
  719. }
  720. assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
  721. "All simple FCA stores should have been pre-split");
  722. handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
  723. }
  724. void visitMemSetInst(MemSetInst &II) {
  725. assert(II.getRawDest() == *U && "Pointer use is not the destination?");
  726. ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
  727. if ((Length && Length->getValue() == 0) ||
  728. (IsOffsetKnown && Offset.uge(AllocSize)))
  729. // Zero-length mem transfer intrinsics can be ignored entirely.
  730. return markAsDead(II);
  731. if (!IsOffsetKnown)
  732. return PI.setAborted(&II);
  733. insertUse(II, Offset, Length ? Length->getLimitedValue()
  734. : AllocSize - Offset.getLimitedValue(),
  735. (bool)Length);
  736. }
  737. void visitMemTransferInst(MemTransferInst &II) {
  738. ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
  739. if (Length && Length->getValue() == 0)
  740. // Zero-length mem transfer intrinsics can be ignored entirely.
  741. return markAsDead(II);
  742. // Because we can visit these intrinsics twice, also check to see if the
  743. // first time marked this instruction as dead. If so, skip it.
  744. if (VisitedDeadInsts.count(&II))
  745. return;
  746. if (!IsOffsetKnown)
  747. return PI.setAborted(&II);
  748. // This side of the transfer is completely out-of-bounds, and so we can
  749. // nuke the entire transfer. However, we also need to nuke the other side
  750. // if already added to our partitions.
  751. // FIXME: Yet another place we really should bypass this when
  752. // instrumenting for ASan.
  753. if (Offset.uge(AllocSize)) {
  754. SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
  755. MemTransferSliceMap.find(&II);
  756. if (MTPI != MemTransferSliceMap.end())
  757. AS.Slices[MTPI->second].kill();
  758. return markAsDead(II);
  759. }
  760. uint64_t RawOffset = Offset.getLimitedValue();
  761. uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
  762. // Check for the special case where the same exact value is used for both
  763. // source and dest.
  764. if (*U == II.getRawDest() && *U == II.getRawSource()) {
  765. // For non-volatile transfers this is a no-op.
  766. if (!II.isVolatile())
  767. return markAsDead(II);
  768. return insertUse(II, Offset, Size, /*IsSplittable=*/false);
  769. }
  770. // If we have seen both source and destination for a mem transfer, then
  771. // they both point to the same alloca.
  772. bool Inserted;
  773. SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
  774. std::tie(MTPI, Inserted) =
  775. MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
  776. unsigned PrevIdx = MTPI->second;
  777. if (!Inserted) {
  778. Slice &PrevP = AS.Slices[PrevIdx];
  779. // Check if the begin offsets match and this is a non-volatile transfer.
  780. // In that case, we can completely elide the transfer.
  781. if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
  782. PrevP.kill();
  783. return markAsDead(II);
  784. }
  785. // Otherwise we have an offset transfer within the same alloca. We can't
  786. // split those.
  787. PrevP.makeUnsplittable();
  788. }
  789. // Insert the use now that we've fixed up the splittable nature.
  790. insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
  791. // Check that we ended up with a valid index in the map.
  792. assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
  793. "Map index doesn't point back to a slice with this user.");
  794. }
  795. // Disable SRoA for any intrinsics except for lifetime invariants.
  796. // FIXME: What about debug intrinsics? This matches old behavior, but
  797. // doesn't make sense.
  798. void visitIntrinsicInst(IntrinsicInst &II) {
  799. if (!IsOffsetKnown)
  800. return PI.setAborted(&II);
  801. if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
  802. II.getIntrinsicID() == Intrinsic::lifetime_end) {
  803. ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
  804. uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
  805. Length->getLimitedValue());
  806. insertUse(II, Offset, Size, true);
  807. return;
  808. }
  809. Base::visitIntrinsicInst(II);
  810. }
  811. Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
  812. // We consider any PHI or select that results in a direct load or store of
  813. // the same offset to be a viable use for slicing purposes. These uses
  814. // are considered unsplittable and the size is the maximum loaded or stored
  815. // size.
  816. SmallPtrSet<Instruction *, 4> Visited;
  817. SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
  818. Visited.insert(Root);
  819. Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
  820. const DataLayout &DL = Root->getModule()->getDataLayout();
  821. // If there are no loads or stores, the access is dead. We mark that as
  822. // a size zero access.
  823. Size = 0;
  824. do {
  825. Instruction *I, *UsedI;
  826. std::tie(UsedI, I) = Uses.pop_back_val();
  827. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  828. Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
  829. continue;
  830. }
  831. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  832. Value *Op = SI->getOperand(0);
  833. if (Op == UsedI)
  834. return SI;
  835. Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
  836. continue;
  837. }
  838. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  839. if (!GEP->hasAllZeroIndices())
  840. return GEP;
  841. } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
  842. !isa<SelectInst>(I)) {
  843. return I;
  844. }
  845. for (User *U : I->users())
  846. if (Visited.insert(cast<Instruction>(U)).second)
  847. Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
  848. } while (!Uses.empty());
  849. return nullptr;
  850. }
  851. void visitPHINodeOrSelectInst(Instruction &I) {
  852. assert(isa<PHINode>(I) || isa<SelectInst>(I));
  853. if (I.use_empty())
  854. return markAsDead(I);
  855. // TODO: We could use SimplifyInstruction here to fold PHINodes and
  856. // SelectInsts. However, doing so requires to change the current
  857. // dead-operand-tracking mechanism. For instance, suppose neither loading
  858. // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
  859. // trap either. However, if we simply replace %U with undef using the
  860. // current dead-operand-tracking mechanism, "load (select undef, undef,
  861. // %other)" may trap because the select may return the first operand
  862. // "undef".
  863. if (Value *Result = foldPHINodeOrSelectInst(I)) {
  864. if (Result == *U)
  865. // If the result of the constant fold will be the pointer, recurse
  866. // through the PHI/select as if we had RAUW'ed it.
  867. enqueueUsers(I);
  868. else
  869. // Otherwise the operand to the PHI/select is dead, and we can replace
  870. // it with undef.
  871. AS.DeadOperands.push_back(U);
  872. return;
  873. }
  874. if (!IsOffsetKnown)
  875. return PI.setAborted(&I);
  876. // See if we already have computed info on this node.
  877. uint64_t &Size = PHIOrSelectSizes[&I];
  878. if (!Size) {
  879. // This is a new PHI/Select, check for an unsafe use of it.
  880. if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
  881. return PI.setAborted(UnsafeI);
  882. }
  883. // For PHI and select operands outside the alloca, we can't nuke the entire
  884. // phi or select -- the other side might still be relevant, so we special
  885. // case them here and use a separate structure to track the operands
  886. // themselves which should be replaced with undef.
  887. // FIXME: This should instead be escaped in the event we're instrumenting
  888. // for address sanitization.
  889. if (Offset.uge(AllocSize)) {
  890. AS.DeadOperands.push_back(U);
  891. return;
  892. }
  893. insertUse(I, Offset, Size);
  894. }
  895. void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
  896. void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
  897. /// \brief Disable SROA entirely if there are unhandled users of the alloca.
  898. void visitInstruction(Instruction &I) { PI.setAborted(&I); }
  899. };
  900. AllocaSlices::AllocaSlices(
  901. const DataLayout &DL, AllocaInst &AI,
  902. const bool SkipHLSLMat) // HLSL Change - not sroa matrix type.
  903. :
  904. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  905. AI(AI),
  906. #endif
  907. PointerEscapingInstr(nullptr) {
  908. SliceBuilder PB(DL, AI, *this, SkipHLSLMat);
  909. SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
  910. if (PtrI.isEscaped() || PtrI.isAborted()) {
  911. // FIXME: We should sink the escape vs. abort info into the caller nicely,
  912. // possibly by just storing the PtrInfo in the AllocaSlices.
  913. PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
  914. : PtrI.getAbortingInst();
  915. assert(PointerEscapingInstr && "Did not track a bad instruction");
  916. return;
  917. }
  918. Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
  919. [](const Slice &S) {
  920. return S.isDead();
  921. }),
  922. Slices.end());
  923. #if 0 // HLSL Change Starts - option pending
  924. #if __cplusplus >= 201103L && !defined(NDEBUG)
  925. if (SROARandomShuffleSlices) {
  926. std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
  927. std::shuffle(Slices.begin(), Slices.end(), MT);
  928. }
  929. #endif
  930. #endif // HLSL Change Ends - option pending
  931. // Sort the uses. This arranges for the offsets to be in ascending order,
  932. // and the sizes to be in descending order.
  933. std::sort(Slices.begin(), Slices.end());
  934. }
  935. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  936. void AllocaSlices::print(raw_ostream &OS, const_iterator I,
  937. StringRef Indent) const {
  938. printSlice(OS, I, Indent);
  939. OS << "\n";
  940. printUse(OS, I, Indent);
  941. }
  942. void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
  943. StringRef Indent) const {
  944. OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
  945. << " slice #" << (I - begin())
  946. << (I->isSplittable() ? " (splittable)" : "");
  947. }
  948. void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
  949. StringRef Indent) const {
  950. OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
  951. }
  952. void AllocaSlices::print(raw_ostream &OS) const {
  953. if (PointerEscapingInstr) {
  954. OS << "Can't analyze slices for alloca: " << AI << "\n"
  955. << " A pointer to this alloca escaped by:\n"
  956. << " " << *PointerEscapingInstr << "\n";
  957. return;
  958. }
  959. OS << "Slices of alloca: " << AI << "\n";
  960. for (const_iterator I = begin(), E = end(); I != E; ++I)
  961. print(OS, I);
  962. }
  963. LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
  964. print(dbgs(), I);
  965. }
  966. LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
  967. #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  968. namespace {
  969. /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
  970. ///
  971. /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
  972. /// the loads and stores of an alloca instruction, as well as updating its
  973. /// debug information. This is used when a domtree is unavailable and thus
  974. /// mem2reg in its full form can't be used to handle promotion of allocas to
  975. /// scalar values.
  976. class AllocaPromoter : public LoadAndStorePromoter {
  977. AllocaInst &AI;
  978. DIBuilder &DIB;
  979. SmallVector<DbgDeclareInst *, 4> DDIs;
  980. SmallVector<DbgValueInst *, 4> DVIs;
  981. public:
  982. AllocaPromoter(ArrayRef<const Instruction *> Insts,
  983. SSAUpdater &S,
  984. AllocaInst &AI, DIBuilder &DIB)
  985. : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
  986. void run(const SmallVectorImpl<Instruction *> &Insts) {
  987. // Retain the debug information attached to the alloca for use when
  988. // rewriting loads and stores.
  989. if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
  990. if (auto *DINode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
  991. for (User *U : DINode->users())
  992. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  993. DDIs.push_back(DDI);
  994. else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  995. DVIs.push_back(DVI);
  996. }
  997. }
  998. LoadAndStorePromoter::run(Insts);
  999. // While we have the debug information, clear it off of the alloca. The
  1000. // caller takes care of deleting the alloca.
  1001. while (!DDIs.empty())
  1002. DDIs.pop_back_val()->eraseFromParent();
  1003. while (!DVIs.empty())
  1004. DVIs.pop_back_val()->eraseFromParent();
  1005. }
  1006. bool
  1007. isInstInList(Instruction *I,
  1008. const SmallVectorImpl<Instruction *> &Insts) const override {
  1009. Value *Ptr;
  1010. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  1011. Ptr = LI->getOperand(0);
  1012. else
  1013. Ptr = cast<StoreInst>(I)->getPointerOperand();
  1014. // Only used to detect cycles, which will be rare and quickly found as
  1015. // we're walking up a chain of defs rather than down through uses.
  1016. SmallPtrSet<Value *, 4> Visited;
  1017. do {
  1018. if (Ptr == &AI)
  1019. return true;
  1020. if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
  1021. Ptr = BCI->getOperand(0);
  1022. else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
  1023. Ptr = GEPI->getPointerOperand();
  1024. else
  1025. return false;
  1026. } while (Visited.insert(Ptr).second);
  1027. return false;
  1028. }
  1029. void updateDebugInfo(Instruction *Inst) const override {
  1030. for (DbgDeclareInst *DDI : DDIs)
  1031. if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  1032. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  1033. else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  1034. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  1035. for (DbgValueInst *DVI : DVIs) {
  1036. Value *Arg = nullptr;
  1037. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  1038. // If an argument is zero extended then use argument directly. The ZExt
  1039. // may be zapped by an optimization pass in future.
  1040. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  1041. Arg = dyn_cast<Argument>(ZExt->getOperand(0));
  1042. else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  1043. Arg = dyn_cast<Argument>(SExt->getOperand(0));
  1044. if (!Arg)
  1045. Arg = SI->getValueOperand();
  1046. } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  1047. Arg = LI->getPointerOperand();
  1048. } else {
  1049. continue;
  1050. }
  1051. DIB.insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
  1052. DVI->getExpression(), DVI->getDebugLoc(),
  1053. Inst);
  1054. }
  1055. }
  1056. };
  1057. } // end anon namespace
  1058. namespace {
  1059. /// \brief An optimization pass providing Scalar Replacement of Aggregates.
  1060. ///
  1061. /// This pass takes allocations which can be completely analyzed (that is, they
  1062. /// don't escape) and tries to turn them into scalar SSA values. There are
  1063. /// a few steps to this process.
  1064. ///
  1065. /// 1) It takes allocations of aggregates and analyzes the ways in which they
  1066. /// are used to try to split them into smaller allocations, ideally of
  1067. /// a single scalar data type. It will split up memcpy and memset accesses
  1068. /// as necessary and try to isolate individual scalar accesses.
  1069. /// 2) It will transform accesses into forms which are suitable for SSA value
  1070. /// promotion. This can be replacing a memset with a scalar store of an
  1071. /// integer value, or it can involve speculating operations on a PHI or
  1072. /// select to be a PHI or select of the results.
  1073. /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
  1074. /// onto insert and extract operations on a vector value, and convert them to
  1075. /// this form. By doing so, it will enable promotion of vector aggregates to
  1076. /// SSA vector values.
  1077. class SROA : public FunctionPass {
  1078. const bool RequiresDomTree;
  1079. const bool SkipHLSLMat; // HLSL Change - not sroa matrix type.
  1080. LLVMContext *C;
  1081. DominatorTree *DT;
  1082. AssumptionCache *AC;
  1083. /// \brief Worklist of alloca instructions to simplify.
  1084. ///
  1085. /// Each alloca in the function is added to this. Each new alloca formed gets
  1086. /// added to it as well to recursively simplify unless that alloca can be
  1087. /// directly promoted. Finally, each time we rewrite a use of an alloca other
  1088. /// the one being actively rewritten, we add it back onto the list if not
  1089. /// already present to ensure it is re-visited.
  1090. SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
  1091. /// \brief A collection of instructions to delete.
  1092. /// We try to batch deletions to simplify code and make things a bit more
  1093. /// efficient.
  1094. SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
  1095. /// \brief Post-promotion worklist.
  1096. ///
  1097. /// Sometimes we discover an alloca which has a high probability of becoming
  1098. /// viable for SROA after a round of promotion takes place. In those cases,
  1099. /// the alloca is enqueued here for re-processing.
  1100. ///
  1101. /// Note that we have to be very careful to clear allocas out of this list in
  1102. /// the event they are deleted.
  1103. SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
  1104. /// \brief A collection of alloca instructions we can directly promote.
  1105. std::vector<AllocaInst *> PromotableAllocas;
  1106. /// \brief A worklist of PHIs to speculate prior to promoting allocas.
  1107. ///
  1108. /// All of these PHIs have been checked for the safety of speculation and by
  1109. /// being speculated will allow promoting allocas currently in the promotable
  1110. /// queue.
  1111. SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
  1112. /// \brief A worklist of select instructions to speculate prior to promoting
  1113. /// allocas.
  1114. ///
  1115. /// All of these select instructions have been checked for the safety of
  1116. /// speculation and by being speculated will allow promoting allocas
  1117. /// currently in the promotable queue.
  1118. SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
  1119. public:
  1120. SROA(bool RequiresDomTree = true, bool SkipHLSLMat = true)
  1121. : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
  1122. SkipHLSLMat(SkipHLSLMat), // HLSL Change - not sroa matrix type.
  1123. C(nullptr), DT(nullptr) {
  1124. initializeSROAPass(*PassRegistry::getPassRegistry());
  1125. }
  1126. bool runOnFunction(Function &F) override;
  1127. void getAnalysisUsage(AnalysisUsage &AU) const override;
  1128. const char *getPassName() const override { return "SROA"; }
  1129. static char ID;
  1130. private:
  1131. friend class PHIOrSelectSpeculator;
  1132. friend class AllocaSliceRewriter;
  1133. bool runOnFunctionImp(Function &F);
  1134. bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
  1135. AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
  1136. AllocaSlices::Partition &P);
  1137. bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
  1138. bool runOnAlloca(AllocaInst &AI);
  1139. void clobberUse(Use &U);
  1140. void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
  1141. bool promoteAllocas(Function &F);
  1142. };
  1143. }
  1144. char SROA::ID = 0;
  1145. FunctionPass *llvm::createSROAPass(bool RequiresDomTree, bool SkipHLSLMat) {
  1146. return new SROA(RequiresDomTree, SkipHLSLMat);
  1147. }
  1148. INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
  1149. false)
  1150. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1151. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1152. INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
  1153. false)
  1154. /// Walk the range of a partitioning looking for a common type to cover this
  1155. /// sequence of slices.
  1156. static Type *findCommonType(AllocaSlices::const_iterator B,
  1157. AllocaSlices::const_iterator E,
  1158. uint64_t EndOffset) {
  1159. Type *Ty = nullptr;
  1160. bool TyIsCommon = true;
  1161. IntegerType *ITy = nullptr;
  1162. // Note that we need to look at *every* alloca slice's Use to ensure we
  1163. // always get consistent results regardless of the order of slices.
  1164. for (AllocaSlices::const_iterator I = B; I != E; ++I) {
  1165. Use *U = I->getUse();
  1166. if (isa<IntrinsicInst>(*U->getUser()))
  1167. continue;
  1168. if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
  1169. continue;
  1170. Type *UserTy = nullptr;
  1171. if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1172. UserTy = LI->getType();
  1173. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1174. UserTy = SI->getValueOperand()->getType();
  1175. }
  1176. if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
  1177. // If the type is larger than the partition, skip it. We only encounter
  1178. // this for split integer operations where we want to use the type of the
  1179. // entity causing the split. Also skip if the type is not a byte width
  1180. // multiple.
  1181. if (UserITy->getBitWidth() % 8 != 0 ||
  1182. UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
  1183. continue;
  1184. // Track the largest bitwidth integer type used in this way in case there
  1185. // is no common type.
  1186. if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
  1187. ITy = UserITy;
  1188. }
  1189. // To avoid depending on the order of slices, Ty and TyIsCommon must not
  1190. // depend on types skipped above.
  1191. if (!UserTy || (Ty && Ty != UserTy))
  1192. TyIsCommon = false; // Give up on anything but an iN type.
  1193. else
  1194. Ty = UserTy;
  1195. }
  1196. return TyIsCommon ? Ty : ITy;
  1197. }
  1198. /// PHI instructions that use an alloca and are subsequently loaded can be
  1199. /// rewritten to load both input pointers in the pred blocks and then PHI the
  1200. /// results, allowing the load of the alloca to be promoted.
  1201. /// From this:
  1202. /// %P2 = phi [i32* %Alloca, i32* %Other]
  1203. /// %V = load i32* %P2
  1204. /// to:
  1205. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1206. /// ...
  1207. /// %V2 = load i32* %Other
  1208. /// ...
  1209. /// %V = phi [i32 %V1, i32 %V2]
  1210. ///
  1211. /// We can do this to a select if its only uses are loads and if the operands
  1212. /// to the select can be loaded unconditionally.
  1213. ///
  1214. /// FIXME: This should be hoisted into a generic utility, likely in
  1215. /// Transforms/Util/Local.h
  1216. static bool isSafePHIToSpeculate(PHINode &PN) {
  1217. // For now, we can only do this promotion if the load is in the same block
  1218. // as the PHI, and if there are no stores between the phi and load.
  1219. // TODO: Allow recursive phi users.
  1220. // TODO: Allow stores.
  1221. BasicBlock *BB = PN.getParent();
  1222. unsigned MaxAlign = 0;
  1223. bool HaveLoad = false;
  1224. for (User *U : PN.users()) {
  1225. LoadInst *LI = dyn_cast<LoadInst>(U);
  1226. if (!LI || !LI->isSimple())
  1227. return false;
  1228. // For now we only allow loads in the same block as the PHI. This is
  1229. // a common case that happens when instcombine merges two loads through
  1230. // a PHI.
  1231. if (LI->getParent() != BB)
  1232. return false;
  1233. // Ensure that there are no instructions between the PHI and the load that
  1234. // could store.
  1235. for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
  1236. if (BBI->mayWriteToMemory())
  1237. return false;
  1238. MaxAlign = std::max(MaxAlign, LI->getAlignment());
  1239. HaveLoad = true;
  1240. }
  1241. if (!HaveLoad)
  1242. return false;
  1243. const DataLayout &DL = PN.getModule()->getDataLayout();
  1244. // We can only transform this if it is safe to push the loads into the
  1245. // predecessor blocks. The only thing to watch out for is that we can't put
  1246. // a possibly trapping load in the predecessor if it is a critical edge.
  1247. for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
  1248. TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
  1249. Value *InVal = PN.getIncomingValue(Idx);
  1250. // If the value is produced by the terminator of the predecessor (an
  1251. // invoke) or it has side-effects, there is no valid place to put a load
  1252. // in the predecessor.
  1253. if (TI == InVal || TI->mayHaveSideEffects())
  1254. return false;
  1255. // If the predecessor has a single successor, then the edge isn't
  1256. // critical.
  1257. if (TI->getNumSuccessors() == 1)
  1258. continue;
  1259. // If this pointer is always safe to load, or if we can prove that there
  1260. // is already a load in the block, then we can move the load to the pred
  1261. // block.
  1262. if (isDereferenceablePointer(InVal, DL) ||
  1263. isSafeToLoadUnconditionally(InVal, TI, MaxAlign))
  1264. continue;
  1265. return false;
  1266. }
  1267. return true;
  1268. }
  1269. static void speculatePHINodeLoads(PHINode &PN) {
  1270. DEBUG(dbgs() << " original: " << PN << "\n");
  1271. Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
  1272. IRBuilderTy PHIBuilder(&PN);
  1273. PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
  1274. PN.getName() + ".sroa.speculated");
  1275. // Get the AA tags and alignment to use from one of the loads. It doesn't
  1276. // matter which one we get and if any differ.
  1277. LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
  1278. AAMDNodes AATags;
  1279. SomeLoad->getAAMetadata(AATags);
  1280. unsigned Align = SomeLoad->getAlignment();
  1281. // Rewrite all loads of the PN to use the new PHI.
  1282. while (!PN.use_empty()) {
  1283. LoadInst *LI = cast<LoadInst>(PN.user_back());
  1284. LI->replaceAllUsesWith(NewPN);
  1285. LI->eraseFromParent();
  1286. }
  1287. // Inject loads into all of the pred blocks.
  1288. for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
  1289. BasicBlock *Pred = PN.getIncomingBlock(Idx);
  1290. TerminatorInst *TI = Pred->getTerminator();
  1291. Value *InVal = PN.getIncomingValue(Idx);
  1292. IRBuilderTy PredBuilder(TI);
  1293. LoadInst *Load = PredBuilder.CreateLoad(
  1294. InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
  1295. ++NumLoadsSpeculated;
  1296. Load->setAlignment(Align);
  1297. if (AATags)
  1298. Load->setAAMetadata(AATags);
  1299. NewPN->addIncoming(Load, Pred);
  1300. }
  1301. DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
  1302. PN.eraseFromParent();
  1303. }
  1304. /// Select instructions that use an alloca and are subsequently loaded can be
  1305. /// rewritten to load both input pointers and then select between the result,
  1306. /// allowing the load of the alloca to be promoted.
  1307. /// From this:
  1308. /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
  1309. /// %V = load i32* %P2
  1310. /// to:
  1311. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1312. /// %V2 = load i32* %Other
  1313. /// %V = select i1 %cond, i32 %V1, i32 %V2
  1314. ///
  1315. /// We can do this to a select if its only uses are loads and if the operand
  1316. /// to the select can be loaded unconditionally.
  1317. static bool isSafeSelectToSpeculate(SelectInst &SI) {
  1318. Value *TValue = SI.getTrueValue();
  1319. Value *FValue = SI.getFalseValue();
  1320. const DataLayout &DL = SI.getModule()->getDataLayout();
  1321. bool TDerefable = isDereferenceablePointer(TValue, DL);
  1322. bool FDerefable = isDereferenceablePointer(FValue, DL);
  1323. for (User *U : SI.users()) {
  1324. LoadInst *LI = dyn_cast<LoadInst>(U);
  1325. if (!LI || !LI->isSimple())
  1326. return false;
  1327. // Both operands to the select need to be dereferencable, either
  1328. // absolutely (e.g. allocas) or at this point because we can see other
  1329. // accesses to it.
  1330. if (!TDerefable &&
  1331. !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment()))
  1332. return false;
  1333. if (!FDerefable &&
  1334. !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment()))
  1335. return false;
  1336. }
  1337. return true;
  1338. }
  1339. static void speculateSelectInstLoads(SelectInst &SI) {
  1340. DEBUG(dbgs() << " original: " << SI << "\n");
  1341. IRBuilderTy IRB(&SI);
  1342. Value *TV = SI.getTrueValue();
  1343. Value *FV = SI.getFalseValue();
  1344. // Replace the loads of the select with a select of two loads.
  1345. while (!SI.use_empty()) {
  1346. LoadInst *LI = cast<LoadInst>(SI.user_back());
  1347. assert(LI->isSimple() && "We only speculate simple loads");
  1348. IRB.SetInsertPoint(LI);
  1349. LoadInst *TL =
  1350. IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
  1351. LoadInst *FL =
  1352. IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
  1353. NumLoadsSpeculated += 2;
  1354. // Transfer alignment and AA info if present.
  1355. TL->setAlignment(LI->getAlignment());
  1356. FL->setAlignment(LI->getAlignment());
  1357. AAMDNodes Tags;
  1358. LI->getAAMetadata(Tags);
  1359. if (Tags) {
  1360. TL->setAAMetadata(Tags);
  1361. FL->setAAMetadata(Tags);
  1362. }
  1363. Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
  1364. LI->getName() + ".sroa.speculated");
  1365. DEBUG(dbgs() << " speculated to: " << *V << "\n");
  1366. LI->replaceAllUsesWith(V);
  1367. LI->eraseFromParent();
  1368. }
  1369. SI.eraseFromParent();
  1370. }
  1371. /// \brief Build a GEP out of a base pointer and indices.
  1372. ///
  1373. /// This will return the BasePtr if that is valid, or build a new GEP
  1374. /// instruction using the IRBuilder if GEP-ing is needed.
  1375. static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
  1376. SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
  1377. if (Indices.empty())
  1378. return BasePtr;
  1379. // A single zero index is a no-op, so check for this and avoid building a GEP
  1380. // in that case.
  1381. if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
  1382. return BasePtr;
  1383. return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
  1384. NamePrefix + "sroa_idx");
  1385. }
  1386. /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
  1387. /// TargetTy without changing the offset of the pointer.
  1388. ///
  1389. /// This routine assumes we've already established a properly offset GEP with
  1390. /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
  1391. /// zero-indices down through type layers until we find one the same as
  1392. /// TargetTy. If we can't find one with the same type, we at least try to use
  1393. /// one with the same size. If none of that works, we just produce the GEP as
  1394. /// indicated by Indices to have the correct offset.
  1395. static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
  1396. Value *BasePtr, Type *Ty, Type *TargetTy,
  1397. SmallVectorImpl<Value *> &Indices,
  1398. Twine NamePrefix) {
  1399. if (Ty == TargetTy)
  1400. return buildGEP(IRB, BasePtr, Indices, NamePrefix);
  1401. // Pointer size to use for the indices.
  1402. unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
  1403. // See if we can descend into a struct and locate a field with the correct
  1404. // type.
  1405. unsigned NumLayers = 0;
  1406. Type *ElementTy = Ty;
  1407. do {
  1408. if (ElementTy->isPointerTy())
  1409. break;
  1410. if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
  1411. ElementTy = ArrayTy->getElementType();
  1412. Indices.push_back(IRB.getIntN(PtrSize, 0));
  1413. } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
  1414. ElementTy = VectorTy->getElementType();
  1415. Indices.push_back(IRB.getInt32(0));
  1416. } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
  1417. if (STy->element_begin() == STy->element_end())
  1418. break; // Nothing left to descend into.
  1419. ElementTy = *STy->element_begin();
  1420. Indices.push_back(IRB.getInt32(0));
  1421. } else {
  1422. break;
  1423. }
  1424. ++NumLayers;
  1425. } while (ElementTy != TargetTy);
  1426. if (ElementTy != TargetTy)
  1427. Indices.erase(Indices.end() - NumLayers, Indices.end());
  1428. return buildGEP(IRB, BasePtr, Indices, NamePrefix);
  1429. }
  1430. /// \brief Recursively compute indices for a natural GEP.
  1431. ///
  1432. /// This is the recursive step for getNaturalGEPWithOffset that walks down the
  1433. /// element types adding appropriate indices for the GEP.
  1434. static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
  1435. Value *Ptr, Type *Ty, APInt &Offset,
  1436. Type *TargetTy,
  1437. SmallVectorImpl<Value *> &Indices,
  1438. Twine NamePrefix) {
  1439. if (Offset == 0)
  1440. return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
  1441. NamePrefix);
  1442. // We can't recurse through pointer types.
  1443. if (Ty->isPointerTy())
  1444. return nullptr;
  1445. // We try to analyze GEPs over vectors here, but note that these GEPs are
  1446. // extremely poorly defined currently. The long-term goal is to remove GEPing
  1447. // over a vector from the IR completely.
  1448. if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
  1449. unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
  1450. if (ElementSizeInBits % 8 != 0) {
  1451. // GEPs over non-multiple of 8 size vector elements are invalid.
  1452. return nullptr;
  1453. }
  1454. APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
  1455. APInt NumSkippedElements = Offset.sdiv(ElementSize);
  1456. if (NumSkippedElements.ugt(VecTy->getNumElements()))
  1457. return nullptr;
  1458. Offset -= NumSkippedElements * ElementSize;
  1459. Indices.push_back(IRB.getInt(NumSkippedElements));
  1460. return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
  1461. Offset, TargetTy, Indices, NamePrefix);
  1462. }
  1463. if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
  1464. Type *ElementTy = ArrTy->getElementType();
  1465. APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
  1466. APInt NumSkippedElements = Offset.sdiv(ElementSize);
  1467. if (NumSkippedElements.ugt(ArrTy->getNumElements()))
  1468. return nullptr;
  1469. Offset -= NumSkippedElements * ElementSize;
  1470. Indices.push_back(IRB.getInt(NumSkippedElements));
  1471. return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
  1472. Indices, NamePrefix);
  1473. }
  1474. StructType *STy = dyn_cast<StructType>(Ty);
  1475. if (!STy)
  1476. return nullptr;
  1477. const StructLayout *SL = DL.getStructLayout(STy);
  1478. uint64_t StructOffset = Offset.getZExtValue();
  1479. if (StructOffset >= SL->getSizeInBytes())
  1480. return nullptr;
  1481. unsigned Index = SL->getElementContainingOffset(StructOffset);
  1482. Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
  1483. Type *ElementTy = STy->getElementType(Index);
  1484. if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
  1485. return nullptr; // The offset points into alignment padding.
  1486. Indices.push_back(IRB.getInt32(Index));
  1487. return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
  1488. Indices, NamePrefix);
  1489. }
  1490. /// \brief Get a natural GEP from a base pointer to a particular offset and
  1491. /// resulting in a particular type.
  1492. ///
  1493. /// The goal is to produce a "natural" looking GEP that works with the existing
  1494. /// composite types to arrive at the appropriate offset and element type for
  1495. /// a pointer. TargetTy is the element type the returned GEP should point-to if
  1496. /// possible. We recurse by decreasing Offset, adding the appropriate index to
  1497. /// Indices, and setting Ty to the result subtype.
  1498. ///
  1499. /// If no natural GEP can be constructed, this function returns null.
  1500. static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
  1501. Value *Ptr, APInt Offset, Type *TargetTy,
  1502. SmallVectorImpl<Value *> &Indices,
  1503. Twine NamePrefix) {
  1504. PointerType *Ty = cast<PointerType>(Ptr->getType());
  1505. // Don't consider any GEPs through an i8* as natural unless the TargetTy is
  1506. // an i8.
  1507. if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
  1508. return nullptr;
  1509. Type *ElementTy = Ty->getElementType();
  1510. if (!ElementTy->isSized())
  1511. return nullptr; // We can't GEP through an unsized element.
  1512. APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
  1513. if (ElementSize == 0)
  1514. return nullptr; // Zero-length arrays can't help us build a natural GEP.
  1515. APInt NumSkippedElements = Offset.sdiv(ElementSize);
  1516. Offset -= NumSkippedElements * ElementSize;
  1517. Indices.push_back(IRB.getInt(NumSkippedElements));
  1518. return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
  1519. Indices, NamePrefix);
  1520. }
  1521. /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
  1522. /// resulting pointer has PointerTy.
  1523. ///
  1524. /// This tries very hard to compute a "natural" GEP which arrives at the offset
  1525. /// and produces the pointer type desired. Where it cannot, it will try to use
  1526. /// the natural GEP to arrive at the offset and bitcast to the type. Where that
  1527. /// fails, it will try to use an existing i8* and GEP to the byte offset and
  1528. /// bitcast to the type.
  1529. ///
  1530. /// The strategy for finding the more natural GEPs is to peel off layers of the
  1531. /// pointer, walking back through bit casts and GEPs, searching for a base
  1532. /// pointer from which we can compute a natural GEP with the desired
  1533. /// properties. The algorithm tries to fold as many constant indices into
  1534. /// a single GEP as possible, thus making each GEP more independent of the
  1535. /// surrounding code.
  1536. static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
  1537. APInt Offset, Type *PointerTy, Twine NamePrefix) {
  1538. // Even though we don't look through PHI nodes, we could be called on an
  1539. // instruction in an unreachable block, which may be on a cycle.
  1540. SmallPtrSet<Value *, 4> Visited;
  1541. Visited.insert(Ptr);
  1542. SmallVector<Value *, 4> Indices;
  1543. // We may end up computing an offset pointer that has the wrong type. If we
  1544. // never are able to compute one directly that has the correct type, we'll
  1545. // fall back to it, so keep it and the base it was computed from around here.
  1546. Value *OffsetPtr = nullptr;
  1547. Value *OffsetBasePtr;
  1548. // Remember any i8 pointer we come across to re-use if we need to do a raw
  1549. // byte offset.
  1550. Value *Int8Ptr = nullptr;
  1551. APInt Int8PtrOffset(Offset.getBitWidth(), 0);
  1552. Type *TargetTy = PointerTy->getPointerElementType();
  1553. do {
  1554. // First fold any existing GEPs into the offset.
  1555. while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
  1556. APInt GEPOffset(Offset.getBitWidth(), 0);
  1557. if (!GEP->accumulateConstantOffset(DL, GEPOffset))
  1558. break;
  1559. Offset += GEPOffset;
  1560. Ptr = GEP->getPointerOperand();
  1561. if (!Visited.insert(Ptr).second)
  1562. break;
  1563. }
  1564. // See if we can perform a natural GEP here.
  1565. Indices.clear();
  1566. if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
  1567. Indices, NamePrefix)) {
  1568. // If we have a new natural pointer at the offset, clear out any old
  1569. // offset pointer we computed. Unless it is the base pointer or
  1570. // a non-instruction, we built a GEP we don't need. Zap it.
  1571. if (OffsetPtr && OffsetPtr != OffsetBasePtr)
  1572. if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
  1573. assert(I->use_empty() && "Built a GEP with uses some how!");
  1574. I->eraseFromParent();
  1575. }
  1576. OffsetPtr = P;
  1577. OffsetBasePtr = Ptr;
  1578. // If we also found a pointer of the right type, we're done.
  1579. if (P->getType() == PointerTy)
  1580. return P;
  1581. }
  1582. // Stash this pointer if we've found an i8*.
  1583. if (Ptr->getType()->isIntegerTy(8)) {
  1584. Int8Ptr = Ptr;
  1585. Int8PtrOffset = Offset;
  1586. }
  1587. // Peel off a layer of the pointer and update the offset appropriately.
  1588. if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
  1589. Ptr = cast<Operator>(Ptr)->getOperand(0);
  1590. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
  1591. if (GA->mayBeOverridden())
  1592. break;
  1593. Ptr = GA->getAliasee();
  1594. } else {
  1595. break;
  1596. }
  1597. assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
  1598. } while (Visited.insert(Ptr).second);
  1599. if (!OffsetPtr) {
  1600. if (!Int8Ptr) {
  1601. Int8Ptr = IRB.CreateBitCast(
  1602. Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
  1603. NamePrefix + "sroa_raw_cast");
  1604. Int8PtrOffset = Offset;
  1605. }
  1606. OffsetPtr = Int8PtrOffset == 0
  1607. ? Int8Ptr
  1608. : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
  1609. IRB.getInt(Int8PtrOffset),
  1610. NamePrefix + "sroa_raw_idx");
  1611. }
  1612. Ptr = OffsetPtr;
  1613. // On the off chance we were targeting i8*, guard the bitcast here.
  1614. if (Ptr->getType() != PointerTy)
  1615. Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
  1616. return Ptr;
  1617. }
  1618. /// \brief Compute the adjusted alignment for a load or store from an offset.
  1619. static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
  1620. const DataLayout &DL) {
  1621. unsigned Alignment;
  1622. Type *Ty;
  1623. if (auto *LI = dyn_cast<LoadInst>(I)) {
  1624. Alignment = LI->getAlignment();
  1625. Ty = LI->getType();
  1626. } else if (auto *SI = dyn_cast<StoreInst>(I)) {
  1627. Alignment = SI->getAlignment();
  1628. Ty = SI->getValueOperand()->getType();
  1629. } else {
  1630. llvm_unreachable("Only loads and stores are allowed!");
  1631. }
  1632. if (!Alignment)
  1633. Alignment = DL.getABITypeAlignment(Ty);
  1634. return MinAlign(Alignment, Offset);
  1635. }
  1636. /// \brief Test whether we can convert a value from the old to the new type.
  1637. ///
  1638. /// This predicate should be used to guard calls to convertValue in order to
  1639. /// ensure that we only try to convert viable values. The strategy is that we
  1640. /// will peel off single element struct and array wrappings to get to an
  1641. /// underlying value, and convert that value.
  1642. static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
  1643. if (OldTy == NewTy)
  1644. return true;
  1645. // For integer types, we can't handle any bit-width differences. This would
  1646. // break both vector conversions with extension and introduce endianness
  1647. // issues when in conjunction with loads and stores.
  1648. if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
  1649. assert(cast<IntegerType>(OldTy)->getBitWidth() !=
  1650. cast<IntegerType>(NewTy)->getBitWidth() &&
  1651. "We can't have the same bitwidth for different int types");
  1652. return false;
  1653. }
  1654. if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
  1655. return false;
  1656. if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
  1657. return false;
  1658. // We can convert pointers to integers and vice-versa. Same for vectors
  1659. // of pointers and integers.
  1660. OldTy = OldTy->getScalarType();
  1661. NewTy = NewTy->getScalarType();
  1662. if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
  1663. if (NewTy->isPointerTy() && OldTy->isPointerTy())
  1664. return true;
  1665. if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
  1666. return true;
  1667. return false;
  1668. }
  1669. return true;
  1670. }
  1671. /// \brief Generic routine to convert an SSA value to a value of a different
  1672. /// type.
  1673. ///
  1674. /// This will try various different casting techniques, such as bitcasts,
  1675. /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
  1676. /// two types for viability with this routine.
  1677. static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
  1678. Type *NewTy) {
  1679. Type *OldTy = V->getType();
  1680. assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
  1681. if (OldTy == NewTy)
  1682. return V;
  1683. assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
  1684. "Integer types must be the exact same to convert.");
  1685. // See if we need inttoptr for this type pair. A cast involving both scalars
  1686. // and vectors requires and additional bitcast.
  1687. if (OldTy->getScalarType()->isIntegerTy() &&
  1688. NewTy->getScalarType()->isPointerTy()) {
  1689. // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
  1690. if (OldTy->isVectorTy() && !NewTy->isVectorTy())
  1691. return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
  1692. NewTy);
  1693. // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
  1694. if (!OldTy->isVectorTy() && NewTy->isVectorTy())
  1695. return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
  1696. NewTy);
  1697. return IRB.CreateIntToPtr(V, NewTy);
  1698. }
  1699. // See if we need ptrtoint for this type pair. A cast involving both scalars
  1700. // and vectors requires and additional bitcast.
  1701. if (OldTy->getScalarType()->isPointerTy() &&
  1702. NewTy->getScalarType()->isIntegerTy()) {
  1703. // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
  1704. if (OldTy->isVectorTy() && !NewTy->isVectorTy())
  1705. return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
  1706. NewTy);
  1707. // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
  1708. if (!OldTy->isVectorTy() && NewTy->isVectorTy())
  1709. return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
  1710. NewTy);
  1711. return IRB.CreatePtrToInt(V, NewTy);
  1712. }
  1713. return IRB.CreateBitCast(V, NewTy);
  1714. }
  1715. /// \brief Test whether the given slice use can be promoted to a vector.
  1716. ///
  1717. /// This function is called to test each entry in a partioning which is slated
  1718. /// for a single slice.
  1719. static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
  1720. const Slice &S, VectorType *Ty,
  1721. uint64_t ElementSize,
  1722. const DataLayout &DL) {
  1723. // First validate the slice offsets.
  1724. uint64_t BeginOffset =
  1725. std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
  1726. uint64_t BeginIndex = BeginOffset / ElementSize;
  1727. if (BeginIndex * ElementSize != BeginOffset ||
  1728. BeginIndex >= Ty->getNumElements())
  1729. return false;
  1730. uint64_t EndOffset =
  1731. std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
  1732. uint64_t EndIndex = EndOffset / ElementSize;
  1733. if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
  1734. return false;
  1735. assert(EndIndex > BeginIndex && "Empty vector!");
  1736. uint64_t NumElements = EndIndex - BeginIndex;
  1737. Type *SliceTy = (NumElements == 1)
  1738. ? Ty->getElementType()
  1739. : VectorType::get(Ty->getElementType(), NumElements);
  1740. Type *SplitIntTy =
  1741. Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
  1742. Use *U = S.getUse();
  1743. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
  1744. if (MI->isVolatile())
  1745. return false;
  1746. if (!S.isSplittable())
  1747. return false; // Skip any unsplittable intrinsics.
  1748. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
  1749. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1750. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1751. return false;
  1752. } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
  1753. // Disable vector promotion when there are loads or stores of an FCA.
  1754. return false;
  1755. } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1756. if (LI->isVolatile())
  1757. return false;
  1758. Type *LTy = LI->getType();
  1759. if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
  1760. assert(LTy->isIntegerTy());
  1761. LTy = SplitIntTy;
  1762. }
  1763. if (!canConvertValue(DL, SliceTy, LTy))
  1764. return false;
  1765. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1766. if (SI->isVolatile())
  1767. return false;
  1768. Type *STy = SI->getValueOperand()->getType();
  1769. if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
  1770. assert(STy->isIntegerTy());
  1771. STy = SplitIntTy;
  1772. }
  1773. if (!canConvertValue(DL, STy, SliceTy))
  1774. return false;
  1775. } else {
  1776. return false;
  1777. }
  1778. return true;
  1779. }
  1780. /// \brief Test whether the given alloca partitioning and range of slices can be
  1781. /// promoted to a vector.
  1782. ///
  1783. /// This is a quick test to check whether we can rewrite a particular alloca
  1784. /// partition (and its newly formed alloca) into a vector alloca with only
  1785. /// whole-vector loads and stores such that it could be promoted to a vector
  1786. /// SSA value. We only can ensure this for a limited set of operations, and we
  1787. /// don't want to do the rewrites unless we are confident that the result will
  1788. /// be promotable, so we have an early test here.
  1789. static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
  1790. const DataLayout &DL) {
  1791. // Collect the candidate types for vector-based promotion. Also track whether
  1792. // we have different element types.
  1793. SmallVector<VectorType *, 4> CandidateTys;
  1794. Type *CommonEltTy = nullptr;
  1795. bool HaveCommonEltTy = true;
  1796. auto CheckCandidateType = [&](Type *Ty) {
  1797. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  1798. CandidateTys.push_back(VTy);
  1799. if (!CommonEltTy)
  1800. CommonEltTy = VTy->getElementType();
  1801. else if (CommonEltTy != VTy->getElementType())
  1802. HaveCommonEltTy = false;
  1803. }
  1804. };
  1805. // Consider any loads or stores that are the exact size of the slice.
  1806. for (const Slice &S : P)
  1807. if (S.beginOffset() == P.beginOffset() &&
  1808. S.endOffset() == P.endOffset()) {
  1809. if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
  1810. CheckCandidateType(LI->getType());
  1811. else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
  1812. CheckCandidateType(SI->getValueOperand()->getType());
  1813. }
  1814. // If we didn't find a vector type, nothing to do here.
  1815. if (CandidateTys.empty())
  1816. return nullptr;
  1817. // Remove non-integer vector types if we had multiple common element types.
  1818. // FIXME: It'd be nice to replace them with integer vector types, but we can't
  1819. // do that until all the backends are known to produce good code for all
  1820. // integer vector types.
  1821. if (!HaveCommonEltTy) {
  1822. CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
  1823. [](VectorType *VTy) {
  1824. return !VTy->getElementType()->isIntegerTy();
  1825. }),
  1826. CandidateTys.end());
  1827. // If there were no integer vector types, give up.
  1828. if (CandidateTys.empty())
  1829. return nullptr;
  1830. // Rank the remaining candidate vector types. This is easy because we know
  1831. // they're all integer vectors. We sort by ascending number of elements.
  1832. auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
  1833. assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
  1834. "Cannot have vector types of different sizes!");
  1835. assert(RHSTy->getElementType()->isIntegerTy() &&
  1836. "All non-integer types eliminated!");
  1837. assert(LHSTy->getElementType()->isIntegerTy() &&
  1838. "All non-integer types eliminated!");
  1839. (void)DL;// HLSL Change - unused var
  1840. return RHSTy->getNumElements() < LHSTy->getNumElements();
  1841. };
  1842. std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
  1843. CandidateTys.erase(
  1844. std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
  1845. CandidateTys.end());
  1846. } else {
  1847. // The only way to have the same element type in every vector type is to
  1848. // have the same vector type. Check that and remove all but one.
  1849. #ifndef NDEBUG
  1850. for (VectorType *VTy : CandidateTys) {
  1851. assert(VTy->getElementType() == CommonEltTy &&
  1852. "Unaccounted for element type!");
  1853. assert(VTy == CandidateTys[0] &&
  1854. "Different vector types with the same element type!");
  1855. }
  1856. #endif
  1857. CandidateTys.resize(1);
  1858. }
  1859. // Try each vector type, and return the one which works.
  1860. auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
  1861. uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
  1862. // While the definition of LLVM vectors is bitpacked, we don't support sizes
  1863. // that aren't byte sized.
  1864. if (ElementSize % 8)
  1865. return false;
  1866. assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
  1867. "vector size not a multiple of element size?");
  1868. ElementSize /= 8;
  1869. for (const Slice &S : P)
  1870. if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
  1871. return false;
  1872. for (const Slice *S : P.splitSliceTails())
  1873. if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
  1874. return false;
  1875. return true;
  1876. };
  1877. for (VectorType *VTy : CandidateTys)
  1878. if (CheckVectorTypeForPromotion(VTy))
  1879. return VTy;
  1880. return nullptr;
  1881. }
  1882. /// \brief Test whether a slice of an alloca is valid for integer widening.
  1883. ///
  1884. /// This implements the necessary checking for the \c isIntegerWideningViable
  1885. /// test below on a single slice of the alloca.
  1886. static bool isIntegerWideningViableForSlice(const Slice &S,
  1887. uint64_t AllocBeginOffset,
  1888. Type *AllocaTy,
  1889. const DataLayout &DL,
  1890. bool &WholeAllocaOp) {
  1891. uint64_t Size = DL.getTypeStoreSize(AllocaTy);
  1892. uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
  1893. uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
  1894. // We can't reasonably handle cases where the load or store extends past
  1895. // the end of the aloca's type and into its padding.
  1896. if (RelEnd > Size)
  1897. return false;
  1898. Use *U = S.getUse();
  1899. if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1900. if (LI->isVolatile())
  1901. return false;
  1902. // We can't handle loads that extend past the allocated memory.
  1903. if (DL.getTypeStoreSize(LI->getType()) > Size)
  1904. return false;
  1905. // Note that we don't count vector loads or stores as whole-alloca
  1906. // operations which enable integer widening because we would prefer to use
  1907. // vector widening instead.
  1908. if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
  1909. WholeAllocaOp = true;
  1910. if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
  1911. if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
  1912. return false;
  1913. } else if (RelBegin != 0 || RelEnd != Size ||
  1914. !canConvertValue(DL, AllocaTy, LI->getType())) {
  1915. // Non-integer loads need to be convertible from the alloca type so that
  1916. // they are promotable.
  1917. return false;
  1918. }
  1919. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1920. Type *ValueTy = SI->getValueOperand()->getType();
  1921. if (SI->isVolatile())
  1922. return false;
  1923. // We can't handle stores that extend past the allocated memory.
  1924. if (DL.getTypeStoreSize(ValueTy) > Size)
  1925. return false;
  1926. // Note that we don't count vector loads or stores as whole-alloca
  1927. // operations which enable integer widening because we would prefer to use
  1928. // vector widening instead.
  1929. if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
  1930. WholeAllocaOp = true;
  1931. if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
  1932. if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
  1933. return false;
  1934. } else if (RelBegin != 0 || RelEnd != Size ||
  1935. !canConvertValue(DL, ValueTy, AllocaTy)) {
  1936. // Non-integer stores need to be convertible to the alloca type so that
  1937. // they are promotable.
  1938. return false;
  1939. }
  1940. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
  1941. if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
  1942. return false;
  1943. if (!S.isSplittable())
  1944. return false; // Skip any unsplittable intrinsics.
  1945. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
  1946. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1947. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1948. return false;
  1949. } else {
  1950. return false;
  1951. }
  1952. return true;
  1953. }
  1954. /// \brief Test whether the given alloca partition's integer operations can be
  1955. /// widened to promotable ones.
  1956. ///
  1957. /// This is a quick test to check whether we can rewrite the integer loads and
  1958. /// stores to a particular alloca into wider loads and stores and be able to
  1959. /// promote the resulting alloca.
  1960. static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
  1961. const DataLayout &DL) {
  1962. uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
  1963. // Don't create integer types larger than the maximum bitwidth.
  1964. if (SizeInBits > IntegerType::MAX_INT_BITS)
  1965. return false;
  1966. // Don't try to handle allocas with bit-padding.
  1967. if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
  1968. return false;
  1969. // We need to ensure that an integer type with the appropriate bitwidth can
  1970. // be converted to the alloca type, whatever that is. We don't want to force
  1971. // the alloca itself to have an integer type if there is a more suitable one.
  1972. Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
  1973. if (!canConvertValue(DL, AllocaTy, IntTy) ||
  1974. !canConvertValue(DL, IntTy, AllocaTy))
  1975. return false;
  1976. // While examining uses, we ensure that the alloca has a covering load or
  1977. // store. We don't want to widen the integer operations only to fail to
  1978. // promote due to some other unsplittable entry (which we may make splittable
  1979. // later). However, if there are only splittable uses, go ahead and assume
  1980. // that we cover the alloca.
  1981. // FIXME: We shouldn't consider split slices that happen to start in the
  1982. // partition here...
  1983. bool WholeAllocaOp =
  1984. P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
  1985. for (const Slice &S : P)
  1986. if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
  1987. WholeAllocaOp))
  1988. return false;
  1989. for (const Slice *S : P.splitSliceTails())
  1990. if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
  1991. WholeAllocaOp))
  1992. return false;
  1993. return WholeAllocaOp;
  1994. }
  1995. static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
  1996. IntegerType *Ty, uint64_t Offset,
  1997. const Twine &Name) {
  1998. DEBUG(dbgs() << " start: " << *V << "\n");
  1999. IntegerType *IntTy = cast<IntegerType>(V->getType());
  2000. assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
  2001. "Element extends past full value");
  2002. uint64_t ShAmt = 8 * Offset;
  2003. if (DL.isBigEndian())
  2004. ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
  2005. if (ShAmt) {
  2006. V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
  2007. DEBUG(dbgs() << " shifted: " << *V << "\n");
  2008. }
  2009. assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
  2010. "Cannot extract to a larger integer!");
  2011. if (Ty != IntTy) {
  2012. V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
  2013. DEBUG(dbgs() << " trunced: " << *V << "\n");
  2014. }
  2015. return V;
  2016. }
  2017. static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
  2018. Value *V, uint64_t Offset, const Twine &Name) {
  2019. IntegerType *IntTy = cast<IntegerType>(Old->getType());
  2020. IntegerType *Ty = cast<IntegerType>(V->getType());
  2021. assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
  2022. "Cannot insert a larger integer!");
  2023. DEBUG(dbgs() << " start: " << *V << "\n");
  2024. if (Ty != IntTy) {
  2025. V = IRB.CreateZExt(V, IntTy, Name + ".ext");
  2026. DEBUG(dbgs() << " extended: " << *V << "\n");
  2027. }
  2028. assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
  2029. "Element store outside of alloca store");
  2030. uint64_t ShAmt = 8 * Offset;
  2031. if (DL.isBigEndian())
  2032. ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
  2033. if (ShAmt) {
  2034. V = IRB.CreateShl(V, ShAmt, Name + ".shift");
  2035. DEBUG(dbgs() << " shifted: " << *V << "\n");
  2036. }
  2037. if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
  2038. APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
  2039. Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
  2040. DEBUG(dbgs() << " masked: " << *Old << "\n");
  2041. V = IRB.CreateOr(Old, V, Name + ".insert");
  2042. DEBUG(dbgs() << " inserted: " << *V << "\n");
  2043. }
  2044. return V;
  2045. }
  2046. static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
  2047. unsigned EndIndex, const Twine &Name) {
  2048. VectorType *VecTy = cast<VectorType>(V->getType());
  2049. unsigned NumElements = EndIndex - BeginIndex;
  2050. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  2051. if (NumElements == VecTy->getNumElements())
  2052. return V;
  2053. if (NumElements == 1) {
  2054. V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
  2055. Name + ".extract");
  2056. DEBUG(dbgs() << " extract: " << *V << "\n");
  2057. return V;
  2058. }
  2059. SmallVector<Constant *, 8> Mask;
  2060. Mask.reserve(NumElements);
  2061. for (unsigned i = BeginIndex; i != EndIndex; ++i)
  2062. Mask.push_back(IRB.getInt32(i));
  2063. V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
  2064. ConstantVector::get(Mask), Name + ".extract");
  2065. DEBUG(dbgs() << " shuffle: " << *V << "\n");
  2066. return V;
  2067. }
  2068. static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
  2069. unsigned BeginIndex, const Twine &Name) {
  2070. VectorType *VecTy = cast<VectorType>(Old->getType());
  2071. assert(VecTy && "Can only insert a vector into a vector");
  2072. VectorType *Ty = dyn_cast<VectorType>(V->getType());
  2073. if (!Ty) {
  2074. // Single element to insert.
  2075. V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
  2076. Name + ".insert");
  2077. DEBUG(dbgs() << " insert: " << *V << "\n");
  2078. return V;
  2079. }
  2080. assert(Ty->getNumElements() <= VecTy->getNumElements() &&
  2081. "Too many elements!");
  2082. if (Ty->getNumElements() == VecTy->getNumElements()) {
  2083. assert(V->getType() == VecTy && "Vector type mismatch");
  2084. return V;
  2085. }
  2086. unsigned EndIndex = BeginIndex + Ty->getNumElements();
  2087. // When inserting a smaller vector into the larger to store, we first
  2088. // use a shuffle vector to widen it with undef elements, and then
  2089. // a second shuffle vector to select between the loaded vector and the
  2090. // incoming vector.
  2091. SmallVector<Constant *, 8> Mask;
  2092. Mask.reserve(VecTy->getNumElements());
  2093. for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
  2094. if (i >= BeginIndex && i < EndIndex)
  2095. Mask.push_back(IRB.getInt32(i - BeginIndex));
  2096. else
  2097. Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
  2098. V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
  2099. ConstantVector::get(Mask), Name + ".expand");
  2100. DEBUG(dbgs() << " shuffle: " << *V << "\n");
  2101. Mask.clear();
  2102. for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
  2103. Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
  2104. V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
  2105. DEBUG(dbgs() << " blend: " << *V << "\n");
  2106. return V;
  2107. }
  2108. namespace {
  2109. /// \brief Visitor to rewrite instructions using p particular slice of an alloca
  2110. /// to use a new alloca.
  2111. ///
  2112. /// Also implements the rewriting to vector-based accesses when the partition
  2113. /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
  2114. /// lives here.
  2115. class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
  2116. // Befriend the base class so it can delegate to private visit methods.
  2117. friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
  2118. typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
  2119. const DataLayout &DL;
  2120. AllocaSlices &AS;
  2121. SROA &Pass;
  2122. AllocaInst &OldAI, &NewAI;
  2123. const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
  2124. Type *NewAllocaTy;
  2125. // This is a convenience and flag variable that will be null unless the new
  2126. // alloca's integer operations should be widened to this integer type due to
  2127. // passing isIntegerWideningViable above. If it is non-null, the desired
  2128. // integer type will be stored here for easy access during rewriting.
  2129. IntegerType *IntTy;
  2130. // If we are rewriting an alloca partition which can be written as pure
  2131. // vector operations, we stash extra information here. When VecTy is
  2132. // non-null, we have some strict guarantees about the rewritten alloca:
  2133. // - The new alloca is exactly the size of the vector type here.
  2134. // - The accesses all either map to the entire vector or to a single
  2135. // element.
  2136. // - The set of accessing instructions is only one of those handled above
  2137. // in isVectorPromotionViable. Generally these are the same access kinds
  2138. // which are promotable via mem2reg.
  2139. VectorType *VecTy;
  2140. Type *ElementTy;
  2141. uint64_t ElementSize;
  2142. // The original offset of the slice currently being rewritten relative to
  2143. // the original alloca.
  2144. uint64_t BeginOffset, EndOffset;
  2145. // The new offsets of the slice currently being rewritten relative to the
  2146. // original alloca.
  2147. uint64_t NewBeginOffset, NewEndOffset;
  2148. uint64_t SliceSize;
  2149. bool IsSplittable;
  2150. bool IsSplit;
  2151. Use *OldUse;
  2152. Instruction *OldPtr;
  2153. // Track post-rewrite users which are PHI nodes and Selects.
  2154. SmallPtrSetImpl<PHINode *> &PHIUsers;
  2155. SmallPtrSetImpl<SelectInst *> &SelectUsers;
  2156. // Utility IR builder, whose name prefix is setup for each visited use, and
  2157. // the insertion point is set to point to the user.
  2158. IRBuilderTy IRB;
  2159. public:
  2160. AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
  2161. AllocaInst &OldAI, AllocaInst &NewAI,
  2162. uint64_t NewAllocaBeginOffset,
  2163. uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
  2164. VectorType *PromotableVecTy,
  2165. SmallPtrSetImpl<PHINode *> &PHIUsers,
  2166. SmallPtrSetImpl<SelectInst *> &SelectUsers)
  2167. : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
  2168. NewAllocaBeginOffset(NewAllocaBeginOffset),
  2169. NewAllocaEndOffset(NewAllocaEndOffset),
  2170. NewAllocaTy(NewAI.getAllocatedType()),
  2171. IntTy(IsIntegerPromotable
  2172. ? Type::getIntNTy(
  2173. NewAI.getContext(),
  2174. DL.getTypeSizeInBits(NewAI.getAllocatedType()))
  2175. : nullptr),
  2176. VecTy(PromotableVecTy),
  2177. ElementTy(VecTy ? VecTy->getElementType() : nullptr),
  2178. ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
  2179. BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
  2180. OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
  2181. IRB(NewAI.getContext(), ConstantFolder()) {
  2182. if (VecTy) {
  2183. assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
  2184. "Only multiple-of-8 sized vector elements are viable");
  2185. ++NumVectorized;
  2186. }
  2187. assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
  2188. }
  2189. bool visit(AllocaSlices::const_iterator I) {
  2190. bool CanSROA = true;
  2191. BeginOffset = I->beginOffset();
  2192. EndOffset = I->endOffset();
  2193. IsSplittable = I->isSplittable();
  2194. IsSplit =
  2195. BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
  2196. DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
  2197. DEBUG(AS.printSlice(dbgs(), I, ""));
  2198. DEBUG(dbgs() << "\n");
  2199. // Compute the intersecting offset range.
  2200. assert(BeginOffset < NewAllocaEndOffset);
  2201. assert(EndOffset > NewAllocaBeginOffset);
  2202. NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
  2203. NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
  2204. SliceSize = NewEndOffset - NewBeginOffset;
  2205. OldUse = I->getUse();
  2206. OldPtr = cast<Instruction>(OldUse->get());
  2207. Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
  2208. IRB.SetInsertPoint(OldUserI);
  2209. IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
  2210. IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
  2211. CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
  2212. if (VecTy || IntTy)
  2213. assert(CanSROA);
  2214. return CanSROA;
  2215. }
  2216. private:
  2217. // Make sure the other visit overloads are visible.
  2218. using Base::visit;
  2219. // Every instruction which can end up as a user must have a rewrite rule.
  2220. bool visitInstruction(Instruction &I) {
  2221. DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
  2222. llvm_unreachable("No rewrite rule for this instruction!");
  2223. }
  2224. Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
  2225. // Note that the offset computation can use BeginOffset or NewBeginOffset
  2226. // interchangeably for unsplit slices.
  2227. assert(IsSplit || BeginOffset == NewBeginOffset);
  2228. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2229. #ifndef NDEBUG
  2230. StringRef OldName = OldPtr->getName();
  2231. // Skip through the last '.sroa.' component of the name.
  2232. size_t LastSROAPrefix = OldName.rfind(".sroa.");
  2233. if (LastSROAPrefix != StringRef::npos) {
  2234. OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
  2235. // Look for an SROA slice index.
  2236. size_t IndexEnd = OldName.find_first_not_of("0123456789");
  2237. if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
  2238. // Strip the index and look for the offset.
  2239. OldName = OldName.substr(IndexEnd + 1);
  2240. size_t OffsetEnd = OldName.find_first_not_of("0123456789");
  2241. if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
  2242. // Strip the offset.
  2243. OldName = OldName.substr(OffsetEnd + 1);
  2244. }
  2245. }
  2246. // Strip any SROA suffixes as well.
  2247. OldName = OldName.substr(0, OldName.find(".sroa_"));
  2248. #endif
  2249. return getAdjustedPtr(IRB, DL, &NewAI,
  2250. APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
  2251. #ifndef NDEBUG
  2252. Twine(OldName) + "."
  2253. #else
  2254. Twine()
  2255. #endif
  2256. );
  2257. }
  2258. /// \brief Compute suitable alignment to access this slice of the *new*
  2259. /// alloca.
  2260. ///
  2261. /// You can optionally pass a type to this routine and if that type's ABI
  2262. /// alignment is itself suitable, this will return zero.
  2263. unsigned getSliceAlign(Type *Ty = nullptr) {
  2264. unsigned NewAIAlign = NewAI.getAlignment();
  2265. if (!NewAIAlign)
  2266. NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
  2267. unsigned Align =
  2268. MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
  2269. return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
  2270. }
  2271. unsigned getIndex(uint64_t Offset) {
  2272. assert(VecTy && "Can only call getIndex when rewriting a vector");
  2273. uint64_t RelOffset = Offset - NewAllocaBeginOffset;
  2274. assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
  2275. uint32_t Index = RelOffset / ElementSize;
  2276. assert(Index * ElementSize == RelOffset);
  2277. return Index;
  2278. }
  2279. void deleteIfTriviallyDead(Value *V) {
  2280. Instruction *I = cast<Instruction>(V);
  2281. if (isInstructionTriviallyDead(I))
  2282. Pass.DeadInsts.insert(I);
  2283. }
  2284. Value *rewriteVectorizedLoadInst() {
  2285. unsigned BeginIndex = getIndex(NewBeginOffset);
  2286. unsigned EndIndex = getIndex(NewEndOffset);
  2287. assert(EndIndex > BeginIndex && "Empty vector!");
  2288. Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2289. return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
  2290. }
  2291. Value *rewriteIntegerLoad(LoadInst &LI) {
  2292. assert(IntTy && "We cannot insert an integer to the alloca");
  2293. assert(!LI.isVolatile());
  2294. Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2295. V = convertValue(DL, IRB, V, IntTy);
  2296. assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
  2297. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2298. if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
  2299. V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
  2300. "extract");
  2301. return V;
  2302. }
  2303. bool visitLoadInst(LoadInst &LI) {
  2304. DEBUG(dbgs() << " original: " << LI << "\n");
  2305. Value *OldOp = LI.getOperand(0);
  2306. assert(OldOp == OldPtr);
  2307. Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
  2308. : LI.getType();
  2309. const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
  2310. bool IsPtrAdjusted = false;
  2311. Value *V;
  2312. if (VecTy) {
  2313. V = rewriteVectorizedLoadInst();
  2314. } else if (IntTy && LI.getType()->isIntegerTy()) {
  2315. V = rewriteIntegerLoad(LI);
  2316. } else if (NewBeginOffset == NewAllocaBeginOffset &&
  2317. NewEndOffset == NewAllocaEndOffset &&
  2318. (canConvertValue(DL, NewAllocaTy, TargetTy) ||
  2319. (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
  2320. TargetTy->isIntegerTy()))) {
  2321. LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
  2322. LI.isVolatile(), LI.getName());
  2323. if (LI.isVolatile())
  2324. NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
  2325. V = NewLI;
  2326. // If this is an integer load past the end of the slice (which means the
  2327. // bytes outside the slice are undef or this load is dead) just forcibly
  2328. // fix the integer size with correct handling of endianness.
  2329. if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
  2330. if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
  2331. if (AITy->getBitWidth() < TITy->getBitWidth()) {
  2332. V = IRB.CreateZExt(V, TITy, "load.ext");
  2333. if (DL.isBigEndian())
  2334. V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
  2335. "endian_shift");
  2336. }
  2337. } else {
  2338. Type *LTy = TargetTy->getPointerTo();
  2339. LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
  2340. getSliceAlign(TargetTy),
  2341. LI.isVolatile(), LI.getName());
  2342. if (LI.isVolatile())
  2343. NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
  2344. V = NewLI;
  2345. IsPtrAdjusted = true;
  2346. }
  2347. V = convertValue(DL, IRB, V, TargetTy);
  2348. if (IsSplit) {
  2349. assert(!LI.isVolatile());
  2350. assert(LI.getType()->isIntegerTy() &&
  2351. "Only integer type loads and stores are split");
  2352. assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
  2353. "Split load isn't smaller than original load");
  2354. assert(LI.getType()->getIntegerBitWidth() ==
  2355. DL.getTypeStoreSizeInBits(LI.getType()) &&
  2356. "Non-byte-multiple bit width");
  2357. // Move the insertion point just past the load so that we can refer to it.
  2358. IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
  2359. // Create a placeholder value with the same type as LI to use as the
  2360. // basis for the new value. This allows us to replace the uses of LI with
  2361. // the computed value, and then replace the placeholder with LI, leaving
  2362. // LI only used for this computation.
  2363. Value *Placeholder =
  2364. new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
  2365. V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
  2366. "insert");
  2367. LI.replaceAllUsesWith(V);
  2368. Placeholder->replaceAllUsesWith(&LI);
  2369. delete Placeholder;
  2370. } else {
  2371. LI.replaceAllUsesWith(V);
  2372. }
  2373. Pass.DeadInsts.insert(&LI);
  2374. deleteIfTriviallyDead(OldOp);
  2375. DEBUG(dbgs() << " to: " << *V << "\n");
  2376. return !LI.isVolatile() && !IsPtrAdjusted;
  2377. }
  2378. bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
  2379. if (V->getType() != VecTy) {
  2380. unsigned BeginIndex = getIndex(NewBeginOffset);
  2381. unsigned EndIndex = getIndex(NewEndOffset);
  2382. assert(EndIndex > BeginIndex && "Empty vector!");
  2383. unsigned NumElements = EndIndex - BeginIndex;
  2384. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  2385. Type *SliceTy = (NumElements == 1)
  2386. ? ElementTy
  2387. : VectorType::get(ElementTy, NumElements);
  2388. if (V->getType() != SliceTy)
  2389. V = convertValue(DL, IRB, V, SliceTy);
  2390. // Mix in the existing elements.
  2391. Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2392. V = insertVector(IRB, Old, V, BeginIndex, "vec");
  2393. }
  2394. StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
  2395. Pass.DeadInsts.insert(&SI);
  2396. (void)Store;
  2397. DEBUG(dbgs() << " to: " << *Store << "\n");
  2398. return true;
  2399. }
  2400. bool rewriteIntegerStore(Value *V, StoreInst &SI) {
  2401. assert(IntTy && "We cannot extract an integer from the alloca");
  2402. assert(!SI.isVolatile());
  2403. if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
  2404. Value *Old =
  2405. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2406. Old = convertValue(DL, IRB, Old, IntTy);
  2407. assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
  2408. uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
  2409. V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
  2410. }
  2411. V = convertValue(DL, IRB, V, NewAllocaTy);
  2412. StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
  2413. Pass.DeadInsts.insert(&SI);
  2414. (void)Store;
  2415. DEBUG(dbgs() << " to: " << *Store << "\n");
  2416. return true;
  2417. }
  2418. bool visitStoreInst(StoreInst &SI) {
  2419. DEBUG(dbgs() << " original: " << SI << "\n");
  2420. Value *OldOp = SI.getOperand(1);
  2421. assert(OldOp == OldPtr);
  2422. Value *V = SI.getValueOperand();
  2423. // Strip all inbounds GEPs and pointer casts to try to dig out any root
  2424. // alloca that should be re-examined after promoting this alloca.
  2425. if (V->getType()->isPointerTy())
  2426. if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
  2427. Pass.PostPromotionWorklist.insert(AI);
  2428. if (SliceSize < DL.getTypeStoreSize(V->getType())) {
  2429. assert(!SI.isVolatile());
  2430. assert(V->getType()->isIntegerTy() &&
  2431. "Only integer type loads and stores are split");
  2432. assert(V->getType()->getIntegerBitWidth() ==
  2433. DL.getTypeStoreSizeInBits(V->getType()) &&
  2434. "Non-byte-multiple bit width");
  2435. IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
  2436. V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
  2437. "extract");
  2438. }
  2439. if (VecTy)
  2440. return rewriteVectorizedStoreInst(V, SI, OldOp);
  2441. if (IntTy && V->getType()->isIntegerTy())
  2442. return rewriteIntegerStore(V, SI);
  2443. const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
  2444. StoreInst *NewSI;
  2445. if (NewBeginOffset == NewAllocaBeginOffset &&
  2446. NewEndOffset == NewAllocaEndOffset &&
  2447. (canConvertValue(DL, V->getType(), NewAllocaTy) ||
  2448. (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
  2449. V->getType()->isIntegerTy()))) {
  2450. // If this is an integer store past the end of slice (and thus the bytes
  2451. // past that point are irrelevant or this is unreachable), truncate the
  2452. // value prior to storing.
  2453. if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
  2454. if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
  2455. if (VITy->getBitWidth() > AITy->getBitWidth()) {
  2456. if (DL.isBigEndian())
  2457. V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
  2458. "endian_shift");
  2459. V = IRB.CreateTrunc(V, AITy, "load.trunc");
  2460. }
  2461. V = convertValue(DL, IRB, V, NewAllocaTy);
  2462. NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
  2463. SI.isVolatile());
  2464. } else {
  2465. Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
  2466. NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
  2467. SI.isVolatile());
  2468. }
  2469. if (SI.isVolatile())
  2470. NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
  2471. Pass.DeadInsts.insert(&SI);
  2472. deleteIfTriviallyDead(OldOp);
  2473. DEBUG(dbgs() << " to: " << *NewSI << "\n");
  2474. return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
  2475. }
  2476. /// \brief Compute an integer value from splatting an i8 across the given
  2477. /// number of bytes.
  2478. ///
  2479. /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
  2480. /// call this routine.
  2481. /// FIXME: Heed the advice above.
  2482. ///
  2483. /// \param V The i8 value to splat.
  2484. /// \param Size The number of bytes in the output (assuming i8 is one byte)
  2485. Value *getIntegerSplat(Value *V, unsigned Size) {
  2486. assert(Size > 0 && "Expected a positive number of bytes.");
  2487. IntegerType *VTy = cast<IntegerType>(V->getType());
  2488. assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
  2489. if (Size == 1)
  2490. return V;
  2491. Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
  2492. V = IRB.CreateMul(
  2493. IRB.CreateZExt(V, SplatIntTy, "zext"),
  2494. ConstantExpr::getUDiv(
  2495. Constant::getAllOnesValue(SplatIntTy),
  2496. ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
  2497. SplatIntTy)),
  2498. "isplat");
  2499. return V;
  2500. }
  2501. /// \brief Compute a vector splat for a given element value.
  2502. Value *getVectorSplat(Value *V, unsigned NumElements) {
  2503. V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
  2504. DEBUG(dbgs() << " splat: " << *V << "\n");
  2505. return V;
  2506. }
  2507. bool visitMemSetInst(MemSetInst &II) {
  2508. DEBUG(dbgs() << " original: " << II << "\n");
  2509. assert(II.getRawDest() == OldPtr);
  2510. // If the memset has a variable size, it cannot be split, just adjust the
  2511. // pointer to the new alloca.
  2512. if (!isa<Constant>(II.getLength())) {
  2513. assert(!IsSplit);
  2514. assert(NewBeginOffset == BeginOffset);
  2515. II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
  2516. Type *CstTy = II.getAlignmentCst()->getType();
  2517. II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
  2518. deleteIfTriviallyDead(OldPtr);
  2519. return false;
  2520. }
  2521. // Record this instruction for deletion.
  2522. Pass.DeadInsts.insert(&II);
  2523. Type *AllocaTy = NewAI.getAllocatedType();
  2524. Type *ScalarTy = AllocaTy->getScalarType();
  2525. // If this doesn't map cleanly onto the alloca type, and that type isn't
  2526. // a single value type, just emit a memset.
  2527. if (!VecTy && !IntTy &&
  2528. (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
  2529. SliceSize != DL.getTypeStoreSize(AllocaTy) ||
  2530. !AllocaTy->isSingleValueType() ||
  2531. !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
  2532. DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
  2533. Type *SizeTy = II.getLength()->getType();
  2534. Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
  2535. CallInst *New = IRB.CreateMemSet(
  2536. getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
  2537. getSliceAlign(), II.isVolatile());
  2538. (void)New;
  2539. DEBUG(dbgs() << " to: " << *New << "\n");
  2540. return false;
  2541. }
  2542. // If we can represent this as a simple value, we have to build the actual
  2543. // value to store, which requires expanding the byte present in memset to
  2544. // a sensible representation for the alloca type. This is essentially
  2545. // splatting the byte to a sufficiently wide integer, splatting it across
  2546. // any desired vector width, and bitcasting to the final type.
  2547. Value *V;
  2548. if (VecTy) {
  2549. // If this is a memset of a vectorized alloca, insert it.
  2550. assert(ElementTy == ScalarTy);
  2551. unsigned BeginIndex = getIndex(NewBeginOffset);
  2552. unsigned EndIndex = getIndex(NewEndOffset);
  2553. assert(EndIndex > BeginIndex && "Empty vector!");
  2554. unsigned NumElements = EndIndex - BeginIndex;
  2555. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  2556. Value *Splat =
  2557. getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
  2558. Splat = convertValue(DL, IRB, Splat, ElementTy);
  2559. if (NumElements > 1)
  2560. Splat = getVectorSplat(Splat, NumElements);
  2561. Value *Old =
  2562. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2563. V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
  2564. } else if (IntTy) {
  2565. // If this is a memset on an alloca where we can widen stores, insert the
  2566. // set integer.
  2567. assert(!II.isVolatile());
  2568. uint64_t Size = NewEndOffset - NewBeginOffset;
  2569. V = getIntegerSplat(II.getValue(), Size);
  2570. if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
  2571. EndOffset != NewAllocaBeginOffset)) {
  2572. Value *Old =
  2573. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2574. Old = convertValue(DL, IRB, Old, IntTy);
  2575. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2576. V = insertInteger(DL, IRB, Old, V, Offset, "insert");
  2577. } else {
  2578. assert(V->getType() == IntTy &&
  2579. "Wrong type for an alloca wide integer!");
  2580. }
  2581. V = convertValue(DL, IRB, V, AllocaTy);
  2582. } else {
  2583. // Established these invariants above.
  2584. assert(NewBeginOffset == NewAllocaBeginOffset);
  2585. assert(NewEndOffset == NewAllocaEndOffset);
  2586. V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
  2587. if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
  2588. V = getVectorSplat(V, AllocaVecTy->getNumElements());
  2589. V = convertValue(DL, IRB, V, AllocaTy);
  2590. }
  2591. Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
  2592. II.isVolatile());
  2593. (void)New;
  2594. DEBUG(dbgs() << " to: " << *New << "\n");
  2595. return !II.isVolatile();
  2596. }
  2597. bool visitMemTransferInst(MemTransferInst &II) {
  2598. // Rewriting of memory transfer instructions can be a bit tricky. We break
  2599. // them into two categories: split intrinsics and unsplit intrinsics.
  2600. DEBUG(dbgs() << " original: " << II << "\n");
  2601. bool IsDest = &II.getRawDestUse() == OldUse;
  2602. assert((IsDest && II.getRawDest() == OldPtr) ||
  2603. (!IsDest && II.getRawSource() == OldPtr));
  2604. unsigned SliceAlign = getSliceAlign();
  2605. // For unsplit intrinsics, we simply modify the source and destination
  2606. // pointers in place. This isn't just an optimization, it is a matter of
  2607. // correctness. With unsplit intrinsics we may be dealing with transfers
  2608. // within a single alloca before SROA ran, or with transfers that have
  2609. // a variable length. We may also be dealing with memmove instead of
  2610. // memcpy, and so simply updating the pointers is the necessary for us to
  2611. // update both source and dest of a single call.
  2612. if (!IsSplittable) {
  2613. Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2614. if (IsDest)
  2615. II.setDest(AdjustedPtr);
  2616. else
  2617. II.setSource(AdjustedPtr);
  2618. if (II.getAlignment() > SliceAlign) {
  2619. Type *CstTy = II.getAlignmentCst()->getType();
  2620. II.setAlignment(
  2621. ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
  2622. }
  2623. DEBUG(dbgs() << " to: " << II << "\n");
  2624. deleteIfTriviallyDead(OldPtr);
  2625. return false;
  2626. }
  2627. // For split transfer intrinsics we have an incredibly useful assurance:
  2628. // the source and destination do not reside within the same alloca, and at
  2629. // least one of them does not escape. This means that we can replace
  2630. // memmove with memcpy, and we don't need to worry about all manner of
  2631. // downsides to splitting and transforming the operations.
  2632. // If this doesn't map cleanly onto the alloca type, and that type isn't
  2633. // a single value type, just emit a memcpy.
  2634. bool EmitMemCpy =
  2635. !VecTy && !IntTy &&
  2636. (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
  2637. SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
  2638. !NewAI.getAllocatedType()->isSingleValueType());
  2639. // If we're just going to emit a memcpy, the alloca hasn't changed, and the
  2640. // size hasn't been shrunk based on analysis of the viable range, this is
  2641. // a no-op.
  2642. if (EmitMemCpy && &OldAI == &NewAI) {
  2643. // Ensure the start lines up.
  2644. assert(NewBeginOffset == BeginOffset);
  2645. // Rewrite the size as needed.
  2646. if (NewEndOffset != EndOffset)
  2647. II.setLength(ConstantInt::get(II.getLength()->getType(),
  2648. NewEndOffset - NewBeginOffset));
  2649. return false;
  2650. }
  2651. // Record this instruction for deletion.
  2652. Pass.DeadInsts.insert(&II);
  2653. // Strip all inbounds GEPs and pointer casts to try to dig out any root
  2654. // alloca that should be re-examined after rewriting this instruction.
  2655. Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
  2656. if (AllocaInst *AI =
  2657. dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
  2658. assert(AI != &OldAI && AI != &NewAI &&
  2659. "Splittable transfers cannot reach the same alloca on both ends.");
  2660. Pass.Worklist.insert(AI);
  2661. }
  2662. Type *OtherPtrTy = OtherPtr->getType();
  2663. unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
  2664. // Compute the relative offset for the other pointer within the transfer.
  2665. unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
  2666. APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
  2667. unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
  2668. OtherOffset.zextOrTrunc(64).getZExtValue());
  2669. if (EmitMemCpy) {
  2670. // Compute the other pointer, folding as much as possible to produce
  2671. // a single, simple GEP in most cases.
  2672. OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
  2673. OtherPtr->getName() + ".");
  2674. Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2675. Type *SizeTy = II.getLength()->getType();
  2676. Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
  2677. CallInst *New = IRB.CreateMemCpy(
  2678. IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
  2679. MinAlign(SliceAlign, OtherAlign), II.isVolatile());
  2680. (void)New;
  2681. DEBUG(dbgs() << " to: " << *New << "\n");
  2682. return false;
  2683. }
  2684. bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
  2685. NewEndOffset == NewAllocaEndOffset;
  2686. uint64_t Size = NewEndOffset - NewBeginOffset;
  2687. unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
  2688. unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
  2689. unsigned NumElements = EndIndex - BeginIndex;
  2690. IntegerType *SubIntTy =
  2691. IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
  2692. // Reset the other pointer type to match the register type we're going to
  2693. // use, but using the address space of the original other pointer.
  2694. if (VecTy && !IsWholeAlloca) {
  2695. if (NumElements == 1)
  2696. OtherPtrTy = VecTy->getElementType();
  2697. else
  2698. OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
  2699. OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
  2700. } else if (IntTy && !IsWholeAlloca) {
  2701. OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
  2702. } else {
  2703. OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
  2704. }
  2705. Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
  2706. OtherPtr->getName() + ".");
  2707. unsigned SrcAlign = OtherAlign;
  2708. Value *DstPtr = &NewAI;
  2709. unsigned DstAlign = SliceAlign;
  2710. if (!IsDest) {
  2711. std::swap(SrcPtr, DstPtr);
  2712. std::swap(SrcAlign, DstAlign);
  2713. }
  2714. Value *Src;
  2715. if (VecTy && !IsWholeAlloca && !IsDest) {
  2716. Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2717. Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
  2718. } else if (IntTy && !IsWholeAlloca && !IsDest) {
  2719. Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2720. Src = convertValue(DL, IRB, Src, IntTy);
  2721. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2722. Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
  2723. } else {
  2724. Src =
  2725. IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
  2726. }
  2727. if (VecTy && !IsWholeAlloca && IsDest) {
  2728. Value *Old =
  2729. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2730. Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
  2731. } else if (IntTy && !IsWholeAlloca && IsDest) {
  2732. Value *Old =
  2733. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2734. Old = convertValue(DL, IRB, Old, IntTy);
  2735. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2736. Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
  2737. Src = convertValue(DL, IRB, Src, NewAllocaTy);
  2738. }
  2739. StoreInst *Store = cast<StoreInst>(
  2740. IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
  2741. (void)Store;
  2742. DEBUG(dbgs() << " to: " << *Store << "\n");
  2743. return !II.isVolatile();
  2744. }
  2745. bool visitIntrinsicInst(IntrinsicInst &II) {
  2746. assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
  2747. II.getIntrinsicID() == Intrinsic::lifetime_end);
  2748. DEBUG(dbgs() << " original: " << II << "\n");
  2749. assert(II.getArgOperand(1) == OldPtr);
  2750. // Record this instruction for deletion.
  2751. Pass.DeadInsts.insert(&II);
  2752. ConstantInt *Size =
  2753. ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
  2754. NewEndOffset - NewBeginOffset);
  2755. Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2756. Value *New;
  2757. if (II.getIntrinsicID() == Intrinsic::lifetime_start)
  2758. New = IRB.CreateLifetimeStart(Ptr, Size);
  2759. else
  2760. New = IRB.CreateLifetimeEnd(Ptr, Size);
  2761. (void)New;
  2762. DEBUG(dbgs() << " to: " << *New << "\n");
  2763. return true;
  2764. }
  2765. bool visitPHINode(PHINode &PN) {
  2766. DEBUG(dbgs() << " original: " << PN << "\n");
  2767. assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
  2768. assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
  2769. // We would like to compute a new pointer in only one place, but have it be
  2770. // as local as possible to the PHI. To do that, we re-use the location of
  2771. // the old pointer, which necessarily must be in the right position to
  2772. // dominate the PHI.
  2773. IRBuilderTy PtrBuilder(IRB);
  2774. if (isa<PHINode>(OldPtr))
  2775. PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
  2776. else
  2777. PtrBuilder.SetInsertPoint(OldPtr);
  2778. PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
  2779. Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
  2780. // Replace the operands which were using the old pointer.
  2781. std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
  2782. DEBUG(dbgs() << " to: " << PN << "\n");
  2783. deleteIfTriviallyDead(OldPtr);
  2784. // PHIs can't be promoted on their own, but often can be speculated. We
  2785. // check the speculation outside of the rewriter so that we see the
  2786. // fully-rewritten alloca.
  2787. PHIUsers.insert(&PN);
  2788. return true;
  2789. }
  2790. bool visitSelectInst(SelectInst &SI) {
  2791. DEBUG(dbgs() << " original: " << SI << "\n");
  2792. assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
  2793. "Pointer isn't an operand!");
  2794. assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
  2795. assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
  2796. Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2797. // Replace the operands which were using the old pointer.
  2798. if (SI.getOperand(1) == OldPtr)
  2799. SI.setOperand(1, NewPtr);
  2800. if (SI.getOperand(2) == OldPtr)
  2801. SI.setOperand(2, NewPtr);
  2802. DEBUG(dbgs() << " to: " << SI << "\n");
  2803. deleteIfTriviallyDead(OldPtr);
  2804. // Selects can't be promoted on their own, but often can be speculated. We
  2805. // check the speculation outside of the rewriter so that we see the
  2806. // fully-rewritten alloca.
  2807. SelectUsers.insert(&SI);
  2808. return true;
  2809. }
  2810. };
  2811. }
  2812. namespace {
  2813. /// \brief Visitor to rewrite aggregate loads and stores as scalar.
  2814. ///
  2815. /// This pass aggressively rewrites all aggregate loads and stores on
  2816. /// a particular pointer (or any pointer derived from it which we can identify)
  2817. /// with scalar loads and stores.
  2818. class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
  2819. // Befriend the base class so it can delegate to private visit methods.
  2820. friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
  2821. const DataLayout &DL;
  2822. const bool SkipHLSLMat; // HLSL Change - not sroa matrix type.
  2823. /// Queue of pointer uses to analyze and potentially rewrite.
  2824. SmallVector<Use *, 8> Queue;
  2825. /// Set to prevent us from cycling with phi nodes and loops.
  2826. SmallPtrSet<User *, 8> Visited;
  2827. /// The current pointer use being rewritten. This is used to dig up the used
  2828. /// value (as opposed to the user).
  2829. Use *U;
  2830. public:
  2831. AggLoadStoreRewriter(const DataLayout &DL, const bool SkipHLSLMat)
  2832. // HLSL Change - not sroa matrix type.
  2833. : DL(DL), SkipHLSLMat(SkipHLSLMat) {}
  2834. /// Rewrite loads and stores through a pointer and all pointers derived from
  2835. /// it.
  2836. bool rewrite(Instruction &I) {
  2837. DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
  2838. enqueueUsers(I);
  2839. bool Changed = false;
  2840. while (!Queue.empty()) {
  2841. U = Queue.pop_back_val();
  2842. Changed |= visit(cast<Instruction>(U->getUser()));
  2843. }
  2844. return Changed;
  2845. }
  2846. private:
  2847. /// Enqueue all the users of the given instruction for further processing.
  2848. /// This uses a set to de-duplicate users.
  2849. void enqueueUsers(Instruction &I) {
  2850. for (Use &U : I.uses())
  2851. if (Visited.insert(U.getUser()).second)
  2852. Queue.push_back(&U);
  2853. }
  2854. // Conservative default is to not rewrite anything.
  2855. bool visitInstruction(Instruction &I) { return false; }
  2856. /// \brief Generic recursive split emission class.
  2857. template <typename Derived> class OpSplitter {
  2858. protected:
  2859. /// The builder used to form new instructions.
  2860. IRBuilderTy IRB;
  2861. /// The indices which to be used with insert- or extractvalue to select the
  2862. /// appropriate value within the aggregate.
  2863. SmallVector<unsigned, 4> Indices;
  2864. /// The indices to a GEP instruction which will move Ptr to the correct slot
  2865. /// within the aggregate.
  2866. SmallVector<Value *, 4> GEPIndices;
  2867. /// The base pointer of the original op, used as a base for GEPing the
  2868. /// split operations.
  2869. Value *Ptr;
  2870. /// Initialize the splitter with an insertion point, Ptr and start with a
  2871. /// single zero GEP index.
  2872. OpSplitter(Instruction *InsertionPoint, Value *Ptr)
  2873. : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
  2874. public:
  2875. /// \brief Generic recursive split emission routine.
  2876. ///
  2877. /// This method recursively splits an aggregate op (load or store) into
  2878. /// scalar or vector ops. It splits recursively until it hits a single value
  2879. /// and emits that single value operation via the template argument.
  2880. ///
  2881. /// The logic of this routine relies on GEPs and insertvalue and
  2882. /// extractvalue all operating with the same fundamental index list, merely
  2883. /// formatted differently (GEPs need actual values).
  2884. ///
  2885. /// \param Ty The type being split recursively into smaller ops.
  2886. /// \param Agg The aggregate value being built up or stored, depending on
  2887. /// whether this is splitting a load or a store respectively.
  2888. void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
  2889. if (Ty->isSingleValueType())
  2890. return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
  2891. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  2892. unsigned OldSize = Indices.size();
  2893. (void)OldSize;
  2894. for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
  2895. ++Idx) {
  2896. assert(Indices.size() == OldSize && "Did not return to the old size");
  2897. Indices.push_back(Idx);
  2898. GEPIndices.push_back(IRB.getInt32(Idx));
  2899. emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
  2900. GEPIndices.pop_back();
  2901. Indices.pop_back();
  2902. }
  2903. return;
  2904. }
  2905. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  2906. unsigned OldSize = Indices.size();
  2907. (void)OldSize;
  2908. for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
  2909. ++Idx) {
  2910. assert(Indices.size() == OldSize && "Did not return to the old size");
  2911. Indices.push_back(Idx);
  2912. GEPIndices.push_back(IRB.getInt32(Idx));
  2913. emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
  2914. GEPIndices.pop_back();
  2915. Indices.pop_back();
  2916. }
  2917. return;
  2918. }
  2919. llvm_unreachable("Only arrays and structs are aggregate loadable types");
  2920. }
  2921. };
  2922. struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
  2923. LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
  2924. : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
  2925. /// Emit a leaf load of a single value. This is called at the leaves of the
  2926. /// recursive emission to actually load values.
  2927. void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
  2928. assert(Ty->isSingleValueType());
  2929. // Load the single value and insert it using the indices.
  2930. Value *GEP =
  2931. IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
  2932. Value *Load = IRB.CreateLoad(GEP, Name + ".load");
  2933. Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
  2934. DEBUG(dbgs() << " to: " << *Load << "\n");
  2935. }
  2936. };
  2937. bool visitLoadInst(LoadInst &LI) {
  2938. assert(LI.getPointerOperand() == *U);
  2939. if (!LI.isSimple() || LI.getType()->isSingleValueType())
  2940. return false;
  2941. // HLSL Change Begin - not sroa matrix type.
  2942. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(LI.getType())) ||
  2943. hlsl::dxilutil::IsHLSLObjectType(LI.getType()))
  2944. return false;
  2945. // HLSL Change End.
  2946. // We have an aggregate being loaded, split it apart.
  2947. DEBUG(dbgs() << " original: " << LI << "\n");
  2948. LoadOpSplitter Splitter(&LI, *U);
  2949. Value *V = UndefValue::get(LI.getType());
  2950. Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
  2951. LI.replaceAllUsesWith(V);
  2952. LI.eraseFromParent();
  2953. return true;
  2954. }
  2955. struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
  2956. StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
  2957. : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
  2958. /// Emit a leaf store of a single value. This is called at the leaves of the
  2959. /// recursive emission to actually produce stores.
  2960. void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
  2961. assert(Ty->isSingleValueType());
  2962. // Extract the single value and store it using the indices.
  2963. Value *Store = IRB.CreateStore(
  2964. IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
  2965. IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
  2966. (void)Store;
  2967. DEBUG(dbgs() << " to: " << *Store << "\n");
  2968. }
  2969. };
  2970. bool visitStoreInst(StoreInst &SI) {
  2971. if (!SI.isSimple() || SI.getPointerOperand() != *U)
  2972. return false;
  2973. Value *V = SI.getValueOperand();
  2974. if (V->getType()->isSingleValueType())
  2975. return false;
  2976. // HLSL Change Begin - not sroa matrix type.
  2977. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(V->getType())) ||
  2978. hlsl::dxilutil::IsHLSLObjectType(V->getType()))
  2979. return false;
  2980. // HLSL Change End.
  2981. // We have an aggregate being stored, split it apart.
  2982. DEBUG(dbgs() << " original: " << SI << "\n");
  2983. StoreOpSplitter Splitter(&SI, *U);
  2984. Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
  2985. SI.eraseFromParent();
  2986. return true;
  2987. }
  2988. bool visitBitCastInst(BitCastInst &BC) {
  2989. // HLSL Change Begin - not sroa matrix type.
  2990. if (PointerType *PT = dyn_cast<PointerType>(BC.getType())) {
  2991. Type *EltTy = PT->getElementType();
  2992. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(EltTy)) ||
  2993. hlsl::dxilutil::IsHLSLObjectType(EltTy))
  2994. return false;
  2995. if (PointerType *SrcPT = dyn_cast<PointerType>(BC.getSrcTy())) {
  2996. Type *SrcEltTy = SrcPT->getElementType();
  2997. if ((SkipHLSLMat && hlsl::HLMatrixType::isa(SrcEltTy)) ||
  2998. hlsl::dxilutil::IsHLSLObjectType(SrcEltTy))
  2999. return false;
  3000. }
  3001. }
  3002. // HLSL Change End.
  3003. enqueueUsers(BC);
  3004. return false;
  3005. }
  3006. bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  3007. enqueueUsers(GEPI);
  3008. return false;
  3009. }
  3010. bool visitPHINode(PHINode &PN) {
  3011. enqueueUsers(PN);
  3012. return false;
  3013. }
  3014. bool visitSelectInst(SelectInst &SI) {
  3015. enqueueUsers(SI);
  3016. return false;
  3017. }
  3018. };
  3019. }
  3020. /// \brief Strip aggregate type wrapping.
  3021. ///
  3022. /// This removes no-op aggregate types wrapping an underlying type. It will
  3023. /// strip as many layers of types as it can without changing either the type
  3024. /// size or the allocated size.
  3025. static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
  3026. if (Ty->isSingleValueType())
  3027. return Ty;
  3028. uint64_t AllocSize = DL.getTypeAllocSize(Ty);
  3029. uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
  3030. Type *InnerTy;
  3031. if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
  3032. InnerTy = ArrTy->getElementType();
  3033. } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
  3034. const StructLayout *SL = DL.getStructLayout(STy);
  3035. unsigned Index = SL->getElementContainingOffset(0);
  3036. InnerTy = STy->getElementType(Index);
  3037. } else {
  3038. return Ty;
  3039. }
  3040. if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
  3041. TypeSize > DL.getTypeSizeInBits(InnerTy))
  3042. return Ty;
  3043. return stripAggregateTypeWrapping(DL, InnerTy);
  3044. }
  3045. /// \brief Try to find a partition of the aggregate type passed in for a given
  3046. /// offset and size.
  3047. ///
  3048. /// This recurses through the aggregate type and tries to compute a subtype
  3049. /// based on the offset and size. When the offset and size span a sub-section
  3050. /// of an array, it will even compute a new array type for that sub-section,
  3051. /// and the same for structs.
  3052. ///
  3053. /// Note that this routine is very strict and tries to find a partition of the
  3054. /// type which produces the *exact* right offset and size. It is not forgiving
  3055. /// when the size or offset cause either end of type-based partition to be off.
  3056. /// Also, this is a best-effort routine. It is reasonable to give up and not
  3057. /// return a type if necessary.
  3058. static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
  3059. uint64_t Size) {
  3060. if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
  3061. return stripAggregateTypeWrapping(DL, Ty);
  3062. if (Offset > DL.getTypeAllocSize(Ty) ||
  3063. (DL.getTypeAllocSize(Ty) - Offset) < Size)
  3064. return nullptr;
  3065. if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
  3066. // We can't partition pointers...
  3067. if (SeqTy->isPointerTy())
  3068. return nullptr;
  3069. Type *ElementTy = SeqTy->getElementType();
  3070. uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
  3071. uint64_t NumSkippedElements = Offset / ElementSize;
  3072. if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
  3073. if (NumSkippedElements >= ArrTy->getNumElements())
  3074. return nullptr;
  3075. } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
  3076. if (NumSkippedElements >= VecTy->getNumElements())
  3077. return nullptr;
  3078. }
  3079. Offset -= NumSkippedElements * ElementSize;
  3080. // First check if we need to recurse.
  3081. if (Offset > 0 || Size < ElementSize) {
  3082. // Bail if the partition ends in a different array element.
  3083. if ((Offset + Size) > ElementSize)
  3084. return nullptr;
  3085. // Recurse through the element type trying to peel off offset bytes.
  3086. return getTypePartition(DL, ElementTy, Offset, Size);
  3087. }
  3088. assert(Offset == 0);
  3089. if (Size == ElementSize)
  3090. return stripAggregateTypeWrapping(DL, ElementTy);
  3091. assert(Size > ElementSize);
  3092. uint64_t NumElements = Size / ElementSize;
  3093. if (NumElements * ElementSize != Size)
  3094. return nullptr;
  3095. return ArrayType::get(ElementTy, NumElements);
  3096. }
  3097. StructType *STy = dyn_cast<StructType>(Ty);
  3098. if (!STy)
  3099. return nullptr;
  3100. const StructLayout *SL = DL.getStructLayout(STy);
  3101. if (Offset >= SL->getSizeInBytes())
  3102. return nullptr;
  3103. uint64_t EndOffset = Offset + Size;
  3104. if (EndOffset > SL->getSizeInBytes())
  3105. return nullptr;
  3106. unsigned Index = SL->getElementContainingOffset(Offset);
  3107. Offset -= SL->getElementOffset(Index);
  3108. Type *ElementTy = STy->getElementType(Index);
  3109. uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
  3110. if (Offset >= ElementSize)
  3111. return nullptr; // The offset points into alignment padding.
  3112. // See if any partition must be contained by the element.
  3113. if (Offset > 0 || Size < ElementSize) {
  3114. if ((Offset + Size) > ElementSize)
  3115. return nullptr;
  3116. return getTypePartition(DL, ElementTy, Offset, Size);
  3117. }
  3118. assert(Offset == 0);
  3119. if (Size == ElementSize)
  3120. return stripAggregateTypeWrapping(DL, ElementTy);
  3121. StructType::element_iterator EI = STy->element_begin() + Index,
  3122. EE = STy->element_end();
  3123. if (EndOffset < SL->getSizeInBytes()) {
  3124. unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
  3125. if (Index == EndIndex)
  3126. return nullptr; // Within a single element and its padding.
  3127. // Don't try to form "natural" types if the elements don't line up with the
  3128. // expected size.
  3129. // FIXME: We could potentially recurse down through the last element in the
  3130. // sub-struct to find a natural end point.
  3131. if (SL->getElementOffset(EndIndex) != EndOffset)
  3132. return nullptr;
  3133. assert(Index < EndIndex);
  3134. EE = STy->element_begin() + EndIndex;
  3135. }
  3136. // Try to build up a sub-structure.
  3137. StructType *SubTy =
  3138. StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
  3139. const StructLayout *SubSL = DL.getStructLayout(SubTy);
  3140. if (Size != SubSL->getSizeInBytes())
  3141. return nullptr; // The sub-struct doesn't have quite the size needed.
  3142. return SubTy;
  3143. }
  3144. /// \brief Pre-split loads and stores to simplify rewriting.
  3145. ///
  3146. /// We want to break up the splittable load+store pairs as much as
  3147. /// possible. This is important to do as a preprocessing step, as once we
  3148. /// start rewriting the accesses to partitions of the alloca we lose the
  3149. /// necessary information to correctly split apart paired loads and stores
  3150. /// which both point into this alloca. The case to consider is something like
  3151. /// the following:
  3152. ///
  3153. /// %a = alloca [12 x i8]
  3154. /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
  3155. /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
  3156. /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
  3157. /// %iptr1 = bitcast i8* %gep1 to i64*
  3158. /// %iptr2 = bitcast i8* %gep2 to i64*
  3159. /// %fptr1 = bitcast i8* %gep1 to float*
  3160. /// %fptr2 = bitcast i8* %gep2 to float*
  3161. /// %fptr3 = bitcast i8* %gep3 to float*
  3162. /// store float 0.0, float* %fptr1
  3163. /// store float 1.0, float* %fptr2
  3164. /// %v = load i64* %iptr1
  3165. /// store i64 %v, i64* %iptr2
  3166. /// %f1 = load float* %fptr2
  3167. /// %f2 = load float* %fptr3
  3168. ///
  3169. /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
  3170. /// promote everything so we recover the 2 SSA values that should have been
  3171. /// there all along.
  3172. ///
  3173. /// \returns true if any changes are made.
  3174. bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
  3175. DEBUG(dbgs() << "Pre-splitting loads and stores\n");
  3176. // Track the loads and stores which are candidates for pre-splitting here, in
  3177. // the order they first appear during the partition scan. These give stable
  3178. // iteration order and a basis for tracking which loads and stores we
  3179. // actually split.
  3180. SmallVector<LoadInst *, 4> Loads;
  3181. SmallVector<StoreInst *, 4> Stores;
  3182. // We need to accumulate the splits required of each load or store where we
  3183. // can find them via a direct lookup. This is important to cross-check loads
  3184. // and stores against each other. We also track the slice so that we can kill
  3185. // all the slices that end up split.
  3186. struct SplitOffsets {
  3187. Slice *S;
  3188. std::vector<uint64_t> Splits;
  3189. };
  3190. SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
  3191. // Track loads out of this alloca which cannot, for any reason, be pre-split.
  3192. // This is important as we also cannot pre-split stores of those loads!
  3193. // FIXME: This is all pretty gross. It means that we can be more aggressive
  3194. // in pre-splitting when the load feeding the store happens to come from
  3195. // a separate alloca. Put another way, the effectiveness of SROA would be
  3196. // decreased by a frontend which just concatenated all of its local allocas
  3197. // into one big flat alloca. But defeating such patterns is exactly the job
  3198. // SROA is tasked with! Sadly, to not have this discrepancy we would have
  3199. // change store pre-splitting to actually force pre-splitting of the load
  3200. // that feeds it *and all stores*. That makes pre-splitting much harder, but
  3201. // maybe it would make it more principled?
  3202. SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
  3203. DEBUG(dbgs() << " Searching for candidate loads and stores\n");
  3204. for (auto &P : AS.partitions()) {
  3205. for (Slice &S : P) {
  3206. Instruction *I = cast<Instruction>(S.getUse()->getUser());
  3207. if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
  3208. // If this was a load we have to track that it can't participate in any
  3209. // pre-splitting!
  3210. if (auto *LI = dyn_cast<LoadInst>(I))
  3211. UnsplittableLoads.insert(LI);
  3212. continue;
  3213. }
  3214. assert(P.endOffset() > S.beginOffset() &&
  3215. "Empty or backwards partition!");
  3216. // Determine if this is a pre-splittable slice.
  3217. if (auto *LI = dyn_cast<LoadInst>(I)) {
  3218. assert(!LI->isVolatile() && "Cannot split volatile loads!");
  3219. // The load must be used exclusively to store into other pointers for
  3220. // us to be able to arbitrarily pre-split it. The stores must also be
  3221. // simple to avoid changing semantics.
  3222. auto IsLoadSimplyStored = [](LoadInst *LI) {
  3223. for (User *LU : LI->users()) {
  3224. auto *SI = dyn_cast<StoreInst>(LU);
  3225. if (!SI || !SI->isSimple())
  3226. return false;
  3227. }
  3228. return true;
  3229. };
  3230. if (!IsLoadSimplyStored(LI)) {
  3231. UnsplittableLoads.insert(LI);
  3232. continue;
  3233. }
  3234. Loads.push_back(LI);
  3235. } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
  3236. if (!SI ||
  3237. S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
  3238. continue;
  3239. auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
  3240. if (!StoredLoad || !StoredLoad->isSimple())
  3241. continue;
  3242. assert(!SI->isVolatile() && "Cannot split volatile stores!");
  3243. Stores.push_back(SI);
  3244. } else {
  3245. // Other uses cannot be pre-split.
  3246. continue;
  3247. }
  3248. // Record the initial split.
  3249. DEBUG(dbgs() << " Candidate: " << *I << "\n");
  3250. auto &Offsets = SplitOffsetsMap[I];
  3251. assert(Offsets.Splits.empty() &&
  3252. "Should not have splits the first time we see an instruction!");
  3253. Offsets.S = &S;
  3254. Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
  3255. }
  3256. // Now scan the already split slices, and add a split for any of them which
  3257. // we're going to pre-split.
  3258. for (Slice *S : P.splitSliceTails()) {
  3259. auto SplitOffsetsMapI =
  3260. SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
  3261. if (SplitOffsetsMapI == SplitOffsetsMap.end())
  3262. continue;
  3263. auto &Offsets = SplitOffsetsMapI->second;
  3264. assert(Offsets.S == S && "Found a mismatched slice!");
  3265. assert(!Offsets.Splits.empty() &&
  3266. "Cannot have an empty set of splits on the second partition!");
  3267. assert(Offsets.Splits.back() ==
  3268. P.beginOffset() - Offsets.S->beginOffset() &&
  3269. "Previous split does not end where this one begins!");
  3270. // Record each split. The last partition's end isn't needed as the size
  3271. // of the slice dictates that.
  3272. if (S->endOffset() > P.endOffset())
  3273. Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
  3274. }
  3275. }
  3276. // We may have split loads where some of their stores are split stores. For
  3277. // such loads and stores, we can only pre-split them if their splits exactly
  3278. // match relative to their starting offset. We have to verify this prior to
  3279. // any rewriting.
  3280. Stores.erase(
  3281. std::remove_if(Stores.begin(), Stores.end(),
  3282. [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
  3283. // Lookup the load we are storing in our map of split
  3284. // offsets.
  3285. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3286. // If it was completely unsplittable, then we're done,
  3287. // and this store can't be pre-split.
  3288. if (UnsplittableLoads.count(LI))
  3289. return true;
  3290. auto LoadOffsetsI = SplitOffsetsMap.find(LI);
  3291. if (LoadOffsetsI == SplitOffsetsMap.end())
  3292. return false; // Unrelated loads are definitely safe.
  3293. auto &LoadOffsets = LoadOffsetsI->second;
  3294. // Now lookup the store's offsets.
  3295. auto &StoreOffsets = SplitOffsetsMap[SI];
  3296. // If the relative offsets of each split in the load and
  3297. // store match exactly, then we can split them and we
  3298. // don't need to remove them here.
  3299. if (LoadOffsets.Splits == StoreOffsets.Splits)
  3300. return false;
  3301. DEBUG(dbgs()
  3302. << " Mismatched splits for load and store:\n"
  3303. << " " << *LI << "\n"
  3304. << " " << *SI << "\n");
  3305. // We've found a store and load that we need to split
  3306. // with mismatched relative splits. Just give up on them
  3307. // and remove both instructions from our list of
  3308. // candidates.
  3309. UnsplittableLoads.insert(LI);
  3310. return true;
  3311. }),
  3312. Stores.end());
  3313. // Now we have to go *back* through all te stores, because a later store may
  3314. // have caused an earlier store's load to become unsplittable and if it is
  3315. // unsplittable for the later store, then we can't rely on it being split in
  3316. // the earlier store either.
  3317. Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
  3318. [&UnsplittableLoads](StoreInst *SI) {
  3319. auto *LI =
  3320. cast<LoadInst>(SI->getValueOperand());
  3321. return UnsplittableLoads.count(LI);
  3322. }),
  3323. Stores.end());
  3324. // Once we've established all the loads that can't be split for some reason,
  3325. // filter any that made it into our list out.
  3326. Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
  3327. [&UnsplittableLoads](LoadInst *LI) {
  3328. return UnsplittableLoads.count(LI);
  3329. }),
  3330. Loads.end());
  3331. // If no loads or stores are left, there is no pre-splitting to be done for
  3332. // this alloca.
  3333. if (Loads.empty() && Stores.empty())
  3334. return false;
  3335. // From here on, we can't fail and will be building new accesses, so rig up
  3336. // an IR builder.
  3337. IRBuilderTy IRB(&AI);
  3338. // Collect the new slices which we will merge into the alloca slices.
  3339. SmallVector<Slice, 4> NewSlices;
  3340. // Track any allocas we end up splitting loads and stores for so we iterate
  3341. // on them.
  3342. SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
  3343. // At this point, we have collected all of the loads and stores we can
  3344. // pre-split, and the specific splits needed for them. We actually do the
  3345. // splitting in a specific order in order to handle when one of the loads in
  3346. // the value operand to one of the stores.
  3347. //
  3348. // First, we rewrite all of the split loads, and just accumulate each split
  3349. // load in a parallel structure. We also build the slices for them and append
  3350. // them to the alloca slices.
  3351. SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
  3352. std::vector<LoadInst *> SplitLoads;
  3353. const DataLayout &DL = AI.getModule()->getDataLayout();
  3354. for (LoadInst *LI : Loads) {
  3355. SplitLoads.clear();
  3356. IntegerType *Ty = cast<IntegerType>(LI->getType());
  3357. uint64_t LoadSize = Ty->getBitWidth() / 8;
  3358. assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
  3359. auto &Offsets = SplitOffsetsMap[LI];
  3360. assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
  3361. "Slice size should always match load size exactly!");
  3362. uint64_t BaseOffset = Offsets.S->beginOffset();
  3363. assert(BaseOffset + LoadSize > BaseOffset &&
  3364. "Cannot represent alloca access size using 64-bit integers!");
  3365. Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
  3366. IRB.SetInsertPoint(BasicBlock::iterator(LI));
  3367. DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
  3368. uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
  3369. int Idx = 0, Size = Offsets.Splits.size();
  3370. for (;;) {
  3371. auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
  3372. auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
  3373. LoadInst *PLoad = IRB.CreateAlignedLoad(
  3374. getAdjustedPtr(IRB, DL, BasePtr,
  3375. APInt(DL.getPointerSizeInBits(), PartOffset),
  3376. PartPtrTy, BasePtr->getName() + "."),
  3377. getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
  3378. LI->getName());
  3379. // Append this load onto the list of split loads so we can find it later
  3380. // to rewrite the stores.
  3381. SplitLoads.push_back(PLoad);
  3382. // Now build a new slice for the alloca.
  3383. NewSlices.push_back(
  3384. Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
  3385. &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
  3386. /*IsSplittable*/ false));
  3387. DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
  3388. << ", " << NewSlices.back().endOffset() << "): " << *PLoad
  3389. << "\n");
  3390. // See if we've handled all the splits.
  3391. if (Idx >= Size)
  3392. break;
  3393. // Setup the next partition.
  3394. PartOffset = Offsets.Splits[Idx];
  3395. ++Idx;
  3396. PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
  3397. }
  3398. // Now that we have the split loads, do the slow walk over all uses of the
  3399. // load and rewrite them as split stores, or save the split loads to use
  3400. // below if the store is going to be split there anyways.
  3401. bool DeferredStores = false;
  3402. for (User *LU : LI->users()) {
  3403. StoreInst *SI = cast<StoreInst>(LU);
  3404. if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
  3405. DeferredStores = true;
  3406. DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
  3407. continue;
  3408. }
  3409. Value *StoreBasePtr = SI->getPointerOperand();
  3410. IRB.SetInsertPoint(BasicBlock::iterator(SI));
  3411. DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
  3412. for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
  3413. LoadInst *PLoad = SplitLoads[Idx];
  3414. uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
  3415. auto *PartPtrTy =
  3416. PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
  3417. StoreInst *PStore = IRB.CreateAlignedStore(
  3418. PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
  3419. APInt(DL.getPointerSizeInBits(), PartOffset),
  3420. PartPtrTy, StoreBasePtr->getName() + "."),
  3421. getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
  3422. (void)PStore;
  3423. DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
  3424. }
  3425. // We want to immediately iterate on any allocas impacted by splitting
  3426. // this store, and we have to track any promotable alloca (indicated by
  3427. // a direct store) as needing to be resplit because it is no longer
  3428. // promotable.
  3429. if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
  3430. ResplitPromotableAllocas.insert(OtherAI);
  3431. Worklist.insert(OtherAI);
  3432. } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
  3433. StoreBasePtr->stripInBoundsOffsets())) {
  3434. Worklist.insert(OtherAI);
  3435. }
  3436. // Mark the original store as dead.
  3437. DeadInsts.insert(SI);
  3438. }
  3439. // Save the split loads if there are deferred stores among the users.
  3440. if (DeferredStores)
  3441. SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
  3442. // Mark the original load as dead and kill the original slice.
  3443. DeadInsts.insert(LI);
  3444. Offsets.S->kill();
  3445. }
  3446. // Second, we rewrite all of the split stores. At this point, we know that
  3447. // all loads from this alloca have been split already. For stores of such
  3448. // loads, we can simply look up the pre-existing split loads. For stores of
  3449. // other loads, we split those loads first and then write split stores of
  3450. // them.
  3451. for (StoreInst *SI : Stores) {
  3452. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3453. IntegerType *Ty = cast<IntegerType>(LI->getType());
  3454. uint64_t StoreSize = Ty->getBitWidth() / 8;
  3455. assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
  3456. auto &Offsets = SplitOffsetsMap[SI];
  3457. assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
  3458. "Slice size should always match load size exactly!");
  3459. uint64_t BaseOffset = Offsets.S->beginOffset();
  3460. assert(BaseOffset + StoreSize > BaseOffset &&
  3461. "Cannot represent alloca access size using 64-bit integers!");
  3462. Value *LoadBasePtr = LI->getPointerOperand();
  3463. Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
  3464. DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
  3465. // Check whether we have an already split load.
  3466. auto SplitLoadsMapI = SplitLoadsMap.find(LI);
  3467. std::vector<LoadInst *> *SplitLoads = nullptr;
  3468. if (SplitLoadsMapI != SplitLoadsMap.end()) {
  3469. SplitLoads = &SplitLoadsMapI->second;
  3470. assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
  3471. "Too few split loads for the number of splits in the store!");
  3472. } else {
  3473. DEBUG(dbgs() << " of load: " << *LI << "\n");
  3474. }
  3475. uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
  3476. int Idx = 0, Size = Offsets.Splits.size();
  3477. for (;;) {
  3478. auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
  3479. auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
  3480. // Either lookup a split load or create one.
  3481. LoadInst *PLoad;
  3482. if (SplitLoads) {
  3483. PLoad = (*SplitLoads)[Idx];
  3484. } else {
  3485. IRB.SetInsertPoint(BasicBlock::iterator(LI));
  3486. PLoad = IRB.CreateAlignedLoad(
  3487. getAdjustedPtr(IRB, DL, LoadBasePtr,
  3488. APInt(DL.getPointerSizeInBits(), PartOffset),
  3489. PartPtrTy, LoadBasePtr->getName() + "."),
  3490. getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
  3491. LI->getName());
  3492. }
  3493. // And store this partition.
  3494. IRB.SetInsertPoint(BasicBlock::iterator(SI));
  3495. StoreInst *PStore = IRB.CreateAlignedStore(
  3496. PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
  3497. APInt(DL.getPointerSizeInBits(), PartOffset),
  3498. PartPtrTy, StoreBasePtr->getName() + "."),
  3499. getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
  3500. // Now build a new slice for the alloca.
  3501. NewSlices.push_back(
  3502. Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
  3503. &PStore->getOperandUse(PStore->getPointerOperandIndex()),
  3504. /*IsSplittable*/ false));
  3505. DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
  3506. << ", " << NewSlices.back().endOffset() << "): " << *PStore
  3507. << "\n");
  3508. if (!SplitLoads) {
  3509. DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
  3510. }
  3511. // See if we've finished all the splits.
  3512. if (Idx >= Size)
  3513. break;
  3514. // Setup the next partition.
  3515. PartOffset = Offsets.Splits[Idx];
  3516. ++Idx;
  3517. PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
  3518. }
  3519. // We want to immediately iterate on any allocas impacted by splitting
  3520. // this load, which is only relevant if it isn't a load of this alloca and
  3521. // thus we didn't already split the loads above. We also have to keep track
  3522. // of any promotable allocas we split loads on as they can no longer be
  3523. // promoted.
  3524. if (!SplitLoads) {
  3525. if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
  3526. assert(OtherAI != &AI && "We can't re-split our own alloca!");
  3527. ResplitPromotableAllocas.insert(OtherAI);
  3528. Worklist.insert(OtherAI);
  3529. } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
  3530. LoadBasePtr->stripInBoundsOffsets())) {
  3531. assert(OtherAI != &AI && "We can't re-split our own alloca!");
  3532. Worklist.insert(OtherAI);
  3533. }
  3534. }
  3535. // Mark the original store as dead now that we've split it up and kill its
  3536. // slice. Note that we leave the original load in place unless this store
  3537. // was its ownly use. It may in turn be split up if it is an alloca load
  3538. // for some other alloca, but it may be a normal load. This may introduce
  3539. // redundant loads, but where those can be merged the rest of the optimizer
  3540. // should handle the merging, and this uncovers SSA splits which is more
  3541. // important. In practice, the original loads will almost always be fully
  3542. // split and removed eventually, and the splits will be merged by any
  3543. // trivial CSE, including instcombine.
  3544. if (LI->hasOneUse()) {
  3545. assert(*LI->user_begin() == SI && "Single use isn't this store!");
  3546. DeadInsts.insert(LI);
  3547. }
  3548. DeadInsts.insert(SI);
  3549. Offsets.S->kill();
  3550. }
  3551. // Remove the killed slices that have ben pre-split.
  3552. AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
  3553. return S.isDead();
  3554. }), AS.end());
  3555. // Insert our new slices. This will sort and merge them into the sorted
  3556. // sequence.
  3557. AS.insert(NewSlices);
  3558. DEBUG(dbgs() << " Pre-split slices:\n");
  3559. #ifndef NDEBUG
  3560. for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
  3561. DEBUG(AS.print(dbgs(), I, " "));
  3562. #endif
  3563. // Finally, don't try to promote any allocas that new require re-splitting.
  3564. // They have already been added to the worklist above.
  3565. PromotableAllocas.erase(
  3566. std::remove_if(
  3567. PromotableAllocas.begin(), PromotableAllocas.end(),
  3568. [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
  3569. PromotableAllocas.end());
  3570. return true;
  3571. }
  3572. /// \brief Rewrite an alloca partition's users.
  3573. ///
  3574. /// This routine drives both of the rewriting goals of the SROA pass. It tries
  3575. /// to rewrite uses of an alloca partition to be conducive for SSA value
  3576. /// promotion. If the partition needs a new, more refined alloca, this will
  3577. /// build that new alloca, preserving as much type information as possible, and
  3578. /// rewrite the uses of the old alloca to point at the new one and have the
  3579. /// appropriate new offsets. It also evaluates how successful the rewrite was
  3580. /// at enabling promotion and if it was successful queues the alloca to be
  3581. /// promoted.
  3582. AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
  3583. AllocaSlices::Partition &P) {
  3584. // Try to compute a friendly type for this partition of the alloca. This
  3585. // won't always succeed, in which case we fall back to a legal integer type
  3586. // or an i8 array of an appropriate size.
  3587. Type *SliceTy = nullptr;
  3588. const DataLayout &DL = AI.getModule()->getDataLayout();
  3589. if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
  3590. if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
  3591. SliceTy = CommonUseTy;
  3592. if (!SliceTy)
  3593. if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
  3594. P.beginOffset(), P.size()))
  3595. SliceTy = TypePartitionTy;
  3596. if ((!SliceTy || (SliceTy->isArrayTy() &&
  3597. SliceTy->getArrayElementType()->isIntegerTy())) &&
  3598. DL.isLegalInteger(P.size() * 8))
  3599. SliceTy = Type::getIntNTy(*C, P.size() * 8);
  3600. if (!SliceTy)
  3601. SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
  3602. assert(DL.getTypeAllocSize(SliceTy) >= P.size());
  3603. bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
  3604. VectorType *VecTy =
  3605. IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
  3606. if (VecTy)
  3607. SliceTy = VecTy;
  3608. // Check for the case where we're going to rewrite to a new alloca of the
  3609. // exact same type as the original, and with the same access offsets. In that
  3610. // case, re-use the existing alloca, but still run through the rewriter to
  3611. // perform phi and select speculation.
  3612. AllocaInst *NewAI;
  3613. if (SliceTy == AI.getAllocatedType()) {
  3614. assert(P.beginOffset() == 0 &&
  3615. "Non-zero begin offset but same alloca type");
  3616. NewAI = &AI;
  3617. // FIXME: We should be able to bail at this point with "nothing changed".
  3618. // FIXME: We might want to defer PHI speculation until after here.
  3619. // FIXME: return nullptr;
  3620. } else {
  3621. unsigned Alignment = AI.getAlignment();
  3622. if (!Alignment) {
  3623. // The minimum alignment which users can rely on when the explicit
  3624. // alignment is omitted or zero is that required by the ABI for this
  3625. // type.
  3626. Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
  3627. }
  3628. Alignment = MinAlign(Alignment, P.beginOffset());
  3629. // If we will get at least this much alignment from the type alone, leave
  3630. // the alloca's alignment unconstrained.
  3631. if (Alignment <= DL.getABITypeAlignment(SliceTy))
  3632. Alignment = 0;
  3633. NewAI = new AllocaInst(
  3634. SliceTy, nullptr, Alignment,
  3635. AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
  3636. ++NumNewAllocas;
  3637. }
  3638. DEBUG(dbgs() << "Rewriting alloca partition "
  3639. << "[" << P.beginOffset() << "," << P.endOffset()
  3640. << ") to: " << *NewAI << "\n");
  3641. // Track the high watermark on the worklist as it is only relevant for
  3642. // promoted allocas. We will reset it to this point if the alloca is not in
  3643. // fact scheduled for promotion.
  3644. unsigned PPWOldSize = PostPromotionWorklist.size();
  3645. unsigned NumUses = 0;
  3646. SmallPtrSet<PHINode *, 8> PHIUsers;
  3647. SmallPtrSet<SelectInst *, 8> SelectUsers;
  3648. AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
  3649. P.endOffset(), IsIntegerPromotable, VecTy,
  3650. PHIUsers, SelectUsers);
  3651. bool Promotable = true;
  3652. for (Slice *S : P.splitSliceTails()) {
  3653. Promotable &= Rewriter.visit(S);
  3654. ++NumUses;
  3655. }
  3656. for (Slice &S : P) {
  3657. Promotable &= Rewriter.visit(&S);
  3658. ++NumUses;
  3659. }
  3660. NumAllocaPartitionUses += NumUses;
  3661. MaxUsesPerAllocaPartition =
  3662. std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
  3663. // Now that we've processed all the slices in the new partition, check if any
  3664. // PHIs or Selects would block promotion.
  3665. for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
  3666. E = PHIUsers.end();
  3667. I != E; ++I)
  3668. if (!isSafePHIToSpeculate(**I)) {
  3669. Promotable = false;
  3670. PHIUsers.clear();
  3671. SelectUsers.clear();
  3672. break;
  3673. }
  3674. for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
  3675. E = SelectUsers.end();
  3676. I != E; ++I)
  3677. if (!isSafeSelectToSpeculate(**I)) {
  3678. Promotable = false;
  3679. PHIUsers.clear();
  3680. SelectUsers.clear();
  3681. break;
  3682. }
  3683. if (Promotable) {
  3684. if (PHIUsers.empty() && SelectUsers.empty()) {
  3685. // Promote the alloca.
  3686. PromotableAllocas.push_back(NewAI);
  3687. } else {
  3688. // If we have either PHIs or Selects to speculate, add them to those
  3689. // worklists and re-queue the new alloca so that we promote in on the
  3690. // next iteration.
  3691. for (PHINode *PHIUser : PHIUsers)
  3692. SpeculatablePHIs.insert(PHIUser);
  3693. for (SelectInst *SelectUser : SelectUsers)
  3694. SpeculatableSelects.insert(SelectUser);
  3695. Worklist.insert(NewAI);
  3696. }
  3697. } else {
  3698. // If we can't promote the alloca, iterate on it to check for new
  3699. // refinements exposed by splitting the current alloca. Don't iterate on an
  3700. // alloca which didn't actually change and didn't get promoted.
  3701. if (NewAI != &AI)
  3702. Worklist.insert(NewAI);
  3703. // Drop any post-promotion work items if promotion didn't happen.
  3704. while (PostPromotionWorklist.size() > PPWOldSize)
  3705. PostPromotionWorklist.pop_back();
  3706. }
  3707. return NewAI;
  3708. }
  3709. /// \brief Walks the slices of an alloca and form partitions based on them,
  3710. /// rewriting each of their uses.
  3711. bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
  3712. if (AS.begin() == AS.end())
  3713. return false;
  3714. unsigned NumPartitions = 0;
  3715. bool Changed = false;
  3716. const DataLayout &DL = AI.getModule()->getDataLayout();
  3717. // First try to pre-split loads and stores.
  3718. Changed |= presplitLoadsAndStores(AI, AS);
  3719. // Now that we have identified any pre-splitting opportunities, mark any
  3720. // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
  3721. // to split these during pre-splitting, we want to force them to be
  3722. // rewritten into a partition.
  3723. bool IsSorted = true;
  3724. for (Slice &S : AS) {
  3725. if (!S.isSplittable())
  3726. continue;
  3727. // FIXME: We currently leave whole-alloca splittable loads and stores. This
  3728. // used to be the only splittable loads and stores and we need to be
  3729. // confident that the above handling of splittable loads and stores is
  3730. // completely sufficient before we forcibly disable the remaining handling.
  3731. if (S.beginOffset() == 0 &&
  3732. S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
  3733. continue;
  3734. if (isa<LoadInst>(S.getUse()->getUser()) ||
  3735. isa<StoreInst>(S.getUse()->getUser())) {
  3736. S.makeUnsplittable();
  3737. IsSorted = false;
  3738. }
  3739. }
  3740. if (!IsSorted)
  3741. std::sort(AS.begin(), AS.end());
  3742. /// \brief Describes the allocas introduced by rewritePartition
  3743. /// in order to migrate the debug info.
  3744. struct Piece {
  3745. AllocaInst *Alloca;
  3746. uint64_t Offset;
  3747. uint64_t Size;
  3748. Piece(AllocaInst *AI, uint64_t O, uint64_t S)
  3749. : Alloca(AI), Offset(O), Size(S) {}
  3750. };
  3751. SmallVector<Piece, 4> Pieces;
  3752. // Rewrite each partition.
  3753. for (auto &P : AS.partitions()) {
  3754. if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
  3755. Changed = true;
  3756. if (NewAI != &AI) {
  3757. uint64_t SizeOfByte = 8;
  3758. uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
  3759. // Don't include any padding.
  3760. uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
  3761. Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
  3762. }
  3763. }
  3764. ++NumPartitions;
  3765. }
  3766. NumAllocaPartitions += NumPartitions;
  3767. MaxPartitionsPerAlloca =
  3768. std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
  3769. // Migrate debug information from the old alloca to the new alloca(s)
  3770. // and the individial partitions.
  3771. if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
  3772. auto *Var = DbgDecl->getVariable();
  3773. auto *Expr = DbgDecl->getExpression();
  3774. DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
  3775. /*AllowUnresolved*/ false);
  3776. bool IsSplit = Pieces.size() > 1;
  3777. // HLSL Change Begins
  3778. // Take into account debug stride in extra metadata
  3779. std::vector<hlsl::DxilDIArrayDim> ArrayDims;
  3780. unsigned FirstFragmentOffsetInBits = 0;
  3781. if (!hlsl::DxilMDHelper::GetVariableDebugLayout(DbgDecl, FirstFragmentOffsetInBits, ArrayDims)
  3782. && Expr->isBitPiece()) {
  3783. FirstFragmentOffsetInBits = Expr->getBitPieceOffset();
  3784. }
  3785. unsigned FragmentSizeInBits = DL.getTypeAllocSizeInBits(AI.getAllocatedType());
  3786. for (const hlsl::DxilDIArrayDim& ArrayDim : ArrayDims) {
  3787. assert(FragmentSizeInBits % ArrayDim.NumElements == 0);
  3788. FragmentSizeInBits /= ArrayDim.NumElements;
  3789. }
  3790. // HLSL Change Ends
  3791. for (auto Piece : Pieces) {
  3792. // Create a piece expression describing the new partition or reuse AI's
  3793. // expression if there is only one partition.
  3794. auto *PieceExpr = Expr;
  3795. if (IsSplit || Expr->isBitPiece()) {
  3796. #if 0 // HLSL Change - Handle Strides
  3797. // If this alloca is already a scalar replacement of a larger aggregate,
  3798. // Piece.Offset describes the offset inside the scalar.
  3799. uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
  3800. uint64_t Start = Offset + Piece.Offset;
  3801. uint64_t Size = Piece.Size;
  3802. if (Expr->isBitPiece()) {
  3803. uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
  3804. if (Start >= AbsEnd)
  3805. // No need to describe a SROAed padding.
  3806. continue;
  3807. Size = std::min(Size, AbsEnd - Start);
  3808. }
  3809. // HLSL Change Begins
  3810. #else
  3811. // Find the fragment from the original user variable in which this piece falls
  3812. uint64_t PieceFragmentIndex = Piece.Offset / FragmentSizeInBits;
  3813. // Compute the offset in the original user variable
  3814. uint64_t StartInFragment = Piece.Offset % FragmentSizeInBits;
  3815. uint64_t Start = FirstFragmentOffsetInBits + Piece.Offset % FragmentSizeInBits;
  3816. for (auto ArrayDimIter = ArrayDims.rbegin(); ArrayDimIter != ArrayDims.rend(); ++ArrayDimIter) {
  3817. Start += ArrayDimIter->StrideInBits * (PieceFragmentIndex % ArrayDimIter->NumElements);
  3818. PieceFragmentIndex /= ArrayDimIter->NumElements;
  3819. }
  3820. uint64_t Size = std::min<uint64_t>(Piece.Size, FragmentSizeInBits - StartInFragment);
  3821. #endif
  3822. // HLSL Change Ends
  3823. PieceExpr = DIB.createBitPieceExpression(Start, Size);
  3824. }
  3825. // Remove any existing dbg.declare intrinsic describing the same alloca.
  3826. if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
  3827. OldDDI->eraseFromParent();
  3828. DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
  3829. &AI);
  3830. }
  3831. }
  3832. return Changed;
  3833. }
  3834. /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
  3835. void SROA::clobberUse(Use &U) {
  3836. Value *OldV = U;
  3837. // Replace the use with an undef value.
  3838. U = UndefValue::get(OldV->getType());
  3839. // Check for this making an instruction dead. We have to garbage collect
  3840. // all the dead instructions to ensure the uses of any alloca end up being
  3841. // minimal.
  3842. if (Instruction *OldI = dyn_cast<Instruction>(OldV))
  3843. if (isInstructionTriviallyDead(OldI)) {
  3844. DeadInsts.insert(OldI);
  3845. }
  3846. }
  3847. /// \brief Analyze an alloca for SROA.
  3848. ///
  3849. /// This analyzes the alloca to ensure we can reason about it, builds
  3850. /// the slices of the alloca, and then hands it off to be split and
  3851. /// rewritten as needed.
  3852. bool SROA::runOnAlloca(AllocaInst &AI) {
  3853. DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
  3854. ++NumAllocasAnalyzed;
  3855. // Special case dead allocas, as they're trivial.
  3856. if (AI.use_empty()) {
  3857. AI.eraseFromParent();
  3858. return true;
  3859. }
  3860. const DataLayout &DL = AI.getModule()->getDataLayout();
  3861. // HLSL Change Begin
  3862. // This passes only deals with byte-sized types.
  3863. // We can have i1 allocas for a bool return value when compiling without optimizations
  3864. // If we let this run, it'll get turned into an i8, which is invalid dxil.
  3865. if (AI.getAllocatedType()->isIntegerTy(1))
  3866. return false;
  3867. // HLSL Change End
  3868. // Skip alloca forms that this analysis can't handle.
  3869. if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
  3870. hlsl::dxilutil::IsHLSLObjectType(
  3871. AI.getAllocatedType()) || // HLSL Change - not sroa resource type.
  3872. // HLSL Change Begin - not sroa matrix type.
  3873. (SkipHLSLMat &&
  3874. hlsl::HLMatrixType::isa(AI.getAllocatedType())) ||
  3875. // HLSL Change End.
  3876. DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
  3877. return false;
  3878. bool Changed = false;
  3879. // First, split any FCA loads and stores touching this alloca to promote
  3880. // better splitting and promotion opportunities.
  3881. AggLoadStoreRewriter AggRewriter(DL, SkipHLSLMat);
  3882. Changed |= AggRewriter.rewrite(AI);
  3883. // Build the slices using a recursive instruction-visiting builder.
  3884. AllocaSlices AS(DL, AI, SkipHLSLMat);
  3885. DEBUG(AS.print(dbgs()));
  3886. if (AS.isEscaped())
  3887. return Changed;
  3888. // Delete all the dead users of this alloca before splitting and rewriting it.
  3889. for (Instruction *DeadUser : AS.getDeadUsers()) {
  3890. // Free up everything used by this instruction.
  3891. for (Use &DeadOp : DeadUser->operands())
  3892. clobberUse(DeadOp);
  3893. // Now replace the uses of this instruction.
  3894. DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
  3895. // And mark it for deletion.
  3896. DeadInsts.insert(DeadUser);
  3897. Changed = true;
  3898. }
  3899. for (Use *DeadOp : AS.getDeadOperands()) {
  3900. clobberUse(*DeadOp);
  3901. Changed = true;
  3902. }
  3903. // No slices to split. Leave the dead alloca for a later pass to clean up.
  3904. if (AS.begin() == AS.end())
  3905. return Changed;
  3906. Changed |= splitAlloca(AI, AS);
  3907. DEBUG(dbgs() << " Speculating PHIs\n");
  3908. while (!SpeculatablePHIs.empty())
  3909. speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
  3910. DEBUG(dbgs() << " Speculating Selects\n");
  3911. while (!SpeculatableSelects.empty())
  3912. speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
  3913. return Changed;
  3914. }
  3915. /// \brief Delete the dead instructions accumulated in this run.
  3916. ///
  3917. /// Recursively deletes the dead instructions we've accumulated. This is done
  3918. /// at the very end to maximize locality of the recursive delete and to
  3919. /// minimize the problems of invalidated instruction pointers as such pointers
  3920. /// are used heavily in the intermediate stages of the algorithm.
  3921. ///
  3922. /// We also record the alloca instructions deleted here so that they aren't
  3923. /// subsequently handed to mem2reg to promote.
  3924. void SROA::deleteDeadInstructions(
  3925. SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
  3926. while (!DeadInsts.empty()) {
  3927. Instruction *I = DeadInsts.pop_back_val();
  3928. DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
  3929. // HLSL Change Begins
  3930. // If the instruction is an alloca, find the possible dbg.declare connected
  3931. // to it, and remove it too. We must do this before calling RAUW or we will
  3932. // not be able to find it.
  3933. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  3934. DeletedAllocas.insert(AI);
  3935. if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
  3936. DbgDecl->eraseFromParent();
  3937. }
  3938. // HLSL Change Ends
  3939. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  3940. for (Use &Operand : I->operands())
  3941. if (Instruction *U = dyn_cast<Instruction>(Operand)) {
  3942. // Zero out the operand and see if it becomes trivially dead.
  3943. Operand = nullptr;
  3944. if (isInstructionTriviallyDead(U))
  3945. DeadInsts.insert(U);
  3946. }
  3947. #if 0 // HLSL Change - blocked moved before replaceAllUsesWith
  3948. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  3949. DeletedAllocas.insert(AI);
  3950. if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
  3951. DbgDecl->eraseFromParent();
  3952. }
  3953. #endif // HLSL Change
  3954. ++NumDeleted;
  3955. I->eraseFromParent();
  3956. }
  3957. }
  3958. static void enqueueUsersInWorklist(Instruction &I,
  3959. SmallVectorImpl<Instruction *> &Worklist,
  3960. SmallPtrSetImpl<Instruction *> &Visited) {
  3961. for (User *U : I.users())
  3962. if (Visited.insert(cast<Instruction>(U)).second)
  3963. Worklist.push_back(cast<Instruction>(U));
  3964. }
  3965. /// \brief Promote the allocas, using the best available technique.
  3966. ///
  3967. /// This attempts to promote whatever allocas have been identified as viable in
  3968. /// the PromotableAllocas list. If that list is empty, there is nothing to do.
  3969. /// If there is a domtree available, we attempt to promote using the full power
  3970. /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
  3971. /// based on the SSAUpdater utilities. This function returns whether any
  3972. /// promotion occurred.
  3973. bool SROA::promoteAllocas(Function &F) {
  3974. if (PromotableAllocas.empty())
  3975. return false;
  3976. NumPromoted += PromotableAllocas.size();
  3977. if (DT && !ForceSSAUpdater) {
  3978. DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
  3979. PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
  3980. PromotableAllocas.clear();
  3981. return true;
  3982. }
  3983. DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
  3984. SSAUpdater SSA;
  3985. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  3986. SmallVector<Instruction *, 64> Insts;
  3987. // We need a worklist to walk the uses of each alloca.
  3988. SmallVector<Instruction *, 8> Worklist;
  3989. SmallPtrSet<Instruction *, 8> Visited;
  3990. SmallVector<Instruction *, 32> DeadInsts;
  3991. for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
  3992. AllocaInst *AI = PromotableAllocas[Idx];
  3993. Insts.clear();
  3994. Worklist.clear();
  3995. Visited.clear();
  3996. enqueueUsersInWorklist(*AI, Worklist, Visited);
  3997. while (!Worklist.empty()) {
  3998. Instruction *I = Worklist.pop_back_val();
  3999. // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
  4000. // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
  4001. // leading to them) here. Eventually it should use them to optimize the
  4002. // scalar values produced.
  4003. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  4004. assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
  4005. II->getIntrinsicID() == Intrinsic::lifetime_end);
  4006. II->eraseFromParent();
  4007. continue;
  4008. }
  4009. // Push the loads and stores we find onto the list. SROA will already
  4010. // have validated that all loads and stores are viable candidates for
  4011. // promotion.
  4012. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  4013. assert(LI->getType() == AI->getAllocatedType());
  4014. Insts.push_back(LI);
  4015. continue;
  4016. }
  4017. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  4018. assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
  4019. Insts.push_back(SI);
  4020. continue;
  4021. }
  4022. // For everything else, we know that only no-op bitcasts and GEPs will
  4023. // make it this far, just recurse through them and recall them for later
  4024. // removal.
  4025. DeadInsts.push_back(I);
  4026. enqueueUsersInWorklist(*I, Worklist, Visited);
  4027. }
  4028. AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
  4029. while (!DeadInsts.empty())
  4030. DeadInsts.pop_back_val()->eraseFromParent();
  4031. AI->eraseFromParent();
  4032. }
  4033. PromotableAllocas.clear();
  4034. return true;
  4035. }
  4036. // HLSL Change - run SROA more than once if updated.
  4037. bool SROA::runOnFunctionImp(Function &F) {
  4038. if (skipOptnoneFunction(F))
  4039. return false;
  4040. DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
  4041. C = &F.getContext();
  4042. DominatorTreeWrapperPass *DTWP =
  4043. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  4044. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  4045. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  4046. BasicBlock &EntryBB = F.getEntryBlock();
  4047. for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
  4048. I != E; ++I) {
  4049. if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
  4050. Worklist.insert(AI);
  4051. }
  4052. bool Changed = false;
  4053. // A set of deleted alloca instruction pointers which should be removed from
  4054. // the list of promotable allocas.
  4055. SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
  4056. do {
  4057. while (!Worklist.empty()) {
  4058. Changed |= runOnAlloca(*Worklist.pop_back_val());
  4059. deleteDeadInstructions(DeletedAllocas);
  4060. // Remove the deleted allocas from various lists so that we don't try to
  4061. // continue processing them.
  4062. if (!DeletedAllocas.empty()) {
  4063. auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
  4064. Worklist.remove_if(IsInSet);
  4065. PostPromotionWorklist.remove_if(IsInSet);
  4066. PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
  4067. PromotableAllocas.end(),
  4068. IsInSet),
  4069. PromotableAllocas.end());
  4070. DeletedAllocas.clear();
  4071. }
  4072. }
  4073. Changed |= promoteAllocas(F);
  4074. Worklist = PostPromotionWorklist;
  4075. PostPromotionWorklist.clear();
  4076. } while (!Worklist.empty());
  4077. return Changed;
  4078. }
  4079. // HLSL Change Begin.
  4080. // In some case, alloca fail to optimized early will be ready to optimize after
  4081. // other alloca is optimized.
  4082. bool SROA::runOnFunction(Function &F) {
  4083. unsigned count = 0;
  4084. const unsigned kMaxCount = 3;
  4085. while ((count++) < kMaxCount) {
  4086. if (!runOnFunctionImp(F))
  4087. break;
  4088. }
  4089. return count > 1;
  4090. }
  4091. // HLSL Change End.
  4092. void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
  4093. AU.addRequired<AssumptionCacheTracker>();
  4094. if (RequiresDomTree)
  4095. AU.addRequired<DominatorTreeWrapperPass>();
  4096. AU.setPreservesCFG();
  4097. }