LCOV - code coverage report
Current view: top level - lib/CodeGen - RegisterCoalescer.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1087 1219 89.2 %
Date: 2017-09-14 15:23:50 Functions: 62 65 95.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13