RegisterCoalescer.cpp 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215
  1. //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the generic RegisterCoalescer interface which
  10. // is used as the common interface used by all clients and
  11. // implementations of register coalescing.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "RegisterCoalescer.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/BitVector.h"
  17. #include "llvm/ADT/DenseSet.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/CodeGen/LiveInterval.h"
  24. #include "llvm/CodeGen/LiveIntervals.h"
  25. #include "llvm/CodeGen/LiveRangeEdit.h"
  26. #include "llvm/CodeGen/MachineBasicBlock.h"
  27. #include "llvm/CodeGen/MachineFunction.h"
  28. #include "llvm/CodeGen/MachineFunctionPass.h"
  29. #include "llvm/CodeGen/MachineInstr.h"
  30. #include "llvm/CodeGen/MachineInstrBuilder.h"
  31. #include "llvm/CodeGen/MachineLoopInfo.h"
  32. #include "llvm/CodeGen/MachineOperand.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/Passes.h"
  35. #include "llvm/CodeGen/RegisterClassInfo.h"
  36. #include "llvm/CodeGen/SlotIndexes.h"
  37. #include "llvm/CodeGen/TargetInstrInfo.h"
  38. #include "llvm/CodeGen/TargetOpcodes.h"
  39. #include "llvm/CodeGen/TargetRegisterInfo.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/IR/DebugLoc.h"
  42. #include "llvm/InitializePasses.h"
  43. #include "llvm/MC/LaneBitmask.h"
  44. #include "llvm/MC/MCInstrDesc.h"
  45. #include "llvm/MC/MCRegisterInfo.h"
  46. #include "llvm/Pass.h"
  47. #include "llvm/Support/CommandLine.h"
  48. #include "llvm/Support/Compiler.h"
  49. #include "llvm/Support/Debug.h"
  50. #include "llvm/Support/ErrorHandling.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. #include <algorithm>
  53. #include <cassert>
  54. #include <iterator>
  55. #include <limits>
  56. #include <tuple>
  57. #include <utility>
  58. #include <vector>
  59. using namespace llvm;
  60. #define DEBUG_TYPE "regalloc"
  61. STATISTIC(numJoins , "Number of interval joins performed");
  62. STATISTIC(numCrossRCs , "Number of cross class joins performed");
  63. STATISTIC(numCommutes , "Number of instruction commuting performed");
  64. STATISTIC(numExtends , "Number of copies extended");
  65. STATISTIC(NumReMats , "Number of instructions re-materialized");
  66. STATISTIC(NumInflated , "Number of register classes inflated");
  67. STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
  68. STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
  69. STATISTIC(NumShrinkToUses, "Number of shrinkToUses called");
  70. static cl::opt<bool> EnableJoining("join-liveintervals",
  71. cl::desc("Coalesce copies (default=true)"),
  72. cl::init(true), cl::Hidden);
  73. static cl::opt<bool> UseTerminalRule("terminal-rule",
  74. cl::desc("Apply the terminal rule"),
  75. cl::init(false), cl::Hidden);
  76. /// Temporary flag to test critical edge unsplitting.
  77. static cl::opt<bool>
  78. EnableJoinSplits("join-splitedges",
  79. cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
  80. /// Temporary flag to test global copy optimization.
  81. static cl::opt<cl::boolOrDefault>
  82. EnableGlobalCopies("join-globalcopies",
  83. cl::desc("Coalesce copies that span blocks (default=subtarget)"),
  84. cl::init(cl::BOU_UNSET), cl::Hidden);
  85. static cl::opt<bool>
  86. VerifyCoalescing("verify-coalescing",
  87. cl::desc("Verify machine instrs before and after register coalescing"),
  88. cl::Hidden);
  89. static cl::opt<unsigned> LateRematUpdateThreshold(
  90. "late-remat-update-threshold", cl::Hidden,
  91. cl::desc("During rematerialization for a copy, if the def instruction has "
  92. "many other copy uses to be rematerialized, delay the multiple "
  93. "separate live interval update work and do them all at once after "
  94. "all those rematerialization are done. It will save a lot of "
  95. "repeated work. "),
  96. cl::init(100));
  97. static cl::opt<unsigned> LargeIntervalSizeThreshold(
  98. "large-interval-size-threshold", cl::Hidden,
  99. cl::desc("If the valnos size of an interval is larger than the threshold, "
  100. "it is regarded as a large interval. "),
  101. cl::init(100));
  102. static cl::opt<unsigned> LargeIntervalFreqThreshold(
  103. "large-interval-freq-threshold", cl::Hidden,
  104. cl::desc("For a large interval, if it is coalesed with other live "
  105. "intervals many times more than the threshold, stop its "
  106. "coalescing to control the compile time. "),
  107. cl::init(100));
  108. namespace {
  109. class JoinVals;
  110. class RegisterCoalescer : public MachineFunctionPass,
  111. private LiveRangeEdit::Delegate {
  112. MachineFunction* MF = nullptr;
  113. MachineRegisterInfo* MRI = nullptr;
  114. const TargetRegisterInfo* TRI = nullptr;
  115. const TargetInstrInfo* TII = nullptr;
  116. LiveIntervals *LIS = nullptr;
  117. const MachineLoopInfo* Loops = nullptr;
  118. AliasAnalysis *AA = nullptr;
  119. RegisterClassInfo RegClassInfo;
  120. /// Position and VReg of a PHI instruction during coalescing.
  121. struct PHIValPos {
  122. SlotIndex SI; ///< Slot where this PHI occurs.
  123. Register Reg; ///< VReg the PHI occurs in.
  124. unsigned SubReg; ///< Qualifying subregister for Reg.
  125. };
  126. /// Map from debug instruction number to PHI position during coalescing.
  127. DenseMap<unsigned, PHIValPos> PHIValToPos;
  128. /// Index of, for each VReg, which debug instruction numbers and
  129. /// corresponding PHIs are sensitive to coalescing. Each VReg may have
  130. /// multiple PHI defs, at different positions.
  131. DenseMap<Register, SmallVector<unsigned, 2>> RegToPHIIdx;
  132. /// Debug variable location tracking -- for each VReg, maintain an
  133. /// ordered-by-slot-index set of DBG_VALUEs, to help quick
  134. /// identification of whether coalescing may change location validity.
  135. using DbgValueLoc = std::pair<SlotIndex, MachineInstr*>;
  136. DenseMap<Register, std::vector<DbgValueLoc>> DbgVRegToValues;
  137. /// VRegs may be repeatedly coalesced, and have many DBG_VALUEs attached.
  138. /// To avoid repeatedly merging sets of DbgValueLocs, instead record
  139. /// which vregs have been coalesced, and where to. This map is from
  140. /// vreg => {set of vregs merged in}.
  141. DenseMap<Register, SmallVector<Register, 4>> DbgMergedVRegNums;
  142. /// A LaneMask to remember on which subregister live ranges we need to call
  143. /// shrinkToUses() later.
  144. LaneBitmask ShrinkMask;
  145. /// True if the main range of the currently coalesced intervals should be
  146. /// checked for smaller live intervals.
  147. bool ShrinkMainRange = false;
  148. /// True if the coalescer should aggressively coalesce global copies
  149. /// in favor of keeping local copies.
  150. bool JoinGlobalCopies = false;
  151. /// True if the coalescer should aggressively coalesce fall-thru
  152. /// blocks exclusively containing copies.
  153. bool JoinSplitEdges = false;
  154. /// Copy instructions yet to be coalesced.
  155. SmallVector<MachineInstr*, 8> WorkList;
  156. SmallVector<MachineInstr*, 8> LocalWorkList;
  157. /// Set of instruction pointers that have been erased, and
  158. /// that may be present in WorkList.
  159. SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
  160. /// Dead instructions that are about to be deleted.
  161. SmallVector<MachineInstr*, 8> DeadDefs;
  162. /// Virtual registers to be considered for register class inflation.
  163. SmallVector<Register, 8> InflateRegs;
  164. /// The collection of live intervals which should have been updated
  165. /// immediately after rematerialiation but delayed until
  166. /// lateLiveIntervalUpdate is called.
  167. DenseSet<Register> ToBeUpdated;
  168. /// Record how many times the large live interval with many valnos
  169. /// has been tried to join with other live interval.
  170. DenseMap<Register, unsigned long> LargeLIVisitCounter;
  171. /// Recursively eliminate dead defs in DeadDefs.
  172. void eliminateDeadDefs();
  173. /// allUsesAvailableAt - Return true if all registers used by OrigMI at
  174. /// OrigIdx are also available with the same value at UseIdx.
  175. bool allUsesAvailableAt(const MachineInstr *OrigMI, SlotIndex OrigIdx,
  176. SlotIndex UseIdx);
  177. /// LiveRangeEdit callback for eliminateDeadDefs().
  178. void LRE_WillEraseInstruction(MachineInstr *MI) override;
  179. /// Coalesce the LocalWorkList.
  180. void coalesceLocals();
  181. /// Join compatible live intervals
  182. void joinAllIntervals();
  183. /// Coalesce copies in the specified MBB, putting
  184. /// copies that cannot yet be coalesced into WorkList.
  185. void copyCoalesceInMBB(MachineBasicBlock *MBB);
  186. /// Tries to coalesce all copies in CurrList. Returns true if any progress
  187. /// was made.
  188. bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
  189. /// If one def has many copy like uses, and those copy uses are all
  190. /// rematerialized, the live interval update needed for those
  191. /// rematerializations will be delayed and done all at once instead
  192. /// of being done multiple times. This is to save compile cost because
  193. /// live interval update is costly.
  194. void lateLiveIntervalUpdate();
  195. /// Check if the incoming value defined by a COPY at \p SLRQ in the subrange
  196. /// has no value defined in the predecessors. If the incoming value is the
  197. /// same as defined by the copy itself, the value is considered undefined.
  198. bool copyValueUndefInPredecessors(LiveRange &S,
  199. const MachineBasicBlock *MBB,
  200. LiveQueryResult SLRQ);
  201. /// Set necessary undef flags on subregister uses after pruning out undef
  202. /// lane segments from the subrange.
  203. void setUndefOnPrunedSubRegUses(LiveInterval &LI, Register Reg,
  204. LaneBitmask PrunedLanes);
  205. /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
  206. /// src/dst of the copy instruction CopyMI. This returns true if the copy
  207. /// was successfully coalesced away. If it is not currently possible to
  208. /// coalesce this interval, but it may be possible if other things get
  209. /// coalesced, then it returns true by reference in 'Again'.
  210. bool joinCopy(MachineInstr *CopyMI, bool &Again);
  211. /// Attempt to join these two intervals. On failure, this
  212. /// returns false. The output "SrcInt" will not have been modified, so we
  213. /// can use this information below to update aliases.
  214. bool joinIntervals(CoalescerPair &CP);
  215. /// Attempt joining two virtual registers. Return true on success.
  216. bool joinVirtRegs(CoalescerPair &CP);
  217. /// If a live interval has many valnos and is coalesced with other
  218. /// live intervals many times, we regard such live interval as having
  219. /// high compile time cost.
  220. bool isHighCostLiveInterval(LiveInterval &LI);
  221. /// Attempt joining with a reserved physreg.
  222. bool joinReservedPhysReg(CoalescerPair &CP);
  223. /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
  224. /// Subranges in @p LI which only partially interfere with the desired
  225. /// LaneMask are split as necessary. @p LaneMask are the lanes that
  226. /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
  227. /// lanemasks already adjusted to the coalesced register.
  228. void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
  229. LaneBitmask LaneMask, CoalescerPair &CP,
  230. unsigned DstIdx);
  231. /// Join the liveranges of two subregisters. Joins @p RRange into
  232. /// @p LRange, @p RRange may be invalid afterwards.
  233. void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
  234. LaneBitmask LaneMask, const CoalescerPair &CP);
  235. /// We found a non-trivially-coalescable copy. If the source value number is
  236. /// defined by a copy from the destination reg see if we can merge these two
  237. /// destination reg valno# into a single value number, eliminating a copy.
  238. /// This returns true if an interval was modified.
  239. bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
  240. /// Return true if there are definitions of IntB
  241. /// other than BValNo val# that can reach uses of AValno val# of IntA.
  242. bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
  243. VNInfo *AValNo, VNInfo *BValNo);
  244. /// We found a non-trivially-coalescable copy.
  245. /// If the source value number is defined by a commutable instruction and
  246. /// its other operand is coalesced to the copy dest register, see if we
  247. /// can transform the copy into a noop by commuting the definition.
  248. /// This returns a pair of two flags:
  249. /// - the first element is true if an interval was modified,
  250. /// - the second element is true if the destination interval needs
  251. /// to be shrunk after deleting the copy.
  252. std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP,
  253. MachineInstr *CopyMI);
  254. /// We found a copy which can be moved to its less frequent predecessor.
  255. bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
  256. /// If the source of a copy is defined by a
  257. /// trivial computation, replace the copy by rematerialize the definition.
  258. bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
  259. bool &IsDefCopy);
  260. /// Return true if a copy involving a physreg should be joined.
  261. bool canJoinPhys(const CoalescerPair &CP);
  262. /// Replace all defs and uses of SrcReg to DstReg and update the subregister
  263. /// number if it is not zero. If DstReg is a physical register and the
  264. /// existing subregister number of the def / use being updated is not zero,
  265. /// make sure to set it to the correct physical subregister.
  266. void updateRegDefsUses(Register SrcReg, Register DstReg, unsigned SubIdx);
  267. /// If the given machine operand reads only undefined lanes add an undef
  268. /// flag.
  269. /// This can happen when undef uses were previously concealed by a copy
  270. /// which we coalesced. Example:
  271. /// %0:sub0<def,read-undef> = ...
  272. /// %1 = COPY %0 <-- Coalescing COPY reveals undef
  273. /// = use %1:sub1 <-- hidden undef use
  274. void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
  275. MachineOperand &MO, unsigned SubRegIdx);
  276. /// Handle copies of undef values. If the undef value is an incoming
  277. /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
  278. /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
  279. /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
  280. MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
  281. /// Check whether or not we should apply the terminal rule on the
  282. /// destination (Dst) of \p Copy.
  283. /// When the terminal rule applies, Copy is not profitable to
  284. /// coalesce.
  285. /// Dst is terminal if it has exactly one affinity (Dst, Src) and
  286. /// at least one interference (Dst, Dst2). If Dst is terminal, the
  287. /// terminal rule consists in checking that at least one of
  288. /// interfering node, say Dst2, has an affinity of equal or greater
  289. /// weight with Src.
  290. /// In that case, Dst2 and Dst will not be able to be both coalesced
  291. /// with Src. Since Dst2 exposes more coalescing opportunities than
  292. /// Dst, we can drop \p Copy.
  293. bool applyTerminalRule(const MachineInstr &Copy) const;
  294. /// Wrapper method for \see LiveIntervals::shrinkToUses.
  295. /// This method does the proper fixing of the live-ranges when the afore
  296. /// mentioned method returns true.
  297. void shrinkToUses(LiveInterval *LI,
  298. SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
  299. NumShrinkToUses++;
  300. if (LIS->shrinkToUses(LI, Dead)) {
  301. /// Check whether or not \p LI is composed by multiple connected
  302. /// components and if that is the case, fix that.
  303. SmallVector<LiveInterval*, 8> SplitLIs;
  304. LIS->splitSeparateComponents(*LI, SplitLIs);
  305. }
  306. }
  307. /// Wrapper Method to do all the necessary work when an Instruction is
  308. /// deleted.
  309. /// Optimizations should use this to make sure that deleted instructions
  310. /// are always accounted for.
  311. void deleteInstr(MachineInstr* MI) {
  312. ErasedInstrs.insert(MI);
  313. LIS->RemoveMachineInstrFromMaps(*MI);
  314. MI->eraseFromParent();
  315. }
  316. /// Walk over function and initialize the DbgVRegToValues map.
  317. void buildVRegToDbgValueMap(MachineFunction &MF);
  318. /// Test whether, after merging, any DBG_VALUEs would refer to a
  319. /// different value number than before merging, and whether this can
  320. /// be resolved. If not, mark the DBG_VALUE as being undef.
  321. void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
  322. JoinVals &LHSVals, LiveRange &RHS,
  323. JoinVals &RHSVals);
  324. void checkMergingChangesDbgValuesImpl(Register Reg, LiveRange &OtherRange,
  325. LiveRange &RegRange, JoinVals &Vals2);
  326. public:
  327. static char ID; ///< Class identification, replacement for typeinfo
  328. RegisterCoalescer() : MachineFunctionPass(ID) {
  329. initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
  330. }
  331. void getAnalysisUsage(AnalysisUsage &AU) const override;
  332. void releaseMemory() override;
  333. /// This is the pass entry point.
  334. bool runOnMachineFunction(MachineFunction&) override;
  335. /// Implement the dump method.
  336. void print(raw_ostream &O, const Module* = nullptr) const override;
  337. };
  338. } // end anonymous namespace
  339. char RegisterCoalescer::ID = 0;
  340. char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
  341. INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
  342. "Simple Register Coalescing", false, false)
  343. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  344. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  345. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  346. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  347. INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
  348. "Simple Register Coalescing", false, false)
  349. LLVM_NODISCARD static bool isMoveInstr(const TargetRegisterInfo &tri,
  350. const MachineInstr *MI, Register &Src,
  351. Register &Dst, unsigned &SrcSub,
  352. unsigned &DstSub) {
  353. if (MI->isCopy()) {
  354. Dst = MI->getOperand(0).getReg();
  355. DstSub = MI->getOperand(0).getSubReg();
  356. Src = MI->getOperand(1).getReg();
  357. SrcSub = MI->getOperand(1).getSubReg();
  358. } else if (MI->isSubregToReg()) {
  359. Dst = MI->getOperand(0).getReg();
  360. DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
  361. MI->getOperand(3).getImm());
  362. Src = MI->getOperand(2).getReg();
  363. SrcSub = MI->getOperand(2).getSubReg();
  364. } else
  365. return false;
  366. return true;
  367. }
  368. /// Return true if this block should be vacated by the coalescer to eliminate
  369. /// branches. The important cases to handle in the coalescer are critical edges
  370. /// split during phi elimination which contain only copies. Simple blocks that
  371. /// contain non-branches should also be vacated, but this can be handled by an
  372. /// earlier pass similar to early if-conversion.
  373. static bool isSplitEdge(const MachineBasicBlock *MBB) {
  374. if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
  375. return false;
  376. for (const auto &MI : *MBB) {
  377. if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
  378. return false;
  379. }
  380. return true;
  381. }
  382. bool CoalescerPair::setRegisters(const MachineInstr *MI) {
  383. SrcReg = DstReg = Register();
  384. SrcIdx = DstIdx = 0;
  385. NewRC = nullptr;
  386. Flipped = CrossClass = false;
  387. Register Src, Dst;
  388. unsigned SrcSub = 0, DstSub = 0;
  389. if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
  390. return false;
  391. Partial = SrcSub || DstSub;
  392. // If one register is a physreg, it must be Dst.
  393. if (Register::isPhysicalRegister(Src)) {
  394. if (Register::isPhysicalRegister(Dst))
  395. return false;
  396. std::swap(Src, Dst);
  397. std::swap(SrcSub, DstSub);
  398. Flipped = true;
  399. }
  400. const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
  401. if (Register::isPhysicalRegister(Dst)) {
  402. // Eliminate DstSub on a physreg.
  403. if (DstSub) {
  404. Dst = TRI.getSubReg(Dst, DstSub);
  405. if (!Dst) return false;
  406. DstSub = 0;
  407. }
  408. // Eliminate SrcSub by picking a corresponding Dst superregister.
  409. if (SrcSub) {
  410. Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
  411. if (!Dst) return false;
  412. } else if (!MRI.getRegClass(Src)->contains(Dst)) {
  413. return false;
  414. }
  415. } else {
  416. // Both registers are virtual.
  417. const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
  418. const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
  419. // Both registers have subreg indices.
  420. if (SrcSub && DstSub) {
  421. // Copies between different sub-registers are never coalescable.
  422. if (Src == Dst && SrcSub != DstSub)
  423. return false;
  424. NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
  425. SrcIdx, DstIdx);
  426. if (!NewRC)
  427. return false;
  428. } else if (DstSub) {
  429. // SrcReg will be merged with a sub-register of DstReg.
  430. SrcIdx = DstSub;
  431. NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
  432. } else if (SrcSub) {
  433. // DstReg will be merged with a sub-register of SrcReg.
  434. DstIdx = SrcSub;
  435. NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
  436. } else {
  437. // This is a straight copy without sub-registers.
  438. NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
  439. }
  440. // The combined constraint may be impossible to satisfy.
  441. if (!NewRC)
  442. return false;
  443. // Prefer SrcReg to be a sub-register of DstReg.
  444. // FIXME: Coalescer should support subregs symmetrically.
  445. if (DstIdx && !SrcIdx) {
  446. std::swap(Src, Dst);
  447. std::swap(SrcIdx, DstIdx);
  448. Flipped = !Flipped;
  449. }
  450. CrossClass = NewRC != DstRC || NewRC != SrcRC;
  451. }
  452. // Check our invariants
  453. assert(Register::isVirtualRegister(Src) && "Src must be virtual");
  454. assert(!(Register::isPhysicalRegister(Dst) && DstSub) &&
  455. "Cannot have a physical SubIdx");
  456. SrcReg = Src;
  457. DstReg = Dst;
  458. return true;
  459. }
  460. bool CoalescerPair::flip() {
  461. if (Register::isPhysicalRegister(DstReg))
  462. return false;
  463. std::swap(SrcReg, DstReg);
  464. std::swap(SrcIdx, DstIdx);
  465. Flipped = !Flipped;
  466. return true;
  467. }
  468. bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
  469. if (!MI)
  470. return false;
  471. Register Src, Dst;
  472. unsigned SrcSub = 0, DstSub = 0;
  473. if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
  474. return false;
  475. // Find the virtual register that is SrcReg.
  476. if (Dst == SrcReg) {
  477. std::swap(Src, Dst);
  478. std::swap(SrcSub, DstSub);
  479. } else if (Src != SrcReg) {
  480. return false;
  481. }
  482. // Now check that Dst matches DstReg.
  483. if (DstReg.isPhysical()) {
  484. if (!Dst.isPhysical())
  485. return false;
  486. assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
  487. // DstSub could be set for a physreg from INSERT_SUBREG.
  488. if (DstSub)
  489. Dst = TRI.getSubReg(Dst, DstSub);
  490. // Full copy of Src.
  491. if (!SrcSub)
  492. return DstReg == Dst;
  493. // This is a partial register copy. Check that the parts match.
  494. return Register(TRI.getSubReg(DstReg, SrcSub)) == Dst;
  495. } else {
  496. // DstReg is virtual.
  497. if (DstReg != Dst)
  498. return false;
  499. // Registers match, do the subregisters line up?
  500. return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
  501. TRI.composeSubRegIndices(DstIdx, DstSub);
  502. }
  503. }
  504. void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
  505. AU.setPreservesCFG();
  506. AU.addRequired<AAResultsWrapperPass>();
  507. AU.addRequired<LiveIntervals>();
  508. AU.addPreserved<LiveIntervals>();
  509. AU.addPreserved<SlotIndexes>();
  510. AU.addRequired<MachineLoopInfo>();
  511. AU.addPreserved<MachineLoopInfo>();
  512. AU.addPreservedID(MachineDominatorsID);
  513. MachineFunctionPass::getAnalysisUsage(AU);
  514. }
  515. void RegisterCoalescer::eliminateDeadDefs() {
  516. SmallVector<Register, 8> NewRegs;
  517. LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
  518. nullptr, this).eliminateDeadDefs(DeadDefs);
  519. }
  520. bool RegisterCoalescer::allUsesAvailableAt(const MachineInstr *OrigMI,
  521. SlotIndex OrigIdx,
  522. SlotIndex UseIdx) {
  523. SmallVector<Register, 8> NewRegs;
  524. return LiveRangeEdit(nullptr, NewRegs, *MF, *LIS, nullptr, this)
  525. .allUsesAvailableAt(OrigMI, OrigIdx, UseIdx);
  526. }
  527. void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
  528. // MI may be in WorkList. Make sure we don't visit it.
  529. ErasedInstrs.insert(MI);
  530. }
  531. bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
  532. MachineInstr *CopyMI) {
  533. assert(!CP.isPartial() && "This doesn't work for partial copies.");
  534. assert(!CP.isPhys() && "This doesn't work for physreg copies.");
  535. LiveInterval &IntA =
  536. LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
  537. LiveInterval &IntB =
  538. LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
  539. SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
  540. // We have a non-trivially-coalescable copy with IntA being the source and
  541. // IntB being the dest, thus this defines a value number in IntB. If the
  542. // source value number (in IntA) is defined by a copy from B, see if we can
  543. // merge these two pieces of B into a single value number, eliminating a copy.
  544. // For example:
  545. //
  546. // A3 = B0
  547. // ...
  548. // B1 = A3 <- this copy
  549. //
  550. // In this case, B0 can be extended to where the B1 copy lives, allowing the
  551. // B1 value number to be replaced with B0 (which simplifies the B
  552. // liveinterval).
  553. // BValNo is a value number in B that is defined by a copy from A. 'B1' in
  554. // the example above.
  555. LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
  556. if (BS == IntB.end()) return false;
  557. VNInfo *BValNo = BS->valno;
  558. // Get the location that B is defined at. Two options: either this value has
  559. // an unknown definition point or it is defined at CopyIdx. If unknown, we
  560. // can't process it.
  561. if (BValNo->def != CopyIdx) return false;
  562. // AValNo is the value number in A that defines the copy, A3 in the example.
  563. SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
  564. LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
  565. // The live segment might not exist after fun with physreg coalescing.
  566. if (AS == IntA.end()) return false;
  567. VNInfo *AValNo = AS->valno;
  568. // If AValNo is defined as a copy from IntB, we can potentially process this.
  569. // Get the instruction that defines this value number.
  570. MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
  571. // Don't allow any partial copies, even if isCoalescable() allows them.
  572. if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
  573. return false;
  574. // Get the Segment in IntB that this value number starts with.
  575. LiveInterval::iterator ValS =
  576. IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
  577. if (ValS == IntB.end())
  578. return false;
  579. // Make sure that the end of the live segment is inside the same block as
  580. // CopyMI.
  581. MachineInstr *ValSEndInst =
  582. LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
  583. if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
  584. return false;
  585. // Okay, we now know that ValS ends in the same block that the CopyMI
  586. // live-range starts. If there are no intervening live segments between them
  587. // in IntB, we can merge them.
  588. if (ValS+1 != BS) return false;
  589. LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg(), TRI));
  590. SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
  591. // We are about to delete CopyMI, so need to remove it as the 'instruction
  592. // that defines this value #'. Update the valnum with the new defining
  593. // instruction #.
  594. BValNo->def = FillerStart;
  595. // Okay, we can merge them. We need to insert a new liverange:
  596. // [ValS.end, BS.begin) of either value number, then we merge the
  597. // two value numbers.
  598. IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
  599. // Okay, merge "B1" into the same value number as "B0".
  600. if (BValNo != ValS->valno)
  601. IntB.MergeValueNumberInto(BValNo, ValS->valno);
  602. // Do the same for the subregister segments.
  603. for (LiveInterval::SubRange &S : IntB.subranges()) {
  604. // Check for SubRange Segments of the form [1234r,1234d:0) which can be
  605. // removed to prevent creating bogus SubRange Segments.
  606. LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
  607. if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
  608. S.removeSegment(*SS, true);
  609. continue;
  610. }
  611. // The subrange may have ended before FillerStart. If so, extend it.
  612. if (!S.getVNInfoAt(FillerStart)) {
  613. SlotIndex BBStart =
  614. LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
  615. S.extendInBlock(BBStart, FillerStart);
  616. }
  617. VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
  618. S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
  619. VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
  620. if (SubBValNo != SubValSNo)
  621. S.MergeValueNumberInto(SubBValNo, SubValSNo);
  622. }
  623. LLVM_DEBUG(dbgs() << " result = " << IntB << '\n');
  624. // If the source instruction was killing the source register before the
  625. // merge, unset the isKill marker given the live range has been extended.
  626. int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg(), true);
  627. if (UIdx != -1) {
  628. ValSEndInst->getOperand(UIdx).setIsKill(false);
  629. }
  630. // Rewrite the copy.
  631. CopyMI->substituteRegister(IntA.reg(), IntB.reg(), 0, *TRI);
  632. // If the copy instruction was killing the destination register or any
  633. // subrange before the merge trim the live range.
  634. bool RecomputeLiveRange = AS->end == CopyIdx;
  635. if (!RecomputeLiveRange) {
  636. for (LiveInterval::SubRange &S : IntA.subranges()) {
  637. LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
  638. if (SS != S.end() && SS->end == CopyIdx) {
  639. RecomputeLiveRange = true;
  640. break;
  641. }
  642. }
  643. }
  644. if (RecomputeLiveRange)
  645. shrinkToUses(&IntA);
  646. ++numExtends;
  647. return true;
  648. }
  649. bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
  650. LiveInterval &IntB,
  651. VNInfo *AValNo,
  652. VNInfo *BValNo) {
  653. // If AValNo has PHI kills, conservatively assume that IntB defs can reach
  654. // the PHI values.
  655. if (LIS->hasPHIKill(IntA, AValNo))
  656. return true;
  657. for (LiveRange::Segment &ASeg : IntA.segments) {
  658. if (ASeg.valno != AValNo) continue;
  659. LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start);
  660. if (BI != IntB.begin())
  661. --BI;
  662. for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
  663. if (BI->valno == BValNo)
  664. continue;
  665. if (BI->start <= ASeg.start && BI->end > ASeg.start)
  666. return true;
  667. if (BI->start > ASeg.start && BI->start < ASeg.end)
  668. return true;
  669. }
  670. }
  671. return false;
  672. }
  673. /// Copy segments with value number @p SrcValNo from liverange @p Src to live
  674. /// range @Dst and use value number @p DstValNo there.
  675. static std::pair<bool,bool>
  676. addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src,
  677. const VNInfo *SrcValNo) {
  678. bool Changed = false;
  679. bool MergedWithDead = false;
  680. for (const LiveRange::Segment &S : Src.segments) {
  681. if (S.valno != SrcValNo)
  682. continue;
  683. // This is adding a segment from Src that ends in a copy that is about
  684. // to be removed. This segment is going to be merged with a pre-existing
  685. // segment in Dst. This works, except in cases when the corresponding
  686. // segment in Dst is dead. For example: adding [192r,208r:1) from Src
  687. // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
  688. // Recognized such cases, so that the segments can be shrunk.
  689. LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
  690. LiveRange::Segment &Merged = *Dst.addSegment(Added);
  691. if (Merged.end.isDead())
  692. MergedWithDead = true;
  693. Changed = true;
  694. }
  695. return std::make_pair(Changed, MergedWithDead);
  696. }
  697. std::pair<bool,bool>
  698. RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
  699. MachineInstr *CopyMI) {
  700. assert(!CP.isPhys());
  701. LiveInterval &IntA =
  702. LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
  703. LiveInterval &IntB =
  704. LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
  705. // We found a non-trivially-coalescable copy with IntA being the source and
  706. // IntB being the dest, thus this defines a value number in IntB. If the
  707. // source value number (in IntA) is defined by a commutable instruction and
  708. // its other operand is coalesced to the copy dest register, see if we can
  709. // transform the copy into a noop by commuting the definition. For example,
  710. //
  711. // A3 = op A2 killed B0
  712. // ...
  713. // B1 = A3 <- this copy
  714. // ...
  715. // = op A3 <- more uses
  716. //
  717. // ==>
  718. //
  719. // B2 = op B0 killed A2
  720. // ...
  721. // B1 = B2 <- now an identity copy
  722. // ...
  723. // = op B2 <- more uses
  724. // BValNo is a value number in B that is defined by a copy from A. 'B1' in
  725. // the example above.
  726. SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
  727. VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
  728. assert(BValNo != nullptr && BValNo->def == CopyIdx);
  729. // AValNo is the value number in A that defines the copy, A3 in the example.
  730. VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
  731. assert(AValNo && !AValNo->isUnused() && "COPY source not live");
  732. if (AValNo->isPHIDef())
  733. return { false, false };
  734. MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
  735. if (!DefMI)
  736. return { false, false };
  737. if (!DefMI->isCommutable())
  738. return { false, false };
  739. // If DefMI is a two-address instruction then commuting it will change the
  740. // destination register.
  741. int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg());
  742. assert(DefIdx != -1);
  743. unsigned UseOpIdx;
  744. if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
  745. return { false, false };
  746. // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
  747. // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
  748. // passed to the method. That _other_ operand is chosen by
  749. // the findCommutedOpIndices() method.
  750. //
  751. // That is obviously an area for improvement in case of instructions having
  752. // more than 2 operands. For example, if some instruction has 3 commutable
  753. // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
  754. // op#2<->op#3) of commute transformation should be considered/tried here.
  755. unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
  756. if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
  757. return { false, false };
  758. MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
  759. Register NewReg = NewDstMO.getReg();
  760. if (NewReg != IntB.reg() || !IntB.Query(AValNo->def).isKill())
  761. return { false, false };
  762. // Make sure there are no other definitions of IntB that would reach the
  763. // uses which the new definition can reach.
  764. if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
  765. return { false, false };
  766. // If some of the uses of IntA.reg is already coalesced away, return false.
  767. // It's not possible to determine whether it's safe to perform the coalescing.
  768. for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg())) {
  769. MachineInstr *UseMI = MO.getParent();
  770. unsigned OpNo = &MO - &UseMI->getOperand(0);
  771. SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
  772. LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
  773. if (US == IntA.end() || US->valno != AValNo)
  774. continue;
  775. // If this use is tied to a def, we can't rewrite the register.
  776. if (UseMI->isRegTiedToDefOperand(OpNo))
  777. return { false, false };
  778. }
  779. LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
  780. << *DefMI);
  781. // At this point we have decided that it is legal to do this
  782. // transformation. Start by commuting the instruction.
  783. MachineBasicBlock *MBB = DefMI->getParent();
  784. MachineInstr *NewMI =
  785. TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
  786. if (!NewMI)
  787. return { false, false };
  788. if (Register::isVirtualRegister(IntA.reg()) &&
  789. Register::isVirtualRegister(IntB.reg()) &&
  790. !MRI->constrainRegClass(IntB.reg(), MRI->getRegClass(IntA.reg())))
  791. return { false, false };
  792. if (NewMI != DefMI) {
  793. LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
  794. MachineBasicBlock::iterator Pos = DefMI;
  795. MBB->insert(Pos, NewMI);
  796. MBB->erase(DefMI);
  797. }
  798. // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
  799. // A = or A, B
  800. // ...
  801. // B = A
  802. // ...
  803. // C = killed A
  804. // ...
  805. // = B
  806. // Update uses of IntA of the specific Val# with IntB.
  807. for (MachineOperand &UseMO :
  808. llvm::make_early_inc_range(MRI->use_operands(IntA.reg()))) {
  809. if (UseMO.isUndef())
  810. continue;
  811. MachineInstr *UseMI = UseMO.getParent();
  812. if (UseMI->isDebugInstr()) {
  813. // FIXME These don't have an instruction index. Not clear we have enough
  814. // info to decide whether to do this replacement or not. For now do it.
  815. UseMO.setReg(NewReg);
  816. continue;
  817. }
  818. SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
  819. LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
  820. assert(US != IntA.end() && "Use must be live");
  821. if (US->valno != AValNo)
  822. continue;
  823. // Kill flags are no longer accurate. They are recomputed after RA.
  824. UseMO.setIsKill(false);
  825. if (Register::isPhysicalRegister(NewReg))
  826. UseMO.substPhysReg(NewReg, *TRI);
  827. else
  828. UseMO.setReg(NewReg);
  829. if (UseMI == CopyMI)
  830. continue;
  831. if (!UseMI->isCopy())
  832. continue;
  833. if (UseMI->getOperand(0).getReg() != IntB.reg() ||
  834. UseMI->getOperand(0).getSubReg())
  835. continue;
  836. // This copy will become a noop. If it's defining a new val#, merge it into
  837. // BValNo.
  838. SlotIndex DefIdx = UseIdx.getRegSlot();
  839. VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
  840. if (!DVNI)
  841. continue;
  842. LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
  843. assert(DVNI->def == DefIdx);
  844. BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
  845. for (LiveInterval::SubRange &S : IntB.subranges()) {
  846. VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
  847. if (!SubDVNI)
  848. continue;
  849. VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
  850. assert(SubBValNo->def == CopyIdx);
  851. S.MergeValueNumberInto(SubDVNI, SubBValNo);
  852. }
  853. deleteInstr(UseMI);
  854. }
  855. // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
  856. // is updated.
  857. bool ShrinkB = false;
  858. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  859. if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
  860. if (!IntA.hasSubRanges()) {
  861. LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg());
  862. IntA.createSubRangeFrom(Allocator, Mask, IntA);
  863. } else if (!IntB.hasSubRanges()) {
  864. LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg());
  865. IntB.createSubRangeFrom(Allocator, Mask, IntB);
  866. }
  867. SlotIndex AIdx = CopyIdx.getRegSlot(true);
  868. LaneBitmask MaskA;
  869. const SlotIndexes &Indexes = *LIS->getSlotIndexes();
  870. for (LiveInterval::SubRange &SA : IntA.subranges()) {
  871. VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
  872. // Even if we are dealing with a full copy, some lanes can
  873. // still be undefined.
  874. // E.g.,
  875. // undef A.subLow = ...
  876. // B = COPY A <== A.subHigh is undefined here and does
  877. // not have a value number.
  878. if (!ASubValNo)
  879. continue;
  880. MaskA |= SA.LaneMask;
  881. IntB.refineSubRanges(
  882. Allocator, SA.LaneMask,
  883. [&Allocator, &SA, CopyIdx, ASubValNo,
  884. &ShrinkB](LiveInterval::SubRange &SR) {
  885. VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
  886. : SR.getVNInfoAt(CopyIdx);
  887. assert(BSubValNo != nullptr);
  888. auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
  889. ShrinkB |= P.second;
  890. if (P.first)
  891. BSubValNo->def = ASubValNo->def;
  892. },
  893. Indexes, *TRI);
  894. }
  895. // Go over all subranges of IntB that have not been covered by IntA,
  896. // and delete the segments starting at CopyIdx. This can happen if
  897. // IntA has undef lanes that are defined in IntB.
  898. for (LiveInterval::SubRange &SB : IntB.subranges()) {
  899. if ((SB.LaneMask & MaskA).any())
  900. continue;
  901. if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
  902. if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
  903. SB.removeSegment(*S, true);
  904. }
  905. }
  906. BValNo->def = AValNo->def;
  907. auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
  908. ShrinkB |= P.second;
  909. LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
  910. LIS->removeVRegDefAt(IntA, AValNo->def);
  911. LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
  912. ++numCommutes;
  913. return { true, ShrinkB };
  914. }
  915. /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
  916. /// predecessor of BB2, and if B is not redefined on the way from A = B
  917. /// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
  918. /// execution goes through the path from BB0 to BB2. We may move B = A
  919. /// to the predecessor without such reversed copy.
  920. /// So we will transform the program from:
  921. /// BB0:
  922. /// A = B; BB1:
  923. /// ... ...
  924. /// / \ /
  925. /// BB2:
  926. /// ...
  927. /// B = A;
  928. ///
  929. /// to:
  930. ///
  931. /// BB0: BB1:
  932. /// A = B; ...
  933. /// ... B = A;
  934. /// / \ /
  935. /// BB2:
  936. /// ...
  937. ///
  938. /// A special case is when BB0 and BB2 are the same BB which is the only
  939. /// BB in a loop:
  940. /// BB1:
  941. /// ...
  942. /// BB0/BB2: ----
  943. /// B = A; |
  944. /// ... |
  945. /// A = B; |
  946. /// |-------
  947. /// |
  948. /// We may hoist B = A from BB0/BB2 to BB1.
  949. ///
  950. /// The major preconditions for correctness to remove such partial
  951. /// redundancy include:
  952. /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
  953. /// the PHI is defined by the reversed copy A = B in BB0.
  954. /// 2. No B is referenced from the start of BB2 to B = A.
  955. /// 3. No B is defined from A = B to the end of BB0.
  956. /// 4. BB1 has only one successor.
  957. ///
  958. /// 2 and 4 implicitly ensure B is not live at the end of BB1.
  959. /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
  960. /// colder place, which not only prevent endless loop, but also make sure
  961. /// the movement of copy is beneficial.
  962. bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
  963. MachineInstr &CopyMI) {
  964. assert(!CP.isPhys());
  965. if (!CopyMI.isFullCopy())
  966. return false;
  967. MachineBasicBlock &MBB = *CopyMI.getParent();
  968. // If this block is the target of an invoke/inlineasm_br, moving the copy into
  969. // the predecessor is tricker, and we don't handle it.
  970. if (MBB.isEHPad() || MBB.isInlineAsmBrIndirectTarget())
  971. return false;
  972. if (MBB.pred_size() != 2)
  973. return false;
  974. LiveInterval &IntA =
  975. LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
  976. LiveInterval &IntB =
  977. LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
  978. // A is defined by PHI at the entry of MBB.
  979. SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
  980. VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
  981. assert(AValNo && !AValNo->isUnused() && "COPY source not live");
  982. if (!AValNo->isPHIDef())
  983. return false;
  984. // No B is referenced before CopyMI in MBB.
  985. if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
  986. return false;
  987. // MBB has two predecessors: one contains A = B so no copy will be inserted
  988. // for it. The other one will have a copy moved from MBB.
  989. bool FoundReverseCopy = false;
  990. MachineBasicBlock *CopyLeftBB = nullptr;
  991. for (MachineBasicBlock *Pred : MBB.predecessors()) {
  992. VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
  993. MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
  994. if (!DefMI || !DefMI->isFullCopy()) {
  995. CopyLeftBB = Pred;
  996. continue;
  997. }
  998. // Check DefMI is a reverse copy and it is in BB Pred.
  999. if (DefMI->getOperand(0).getReg() != IntA.reg() ||
  1000. DefMI->getOperand(1).getReg() != IntB.reg() ||
  1001. DefMI->getParent() != Pred) {
  1002. CopyLeftBB = Pred;
  1003. continue;
  1004. }
  1005. // If there is any other def of B after DefMI and before the end of Pred,
  1006. // we need to keep the copy of B = A at the end of Pred if we remove
  1007. // B = A from MBB.
  1008. bool ValB_Changed = false;
  1009. for (auto VNI : IntB.valnos) {
  1010. if (VNI->isUnused())
  1011. continue;
  1012. if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
  1013. ValB_Changed = true;
  1014. break;
  1015. }
  1016. }
  1017. if (ValB_Changed) {
  1018. CopyLeftBB = Pred;
  1019. continue;
  1020. }
  1021. FoundReverseCopy = true;
  1022. }
  1023. // If no reverse copy is found in predecessors, nothing to do.
  1024. if (!FoundReverseCopy)
  1025. return false;
  1026. // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
  1027. // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
  1028. // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
  1029. // update IntA/IntB.
  1030. //
  1031. // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
  1032. // MBB is hotter than CopyLeftBB.
  1033. if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
  1034. return false;
  1035. // Now (almost sure it's) ok to move copy.
  1036. if (CopyLeftBB) {
  1037. // Position in CopyLeftBB where we should insert new copy.
  1038. auto InsPos = CopyLeftBB->getFirstTerminator();
  1039. // Make sure that B isn't referenced in the terminators (if any) at the end
  1040. // of the predecessor since we're about to insert a new definition of B
  1041. // before them.
  1042. if (InsPos != CopyLeftBB->end()) {
  1043. SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
  1044. if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
  1045. return false;
  1046. }
  1047. LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
  1048. << printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
  1049. // Insert new copy to CopyLeftBB.
  1050. MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
  1051. TII->get(TargetOpcode::COPY), IntB.reg())
  1052. .addReg(IntA.reg());
  1053. SlotIndex NewCopyIdx =
  1054. LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
  1055. IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
  1056. for (LiveInterval::SubRange &SR : IntB.subranges())
  1057. SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
  1058. // If the newly created Instruction has an address of an instruction that was
  1059. // deleted before (object recycled by the allocator) it needs to be removed from
  1060. // the deleted list.
  1061. ErasedInstrs.erase(NewCopyMI);
  1062. } else {
  1063. LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
  1064. << printMBBReference(MBB) << '\t' << CopyMI);
  1065. }
  1066. // Remove CopyMI.
  1067. // Note: This is fine to remove the copy before updating the live-ranges.
  1068. // While updating the live-ranges, we only look at slot indices and
  1069. // never go back to the instruction.
  1070. // Mark instructions as deleted.
  1071. deleteInstr(&CopyMI);
  1072. // Update the liveness.
  1073. SmallVector<SlotIndex, 8> EndPoints;
  1074. VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
  1075. LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
  1076. &EndPoints);
  1077. BValNo->markUnused();
  1078. // Extend IntB to the EndPoints of its original live interval.
  1079. LIS->extendToIndices(IntB, EndPoints);
  1080. // Now, do the same for its subranges.
  1081. for (LiveInterval::SubRange &SR : IntB.subranges()) {
  1082. EndPoints.clear();
  1083. VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
  1084. assert(BValNo && "All sublanes should be live");
  1085. LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
  1086. BValNo->markUnused();
  1087. // We can have a situation where the result of the original copy is live,
  1088. // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
  1089. // the copy appear as an endpoint from pruneValue(), but we don't want it
  1090. // to because the copy has been removed. We can go ahead and remove that
  1091. // endpoint; there is no other situation here that there could be a use at
  1092. // the same place as we know that the copy is a full copy.
  1093. for (unsigned I = 0; I != EndPoints.size(); ) {
  1094. if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
  1095. EndPoints[I] = EndPoints.back();
  1096. EndPoints.pop_back();
  1097. continue;
  1098. }
  1099. ++I;
  1100. }
  1101. SmallVector<SlotIndex, 8> Undefs;
  1102. IntB.computeSubRangeUndefs(Undefs, SR.LaneMask, *MRI,
  1103. *LIS->getSlotIndexes());
  1104. LIS->extendToIndices(SR, EndPoints, Undefs);
  1105. }
  1106. // If any dead defs were extended, truncate them.
  1107. shrinkToUses(&IntB);
  1108. // Finally, update the live-range of IntA.
  1109. shrinkToUses(&IntA);
  1110. return true;
  1111. }
  1112. /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
  1113. /// defining a subregister.
  1114. static bool definesFullReg(const MachineInstr &MI, Register Reg) {
  1115. assert(!Reg.isPhysical() && "This code cannot handle physreg aliasing");
  1116. for (const MachineOperand &Op : MI.operands()) {
  1117. if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
  1118. continue;
  1119. // Return true if we define the full register or don't care about the value
  1120. // inside other subregisters.
  1121. if (Op.getSubReg() == 0 || Op.isUndef())
  1122. return true;
  1123. }
  1124. return false;
  1125. }
  1126. bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
  1127. MachineInstr *CopyMI,
  1128. bool &IsDefCopy) {
  1129. IsDefCopy = false;
  1130. Register SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
  1131. unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
  1132. Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
  1133. unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
  1134. if (Register::isPhysicalRegister(SrcReg))
  1135. return false;
  1136. LiveInterval &SrcInt = LIS->getInterval(SrcReg);
  1137. SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
  1138. VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
  1139. if (!ValNo)
  1140. return false;
  1141. if (ValNo->isPHIDef() || ValNo->isUnused())
  1142. return false;
  1143. MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
  1144. if (!DefMI)
  1145. return false;
  1146. if (DefMI->isCopyLike()) {
  1147. IsDefCopy = true;
  1148. return false;
  1149. }
  1150. if (!TII->isAsCheapAsAMove(*DefMI))
  1151. return false;
  1152. if (!TII->isTriviallyReMaterializable(*DefMI, AA))
  1153. return false;
  1154. if (!definesFullReg(*DefMI, SrcReg))
  1155. return false;
  1156. bool SawStore = false;
  1157. if (!DefMI->isSafeToMove(AA, SawStore))
  1158. return false;
  1159. const MCInstrDesc &MCID = DefMI->getDesc();
  1160. if (MCID.getNumDefs() != 1)
  1161. return false;
  1162. // Only support subregister destinations when the def is read-undef.
  1163. MachineOperand &DstOperand = CopyMI->getOperand(0);
  1164. Register CopyDstReg = DstOperand.getReg();
  1165. if (DstOperand.getSubReg() && !DstOperand.isUndef())
  1166. return false;
  1167. // If both SrcIdx and DstIdx are set, correct rematerialization would widen
  1168. // the register substantially (beyond both source and dest size). This is bad
  1169. // for performance since it can cascade through a function, introducing many
  1170. // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
  1171. // around after a few subreg copies).
  1172. if (SrcIdx && DstIdx)
  1173. return false;
  1174. const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
  1175. if (!DefMI->isImplicitDef()) {
  1176. if (DstReg.isPhysical()) {
  1177. Register NewDstReg = DstReg;
  1178. unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
  1179. DefMI->getOperand(0).getSubReg());
  1180. if (NewDstIdx)
  1181. NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
  1182. // Finally, make sure that the physical subregister that will be
  1183. // constructed later is permitted for the instruction.
  1184. if (!DefRC->contains(NewDstReg))
  1185. return false;
  1186. } else {
  1187. // Theoretically, some stack frame reference could exist. Just make sure
  1188. // it hasn't actually happened.
  1189. assert(Register::isVirtualRegister(DstReg) &&
  1190. "Only expect to deal with virtual or physical registers");
  1191. }
  1192. }
  1193. if (!allUsesAvailableAt(DefMI, ValNo->def, CopyIdx))
  1194. return false;
  1195. DebugLoc DL = CopyMI->getDebugLoc();
  1196. MachineBasicBlock *MBB = CopyMI->getParent();
  1197. MachineBasicBlock::iterator MII =
  1198. std::next(MachineBasicBlock::iterator(CopyMI));
  1199. TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
  1200. MachineInstr &NewMI = *std::prev(MII);
  1201. NewMI.setDebugLoc(DL);
  1202. // In a situation like the following:
  1203. // %0:subreg = instr ; DefMI, subreg = DstIdx
  1204. // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0
  1205. // instead of widening %1 to the register class of %0 simply do:
  1206. // %1 = instr
  1207. const TargetRegisterClass *NewRC = CP.getNewRC();
  1208. if (DstIdx != 0) {
  1209. MachineOperand &DefMO = NewMI.getOperand(0);
  1210. if (DefMO.getSubReg() == DstIdx) {
  1211. assert(SrcIdx == 0 && CP.isFlipped()
  1212. && "Shouldn't have SrcIdx+DstIdx at this point");
  1213. const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
  1214. const TargetRegisterClass *CommonRC =
  1215. TRI->getCommonSubClass(DefRC, DstRC);
  1216. if (CommonRC != nullptr) {
  1217. NewRC = CommonRC;
  1218. DstIdx = 0;
  1219. DefMO.setSubReg(0);
  1220. DefMO.setIsUndef(false); // Only subregs can have def+undef.
  1221. }
  1222. }
  1223. }
  1224. // CopyMI may have implicit operands, save them so that we can transfer them
  1225. // over to the newly materialized instruction after CopyMI is removed.
  1226. SmallVector<MachineOperand, 4> ImplicitOps;
  1227. ImplicitOps.reserve(CopyMI->getNumOperands() -
  1228. CopyMI->getDesc().getNumOperands());
  1229. for (unsigned I = CopyMI->getDesc().getNumOperands(),
  1230. E = CopyMI->getNumOperands();
  1231. I != E; ++I) {
  1232. MachineOperand &MO = CopyMI->getOperand(I);
  1233. if (MO.isReg()) {
  1234. assert(MO.isImplicit() && "No explicit operands after implicit operands.");
  1235. // Discard VReg implicit defs.
  1236. if (Register::isPhysicalRegister(MO.getReg()))
  1237. ImplicitOps.push_back(MO);
  1238. }
  1239. }
  1240. LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI);
  1241. CopyMI->eraseFromParent();
  1242. ErasedInstrs.insert(CopyMI);
  1243. // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
  1244. // We need to remember these so we can add intervals once we insert
  1245. // NewMI into SlotIndexes.
  1246. SmallVector<MCRegister, 4> NewMIImplDefs;
  1247. for (unsigned i = NewMI.getDesc().getNumOperands(),
  1248. e = NewMI.getNumOperands();
  1249. i != e; ++i) {
  1250. MachineOperand &MO = NewMI.getOperand(i);
  1251. if (MO.isReg() && MO.isDef()) {
  1252. assert(MO.isImplicit() && MO.isDead() &&
  1253. Register::isPhysicalRegister(MO.getReg()));
  1254. NewMIImplDefs.push_back(MO.getReg().asMCReg());
  1255. }
  1256. }
  1257. if (DstReg.isVirtual()) {
  1258. unsigned NewIdx = NewMI.getOperand(0).getSubReg();
  1259. if (DefRC != nullptr) {
  1260. if (NewIdx)
  1261. NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
  1262. else
  1263. NewRC = TRI->getCommonSubClass(NewRC, DefRC);
  1264. assert(NewRC && "subreg chosen for remat incompatible with instruction");
  1265. }
  1266. // Remap subranges to new lanemask and change register class.
  1267. LiveInterval &DstInt = LIS->getInterval(DstReg);
  1268. for (LiveInterval::SubRange &SR : DstInt.subranges()) {
  1269. SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
  1270. }
  1271. MRI->setRegClass(DstReg, NewRC);
  1272. // Update machine operands and add flags.
  1273. updateRegDefsUses(DstReg, DstReg, DstIdx);
  1274. NewMI.getOperand(0).setSubReg(NewIdx);
  1275. // updateRegDefUses can add an "undef" flag to the definition, since
  1276. // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
  1277. // sure that "undef" is not set.
  1278. if (NewIdx == 0)
  1279. NewMI.getOperand(0).setIsUndef(false);
  1280. // Add dead subregister definitions if we are defining the whole register
  1281. // but only part of it is live.
  1282. // This could happen if the rematerialization instruction is rematerializing
  1283. // more than actually is used in the register.
  1284. // An example would be:
  1285. // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
  1286. // ; Copying only part of the register here, but the rest is undef.
  1287. // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
  1288. // ==>
  1289. // ; Materialize all the constants but only using one
  1290. // %2 = LOAD_CONSTANTS 5, 8
  1291. //
  1292. // at this point for the part that wasn't defined before we could have
  1293. // subranges missing the definition.
  1294. if (NewIdx == 0 && DstInt.hasSubRanges()) {
  1295. SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
  1296. SlotIndex DefIndex =
  1297. CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
  1298. LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
  1299. VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
  1300. for (LiveInterval::SubRange &SR : DstInt.subranges()) {
  1301. if (!SR.liveAt(DefIndex))
  1302. SR.createDeadDef(DefIndex, Alloc);
  1303. MaxMask &= ~SR.LaneMask;
  1304. }
  1305. if (MaxMask.any()) {
  1306. LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
  1307. SR->createDeadDef(DefIndex, Alloc);
  1308. }
  1309. }
  1310. // Make sure that the subrange for resultant undef is removed
  1311. // For example:
  1312. // %1:sub1<def,read-undef> = LOAD CONSTANT 1
  1313. // %2 = COPY %1
  1314. // ==>
  1315. // %2:sub1<def, read-undef> = LOAD CONSTANT 1
  1316. // ; Correct but need to remove the subrange for %2:sub0
  1317. // ; as it is now undef
  1318. if (NewIdx != 0 && DstInt.hasSubRanges()) {
  1319. // The affected subregister segments can be removed.
  1320. SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
  1321. LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
  1322. bool UpdatedSubRanges = false;
  1323. SlotIndex DefIndex =
  1324. CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
  1325. VNInfo::Allocator &Alloc = LIS->getVNInfoAllocator();
  1326. for (LiveInterval::SubRange &SR : DstInt.subranges()) {
  1327. if ((SR.LaneMask & DstMask).none()) {
  1328. LLVM_DEBUG(dbgs()
  1329. << "Removing undefined SubRange "
  1330. << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
  1331. // VNI is in ValNo - remove any segments in this SubRange that have this ValNo
  1332. if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
  1333. SR.removeValNo(RmValNo);
  1334. UpdatedSubRanges = true;
  1335. }
  1336. } else {
  1337. // We know that this lane is defined by this instruction,
  1338. // but at this point it may be empty because it is not used by
  1339. // anything. This happens when updateRegDefUses adds the missing
  1340. // lanes. Assign that lane a dead def so that the interferences
  1341. // are properly modeled.
  1342. if (SR.empty())
  1343. SR.createDeadDef(DefIndex, Alloc);
  1344. }
  1345. }
  1346. if (UpdatedSubRanges)
  1347. DstInt.removeEmptySubRanges();
  1348. }
  1349. } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
  1350. // The New instruction may be defining a sub-register of what's actually
  1351. // been asked for. If so it must implicitly define the whole thing.
  1352. assert(Register::isPhysicalRegister(DstReg) &&
  1353. "Only expect virtual or physical registers in remat");
  1354. NewMI.getOperand(0).setIsDead(true);
  1355. NewMI.addOperand(MachineOperand::CreateReg(
  1356. CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
  1357. // Record small dead def live-ranges for all the subregisters
  1358. // of the destination register.
  1359. // Otherwise, variables that live through may miss some
  1360. // interferences, thus creating invalid allocation.
  1361. // E.g., i386 code:
  1362. // %1 = somedef ; %1 GR8
  1363. // %2 = remat ; %2 GR32
  1364. // CL = COPY %2.sub_8bit
  1365. // = somedef %1 ; %1 GR8
  1366. // =>
  1367. // %1 = somedef ; %1 GR8
  1368. // dead ECX = remat ; implicit-def CL
  1369. // = somedef %1 ; %1 GR8
  1370. // %1 will see the interferences with CL but not with CH since
  1371. // no live-ranges would have been created for ECX.
  1372. // Fix that!
  1373. SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
  1374. for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI);
  1375. Units.isValid(); ++Units)
  1376. if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
  1377. LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
  1378. }
  1379. if (NewMI.getOperand(0).getSubReg())
  1380. NewMI.getOperand(0).setIsUndef();
  1381. // Transfer over implicit operands to the rematerialized instruction.
  1382. for (MachineOperand &MO : ImplicitOps)
  1383. NewMI.addOperand(MO);
  1384. SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
  1385. for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
  1386. MCRegister Reg = NewMIImplDefs[i];
  1387. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1388. if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
  1389. LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
  1390. }
  1391. LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
  1392. ++NumReMats;
  1393. // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
  1394. // to describe DstReg instead.
  1395. if (MRI->use_nodbg_empty(SrcReg)) {
  1396. for (MachineOperand &UseMO :
  1397. llvm::make_early_inc_range(MRI->use_operands(SrcReg))) {
  1398. MachineInstr *UseMI = UseMO.getParent();
  1399. if (UseMI->isDebugInstr()) {
  1400. if (Register::isPhysicalRegister(DstReg))
  1401. UseMO.substPhysReg(DstReg, *TRI);
  1402. else
  1403. UseMO.setReg(DstReg);
  1404. // Move the debug value directly after the def of the rematerialized
  1405. // value in DstReg.
  1406. MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
  1407. LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
  1408. }
  1409. }
  1410. }
  1411. if (ToBeUpdated.count(SrcReg))
  1412. return true;
  1413. unsigned NumCopyUses = 0;
  1414. for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
  1415. if (UseMO.getParent()->isCopyLike())
  1416. NumCopyUses++;
  1417. }
  1418. if (NumCopyUses < LateRematUpdateThreshold) {
  1419. // The source interval can become smaller because we removed a use.
  1420. shrinkToUses(&SrcInt, &DeadDefs);
  1421. if (!DeadDefs.empty())
  1422. eliminateDeadDefs();
  1423. } else {
  1424. ToBeUpdated.insert(SrcReg);
  1425. }
  1426. return true;
  1427. }
  1428. MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
  1429. // ProcessImplicitDefs may leave some copies of <undef> values, it only
  1430. // removes local variables. When we have a copy like:
  1431. //
  1432. // %1 = COPY undef %2
  1433. //
  1434. // We delete the copy and remove the corresponding value number from %1.
  1435. // Any uses of that value number are marked as <undef>.
  1436. // Note that we do not query CoalescerPair here but redo isMoveInstr as the
  1437. // CoalescerPair may have a new register class with adjusted subreg indices
  1438. // at this point.
  1439. Register SrcReg, DstReg;
  1440. unsigned SrcSubIdx = 0, DstSubIdx = 0;
  1441. if(!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
  1442. return nullptr;
  1443. SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
  1444. const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
  1445. // CopyMI is undef iff SrcReg is not live before the instruction.
  1446. if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
  1447. LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
  1448. for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
  1449. if ((SR.LaneMask & SrcMask).none())
  1450. continue;
  1451. if (SR.liveAt(Idx))
  1452. return nullptr;
  1453. }
  1454. } else if (SrcLI.liveAt(Idx))
  1455. return nullptr;
  1456. // If the undef copy defines a live-out value (i.e. an input to a PHI def),
  1457. // then replace it with an IMPLICIT_DEF.
  1458. LiveInterval &DstLI = LIS->getInterval(DstReg);
  1459. SlotIndex RegIndex = Idx.getRegSlot();
  1460. LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
  1461. assert(Seg != nullptr && "No segment for defining instruction");
  1462. if (VNInfo *V = DstLI.getVNInfoAt(Seg->end)) {
  1463. if (V->isPHIDef()) {
  1464. CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
  1465. for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
  1466. MachineOperand &MO = CopyMI->getOperand(i-1);
  1467. if (MO.isReg() && MO.isUse())
  1468. CopyMI->RemoveOperand(i-1);
  1469. }
  1470. LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
  1471. "implicit def\n");
  1472. return CopyMI;
  1473. }
  1474. }
  1475. // Remove any DstReg segments starting at the instruction.
  1476. LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
  1477. // Remove value or merge with previous one in case of a subregister def.
  1478. if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
  1479. VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
  1480. DstLI.MergeValueNumberInto(VNI, PrevVNI);
  1481. // The affected subregister segments can be removed.
  1482. LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
  1483. for (LiveInterval::SubRange &SR : DstLI.subranges()) {
  1484. if ((SR.LaneMask & DstMask).none())
  1485. continue;
  1486. VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
  1487. assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
  1488. SR.removeValNo(SVNI);
  1489. }
  1490. DstLI.removeEmptySubRanges();
  1491. } else
  1492. LIS->removeVRegDefAt(DstLI, RegIndex);
  1493. // Mark uses as undef.
  1494. for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
  1495. if (MO.isDef() /*|| MO.isUndef()*/)
  1496. continue;
  1497. const MachineInstr &MI = *MO.getParent();
  1498. SlotIndex UseIdx = LIS->getInstructionIndex(MI);
  1499. LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
  1500. bool isLive;
  1501. if (!UseMask.all() && DstLI.hasSubRanges()) {
  1502. isLive = false;
  1503. for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
  1504. if ((SR.LaneMask & UseMask).none())
  1505. continue;
  1506. if (SR.liveAt(UseIdx)) {
  1507. isLive = true;
  1508. break;
  1509. }
  1510. }
  1511. } else
  1512. isLive = DstLI.liveAt(UseIdx);
  1513. if (isLive)
  1514. continue;
  1515. MO.setIsUndef(true);
  1516. LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
  1517. }
  1518. // A def of a subregister may be a use of the other subregisters, so
  1519. // deleting a def of a subregister may also remove uses. Since CopyMI
  1520. // is still part of the function (but about to be erased), mark all
  1521. // defs of DstReg in it as <undef>, so that shrinkToUses would
  1522. // ignore them.
  1523. for (MachineOperand &MO : CopyMI->operands())
  1524. if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
  1525. MO.setIsUndef(true);
  1526. LIS->shrinkToUses(&DstLI);
  1527. return CopyMI;
  1528. }
  1529. void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
  1530. MachineOperand &MO, unsigned SubRegIdx) {
  1531. LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
  1532. if (MO.isDef())
  1533. Mask = ~Mask;
  1534. bool IsUndef = true;
  1535. for (const LiveInterval::SubRange &S : Int.subranges()) {
  1536. if ((S.LaneMask & Mask).none())
  1537. continue;
  1538. if (S.liveAt(UseIdx)) {
  1539. IsUndef = false;
  1540. break;
  1541. }
  1542. }
  1543. if (IsUndef) {
  1544. MO.setIsUndef(true);
  1545. // We found out some subregister use is actually reading an undefined
  1546. // value. In some cases the whole vreg has become undefined at this
  1547. // point so we have to potentially shrink the main range if the
  1548. // use was ending a live segment there.
  1549. LiveQueryResult Q = Int.Query(UseIdx);
  1550. if (Q.valueOut() == nullptr)
  1551. ShrinkMainRange = true;
  1552. }
  1553. }
  1554. void RegisterCoalescer::updateRegDefsUses(Register SrcReg, Register DstReg,
  1555. unsigned SubIdx) {
  1556. bool DstIsPhys = Register::isPhysicalRegister(DstReg);
  1557. LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
  1558. if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
  1559. for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
  1560. unsigned SubReg = MO.getSubReg();
  1561. if (SubReg == 0 || MO.isUndef())
  1562. continue;
  1563. MachineInstr &MI = *MO.getParent();
  1564. if (MI.isDebugInstr())
  1565. continue;
  1566. SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
  1567. addUndefFlag(*DstInt, UseIdx, MO, SubReg);
  1568. }
  1569. }
  1570. SmallPtrSet<MachineInstr*, 8> Visited;
  1571. for (MachineRegisterInfo::reg_instr_iterator
  1572. I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
  1573. I != E; ) {
  1574. MachineInstr *UseMI = &*(I++);
  1575. // Each instruction can only be rewritten once because sub-register
  1576. // composition is not always idempotent. When SrcReg != DstReg, rewriting
  1577. // the UseMI operands removes them from the SrcReg use-def chain, but when
  1578. // SrcReg is DstReg we could encounter UseMI twice if it has multiple
  1579. // operands mentioning the virtual register.
  1580. if (SrcReg == DstReg && !Visited.insert(UseMI).second)
  1581. continue;
  1582. SmallVector<unsigned,8> Ops;
  1583. bool Reads, Writes;
  1584. std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
  1585. // If SrcReg wasn't read, it may still be the case that DstReg is live-in
  1586. // because SrcReg is a sub-register.
  1587. if (DstInt && !Reads && SubIdx && !UseMI->isDebugInstr())
  1588. Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
  1589. // Replace SrcReg with DstReg in all UseMI operands.
  1590. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  1591. MachineOperand &MO = UseMI->getOperand(Ops[i]);
  1592. // Adjust <undef> flags in case of sub-register joins. We don't want to
  1593. // turn a full def into a read-modify-write sub-register def and vice
  1594. // versa.
  1595. if (SubIdx && MO.isDef())
  1596. MO.setIsUndef(!Reads);
  1597. // A subreg use of a partially undef (super) register may be a complete
  1598. // undef use now and then has to be marked that way.
  1599. if (MO.isUse() && !DstIsPhys) {
  1600. unsigned SubUseIdx = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
  1601. if (SubUseIdx != 0 && MRI->shouldTrackSubRegLiveness(DstReg)) {
  1602. if (!DstInt->hasSubRanges()) {
  1603. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  1604. LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg());
  1605. LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
  1606. LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
  1607. DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
  1608. // The unused lanes are just empty live-ranges at this point.
  1609. // It is the caller responsibility to set the proper
  1610. // dead segments if there is an actual dead def of the
  1611. // unused lanes. This may happen with rematerialization.
  1612. DstInt->createSubRange(Allocator, UnusedLanes);
  1613. }
  1614. SlotIndex MIIdx = UseMI->isDebugInstr()
  1615. ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
  1616. : LIS->getInstructionIndex(*UseMI);
  1617. SlotIndex UseIdx = MIIdx.getRegSlot(true);
  1618. addUndefFlag(*DstInt, UseIdx, MO, SubUseIdx);
  1619. }
  1620. }
  1621. if (DstIsPhys)
  1622. MO.substPhysReg(DstReg, *TRI);
  1623. else
  1624. MO.substVirtReg(DstReg, SubIdx, *TRI);
  1625. }
  1626. LLVM_DEBUG({
  1627. dbgs() << "\t\tupdated: ";
  1628. if (!UseMI->isDebugInstr())
  1629. dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
  1630. dbgs() << *UseMI;
  1631. });
  1632. }
  1633. }
  1634. bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
  1635. // Always join simple intervals that are defined by a single copy from a
  1636. // reserved register. This doesn't increase register pressure, so it is
  1637. // always beneficial.
  1638. if (!MRI->isReserved(CP.getDstReg())) {
  1639. LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
  1640. return false;
  1641. }
  1642. LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
  1643. if (JoinVInt.containsOneValue())
  1644. return true;
  1645. LLVM_DEBUG(
  1646. dbgs() << "\tCannot join complex intervals into reserved register.\n");
  1647. return false;
  1648. }
  1649. bool RegisterCoalescer::copyValueUndefInPredecessors(
  1650. LiveRange &S, const MachineBasicBlock *MBB, LiveQueryResult SLRQ) {
  1651. for (const MachineBasicBlock *Pred : MBB->predecessors()) {
  1652. SlotIndex PredEnd = LIS->getMBBEndIdx(Pred);
  1653. if (VNInfo *V = S.getVNInfoAt(PredEnd.getPrevSlot())) {
  1654. // If this is a self loop, we may be reading the same value.
  1655. if (V->id != SLRQ.valueOutOrDead()->id)
  1656. return false;
  1657. }
  1658. }
  1659. return true;
  1660. }
  1661. void RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
  1662. Register Reg,
  1663. LaneBitmask PrunedLanes) {
  1664. // If we had other instructions in the segment reading the undef sublane
  1665. // value, we need to mark them with undef.
  1666. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  1667. unsigned SubRegIdx = MO.getSubReg();
  1668. if (SubRegIdx == 0 || MO.isUndef())
  1669. continue;
  1670. LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
  1671. SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
  1672. for (LiveInterval::SubRange &S : LI.subranges()) {
  1673. if (!S.liveAt(Pos) && (PrunedLanes & SubRegMask).any()) {
  1674. MO.setIsUndef();
  1675. break;
  1676. }
  1677. }
  1678. }
  1679. LI.removeEmptySubRanges();
  1680. // A def of a subregister may be a use of other register lanes. Replacing
  1681. // such a def with a def of a different register will eliminate the use,
  1682. // and may cause the recorded live range to be larger than the actual
  1683. // liveness in the program IR.
  1684. LIS->shrinkToUses(&LI);
  1685. }
  1686. bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
  1687. Again = false;
  1688. LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
  1689. CoalescerPair CP(*TRI);
  1690. if (!CP.setRegisters(CopyMI)) {
  1691. LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
  1692. return false;
  1693. }
  1694. if (CP.getNewRC()) {
  1695. auto SrcRC = MRI->getRegClass(CP.getSrcReg());
  1696. auto DstRC = MRI->getRegClass(CP.getDstReg());
  1697. unsigned SrcIdx = CP.getSrcIdx();
  1698. unsigned DstIdx = CP.getDstIdx();
  1699. if (CP.isFlipped()) {
  1700. std::swap(SrcIdx, DstIdx);
  1701. std::swap(SrcRC, DstRC);
  1702. }
  1703. if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
  1704. CP.getNewRC(), *LIS)) {
  1705. LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
  1706. return false;
  1707. }
  1708. }
  1709. // Dead code elimination. This really should be handled by MachineDCE, but
  1710. // sometimes dead copies slip through, and we can't generate invalid live
  1711. // ranges.
  1712. if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
  1713. LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
  1714. DeadDefs.push_back(CopyMI);
  1715. eliminateDeadDefs();
  1716. return true;
  1717. }
  1718. // Eliminate undefs.
  1719. if (!CP.isPhys()) {
  1720. // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
  1721. if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
  1722. if (UndefMI->isImplicitDef())
  1723. return false;
  1724. deleteInstr(CopyMI);
  1725. return false; // Not coalescable.
  1726. }
  1727. }
  1728. // Coalesced copies are normally removed immediately, but transformations
  1729. // like removeCopyByCommutingDef() can inadvertently create identity copies.
  1730. // When that happens, just join the values and remove the copy.
  1731. if (CP.getSrcReg() == CP.getDstReg()) {
  1732. LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
  1733. LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
  1734. const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
  1735. LiveQueryResult LRQ = LI.Query(CopyIdx);
  1736. if (VNInfo *DefVNI = LRQ.valueDefined()) {
  1737. VNInfo *ReadVNI = LRQ.valueIn();
  1738. assert(ReadVNI && "No value before copy and no <undef> flag.");
  1739. assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
  1740. // Track incoming undef lanes we need to eliminate from the subrange.
  1741. LaneBitmask PrunedLanes;
  1742. MachineBasicBlock *MBB = CopyMI->getParent();
  1743. // Process subregister liveranges.
  1744. for (LiveInterval::SubRange &S : LI.subranges()) {
  1745. LiveQueryResult SLRQ = S.Query(CopyIdx);
  1746. if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
  1747. if (VNInfo *SReadVNI = SLRQ.valueIn())
  1748. SDefVNI = S.MergeValueNumberInto(SDefVNI, SReadVNI);
  1749. // If this copy introduced an undef subrange from an incoming value,
  1750. // we need to eliminate the undef live in values from the subrange.
  1751. if (copyValueUndefInPredecessors(S, MBB, SLRQ)) {
  1752. LLVM_DEBUG(dbgs() << "Incoming sublane value is undef at copy\n");
  1753. PrunedLanes |= S.LaneMask;
  1754. S.removeValNo(SDefVNI);
  1755. }
  1756. }
  1757. }
  1758. LI.MergeValueNumberInto(DefVNI, ReadVNI);
  1759. if (PrunedLanes.any()) {
  1760. LLVM_DEBUG(dbgs() << "Pruning undef incoming lanes: "
  1761. << PrunedLanes << '\n');
  1762. setUndefOnPrunedSubRegUses(LI, CP.getSrcReg(), PrunedLanes);
  1763. }
  1764. LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
  1765. }
  1766. deleteInstr(CopyMI);
  1767. return true;
  1768. }
  1769. // Enforce policies.
  1770. if (CP.isPhys()) {
  1771. LLVM_DEBUG(dbgs() << "\tConsidering merging "
  1772. << printReg(CP.getSrcReg(), TRI) << " with "
  1773. << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
  1774. if (!canJoinPhys(CP)) {
  1775. // Before giving up coalescing, if definition of source is defined by
  1776. // trivial computation, try rematerializing it.
  1777. bool IsDefCopy = false;
  1778. if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
  1779. return true;
  1780. if (IsDefCopy)
  1781. Again = true; // May be possible to coalesce later.
  1782. return false;
  1783. }
  1784. } else {
  1785. // When possible, let DstReg be the larger interval.
  1786. if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
  1787. LIS->getInterval(CP.getDstReg()).size())
  1788. CP.flip();
  1789. LLVM_DEBUG({
  1790. dbgs() << "\tConsidering merging to "
  1791. << TRI->getRegClassName(CP.getNewRC()) << " with ";
  1792. if (CP.getDstIdx() && CP.getSrcIdx())
  1793. dbgs() << printReg(CP.getDstReg()) << " in "
  1794. << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
  1795. << printReg(CP.getSrcReg()) << " in "
  1796. << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
  1797. else
  1798. dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
  1799. << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
  1800. });
  1801. }
  1802. ShrinkMask = LaneBitmask::getNone();
  1803. ShrinkMainRange = false;
  1804. // Okay, attempt to join these two intervals. On failure, this returns false.
  1805. // Otherwise, if one of the intervals being joined is a physreg, this method
  1806. // always canonicalizes DstInt to be it. The output "SrcInt" will not have
  1807. // been modified, so we can use this information below to update aliases.
  1808. if (!joinIntervals(CP)) {
  1809. // Coalescing failed.
  1810. // If definition of source is defined by trivial computation, try
  1811. // rematerializing it.
  1812. bool IsDefCopy = false;
  1813. if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
  1814. return true;
  1815. // If we can eliminate the copy without merging the live segments, do so
  1816. // now.
  1817. if (!CP.isPartial() && !CP.isPhys()) {
  1818. bool Changed = adjustCopiesBackFrom(CP, CopyMI);
  1819. bool Shrink = false;
  1820. if (!Changed)
  1821. std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
  1822. if (Changed) {
  1823. deleteInstr(CopyMI);
  1824. if (Shrink) {
  1825. Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
  1826. LiveInterval &DstLI = LIS->getInterval(DstReg);
  1827. shrinkToUses(&DstLI);
  1828. LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n');
  1829. }
  1830. LLVM_DEBUG(dbgs() << "\tTrivial!\n");
  1831. return true;
  1832. }
  1833. }
  1834. // Try and see if we can partially eliminate the copy by moving the copy to
  1835. // its predecessor.
  1836. if (!CP.isPartial() && !CP.isPhys())
  1837. if (removePartialRedundancy(CP, *CopyMI))
  1838. return true;
  1839. // Otherwise, we are unable to join the intervals.
  1840. LLVM_DEBUG(dbgs() << "\tInterference!\n");
  1841. Again = true; // May be possible to coalesce later.
  1842. return false;
  1843. }
  1844. // Coalescing to a virtual register that is of a sub-register class of the
  1845. // other. Make sure the resulting register is set to the right register class.
  1846. if (CP.isCrossClass()) {
  1847. ++numCrossRCs;
  1848. MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
  1849. }
  1850. // Removing sub-register copies can ease the register class constraints.
  1851. // Make sure we attempt to inflate the register class of DstReg.
  1852. if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
  1853. InflateRegs.push_back(CP.getDstReg());
  1854. // CopyMI has been erased by joinIntervals at this point. Remove it from
  1855. // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
  1856. // to the work list. This keeps ErasedInstrs from growing needlessly.
  1857. ErasedInstrs.erase(CopyMI);
  1858. // Rewrite all SrcReg operands to DstReg.
  1859. // Also update DstReg operands to include DstIdx if it is set.
  1860. if (CP.getDstIdx())
  1861. updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
  1862. updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
  1863. // Shrink subregister ranges if necessary.
  1864. if (ShrinkMask.any()) {
  1865. LiveInterval &LI = LIS->getInterval(CP.getDstReg());
  1866. for (LiveInterval::SubRange &S : LI.subranges()) {
  1867. if ((S.LaneMask & ShrinkMask).none())
  1868. continue;
  1869. LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
  1870. << ")\n");
  1871. LIS->shrinkToUses(S, LI.reg());
  1872. }
  1873. LI.removeEmptySubRanges();
  1874. }
  1875. // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
  1876. // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
  1877. // is not up-to-date, need to update the merged live interval here.
  1878. if (ToBeUpdated.count(CP.getSrcReg()))
  1879. ShrinkMainRange = true;
  1880. if (ShrinkMainRange) {
  1881. LiveInterval &LI = LIS->getInterval(CP.getDstReg());
  1882. shrinkToUses(&LI);
  1883. }
  1884. // SrcReg is guaranteed to be the register whose live interval that is
  1885. // being merged.
  1886. LIS->removeInterval(CP.getSrcReg());
  1887. // Update regalloc hint.
  1888. TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
  1889. LLVM_DEBUG({
  1890. dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
  1891. << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
  1892. dbgs() << "\tResult = ";
  1893. if (CP.isPhys())
  1894. dbgs() << printReg(CP.getDstReg(), TRI);
  1895. else
  1896. dbgs() << LIS->getInterval(CP.getDstReg());
  1897. dbgs() << '\n';
  1898. });
  1899. ++numJoins;
  1900. return true;
  1901. }
  1902. bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
  1903. Register DstReg = CP.getDstReg();
  1904. Register SrcReg = CP.getSrcReg();
  1905. assert(CP.isPhys() && "Must be a physreg copy");
  1906. assert(MRI->isReserved(DstReg) && "Not a reserved register");
  1907. LiveInterval &RHS = LIS->getInterval(SrcReg);
  1908. LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
  1909. assert(RHS.containsOneValue() && "Invalid join with reserved register");
  1910. // Optimization for reserved registers like ESP. We can only merge with a
  1911. // reserved physreg if RHS has a single value that is a copy of DstReg.
  1912. // The live range of the reserved register will look like a set of dead defs
  1913. // - we don't properly track the live range of reserved registers.
  1914. // Deny any overlapping intervals. This depends on all the reserved
  1915. // register live ranges to look like dead defs.
  1916. if (!MRI->isConstantPhysReg(DstReg)) {
  1917. for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
  1918. // Abort if not all the regunits are reserved.
  1919. for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) {
  1920. if (!MRI->isReserved(*RI))
  1921. return false;
  1922. }
  1923. if (RHS.overlaps(LIS->getRegUnit(*UI))) {
  1924. LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI)
  1925. << '\n');
  1926. return false;
  1927. }
  1928. }
  1929. // We must also check for overlaps with regmask clobbers.
  1930. BitVector RegMaskUsable;
  1931. if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
  1932. !RegMaskUsable.test(DstReg)) {
  1933. LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
  1934. return false;
  1935. }
  1936. }
  1937. // Skip any value computations, we are not adding new values to the
  1938. // reserved register. Also skip merging the live ranges, the reserved
  1939. // register live range doesn't need to be accurate as long as all the
  1940. // defs are there.
  1941. // Delete the identity copy.
  1942. MachineInstr *CopyMI;
  1943. if (CP.isFlipped()) {
  1944. // Physreg is copied into vreg
  1945. // %y = COPY %physreg_x
  1946. // ... //< no other def of %physreg_x here
  1947. // use %y
  1948. // =>
  1949. // ...
  1950. // use %physreg_x
  1951. CopyMI = MRI->getVRegDef(SrcReg);
  1952. } else {
  1953. // VReg is copied into physreg:
  1954. // %y = def
  1955. // ... //< no other def or use of %physreg_x here
  1956. // %physreg_x = COPY %y
  1957. // =>
  1958. // %physreg_x = def
  1959. // ...
  1960. if (!MRI->hasOneNonDBGUse(SrcReg)) {
  1961. LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
  1962. return false;
  1963. }
  1964. if (!LIS->intervalIsInOneMBB(RHS)) {
  1965. LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
  1966. return false;
  1967. }
  1968. MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
  1969. CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
  1970. SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
  1971. SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
  1972. if (!MRI->isConstantPhysReg(DstReg)) {
  1973. // We checked above that there are no interfering defs of the physical
  1974. // register. However, for this case, where we intend to move up the def of
  1975. // the physical register, we also need to check for interfering uses.
  1976. SlotIndexes *Indexes = LIS->getSlotIndexes();
  1977. for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
  1978. SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
  1979. MachineInstr *MI = LIS->getInstructionFromIndex(SI);
  1980. if (MI->readsRegister(DstReg, TRI)) {
  1981. LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
  1982. return false;
  1983. }
  1984. }
  1985. }
  1986. // We're going to remove the copy which defines a physical reserved
  1987. // register, so remove its valno, etc.
  1988. LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
  1989. << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
  1990. LIS->removePhysRegDefAt(DstReg.asMCReg(), CopyRegIdx);
  1991. // Create a new dead def at the new def location.
  1992. for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
  1993. LiveRange &LR = LIS->getRegUnit(*UI);
  1994. LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
  1995. }
  1996. }
  1997. deleteInstr(CopyMI);
  1998. // We don't track kills for reserved registers.
  1999. MRI->clearKillFlags(CP.getSrcReg());
  2000. return true;
  2001. }
  2002. //===----------------------------------------------------------------------===//
  2003. // Interference checking and interval joining
  2004. //===----------------------------------------------------------------------===//
  2005. //
  2006. // In the easiest case, the two live ranges being joined are disjoint, and
  2007. // there is no interference to consider. It is quite common, though, to have
  2008. // overlapping live ranges, and we need to check if the interference can be
  2009. // resolved.
  2010. //
  2011. // The live range of a single SSA value forms a sub-tree of the dominator tree.
  2012. // This means that two SSA values overlap if and only if the def of one value
  2013. // is contained in the live range of the other value. As a special case, the
  2014. // overlapping values can be defined at the same index.
  2015. //
  2016. // The interference from an overlapping def can be resolved in these cases:
  2017. //
  2018. // 1. Coalescable copies. The value is defined by a copy that would become an
  2019. // identity copy after joining SrcReg and DstReg. The copy instruction will
  2020. // be removed, and the value will be merged with the source value.
  2021. //
  2022. // There can be several copies back and forth, causing many values to be
  2023. // merged into one. We compute a list of ultimate values in the joined live
  2024. // range as well as a mappings from the old value numbers.
  2025. //
  2026. // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
  2027. // predecessors have a live out value. It doesn't cause real interference,
  2028. // and can be merged into the value it overlaps. Like a coalescable copy, it
  2029. // can be erased after joining.
  2030. //
  2031. // 3. Copy of external value. The overlapping def may be a copy of a value that
  2032. // is already in the other register. This is like a coalescable copy, but
  2033. // the live range of the source register must be trimmed after erasing the
  2034. // copy instruction:
  2035. //
  2036. // %src = COPY %ext
  2037. // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
  2038. //
  2039. // 4. Clobbering undefined lanes. Vector registers are sometimes built by
  2040. // defining one lane at a time:
  2041. //
  2042. // %dst:ssub0<def,read-undef> = FOO
  2043. // %src = BAR
  2044. // %dst:ssub1 = COPY %src
  2045. //
  2046. // The live range of %src overlaps the %dst value defined by FOO, but
  2047. // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
  2048. // which was undef anyway.
  2049. //
  2050. // The value mapping is more complicated in this case. The final live range
  2051. // will have different value numbers for both FOO and BAR, but there is no
  2052. // simple mapping from old to new values. It may even be necessary to add
  2053. // new PHI values.
  2054. //
  2055. // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
  2056. // is live, but never read. This can happen because we don't compute
  2057. // individual live ranges per lane.
  2058. //
  2059. // %dst = FOO
  2060. // %src = BAR
  2061. // %dst:ssub1 = COPY %src
  2062. //
  2063. // This kind of interference is only resolved locally. If the clobbered
  2064. // lane value escapes the block, the join is aborted.
  2065. namespace {
  2066. /// Track information about values in a single virtual register about to be
  2067. /// joined. Objects of this class are always created in pairs - one for each
  2068. /// side of the CoalescerPair (or one for each lane of a side of the coalescer
  2069. /// pair)
  2070. class JoinVals {
  2071. /// Live range we work on.
  2072. LiveRange &LR;
  2073. /// (Main) register we work on.
  2074. const Register Reg;
  2075. /// Reg (and therefore the values in this liverange) will end up as
  2076. /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
  2077. /// CP.SrcIdx.
  2078. const unsigned SubIdx;
  2079. /// The LaneMask that this liverange will occupy the coalesced register. May
  2080. /// be smaller than the lanemask produced by SubIdx when merging subranges.
  2081. const LaneBitmask LaneMask;
  2082. /// This is true when joining sub register ranges, false when joining main
  2083. /// ranges.
  2084. const bool SubRangeJoin;
  2085. /// Whether the current LiveInterval tracks subregister liveness.
  2086. const bool TrackSubRegLiveness;
  2087. /// Values that will be present in the final live range.
  2088. SmallVectorImpl<VNInfo*> &NewVNInfo;
  2089. const CoalescerPair &CP;
  2090. LiveIntervals *LIS;
  2091. SlotIndexes *Indexes;
  2092. const TargetRegisterInfo *TRI;
  2093. /// Value number assignments. Maps value numbers in LI to entries in
  2094. /// NewVNInfo. This is suitable for passing to LiveInterval::join().
  2095. SmallVector<int, 8> Assignments;
  2096. public:
  2097. /// Conflict resolution for overlapping values.
  2098. enum ConflictResolution {
  2099. /// No overlap, simply keep this value.
  2100. CR_Keep,
  2101. /// Merge this value into OtherVNI and erase the defining instruction.
  2102. /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
  2103. /// values.
  2104. CR_Erase,
  2105. /// Merge this value into OtherVNI but keep the defining instruction.
  2106. /// This is for the special case where OtherVNI is defined by the same
  2107. /// instruction.
  2108. CR_Merge,
  2109. /// Keep this value, and have it replace OtherVNI where possible. This
  2110. /// complicates value mapping since OtherVNI maps to two different values
  2111. /// before and after this def.
  2112. /// Used when clobbering undefined or dead lanes.
  2113. CR_Replace,
  2114. /// Unresolved conflict. Visit later when all values have been mapped.
  2115. CR_Unresolved,
  2116. /// Unresolvable conflict. Abort the join.
  2117. CR_Impossible
  2118. };
  2119. private:
  2120. /// Per-value info for LI. The lane bit masks are all relative to the final
  2121. /// joined register, so they can be compared directly between SrcReg and
  2122. /// DstReg.
  2123. struct Val {
  2124. ConflictResolution Resolution = CR_Keep;
  2125. /// Lanes written by this def, 0 for unanalyzed values.
  2126. LaneBitmask WriteLanes;
  2127. /// Lanes with defined values in this register. Other lanes are undef and
  2128. /// safe to clobber.
  2129. LaneBitmask ValidLanes;
  2130. /// Value in LI being redefined by this def.
  2131. VNInfo *RedefVNI = nullptr;
  2132. /// Value in the other live range that overlaps this def, if any.
  2133. VNInfo *OtherVNI = nullptr;
  2134. /// Is this value an IMPLICIT_DEF that can be erased?
  2135. ///
  2136. /// IMPLICIT_DEF values should only exist at the end of a basic block that
  2137. /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
  2138. /// safely erased if they are overlapping a live value in the other live
  2139. /// interval.
  2140. ///
  2141. /// Weird control flow graphs and incomplete PHI handling in
  2142. /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
  2143. /// longer live ranges. Such IMPLICIT_DEF values should be treated like
  2144. /// normal values.
  2145. bool ErasableImplicitDef = false;
  2146. /// True when the live range of this value will be pruned because of an
  2147. /// overlapping CR_Replace value in the other live range.
  2148. bool Pruned = false;
  2149. /// True once Pruned above has been computed.
  2150. bool PrunedComputed = false;
  2151. /// True if this value is determined to be identical to OtherVNI
  2152. /// (in valuesIdentical). This is used with CR_Erase where the erased
  2153. /// copy is redundant, i.e. the source value is already the same as
  2154. /// the destination. In such cases the subranges need to be updated
  2155. /// properly. See comment at pruneSubRegValues for more info.
  2156. bool Identical = false;
  2157. Val() = default;
  2158. bool isAnalyzed() const { return WriteLanes.any(); }
  2159. };
  2160. /// One entry per value number in LI.
  2161. SmallVector<Val, 8> Vals;
  2162. /// Compute the bitmask of lanes actually written by DefMI.
  2163. /// Set Redef if there are any partial register definitions that depend on the
  2164. /// previous value of the register.
  2165. LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
  2166. /// Find the ultimate value that VNI was copied from.
  2167. std::pair<const VNInfo *, Register> followCopyChain(const VNInfo *VNI) const;
  2168. bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const;
  2169. /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
  2170. /// Return a conflict resolution when possible, but leave the hard cases as
  2171. /// CR_Unresolved.
  2172. /// Recursively calls computeAssignment() on this and Other, guaranteeing that
  2173. /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
  2174. /// The recursion always goes upwards in the dominator tree, making loops
  2175. /// impossible.
  2176. ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
  2177. /// Compute the value assignment for ValNo in RI.
  2178. /// This may be called recursively by analyzeValue(), but never for a ValNo on
  2179. /// the stack.
  2180. void computeAssignment(unsigned ValNo, JoinVals &Other);
  2181. /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
  2182. /// the extent of the tainted lanes in the block.
  2183. ///
  2184. /// Multiple values in Other.LR can be affected since partial redefinitions
  2185. /// can preserve previously tainted lanes.
  2186. ///
  2187. /// 1 %dst = VLOAD <-- Define all lanes in %dst
  2188. /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
  2189. /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
  2190. /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
  2191. ///
  2192. /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
  2193. /// entry to TaintedVals.
  2194. ///
  2195. /// Returns false if the tainted lanes extend beyond the basic block.
  2196. bool
  2197. taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
  2198. SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
  2199. /// Return true if MI uses any of the given Lanes from Reg.
  2200. /// This does not include partial redefinitions of Reg.
  2201. bool usesLanes(const MachineInstr &MI, Register, unsigned, LaneBitmask) const;
  2202. /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
  2203. /// be pruned:
  2204. ///
  2205. /// %dst = COPY %src
  2206. /// %src = COPY %dst <-- This value to be pruned.
  2207. /// %dst = COPY %src <-- This value is a copy of a pruned value.
  2208. bool isPrunedValue(unsigned ValNo, JoinVals &Other);
  2209. public:
  2210. JoinVals(LiveRange &LR, Register Reg, unsigned SubIdx, LaneBitmask LaneMask,
  2211. SmallVectorImpl<VNInfo *> &newVNInfo, const CoalescerPair &cp,
  2212. LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
  2213. bool TrackSubRegLiveness)
  2214. : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
  2215. SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
  2216. NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
  2217. TRI(TRI), Assignments(LR.getNumValNums(), -1),
  2218. Vals(LR.getNumValNums()) {}
  2219. /// Analyze defs in LR and compute a value mapping in NewVNInfo.
  2220. /// Returns false if any conflicts were impossible to resolve.
  2221. bool mapValues(JoinVals &Other);
  2222. /// Try to resolve conflicts that require all values to be mapped.
  2223. /// Returns false if any conflicts were impossible to resolve.
  2224. bool resolveConflicts(JoinVals &Other);
  2225. /// Prune the live range of values in Other.LR where they would conflict with
  2226. /// CR_Replace values in LR. Collect end points for restoring the live range
  2227. /// after joining.
  2228. void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
  2229. bool changeInstrs);
  2230. /// Removes subranges starting at copies that get removed. This sometimes
  2231. /// happens when undefined subranges are copied around. These ranges contain
  2232. /// no useful information and can be removed.
  2233. void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
  2234. /// Pruning values in subranges can lead to removing segments in these
  2235. /// subranges started by IMPLICIT_DEFs. The corresponding segments in
  2236. /// the main range also need to be removed. This function will mark
  2237. /// the corresponding values in the main range as pruned, so that
  2238. /// eraseInstrs can do the final cleanup.
  2239. /// The parameter @p LI must be the interval whose main range is the
  2240. /// live range LR.
  2241. void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
  2242. /// Erase any machine instructions that have been coalesced away.
  2243. /// Add erased instructions to ErasedInstrs.
  2244. /// Add foreign virtual registers to ShrinkRegs if their live range ended at
  2245. /// the erased instrs.
  2246. void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
  2247. SmallVectorImpl<Register> &ShrinkRegs,
  2248. LiveInterval *LI = nullptr);
  2249. /// Remove liverange defs at places where implicit defs will be removed.
  2250. void removeImplicitDefs();
  2251. /// Get the value assignments suitable for passing to LiveInterval::join.
  2252. const int *getAssignments() const { return Assignments.data(); }
  2253. /// Get the conflict resolution for a value number.
  2254. ConflictResolution getResolution(unsigned Num) const {
  2255. return Vals[Num].Resolution;
  2256. }
  2257. };
  2258. } // end anonymous namespace
  2259. LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
  2260. const {
  2261. LaneBitmask L;
  2262. for (const MachineOperand &MO : DefMI->operands()) {
  2263. if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
  2264. continue;
  2265. L |= TRI->getSubRegIndexLaneMask(
  2266. TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
  2267. if (MO.readsReg())
  2268. Redef = true;
  2269. }
  2270. return L;
  2271. }
  2272. std::pair<const VNInfo *, Register>
  2273. JoinVals::followCopyChain(const VNInfo *VNI) const {
  2274. Register TrackReg = Reg;
  2275. while (!VNI->isPHIDef()) {
  2276. SlotIndex Def = VNI->def;
  2277. MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
  2278. assert(MI && "No defining instruction");
  2279. if (!MI->isFullCopy())
  2280. return std::make_pair(VNI, TrackReg);
  2281. Register SrcReg = MI->getOperand(1).getReg();
  2282. if (!SrcReg.isVirtual())
  2283. return std::make_pair(VNI, TrackReg);
  2284. const LiveInterval &LI = LIS->getInterval(SrcReg);
  2285. const VNInfo *ValueIn;
  2286. // No subrange involved.
  2287. if (!SubRangeJoin || !LI.hasSubRanges()) {
  2288. LiveQueryResult LRQ = LI.Query(Def);
  2289. ValueIn = LRQ.valueIn();
  2290. } else {
  2291. // Query subranges. Ensure that all matching ones take us to the same def
  2292. // (allowing some of them to be undef).
  2293. ValueIn = nullptr;
  2294. for (const LiveInterval::SubRange &S : LI.subranges()) {
  2295. // Transform lanemask to a mask in the joined live interval.
  2296. LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
  2297. if ((SMask & LaneMask).none())
  2298. continue;
  2299. LiveQueryResult LRQ = S.Query(Def);
  2300. if (!ValueIn) {
  2301. ValueIn = LRQ.valueIn();
  2302. continue;
  2303. }
  2304. if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
  2305. return std::make_pair(VNI, TrackReg);
  2306. }
  2307. }
  2308. if (ValueIn == nullptr) {
  2309. // Reaching an undefined value is legitimate, for example:
  2310. //
  2311. // 1 undef %0.sub1 = ... ;; %0.sub0 == undef
  2312. // 2 %1 = COPY %0 ;; %1 is defined here.
  2313. // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition,
  2314. // ;; but it's equivalent to "undef".
  2315. return std::make_pair(nullptr, SrcReg);
  2316. }
  2317. VNI = ValueIn;
  2318. TrackReg = SrcReg;
  2319. }
  2320. return std::make_pair(VNI, TrackReg);
  2321. }
  2322. bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
  2323. const JoinVals &Other) const {
  2324. const VNInfo *Orig0;
  2325. Register Reg0;
  2326. std::tie(Orig0, Reg0) = followCopyChain(Value0);
  2327. if (Orig0 == Value1 && Reg0 == Other.Reg)
  2328. return true;
  2329. const VNInfo *Orig1;
  2330. Register Reg1;
  2331. std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
  2332. // If both values are undefined, and the source registers are the same
  2333. // register, the values are identical. Filter out cases where only one
  2334. // value is defined.
  2335. if (Orig0 == nullptr || Orig1 == nullptr)
  2336. return Orig0 == Orig1 && Reg0 == Reg1;
  2337. // The values are equal if they are defined at the same place and use the
  2338. // same register. Note that we cannot compare VNInfos directly as some of
  2339. // them might be from a copy created in mergeSubRangeInto() while the other
  2340. // is from the original LiveInterval.
  2341. return Orig0->def == Orig1->def && Reg0 == Reg1;
  2342. }
  2343. JoinVals::ConflictResolution
  2344. JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
  2345. Val &V = Vals[ValNo];
  2346. assert(!V.isAnalyzed() && "Value has already been analyzed!");
  2347. VNInfo *VNI = LR.getValNumInfo(ValNo);
  2348. if (VNI->isUnused()) {
  2349. V.WriteLanes = LaneBitmask::getAll();
  2350. return CR_Keep;
  2351. }
  2352. // Get the instruction defining this value, compute the lanes written.
  2353. const MachineInstr *DefMI = nullptr;
  2354. if (VNI->isPHIDef()) {
  2355. // Conservatively assume that all lanes in a PHI are valid.
  2356. LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
  2357. : TRI->getSubRegIndexLaneMask(SubIdx);
  2358. V.ValidLanes = V.WriteLanes = Lanes;
  2359. } else {
  2360. DefMI = Indexes->getInstructionFromIndex(VNI->def);
  2361. assert(DefMI != nullptr);
  2362. if (SubRangeJoin) {
  2363. // We don't care about the lanes when joining subregister ranges.
  2364. V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
  2365. if (DefMI->isImplicitDef()) {
  2366. V.ValidLanes = LaneBitmask::getNone();
  2367. V.ErasableImplicitDef = true;
  2368. }
  2369. } else {
  2370. bool Redef = false;
  2371. V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
  2372. // If this is a read-modify-write instruction, there may be more valid
  2373. // lanes than the ones written by this instruction.
  2374. // This only covers partial redef operands. DefMI may have normal use
  2375. // operands reading the register. They don't contribute valid lanes.
  2376. //
  2377. // This adds ssub1 to the set of valid lanes in %src:
  2378. //
  2379. // %src:ssub1 = FOO
  2380. //
  2381. // This leaves only ssub1 valid, making any other lanes undef:
  2382. //
  2383. // %src:ssub1<def,read-undef> = FOO %src:ssub2
  2384. //
  2385. // The <read-undef> flag on the def operand means that old lane values are
  2386. // not important.
  2387. if (Redef) {
  2388. V.RedefVNI = LR.Query(VNI->def).valueIn();
  2389. assert((TrackSubRegLiveness || V.RedefVNI) &&
  2390. "Instruction is reading nonexistent value");
  2391. if (V.RedefVNI != nullptr) {
  2392. computeAssignment(V.RedefVNI->id, Other);
  2393. V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
  2394. }
  2395. }
  2396. // An IMPLICIT_DEF writes undef values.
  2397. if (DefMI->isImplicitDef()) {
  2398. // We normally expect IMPLICIT_DEF values to be live only until the end
  2399. // of their block. If the value is really live longer and gets pruned in
  2400. // another block, this flag is cleared again.
  2401. //
  2402. // Clearing the valid lanes is deferred until it is sure this can be
  2403. // erased.
  2404. V.ErasableImplicitDef = true;
  2405. }
  2406. }
  2407. }
  2408. // Find the value in Other that overlaps VNI->def, if any.
  2409. LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
  2410. // It is possible that both values are defined by the same instruction, or
  2411. // the values are PHIs defined in the same block. When that happens, the two
  2412. // values should be merged into one, but not into any preceding value.
  2413. // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
  2414. if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
  2415. assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
  2416. // One value stays, the other is merged. Keep the earlier one, or the first
  2417. // one we see.
  2418. if (OtherVNI->def < VNI->def)
  2419. Other.computeAssignment(OtherVNI->id, *this);
  2420. else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
  2421. // This is an early-clobber def overlapping a live-in value in the other
  2422. // register. Not mergeable.
  2423. V.OtherVNI = OtherLRQ.valueIn();
  2424. return CR_Impossible;
  2425. }
  2426. V.OtherVNI = OtherVNI;
  2427. Val &OtherV = Other.Vals[OtherVNI->id];
  2428. // Keep this value, check for conflicts when analyzing OtherVNI.
  2429. if (!OtherV.isAnalyzed())
  2430. return CR_Keep;
  2431. // Both sides have been analyzed now.
  2432. // Allow overlapping PHI values. Any real interference would show up in a
  2433. // predecessor, the PHI itself can't introduce any conflicts.
  2434. if (VNI->isPHIDef())
  2435. return CR_Merge;
  2436. if ((V.ValidLanes & OtherV.ValidLanes).any())
  2437. // Overlapping lanes can't be resolved.
  2438. return CR_Impossible;
  2439. else
  2440. return CR_Merge;
  2441. }
  2442. // No simultaneous def. Is Other live at the def?
  2443. V.OtherVNI = OtherLRQ.valueIn();
  2444. if (!V.OtherVNI)
  2445. // No overlap, no conflict.
  2446. return CR_Keep;
  2447. assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
  2448. // We have overlapping values, or possibly a kill of Other.
  2449. // Recursively compute assignments up the dominator tree.
  2450. Other.computeAssignment(V.OtherVNI->id, *this);
  2451. Val &OtherV = Other.Vals[V.OtherVNI->id];
  2452. if (OtherV.ErasableImplicitDef) {
  2453. // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
  2454. // This shouldn't normally happen, but ProcessImplicitDefs can leave such
  2455. // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
  2456. // technically.
  2457. //
  2458. // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
  2459. // to erase the IMPLICIT_DEF instruction.
  2460. if (DefMI &&
  2461. DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
  2462. LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
  2463. << " extends into "
  2464. << printMBBReference(*DefMI->getParent())
  2465. << ", keeping it.\n");
  2466. OtherV.ErasableImplicitDef = false;
  2467. } else {
  2468. // We deferred clearing these lanes in case we needed to save them
  2469. OtherV.ValidLanes &= ~OtherV.WriteLanes;
  2470. }
  2471. }
  2472. // Allow overlapping PHI values. Any real interference would show up in a
  2473. // predecessor, the PHI itself can't introduce any conflicts.
  2474. if (VNI->isPHIDef())
  2475. return CR_Replace;
  2476. // Check for simple erasable conflicts.
  2477. if (DefMI->isImplicitDef())
  2478. return CR_Erase;
  2479. // Include the non-conflict where DefMI is a coalescable copy that kills
  2480. // OtherVNI. We still want the copy erased and value numbers merged.
  2481. if (CP.isCoalescable(DefMI)) {
  2482. // Some of the lanes copied from OtherVNI may be undef, making them undef
  2483. // here too.
  2484. V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
  2485. return CR_Erase;
  2486. }
  2487. // This may not be a real conflict if DefMI simply kills Other and defines
  2488. // VNI.
  2489. if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
  2490. return CR_Keep;
  2491. // Handle the case where VNI and OtherVNI can be proven to be identical:
  2492. //
  2493. // %other = COPY %ext
  2494. // %this = COPY %ext <-- Erase this copy
  2495. //
  2496. if (DefMI->isFullCopy() && !CP.isPartial() &&
  2497. valuesIdentical(VNI, V.OtherVNI, Other)) {
  2498. V.Identical = true;
  2499. return CR_Erase;
  2500. }
  2501. // The remaining checks apply to the lanes, which aren't tracked here. This
  2502. // was already decided to be OK via the following CR_Replace condition.
  2503. // CR_Replace.
  2504. if (SubRangeJoin)
  2505. return CR_Replace;
  2506. // If the lanes written by this instruction were all undef in OtherVNI, it is
  2507. // still safe to join the live ranges. This can't be done with a simple value
  2508. // mapping, though - OtherVNI will map to multiple values:
  2509. //
  2510. // 1 %dst:ssub0 = FOO <-- OtherVNI
  2511. // 2 %src = BAR <-- VNI
  2512. // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy.
  2513. // 4 BAZ killed %dst
  2514. // 5 QUUX killed %src
  2515. //
  2516. // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
  2517. // handles this complex value mapping.
  2518. if ((V.WriteLanes & OtherV.ValidLanes).none())
  2519. return CR_Replace;
  2520. // If the other live range is killed by DefMI and the live ranges are still
  2521. // overlapping, it must be because we're looking at an early clobber def:
  2522. //
  2523. // %dst<def,early-clobber> = ASM killed %src
  2524. //
  2525. // In this case, it is illegal to merge the two live ranges since the early
  2526. // clobber def would clobber %src before it was read.
  2527. if (OtherLRQ.isKill()) {
  2528. // This case where the def doesn't overlap the kill is handled above.
  2529. assert(VNI->def.isEarlyClobber() &&
  2530. "Only early clobber defs can overlap a kill");
  2531. return CR_Impossible;
  2532. }
  2533. // VNI is clobbering live lanes in OtherVNI, but there is still the
  2534. // possibility that no instructions actually read the clobbered lanes.
  2535. // If we're clobbering all the lanes in OtherVNI, at least one must be read.
  2536. // Otherwise Other.RI wouldn't be live here.
  2537. if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
  2538. return CR_Impossible;
  2539. if (TrackSubRegLiveness) {
  2540. auto &OtherLI = LIS->getInterval(Other.Reg);
  2541. // If OtherVNI does not have subranges, it means all the lanes of OtherVNI
  2542. // share the same live range, so we just need to check whether they have
  2543. // any conflict bit in their LaneMask.
  2544. if (!OtherLI.hasSubRanges()) {
  2545. LaneBitmask OtherMask = TRI->getSubRegIndexLaneMask(Other.SubIdx);
  2546. return (OtherMask & V.WriteLanes).none() ? CR_Replace : CR_Impossible;
  2547. }
  2548. // If we are clobbering some active lanes of OtherVNI at VNI->def, it is
  2549. // impossible to resolve the conflict. Otherwise, we can just replace
  2550. // OtherVNI because of no real conflict.
  2551. for (LiveInterval::SubRange &OtherSR : OtherLI.subranges()) {
  2552. LaneBitmask OtherMask =
  2553. TRI->composeSubRegIndexLaneMask(Other.SubIdx, OtherSR.LaneMask);
  2554. if ((OtherMask & V.WriteLanes).none())
  2555. continue;
  2556. auto OtherSRQ = OtherSR.Query(VNI->def);
  2557. if (OtherSRQ.valueIn() && OtherSRQ.endPoint() > VNI->def) {
  2558. // VNI is clobbering some lanes of OtherVNI, they have real conflict.
  2559. return CR_Impossible;
  2560. }
  2561. }
  2562. // VNI is NOT clobbering any lane of OtherVNI, just replace OtherVNI.
  2563. return CR_Replace;
  2564. }
  2565. // We need to verify that no instructions are reading the clobbered lanes.
  2566. // To save compile time, we'll only check that locally. Don't allow the
  2567. // tainted value to escape the basic block.
  2568. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
  2569. if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
  2570. return CR_Impossible;
  2571. // There are still some things that could go wrong besides clobbered lanes
  2572. // being read, for example OtherVNI may be only partially redefined in MBB,
  2573. // and some clobbered lanes could escape the block. Save this analysis for
  2574. // resolveConflicts() when all values have been mapped. We need to know
  2575. // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
  2576. // that now - the recursive analyzeValue() calls must go upwards in the
  2577. // dominator tree.
  2578. return CR_Unresolved;
  2579. }
  2580. void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
  2581. Val &V = Vals[ValNo];
  2582. if (V.isAnalyzed()) {
  2583. // Recursion should always move up the dominator tree, so ValNo is not
  2584. // supposed to reappear before it has been assigned.
  2585. assert(Assignments[ValNo] != -1 && "Bad recursion?");
  2586. return;
  2587. }
  2588. switch ((V.Resolution = analyzeValue(ValNo, Other))) {
  2589. case CR_Erase:
  2590. case CR_Merge:
  2591. // Merge this ValNo into OtherVNI.
  2592. assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
  2593. assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
  2594. Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
  2595. LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
  2596. << LR.getValNumInfo(ValNo)->def << " into "
  2597. << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
  2598. << V.OtherVNI->def << " --> @"
  2599. << NewVNInfo[Assignments[ValNo]]->def << '\n');
  2600. break;
  2601. case CR_Replace:
  2602. case CR_Unresolved: {
  2603. // The other value is going to be pruned if this join is successful.
  2604. assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
  2605. Val &OtherV = Other.Vals[V.OtherVNI->id];
  2606. // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
  2607. // its lanes.
  2608. if (OtherV.ErasableImplicitDef &&
  2609. TrackSubRegLiveness &&
  2610. (OtherV.WriteLanes & ~V.ValidLanes).any()) {
  2611. LLVM_DEBUG(dbgs() << "Cannot erase implicit_def with missing values\n");
  2612. OtherV.ErasableImplicitDef = false;
  2613. // The valid lanes written by the implicit_def were speculatively cleared
  2614. // before, so make this more conservative. It may be better to track this,
  2615. // I haven't found a testcase where it matters.
  2616. OtherV.ValidLanes = LaneBitmask::getAll();
  2617. }
  2618. OtherV.Pruned = true;
  2619. LLVM_FALLTHROUGH;
  2620. }
  2621. default:
  2622. // This value number needs to go in the final joined live range.
  2623. Assignments[ValNo] = NewVNInfo.size();
  2624. NewVNInfo.push_back(LR.getValNumInfo(ValNo));
  2625. break;
  2626. }
  2627. }
  2628. bool JoinVals::mapValues(JoinVals &Other) {
  2629. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2630. computeAssignment(i, Other);
  2631. if (Vals[i].Resolution == CR_Impossible) {
  2632. LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
  2633. << '@' << LR.getValNumInfo(i)->def << '\n');
  2634. return false;
  2635. }
  2636. }
  2637. return true;
  2638. }
  2639. bool JoinVals::
  2640. taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
  2641. SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
  2642. VNInfo *VNI = LR.getValNumInfo(ValNo);
  2643. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
  2644. SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
  2645. // Scan Other.LR from VNI.def to MBBEnd.
  2646. LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
  2647. assert(OtherI != Other.LR.end() && "No conflict?");
  2648. do {
  2649. // OtherI is pointing to a tainted value. Abort the join if the tainted
  2650. // lanes escape the block.
  2651. SlotIndex End = OtherI->end;
  2652. if (End >= MBBEnd) {
  2653. LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
  2654. << OtherI->valno->id << '@' << OtherI->start << '\n');
  2655. return false;
  2656. }
  2657. LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
  2658. << OtherI->valno->id << '@' << OtherI->start << " to "
  2659. << End << '\n');
  2660. // A dead def is not a problem.
  2661. if (End.isDead())
  2662. break;
  2663. TaintExtent.push_back(std::make_pair(End, TaintedLanes));
  2664. // Check for another def in the MBB.
  2665. if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
  2666. break;
  2667. // Lanes written by the new def are no longer tainted.
  2668. const Val &OV = Other.Vals[OtherI->valno->id];
  2669. TaintedLanes &= ~OV.WriteLanes;
  2670. if (!OV.RedefVNI)
  2671. break;
  2672. } while (TaintedLanes.any());
  2673. return true;
  2674. }
  2675. bool JoinVals::usesLanes(const MachineInstr &MI, Register Reg, unsigned SubIdx,
  2676. LaneBitmask Lanes) const {
  2677. if (MI.isDebugOrPseudoInstr())
  2678. return false;
  2679. for (const MachineOperand &MO : MI.operands()) {
  2680. if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
  2681. continue;
  2682. if (!MO.readsReg())
  2683. continue;
  2684. unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
  2685. if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
  2686. return true;
  2687. }
  2688. return false;
  2689. }
  2690. bool JoinVals::resolveConflicts(JoinVals &Other) {
  2691. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2692. Val &V = Vals[i];
  2693. assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
  2694. if (V.Resolution != CR_Unresolved)
  2695. continue;
  2696. LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
  2697. << LR.getValNumInfo(i)->def
  2698. << ' ' << PrintLaneMask(LaneMask) << '\n');
  2699. if (SubRangeJoin)
  2700. return false;
  2701. ++NumLaneConflicts;
  2702. assert(V.OtherVNI && "Inconsistent conflict resolution.");
  2703. VNInfo *VNI = LR.getValNumInfo(i);
  2704. const Val &OtherV = Other.Vals[V.OtherVNI->id];
  2705. // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
  2706. // join, those lanes will be tainted with a wrong value. Get the extent of
  2707. // the tainted lanes.
  2708. LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
  2709. SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
  2710. if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
  2711. // Tainted lanes would extend beyond the basic block.
  2712. return false;
  2713. assert(!TaintExtent.empty() && "There should be at least one conflict.");
  2714. // Now look at the instructions from VNI->def to TaintExtent (inclusive).
  2715. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
  2716. MachineBasicBlock::iterator MI = MBB->begin();
  2717. if (!VNI->isPHIDef()) {
  2718. MI = Indexes->getInstructionFromIndex(VNI->def);
  2719. if (!VNI->def.isEarlyClobber()) {
  2720. // No need to check the instruction defining VNI for reads.
  2721. ++MI;
  2722. }
  2723. }
  2724. assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
  2725. "Interference ends on VNI->def. Should have been handled earlier");
  2726. MachineInstr *LastMI =
  2727. Indexes->getInstructionFromIndex(TaintExtent.front().first);
  2728. assert(LastMI && "Range must end at a proper instruction");
  2729. unsigned TaintNum = 0;
  2730. while (true) {
  2731. assert(MI != MBB->end() && "Bad LastMI");
  2732. if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
  2733. LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
  2734. return false;
  2735. }
  2736. // LastMI is the last instruction to use the current value.
  2737. if (&*MI == LastMI) {
  2738. if (++TaintNum == TaintExtent.size())
  2739. break;
  2740. LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
  2741. assert(LastMI && "Range must end at a proper instruction");
  2742. TaintedLanes = TaintExtent[TaintNum].second;
  2743. }
  2744. ++MI;
  2745. }
  2746. // The tainted lanes are unused.
  2747. V.Resolution = CR_Replace;
  2748. ++NumLaneResolves;
  2749. }
  2750. return true;
  2751. }
  2752. bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
  2753. Val &V = Vals[ValNo];
  2754. if (V.Pruned || V.PrunedComputed)
  2755. return V.Pruned;
  2756. if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
  2757. return V.Pruned;
  2758. // Follow copies up the dominator tree and check if any intermediate value
  2759. // has been pruned.
  2760. V.PrunedComputed = true;
  2761. V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
  2762. return V.Pruned;
  2763. }
  2764. void JoinVals::pruneValues(JoinVals &Other,
  2765. SmallVectorImpl<SlotIndex> &EndPoints,
  2766. bool changeInstrs) {
  2767. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2768. SlotIndex Def = LR.getValNumInfo(i)->def;
  2769. switch (Vals[i].Resolution) {
  2770. case CR_Keep:
  2771. break;
  2772. case CR_Replace: {
  2773. // This value takes precedence over the value in Other.LR.
  2774. LIS->pruneValue(Other.LR, Def, &EndPoints);
  2775. // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
  2776. // instructions are only inserted to provide a live-out value for PHI
  2777. // predecessors, so the instruction should simply go away once its value
  2778. // has been replaced.
  2779. Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
  2780. bool EraseImpDef = OtherV.ErasableImplicitDef &&
  2781. OtherV.Resolution == CR_Keep;
  2782. if (!Def.isBlock()) {
  2783. if (changeInstrs) {
  2784. // Remove <def,read-undef> flags. This def is now a partial redef.
  2785. // Also remove dead flags since the joined live range will
  2786. // continue past this instruction.
  2787. for (MachineOperand &MO :
  2788. Indexes->getInstructionFromIndex(Def)->operands()) {
  2789. if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
  2790. if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
  2791. MO.setIsUndef(false);
  2792. MO.setIsDead(false);
  2793. }
  2794. }
  2795. }
  2796. // This value will reach instructions below, but we need to make sure
  2797. // the live range also reaches the instruction at Def.
  2798. if (!EraseImpDef)
  2799. EndPoints.push_back(Def);
  2800. }
  2801. LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
  2802. << ": " << Other.LR << '\n');
  2803. break;
  2804. }
  2805. case CR_Erase:
  2806. case CR_Merge:
  2807. if (isPrunedValue(i, Other)) {
  2808. // This value is ultimately a copy of a pruned value in LR or Other.LR.
  2809. // We can no longer trust the value mapping computed by
  2810. // computeAssignment(), the value that was originally copied could have
  2811. // been replaced.
  2812. LIS->pruneValue(LR, Def, &EndPoints);
  2813. LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
  2814. << Def << ": " << LR << '\n');
  2815. }
  2816. break;
  2817. case CR_Unresolved:
  2818. case CR_Impossible:
  2819. llvm_unreachable("Unresolved conflicts");
  2820. }
  2821. }
  2822. }
  2823. // Check if the segment consists of a copied live-through value (i.e. the copy
  2824. // in the block only extended the liveness, of an undef value which we may need
  2825. // to handle).
  2826. static bool isLiveThrough(const LiveQueryResult Q) {
  2827. return Q.valueIn() && Q.valueIn()->isPHIDef() && Q.valueIn() == Q.valueOut();
  2828. }
  2829. /// Consider the following situation when coalescing the copy between
  2830. /// %31 and %45 at 800. (The vertical lines represent live range segments.)
  2831. ///
  2832. /// Main range Subrange 0004 (sub2)
  2833. /// %31 %45 %31 %45
  2834. /// 544 %45 = COPY %28 + +
  2835. /// | v1 | v1
  2836. /// 560B bb.1: + +
  2837. /// 624 = %45.sub2 | v2 | v2
  2838. /// 800 %31 = COPY %45 + + + +
  2839. /// | v0 | v0
  2840. /// 816 %31.sub1 = ... + |
  2841. /// 880 %30 = COPY %31 | v1 +
  2842. /// 928 %45 = COPY %30 | + +
  2843. /// | | v0 | v0 <--+
  2844. /// 992B ; backedge -> bb.1 | + + |
  2845. /// 1040 = %31.sub0 + |
  2846. /// This value must remain
  2847. /// live-out!
  2848. ///
  2849. /// Assuming that %31 is coalesced into %45, the copy at 928 becomes
  2850. /// redundant, since it copies the value from %45 back into it. The
  2851. /// conflict resolution for the main range determines that %45.v0 is
  2852. /// to be erased, which is ok since %31.v1 is identical to it.
  2853. /// The problem happens with the subrange for sub2: it has to be live
  2854. /// on exit from the block, but since 928 was actually a point of
  2855. /// definition of %45.sub2, %45.sub2 was not live immediately prior
  2856. /// to that definition. As a result, when 928 was erased, the value v0
  2857. /// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
  2858. /// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
  2859. /// providing an incorrect value to the use at 624.
  2860. ///
  2861. /// Since the main-range values %31.v1 and %45.v0 were proved to be
  2862. /// identical, the corresponding values in subranges must also be the
  2863. /// same. A redundant copy is removed because it's not needed, and not
  2864. /// because it copied an undefined value, so any liveness that originated
  2865. /// from that copy cannot disappear. When pruning a value that started
  2866. /// at the removed copy, the corresponding identical value must be
  2867. /// extended to replace it.
  2868. void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
  2869. // Look for values being erased.
  2870. bool DidPrune = false;
  2871. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2872. Val &V = Vals[i];
  2873. // We should trigger in all cases in which eraseInstrs() does something.
  2874. // match what eraseInstrs() is doing, print a message so
  2875. if (V.Resolution != CR_Erase &&
  2876. (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
  2877. continue;
  2878. // Check subranges at the point where the copy will be removed.
  2879. SlotIndex Def = LR.getValNumInfo(i)->def;
  2880. SlotIndex OtherDef;
  2881. if (V.Identical)
  2882. OtherDef = V.OtherVNI->def;
  2883. // Print message so mismatches with eraseInstrs() can be diagnosed.
  2884. LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
  2885. << '\n');
  2886. for (LiveInterval::SubRange &S : LI.subranges()) {
  2887. LiveQueryResult Q = S.Query(Def);
  2888. // If a subrange starts at the copy then an undefined value has been
  2889. // copied and we must remove that subrange value as well.
  2890. VNInfo *ValueOut = Q.valueOutOrDead();
  2891. if (ValueOut != nullptr && (Q.valueIn() == nullptr ||
  2892. (V.Identical && V.Resolution == CR_Erase &&
  2893. ValueOut->def == Def))) {
  2894. LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
  2895. << " at " << Def << "\n");
  2896. SmallVector<SlotIndex,8> EndPoints;
  2897. LIS->pruneValue(S, Def, &EndPoints);
  2898. DidPrune = true;
  2899. // Mark value number as unused.
  2900. ValueOut->markUnused();
  2901. if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
  2902. // If V is identical to V.OtherVNI (and S was live at OtherDef),
  2903. // then we can't simply prune V from S. V needs to be replaced
  2904. // with V.OtherVNI.
  2905. LIS->extendToIndices(S, EndPoints);
  2906. }
  2907. // We may need to eliminate the subrange if the copy introduced a live
  2908. // out undef value.
  2909. if (ValueOut->isPHIDef())
  2910. ShrinkMask |= S.LaneMask;
  2911. continue;
  2912. }
  2913. // If a subrange ends at the copy, then a value was copied but only
  2914. // partially used later. Shrink the subregister range appropriately.
  2915. //
  2916. // Ultimately this calls shrinkToUses, so assuming ShrinkMask is
  2917. // conservatively correct.
  2918. if ((Q.valueIn() != nullptr && Q.valueOut() == nullptr) ||
  2919. (V.Resolution == CR_Erase && isLiveThrough(Q))) {
  2920. LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
  2921. << PrintLaneMask(S.LaneMask) << " at " << Def
  2922. << "\n");
  2923. ShrinkMask |= S.LaneMask;
  2924. }
  2925. }
  2926. }
  2927. if (DidPrune)
  2928. LI.removeEmptySubRanges();
  2929. }
  2930. /// Check if any of the subranges of @p LI contain a definition at @p Def.
  2931. static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
  2932. for (LiveInterval::SubRange &SR : LI.subranges()) {
  2933. if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
  2934. if (VNI->def == Def)
  2935. return true;
  2936. }
  2937. return false;
  2938. }
  2939. void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
  2940. assert(&static_cast<LiveRange&>(LI) == &LR);
  2941. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2942. if (Vals[i].Resolution != CR_Keep)
  2943. continue;
  2944. VNInfo *VNI = LR.getValNumInfo(i);
  2945. if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
  2946. continue;
  2947. Vals[i].Pruned = true;
  2948. ShrinkMainRange = true;
  2949. }
  2950. }
  2951. void JoinVals::removeImplicitDefs() {
  2952. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2953. Val &V = Vals[i];
  2954. if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
  2955. continue;
  2956. VNInfo *VNI = LR.getValNumInfo(i);
  2957. VNI->markUnused();
  2958. LR.removeValNo(VNI);
  2959. }
  2960. }
  2961. void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
  2962. SmallVectorImpl<Register> &ShrinkRegs,
  2963. LiveInterval *LI) {
  2964. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2965. // Get the def location before markUnused() below invalidates it.
  2966. VNInfo *VNI = LR.getValNumInfo(i);
  2967. SlotIndex Def = VNI->def;
  2968. switch (Vals[i].Resolution) {
  2969. case CR_Keep: {
  2970. // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
  2971. // longer. The IMPLICIT_DEF instructions are only inserted by
  2972. // PHIElimination to guarantee that all PHI predecessors have a value.
  2973. if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
  2974. break;
  2975. // Remove value number i from LR.
  2976. // For intervals with subranges, removing a segment from the main range
  2977. // may require extending the previous segment: for each definition of
  2978. // a subregister, there will be a corresponding def in the main range.
  2979. // That def may fall in the middle of a segment from another subrange.
  2980. // In such cases, removing this def from the main range must be
  2981. // complemented by extending the main range to account for the liveness
  2982. // of the other subrange.
  2983. // The new end point of the main range segment to be extended.
  2984. SlotIndex NewEnd;
  2985. if (LI != nullptr) {
  2986. LiveRange::iterator I = LR.FindSegmentContaining(Def);
  2987. assert(I != LR.end());
  2988. // Do not extend beyond the end of the segment being removed.
  2989. // The segment may have been pruned in preparation for joining
  2990. // live ranges.
  2991. NewEnd = I->end;
  2992. }
  2993. LR.removeValNo(VNI);
  2994. // Note that this VNInfo is reused and still referenced in NewVNInfo,
  2995. // make it appear like an unused value number.
  2996. VNI->markUnused();
  2997. if (LI != nullptr && LI->hasSubRanges()) {
  2998. assert(static_cast<LiveRange*>(LI) == &LR);
  2999. // Determine the end point based on the subrange information:
  3000. // minimum of (earliest def of next segment,
  3001. // latest end point of containing segment)
  3002. SlotIndex ED, LE;
  3003. for (LiveInterval::SubRange &SR : LI->subranges()) {
  3004. LiveRange::iterator I = SR.find(Def);
  3005. if (I == SR.end())
  3006. continue;
  3007. if (I->start > Def)
  3008. ED = ED.isValid() ? std::min(ED, I->start) : I->start;
  3009. else
  3010. LE = LE.isValid() ? std::max(LE, I->end) : I->end;
  3011. }
  3012. if (LE.isValid())
  3013. NewEnd = std::min(NewEnd, LE);
  3014. if (ED.isValid())
  3015. NewEnd = std::min(NewEnd, ED);
  3016. // We only want to do the extension if there was a subrange that
  3017. // was live across Def.
  3018. if (LE.isValid()) {
  3019. LiveRange::iterator S = LR.find(Def);
  3020. if (S != LR.begin())
  3021. std::prev(S)->end = NewEnd;
  3022. }
  3023. }
  3024. LLVM_DEBUG({
  3025. dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
  3026. if (LI != nullptr)
  3027. dbgs() << "\t\t LHS = " << *LI << '\n';
  3028. });
  3029. LLVM_FALLTHROUGH;
  3030. }
  3031. case CR_Erase: {
  3032. MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
  3033. assert(MI && "No instruction to erase");
  3034. if (MI->isCopy()) {
  3035. Register Reg = MI->getOperand(1).getReg();
  3036. if (Register::isVirtualRegister(Reg) && Reg != CP.getSrcReg() &&
  3037. Reg != CP.getDstReg())
  3038. ShrinkRegs.push_back(Reg);
  3039. }
  3040. ErasedInstrs.insert(MI);
  3041. LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
  3042. LIS->RemoveMachineInstrFromMaps(*MI);
  3043. MI->eraseFromParent();
  3044. break;
  3045. }
  3046. default:
  3047. break;
  3048. }
  3049. }
  3050. }
  3051. void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
  3052. LaneBitmask LaneMask,
  3053. const CoalescerPair &CP) {
  3054. SmallVector<VNInfo*, 16> NewVNInfo;
  3055. JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
  3056. NewVNInfo, CP, LIS, TRI, true, true);
  3057. JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
  3058. NewVNInfo, CP, LIS, TRI, true, true);
  3059. // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
  3060. // We should be able to resolve all conflicts here as we could successfully do
  3061. // it on the mainrange already. There is however a problem when multiple
  3062. // ranges get mapped to the "overflow" lane mask bit which creates unexpected
  3063. // interferences.
  3064. if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
  3065. // We already determined that it is legal to merge the intervals, so this
  3066. // should never fail.
  3067. llvm_unreachable("*** Couldn't join subrange!\n");
  3068. }
  3069. if (!LHSVals.resolveConflicts(RHSVals) ||
  3070. !RHSVals.resolveConflicts(LHSVals)) {
  3071. // We already determined that it is legal to merge the intervals, so this
  3072. // should never fail.
  3073. llvm_unreachable("*** Couldn't join subrange!\n");
  3074. }
  3075. // The merging algorithm in LiveInterval::join() can't handle conflicting
  3076. // value mappings, so we need to remove any live ranges that overlap a
  3077. // CR_Replace resolution. Collect a set of end points that can be used to
  3078. // restore the live range after joining.
  3079. SmallVector<SlotIndex, 8> EndPoints;
  3080. LHSVals.pruneValues(RHSVals, EndPoints, false);
  3081. RHSVals.pruneValues(LHSVals, EndPoints, false);
  3082. LHSVals.removeImplicitDefs();
  3083. RHSVals.removeImplicitDefs();
  3084. LRange.verify();
  3085. RRange.verify();
  3086. // Join RRange into LHS.
  3087. LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
  3088. NewVNInfo);
  3089. LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)
  3090. << ' ' << LRange << "\n");
  3091. if (EndPoints.empty())
  3092. return;
  3093. // Recompute the parts of the live range we had to remove because of
  3094. // CR_Replace conflicts.
  3095. LLVM_DEBUG({
  3096. dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
  3097. for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
  3098. dbgs() << EndPoints[i];
  3099. if (i != n-1)
  3100. dbgs() << ',';
  3101. }
  3102. dbgs() << ": " << LRange << '\n';
  3103. });
  3104. LIS->extendToIndices(LRange, EndPoints);
  3105. }
  3106. void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
  3107. const LiveRange &ToMerge,
  3108. LaneBitmask LaneMask,
  3109. CoalescerPair &CP,
  3110. unsigned ComposeSubRegIdx) {
  3111. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  3112. LI.refineSubRanges(
  3113. Allocator, LaneMask,
  3114. [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
  3115. if (SR.empty()) {
  3116. SR.assign(ToMerge, Allocator);
  3117. } else {
  3118. // joinSubRegRange() destroys the merged range, so we need a copy.
  3119. LiveRange RangeCopy(ToMerge, Allocator);
  3120. joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
  3121. }
  3122. },
  3123. *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
  3124. }
  3125. bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
  3126. if (LI.valnos.size() < LargeIntervalSizeThreshold)
  3127. return false;
  3128. auto &Counter = LargeLIVisitCounter[LI.reg()];
  3129. if (Counter < LargeIntervalFreqThreshold) {
  3130. Counter++;
  3131. return false;
  3132. }
  3133. return true;
  3134. }
  3135. bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
  3136. SmallVector<VNInfo*, 16> NewVNInfo;
  3137. LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
  3138. LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
  3139. bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
  3140. JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
  3141. NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
  3142. JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
  3143. NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
  3144. LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
  3145. if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS))
  3146. return false;
  3147. // First compute NewVNInfo and the simple value mappings.
  3148. // Detect impossible conflicts early.
  3149. if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
  3150. return false;
  3151. // Some conflicts can only be resolved after all values have been mapped.
  3152. if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
  3153. return false;
  3154. // All clear, the live ranges can be merged.
  3155. if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
  3156. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  3157. // Transform lanemasks from the LHS to masks in the coalesced register and
  3158. // create initial subranges if necessary.
  3159. unsigned DstIdx = CP.getDstIdx();
  3160. if (!LHS.hasSubRanges()) {
  3161. LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
  3162. : TRI->getSubRegIndexLaneMask(DstIdx);
  3163. // LHS must support subregs or we wouldn't be in this codepath.
  3164. assert(Mask.any());
  3165. LHS.createSubRangeFrom(Allocator, Mask, LHS);
  3166. } else if (DstIdx != 0) {
  3167. // Transform LHS lanemasks to new register class if necessary.
  3168. for (LiveInterval::SubRange &R : LHS.subranges()) {
  3169. LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
  3170. R.LaneMask = Mask;
  3171. }
  3172. }
  3173. LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
  3174. << '\n');
  3175. // Determine lanemasks of RHS in the coalesced register and merge subranges.
  3176. unsigned SrcIdx = CP.getSrcIdx();
  3177. if (!RHS.hasSubRanges()) {
  3178. LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
  3179. : TRI->getSubRegIndexLaneMask(SrcIdx);
  3180. mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
  3181. } else {
  3182. // Pair up subranges and merge.
  3183. for (LiveInterval::SubRange &R : RHS.subranges()) {
  3184. LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
  3185. mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
  3186. }
  3187. }
  3188. LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
  3189. // Pruning implicit defs from subranges may result in the main range
  3190. // having stale segments.
  3191. LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
  3192. LHSVals.pruneSubRegValues(LHS, ShrinkMask);
  3193. RHSVals.pruneSubRegValues(LHS, ShrinkMask);
  3194. }
  3195. // The merging algorithm in LiveInterval::join() can't handle conflicting
  3196. // value mappings, so we need to remove any live ranges that overlap a
  3197. // CR_Replace resolution. Collect a set of end points that can be used to
  3198. // restore the live range after joining.
  3199. SmallVector<SlotIndex, 8> EndPoints;
  3200. LHSVals.pruneValues(RHSVals, EndPoints, true);
  3201. RHSVals.pruneValues(LHSVals, EndPoints, true);
  3202. // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
  3203. // registers to require trimming.
  3204. SmallVector<Register, 8> ShrinkRegs;
  3205. LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
  3206. RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
  3207. while (!ShrinkRegs.empty())
  3208. shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
  3209. // Scan and mark undef any DBG_VALUEs that would refer to a different value.
  3210. checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
  3211. // If the RHS covers any PHI locations that were tracked for debug-info, we
  3212. // must update tracking information to reflect the join.
  3213. auto RegIt = RegToPHIIdx.find(CP.getSrcReg());
  3214. if (RegIt != RegToPHIIdx.end()) {
  3215. // Iterate over all the debug instruction numbers assigned this register.
  3216. for (unsigned InstID : RegIt->second) {
  3217. auto PHIIt = PHIValToPos.find(InstID);
  3218. assert(PHIIt != PHIValToPos.end());
  3219. const SlotIndex &SI = PHIIt->second.SI;
  3220. // Does the RHS cover the position of this PHI?
  3221. auto LII = RHS.find(SI);
  3222. if (LII == RHS.end() || LII->start > SI)
  3223. continue;
  3224. // Accept two kinds of subregister movement:
  3225. // * When we merge from one register class into a larger register:
  3226. // %1:gr16 = some-inst
  3227. // ->
  3228. // %2:gr32.sub_16bit = some-inst
  3229. // * When the PHI is already in a subregister, and the larger class
  3230. // is coalesced:
  3231. // %2:gr32.sub_16bit = some-inst
  3232. // %3:gr32 = COPY %2
  3233. // ->
  3234. // %3:gr32.sub_16bit = some-inst
  3235. // Test for subregister move:
  3236. if (CP.getSrcIdx() != 0 || CP.getDstIdx() != 0)
  3237. // If we're moving between different subregisters, ignore this join.
  3238. // The PHI will not get a location, dropping variable locations.
  3239. if (PHIIt->second.SubReg && PHIIt->second.SubReg != CP.getSrcIdx())
  3240. continue;
  3241. // Update our tracking of where the PHI is.
  3242. PHIIt->second.Reg = CP.getDstReg();
  3243. // If we merge into a sub-register of a larger class (test above),
  3244. // update SubReg.
  3245. if (CP.getSrcIdx() != 0)
  3246. PHIIt->second.SubReg = CP.getSrcIdx();
  3247. }
  3248. // Rebuild the register index in RegToPHIIdx to account for PHIs tracking
  3249. // different VRegs now. Copy old collection of debug instruction numbers and
  3250. // erase the old one:
  3251. auto InstrNums = RegIt->second;
  3252. RegToPHIIdx.erase(RegIt);
  3253. // There might already be PHIs being tracked in the destination VReg. Insert
  3254. // into an existing tracking collection, or insert a new one.
  3255. RegIt = RegToPHIIdx.find(CP.getDstReg());
  3256. if (RegIt != RegToPHIIdx.end())
  3257. RegIt->second.insert(RegIt->second.end(), InstrNums.begin(),
  3258. InstrNums.end());
  3259. else
  3260. RegToPHIIdx.insert({CP.getDstReg(), InstrNums});
  3261. }
  3262. // Join RHS into LHS.
  3263. LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
  3264. // Kill flags are going to be wrong if the live ranges were overlapping.
  3265. // Eventually, we should simply clear all kill flags when computing live
  3266. // ranges. They are reinserted after register allocation.
  3267. MRI->clearKillFlags(LHS.reg());
  3268. MRI->clearKillFlags(RHS.reg());
  3269. if (!EndPoints.empty()) {
  3270. // Recompute the parts of the live range we had to remove because of
  3271. // CR_Replace conflicts.
  3272. LLVM_DEBUG({
  3273. dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
  3274. for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
  3275. dbgs() << EndPoints[i];
  3276. if (i != n-1)
  3277. dbgs() << ',';
  3278. }
  3279. dbgs() << ": " << LHS << '\n';
  3280. });
  3281. LIS->extendToIndices((LiveRange&)LHS, EndPoints);
  3282. }
  3283. return true;
  3284. }
  3285. bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
  3286. return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
  3287. }
  3288. void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF)
  3289. {
  3290. const SlotIndexes &Slots = *LIS->getSlotIndexes();
  3291. SmallVector<MachineInstr *, 8> ToInsert;
  3292. // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
  3293. // vreg => DbgValueLoc map.
  3294. auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
  3295. for (auto *X : ToInsert) {
  3296. for (const auto &Op : X->debug_operands()) {
  3297. if (Op.isReg() && Op.getReg().isVirtual())
  3298. DbgVRegToValues[Op.getReg()].push_back({Slot, X});
  3299. }
  3300. }
  3301. ToInsert.clear();
  3302. };
  3303. // Iterate over all instructions, collecting them into the ToInsert vector.
  3304. // Once a non-debug instruction is found, record the slot index of the
  3305. // collected DBG_VALUEs.
  3306. for (auto &MBB : MF) {
  3307. SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
  3308. for (auto &MI : MBB) {
  3309. if (MI.isDebugValue()) {
  3310. if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
  3311. return MO.isReg() && MO.getReg().isVirtual();
  3312. }))
  3313. ToInsert.push_back(&MI);
  3314. } else if (!MI.isDebugOrPseudoInstr()) {
  3315. CurrentSlot = Slots.getInstructionIndex(MI);
  3316. CloseNewDVRange(CurrentSlot);
  3317. }
  3318. }
  3319. // Close range of DBG_VALUEs at the end of blocks.
  3320. CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
  3321. }
  3322. // Sort all DBG_VALUEs we've seen by slot number.
  3323. for (auto &Pair : DbgVRegToValues)
  3324. llvm::sort(Pair.second);
  3325. }
  3326. void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
  3327. LiveRange &LHS,
  3328. JoinVals &LHSVals,
  3329. LiveRange &RHS,
  3330. JoinVals &RHSVals) {
  3331. auto ScanForDstReg = [&](Register Reg) {
  3332. checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
  3333. };
  3334. auto ScanForSrcReg = [&](Register Reg) {
  3335. checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
  3336. };
  3337. // Scan for potentially unsound DBG_VALUEs: examine first the register number
  3338. // Reg, and then any other vregs that may have been merged into it.
  3339. auto PerformScan = [this](Register Reg, std::function<void(Register)> Func) {
  3340. Func(Reg);
  3341. if (DbgMergedVRegNums.count(Reg))
  3342. for (Register X : DbgMergedVRegNums[Reg])
  3343. Func(X);
  3344. };
  3345. // Scan for unsound updates of both the source and destination register.
  3346. PerformScan(CP.getSrcReg(), ScanForSrcReg);
  3347. PerformScan(CP.getDstReg(), ScanForDstReg);
  3348. }
  3349. void RegisterCoalescer::checkMergingChangesDbgValuesImpl(Register Reg,
  3350. LiveRange &OtherLR,
  3351. LiveRange &RegLR,
  3352. JoinVals &RegVals) {
  3353. // Are there any DBG_VALUEs to examine?
  3354. auto VRegMapIt = DbgVRegToValues.find(Reg);
  3355. if (VRegMapIt == DbgVRegToValues.end())
  3356. return;
  3357. auto &DbgValueSet = VRegMapIt->second;
  3358. auto DbgValueSetIt = DbgValueSet.begin();
  3359. auto SegmentIt = OtherLR.begin();
  3360. bool LastUndefResult = false;
  3361. SlotIndex LastUndefIdx;
  3362. // If the "Other" register is live at a slot Idx, test whether Reg can
  3363. // safely be merged with it, or should be marked undef.
  3364. auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
  3365. &LastUndefIdx](SlotIndex Idx) -> bool {
  3366. // Our worst-case performance typically happens with asan, causing very
  3367. // many DBG_VALUEs of the same location. Cache a copy of the most recent
  3368. // result for this edge-case.
  3369. if (LastUndefIdx == Idx)
  3370. return LastUndefResult;
  3371. // If the other range was live, and Reg's was not, the register coalescer
  3372. // will not have tried to resolve any conflicts. We don't know whether
  3373. // the DBG_VALUE will refer to the same value number, so it must be made
  3374. // undef.
  3375. auto OtherIt = RegLR.find(Idx);
  3376. if (OtherIt == RegLR.end())
  3377. return true;
  3378. // Both the registers were live: examine the conflict resolution record for
  3379. // the value number Reg refers to. CR_Keep meant that this value number
  3380. // "won" and the merged register definitely refers to that value. CR_Erase
  3381. // means the value number was a redundant copy of the other value, which
  3382. // was coalesced and Reg deleted. It's safe to refer to the other register
  3383. // (which will be the source of the copy).
  3384. auto Resolution = RegVals.getResolution(OtherIt->valno->id);
  3385. LastUndefResult = Resolution != JoinVals::CR_Keep &&
  3386. Resolution != JoinVals::CR_Erase;
  3387. LastUndefIdx = Idx;
  3388. return LastUndefResult;
  3389. };
  3390. // Iterate over both the live-range of the "Other" register, and the set of
  3391. // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
  3392. // slot index. This relies on the DbgValueSet being ordered.
  3393. while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
  3394. if (DbgValueSetIt->first < SegmentIt->end) {
  3395. // "Other" is live and there is a DBG_VALUE of Reg: test if we should
  3396. // set it undef.
  3397. if (DbgValueSetIt->first >= SegmentIt->start) {
  3398. bool HasReg = DbgValueSetIt->second->hasDebugOperandForReg(Reg);
  3399. bool ShouldUndefReg = ShouldUndef(DbgValueSetIt->first);
  3400. if (HasReg && ShouldUndefReg) {
  3401. // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
  3402. DbgValueSetIt->second->setDebugValueUndef();
  3403. continue;
  3404. }
  3405. }
  3406. ++DbgValueSetIt;
  3407. } else {
  3408. ++SegmentIt;
  3409. }
  3410. }
  3411. }
  3412. namespace {
  3413. /// Information concerning MBB coalescing priority.
  3414. struct MBBPriorityInfo {
  3415. MachineBasicBlock *MBB;
  3416. unsigned Depth;
  3417. bool IsSplit;
  3418. MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
  3419. : MBB(mbb), Depth(depth), IsSplit(issplit) {}
  3420. };
  3421. } // end anonymous namespace
  3422. /// C-style comparator that sorts first based on the loop depth of the basic
  3423. /// block (the unsigned), and then on the MBB number.
  3424. ///
  3425. /// EnableGlobalCopies assumes that the primary sort key is loop depth.
  3426. static int compareMBBPriority(const MBBPriorityInfo *LHS,
  3427. const MBBPriorityInfo *RHS) {
  3428. // Deeper loops first
  3429. if (LHS->Depth != RHS->Depth)
  3430. return LHS->Depth > RHS->Depth ? -1 : 1;
  3431. // Try to unsplit critical edges next.
  3432. if (LHS->IsSplit != RHS->IsSplit)
  3433. return LHS->IsSplit ? -1 : 1;
  3434. // Prefer blocks that are more connected in the CFG. This takes care of
  3435. // the most difficult copies first while intervals are short.
  3436. unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
  3437. unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
  3438. if (cl != cr)
  3439. return cl > cr ? -1 : 1;
  3440. // As a last resort, sort by block number.
  3441. return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
  3442. }
  3443. /// \returns true if the given copy uses or defines a local live range.
  3444. static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
  3445. if (!Copy->isCopy())
  3446. return false;
  3447. if (Copy->getOperand(1).isUndef())
  3448. return false;
  3449. Register SrcReg = Copy->getOperand(1).getReg();
  3450. Register DstReg = Copy->getOperand(0).getReg();
  3451. if (Register::isPhysicalRegister(SrcReg) ||
  3452. Register::isPhysicalRegister(DstReg))
  3453. return false;
  3454. return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
  3455. || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
  3456. }
  3457. void RegisterCoalescer::lateLiveIntervalUpdate() {
  3458. for (Register reg : ToBeUpdated) {
  3459. if (!LIS->hasInterval(reg))
  3460. continue;
  3461. LiveInterval &LI = LIS->getInterval(reg);
  3462. shrinkToUses(&LI, &DeadDefs);
  3463. if (!DeadDefs.empty())
  3464. eliminateDeadDefs();
  3465. }
  3466. ToBeUpdated.clear();
  3467. }
  3468. bool RegisterCoalescer::
  3469. copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
  3470. bool Progress = false;
  3471. for (MachineInstr *&MI : CurrList) {
  3472. if (!MI)
  3473. continue;
  3474. // Skip instruction pointers that have already been erased, for example by
  3475. // dead code elimination.
  3476. if (ErasedInstrs.count(MI)) {
  3477. MI = nullptr;
  3478. continue;
  3479. }
  3480. bool Again = false;
  3481. bool Success = joinCopy(MI, Again);
  3482. Progress |= Success;
  3483. if (Success || !Again)
  3484. MI = nullptr;
  3485. }
  3486. return Progress;
  3487. }
  3488. /// Check if DstReg is a terminal node.
  3489. /// I.e., it does not have any affinity other than \p Copy.
  3490. static bool isTerminalReg(Register DstReg, const MachineInstr &Copy,
  3491. const MachineRegisterInfo *MRI) {
  3492. assert(Copy.isCopyLike());
  3493. // Check if the destination of this copy as any other affinity.
  3494. for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
  3495. if (&MI != &Copy && MI.isCopyLike())
  3496. return false;
  3497. return true;
  3498. }
  3499. bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
  3500. assert(Copy.isCopyLike());
  3501. if (!UseTerminalRule)
  3502. return false;
  3503. Register SrcReg, DstReg;
  3504. unsigned SrcSubReg = 0, DstSubReg = 0;
  3505. if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
  3506. return false;
  3507. // Check if the destination of this copy has any other affinity.
  3508. if (DstReg.isPhysical() ||
  3509. // If SrcReg is a physical register, the copy won't be coalesced.
  3510. // Ignoring it may have other side effect (like missing
  3511. // rematerialization). So keep it.
  3512. SrcReg.isPhysical() || !isTerminalReg(DstReg, Copy, MRI))
  3513. return false;
  3514. // DstReg is a terminal node. Check if it interferes with any other
  3515. // copy involving SrcReg.
  3516. const MachineBasicBlock *OrigBB = Copy.getParent();
  3517. const LiveInterval &DstLI = LIS->getInterval(DstReg);
  3518. for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
  3519. // Technically we should check if the weight of the new copy is
  3520. // interesting compared to the other one and update the weight
  3521. // of the copies accordingly. However, this would only work if
  3522. // we would gather all the copies first then coalesce, whereas
  3523. // right now we interleave both actions.
  3524. // For now, just consider the copies that are in the same block.
  3525. if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
  3526. continue;
  3527. Register OtherSrcReg, OtherReg;
  3528. unsigned OtherSrcSubReg = 0, OtherSubReg = 0;
  3529. if (!isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
  3530. OtherSubReg))
  3531. return false;
  3532. if (OtherReg == SrcReg)
  3533. OtherReg = OtherSrcReg;
  3534. // Check if OtherReg is a non-terminal.
  3535. if (Register::isPhysicalRegister(OtherReg) ||
  3536. isTerminalReg(OtherReg, MI, MRI))
  3537. continue;
  3538. // Check that OtherReg interfere with DstReg.
  3539. if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
  3540. LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
  3541. << '\n');
  3542. return true;
  3543. }
  3544. }
  3545. return false;
  3546. }
  3547. void
  3548. RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
  3549. LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
  3550. // Collect all copy-like instructions in MBB. Don't start coalescing anything
  3551. // yet, it might invalidate the iterator.
  3552. const unsigned PrevSize = WorkList.size();
  3553. if (JoinGlobalCopies) {
  3554. SmallVector<MachineInstr*, 2> LocalTerminals;
  3555. SmallVector<MachineInstr*, 2> GlobalTerminals;
  3556. // Coalesce copies bottom-up to coalesce local defs before local uses. They
  3557. // are not inherently easier to resolve, but slightly preferable until we
  3558. // have local live range splitting. In particular this is required by
  3559. // cmp+jmp macro fusion.
  3560. for (MachineInstr &MI : *MBB) {
  3561. if (!MI.isCopyLike())
  3562. continue;
  3563. bool ApplyTerminalRule = applyTerminalRule(MI);
  3564. if (isLocalCopy(&MI, LIS)) {
  3565. if (ApplyTerminalRule)
  3566. LocalTerminals.push_back(&MI);
  3567. else
  3568. LocalWorkList.push_back(&MI);
  3569. } else {
  3570. if (ApplyTerminalRule)
  3571. GlobalTerminals.push_back(&MI);
  3572. else
  3573. WorkList.push_back(&MI);
  3574. }
  3575. }
  3576. // Append the copies evicted by the terminal rule at the end of the list.
  3577. LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
  3578. WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
  3579. }
  3580. else {
  3581. SmallVector<MachineInstr*, 2> Terminals;
  3582. for (MachineInstr &MII : *MBB)
  3583. if (MII.isCopyLike()) {
  3584. if (applyTerminalRule(MII))
  3585. Terminals.push_back(&MII);
  3586. else
  3587. WorkList.push_back(&MII);
  3588. }
  3589. // Append the copies evicted by the terminal rule at the end of the list.
  3590. WorkList.append(Terminals.begin(), Terminals.end());
  3591. }
  3592. // Try coalescing the collected copies immediately, and remove the nulls.
  3593. // This prevents the WorkList from getting too large since most copies are
  3594. // joinable on the first attempt.
  3595. MutableArrayRef<MachineInstr*>
  3596. CurrList(WorkList.begin() + PrevSize, WorkList.end());
  3597. if (copyCoalesceWorkList(CurrList))
  3598. WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
  3599. nullptr), WorkList.end());
  3600. }
  3601. void RegisterCoalescer::coalesceLocals() {
  3602. copyCoalesceWorkList(LocalWorkList);
  3603. for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
  3604. if (LocalWorkList[j])
  3605. WorkList.push_back(LocalWorkList[j]);
  3606. }
  3607. LocalWorkList.clear();
  3608. }
  3609. void RegisterCoalescer::joinAllIntervals() {
  3610. LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
  3611. assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
  3612. std::vector<MBBPriorityInfo> MBBs;
  3613. MBBs.reserve(MF->size());
  3614. for (MachineBasicBlock &MBB : *MF) {
  3615. MBBs.push_back(MBBPriorityInfo(&MBB, Loops->getLoopDepth(&MBB),
  3616. JoinSplitEdges && isSplitEdge(&MBB)));
  3617. }
  3618. array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
  3619. // Coalesce intervals in MBB priority order.
  3620. unsigned CurrDepth = std::numeric_limits<unsigned>::max();
  3621. for (MBBPriorityInfo &MBB : MBBs) {
  3622. // Try coalescing the collected local copies for deeper loops.
  3623. if (JoinGlobalCopies && MBB.Depth < CurrDepth) {
  3624. coalesceLocals();
  3625. CurrDepth = MBB.Depth;
  3626. }
  3627. copyCoalesceInMBB(MBB.MBB);
  3628. }
  3629. lateLiveIntervalUpdate();
  3630. coalesceLocals();
  3631. // Joining intervals can allow other intervals to be joined. Iteratively join
  3632. // until we make no progress.
  3633. while (copyCoalesceWorkList(WorkList))
  3634. /* empty */ ;
  3635. lateLiveIntervalUpdate();
  3636. }
  3637. void RegisterCoalescer::releaseMemory() {
  3638. ErasedInstrs.clear();
  3639. WorkList.clear();
  3640. DeadDefs.clear();
  3641. InflateRegs.clear();
  3642. LargeLIVisitCounter.clear();
  3643. }
  3644. bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
  3645. LLVM_DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
  3646. << "********** Function: " << fn.getName() << '\n');
  3647. // Variables changed between a setjmp and a longjump can have undefined value
  3648. // after the longjmp. This behaviour can be observed if such a variable is
  3649. // spilled, so longjmp won't restore the value in the spill slot.
  3650. // RegisterCoalescer should not run in functions with a setjmp to avoid
  3651. // merging such undefined variables with predictable ones.
  3652. //
  3653. // TODO: Could specifically disable coalescing registers live across setjmp
  3654. // calls
  3655. if (fn.exposesReturnsTwice()) {
  3656. LLVM_DEBUG(
  3657. dbgs() << "* Skipped as it exposes funcions that returns twice.\n");
  3658. return false;
  3659. }
  3660. MF = &fn;
  3661. MRI = &fn.getRegInfo();
  3662. const TargetSubtargetInfo &STI = fn.getSubtarget();
  3663. TRI = STI.getRegisterInfo();
  3664. TII = STI.getInstrInfo();
  3665. LIS = &getAnalysis<LiveIntervals>();
  3666. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  3667. Loops = &getAnalysis<MachineLoopInfo>();
  3668. if (EnableGlobalCopies == cl::BOU_UNSET)
  3669. JoinGlobalCopies = STI.enableJoinGlobalCopies();
  3670. else
  3671. JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
  3672. // If there are PHIs tracked by debug-info, they will need updating during
  3673. // coalescing. Build an index of those PHIs to ease updating.
  3674. SlotIndexes *Slots = LIS->getSlotIndexes();
  3675. for (const auto &DebugPHI : MF->DebugPHIPositions) {
  3676. MachineBasicBlock *MBB = DebugPHI.second.MBB;
  3677. Register Reg = DebugPHI.second.Reg;
  3678. unsigned SubReg = DebugPHI.second.SubReg;
  3679. SlotIndex SI = Slots->getMBBStartIdx(MBB);
  3680. PHIValPos P = {SI, Reg, SubReg};
  3681. PHIValToPos.insert(std::make_pair(DebugPHI.first, P));
  3682. RegToPHIIdx[Reg].push_back(DebugPHI.first);
  3683. }
  3684. // The MachineScheduler does not currently require JoinSplitEdges. This will
  3685. // either be enabled unconditionally or replaced by a more general live range
  3686. // splitting optimization.
  3687. JoinSplitEdges = EnableJoinSplits;
  3688. if (VerifyCoalescing)
  3689. MF->verify(this, "Before register coalescing");
  3690. DbgVRegToValues.clear();
  3691. DbgMergedVRegNums.clear();
  3692. buildVRegToDbgValueMap(fn);
  3693. RegClassInfo.runOnMachineFunction(fn);
  3694. // Join (coalesce) intervals if requested.
  3695. if (EnableJoining)
  3696. joinAllIntervals();
  3697. // After deleting a lot of copies, register classes may be less constrained.
  3698. // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
  3699. // DPR inflation.
  3700. array_pod_sort(InflateRegs.begin(), InflateRegs.end());
  3701. InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
  3702. InflateRegs.end());
  3703. LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
  3704. << " regs.\n");
  3705. for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
  3706. Register Reg = InflateRegs[i];
  3707. if (MRI->reg_nodbg_empty(Reg))
  3708. continue;
  3709. if (MRI->recomputeRegClass(Reg)) {
  3710. LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
  3711. << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
  3712. ++NumInflated;
  3713. LiveInterval &LI = LIS->getInterval(Reg);
  3714. if (LI.hasSubRanges()) {
  3715. // If the inflated register class does not support subregisters anymore
  3716. // remove the subranges.
  3717. if (!MRI->shouldTrackSubRegLiveness(Reg)) {
  3718. LI.clearSubRanges();
  3719. } else {
  3720. #ifndef NDEBUG
  3721. LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
  3722. // If subranges are still supported, then the same subregs
  3723. // should still be supported.
  3724. for (LiveInterval::SubRange &S : LI.subranges()) {
  3725. assert((S.LaneMask & ~MaxMask).none());
  3726. }
  3727. #endif
  3728. }
  3729. }
  3730. }
  3731. }
  3732. // After coalescing, update any PHIs that are being tracked by debug-info
  3733. // with their new VReg locations.
  3734. for (auto &p : MF->DebugPHIPositions) {
  3735. auto it = PHIValToPos.find(p.first);
  3736. assert(it != PHIValToPos.end());
  3737. p.second.Reg = it->second.Reg;
  3738. p.second.SubReg = it->second.SubReg;
  3739. }
  3740. PHIValToPos.clear();
  3741. RegToPHIIdx.clear();
  3742. LLVM_DEBUG(dump());
  3743. if (VerifyCoalescing)
  3744. MF->verify(this, "After register coalescing");
  3745. return true;
  3746. }
  3747. void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
  3748. LIS->print(O, m);
  3749. }