RegisterCoalescer.cpp 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012
  1. //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the generic RegisterCoalescer interface which
  11. // is used as the common interface used by all clients and
  12. // implementations of register coalescing.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "RegisterCoalescer.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  21. #include "llvm/CodeGen/LiveRangeEdit.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineLoopInfo.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/Passes.h"
  27. #include "llvm/CodeGen/RegisterClassInfo.h"
  28. #include "llvm/CodeGen/VirtRegMap.h"
  29. #include "llvm/IR/Value.h"
  30. #include "llvm/Pass.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/Format.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Target/TargetInstrInfo.h"
  37. #include "llvm/Target/TargetMachine.h"
  38. #include "llvm/Target/TargetRegisterInfo.h"
  39. #include "llvm/Target/TargetSubtargetInfo.h"
  40. #include <algorithm>
  41. #include <cmath>
  42. using namespace llvm;
  43. #define DEBUG_TYPE "regalloc"
  44. STATISTIC(numJoins , "Number of interval joins performed");
  45. STATISTIC(numCrossRCs , "Number of cross class joins performed");
  46. STATISTIC(numCommutes , "Number of instruction commuting performed");
  47. STATISTIC(numExtends , "Number of copies extended");
  48. STATISTIC(NumReMats , "Number of instructions re-materialized");
  49. STATISTIC(NumInflated , "Number of register classes inflated");
  50. STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
  51. STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
  52. static cl::opt<bool>
  53. EnableJoining("join-liveintervals",
  54. cl::desc("Coalesce copies (default=true)"),
  55. cl::init(true));
  56. static cl::opt<bool> UseTerminalRule("terminal-rule",
  57. cl::desc("Apply the terminal rule"),
  58. cl::init(false), cl::Hidden);
  59. /// Temporary flag to test critical edge unsplitting.
  60. static cl::opt<bool>
  61. EnableJoinSplits("join-splitedges",
  62. cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
  63. /// Temporary flag to test global copy optimization.
  64. static cl::opt<cl::boolOrDefault>
  65. EnableGlobalCopies("join-globalcopies",
  66. cl::desc("Coalesce copies that span blocks (default=subtarget)"),
  67. cl::init(cl::BOU_UNSET), cl::Hidden);
  68. static cl::opt<bool>
  69. VerifyCoalescing("verify-coalescing",
  70. cl::desc("Verify machine instrs before and after register coalescing"),
  71. cl::Hidden);
  72. namespace {
  73. class RegisterCoalescer : public MachineFunctionPass,
  74. private LiveRangeEdit::Delegate {
  75. MachineFunction* MF;
  76. MachineRegisterInfo* MRI;
  77. const TargetMachine* TM;
  78. const TargetRegisterInfo* TRI;
  79. const TargetInstrInfo* TII;
  80. LiveIntervals *LIS;
  81. const MachineLoopInfo* Loops;
  82. AliasAnalysis *AA;
  83. RegisterClassInfo RegClassInfo;
  84. /// A LaneMask to remember on which subregister live ranges we need to call
  85. /// shrinkToUses() later.
  86. unsigned ShrinkMask;
  87. /// True if the main range of the currently coalesced intervals should be
  88. /// checked for smaller live intervals.
  89. bool ShrinkMainRange;
  90. /// \brief True if the coalescer should aggressively coalesce global copies
  91. /// in favor of keeping local copies.
  92. bool JoinGlobalCopies;
  93. /// \brief True if the coalescer should aggressively coalesce fall-thru
  94. /// blocks exclusively containing copies.
  95. bool JoinSplitEdges;
  96. /// Copy instructions yet to be coalesced.
  97. SmallVector<MachineInstr*, 8> WorkList;
  98. SmallVector<MachineInstr*, 8> LocalWorkList;
  99. /// Set of instruction pointers that have been erased, and
  100. /// that may be present in WorkList.
  101. SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
  102. /// Dead instructions that are about to be deleted.
  103. SmallVector<MachineInstr*, 8> DeadDefs;
  104. /// Virtual registers to be considered for register class inflation.
  105. SmallVector<unsigned, 8> InflateRegs;
  106. /// Recursively eliminate dead defs in DeadDefs.
  107. void eliminateDeadDefs();
  108. /// LiveRangeEdit callback for eliminateDeadDefs().
  109. void LRE_WillEraseInstruction(MachineInstr *MI) override;
  110. /// Coalesce the LocalWorkList.
  111. void coalesceLocals();
  112. /// Join compatible live intervals
  113. void joinAllIntervals();
  114. /// Coalesce copies in the specified MBB, putting
  115. /// copies that cannot yet be coalesced into WorkList.
  116. void copyCoalesceInMBB(MachineBasicBlock *MBB);
  117. /// Tries to coalesce all copies in CurrList. Returns true if any progress
  118. /// was made.
  119. bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
  120. /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
  121. /// src/dst of the copy instruction CopyMI. This returns true if the copy
  122. /// was successfully coalesced away. If it is not currently possible to
  123. /// coalesce this interval, but it may be possible if other things get
  124. /// coalesced, then it returns true by reference in 'Again'.
  125. bool joinCopy(MachineInstr *TheCopy, bool &Again);
  126. /// Attempt to join these two intervals. On failure, this
  127. /// returns false. The output "SrcInt" will not have been modified, so we
  128. /// can use this information below to update aliases.
  129. bool joinIntervals(CoalescerPair &CP);
  130. /// Attempt joining two virtual registers. Return true on success.
  131. bool joinVirtRegs(CoalescerPair &CP);
  132. /// Attempt joining with a reserved physreg.
  133. bool joinReservedPhysReg(CoalescerPair &CP);
  134. /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
  135. /// Subranges in @p LI which only partially interfere with the desired
  136. /// LaneMask are split as necessary. @p LaneMask are the lanes that
  137. /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
  138. /// lanemasks already adjusted to the coalesced register.
  139. /// @returns false if live range conflicts couldn't get resolved.
  140. bool mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
  141. unsigned LaneMask, CoalescerPair &CP);
  142. /// Join the liveranges of two subregisters. Joins @p RRange into
  143. /// @p LRange, @p RRange may be invalid afterwards.
  144. /// @returns false if live range conflicts couldn't get resolved.
  145. bool joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
  146. unsigned LaneMask, const CoalescerPair &CP);
  147. /// We found a non-trivially-coalescable copy. If the source value number is
  148. /// defined by a copy from the destination reg see if we can merge these two
  149. /// destination reg valno# into a single value number, eliminating a copy.
  150. /// This returns true if an interval was modified.
  151. bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
  152. /// Return true if there are definitions of IntB
  153. /// other than BValNo val# that can reach uses of AValno val# of IntA.
  154. bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
  155. VNInfo *AValNo, VNInfo *BValNo);
  156. /// We found a non-trivially-coalescable copy.
  157. /// If the source value number is defined by a commutable instruction and
  158. /// its other operand is coalesced to the copy dest register, see if we
  159. /// can transform the copy into a noop by commuting the definition.
  160. /// This returns true if an interval was modified.
  161. bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
  162. /// If the source of a copy is defined by a
  163. /// trivial computation, replace the copy by rematerialize the definition.
  164. bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
  165. bool &IsDefCopy);
  166. /// Return true if a copy involving a physreg should be joined.
  167. bool canJoinPhys(const CoalescerPair &CP);
  168. /// Replace all defs and uses of SrcReg to DstReg and update the subregister
  169. /// number if it is not zero. If DstReg is a physical register and the
  170. /// existing subregister number of the def / use being updated is not zero,
  171. /// make sure to set it to the correct physical subregister.
  172. void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
  173. /// Handle copies of undef values.
  174. /// Returns true if @p CopyMI was a copy of an undef value and eliminated.
  175. bool eliminateUndefCopy(MachineInstr *CopyMI);
  176. /// Check whether or not we should apply the terminal rule on the
  177. /// destination (Dst) of \p Copy.
  178. /// When the terminal rule applies, Copy is not profitable to
  179. /// coalesce.
  180. /// Dst is terminal if it has exactly one affinity (Dst, Src) and
  181. /// at least one interference (Dst, Dst2). If Dst is terminal, the
  182. /// terminal rule consists in checking that at least one of
  183. /// interfering node, say Dst2, has an affinity of equal or greater
  184. /// weight with Src.
  185. /// In that case, Dst2 and Dst will not be able to be both coalesced
  186. /// with Src. Since Dst2 exposes more coalescing opportunities than
  187. /// Dst, we can drop \p Copy.
  188. bool applyTerminalRule(const MachineInstr &Copy) const;
  189. /// Check whether or not \p LI is composed by multiple connected
  190. /// components and if that is the case, fix that.
  191. void splitNewRanges(LiveInterval *LI) {
  192. ConnectedVNInfoEqClasses ConEQ(*LIS);
  193. unsigned NumComps = ConEQ.Classify(LI);
  194. if (NumComps <= 1)
  195. return;
  196. SmallVector<LiveInterval*, 8> NewComps(1, LI);
  197. for (unsigned i = 1; i != NumComps; ++i) {
  198. unsigned VReg = MRI->createVirtualRegister(MRI->getRegClass(LI->reg));
  199. NewComps.push_back(&LIS->createEmptyInterval(VReg));
  200. }
  201. ConEQ.Distribute(&NewComps[0], *MRI);
  202. }
  203. /// Wrapper method for \see LiveIntervals::shrinkToUses.
  204. /// This method does the proper fixing of the live-ranges when the afore
  205. /// mentioned method returns true.
  206. void shrinkToUses(LiveInterval *LI,
  207. SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
  208. if (LIS->shrinkToUses(LI, Dead))
  209. // We may have created multiple connected components, split them.
  210. splitNewRanges(LI);
  211. }
  212. public:
  213. static char ID; ///< Class identification, replacement for typeinfo
  214. RegisterCoalescer() : MachineFunctionPass(ID) {
  215. initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
  216. }
  217. void getAnalysisUsage(AnalysisUsage &AU) const override;
  218. void releaseMemory() override;
  219. /// This is the pass entry point.
  220. bool runOnMachineFunction(MachineFunction&) override;
  221. /// Implement the dump method.
  222. void print(raw_ostream &O, const Module* = nullptr) const override;
  223. };
  224. } // end anonymous namespace
  225. char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
  226. INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
  227. "Simple Register Coalescing", false, false)
  228. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  229. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  230. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  231. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  232. INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
  233. "Simple Register Coalescing", false, false)
  234. char RegisterCoalescer::ID = 0;
  235. static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
  236. unsigned &Src, unsigned &Dst,
  237. unsigned &SrcSub, unsigned &DstSub) {
  238. if (MI->isCopy()) {
  239. Dst = MI->getOperand(0).getReg();
  240. DstSub = MI->getOperand(0).getSubReg();
  241. Src = MI->getOperand(1).getReg();
  242. SrcSub = MI->getOperand(1).getSubReg();
  243. } else if (MI->isSubregToReg()) {
  244. Dst = MI->getOperand(0).getReg();
  245. DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
  246. MI->getOperand(3).getImm());
  247. Src = MI->getOperand(2).getReg();
  248. SrcSub = MI->getOperand(2).getSubReg();
  249. } else
  250. return false;
  251. return true;
  252. }
  253. /// Return true if this block should be vacated by the coalescer to eliminate
  254. /// branches. The important cases to handle in the coalescer are critical edges
  255. /// split during phi elimination which contain only copies. Simple blocks that
  256. /// contain non-branches should also be vacated, but this can be handled by an
  257. /// earlier pass similar to early if-conversion.
  258. static bool isSplitEdge(const MachineBasicBlock *MBB) {
  259. if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
  260. return false;
  261. for (const auto &MI : *MBB) {
  262. if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
  263. return false;
  264. }
  265. return true;
  266. }
  267. bool CoalescerPair::setRegisters(const MachineInstr *MI) {
  268. SrcReg = DstReg = 0;
  269. SrcIdx = DstIdx = 0;
  270. NewRC = nullptr;
  271. Flipped = CrossClass = false;
  272. unsigned Src, Dst, SrcSub, DstSub;
  273. if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
  274. return false;
  275. Partial = SrcSub || DstSub;
  276. // If one register is a physreg, it must be Dst.
  277. if (TargetRegisterInfo::isPhysicalRegister(Src)) {
  278. if (TargetRegisterInfo::isPhysicalRegister(Dst))
  279. return false;
  280. std::swap(Src, Dst);
  281. std::swap(SrcSub, DstSub);
  282. Flipped = true;
  283. }
  284. const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
  285. if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
  286. // Eliminate DstSub on a physreg.
  287. if (DstSub) {
  288. Dst = TRI.getSubReg(Dst, DstSub);
  289. if (!Dst) return false;
  290. DstSub = 0;
  291. }
  292. // Eliminate SrcSub by picking a corresponding Dst superregister.
  293. if (SrcSub) {
  294. Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
  295. if (!Dst) return false;
  296. } else if (!MRI.getRegClass(Src)->contains(Dst)) {
  297. return false;
  298. }
  299. } else {
  300. // Both registers are virtual.
  301. const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
  302. const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
  303. // Both registers have subreg indices.
  304. if (SrcSub && DstSub) {
  305. // Copies between different sub-registers are never coalescable.
  306. if (Src == Dst && SrcSub != DstSub)
  307. return false;
  308. NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
  309. SrcIdx, DstIdx);
  310. if (!NewRC)
  311. return false;
  312. } else if (DstSub) {
  313. // SrcReg will be merged with a sub-register of DstReg.
  314. SrcIdx = DstSub;
  315. NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
  316. } else if (SrcSub) {
  317. // DstReg will be merged with a sub-register of SrcReg.
  318. DstIdx = SrcSub;
  319. NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
  320. } else {
  321. // This is a straight copy without sub-registers.
  322. NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
  323. }
  324. // The combined constraint may be impossible to satisfy.
  325. if (!NewRC)
  326. return false;
  327. // Prefer SrcReg to be a sub-register of DstReg.
  328. // FIXME: Coalescer should support subregs symmetrically.
  329. if (DstIdx && !SrcIdx) {
  330. std::swap(Src, Dst);
  331. std::swap(SrcIdx, DstIdx);
  332. Flipped = !Flipped;
  333. }
  334. CrossClass = NewRC != DstRC || NewRC != SrcRC;
  335. }
  336. // Check our invariants
  337. assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
  338. assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
  339. "Cannot have a physical SubIdx");
  340. SrcReg = Src;
  341. DstReg = Dst;
  342. return true;
  343. }
  344. bool CoalescerPair::flip() {
  345. if (TargetRegisterInfo::isPhysicalRegister(DstReg))
  346. return false;
  347. std::swap(SrcReg, DstReg);
  348. std::swap(SrcIdx, DstIdx);
  349. Flipped = !Flipped;
  350. return true;
  351. }
  352. bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
  353. if (!MI)
  354. return false;
  355. unsigned Src, Dst, SrcSub, DstSub;
  356. if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
  357. return false;
  358. // Find the virtual register that is SrcReg.
  359. if (Dst == SrcReg) {
  360. std::swap(Src, Dst);
  361. std::swap(SrcSub, DstSub);
  362. } else if (Src != SrcReg) {
  363. return false;
  364. }
  365. // Now check that Dst matches DstReg.
  366. if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
  367. if (!TargetRegisterInfo::isPhysicalRegister(Dst))
  368. return false;
  369. assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
  370. // DstSub could be set for a physreg from INSERT_SUBREG.
  371. if (DstSub)
  372. Dst = TRI.getSubReg(Dst, DstSub);
  373. // Full copy of Src.
  374. if (!SrcSub)
  375. return DstReg == Dst;
  376. // This is a partial register copy. Check that the parts match.
  377. return TRI.getSubReg(DstReg, SrcSub) == Dst;
  378. } else {
  379. // DstReg is virtual.
  380. if (DstReg != Dst)
  381. return false;
  382. // Registers match, do the subregisters line up?
  383. return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
  384. TRI.composeSubRegIndices(DstIdx, DstSub);
  385. }
  386. }
  387. void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
  388. AU.setPreservesCFG();
  389. AU.addRequired<AliasAnalysis>();
  390. AU.addRequired<LiveIntervals>();
  391. AU.addPreserved<LiveIntervals>();
  392. AU.addPreserved<SlotIndexes>();
  393. AU.addRequired<MachineLoopInfo>();
  394. AU.addPreserved<MachineLoopInfo>();
  395. AU.addPreservedID(MachineDominatorsID);
  396. MachineFunctionPass::getAnalysisUsage(AU);
  397. }
  398. void RegisterCoalescer::eliminateDeadDefs() {
  399. SmallVector<unsigned, 8> NewRegs;
  400. LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
  401. nullptr, this).eliminateDeadDefs(DeadDefs);
  402. }
  403. void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
  404. // MI may be in WorkList. Make sure we don't visit it.
  405. ErasedInstrs.insert(MI);
  406. }
  407. bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
  408. MachineInstr *CopyMI) {
  409. assert(!CP.isPartial() && "This doesn't work for partial copies.");
  410. assert(!CP.isPhys() && "This doesn't work for physreg copies.");
  411. LiveInterval &IntA =
  412. LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
  413. LiveInterval &IntB =
  414. LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
  415. SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
  416. // We have a non-trivially-coalescable copy with IntA being the source and
  417. // IntB being the dest, thus this defines a value number in IntB. If the
  418. // source value number (in IntA) is defined by a copy from B, see if we can
  419. // merge these two pieces of B into a single value number, eliminating a copy.
  420. // For example:
  421. //
  422. // A3 = B0
  423. // ...
  424. // B1 = A3 <- this copy
  425. //
  426. // In this case, B0 can be extended to where the B1 copy lives, allowing the
  427. // B1 value number to be replaced with B0 (which simplifies the B
  428. // liveinterval).
  429. // BValNo is a value number in B that is defined by a copy from A. 'B1' in
  430. // the example above.
  431. LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
  432. if (BS == IntB.end()) return false;
  433. VNInfo *BValNo = BS->valno;
  434. // Get the location that B is defined at. Two options: either this value has
  435. // an unknown definition point or it is defined at CopyIdx. If unknown, we
  436. // can't process it.
  437. if (BValNo->def != CopyIdx) return false;
  438. // AValNo is the value number in A that defines the copy, A3 in the example.
  439. SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
  440. LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
  441. // The live segment might not exist after fun with physreg coalescing.
  442. if (AS == IntA.end()) return false;
  443. VNInfo *AValNo = AS->valno;
  444. // If AValNo is defined as a copy from IntB, we can potentially process this.
  445. // Get the instruction that defines this value number.
  446. MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
  447. // Don't allow any partial copies, even if isCoalescable() allows them.
  448. if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
  449. return false;
  450. // Get the Segment in IntB that this value number starts with.
  451. LiveInterval::iterator ValS =
  452. IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
  453. if (ValS == IntB.end())
  454. return false;
  455. // Make sure that the end of the live segment is inside the same block as
  456. // CopyMI.
  457. MachineInstr *ValSEndInst =
  458. LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
  459. if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
  460. return false;
  461. // Okay, we now know that ValS ends in the same block that the CopyMI
  462. // live-range starts. If there are no intervening live segments between them
  463. // in IntB, we can merge them.
  464. if (ValS+1 != BS) return false;
  465. DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
  466. SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
  467. // We are about to delete CopyMI, so need to remove it as the 'instruction
  468. // that defines this value #'. Update the valnum with the new defining
  469. // instruction #.
  470. BValNo->def = FillerStart;
  471. // Okay, we can merge them. We need to insert a new liverange:
  472. // [ValS.end, BS.begin) of either value number, then we merge the
  473. // two value numbers.
  474. IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
  475. // Okay, merge "B1" into the same value number as "B0".
  476. if (BValNo != ValS->valno)
  477. IntB.MergeValueNumberInto(BValNo, ValS->valno);
  478. // Do the same for the subregister segments.
  479. for (LiveInterval::SubRange &S : IntB.subranges()) {
  480. VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
  481. S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
  482. VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
  483. if (SubBValNo != SubValSNo)
  484. S.MergeValueNumberInto(SubBValNo, SubValSNo);
  485. }
  486. DEBUG(dbgs() << " result = " << IntB << '\n');
  487. // If the source instruction was killing the source register before the
  488. // merge, unset the isKill marker given the live range has been extended.
  489. int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
  490. if (UIdx != -1) {
  491. ValSEndInst->getOperand(UIdx).setIsKill(false);
  492. }
  493. // Rewrite the copy. If the copy instruction was killing the destination
  494. // register before the merge, find the last use and trim the live range. That
  495. // will also add the isKill marker.
  496. CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
  497. if (AS->end == CopyIdx)
  498. shrinkToUses(&IntA);
  499. ++numExtends;
  500. return true;
  501. }
  502. bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
  503. LiveInterval &IntB,
  504. VNInfo *AValNo,
  505. VNInfo *BValNo) {
  506. // If AValNo has PHI kills, conservatively assume that IntB defs can reach
  507. // the PHI values.
  508. if (LIS->hasPHIKill(IntA, AValNo))
  509. return true;
  510. for (LiveRange::Segment &ASeg : IntA.segments) {
  511. if (ASeg.valno != AValNo) continue;
  512. LiveInterval::iterator BI =
  513. std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
  514. if (BI != IntB.begin())
  515. --BI;
  516. for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
  517. if (BI->valno == BValNo)
  518. continue;
  519. if (BI->start <= ASeg.start && BI->end > ASeg.start)
  520. return true;
  521. if (BI->start > ASeg.start && BI->start < ASeg.end)
  522. return true;
  523. }
  524. }
  525. return false;
  526. }
  527. /// Copy segements with value number @p SrcValNo from liverange @p Src to live
  528. /// range @Dst and use value number @p DstValNo there.
  529. static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
  530. const LiveRange &Src, const VNInfo *SrcValNo)
  531. {
  532. for (const LiveRange::Segment &S : Src.segments) {
  533. if (S.valno != SrcValNo)
  534. continue;
  535. Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
  536. }
  537. }
  538. bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
  539. MachineInstr *CopyMI) {
  540. assert(!CP.isPhys());
  541. LiveInterval &IntA =
  542. LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
  543. LiveInterval &IntB =
  544. LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
  545. // We found a non-trivially-coalescable copy with IntA being the source and
  546. // IntB being the dest, thus this defines a value number in IntB. If the
  547. // source value number (in IntA) is defined by a commutable instruction and
  548. // its other operand is coalesced to the copy dest register, see if we can
  549. // transform the copy into a noop by commuting the definition. For example,
  550. //
  551. // A3 = op A2 B0<kill>
  552. // ...
  553. // B1 = A3 <- this copy
  554. // ...
  555. // = op A3 <- more uses
  556. //
  557. // ==>
  558. //
  559. // B2 = op B0 A2<kill>
  560. // ...
  561. // B1 = B2 <- now an identity copy
  562. // ...
  563. // = op B2 <- more uses
  564. // BValNo is a value number in B that is defined by a copy from A. 'B1' in
  565. // the example above.
  566. SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
  567. VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
  568. assert(BValNo != nullptr && BValNo->def == CopyIdx);
  569. // AValNo is the value number in A that defines the copy, A3 in the example.
  570. VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
  571. assert(AValNo && !AValNo->isUnused() && "COPY source not live");
  572. if (AValNo->isPHIDef())
  573. return false;
  574. MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
  575. if (!DefMI)
  576. return false;
  577. if (!DefMI->isCommutable())
  578. return false;
  579. // If DefMI is a two-address instruction then commuting it will change the
  580. // destination register.
  581. int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
  582. assert(DefIdx != -1);
  583. unsigned UseOpIdx;
  584. if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
  585. return false;
  586. unsigned Op1, Op2, NewDstIdx;
  587. if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
  588. return false;
  589. if (Op1 == UseOpIdx)
  590. NewDstIdx = Op2;
  591. else if (Op2 == UseOpIdx)
  592. NewDstIdx = Op1;
  593. else
  594. return false;
  595. MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
  596. unsigned NewReg = NewDstMO.getReg();
  597. if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
  598. return false;
  599. // Make sure there are no other definitions of IntB that would reach the
  600. // uses which the new definition can reach.
  601. if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
  602. return false;
  603. // If some of the uses of IntA.reg is already coalesced away, return false.
  604. // It's not possible to determine whether it's safe to perform the coalescing.
  605. for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
  606. MachineInstr *UseMI = MO.getParent();
  607. unsigned OpNo = &MO - &UseMI->getOperand(0);
  608. SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
  609. LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
  610. if (US == IntA.end() || US->valno != AValNo)
  611. continue;
  612. // If this use is tied to a def, we can't rewrite the register.
  613. if (UseMI->isRegTiedToDefOperand(OpNo))
  614. return false;
  615. }
  616. DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
  617. << *DefMI);
  618. // At this point we have decided that it is legal to do this
  619. // transformation. Start by commuting the instruction.
  620. MachineBasicBlock *MBB = DefMI->getParent();
  621. MachineInstr *NewMI = TII->commuteInstruction(DefMI);
  622. if (!NewMI)
  623. return false;
  624. if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
  625. TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
  626. !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
  627. return false;
  628. if (NewMI != DefMI) {
  629. LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
  630. MachineBasicBlock::iterator Pos = DefMI;
  631. MBB->insert(Pos, NewMI);
  632. MBB->erase(DefMI);
  633. }
  634. // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
  635. // A = or A, B
  636. // ...
  637. // B = A
  638. // ...
  639. // C = A<kill>
  640. // ...
  641. // = B
  642. // Update uses of IntA of the specific Val# with IntB.
  643. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
  644. UE = MRI->use_end();
  645. UI != UE; /* ++UI is below because of possible MI removal */) {
  646. MachineOperand &UseMO = *UI;
  647. ++UI;
  648. if (UseMO.isUndef())
  649. continue;
  650. MachineInstr *UseMI = UseMO.getParent();
  651. if (UseMI->isDebugValue()) {
  652. // FIXME These don't have an instruction index. Not clear we have enough
  653. // info to decide whether to do this replacement or not. For now do it.
  654. UseMO.setReg(NewReg);
  655. continue;
  656. }
  657. SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
  658. LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
  659. assert(US != IntA.end() && "Use must be live");
  660. if (US->valno != AValNo)
  661. continue;
  662. // Kill flags are no longer accurate. They are recomputed after RA.
  663. UseMO.setIsKill(false);
  664. if (TargetRegisterInfo::isPhysicalRegister(NewReg))
  665. UseMO.substPhysReg(NewReg, *TRI);
  666. else
  667. UseMO.setReg(NewReg);
  668. if (UseMI == CopyMI)
  669. continue;
  670. if (!UseMI->isCopy())
  671. continue;
  672. if (UseMI->getOperand(0).getReg() != IntB.reg ||
  673. UseMI->getOperand(0).getSubReg())
  674. continue;
  675. // This copy will become a noop. If it's defining a new val#, merge it into
  676. // BValNo.
  677. SlotIndex DefIdx = UseIdx.getRegSlot();
  678. VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
  679. if (!DVNI)
  680. continue;
  681. DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
  682. assert(DVNI->def == DefIdx);
  683. BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
  684. for (LiveInterval::SubRange &S : IntB.subranges()) {
  685. VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
  686. if (!SubDVNI)
  687. continue;
  688. VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
  689. assert(SubBValNo->def == CopyIdx);
  690. S.MergeValueNumberInto(SubDVNI, SubBValNo);
  691. }
  692. ErasedInstrs.insert(UseMI);
  693. LIS->RemoveMachineInstrFromMaps(UseMI);
  694. UseMI->eraseFromParent();
  695. }
  696. // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
  697. // is updated.
  698. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  699. if (IntB.hasSubRanges()) {
  700. if (!IntA.hasSubRanges()) {
  701. unsigned Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
  702. IntA.createSubRangeFrom(Allocator, Mask, IntA);
  703. }
  704. SlotIndex AIdx = CopyIdx.getRegSlot(true);
  705. for (LiveInterval::SubRange &SA : IntA.subranges()) {
  706. VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
  707. assert(ASubValNo != nullptr);
  708. unsigned AMask = SA.LaneMask;
  709. for (LiveInterval::SubRange &SB : IntB.subranges()) {
  710. unsigned BMask = SB.LaneMask;
  711. unsigned Common = BMask & AMask;
  712. if (Common == 0)
  713. continue;
  714. DEBUG(
  715. dbgs() << format("\t\tCopy+Merge %04X into %04X\n", BMask, Common));
  716. unsigned BRest = BMask & ~AMask;
  717. LiveInterval::SubRange *CommonRange;
  718. if (BRest != 0) {
  719. SB.LaneMask = BRest;
  720. DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", BRest));
  721. // Duplicate SubRange for newly merged common stuff.
  722. CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
  723. } else {
  724. // We van reuse the L SubRange.
  725. SB.LaneMask = Common;
  726. CommonRange = &SB;
  727. }
  728. LiveRange RangeCopy(SB, Allocator);
  729. VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
  730. assert(BSubValNo->def == CopyIdx);
  731. BSubValNo->def = ASubValNo->def;
  732. addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
  733. AMask &= ~BMask;
  734. }
  735. if (AMask != 0) {
  736. DEBUG(dbgs() << format("\t\tNew Lane %04X\n", AMask));
  737. LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
  738. VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
  739. addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
  740. }
  741. }
  742. }
  743. BValNo->def = AValNo->def;
  744. addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
  745. DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
  746. LIS->removeVRegDefAt(IntA, AValNo->def);
  747. DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
  748. ++numCommutes;
  749. return true;
  750. }
  751. /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
  752. /// defining a subregister.
  753. static bool definesFullReg(const MachineInstr &MI, unsigned Reg) {
  754. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
  755. "This code cannot handle physreg aliasing");
  756. for (const MachineOperand &Op : MI.operands()) {
  757. if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
  758. continue;
  759. // Return true if we define the full register or don't care about the value
  760. // inside other subregisters.
  761. if (Op.getSubReg() == 0 || Op.isUndef())
  762. return true;
  763. }
  764. return false;
  765. }
  766. bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
  767. MachineInstr *CopyMI,
  768. bool &IsDefCopy) {
  769. IsDefCopy = false;
  770. unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
  771. unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
  772. unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
  773. unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
  774. if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
  775. return false;
  776. LiveInterval &SrcInt = LIS->getInterval(SrcReg);
  777. SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
  778. VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
  779. assert(ValNo && "CopyMI input register not live");
  780. if (ValNo->isPHIDef() || ValNo->isUnused())
  781. return false;
  782. MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
  783. if (!DefMI)
  784. return false;
  785. if (DefMI->isCopyLike()) {
  786. IsDefCopy = true;
  787. return false;
  788. }
  789. if (!TII->isAsCheapAsAMove(DefMI))
  790. return false;
  791. if (!TII->isTriviallyReMaterializable(DefMI, AA))
  792. return false;
  793. if (!definesFullReg(*DefMI, SrcReg))
  794. return false;
  795. bool SawStore = false;
  796. if (!DefMI->isSafeToMove(AA, SawStore))
  797. return false;
  798. const MCInstrDesc &MCID = DefMI->getDesc();
  799. if (MCID.getNumDefs() != 1)
  800. return false;
  801. // Only support subregister destinations when the def is read-undef.
  802. MachineOperand &DstOperand = CopyMI->getOperand(0);
  803. unsigned CopyDstReg = DstOperand.getReg();
  804. if (DstOperand.getSubReg() && !DstOperand.isUndef())
  805. return false;
  806. // If both SrcIdx and DstIdx are set, correct rematerialization would widen
  807. // the register substantially (beyond both source and dest size). This is bad
  808. // for performance since it can cascade through a function, introducing many
  809. // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
  810. // around after a few subreg copies).
  811. if (SrcIdx && DstIdx)
  812. return false;
  813. const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
  814. if (!DefMI->isImplicitDef()) {
  815. if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
  816. unsigned NewDstReg = DstReg;
  817. unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
  818. DefMI->getOperand(0).getSubReg());
  819. if (NewDstIdx)
  820. NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
  821. // Finally, make sure that the physical subregister that will be
  822. // constructed later is permitted for the instruction.
  823. if (!DefRC->contains(NewDstReg))
  824. return false;
  825. } else {
  826. // Theoretically, some stack frame reference could exist. Just make sure
  827. // it hasn't actually happened.
  828. assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
  829. "Only expect to deal with virtual or physical registers");
  830. }
  831. }
  832. MachineBasicBlock *MBB = CopyMI->getParent();
  833. MachineBasicBlock::iterator MII =
  834. std::next(MachineBasicBlock::iterator(CopyMI));
  835. TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
  836. MachineInstr *NewMI = std::prev(MII);
  837. // In a situation like the following:
  838. // %vreg0:subreg = instr ; DefMI, subreg = DstIdx
  839. // %vreg1 = copy %vreg0:subreg ; CopyMI, SrcIdx = 0
  840. // instead of widening %vreg1 to the register class of %vreg0 simply do:
  841. // %vreg1 = instr
  842. const TargetRegisterClass *NewRC = CP.getNewRC();
  843. if (DstIdx != 0) {
  844. MachineOperand &DefMO = NewMI->getOperand(0);
  845. if (DefMO.getSubReg() == DstIdx) {
  846. assert(SrcIdx == 0 && CP.isFlipped()
  847. && "Shouldn't have SrcIdx+DstIdx at this point");
  848. const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
  849. const TargetRegisterClass *CommonRC =
  850. TRI->getCommonSubClass(DefRC, DstRC);
  851. if (CommonRC != nullptr) {
  852. NewRC = CommonRC;
  853. DstIdx = 0;
  854. DefMO.setSubReg(0);
  855. }
  856. }
  857. }
  858. LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
  859. CopyMI->eraseFromParent();
  860. ErasedInstrs.insert(CopyMI);
  861. // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
  862. // We need to remember these so we can add intervals once we insert
  863. // NewMI into SlotIndexes.
  864. SmallVector<unsigned, 4> NewMIImplDefs;
  865. for (unsigned i = NewMI->getDesc().getNumOperands(),
  866. e = NewMI->getNumOperands(); i != e; ++i) {
  867. MachineOperand &MO = NewMI->getOperand(i);
  868. if (MO.isReg() && MO.isDef()) {
  869. assert(MO.isImplicit() && MO.isDead() &&
  870. TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
  871. NewMIImplDefs.push_back(MO.getReg());
  872. }
  873. }
  874. if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
  875. unsigned NewIdx = NewMI->getOperand(0).getSubReg();
  876. if (DefRC != nullptr) {
  877. if (NewIdx)
  878. NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
  879. else
  880. NewRC = TRI->getCommonSubClass(NewRC, DefRC);
  881. assert(NewRC && "subreg chosen for remat incompatible with instruction");
  882. }
  883. MRI->setRegClass(DstReg, NewRC);
  884. updateRegDefsUses(DstReg, DstReg, DstIdx);
  885. NewMI->getOperand(0).setSubReg(NewIdx);
  886. } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
  887. // The New instruction may be defining a sub-register of what's actually
  888. // been asked for. If so it must implicitly define the whole thing.
  889. assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
  890. "Only expect virtual or physical registers in remat");
  891. NewMI->getOperand(0).setIsDead(true);
  892. NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
  893. true /*IsDef*/,
  894. true /*IsImp*/,
  895. false /*IsKill*/));
  896. // Record small dead def live-ranges for all the subregisters
  897. // of the destination register.
  898. // Otherwise, variables that live through may miss some
  899. // interferences, thus creating invalid allocation.
  900. // E.g., i386 code:
  901. // vreg1 = somedef ; vreg1 GR8
  902. // vreg2 = remat ; vreg2 GR32
  903. // CL = COPY vreg2.sub_8bit
  904. // = somedef vreg1 ; vreg1 GR8
  905. // =>
  906. // vreg1 = somedef ; vreg1 GR8
  907. // ECX<def, dead> = remat ; CL<imp-def>
  908. // = somedef vreg1 ; vreg1 GR8
  909. // vreg1 will see the inteferences with CL but not with CH since
  910. // no live-ranges would have been created for ECX.
  911. // Fix that!
  912. SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
  913. for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
  914. Units.isValid(); ++Units)
  915. if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
  916. LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
  917. }
  918. if (NewMI->getOperand(0).getSubReg())
  919. NewMI->getOperand(0).setIsUndef();
  920. // CopyMI may have implicit operands, transfer them over to the newly
  921. // rematerialized instruction. And update implicit def interval valnos.
  922. for (unsigned i = CopyMI->getDesc().getNumOperands(),
  923. e = CopyMI->getNumOperands(); i != e; ++i) {
  924. MachineOperand &MO = CopyMI->getOperand(i);
  925. if (MO.isReg()) {
  926. assert(MO.isImplicit() && "No explicit operands after implict operands.");
  927. // Discard VReg implicit defs.
  928. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
  929. NewMI->addOperand(MO);
  930. }
  931. }
  932. }
  933. SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
  934. for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
  935. unsigned Reg = NewMIImplDefs[i];
  936. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  937. if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
  938. LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
  939. }
  940. DEBUG(dbgs() << "Remat: " << *NewMI);
  941. ++NumReMats;
  942. // The source interval can become smaller because we removed a use.
  943. shrinkToUses(&SrcInt, &DeadDefs);
  944. if (!DeadDefs.empty()) {
  945. // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
  946. // to describe DstReg instead.
  947. for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
  948. MachineInstr *UseMI = UseMO.getParent();
  949. if (UseMI->isDebugValue()) {
  950. UseMO.setReg(DstReg);
  951. DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
  952. }
  953. }
  954. eliminateDeadDefs();
  955. }
  956. return true;
  957. }
  958. bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
  959. // ProcessImpicitDefs may leave some copies of <undef> values, it only removes
  960. // local variables. When we have a copy like:
  961. //
  962. // %vreg1 = COPY %vreg2<undef>
  963. //
  964. // We delete the copy and remove the corresponding value number from %vreg1.
  965. // Any uses of that value number are marked as <undef>.
  966. // Note that we do not query CoalescerPair here but redo isMoveInstr as the
  967. // CoalescerPair may have a new register class with adjusted subreg indices
  968. // at this point.
  969. unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
  970. isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
  971. SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
  972. const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
  973. // CopyMI is undef iff SrcReg is not live before the instruction.
  974. if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
  975. unsigned SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
  976. for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
  977. if ((SR.LaneMask & SrcMask) == 0)
  978. continue;
  979. if (SR.liveAt(Idx))
  980. return false;
  981. }
  982. } else if (SrcLI.liveAt(Idx))
  983. return false;
  984. DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
  985. // Remove any DstReg segments starting at the instruction.
  986. LiveInterval &DstLI = LIS->getInterval(DstReg);
  987. SlotIndex RegIndex = Idx.getRegSlot();
  988. // Remove value or merge with previous one in case of a subregister def.
  989. if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
  990. VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
  991. DstLI.MergeValueNumberInto(VNI, PrevVNI);
  992. // The affected subregister segments can be removed.
  993. unsigned DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
  994. for (LiveInterval::SubRange &SR : DstLI.subranges()) {
  995. if ((SR.LaneMask & DstMask) == 0)
  996. continue;
  997. VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
  998. assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
  999. SR.removeValNo(SVNI);
  1000. }
  1001. DstLI.removeEmptySubRanges();
  1002. } else
  1003. LIS->removeVRegDefAt(DstLI, RegIndex);
  1004. // Mark uses as undef.
  1005. for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
  1006. if (MO.isDef() /*|| MO.isUndef()*/)
  1007. continue;
  1008. const MachineInstr &MI = *MO.getParent();
  1009. SlotIndex UseIdx = LIS->getInstructionIndex(&MI);
  1010. unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
  1011. bool isLive;
  1012. if (UseMask != ~0u && DstLI.hasSubRanges()) {
  1013. isLive = false;
  1014. for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
  1015. if ((SR.LaneMask & UseMask) == 0)
  1016. continue;
  1017. if (SR.liveAt(UseIdx)) {
  1018. isLive = true;
  1019. break;
  1020. }
  1021. }
  1022. } else
  1023. isLive = DstLI.liveAt(UseIdx);
  1024. if (isLive)
  1025. continue;
  1026. MO.setIsUndef(true);
  1027. DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
  1028. }
  1029. return true;
  1030. }
  1031. void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
  1032. unsigned DstReg,
  1033. unsigned SubIdx) {
  1034. bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  1035. LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
  1036. SmallPtrSet<MachineInstr*, 8> Visited;
  1037. for (MachineRegisterInfo::reg_instr_iterator
  1038. I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
  1039. I != E; ) {
  1040. MachineInstr *UseMI = &*(I++);
  1041. // Each instruction can only be rewritten once because sub-register
  1042. // composition is not always idempotent. When SrcReg != DstReg, rewriting
  1043. // the UseMI operands removes them from the SrcReg use-def chain, but when
  1044. // SrcReg is DstReg we could encounter UseMI twice if it has multiple
  1045. // operands mentioning the virtual register.
  1046. if (SrcReg == DstReg && !Visited.insert(UseMI).second)
  1047. continue;
  1048. SmallVector<unsigned,8> Ops;
  1049. bool Reads, Writes;
  1050. std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
  1051. // If SrcReg wasn't read, it may still be the case that DstReg is live-in
  1052. // because SrcReg is a sub-register.
  1053. if (DstInt && !Reads && SubIdx)
  1054. Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
  1055. // Replace SrcReg with DstReg in all UseMI operands.
  1056. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  1057. MachineOperand &MO = UseMI->getOperand(Ops[i]);
  1058. // Adjust <undef> flags in case of sub-register joins. We don't want to
  1059. // turn a full def into a read-modify-write sub-register def and vice
  1060. // versa.
  1061. if (SubIdx && MO.isDef())
  1062. MO.setIsUndef(!Reads);
  1063. // A subreg use of a partially undef (super) register may be a complete
  1064. // undef use now and then has to be marked that way.
  1065. if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) {
  1066. if (!DstInt->hasSubRanges()) {
  1067. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  1068. unsigned Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
  1069. DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
  1070. }
  1071. unsigned Mask = TRI->getSubRegIndexLaneMask(SubIdx);
  1072. bool IsUndef = true;
  1073. SlotIndex MIIdx = UseMI->isDebugValue()
  1074. ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
  1075. : LIS->getInstructionIndex(UseMI);
  1076. SlotIndex UseIdx = MIIdx.getRegSlot(true);
  1077. for (LiveInterval::SubRange &S : DstInt->subranges()) {
  1078. if ((S.LaneMask & Mask) == 0)
  1079. continue;
  1080. if (S.liveAt(UseIdx)) {
  1081. IsUndef = false;
  1082. break;
  1083. }
  1084. }
  1085. if (IsUndef) {
  1086. MO.setIsUndef(true);
  1087. // We found out some subregister use is actually reading an undefined
  1088. // value. In some cases the whole vreg has become undefined at this
  1089. // point so we have to potentially shrink the main range if the
  1090. // use was ending a live segment there.
  1091. LiveQueryResult Q = DstInt->Query(MIIdx);
  1092. if (Q.valueOut() == nullptr)
  1093. ShrinkMainRange = true;
  1094. }
  1095. }
  1096. if (DstIsPhys)
  1097. MO.substPhysReg(DstReg, *TRI);
  1098. else
  1099. MO.substVirtReg(DstReg, SubIdx, *TRI);
  1100. }
  1101. DEBUG({
  1102. dbgs() << "\t\tupdated: ";
  1103. if (!UseMI->isDebugValue())
  1104. dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
  1105. dbgs() << *UseMI;
  1106. });
  1107. }
  1108. }
  1109. bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
  1110. // Always join simple intervals that are defined by a single copy from a
  1111. // reserved register. This doesn't increase register pressure, so it is
  1112. // always beneficial.
  1113. if (!MRI->isReserved(CP.getDstReg())) {
  1114. DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
  1115. return false;
  1116. }
  1117. LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
  1118. if (JoinVInt.containsOneValue())
  1119. return true;
  1120. DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n");
  1121. return false;
  1122. }
  1123. bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
  1124. Again = false;
  1125. DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
  1126. CoalescerPair CP(*TRI);
  1127. if (!CP.setRegisters(CopyMI)) {
  1128. DEBUG(dbgs() << "\tNot coalescable.\n");
  1129. return false;
  1130. }
  1131. if (CP.getNewRC()) {
  1132. auto SrcRC = MRI->getRegClass(CP.getSrcReg());
  1133. auto DstRC = MRI->getRegClass(CP.getDstReg());
  1134. unsigned SrcIdx = CP.getSrcIdx();
  1135. unsigned DstIdx = CP.getDstIdx();
  1136. if (CP.isFlipped()) {
  1137. std::swap(SrcIdx, DstIdx);
  1138. std::swap(SrcRC, DstRC);
  1139. }
  1140. if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
  1141. CP.getNewRC())) {
  1142. DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
  1143. return false;
  1144. }
  1145. }
  1146. // Dead code elimination. This really should be handled by MachineDCE, but
  1147. // sometimes dead copies slip through, and we can't generate invalid live
  1148. // ranges.
  1149. if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
  1150. DEBUG(dbgs() << "\tCopy is dead.\n");
  1151. DeadDefs.push_back(CopyMI);
  1152. eliminateDeadDefs();
  1153. return true;
  1154. }
  1155. // Eliminate undefs.
  1156. if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
  1157. LIS->RemoveMachineInstrFromMaps(CopyMI);
  1158. CopyMI->eraseFromParent();
  1159. return false; // Not coalescable.
  1160. }
  1161. // Coalesced copies are normally removed immediately, but transformations
  1162. // like removeCopyByCommutingDef() can inadvertently create identity copies.
  1163. // When that happens, just join the values and remove the copy.
  1164. if (CP.getSrcReg() == CP.getDstReg()) {
  1165. LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
  1166. DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
  1167. const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
  1168. LiveQueryResult LRQ = LI.Query(CopyIdx);
  1169. if (VNInfo *DefVNI = LRQ.valueDefined()) {
  1170. VNInfo *ReadVNI = LRQ.valueIn();
  1171. assert(ReadVNI && "No value before copy and no <undef> flag.");
  1172. assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
  1173. LI.MergeValueNumberInto(DefVNI, ReadVNI);
  1174. // Process subregister liveranges.
  1175. for (LiveInterval::SubRange &S : LI.subranges()) {
  1176. LiveQueryResult SLRQ = S.Query(CopyIdx);
  1177. if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
  1178. VNInfo *SReadVNI = SLRQ.valueIn();
  1179. S.MergeValueNumberInto(SDefVNI, SReadVNI);
  1180. }
  1181. }
  1182. DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
  1183. }
  1184. LIS->RemoveMachineInstrFromMaps(CopyMI);
  1185. CopyMI->eraseFromParent();
  1186. return true;
  1187. }
  1188. // Enforce policies.
  1189. if (CP.isPhys()) {
  1190. DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
  1191. << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
  1192. << '\n');
  1193. if (!canJoinPhys(CP)) {
  1194. // Before giving up coalescing, if definition of source is defined by
  1195. // trivial computation, try rematerializing it.
  1196. bool IsDefCopy;
  1197. if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
  1198. return true;
  1199. if (IsDefCopy)
  1200. Again = true; // May be possible to coalesce later.
  1201. return false;
  1202. }
  1203. } else {
  1204. // When possible, let DstReg be the larger interval.
  1205. if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
  1206. LIS->getInterval(CP.getDstReg()).size())
  1207. CP.flip();
  1208. DEBUG({
  1209. dbgs() << "\tConsidering merging to "
  1210. << TRI->getRegClassName(CP.getNewRC()) << " with ";
  1211. if (CP.getDstIdx() && CP.getSrcIdx())
  1212. dbgs() << PrintReg(CP.getDstReg()) << " in "
  1213. << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
  1214. << PrintReg(CP.getSrcReg()) << " in "
  1215. << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
  1216. else
  1217. dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
  1218. << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
  1219. });
  1220. }
  1221. ShrinkMask = 0;
  1222. ShrinkMainRange = false;
  1223. // Okay, attempt to join these two intervals. On failure, this returns false.
  1224. // Otherwise, if one of the intervals being joined is a physreg, this method
  1225. // always canonicalizes DstInt to be it. The output "SrcInt" will not have
  1226. // been modified, so we can use this information below to update aliases.
  1227. if (!joinIntervals(CP)) {
  1228. // Coalescing failed.
  1229. // If definition of source is defined by trivial computation, try
  1230. // rematerializing it.
  1231. bool IsDefCopy;
  1232. if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
  1233. return true;
  1234. // If we can eliminate the copy without merging the live segments, do so
  1235. // now.
  1236. if (!CP.isPartial() && !CP.isPhys()) {
  1237. if (adjustCopiesBackFrom(CP, CopyMI) ||
  1238. removeCopyByCommutingDef(CP, CopyMI)) {
  1239. LIS->RemoveMachineInstrFromMaps(CopyMI);
  1240. CopyMI->eraseFromParent();
  1241. DEBUG(dbgs() << "\tTrivial!\n");
  1242. return true;
  1243. }
  1244. }
  1245. // Otherwise, we are unable to join the intervals.
  1246. DEBUG(dbgs() << "\tInterference!\n");
  1247. Again = true; // May be possible to coalesce later.
  1248. return false;
  1249. }
  1250. // Coalescing to a virtual register that is of a sub-register class of the
  1251. // other. Make sure the resulting register is set to the right register class.
  1252. if (CP.isCrossClass()) {
  1253. ++numCrossRCs;
  1254. MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
  1255. }
  1256. // Removing sub-register copies can ease the register class constraints.
  1257. // Make sure we attempt to inflate the register class of DstReg.
  1258. if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
  1259. InflateRegs.push_back(CP.getDstReg());
  1260. // CopyMI has been erased by joinIntervals at this point. Remove it from
  1261. // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
  1262. // to the work list. This keeps ErasedInstrs from growing needlessly.
  1263. ErasedInstrs.erase(CopyMI);
  1264. // Rewrite all SrcReg operands to DstReg.
  1265. // Also update DstReg operands to include DstIdx if it is set.
  1266. if (CP.getDstIdx())
  1267. updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
  1268. updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
  1269. // Shrink subregister ranges if necessary.
  1270. if (ShrinkMask != 0) {
  1271. LiveInterval &LI = LIS->getInterval(CP.getDstReg());
  1272. for (LiveInterval::SubRange &S : LI.subranges()) {
  1273. if ((S.LaneMask & ShrinkMask) == 0)
  1274. continue;
  1275. DEBUG(dbgs() << "Shrink LaneUses (Lane "
  1276. << format("%04X", S.LaneMask) << ")\n");
  1277. LIS->shrinkToUses(S, LI.reg);
  1278. }
  1279. LI.removeEmptySubRanges();
  1280. }
  1281. if (ShrinkMainRange) {
  1282. LiveInterval &LI = LIS->getInterval(CP.getDstReg());
  1283. shrinkToUses(&LI);
  1284. }
  1285. // SrcReg is guaranteed to be the register whose live interval that is
  1286. // being merged.
  1287. LIS->removeInterval(CP.getSrcReg());
  1288. // Update regalloc hint.
  1289. TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
  1290. DEBUG({
  1291. dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
  1292. << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
  1293. dbgs() << "\tResult = ";
  1294. if (CP.isPhys())
  1295. dbgs() << PrintReg(CP.getDstReg(), TRI);
  1296. else
  1297. dbgs() << LIS->getInterval(CP.getDstReg());
  1298. dbgs() << '\n';
  1299. });
  1300. ++numJoins;
  1301. return true;
  1302. }
  1303. bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
  1304. unsigned DstReg = CP.getDstReg();
  1305. assert(CP.isPhys() && "Must be a physreg copy");
  1306. assert(MRI->isReserved(DstReg) && "Not a reserved register");
  1307. LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
  1308. DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
  1309. assert(RHS.containsOneValue() && "Invalid join with reserved register");
  1310. // Optimization for reserved registers like ESP. We can only merge with a
  1311. // reserved physreg if RHS has a single value that is a copy of DstReg.
  1312. // The live range of the reserved register will look like a set of dead defs
  1313. // - we don't properly track the live range of reserved registers.
  1314. // Deny any overlapping intervals. This depends on all the reserved
  1315. // register live ranges to look like dead defs.
  1316. for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI)
  1317. if (RHS.overlaps(LIS->getRegUnit(*UI))) {
  1318. DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
  1319. return false;
  1320. }
  1321. // Skip any value computations, we are not adding new values to the
  1322. // reserved register. Also skip merging the live ranges, the reserved
  1323. // register live range doesn't need to be accurate as long as all the
  1324. // defs are there.
  1325. // Delete the identity copy.
  1326. MachineInstr *CopyMI;
  1327. if (CP.isFlipped()) {
  1328. CopyMI = MRI->getVRegDef(RHS.reg);
  1329. } else {
  1330. if (!MRI->hasOneNonDBGUse(RHS.reg)) {
  1331. DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
  1332. return false;
  1333. }
  1334. MachineInstr *DestMI = MRI->getVRegDef(RHS.reg);
  1335. CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg);
  1336. const SlotIndex CopyRegIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
  1337. const SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
  1338. // We checked above that there are no interfering defs of the physical
  1339. // register. However, for this case, where we intent to move up the def of
  1340. // the physical register, we also need to check for interfering uses.
  1341. SlotIndexes *Indexes = LIS->getSlotIndexes();
  1342. for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
  1343. SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
  1344. MachineInstr *MI = LIS->getInstructionFromIndex(SI);
  1345. if (MI->readsRegister(DstReg, TRI)) {
  1346. DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
  1347. return false;
  1348. }
  1349. // We must also check for clobbers caused by regmasks.
  1350. for (const auto &MO : MI->operands()) {
  1351. if (MO.isRegMask() && MO.clobbersPhysReg(DstReg)) {
  1352. DEBUG(dbgs() << "\t\tInterference (regmask clobber): " << *MI);
  1353. return false;
  1354. }
  1355. }
  1356. }
  1357. // We're going to remove the copy which defines a physical reserved
  1358. // register, so remove its valno, etc.
  1359. DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at "
  1360. << CopyRegIdx << "\n");
  1361. LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
  1362. // Create a new dead def at the new def location.
  1363. for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
  1364. LiveRange &LR = LIS->getRegUnit(*UI);
  1365. LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
  1366. }
  1367. }
  1368. LIS->RemoveMachineInstrFromMaps(CopyMI);
  1369. CopyMI->eraseFromParent();
  1370. // We don't track kills for reserved registers.
  1371. MRI->clearKillFlags(CP.getSrcReg());
  1372. return true;
  1373. }
  1374. //===----------------------------------------------------------------------===//
  1375. // Interference checking and interval joining
  1376. //===----------------------------------------------------------------------===//
  1377. //
  1378. // In the easiest case, the two live ranges being joined are disjoint, and
  1379. // there is no interference to consider. It is quite common, though, to have
  1380. // overlapping live ranges, and we need to check if the interference can be
  1381. // resolved.
  1382. //
  1383. // The live range of a single SSA value forms a sub-tree of the dominator tree.
  1384. // This means that two SSA values overlap if and only if the def of one value
  1385. // is contained in the live range of the other value. As a special case, the
  1386. // overlapping values can be defined at the same index.
  1387. //
  1388. // The interference from an overlapping def can be resolved in these cases:
  1389. //
  1390. // 1. Coalescable copies. The value is defined by a copy that would become an
  1391. // identity copy after joining SrcReg and DstReg. The copy instruction will
  1392. // be removed, and the value will be merged with the source value.
  1393. //
  1394. // There can be several copies back and forth, causing many values to be
  1395. // merged into one. We compute a list of ultimate values in the joined live
  1396. // range as well as a mappings from the old value numbers.
  1397. //
  1398. // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
  1399. // predecessors have a live out value. It doesn't cause real interference,
  1400. // and can be merged into the value it overlaps. Like a coalescable copy, it
  1401. // can be erased after joining.
  1402. //
  1403. // 3. Copy of external value. The overlapping def may be a copy of a value that
  1404. // is already in the other register. This is like a coalescable copy, but
  1405. // the live range of the source register must be trimmed after erasing the
  1406. // copy instruction:
  1407. //
  1408. // %src = COPY %ext
  1409. // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
  1410. //
  1411. // 4. Clobbering undefined lanes. Vector registers are sometimes built by
  1412. // defining one lane at a time:
  1413. //
  1414. // %dst:ssub0<def,read-undef> = FOO
  1415. // %src = BAR
  1416. // %dst:ssub1<def> = COPY %src
  1417. //
  1418. // The live range of %src overlaps the %dst value defined by FOO, but
  1419. // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
  1420. // which was undef anyway.
  1421. //
  1422. // The value mapping is more complicated in this case. The final live range
  1423. // will have different value numbers for both FOO and BAR, but there is no
  1424. // simple mapping from old to new values. It may even be necessary to add
  1425. // new PHI values.
  1426. //
  1427. // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
  1428. // is live, but never read. This can happen because we don't compute
  1429. // individual live ranges per lane.
  1430. //
  1431. // %dst<def> = FOO
  1432. // %src = BAR
  1433. // %dst:ssub1<def> = COPY %src
  1434. //
  1435. // This kind of interference is only resolved locally. If the clobbered
  1436. // lane value escapes the block, the join is aborted.
  1437. namespace {
  1438. /// Track information about values in a single virtual register about to be
  1439. /// joined. Objects of this class are always created in pairs - one for each
  1440. /// side of the CoalescerPair (or one for each lane of a side of the coalescer
  1441. /// pair)
  1442. class JoinVals {
  1443. /// Live range we work on.
  1444. LiveRange &LR;
  1445. /// (Main) register we work on.
  1446. const unsigned Reg;
  1447. /// Reg (and therefore the values in this liverange) will end up as
  1448. /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
  1449. /// CP.SrcIdx.
  1450. const unsigned SubIdx;
  1451. /// The LaneMask that this liverange will occupy the coalesced register. May
  1452. /// be smaller than the lanemask produced by SubIdx when merging subranges.
  1453. const unsigned LaneMask;
  1454. /// This is true when joining sub register ranges, false when joining main
  1455. /// ranges.
  1456. const bool SubRangeJoin;
  1457. /// Whether the current LiveInterval tracks subregister liveness.
  1458. const bool TrackSubRegLiveness;
  1459. /// Values that will be present in the final live range.
  1460. SmallVectorImpl<VNInfo*> &NewVNInfo;
  1461. const CoalescerPair &CP;
  1462. LiveIntervals *LIS;
  1463. SlotIndexes *Indexes;
  1464. const TargetRegisterInfo *TRI;
  1465. /// Value number assignments. Maps value numbers in LI to entries in
  1466. /// NewVNInfo. This is suitable for passing to LiveInterval::join().
  1467. SmallVector<int, 8> Assignments;
  1468. /// Conflict resolution for overlapping values.
  1469. enum ConflictResolution {
  1470. /// No overlap, simply keep this value.
  1471. CR_Keep,
  1472. /// Merge this value into OtherVNI and erase the defining instruction.
  1473. /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
  1474. /// values.
  1475. CR_Erase,
  1476. /// Merge this value into OtherVNI but keep the defining instruction.
  1477. /// This is for the special case where OtherVNI is defined by the same
  1478. /// instruction.
  1479. CR_Merge,
  1480. /// Keep this value, and have it replace OtherVNI where possible. This
  1481. /// complicates value mapping since OtherVNI maps to two different values
  1482. /// before and after this def.
  1483. /// Used when clobbering undefined or dead lanes.
  1484. CR_Replace,
  1485. /// Unresolved conflict. Visit later when all values have been mapped.
  1486. CR_Unresolved,
  1487. /// Unresolvable conflict. Abort the join.
  1488. CR_Impossible
  1489. };
  1490. /// Per-value info for LI. The lane bit masks are all relative to the final
  1491. /// joined register, so they can be compared directly between SrcReg and
  1492. /// DstReg.
  1493. struct Val {
  1494. ConflictResolution Resolution;
  1495. /// Lanes written by this def, 0 for unanalyzed values.
  1496. unsigned WriteLanes;
  1497. /// Lanes with defined values in this register. Other lanes are undef and
  1498. /// safe to clobber.
  1499. unsigned ValidLanes;
  1500. /// Value in LI being redefined by this def.
  1501. VNInfo *RedefVNI;
  1502. /// Value in the other live range that overlaps this def, if any.
  1503. VNInfo *OtherVNI;
  1504. /// Is this value an IMPLICIT_DEF that can be erased?
  1505. ///
  1506. /// IMPLICIT_DEF values should only exist at the end of a basic block that
  1507. /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
  1508. /// safely erased if they are overlapping a live value in the other live
  1509. /// interval.
  1510. ///
  1511. /// Weird control flow graphs and incomplete PHI handling in
  1512. /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
  1513. /// longer live ranges. Such IMPLICIT_DEF values should be treated like
  1514. /// normal values.
  1515. bool ErasableImplicitDef;
  1516. /// True when the live range of this value will be pruned because of an
  1517. /// overlapping CR_Replace value in the other live range.
  1518. bool Pruned;
  1519. /// True once Pruned above has been computed.
  1520. bool PrunedComputed;
  1521. Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
  1522. RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
  1523. Pruned(false), PrunedComputed(false) {}
  1524. bool isAnalyzed() const { return WriteLanes != 0; }
  1525. };
  1526. /// One entry per value number in LI.
  1527. SmallVector<Val, 8> Vals;
  1528. /// Compute the bitmask of lanes actually written by DefMI.
  1529. /// Set Redef if there are any partial register definitions that depend on the
  1530. /// previous value of the register.
  1531. unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
  1532. /// Find the ultimate value that VNI was copied from.
  1533. std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
  1534. bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
  1535. /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
  1536. /// Return a conflict resolution when possible, but leave the hard cases as
  1537. /// CR_Unresolved.
  1538. /// Recursively calls computeAssignment() on this and Other, guaranteeing that
  1539. /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
  1540. /// The recursion always goes upwards in the dominator tree, making loops
  1541. /// impossible.
  1542. ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
  1543. /// Compute the value assignment for ValNo in RI.
  1544. /// This may be called recursively by analyzeValue(), but never for a ValNo on
  1545. /// the stack.
  1546. void computeAssignment(unsigned ValNo, JoinVals &Other);
  1547. /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
  1548. /// the extent of the tainted lanes in the block.
  1549. ///
  1550. /// Multiple values in Other.LR can be affected since partial redefinitions
  1551. /// can preserve previously tainted lanes.
  1552. ///
  1553. /// 1 %dst = VLOAD <-- Define all lanes in %dst
  1554. /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
  1555. /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
  1556. /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
  1557. ///
  1558. /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
  1559. /// entry to TaintedVals.
  1560. ///
  1561. /// Returns false if the tainted lanes extend beyond the basic block.
  1562. bool taintExtent(unsigned, unsigned, JoinVals&,
  1563. SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
  1564. /// Return true if MI uses any of the given Lanes from Reg.
  1565. /// This does not include partial redefinitions of Reg.
  1566. bool usesLanes(const MachineInstr *MI, unsigned, unsigned, unsigned) const;
  1567. /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
  1568. /// be pruned:
  1569. ///
  1570. /// %dst = COPY %src
  1571. /// %src = COPY %dst <-- This value to be pruned.
  1572. /// %dst = COPY %src <-- This value is a copy of a pruned value.
  1573. bool isPrunedValue(unsigned ValNo, JoinVals &Other);
  1574. public:
  1575. JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, unsigned LaneMask,
  1576. SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
  1577. LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
  1578. bool TrackSubRegLiveness)
  1579. : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
  1580. SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
  1581. NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
  1582. TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
  1583. {}
  1584. /// Analyze defs in LR and compute a value mapping in NewVNInfo.
  1585. /// Returns false if any conflicts were impossible to resolve.
  1586. bool mapValues(JoinVals &Other);
  1587. /// Try to resolve conflicts that require all values to be mapped.
  1588. /// Returns false if any conflicts were impossible to resolve.
  1589. bool resolveConflicts(JoinVals &Other);
  1590. /// Prune the live range of values in Other.LR where they would conflict with
  1591. /// CR_Replace values in LR. Collect end points for restoring the live range
  1592. /// after joining.
  1593. void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
  1594. bool changeInstrs);
  1595. /// Removes subranges starting at copies that get removed. This sometimes
  1596. /// happens when undefined subranges are copied around. These ranges contain
  1597. /// no usefull information and can be removed.
  1598. void pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask);
  1599. /// Erase any machine instructions that have been coalesced away.
  1600. /// Add erased instructions to ErasedInstrs.
  1601. /// Add foreign virtual registers to ShrinkRegs if their live range ended at
  1602. /// the erased instrs.
  1603. void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
  1604. SmallVectorImpl<unsigned> &ShrinkRegs);
  1605. /// Remove liverange defs at places where implicit defs will be removed.
  1606. void removeImplicitDefs();
  1607. /// Get the value assignments suitable for passing to LiveInterval::join.
  1608. const int *getAssignments() const { return Assignments.data(); }
  1609. };
  1610. } // end anonymous namespace
  1611. unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
  1612. const {
  1613. unsigned L = 0;
  1614. for (const MachineOperand &MO : DefMI->operands()) {
  1615. if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
  1616. continue;
  1617. L |= TRI->getSubRegIndexLaneMask(
  1618. TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
  1619. if (MO.readsReg())
  1620. Redef = true;
  1621. }
  1622. return L;
  1623. }
  1624. std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
  1625. const VNInfo *VNI) const {
  1626. unsigned Reg = this->Reg;
  1627. while (!VNI->isPHIDef()) {
  1628. SlotIndex Def = VNI->def;
  1629. MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
  1630. assert(MI && "No defining instruction");
  1631. if (!MI->isFullCopy())
  1632. return std::make_pair(VNI, Reg);
  1633. unsigned SrcReg = MI->getOperand(1).getReg();
  1634. if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
  1635. return std::make_pair(VNI, Reg);
  1636. const LiveInterval &LI = LIS->getInterval(SrcReg);
  1637. const VNInfo *ValueIn;
  1638. // No subrange involved.
  1639. if (!SubRangeJoin || !LI.hasSubRanges()) {
  1640. LiveQueryResult LRQ = LI.Query(Def);
  1641. ValueIn = LRQ.valueIn();
  1642. } else {
  1643. // Query subranges. Pick the first matching one.
  1644. ValueIn = nullptr;
  1645. for (const LiveInterval::SubRange &S : LI.subranges()) {
  1646. // Transform lanemask to a mask in the joined live interval.
  1647. unsigned SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
  1648. if ((SMask & LaneMask) == 0)
  1649. continue;
  1650. LiveQueryResult LRQ = S.Query(Def);
  1651. ValueIn = LRQ.valueIn();
  1652. break;
  1653. }
  1654. }
  1655. if (ValueIn == nullptr)
  1656. break;
  1657. VNI = ValueIn;
  1658. Reg = SrcReg;
  1659. }
  1660. return std::make_pair(VNI, Reg);
  1661. }
  1662. bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
  1663. const JoinVals &Other) const {
  1664. const VNInfo *Orig0;
  1665. unsigned Reg0;
  1666. std::tie(Orig0, Reg0) = followCopyChain(Value0);
  1667. if (Orig0 == Value1)
  1668. return true;
  1669. const VNInfo *Orig1;
  1670. unsigned Reg1;
  1671. std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
  1672. // The values are equal if they are defined at the same place and use the
  1673. // same register. Note that we cannot compare VNInfos directly as some of
  1674. // them might be from a copy created in mergeSubRangeInto() while the other
  1675. // is from the original LiveInterval.
  1676. return Orig0->def == Orig1->def && Reg0 == Reg1;
  1677. }
  1678. JoinVals::ConflictResolution
  1679. JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
  1680. Val &V = Vals[ValNo];
  1681. assert(!V.isAnalyzed() && "Value has already been analyzed!");
  1682. VNInfo *VNI = LR.getValNumInfo(ValNo);
  1683. if (VNI->isUnused()) {
  1684. V.WriteLanes = ~0u;
  1685. return CR_Keep;
  1686. }
  1687. // Get the instruction defining this value, compute the lanes written.
  1688. const MachineInstr *DefMI = nullptr;
  1689. if (VNI->isPHIDef()) {
  1690. // Conservatively assume that all lanes in a PHI are valid.
  1691. unsigned Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
  1692. V.ValidLanes = V.WriteLanes = Lanes;
  1693. } else {
  1694. DefMI = Indexes->getInstructionFromIndex(VNI->def);
  1695. assert(DefMI != nullptr);
  1696. if (SubRangeJoin) {
  1697. // We don't care about the lanes when joining subregister ranges.
  1698. V.WriteLanes = V.ValidLanes = 1;
  1699. if (DefMI->isImplicitDef()) {
  1700. V.ValidLanes = 0;
  1701. V.ErasableImplicitDef = true;
  1702. }
  1703. } else {
  1704. bool Redef = false;
  1705. V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
  1706. // If this is a read-modify-write instruction, there may be more valid
  1707. // lanes than the ones written by this instruction.
  1708. // This only covers partial redef operands. DefMI may have normal use
  1709. // operands reading the register. They don't contribute valid lanes.
  1710. //
  1711. // This adds ssub1 to the set of valid lanes in %src:
  1712. //
  1713. // %src:ssub1<def> = FOO
  1714. //
  1715. // This leaves only ssub1 valid, making any other lanes undef:
  1716. //
  1717. // %src:ssub1<def,read-undef> = FOO %src:ssub2
  1718. //
  1719. // The <read-undef> flag on the def operand means that old lane values are
  1720. // not important.
  1721. if (Redef) {
  1722. V.RedefVNI = LR.Query(VNI->def).valueIn();
  1723. assert((TrackSubRegLiveness || V.RedefVNI) &&
  1724. "Instruction is reading nonexistent value");
  1725. if (V.RedefVNI != nullptr) {
  1726. computeAssignment(V.RedefVNI->id, Other);
  1727. V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
  1728. }
  1729. }
  1730. // An IMPLICIT_DEF writes undef values.
  1731. if (DefMI->isImplicitDef()) {
  1732. // We normally expect IMPLICIT_DEF values to be live only until the end
  1733. // of their block. If the value is really live longer and gets pruned in
  1734. // another block, this flag is cleared again.
  1735. V.ErasableImplicitDef = true;
  1736. V.ValidLanes &= ~V.WriteLanes;
  1737. }
  1738. }
  1739. }
  1740. // Find the value in Other that overlaps VNI->def, if any.
  1741. LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
  1742. // It is possible that both values are defined by the same instruction, or
  1743. // the values are PHIs defined in the same block. When that happens, the two
  1744. // values should be merged into one, but not into any preceding value.
  1745. // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
  1746. if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
  1747. assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
  1748. // One value stays, the other is merged. Keep the earlier one, or the first
  1749. // one we see.
  1750. if (OtherVNI->def < VNI->def)
  1751. Other.computeAssignment(OtherVNI->id, *this);
  1752. else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
  1753. // This is an early-clobber def overlapping a live-in value in the other
  1754. // register. Not mergeable.
  1755. V.OtherVNI = OtherLRQ.valueIn();
  1756. return CR_Impossible;
  1757. }
  1758. V.OtherVNI = OtherVNI;
  1759. Val &OtherV = Other.Vals[OtherVNI->id];
  1760. // Keep this value, check for conflicts when analyzing OtherVNI.
  1761. if (!OtherV.isAnalyzed())
  1762. return CR_Keep;
  1763. // Both sides have been analyzed now.
  1764. // Allow overlapping PHI values. Any real interference would show up in a
  1765. // predecessor, the PHI itself can't introduce any conflicts.
  1766. if (VNI->isPHIDef())
  1767. return CR_Merge;
  1768. if (V.ValidLanes & OtherV.ValidLanes)
  1769. // Overlapping lanes can't be resolved.
  1770. return CR_Impossible;
  1771. else
  1772. return CR_Merge;
  1773. }
  1774. // No simultaneous def. Is Other live at the def?
  1775. V.OtherVNI = OtherLRQ.valueIn();
  1776. if (!V.OtherVNI)
  1777. // No overlap, no conflict.
  1778. return CR_Keep;
  1779. assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
  1780. // We have overlapping values, or possibly a kill of Other.
  1781. // Recursively compute assignments up the dominator tree.
  1782. Other.computeAssignment(V.OtherVNI->id, *this);
  1783. Val &OtherV = Other.Vals[V.OtherVNI->id];
  1784. // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
  1785. // This shouldn't normally happen, but ProcessImplicitDefs can leave such
  1786. // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
  1787. // technically.
  1788. //
  1789. // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
  1790. // to erase the IMPLICIT_DEF instruction.
  1791. if (OtherV.ErasableImplicitDef && DefMI &&
  1792. DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
  1793. DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
  1794. << " extends into BB#" << DefMI->getParent()->getNumber()
  1795. << ", keeping it.\n");
  1796. OtherV.ErasableImplicitDef = false;
  1797. }
  1798. // Allow overlapping PHI values. Any real interference would show up in a
  1799. // predecessor, the PHI itself can't introduce any conflicts.
  1800. if (VNI->isPHIDef())
  1801. return CR_Replace;
  1802. // Check for simple erasable conflicts.
  1803. if (DefMI->isImplicitDef()) {
  1804. // We need the def for the subregister if there is nothing else live at the
  1805. // subrange at this point.
  1806. if (TrackSubRegLiveness
  1807. && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)) == 0)
  1808. return CR_Replace;
  1809. return CR_Erase;
  1810. }
  1811. // Include the non-conflict where DefMI is a coalescable copy that kills
  1812. // OtherVNI. We still want the copy erased and value numbers merged.
  1813. if (CP.isCoalescable(DefMI)) {
  1814. // Some of the lanes copied from OtherVNI may be undef, making them undef
  1815. // here too.
  1816. V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
  1817. return CR_Erase;
  1818. }
  1819. // This may not be a real conflict if DefMI simply kills Other and defines
  1820. // VNI.
  1821. if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
  1822. return CR_Keep;
  1823. // Handle the case where VNI and OtherVNI can be proven to be identical:
  1824. //
  1825. // %other = COPY %ext
  1826. // %this = COPY %ext <-- Erase this copy
  1827. //
  1828. if (DefMI->isFullCopy() && !CP.isPartial()
  1829. && valuesIdentical(VNI, V.OtherVNI, Other))
  1830. return CR_Erase;
  1831. // If the lanes written by this instruction were all undef in OtherVNI, it is
  1832. // still safe to join the live ranges. This can't be done with a simple value
  1833. // mapping, though - OtherVNI will map to multiple values:
  1834. //
  1835. // 1 %dst:ssub0 = FOO <-- OtherVNI
  1836. // 2 %src = BAR <-- VNI
  1837. // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
  1838. // 4 BAZ %dst<kill>
  1839. // 5 QUUX %src<kill>
  1840. //
  1841. // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
  1842. // handles this complex value mapping.
  1843. if ((V.WriteLanes & OtherV.ValidLanes) == 0)
  1844. return CR_Replace;
  1845. // If the other live range is killed by DefMI and the live ranges are still
  1846. // overlapping, it must be because we're looking at an early clobber def:
  1847. //
  1848. // %dst<def,early-clobber> = ASM %src<kill>
  1849. //
  1850. // In this case, it is illegal to merge the two live ranges since the early
  1851. // clobber def would clobber %src before it was read.
  1852. if (OtherLRQ.isKill()) {
  1853. // This case where the def doesn't overlap the kill is handled above.
  1854. assert(VNI->def.isEarlyClobber() &&
  1855. "Only early clobber defs can overlap a kill");
  1856. return CR_Impossible;
  1857. }
  1858. // VNI is clobbering live lanes in OtherVNI, but there is still the
  1859. // possibility that no instructions actually read the clobbered lanes.
  1860. // If we're clobbering all the lanes in OtherVNI, at least one must be read.
  1861. // Otherwise Other.RI wouldn't be live here.
  1862. if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
  1863. return CR_Impossible;
  1864. // We need to verify that no instructions are reading the clobbered lanes. To
  1865. // save compile time, we'll only check that locally. Don't allow the tainted
  1866. // value to escape the basic block.
  1867. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
  1868. if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
  1869. return CR_Impossible;
  1870. // There are still some things that could go wrong besides clobbered lanes
  1871. // being read, for example OtherVNI may be only partially redefined in MBB,
  1872. // and some clobbered lanes could escape the block. Save this analysis for
  1873. // resolveConflicts() when all values have been mapped. We need to know
  1874. // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
  1875. // that now - the recursive analyzeValue() calls must go upwards in the
  1876. // dominator tree.
  1877. return CR_Unresolved;
  1878. }
  1879. void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
  1880. Val &V = Vals[ValNo];
  1881. if (V.isAnalyzed()) {
  1882. // Recursion should always move up the dominator tree, so ValNo is not
  1883. // supposed to reappear before it has been assigned.
  1884. assert(Assignments[ValNo] != -1 && "Bad recursion?");
  1885. return;
  1886. }
  1887. switch ((V.Resolution = analyzeValue(ValNo, Other))) {
  1888. case CR_Erase:
  1889. case CR_Merge:
  1890. // Merge this ValNo into OtherVNI.
  1891. assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
  1892. assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
  1893. Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
  1894. DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
  1895. << LR.getValNumInfo(ValNo)->def << " into "
  1896. << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
  1897. << V.OtherVNI->def << " --> @"
  1898. << NewVNInfo[Assignments[ValNo]]->def << '\n');
  1899. break;
  1900. case CR_Replace:
  1901. case CR_Unresolved: {
  1902. // The other value is going to be pruned if this join is successful.
  1903. assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
  1904. Val &OtherV = Other.Vals[V.OtherVNI->id];
  1905. // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
  1906. // its lanes.
  1907. if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
  1908. OtherV.ErasableImplicitDef = false;
  1909. OtherV.Pruned = true;
  1910. }
  1911. // Fall through.
  1912. default:
  1913. // This value number needs to go in the final joined live range.
  1914. Assignments[ValNo] = NewVNInfo.size();
  1915. NewVNInfo.push_back(LR.getValNumInfo(ValNo));
  1916. break;
  1917. }
  1918. }
  1919. bool JoinVals::mapValues(JoinVals &Other) {
  1920. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  1921. computeAssignment(i, Other);
  1922. if (Vals[i].Resolution == CR_Impossible) {
  1923. DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
  1924. << '@' << LR.getValNumInfo(i)->def << '\n');
  1925. return false;
  1926. }
  1927. }
  1928. return true;
  1929. }
  1930. bool JoinVals::
  1931. taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
  1932. SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
  1933. VNInfo *VNI = LR.getValNumInfo(ValNo);
  1934. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
  1935. SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
  1936. // Scan Other.LR from VNI.def to MBBEnd.
  1937. LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
  1938. assert(OtherI != Other.LR.end() && "No conflict?");
  1939. do {
  1940. // OtherI is pointing to a tainted value. Abort the join if the tainted
  1941. // lanes escape the block.
  1942. SlotIndex End = OtherI->end;
  1943. if (End >= MBBEnd) {
  1944. DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
  1945. << OtherI->valno->id << '@' << OtherI->start << '\n');
  1946. return false;
  1947. }
  1948. DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
  1949. << OtherI->valno->id << '@' << OtherI->start
  1950. << " to " << End << '\n');
  1951. // A dead def is not a problem.
  1952. if (End.isDead())
  1953. break;
  1954. TaintExtent.push_back(std::make_pair(End, TaintedLanes));
  1955. // Check for another def in the MBB.
  1956. if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
  1957. break;
  1958. // Lanes written by the new def are no longer tainted.
  1959. const Val &OV = Other.Vals[OtherI->valno->id];
  1960. TaintedLanes &= ~OV.WriteLanes;
  1961. if (!OV.RedefVNI)
  1962. break;
  1963. } while (TaintedLanes);
  1964. return true;
  1965. }
  1966. bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
  1967. unsigned Lanes) const {
  1968. if (MI->isDebugValue())
  1969. return false;
  1970. for (const MachineOperand &MO : MI->operands()) {
  1971. if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
  1972. continue;
  1973. if (!MO.readsReg())
  1974. continue;
  1975. if (Lanes & TRI->getSubRegIndexLaneMask(
  1976. TRI->composeSubRegIndices(SubIdx, MO.getSubReg())))
  1977. return true;
  1978. }
  1979. return false;
  1980. }
  1981. bool JoinVals::resolveConflicts(JoinVals &Other) {
  1982. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  1983. Val &V = Vals[i];
  1984. assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
  1985. if (V.Resolution != CR_Unresolved)
  1986. continue;
  1987. DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
  1988. << '@' << LR.getValNumInfo(i)->def << '\n');
  1989. if (SubRangeJoin)
  1990. return false;
  1991. ++NumLaneConflicts;
  1992. assert(V.OtherVNI && "Inconsistent conflict resolution.");
  1993. VNInfo *VNI = LR.getValNumInfo(i);
  1994. const Val &OtherV = Other.Vals[V.OtherVNI->id];
  1995. // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
  1996. // join, those lanes will be tainted with a wrong value. Get the extent of
  1997. // the tainted lanes.
  1998. unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
  1999. SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
  2000. if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
  2001. // Tainted lanes would extend beyond the basic block.
  2002. return false;
  2003. assert(!TaintExtent.empty() && "There should be at least one conflict.");
  2004. // Now look at the instructions from VNI->def to TaintExtent (inclusive).
  2005. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
  2006. MachineBasicBlock::iterator MI = MBB->begin();
  2007. if (!VNI->isPHIDef()) {
  2008. MI = Indexes->getInstructionFromIndex(VNI->def);
  2009. // No need to check the instruction defining VNI for reads.
  2010. ++MI;
  2011. }
  2012. assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
  2013. "Interference ends on VNI->def. Should have been handled earlier");
  2014. MachineInstr *LastMI =
  2015. Indexes->getInstructionFromIndex(TaintExtent.front().first);
  2016. assert(LastMI && "Range must end at a proper instruction");
  2017. unsigned TaintNum = 0;
  2018. for(;;) {
  2019. assert(MI != MBB->end() && "Bad LastMI");
  2020. if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
  2021. DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
  2022. return false;
  2023. }
  2024. // LastMI is the last instruction to use the current value.
  2025. if (&*MI == LastMI) {
  2026. if (++TaintNum == TaintExtent.size())
  2027. break;
  2028. LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
  2029. assert(LastMI && "Range must end at a proper instruction");
  2030. TaintedLanes = TaintExtent[TaintNum].second;
  2031. }
  2032. ++MI;
  2033. }
  2034. // The tainted lanes are unused.
  2035. V.Resolution = CR_Replace;
  2036. ++NumLaneResolves;
  2037. }
  2038. return true;
  2039. }
  2040. bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
  2041. Val &V = Vals[ValNo];
  2042. if (V.Pruned || V.PrunedComputed)
  2043. return V.Pruned;
  2044. if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
  2045. return V.Pruned;
  2046. // Follow copies up the dominator tree and check if any intermediate value
  2047. // has been pruned.
  2048. V.PrunedComputed = true;
  2049. V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
  2050. return V.Pruned;
  2051. }
  2052. void JoinVals::pruneValues(JoinVals &Other,
  2053. SmallVectorImpl<SlotIndex> &EndPoints,
  2054. bool changeInstrs) {
  2055. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2056. SlotIndex Def = LR.getValNumInfo(i)->def;
  2057. switch (Vals[i].Resolution) {
  2058. case CR_Keep:
  2059. break;
  2060. case CR_Replace: {
  2061. // This value takes precedence over the value in Other.LR.
  2062. LIS->pruneValue(Other.LR, Def, &EndPoints);
  2063. // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
  2064. // instructions are only inserted to provide a live-out value for PHI
  2065. // predecessors, so the instruction should simply go away once its value
  2066. // has been replaced.
  2067. Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
  2068. bool EraseImpDef = OtherV.ErasableImplicitDef &&
  2069. OtherV.Resolution == CR_Keep;
  2070. if (!Def.isBlock()) {
  2071. if (changeInstrs) {
  2072. // Remove <def,read-undef> flags. This def is now a partial redef.
  2073. // Also remove <def,dead> flags since the joined live range will
  2074. // continue past this instruction.
  2075. for (MachineOperand &MO :
  2076. Indexes->getInstructionFromIndex(Def)->operands()) {
  2077. if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
  2078. MO.setIsUndef(EraseImpDef);
  2079. MO.setIsDead(false);
  2080. }
  2081. }
  2082. }
  2083. // This value will reach instructions below, but we need to make sure
  2084. // the live range also reaches the instruction at Def.
  2085. if (!EraseImpDef)
  2086. EndPoints.push_back(Def);
  2087. }
  2088. DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
  2089. << ": " << Other.LR << '\n');
  2090. break;
  2091. }
  2092. case CR_Erase:
  2093. case CR_Merge:
  2094. if (isPrunedValue(i, Other)) {
  2095. // This value is ultimately a copy of a pruned value in LR or Other.LR.
  2096. // We can no longer trust the value mapping computed by
  2097. // computeAssignment(), the value that was originally copied could have
  2098. // been replaced.
  2099. LIS->pruneValue(LR, Def, &EndPoints);
  2100. DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
  2101. << Def << ": " << LR << '\n');
  2102. }
  2103. break;
  2104. case CR_Unresolved:
  2105. case CR_Impossible:
  2106. llvm_unreachable("Unresolved conflicts");
  2107. }
  2108. }
  2109. }
  2110. void JoinVals::pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask)
  2111. {
  2112. // Look for values being erased.
  2113. bool DidPrune = false;
  2114. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2115. if (Vals[i].Resolution != CR_Erase)
  2116. continue;
  2117. // Check subranges at the point where the copy will be removed.
  2118. SlotIndex Def = LR.getValNumInfo(i)->def;
  2119. for (LiveInterval::SubRange &S : LI.subranges()) {
  2120. LiveQueryResult Q = S.Query(Def);
  2121. // If a subrange starts at the copy then an undefined value has been
  2122. // copied and we must remove that subrange value as well.
  2123. VNInfo *ValueOut = Q.valueOutOrDead();
  2124. if (ValueOut != nullptr && Q.valueIn() == nullptr) {
  2125. DEBUG(dbgs() << "\t\tPrune sublane " << format("%04X", S.LaneMask)
  2126. << " at " << Def << "\n");
  2127. LIS->pruneValue(S, Def, nullptr);
  2128. DidPrune = true;
  2129. // Mark value number as unused.
  2130. ValueOut->markUnused();
  2131. continue;
  2132. }
  2133. // If a subrange ends at the copy, then a value was copied but only
  2134. // partially used later. Shrink the subregister range apropriately.
  2135. if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
  2136. DEBUG(dbgs() << "\t\tDead uses at sublane "
  2137. << format("%04X", S.LaneMask) << " at " << Def << "\n");
  2138. ShrinkMask |= S.LaneMask;
  2139. }
  2140. }
  2141. }
  2142. if (DidPrune)
  2143. LI.removeEmptySubRanges();
  2144. }
  2145. void JoinVals::removeImplicitDefs() {
  2146. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2147. Val &V = Vals[i];
  2148. if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
  2149. continue;
  2150. VNInfo *VNI = LR.getValNumInfo(i);
  2151. VNI->markUnused();
  2152. LR.removeValNo(VNI);
  2153. }
  2154. }
  2155. void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
  2156. SmallVectorImpl<unsigned> &ShrinkRegs) {
  2157. for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
  2158. // Get the def location before markUnused() below invalidates it.
  2159. SlotIndex Def = LR.getValNumInfo(i)->def;
  2160. switch (Vals[i].Resolution) {
  2161. case CR_Keep: {
  2162. // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
  2163. // longer. The IMPLICIT_DEF instructions are only inserted by
  2164. // PHIElimination to guarantee that all PHI predecessors have a value.
  2165. if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
  2166. break;
  2167. // Remove value number i from LR.
  2168. VNInfo *VNI = LR.getValNumInfo(i);
  2169. LR.removeValNo(VNI);
  2170. // Note that this VNInfo is reused and still referenced in NewVNInfo,
  2171. // make it appear like an unused value number.
  2172. VNI->markUnused();
  2173. DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
  2174. // FALL THROUGH.
  2175. }
  2176. case CR_Erase: {
  2177. MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
  2178. assert(MI && "No instruction to erase");
  2179. if (MI->isCopy()) {
  2180. unsigned Reg = MI->getOperand(1).getReg();
  2181. if (TargetRegisterInfo::isVirtualRegister(Reg) &&
  2182. Reg != CP.getSrcReg() && Reg != CP.getDstReg())
  2183. ShrinkRegs.push_back(Reg);
  2184. }
  2185. ErasedInstrs.insert(MI);
  2186. DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
  2187. LIS->RemoveMachineInstrFromMaps(MI);
  2188. MI->eraseFromParent();
  2189. break;
  2190. }
  2191. default:
  2192. break;
  2193. }
  2194. }
  2195. }
  2196. bool RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
  2197. unsigned LaneMask,
  2198. const CoalescerPair &CP) {
  2199. SmallVector<VNInfo*, 16> NewVNInfo;
  2200. JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
  2201. NewVNInfo, CP, LIS, TRI, true, true);
  2202. JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
  2203. NewVNInfo, CP, LIS, TRI, true, true);
  2204. // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
  2205. // We should be able to resolve all conflicts here as we could successfully do
  2206. // it on the mainrange already. There is however a problem when multiple
  2207. // ranges get mapped to the "overflow" lane mask bit which creates unexpected
  2208. // interferences.
  2209. if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
  2210. DEBUG(dbgs() << "*** Couldn't join subrange!\n");
  2211. return false;
  2212. }
  2213. if (!LHSVals.resolveConflicts(RHSVals) ||
  2214. !RHSVals.resolveConflicts(LHSVals)) {
  2215. DEBUG(dbgs() << "*** Couldn't join subrange!\n");
  2216. return false;
  2217. }
  2218. // The merging algorithm in LiveInterval::join() can't handle conflicting
  2219. // value mappings, so we need to remove any live ranges that overlap a
  2220. // CR_Replace resolution. Collect a set of end points that can be used to
  2221. // restore the live range after joining.
  2222. SmallVector<SlotIndex, 8> EndPoints;
  2223. LHSVals.pruneValues(RHSVals, EndPoints, false);
  2224. RHSVals.pruneValues(LHSVals, EndPoints, false);
  2225. LHSVals.removeImplicitDefs();
  2226. RHSVals.removeImplicitDefs();
  2227. LRange.verify();
  2228. RRange.verify();
  2229. // Join RRange into LHS.
  2230. LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
  2231. NewVNInfo);
  2232. DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
  2233. if (EndPoints.empty())
  2234. return true;
  2235. // Recompute the parts of the live range we had to remove because of
  2236. // CR_Replace conflicts.
  2237. DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
  2238. << " points: " << LRange << '\n');
  2239. LIS->extendToIndices(LRange, EndPoints);
  2240. return true;
  2241. }
  2242. bool RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
  2243. const LiveRange &ToMerge,
  2244. unsigned LaneMask, CoalescerPair &CP) {
  2245. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  2246. for (LiveInterval::SubRange &R : LI.subranges()) {
  2247. unsigned RMask = R.LaneMask;
  2248. // LaneMask of subregisters common to subrange R and ToMerge.
  2249. unsigned Common = RMask & LaneMask;
  2250. // There is nothing to do without common subregs.
  2251. if (Common == 0)
  2252. continue;
  2253. DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", RMask, Common));
  2254. // LaneMask of subregisters contained in the R range but not in ToMerge,
  2255. // they have to split into their own subrange.
  2256. unsigned LRest = RMask & ~LaneMask;
  2257. LiveInterval::SubRange *CommonRange;
  2258. if (LRest != 0) {
  2259. R.LaneMask = LRest;
  2260. DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", LRest));
  2261. // Duplicate SubRange for newly merged common stuff.
  2262. CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
  2263. } else {
  2264. // Reuse the existing range.
  2265. R.LaneMask = Common;
  2266. CommonRange = &R;
  2267. }
  2268. LiveRange RangeCopy(ToMerge, Allocator);
  2269. if (!joinSubRegRanges(*CommonRange, RangeCopy, Common, CP))
  2270. return false;
  2271. LaneMask &= ~RMask;
  2272. }
  2273. if (LaneMask != 0) {
  2274. DEBUG(dbgs() << format("\t\tNew Lane %04X\n", LaneMask));
  2275. LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
  2276. }
  2277. return true;
  2278. }
  2279. bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
  2280. SmallVector<VNInfo*, 16> NewVNInfo;
  2281. LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
  2282. LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
  2283. bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
  2284. JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), 0, NewVNInfo, CP, LIS,
  2285. TRI, false, TrackSubRegLiveness);
  2286. JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), 0, NewVNInfo, CP, LIS,
  2287. TRI, false, TrackSubRegLiveness);
  2288. DEBUG(dbgs() << "\t\tRHS = " << RHS
  2289. << "\n\t\tLHS = " << LHS
  2290. << '\n');
  2291. // First compute NewVNInfo and the simple value mappings.
  2292. // Detect impossible conflicts early.
  2293. if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
  2294. return false;
  2295. // Some conflicts can only be resolved after all values have been mapped.
  2296. if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
  2297. return false;
  2298. // All clear, the live ranges can be merged.
  2299. if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
  2300. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  2301. // Transform lanemasks from the LHS to masks in the coalesced register and
  2302. // create initial subranges if necessary.
  2303. unsigned DstIdx = CP.getDstIdx();
  2304. if (!LHS.hasSubRanges()) {
  2305. unsigned Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
  2306. : TRI->getSubRegIndexLaneMask(DstIdx);
  2307. // LHS must support subregs or we wouldn't be in this codepath.
  2308. assert(Mask != 0);
  2309. LHS.createSubRangeFrom(Allocator, Mask, LHS);
  2310. } else if (DstIdx != 0) {
  2311. // Transform LHS lanemasks to new register class if necessary.
  2312. for (LiveInterval::SubRange &R : LHS.subranges()) {
  2313. unsigned Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
  2314. R.LaneMask = Mask;
  2315. }
  2316. }
  2317. DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
  2318. << ' ' << LHS << '\n');
  2319. // Determine lanemasks of RHS in the coalesced register and merge subranges.
  2320. unsigned SrcIdx = CP.getSrcIdx();
  2321. bool Abort = false;
  2322. if (!RHS.hasSubRanges()) {
  2323. unsigned Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
  2324. : TRI->getSubRegIndexLaneMask(SrcIdx);
  2325. if (!mergeSubRangeInto(LHS, RHS, Mask, CP))
  2326. Abort = true;
  2327. } else {
  2328. // Pair up subranges and merge.
  2329. for (LiveInterval::SubRange &R : RHS.subranges()) {
  2330. unsigned Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
  2331. if (!mergeSubRangeInto(LHS, R, Mask, CP)) {
  2332. Abort = true;
  2333. break;
  2334. }
  2335. }
  2336. }
  2337. if (Abort) {
  2338. // This shouldn't have happened :-(
  2339. // However we are aware of at least one existing problem where we
  2340. // can't merge subranges when multiple ranges end up in the
  2341. // "overflow bit" 32. As a workaround we drop all subregister ranges
  2342. // which means we loose some precision but are back to a well defined
  2343. // state.
  2344. assert(TargetRegisterInfo::isImpreciseLaneMask(
  2345. CP.getNewRC()->getLaneMask())
  2346. && "SubRange merge should only fail when merging into bit 32.");
  2347. DEBUG(dbgs() << "\tSubrange join aborted!\n");
  2348. LHS.clearSubRanges();
  2349. RHS.clearSubRanges();
  2350. } else {
  2351. DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
  2352. LHSVals.pruneSubRegValues(LHS, ShrinkMask);
  2353. RHSVals.pruneSubRegValues(LHS, ShrinkMask);
  2354. }
  2355. }
  2356. // The merging algorithm in LiveInterval::join() can't handle conflicting
  2357. // value mappings, so we need to remove any live ranges that overlap a
  2358. // CR_Replace resolution. Collect a set of end points that can be used to
  2359. // restore the live range after joining.
  2360. SmallVector<SlotIndex, 8> EndPoints;
  2361. LHSVals.pruneValues(RHSVals, EndPoints, true);
  2362. RHSVals.pruneValues(LHSVals, EndPoints, true);
  2363. // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
  2364. // registers to require trimming.
  2365. SmallVector<unsigned, 8> ShrinkRegs;
  2366. LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
  2367. RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
  2368. while (!ShrinkRegs.empty())
  2369. shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
  2370. // Join RHS into LHS.
  2371. LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
  2372. // Kill flags are going to be wrong if the live ranges were overlapping.
  2373. // Eventually, we should simply clear all kill flags when computing live
  2374. // ranges. They are reinserted after register allocation.
  2375. MRI->clearKillFlags(LHS.reg);
  2376. MRI->clearKillFlags(RHS.reg);
  2377. if (!EndPoints.empty()) {
  2378. // Recompute the parts of the live range we had to remove because of
  2379. // CR_Replace conflicts.
  2380. DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
  2381. << " points: " << LHS << '\n');
  2382. LIS->extendToIndices((LiveRange&)LHS, EndPoints);
  2383. }
  2384. return true;
  2385. }
  2386. bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
  2387. return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
  2388. }
  2389. namespace {
  2390. /// Information concerning MBB coalescing priority.
  2391. struct MBBPriorityInfo {
  2392. MachineBasicBlock *MBB;
  2393. unsigned Depth;
  2394. bool IsSplit;
  2395. MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
  2396. : MBB(mbb), Depth(depth), IsSplit(issplit) {}
  2397. };
  2398. }
  2399. /// C-style comparator that sorts first based on the loop depth of the basic
  2400. /// block (the unsigned), and then on the MBB number.
  2401. ///
  2402. /// EnableGlobalCopies assumes that the primary sort key is loop depth.
  2403. // HLSL Change: changed calling convention to __cdecl
  2404. static int __cdecl compareMBBPriority(const MBBPriorityInfo *LHS,
  2405. const MBBPriorityInfo *RHS) {
  2406. // Deeper loops first
  2407. if (LHS->Depth != RHS->Depth)
  2408. return LHS->Depth > RHS->Depth ? -1 : 1;
  2409. // Try to unsplit critical edges next.
  2410. if (LHS->IsSplit != RHS->IsSplit)
  2411. return LHS->IsSplit ? -1 : 1;
  2412. // Prefer blocks that are more connected in the CFG. This takes care of
  2413. // the most difficult copies first while intervals are short.
  2414. unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
  2415. unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
  2416. if (cl != cr)
  2417. return cl > cr ? -1 : 1;
  2418. // As a last resort, sort by block number.
  2419. return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
  2420. }
  2421. /// \returns true if the given copy uses or defines a local live range.
  2422. static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
  2423. if (!Copy->isCopy())
  2424. return false;
  2425. if (Copy->getOperand(1).isUndef())
  2426. return false;
  2427. unsigned SrcReg = Copy->getOperand(1).getReg();
  2428. unsigned DstReg = Copy->getOperand(0).getReg();
  2429. if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
  2430. || TargetRegisterInfo::isPhysicalRegister(DstReg))
  2431. return false;
  2432. return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
  2433. || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
  2434. }
  2435. bool RegisterCoalescer::
  2436. copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
  2437. bool Progress = false;
  2438. for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
  2439. if (!CurrList[i])
  2440. continue;
  2441. // Skip instruction pointers that have already been erased, for example by
  2442. // dead code elimination.
  2443. if (ErasedInstrs.erase(CurrList[i])) {
  2444. CurrList[i] = nullptr;
  2445. continue;
  2446. }
  2447. bool Again = false;
  2448. bool Success = joinCopy(CurrList[i], Again);
  2449. Progress |= Success;
  2450. if (Success || !Again)
  2451. CurrList[i] = nullptr;
  2452. }
  2453. return Progress;
  2454. }
  2455. /// Check if DstReg is a terminal node.
  2456. /// I.e., it does not have any affinity other than \p Copy.
  2457. static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy,
  2458. const MachineRegisterInfo *MRI) {
  2459. assert(Copy.isCopyLike());
  2460. // Check if the destination of this copy as any other affinity.
  2461. for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
  2462. if (&MI != &Copy && MI.isCopyLike())
  2463. return false;
  2464. return true;
  2465. }
  2466. bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
  2467. assert(Copy.isCopyLike());
  2468. if (!UseTerminalRule)
  2469. return false;
  2470. unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
  2471. isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
  2472. // Check if the destination of this copy has any other affinity.
  2473. if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
  2474. // If SrcReg is a physical register, the copy won't be coalesced.
  2475. // Ignoring it may have other side effect (like missing
  2476. // rematerialization). So keep it.
  2477. TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
  2478. !isTerminalReg(DstReg, Copy, MRI))
  2479. return false;
  2480. // DstReg is a terminal node. Check if it inteferes with any other
  2481. // copy involving SrcReg.
  2482. const MachineBasicBlock *OrigBB = Copy.getParent();
  2483. const LiveInterval &DstLI = LIS->getInterval(DstReg);
  2484. for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
  2485. // Technically we should check if the weight of the new copy is
  2486. // interesting compared to the other one and update the weight
  2487. // of the copies accordingly. However, this would only work if
  2488. // we would gather all the copies first then coalesce, whereas
  2489. // right now we interleave both actions.
  2490. // For now, just consider the copies that are in the same block.
  2491. if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
  2492. continue;
  2493. unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
  2494. isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
  2495. OtherSubReg);
  2496. if (OtherReg == SrcReg)
  2497. OtherReg = OtherSrcReg;
  2498. // Check if OtherReg is a non-terminal.
  2499. if (TargetRegisterInfo::isPhysicalRegister(OtherReg) ||
  2500. isTerminalReg(OtherReg, MI, MRI))
  2501. continue;
  2502. // Check that OtherReg interfere with DstReg.
  2503. if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
  2504. DEBUG(dbgs() << "Apply terminal rule for: " << PrintReg(DstReg) << '\n');
  2505. return true;
  2506. }
  2507. }
  2508. return false;
  2509. }
  2510. void
  2511. RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
  2512. DEBUG(dbgs() << MBB->getName() << ":\n");
  2513. // Collect all copy-like instructions in MBB. Don't start coalescing anything
  2514. // yet, it might invalidate the iterator.
  2515. const unsigned PrevSize = WorkList.size();
  2516. if (JoinGlobalCopies) {
  2517. SmallVector<MachineInstr*, 2> LocalTerminals;
  2518. SmallVector<MachineInstr*, 2> GlobalTerminals;
  2519. // Coalesce copies bottom-up to coalesce local defs before local uses. They
  2520. // are not inherently easier to resolve, but slightly preferable until we
  2521. // have local live range splitting. In particular this is required by
  2522. // cmp+jmp macro fusion.
  2523. for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
  2524. MII != E; ++MII) {
  2525. if (!MII->isCopyLike())
  2526. continue;
  2527. bool ApplyTerminalRule = applyTerminalRule(*MII);
  2528. if (isLocalCopy(&(*MII), LIS)) {
  2529. if (ApplyTerminalRule)
  2530. LocalTerminals.push_back(&(*MII));
  2531. else
  2532. LocalWorkList.push_back(&(*MII));
  2533. } else {
  2534. if (ApplyTerminalRule)
  2535. GlobalTerminals.push_back(&(*MII));
  2536. else
  2537. WorkList.push_back(&(*MII));
  2538. }
  2539. }
  2540. // Append the copies evicted by the terminal rule at the end of the list.
  2541. LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
  2542. WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
  2543. }
  2544. else {
  2545. SmallVector<MachineInstr*, 2> Terminals;
  2546. for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
  2547. MII != E; ++MII)
  2548. if (MII->isCopyLike()) {
  2549. if (applyTerminalRule(*MII))
  2550. Terminals.push_back(&(*MII));
  2551. else
  2552. WorkList.push_back(MII);
  2553. }
  2554. // Append the copies evicted by the terminal rule at the end of the list.
  2555. WorkList.append(Terminals.begin(), Terminals.end());
  2556. }
  2557. // Try coalescing the collected copies immediately, and remove the nulls.
  2558. // This prevents the WorkList from getting too large since most copies are
  2559. // joinable on the first attempt.
  2560. MutableArrayRef<MachineInstr*>
  2561. CurrList(WorkList.begin() + PrevSize, WorkList.end());
  2562. if (copyCoalesceWorkList(CurrList))
  2563. WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
  2564. (MachineInstr*)nullptr), WorkList.end());
  2565. }
  2566. void RegisterCoalescer::coalesceLocals() {
  2567. copyCoalesceWorkList(LocalWorkList);
  2568. for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
  2569. if (LocalWorkList[j])
  2570. WorkList.push_back(LocalWorkList[j]);
  2571. }
  2572. LocalWorkList.clear();
  2573. }
  2574. void RegisterCoalescer::joinAllIntervals() {
  2575. DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
  2576. assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
  2577. std::vector<MBBPriorityInfo> MBBs;
  2578. MBBs.reserve(MF->size());
  2579. for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
  2580. MachineBasicBlock *MBB = I;
  2581. MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
  2582. JoinSplitEdges && isSplitEdge(MBB)));
  2583. }
  2584. array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
  2585. // Coalesce intervals in MBB priority order.
  2586. unsigned CurrDepth = UINT_MAX;
  2587. for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
  2588. // Try coalescing the collected local copies for deeper loops.
  2589. if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
  2590. coalesceLocals();
  2591. CurrDepth = MBBs[i].Depth;
  2592. }
  2593. copyCoalesceInMBB(MBBs[i].MBB);
  2594. }
  2595. coalesceLocals();
  2596. // Joining intervals can allow other intervals to be joined. Iteratively join
  2597. // until we make no progress.
  2598. while (copyCoalesceWorkList(WorkList))
  2599. /* empty */ ;
  2600. }
  2601. void RegisterCoalescer::releaseMemory() {
  2602. ErasedInstrs.clear();
  2603. WorkList.clear();
  2604. DeadDefs.clear();
  2605. InflateRegs.clear();
  2606. }
  2607. bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
  2608. MF = &fn;
  2609. MRI = &fn.getRegInfo();
  2610. TM = &fn.getTarget();
  2611. const TargetSubtargetInfo &STI = fn.getSubtarget();
  2612. TRI = STI.getRegisterInfo();
  2613. TII = STI.getInstrInfo();
  2614. LIS = &getAnalysis<LiveIntervals>();
  2615. AA = &getAnalysis<AliasAnalysis>();
  2616. Loops = &getAnalysis<MachineLoopInfo>();
  2617. if (EnableGlobalCopies == cl::BOU_UNSET)
  2618. JoinGlobalCopies = STI.enableJoinGlobalCopies();
  2619. else
  2620. JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
  2621. // The MachineScheduler does not currently require JoinSplitEdges. This will
  2622. // either be enabled unconditionally or replaced by a more general live range
  2623. // splitting optimization.
  2624. JoinSplitEdges = EnableJoinSplits;
  2625. DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
  2626. << "********** Function: " << MF->getName() << '\n');
  2627. if (VerifyCoalescing)
  2628. MF->verify(this, "Before register coalescing");
  2629. RegClassInfo.runOnMachineFunction(fn);
  2630. // Join (coalesce) intervals if requested.
  2631. if (EnableJoining)
  2632. joinAllIntervals();
  2633. // After deleting a lot of copies, register classes may be less constrained.
  2634. // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
  2635. // DPR inflation.
  2636. array_pod_sort(InflateRegs.begin(), InflateRegs.end());
  2637. InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
  2638. InflateRegs.end());
  2639. DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
  2640. for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
  2641. unsigned Reg = InflateRegs[i];
  2642. if (MRI->reg_nodbg_empty(Reg))
  2643. continue;
  2644. if (MRI->recomputeRegClass(Reg)) {
  2645. DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
  2646. << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
  2647. LiveInterval &LI = LIS->getInterval(Reg);
  2648. unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
  2649. if (MaxMask == 0) {
  2650. // If the inflated register class does not support subregisters anymore
  2651. // remove the subranges.
  2652. LI.clearSubRanges();
  2653. } else {
  2654. #ifndef NDEBUG
  2655. // If subranges are still supported, then the same subregs should still
  2656. // be supported.
  2657. for (LiveInterval::SubRange &S : LI.subranges()) {
  2658. assert ((S.LaneMask & ~MaxMask) == 0);
  2659. }
  2660. #endif
  2661. }
  2662. ++NumInflated;
  2663. }
  2664. }
  2665. DEBUG(dump());
  2666. if (VerifyCoalescing)
  2667. MF->verify(this, "After register coalescing");
  2668. return true;
  2669. }
  2670. void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
  2671. LIS->print(O, m);
  2672. }