12cab237bSDimitry Andric //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
22cab237bSDimitry Andric //
32cab237bSDimitry Andric //                     The LLVM Compiler Infrastructure
42cab237bSDimitry Andric //
52cab237bSDimitry Andric // This file is distributed under the University of Illinois Open Source
62cab237bSDimitry Andric // License. See LICENSE.TXT for details.
72cab237bSDimitry Andric //
82cab237bSDimitry Andric //===----------------------------------------------------------------------===//
92cab237bSDimitry Andric //
102cab237bSDimitry Andric /// \file This file implements the LiveInterval analysis pass which is used
112cab237bSDimitry Andric /// by the Linear Scan Register allocator. This pass linearizes the
122cab237bSDimitry Andric /// basic blocks of the function in DFS order and computes live intervals for
132cab237bSDimitry Andric /// each virtual and physical register.
142cab237bSDimitry Andric //
152cab237bSDimitry Andric //===----------------------------------------------------------------------===//
162cab237bSDimitry Andric 
172cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
182cab237bSDimitry Andric #include "LiveRangeCalc.h"
192cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
202cab237bSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
212cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
222cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
232cab237bSDimitry Andric #include "llvm/ADT/iterator_range.h"
242cab237bSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
252cab237bSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
272cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
282cab237bSDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
302cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
312cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
322cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
332cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
342cab237bSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
352cab237bSDimitry Andric #include "llvm/CodeGen/Passes.h"
362cab237bSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
382cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
392cab237bSDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
40*4ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
412cab237bSDimitry Andric #include "llvm/MC/LaneBitmask.h"
422cab237bSDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
432cab237bSDimitry Andric #include "llvm/Pass.h"
442cab237bSDimitry Andric #include "llvm/Support/BlockFrequency.h"
452cab237bSDimitry Andric #include "llvm/Support/CommandLine.h"
462cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
472cab237bSDimitry Andric #include "llvm/Support/Debug.h"
482cab237bSDimitry Andric #include "llvm/Support/MathExtras.h"
492cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
502cab237bSDimitry Andric #include <algorithm>
512cab237bSDimitry Andric #include <cassert>
522cab237bSDimitry Andric #include <cstdint>
532cab237bSDimitry Andric #include <iterator>
542cab237bSDimitry Andric #include <tuple>
552cab237bSDimitry Andric #include <utility>
562cab237bSDimitry Andric 
572cab237bSDimitry Andric using namespace llvm;
582cab237bSDimitry Andric 
592cab237bSDimitry Andric #define DEBUG_TYPE "regalloc"
602cab237bSDimitry Andric 
612cab237bSDimitry Andric char LiveIntervals::ID = 0;
622cab237bSDimitry Andric char &llvm::LiveIntervalsID = LiveIntervals::ID;
632cab237bSDimitry Andric INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
642cab237bSDimitry Andric                 "Live Interval Analysis", false, false)
652cab237bSDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
662cab237bSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
672cab237bSDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
682cab237bSDimitry Andric INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
692cab237bSDimitry Andric                 "Live Interval Analysis", false, false)
702cab237bSDimitry Andric 
712cab237bSDimitry Andric #ifndef NDEBUG
722cab237bSDimitry Andric static cl::opt<bool> EnablePrecomputePhysRegs(
732cab237bSDimitry Andric   "precompute-phys-liveness", cl::Hidden,
742cab237bSDimitry Andric   cl::desc("Eagerly compute live intervals for all physreg units."));
752cab237bSDimitry Andric #else
762cab237bSDimitry Andric static bool EnablePrecomputePhysRegs = false;
772cab237bSDimitry Andric #endif // NDEBUG
782cab237bSDimitry Andric 
792cab237bSDimitry Andric namespace llvm {
802cab237bSDimitry Andric 
812cab237bSDimitry Andric cl::opt<bool> UseSegmentSetForPhysRegs(
822cab237bSDimitry Andric     "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
832cab237bSDimitry Andric     cl::desc(
842cab237bSDimitry Andric         "Use segment set for the computation of the live ranges of physregs."));
852cab237bSDimitry Andric 
862cab237bSDimitry Andric } // end namespace llvm
872cab237bSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const882cab237bSDimitry Andric void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
892cab237bSDimitry Andric   AU.setPreservesCFG();
902cab237bSDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
912cab237bSDimitry Andric   AU.addPreserved<AAResultsWrapperPass>();
922cab237bSDimitry Andric   AU.addPreserved<LiveVariables>();
932cab237bSDimitry Andric   AU.addPreservedID(MachineLoopInfoID);
942cab237bSDimitry Andric   AU.addRequiredTransitiveID(MachineDominatorsID);
952cab237bSDimitry Andric   AU.addPreservedID(MachineDominatorsID);
962cab237bSDimitry Andric   AU.addPreserved<SlotIndexes>();
972cab237bSDimitry Andric   AU.addRequiredTransitive<SlotIndexes>();
982cab237bSDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
992cab237bSDimitry Andric }
1002cab237bSDimitry Andric 
LiveIntervals()1012cab237bSDimitry Andric LiveIntervals::LiveIntervals() : MachineFunctionPass(ID) {
1022cab237bSDimitry Andric   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
1032cab237bSDimitry Andric }
1042cab237bSDimitry Andric 
~LiveIntervals()1052cab237bSDimitry Andric LiveIntervals::~LiveIntervals() {
1062cab237bSDimitry Andric   delete LRCalc;
1072cab237bSDimitry Andric }
1082cab237bSDimitry Andric 
releaseMemory()1092cab237bSDimitry Andric void LiveIntervals::releaseMemory() {
1102cab237bSDimitry Andric   // Free the live intervals themselves.
1112cab237bSDimitry Andric   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
1122cab237bSDimitry Andric     delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
1132cab237bSDimitry Andric   VirtRegIntervals.clear();
1142cab237bSDimitry Andric   RegMaskSlots.clear();
1152cab237bSDimitry Andric   RegMaskBits.clear();
1162cab237bSDimitry Andric   RegMaskBlocks.clear();
1172cab237bSDimitry Andric 
1182cab237bSDimitry Andric   for (LiveRange *LR : RegUnitRanges)
1192cab237bSDimitry Andric     delete LR;
1202cab237bSDimitry Andric   RegUnitRanges.clear();
1212cab237bSDimitry Andric 
1222cab237bSDimitry Andric   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
1232cab237bSDimitry Andric   VNInfoAllocator.Reset();
1242cab237bSDimitry Andric }
1252cab237bSDimitry Andric 
runOnMachineFunction(MachineFunction & fn)1262cab237bSDimitry Andric bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
1272cab237bSDimitry Andric   MF = &fn;
1282cab237bSDimitry Andric   MRI = &MF->getRegInfo();
1292cab237bSDimitry Andric   TRI = MF->getSubtarget().getRegisterInfo();
1302cab237bSDimitry Andric   TII = MF->getSubtarget().getInstrInfo();
1312cab237bSDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1322cab237bSDimitry Andric   Indexes = &getAnalysis<SlotIndexes>();
1332cab237bSDimitry Andric   DomTree = &getAnalysis<MachineDominatorTree>();
1342cab237bSDimitry Andric 
1352cab237bSDimitry Andric   if (!LRCalc)
1362cab237bSDimitry Andric     LRCalc = new LiveRangeCalc();
1372cab237bSDimitry Andric 
1382cab237bSDimitry Andric   // Allocate space for all virtual registers.
1392cab237bSDimitry Andric   VirtRegIntervals.resize(MRI->getNumVirtRegs());
1402cab237bSDimitry Andric 
1412cab237bSDimitry Andric   computeVirtRegs();
1422cab237bSDimitry Andric   computeRegMasks();
1432cab237bSDimitry Andric   computeLiveInRegUnits();
1442cab237bSDimitry Andric 
1452cab237bSDimitry Andric   if (EnablePrecomputePhysRegs) {
1462cab237bSDimitry Andric     // For stress testing, precompute live ranges of all physical register
1472cab237bSDimitry Andric     // units, including reserved registers.
1482cab237bSDimitry Andric     for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1492cab237bSDimitry Andric       getRegUnit(i);
1502cab237bSDimitry Andric   }
151*4ba319b5SDimitry Andric   LLVM_DEBUG(dump());
1522cab237bSDimitry Andric   return true;
1532cab237bSDimitry Andric }
1542cab237bSDimitry Andric 
print(raw_ostream & OS,const Module *) const1552cab237bSDimitry Andric void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
1562cab237bSDimitry Andric   OS << "********** INTERVALS **********\n";
1572cab237bSDimitry Andric 
1582cab237bSDimitry Andric   // Dump the regunits.
1592cab237bSDimitry Andric   for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
1602cab237bSDimitry Andric     if (LiveRange *LR = RegUnitRanges[Unit])
1612cab237bSDimitry Andric       OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
1622cab237bSDimitry Andric 
1632cab237bSDimitry Andric   // Dump the virtregs.
1642cab237bSDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1652cab237bSDimitry Andric     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1662cab237bSDimitry Andric     if (hasInterval(Reg))
1672cab237bSDimitry Andric       OS << getInterval(Reg) << '\n';
1682cab237bSDimitry Andric   }
1692cab237bSDimitry Andric 
1702cab237bSDimitry Andric   OS << "RegMasks:";
1712cab237bSDimitry Andric   for (SlotIndex Idx : RegMaskSlots)
1722cab237bSDimitry Andric     OS << ' ' << Idx;
1732cab237bSDimitry Andric   OS << '\n';
1742cab237bSDimitry Andric 
1752cab237bSDimitry Andric   printInstrs(OS);
1762cab237bSDimitry Andric }
1772cab237bSDimitry Andric 
printInstrs(raw_ostream & OS) const1782cab237bSDimitry Andric void LiveIntervals::printInstrs(raw_ostream &OS) const {
1792cab237bSDimitry Andric   OS << "********** MACHINEINSTRS **********\n";
1802cab237bSDimitry Andric   MF->print(OS, Indexes);
1812cab237bSDimitry Andric }
1822cab237bSDimitry Andric 
1832cab237bSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpInstrs() const1842cab237bSDimitry Andric LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
1852cab237bSDimitry Andric   printInstrs(dbgs());
1862cab237bSDimitry Andric }
1872cab237bSDimitry Andric #endif
1882cab237bSDimitry Andric 
createInterval(unsigned reg)1892cab237bSDimitry Andric LiveInterval* LiveIntervals::createInterval(unsigned reg) {
1902cab237bSDimitry Andric   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? huge_valf : 0.0F;
1912cab237bSDimitry Andric   return new LiveInterval(reg, Weight);
1922cab237bSDimitry Andric }
1932cab237bSDimitry Andric 
1942cab237bSDimitry Andric /// Compute the live interval of a virtual register, based on defs and uses.
computeVirtRegInterval(LiveInterval & LI)1952cab237bSDimitry Andric void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
1962cab237bSDimitry Andric   assert(LRCalc && "LRCalc not initialized.");
1972cab237bSDimitry Andric   assert(LI.empty() && "Should only compute empty intervals.");
1982cab237bSDimitry Andric   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1992cab237bSDimitry Andric   LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
2002cab237bSDimitry Andric   computeDeadValues(LI, nullptr);
2012cab237bSDimitry Andric }
2022cab237bSDimitry Andric 
computeVirtRegs()2032cab237bSDimitry Andric void LiveIntervals::computeVirtRegs() {
2042cab237bSDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
2052cab237bSDimitry Andric     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
2062cab237bSDimitry Andric     if (MRI->reg_nodbg_empty(Reg))
2072cab237bSDimitry Andric       continue;
2082cab237bSDimitry Andric     createAndComputeVirtRegInterval(Reg);
2092cab237bSDimitry Andric   }
2102cab237bSDimitry Andric }
2112cab237bSDimitry Andric 
computeRegMasks()2122cab237bSDimitry Andric void LiveIntervals::computeRegMasks() {
2132cab237bSDimitry Andric   RegMaskBlocks.resize(MF->getNumBlockIDs());
2142cab237bSDimitry Andric 
2152cab237bSDimitry Andric   // Find all instructions with regmask operands.
2162cab237bSDimitry Andric   for (const MachineBasicBlock &MBB : *MF) {
2172cab237bSDimitry Andric     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
2182cab237bSDimitry Andric     RMB.first = RegMaskSlots.size();
2192cab237bSDimitry Andric 
2202cab237bSDimitry Andric     // Some block starts, such as EH funclets, create masks.
2212cab237bSDimitry Andric     if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
2222cab237bSDimitry Andric       RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
2232cab237bSDimitry Andric       RegMaskBits.push_back(Mask);
2242cab237bSDimitry Andric     }
2252cab237bSDimitry Andric 
2262cab237bSDimitry Andric     for (const MachineInstr &MI : MBB) {
2272cab237bSDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
2282cab237bSDimitry Andric         if (!MO.isRegMask())
2292cab237bSDimitry Andric           continue;
2302cab237bSDimitry Andric         RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
2312cab237bSDimitry Andric         RegMaskBits.push_back(MO.getRegMask());
2322cab237bSDimitry Andric       }
2332cab237bSDimitry Andric     }
2342cab237bSDimitry Andric 
2352cab237bSDimitry Andric     // Some block ends, such as funclet returns, create masks. Put the mask on
2362cab237bSDimitry Andric     // the last instruction of the block, because MBB slot index intervals are
2372cab237bSDimitry Andric     // half-open.
2382cab237bSDimitry Andric     if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
2392cab237bSDimitry Andric       assert(!MBB.empty() && "empty return block?");
2402cab237bSDimitry Andric       RegMaskSlots.push_back(
2412cab237bSDimitry Andric           Indexes->getInstructionIndex(MBB.back()).getRegSlot());
2422cab237bSDimitry Andric       RegMaskBits.push_back(Mask);
2432cab237bSDimitry Andric     }
2442cab237bSDimitry Andric 
2452cab237bSDimitry Andric     // Compute the number of register mask instructions in this block.
2462cab237bSDimitry Andric     RMB.second = RegMaskSlots.size() - RMB.first;
2472cab237bSDimitry Andric   }
2482cab237bSDimitry Andric }
2492cab237bSDimitry Andric 
2502cab237bSDimitry Andric //===----------------------------------------------------------------------===//
2512cab237bSDimitry Andric //                           Register Unit Liveness
2522cab237bSDimitry Andric //===----------------------------------------------------------------------===//
2532cab237bSDimitry Andric //
2542cab237bSDimitry Andric // Fixed interference typically comes from ABI boundaries: Function arguments
2552cab237bSDimitry Andric // and return values are passed in fixed registers, and so are exception
2562cab237bSDimitry Andric // pointers entering landing pads. Certain instructions require values to be
2572cab237bSDimitry Andric // present in specific registers. That is also represented through fixed
2582cab237bSDimitry Andric // interference.
2592cab237bSDimitry Andric //
2602cab237bSDimitry Andric 
2612cab237bSDimitry Andric /// Compute the live range of a register unit, based on the uses and defs of
2622cab237bSDimitry Andric /// aliasing registers.  The range should be empty, or contain only dead
2632cab237bSDimitry Andric /// phi-defs from ABI blocks.
computeRegUnitRange(LiveRange & LR,unsigned Unit)2642cab237bSDimitry Andric void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
2652cab237bSDimitry Andric   assert(LRCalc && "LRCalc not initialized.");
2662cab237bSDimitry Andric   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
2672cab237bSDimitry Andric 
2682cab237bSDimitry Andric   // The physregs aliasing Unit are the roots and their super-registers.
2692cab237bSDimitry Andric   // Create all values as dead defs before extending to uses. Note that roots
2702cab237bSDimitry Andric   // may share super-registers. That's OK because createDeadDefs() is
2712cab237bSDimitry Andric   // idempotent. It is very rare for a register unit to have multiple roots, so
2722cab237bSDimitry Andric   // uniquing super-registers is probably not worthwhile.
2732cab237bSDimitry Andric   bool IsReserved = false;
2742cab237bSDimitry Andric   for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
2752cab237bSDimitry Andric     bool IsRootReserved = true;
2762cab237bSDimitry Andric     for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
2772cab237bSDimitry Andric          Super.isValid(); ++Super) {
2782cab237bSDimitry Andric       unsigned Reg = *Super;
2792cab237bSDimitry Andric       if (!MRI->reg_empty(Reg))
2802cab237bSDimitry Andric         LRCalc->createDeadDefs(LR, Reg);
2812cab237bSDimitry Andric       // A register unit is considered reserved if all its roots and all their
2822cab237bSDimitry Andric       // super registers are reserved.
2832cab237bSDimitry Andric       if (!MRI->isReserved(Reg))
2842cab237bSDimitry Andric         IsRootReserved = false;
2852cab237bSDimitry Andric     }
2862cab237bSDimitry Andric     IsReserved |= IsRootReserved;
2872cab237bSDimitry Andric   }
2882cab237bSDimitry Andric   assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
2892cab237bSDimitry Andric          "reserved computation mismatch");
2902cab237bSDimitry Andric 
2912cab237bSDimitry Andric   // Now extend LR to reach all uses.
2922cab237bSDimitry Andric   // Ignore uses of reserved registers. We only track defs of those.
2932cab237bSDimitry Andric   if (!IsReserved) {
2942cab237bSDimitry Andric     for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
2952cab237bSDimitry Andric       for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
2962cab237bSDimitry Andric            Super.isValid(); ++Super) {
2972cab237bSDimitry Andric         unsigned Reg = *Super;
2982cab237bSDimitry Andric         if (!MRI->reg_empty(Reg))
2992cab237bSDimitry Andric           LRCalc->extendToUses(LR, Reg);
3002cab237bSDimitry Andric       }
3012cab237bSDimitry Andric     }
3022cab237bSDimitry Andric   }
3032cab237bSDimitry Andric 
3042cab237bSDimitry Andric   // Flush the segment set to the segment vector.
3052cab237bSDimitry Andric   if (UseSegmentSetForPhysRegs)
3062cab237bSDimitry Andric     LR.flushSegmentSet();
3072cab237bSDimitry Andric }
3082cab237bSDimitry Andric 
3092cab237bSDimitry Andric /// Precompute the live ranges of any register units that are live-in to an ABI
3102cab237bSDimitry Andric /// block somewhere. Register values can appear without a corresponding def when
3112cab237bSDimitry Andric /// entering the entry block or a landing pad.
computeLiveInRegUnits()3122cab237bSDimitry Andric void LiveIntervals::computeLiveInRegUnits() {
3132cab237bSDimitry Andric   RegUnitRanges.resize(TRI->getNumRegUnits());
314*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
3152cab237bSDimitry Andric 
3162cab237bSDimitry Andric   // Keep track of the live range sets allocated.
3172cab237bSDimitry Andric   SmallVector<unsigned, 8> NewRanges;
3182cab237bSDimitry Andric 
3192cab237bSDimitry Andric   // Check all basic blocks for live-ins.
3202cab237bSDimitry Andric   for (const MachineBasicBlock &MBB : *MF) {
3212cab237bSDimitry Andric     // We only care about ABI blocks: Entry + landing pads.
3222cab237bSDimitry Andric     if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
3232cab237bSDimitry Andric       continue;
3242cab237bSDimitry Andric 
3252cab237bSDimitry Andric     // Create phi-defs at Begin for all live-in registers.
3262cab237bSDimitry Andric     SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
327*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
3282cab237bSDimitry Andric     for (const auto &LI : MBB.liveins()) {
3292cab237bSDimitry Andric       for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
3302cab237bSDimitry Andric         unsigned Unit = *Units;
3312cab237bSDimitry Andric         LiveRange *LR = RegUnitRanges[Unit];
3322cab237bSDimitry Andric         if (!LR) {
3332cab237bSDimitry Andric           // Use segment set to speed-up initial computation of the live range.
3342cab237bSDimitry Andric           LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
3352cab237bSDimitry Andric           NewRanges.push_back(Unit);
3362cab237bSDimitry Andric         }
3372cab237bSDimitry Andric         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
3382cab237bSDimitry Andric         (void)VNI;
339*4ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
3402cab237bSDimitry Andric       }
3412cab237bSDimitry Andric     }
342*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
3432cab237bSDimitry Andric   }
344*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
3452cab237bSDimitry Andric 
3462cab237bSDimitry Andric   // Compute the 'normal' part of the ranges.
3472cab237bSDimitry Andric   for (unsigned Unit : NewRanges)
3482cab237bSDimitry Andric     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
3492cab237bSDimitry Andric }
3502cab237bSDimitry Andric 
createSegmentsForValues(LiveRange & LR,iterator_range<LiveInterval::vni_iterator> VNIs)3512cab237bSDimitry Andric static void createSegmentsForValues(LiveRange &LR,
3522cab237bSDimitry Andric     iterator_range<LiveInterval::vni_iterator> VNIs) {
3532cab237bSDimitry Andric   for (VNInfo *VNI : VNIs) {
3542cab237bSDimitry Andric     if (VNI->isUnused())
3552cab237bSDimitry Andric       continue;
3562cab237bSDimitry Andric     SlotIndex Def = VNI->def;
3572cab237bSDimitry Andric     LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
3582cab237bSDimitry Andric   }
3592cab237bSDimitry Andric }
3602cab237bSDimitry Andric 
extendSegmentsToUses(LiveRange & Segments,ShrinkToUsesWorkList & WorkList,unsigned Reg,LaneBitmask LaneMask)361*4ba319b5SDimitry Andric void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
3622cab237bSDimitry Andric                                          ShrinkToUsesWorkList &WorkList,
363*4ba319b5SDimitry Andric                                          unsigned Reg, LaneBitmask LaneMask) {
3642cab237bSDimitry Andric   // Keep track of the PHIs that are in use.
3652cab237bSDimitry Andric   SmallPtrSet<VNInfo*, 8> UsedPHIs;
3662cab237bSDimitry Andric   // Blocks that have already been added to WorkList as live-out.
3672cab237bSDimitry Andric   SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
3682cab237bSDimitry Andric 
369*4ba319b5SDimitry Andric   auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
370*4ba319b5SDimitry Andric         -> const LiveRange& {
371*4ba319b5SDimitry Andric     if (M.none())
372*4ba319b5SDimitry Andric       return I;
373*4ba319b5SDimitry Andric     for (const LiveInterval::SubRange &SR : I.subranges()) {
374*4ba319b5SDimitry Andric       if ((SR.LaneMask & M).any()) {
375*4ba319b5SDimitry Andric         assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
376*4ba319b5SDimitry Andric         return SR;
377*4ba319b5SDimitry Andric       }
378*4ba319b5SDimitry Andric     }
379*4ba319b5SDimitry Andric     llvm_unreachable("Subrange for mask not found");
380*4ba319b5SDimitry Andric   };
381*4ba319b5SDimitry Andric 
382*4ba319b5SDimitry Andric   const LiveInterval &LI = getInterval(Reg);
383*4ba319b5SDimitry Andric   const LiveRange &OldRange = getSubRange(LI, LaneMask);
384*4ba319b5SDimitry Andric 
3852cab237bSDimitry Andric   // Extend intervals to reach all uses in WorkList.
3862cab237bSDimitry Andric   while (!WorkList.empty()) {
3872cab237bSDimitry Andric     SlotIndex Idx = WorkList.back().first;
3882cab237bSDimitry Andric     VNInfo *VNI = WorkList.back().second;
3892cab237bSDimitry Andric     WorkList.pop_back();
390*4ba319b5SDimitry Andric     const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
391*4ba319b5SDimitry Andric     SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
3922cab237bSDimitry Andric 
3932cab237bSDimitry Andric     // Extend the live range for VNI to be live at Idx.
394*4ba319b5SDimitry Andric     if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
3952cab237bSDimitry Andric       assert(ExtVNI == VNI && "Unexpected existing value number");
3962cab237bSDimitry Andric       (void)ExtVNI;
3972cab237bSDimitry Andric       // Is this a PHIDef we haven't seen before?
3982cab237bSDimitry Andric       if (!VNI->isPHIDef() || VNI->def != BlockStart ||
3992cab237bSDimitry Andric           !UsedPHIs.insert(VNI).second)
4002cab237bSDimitry Andric         continue;
4012cab237bSDimitry Andric       // The PHI is live, make sure the predecessors are live-out.
4022cab237bSDimitry Andric       for (const MachineBasicBlock *Pred : MBB->predecessors()) {
4032cab237bSDimitry Andric         if (!LiveOut.insert(Pred).second)
4042cab237bSDimitry Andric           continue;
405*4ba319b5SDimitry Andric         SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
4062cab237bSDimitry Andric         // A predecessor is not required to have a live-out value for a PHI.
4072cab237bSDimitry Andric         if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
4082cab237bSDimitry Andric           WorkList.push_back(std::make_pair(Stop, PVNI));
4092cab237bSDimitry Andric       }
4102cab237bSDimitry Andric       continue;
4112cab237bSDimitry Andric     }
4122cab237bSDimitry Andric 
4132cab237bSDimitry Andric     // VNI is live-in to MBB.
414*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
415*4ba319b5SDimitry Andric     Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
4162cab237bSDimitry Andric 
4172cab237bSDimitry Andric     // Make sure VNI is live-out from the predecessors.
4182cab237bSDimitry Andric     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
4192cab237bSDimitry Andric       if (!LiveOut.insert(Pred).second)
4202cab237bSDimitry Andric         continue;
421*4ba319b5SDimitry Andric       SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
422*4ba319b5SDimitry Andric       if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
423*4ba319b5SDimitry Andric         assert(OldVNI == VNI && "Wrong value out of predecessor");
424*4ba319b5SDimitry Andric         (void)OldVNI;
4252cab237bSDimitry Andric         WorkList.push_back(std::make_pair(Stop, VNI));
426*4ba319b5SDimitry Andric       } else {
427*4ba319b5SDimitry Andric #ifndef NDEBUG
428*4ba319b5SDimitry Andric         // There was no old VNI. Verify that Stop is jointly dominated
429*4ba319b5SDimitry Andric         // by <undef>s for this live range.
430*4ba319b5SDimitry Andric         assert(LaneMask.any() &&
431*4ba319b5SDimitry Andric                "Missing value out of predecessor for main range");
432*4ba319b5SDimitry Andric         SmallVector<SlotIndex,8> Undefs;
433*4ba319b5SDimitry Andric         LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
434*4ba319b5SDimitry Andric         assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
435*4ba319b5SDimitry Andric                "Missing value out of predecessor for subrange");
436*4ba319b5SDimitry Andric #endif
437*4ba319b5SDimitry Andric       }
4382cab237bSDimitry Andric     }
4392cab237bSDimitry Andric   }
4402cab237bSDimitry Andric }
4412cab237bSDimitry Andric 
shrinkToUses(LiveInterval * li,SmallVectorImpl<MachineInstr * > * dead)4422cab237bSDimitry Andric bool LiveIntervals::shrinkToUses(LiveInterval *li,
4432cab237bSDimitry Andric                                  SmallVectorImpl<MachineInstr*> *dead) {
444*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
4452cab237bSDimitry Andric   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
4462cab237bSDimitry Andric          && "Can only shrink virtual registers");
4472cab237bSDimitry Andric 
4482cab237bSDimitry Andric   // Shrink subregister live ranges.
4492cab237bSDimitry Andric   bool NeedsCleanup = false;
4502cab237bSDimitry Andric   for (LiveInterval::SubRange &S : li->subranges()) {
4512cab237bSDimitry Andric     shrinkToUses(S, li->reg);
4522cab237bSDimitry Andric     if (S.empty())
4532cab237bSDimitry Andric       NeedsCleanup = true;
4542cab237bSDimitry Andric   }
4552cab237bSDimitry Andric   if (NeedsCleanup)
4562cab237bSDimitry Andric     li->removeEmptySubRanges();
4572cab237bSDimitry Andric 
4582cab237bSDimitry Andric   // Find all the values used, including PHI kills.
4592cab237bSDimitry Andric   ShrinkToUsesWorkList WorkList;
4602cab237bSDimitry Andric 
4612cab237bSDimitry Andric   // Visit all instructions reading li->reg.
4622cab237bSDimitry Andric   unsigned Reg = li->reg;
4632cab237bSDimitry Andric   for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
4642cab237bSDimitry Andric     if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg))
4652cab237bSDimitry Andric       continue;
4662cab237bSDimitry Andric     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
4672cab237bSDimitry Andric     LiveQueryResult LRQ = li->Query(Idx);
4682cab237bSDimitry Andric     VNInfo *VNI = LRQ.valueIn();
4692cab237bSDimitry Andric     if (!VNI) {
4702cab237bSDimitry Andric       // This shouldn't happen: readsVirtualRegister returns true, but there is
4712cab237bSDimitry Andric       // no live value. It is likely caused by a target getting <undef> flags
4722cab237bSDimitry Andric       // wrong.
473*4ba319b5SDimitry Andric       LLVM_DEBUG(
474*4ba319b5SDimitry Andric           dbgs() << Idx << '\t' << UseMI
4752cab237bSDimitry Andric                  << "Warning: Instr claims to read non-existent value in "
4762cab237bSDimitry Andric                  << *li << '\n');
4772cab237bSDimitry Andric       continue;
4782cab237bSDimitry Andric     }
4792cab237bSDimitry Andric     // Special case: An early-clobber tied operand reads and writes the
4802cab237bSDimitry Andric     // register one slot early.
4812cab237bSDimitry Andric     if (VNInfo *DefVNI = LRQ.valueDefined())
4822cab237bSDimitry Andric       Idx = DefVNI->def;
4832cab237bSDimitry Andric 
4842cab237bSDimitry Andric     WorkList.push_back(std::make_pair(Idx, VNI));
4852cab237bSDimitry Andric   }
4862cab237bSDimitry Andric 
4872cab237bSDimitry Andric   // Create new live ranges with only minimal live segments per def.
4882cab237bSDimitry Andric   LiveRange NewLR;
4892cab237bSDimitry Andric   createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
490*4ba319b5SDimitry Andric   extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
4912cab237bSDimitry Andric 
4922cab237bSDimitry Andric   // Move the trimmed segments back.
4932cab237bSDimitry Andric   li->segments.swap(NewLR.segments);
4942cab237bSDimitry Andric 
4952cab237bSDimitry Andric   // Handle dead values.
4962cab237bSDimitry Andric   bool CanSeparate = computeDeadValues(*li, dead);
497*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
4982cab237bSDimitry Andric   return CanSeparate;
4992cab237bSDimitry Andric }
5002cab237bSDimitry Andric 
computeDeadValues(LiveInterval & LI,SmallVectorImpl<MachineInstr * > * dead)5012cab237bSDimitry Andric bool LiveIntervals::computeDeadValues(LiveInterval &LI,
5022cab237bSDimitry Andric                                       SmallVectorImpl<MachineInstr*> *dead) {
5032cab237bSDimitry Andric   bool MayHaveSplitComponents = false;
5042cab237bSDimitry Andric   for (VNInfo *VNI : LI.valnos) {
5052cab237bSDimitry Andric     if (VNI->isUnused())
5062cab237bSDimitry Andric       continue;
5072cab237bSDimitry Andric     SlotIndex Def = VNI->def;
5082cab237bSDimitry Andric     LiveRange::iterator I = LI.FindSegmentContaining(Def);
5092cab237bSDimitry Andric     assert(I != LI.end() && "Missing segment for VNI");
5102cab237bSDimitry Andric 
5112cab237bSDimitry Andric     // Is the register live before? Otherwise we may have to add a read-undef
5122cab237bSDimitry Andric     // flag for subregister defs.
5132cab237bSDimitry Andric     unsigned VReg = LI.reg;
5142cab237bSDimitry Andric     if (MRI->shouldTrackSubRegLiveness(VReg)) {
5152cab237bSDimitry Andric       if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
5162cab237bSDimitry Andric         MachineInstr *MI = getInstructionFromIndex(Def);
5172cab237bSDimitry Andric         MI->setRegisterDefReadUndef(VReg);
5182cab237bSDimitry Andric       }
5192cab237bSDimitry Andric     }
5202cab237bSDimitry Andric 
5212cab237bSDimitry Andric     if (I->end != Def.getDeadSlot())
5222cab237bSDimitry Andric       continue;
5232cab237bSDimitry Andric     if (VNI->isPHIDef()) {
5242cab237bSDimitry Andric       // This is a dead PHI. Remove it.
5252cab237bSDimitry Andric       VNI->markUnused();
5262cab237bSDimitry Andric       LI.removeSegment(I);
527*4ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
5282cab237bSDimitry Andric       MayHaveSplitComponents = true;
5292cab237bSDimitry Andric     } else {
5302cab237bSDimitry Andric       // This is a dead def. Make sure the instruction knows.
5312cab237bSDimitry Andric       MachineInstr *MI = getInstructionFromIndex(Def);
5322cab237bSDimitry Andric       assert(MI && "No instruction defining live value");
5332cab237bSDimitry Andric       MI->addRegisterDead(LI.reg, TRI);
5342cab237bSDimitry Andric       if (dead && MI->allDefsAreDead()) {
535*4ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
5362cab237bSDimitry Andric         dead->push_back(MI);
5372cab237bSDimitry Andric       }
5382cab237bSDimitry Andric     }
5392cab237bSDimitry Andric   }
5402cab237bSDimitry Andric   return MayHaveSplitComponents;
5412cab237bSDimitry Andric }
5422cab237bSDimitry Andric 
shrinkToUses(LiveInterval::SubRange & SR,unsigned Reg)5432cab237bSDimitry Andric void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg) {
544*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
5452cab237bSDimitry Andric   assert(TargetRegisterInfo::isVirtualRegister(Reg)
5462cab237bSDimitry Andric          && "Can only shrink virtual registers");
5472cab237bSDimitry Andric   // Find all the values used, including PHI kills.
5482cab237bSDimitry Andric   ShrinkToUsesWorkList WorkList;
5492cab237bSDimitry Andric 
5502cab237bSDimitry Andric   // Visit all instructions reading Reg.
5512cab237bSDimitry Andric   SlotIndex LastIdx;
5522cab237bSDimitry Andric   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
5532cab237bSDimitry Andric     // Skip "undef" uses.
5542cab237bSDimitry Andric     if (!MO.readsReg())
5552cab237bSDimitry Andric       continue;
5562cab237bSDimitry Andric     // Maybe the operand is for a subregister we don't care about.
5572cab237bSDimitry Andric     unsigned SubReg = MO.getSubReg();
5582cab237bSDimitry Andric     if (SubReg != 0) {
5592cab237bSDimitry Andric       LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
5602cab237bSDimitry Andric       if ((LaneMask & SR.LaneMask).none())
5612cab237bSDimitry Andric         continue;
5622cab237bSDimitry Andric     }
5632cab237bSDimitry Andric     // We only need to visit each instruction once.
5642cab237bSDimitry Andric     MachineInstr *UseMI = MO.getParent();
5652cab237bSDimitry Andric     SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
5662cab237bSDimitry Andric     if (Idx == LastIdx)
5672cab237bSDimitry Andric       continue;
5682cab237bSDimitry Andric     LastIdx = Idx;
5692cab237bSDimitry Andric 
5702cab237bSDimitry Andric     LiveQueryResult LRQ = SR.Query(Idx);
5712cab237bSDimitry Andric     VNInfo *VNI = LRQ.valueIn();
5722cab237bSDimitry Andric     // For Subranges it is possible that only undef values are left in that
5732cab237bSDimitry Andric     // part of the subregister, so there is no real liverange at the use
5742cab237bSDimitry Andric     if (!VNI)
5752cab237bSDimitry Andric       continue;
5762cab237bSDimitry Andric 
5772cab237bSDimitry Andric     // Special case: An early-clobber tied operand reads and writes the
5782cab237bSDimitry Andric     // register one slot early.
5792cab237bSDimitry Andric     if (VNInfo *DefVNI = LRQ.valueDefined())
5802cab237bSDimitry Andric       Idx = DefVNI->def;
5812cab237bSDimitry Andric 
5822cab237bSDimitry Andric     WorkList.push_back(std::make_pair(Idx, VNI));
5832cab237bSDimitry Andric   }
5842cab237bSDimitry Andric 
5852cab237bSDimitry Andric   // Create a new live ranges with only minimal live segments per def.
5862cab237bSDimitry Andric   LiveRange NewLR;
5872cab237bSDimitry Andric   createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
588*4ba319b5SDimitry Andric   extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
5892cab237bSDimitry Andric 
5902cab237bSDimitry Andric   // Move the trimmed ranges back.
5912cab237bSDimitry Andric   SR.segments.swap(NewLR.segments);
5922cab237bSDimitry Andric 
5932cab237bSDimitry Andric   // Remove dead PHI value numbers
5942cab237bSDimitry Andric   for (VNInfo *VNI : SR.valnos) {
5952cab237bSDimitry Andric     if (VNI->isUnused())
5962cab237bSDimitry Andric       continue;
5972cab237bSDimitry Andric     const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
5982cab237bSDimitry Andric     assert(Segment != nullptr && "Missing segment for VNI");
5992cab237bSDimitry Andric     if (Segment->end != VNI->def.getDeadSlot())
6002cab237bSDimitry Andric       continue;
6012cab237bSDimitry Andric     if (VNI->isPHIDef()) {
6022cab237bSDimitry Andric       // This is a dead PHI. Remove it.
603*4ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
604*4ba319b5SDimitry Andric                         << " may separate interval\n");
6052cab237bSDimitry Andric       VNI->markUnused();
6062cab237bSDimitry Andric       SR.removeSegment(*Segment);
6072cab237bSDimitry Andric     }
6082cab237bSDimitry Andric   }
6092cab237bSDimitry Andric 
610*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
6112cab237bSDimitry Andric }
6122cab237bSDimitry Andric 
extendToIndices(LiveRange & LR,ArrayRef<SlotIndex> Indices,ArrayRef<SlotIndex> Undefs)6132cab237bSDimitry Andric void LiveIntervals::extendToIndices(LiveRange &LR,
6142cab237bSDimitry Andric                                     ArrayRef<SlotIndex> Indices,
6152cab237bSDimitry Andric                                     ArrayRef<SlotIndex> Undefs) {
6162cab237bSDimitry Andric   assert(LRCalc && "LRCalc not initialized.");
6172cab237bSDimitry Andric   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
6182cab237bSDimitry Andric   for (SlotIndex Idx : Indices)
6192cab237bSDimitry Andric     LRCalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
6202cab237bSDimitry Andric }
6212cab237bSDimitry Andric 
pruneValue(LiveRange & LR,SlotIndex Kill,SmallVectorImpl<SlotIndex> * EndPoints)6222cab237bSDimitry Andric void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
6232cab237bSDimitry Andric                                SmallVectorImpl<SlotIndex> *EndPoints) {
6242cab237bSDimitry Andric   LiveQueryResult LRQ = LR.Query(Kill);
6252cab237bSDimitry Andric   VNInfo *VNI = LRQ.valueOutOrDead();
6262cab237bSDimitry Andric   if (!VNI)
6272cab237bSDimitry Andric     return;
6282cab237bSDimitry Andric 
6292cab237bSDimitry Andric   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
6302cab237bSDimitry Andric   SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
6312cab237bSDimitry Andric 
6322cab237bSDimitry Andric   // If VNI isn't live out from KillMBB, the value is trivially pruned.
6332cab237bSDimitry Andric   if (LRQ.endPoint() < MBBEnd) {
6342cab237bSDimitry Andric     LR.removeSegment(Kill, LRQ.endPoint());
6352cab237bSDimitry Andric     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
6362cab237bSDimitry Andric     return;
6372cab237bSDimitry Andric   }
6382cab237bSDimitry Andric 
6392cab237bSDimitry Andric   // VNI is live out of KillMBB.
6402cab237bSDimitry Andric   LR.removeSegment(Kill, MBBEnd);
6412cab237bSDimitry Andric   if (EndPoints) EndPoints->push_back(MBBEnd);
6422cab237bSDimitry Andric 
6432cab237bSDimitry Andric   // Find all blocks that are reachable from KillMBB without leaving VNI's live
6442cab237bSDimitry Andric   // range. It is possible that KillMBB itself is reachable, so start a DFS
6452cab237bSDimitry Andric   // from each successor.
6462cab237bSDimitry Andric   using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
6472cab237bSDimitry Andric   VisitedTy Visited;
6482cab237bSDimitry Andric   for (MachineBasicBlock *Succ : KillMBB->successors()) {
6492cab237bSDimitry Andric     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
6502cab237bSDimitry Andric          I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
6512cab237bSDimitry Andric          I != E;) {
6522cab237bSDimitry Andric       MachineBasicBlock *MBB = *I;
6532cab237bSDimitry Andric 
6542cab237bSDimitry Andric       // Check if VNI is live in to MBB.
6552cab237bSDimitry Andric       SlotIndex MBBStart, MBBEnd;
6562cab237bSDimitry Andric       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
6572cab237bSDimitry Andric       LiveQueryResult LRQ = LR.Query(MBBStart);
6582cab237bSDimitry Andric       if (LRQ.valueIn() != VNI) {
6592cab237bSDimitry Andric         // This block isn't part of the VNI segment. Prune the search.
6602cab237bSDimitry Andric         I.skipChildren();
6612cab237bSDimitry Andric         continue;
6622cab237bSDimitry Andric       }
6632cab237bSDimitry Andric 
6642cab237bSDimitry Andric       // Prune the search if VNI is killed in MBB.
6652cab237bSDimitry Andric       if (LRQ.endPoint() < MBBEnd) {
6662cab237bSDimitry Andric         LR.removeSegment(MBBStart, LRQ.endPoint());
6672cab237bSDimitry Andric         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
6682cab237bSDimitry Andric         I.skipChildren();
6692cab237bSDimitry Andric         continue;
6702cab237bSDimitry Andric       }
6712cab237bSDimitry Andric 
6722cab237bSDimitry Andric       // VNI is live through MBB.
6732cab237bSDimitry Andric       LR.removeSegment(MBBStart, MBBEnd);
6742cab237bSDimitry Andric       if (EndPoints) EndPoints->push_back(MBBEnd);
6752cab237bSDimitry Andric       ++I;
6762cab237bSDimitry Andric     }
6772cab237bSDimitry Andric   }
6782cab237bSDimitry Andric }
6792cab237bSDimitry Andric 
6802cab237bSDimitry Andric //===----------------------------------------------------------------------===//
6812cab237bSDimitry Andric // Register allocator hooks.
6822cab237bSDimitry Andric //
6832cab237bSDimitry Andric 
addKillFlags(const VirtRegMap * VRM)6842cab237bSDimitry Andric void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
6852cab237bSDimitry Andric   // Keep track of regunit ranges.
6862cab237bSDimitry Andric   SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
6872cab237bSDimitry Andric   // Keep track of subregister ranges.
6882cab237bSDimitry Andric   SmallVector<std::pair<const LiveInterval::SubRange*,
6892cab237bSDimitry Andric                         LiveRange::const_iterator>, 4> SRs;
6902cab237bSDimitry Andric 
6912cab237bSDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
6922cab237bSDimitry Andric     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
6932cab237bSDimitry Andric     if (MRI->reg_nodbg_empty(Reg))
6942cab237bSDimitry Andric       continue;
6952cab237bSDimitry Andric     const LiveInterval &LI = getInterval(Reg);
6962cab237bSDimitry Andric     if (LI.empty())
6972cab237bSDimitry Andric       continue;
6982cab237bSDimitry Andric 
6992cab237bSDimitry Andric     // Find the regunit intervals for the assigned register. They may overlap
7002cab237bSDimitry Andric     // the virtual register live range, cancelling any kills.
7012cab237bSDimitry Andric     RU.clear();
7022cab237bSDimitry Andric     for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid();
7032cab237bSDimitry Andric          ++Unit) {
7042cab237bSDimitry Andric       const LiveRange &RURange = getRegUnit(*Unit);
7052cab237bSDimitry Andric       if (RURange.empty())
7062cab237bSDimitry Andric         continue;
7072cab237bSDimitry Andric       RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
7082cab237bSDimitry Andric     }
7092cab237bSDimitry Andric 
7102cab237bSDimitry Andric     if (MRI->subRegLivenessEnabled()) {
7112cab237bSDimitry Andric       SRs.clear();
7122cab237bSDimitry Andric       for (const LiveInterval::SubRange &SR : LI.subranges()) {
7132cab237bSDimitry Andric         SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
7142cab237bSDimitry Andric       }
7152cab237bSDimitry Andric     }
7162cab237bSDimitry Andric 
7172cab237bSDimitry Andric     // Every instruction that kills Reg corresponds to a segment range end
7182cab237bSDimitry Andric     // point.
7192cab237bSDimitry Andric     for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
7202cab237bSDimitry Andric          ++RI) {
7212cab237bSDimitry Andric       // A block index indicates an MBB edge.
7222cab237bSDimitry Andric       if (RI->end.isBlock())
7232cab237bSDimitry Andric         continue;
7242cab237bSDimitry Andric       MachineInstr *MI = getInstructionFromIndex(RI->end);
7252cab237bSDimitry Andric       if (!MI)
7262cab237bSDimitry Andric         continue;
7272cab237bSDimitry Andric 
7282cab237bSDimitry Andric       // Check if any of the regunits are live beyond the end of RI. That could
7292cab237bSDimitry Andric       // happen when a physreg is defined as a copy of a virtreg:
7302cab237bSDimitry Andric       //
7312cab237bSDimitry Andric       //   %eax = COPY %5
7322cab237bSDimitry Andric       //   FOO %5             <--- MI, cancel kill because %eax is live.
7332cab237bSDimitry Andric       //   BAR killed %eax
7342cab237bSDimitry Andric       //
7352cab237bSDimitry Andric       // There should be no kill flag on FOO when %5 is rewritten as %eax.
7362cab237bSDimitry Andric       for (auto &RUP : RU) {
7372cab237bSDimitry Andric         const LiveRange &RURange = *RUP.first;
7382cab237bSDimitry Andric         LiveRange::const_iterator &I = RUP.second;
7392cab237bSDimitry Andric         if (I == RURange.end())
7402cab237bSDimitry Andric           continue;
7412cab237bSDimitry Andric         I = RURange.advanceTo(I, RI->end);
7422cab237bSDimitry Andric         if (I == RURange.end() || I->start >= RI->end)
7432cab237bSDimitry Andric           continue;
7442cab237bSDimitry Andric         // I is overlapping RI.
7452cab237bSDimitry Andric         goto CancelKill;
7462cab237bSDimitry Andric       }
7472cab237bSDimitry Andric 
7482cab237bSDimitry Andric       if (MRI->subRegLivenessEnabled()) {
7492cab237bSDimitry Andric         // When reading a partial undefined value we must not add a kill flag.
7502cab237bSDimitry Andric         // The regalloc might have used the undef lane for something else.
7512cab237bSDimitry Andric         // Example:
7522cab237bSDimitry Andric         //     %1 = ...                  ; R32: %1
7532cab237bSDimitry Andric         //     %2:high16 = ...           ; R64: %2
7542cab237bSDimitry Andric         //        = read killed %2        ; R64: %2
7552cab237bSDimitry Andric         //        = read %1              ; R32: %1
7562cab237bSDimitry Andric         // The <kill> flag is correct for %2, but the register allocator may
7572cab237bSDimitry Andric         // assign R0L to %1, and R0 to %2 because the low 32bits of R0
7582cab237bSDimitry Andric         // are actually never written by %2. After assignment the <kill>
7592cab237bSDimitry Andric         // flag at the read instruction is invalid.
7602cab237bSDimitry Andric         LaneBitmask DefinedLanesMask;
7612cab237bSDimitry Andric         if (!SRs.empty()) {
7622cab237bSDimitry Andric           // Compute a mask of lanes that are defined.
7632cab237bSDimitry Andric           DefinedLanesMask = LaneBitmask::getNone();
7642cab237bSDimitry Andric           for (auto &SRP : SRs) {
7652cab237bSDimitry Andric             const LiveInterval::SubRange &SR = *SRP.first;
7662cab237bSDimitry Andric             LiveRange::const_iterator &I = SRP.second;
7672cab237bSDimitry Andric             if (I == SR.end())
7682cab237bSDimitry Andric               continue;
7692cab237bSDimitry Andric             I = SR.advanceTo(I, RI->end);
7702cab237bSDimitry Andric             if (I == SR.end() || I->start >= RI->end)
7712cab237bSDimitry Andric               continue;
7722cab237bSDimitry Andric             // I is overlapping RI
7732cab237bSDimitry Andric             DefinedLanesMask |= SR.LaneMask;
7742cab237bSDimitry Andric           }
7752cab237bSDimitry Andric         } else
7762cab237bSDimitry Andric           DefinedLanesMask = LaneBitmask::getAll();
7772cab237bSDimitry Andric 
7782cab237bSDimitry Andric         bool IsFullWrite = false;
7792cab237bSDimitry Andric         for (const MachineOperand &MO : MI->operands()) {
7802cab237bSDimitry Andric           if (!MO.isReg() || MO.getReg() != Reg)
7812cab237bSDimitry Andric             continue;
7822cab237bSDimitry Andric           if (MO.isUse()) {
7832cab237bSDimitry Andric             // Reading any undefined lanes?
7842cab237bSDimitry Andric             LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
7852cab237bSDimitry Andric             if ((UseMask & ~DefinedLanesMask).any())
7862cab237bSDimitry Andric               goto CancelKill;
7872cab237bSDimitry Andric           } else if (MO.getSubReg() == 0) {
7882cab237bSDimitry Andric             // Writing to the full register?
7892cab237bSDimitry Andric             assert(MO.isDef());
7902cab237bSDimitry Andric             IsFullWrite = true;
7912cab237bSDimitry Andric           }
7922cab237bSDimitry Andric         }
7932cab237bSDimitry Andric 
7942cab237bSDimitry Andric         // If an instruction writes to a subregister, a new segment starts in
7952cab237bSDimitry Andric         // the LiveInterval. But as this is only overriding part of the register
7962cab237bSDimitry Andric         // adding kill-flags is not correct here after registers have been
7972cab237bSDimitry Andric         // assigned.
7982cab237bSDimitry Andric         if (!IsFullWrite) {
7992cab237bSDimitry Andric           // Next segment has to be adjacent in the subregister write case.
8002cab237bSDimitry Andric           LiveRange::const_iterator N = std::next(RI);
8012cab237bSDimitry Andric           if (N != LI.end() && N->start == RI->end)
8022cab237bSDimitry Andric             goto CancelKill;
8032cab237bSDimitry Andric         }
8042cab237bSDimitry Andric       }
8052cab237bSDimitry Andric 
8062cab237bSDimitry Andric       MI->addRegisterKilled(Reg, nullptr);
8072cab237bSDimitry Andric       continue;
8082cab237bSDimitry Andric CancelKill:
8092cab237bSDimitry Andric       MI->clearRegisterKills(Reg, nullptr);
8102cab237bSDimitry Andric     }
8112cab237bSDimitry Andric   }
8122cab237bSDimitry Andric }
8132cab237bSDimitry Andric 
8142cab237bSDimitry Andric MachineBasicBlock*
intervalIsInOneMBB(const LiveInterval & LI) const8152cab237bSDimitry Andric LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
8162cab237bSDimitry Andric   // A local live range must be fully contained inside the block, meaning it is
8172cab237bSDimitry Andric   // defined and killed at instructions, not at block boundaries. It is not
818*4ba319b5SDimitry Andric   // live in or out of any block.
8192cab237bSDimitry Andric   //
8202cab237bSDimitry Andric   // It is technically possible to have a PHI-defined live range identical to a
8212cab237bSDimitry Andric   // single block, but we are going to return false in that case.
8222cab237bSDimitry Andric 
8232cab237bSDimitry Andric   SlotIndex Start = LI.beginIndex();
8242cab237bSDimitry Andric   if (Start.isBlock())
8252cab237bSDimitry Andric     return nullptr;
8262cab237bSDimitry Andric 
8272cab237bSDimitry Andric   SlotIndex Stop = LI.endIndex();
8282cab237bSDimitry Andric   if (Stop.isBlock())
8292cab237bSDimitry Andric     return nullptr;
8302cab237bSDimitry Andric 
8312cab237bSDimitry Andric   // getMBBFromIndex doesn't need to search the MBB table when both indexes
8322cab237bSDimitry Andric   // belong to proper instructions.
8332cab237bSDimitry Andric   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
8342cab237bSDimitry Andric   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
8352cab237bSDimitry Andric   return MBB1 == MBB2 ? MBB1 : nullptr;
8362cab237bSDimitry Andric }
8372cab237bSDimitry Andric 
8382cab237bSDimitry Andric bool
hasPHIKill(const LiveInterval & LI,const VNInfo * VNI) const8392cab237bSDimitry Andric LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
8402cab237bSDimitry Andric   for (const VNInfo *PHI : LI.valnos) {
8412cab237bSDimitry Andric     if (PHI->isUnused() || !PHI->isPHIDef())
8422cab237bSDimitry Andric       continue;
8432cab237bSDimitry Andric     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
8442cab237bSDimitry Andric     // Conservatively return true instead of scanning huge predecessor lists.
8452cab237bSDimitry Andric     if (PHIMBB->pred_size() > 100)
8462cab237bSDimitry Andric       return true;
8472cab237bSDimitry Andric     for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
8482cab237bSDimitry Andric       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
8492cab237bSDimitry Andric         return true;
8502cab237bSDimitry Andric   }
8512cab237bSDimitry Andric   return false;
8522cab237bSDimitry Andric }
8532cab237bSDimitry Andric 
getSpillWeight(bool isDef,bool isUse,const MachineBlockFrequencyInfo * MBFI,const MachineInstr & MI)8542cab237bSDimitry Andric float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
8552cab237bSDimitry Andric                                     const MachineBlockFrequencyInfo *MBFI,
8562cab237bSDimitry Andric                                     const MachineInstr &MI) {
8572cab237bSDimitry Andric   return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
8582cab237bSDimitry Andric }
8592cab237bSDimitry Andric 
getSpillWeight(bool isDef,bool isUse,const MachineBlockFrequencyInfo * MBFI,const MachineBasicBlock * MBB)8602cab237bSDimitry Andric float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
8612cab237bSDimitry Andric                                     const MachineBlockFrequencyInfo *MBFI,
8622cab237bSDimitry Andric                                     const MachineBasicBlock *MBB) {
8632cab237bSDimitry Andric   BlockFrequency Freq = MBFI->getBlockFreq(MBB);
8642cab237bSDimitry Andric   const float Scale = 1.0f / MBFI->getEntryFreq();
8652cab237bSDimitry Andric   return (isDef + isUse) * (Freq.getFrequency() * Scale);
8662cab237bSDimitry Andric }
8672cab237bSDimitry Andric 
8682cab237bSDimitry Andric LiveRange::Segment
addSegmentToEndOfBlock(unsigned reg,MachineInstr & startInst)8692cab237bSDimitry Andric LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) {
8702cab237bSDimitry Andric   LiveInterval& Interval = createEmptyInterval(reg);
8712cab237bSDimitry Andric   VNInfo *VN = Interval.getNextValue(
8722cab237bSDimitry Andric       SlotIndex(getInstructionIndex(startInst).getRegSlot()),
8732cab237bSDimitry Andric       getVNInfoAllocator());
8742cab237bSDimitry Andric   LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
8752cab237bSDimitry Andric                        getMBBEndIdx(startInst.getParent()), VN);
8762cab237bSDimitry Andric   Interval.addSegment(S);
8772cab237bSDimitry Andric 
8782cab237bSDimitry Andric   return S;
8792cab237bSDimitry Andric }
8802cab237bSDimitry Andric 
8812cab237bSDimitry Andric //===----------------------------------------------------------------------===//
8822cab237bSDimitry Andric //                          Register mask functions
8832cab237bSDimitry Andric //===----------------------------------------------------------------------===//
8842cab237bSDimitry Andric 
checkRegMaskInterference(LiveInterval & LI,BitVector & UsableRegs)8852cab237bSDimitry Andric bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
8862cab237bSDimitry Andric                                              BitVector &UsableRegs) {
8872cab237bSDimitry Andric   if (LI.empty())
8882cab237bSDimitry Andric     return false;
8892cab237bSDimitry Andric   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
8902cab237bSDimitry Andric 
8912cab237bSDimitry Andric   // Use a smaller arrays for local live ranges.
8922cab237bSDimitry Andric   ArrayRef<SlotIndex> Slots;
8932cab237bSDimitry Andric   ArrayRef<const uint32_t*> Bits;
8942cab237bSDimitry Andric   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
8952cab237bSDimitry Andric     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
8962cab237bSDimitry Andric     Bits = getRegMaskBitsInBlock(MBB->getNumber());
8972cab237bSDimitry Andric   } else {
8982cab237bSDimitry Andric     Slots = getRegMaskSlots();
8992cab237bSDimitry Andric     Bits = getRegMaskBits();
9002cab237bSDimitry Andric   }
9012cab237bSDimitry Andric 
9022cab237bSDimitry Andric   // We are going to enumerate all the register mask slots contained in LI.
9032cab237bSDimitry Andric   // Start with a binary search of RegMaskSlots to find a starting point.
9042cab237bSDimitry Andric   ArrayRef<SlotIndex>::iterator SlotI =
9052cab237bSDimitry Andric     std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
9062cab237bSDimitry Andric   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
9072cab237bSDimitry Andric 
9082cab237bSDimitry Andric   // No slots in range, LI begins after the last call.
9092cab237bSDimitry Andric   if (SlotI == SlotE)
9102cab237bSDimitry Andric     return false;
9112cab237bSDimitry Andric 
9122cab237bSDimitry Andric   bool Found = false;
9132cab237bSDimitry Andric   while (true) {
9142cab237bSDimitry Andric     assert(*SlotI >= LiveI->start);
9152cab237bSDimitry Andric     // Loop over all slots overlapping this segment.
9162cab237bSDimitry Andric     while (*SlotI < LiveI->end) {
9172cab237bSDimitry Andric       // *SlotI overlaps LI. Collect mask bits.
9182cab237bSDimitry Andric       if (!Found) {
9192cab237bSDimitry Andric         // This is the first overlap. Initialize UsableRegs to all ones.
9202cab237bSDimitry Andric         UsableRegs.clear();
9212cab237bSDimitry Andric         UsableRegs.resize(TRI->getNumRegs(), true);
9222cab237bSDimitry Andric         Found = true;
9232cab237bSDimitry Andric       }
9242cab237bSDimitry Andric       // Remove usable registers clobbered by this mask.
9252cab237bSDimitry Andric       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
9262cab237bSDimitry Andric       if (++SlotI == SlotE)
9272cab237bSDimitry Andric         return Found;
9282cab237bSDimitry Andric     }
9292cab237bSDimitry Andric     // *SlotI is beyond the current LI segment.
9302cab237bSDimitry Andric     LiveI = LI.advanceTo(LiveI, *SlotI);
9312cab237bSDimitry Andric     if (LiveI == LiveE)
9322cab237bSDimitry Andric       return Found;
9332cab237bSDimitry Andric     // Advance SlotI until it overlaps.
9342cab237bSDimitry Andric     while (*SlotI < LiveI->start)
9352cab237bSDimitry Andric       if (++SlotI == SlotE)
9362cab237bSDimitry Andric         return Found;
9372cab237bSDimitry Andric   }
9382cab237bSDimitry Andric }
9392cab237bSDimitry Andric 
9402cab237bSDimitry Andric //===----------------------------------------------------------------------===//
9412cab237bSDimitry Andric //                         IntervalUpdate class.
9422cab237bSDimitry Andric //===----------------------------------------------------------------------===//
9432cab237bSDimitry Andric 
9442cab237bSDimitry Andric /// Toolkit used by handleMove to trim or extend live intervals.
9452cab237bSDimitry Andric class LiveIntervals::HMEditor {
9462cab237bSDimitry Andric private:
9472cab237bSDimitry Andric   LiveIntervals& LIS;
9482cab237bSDimitry Andric   const MachineRegisterInfo& MRI;
9492cab237bSDimitry Andric   const TargetRegisterInfo& TRI;
9502cab237bSDimitry Andric   SlotIndex OldIdx;
9512cab237bSDimitry Andric   SlotIndex NewIdx;
9522cab237bSDimitry Andric   SmallPtrSet<LiveRange*, 8> Updated;
9532cab237bSDimitry Andric   bool UpdateFlags;
9542cab237bSDimitry Andric 
9552cab237bSDimitry Andric public:
HMEditor(LiveIntervals & LIS,const MachineRegisterInfo & MRI,const TargetRegisterInfo & TRI,SlotIndex OldIdx,SlotIndex NewIdx,bool UpdateFlags)9562cab237bSDimitry Andric   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
9572cab237bSDimitry Andric            const TargetRegisterInfo& TRI,
9582cab237bSDimitry Andric            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
9592cab237bSDimitry Andric     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
9602cab237bSDimitry Andric       UpdateFlags(UpdateFlags) {}
9612cab237bSDimitry Andric 
9622cab237bSDimitry Andric   // FIXME: UpdateFlags is a workaround that creates live intervals for all
9632cab237bSDimitry Andric   // physregs, even those that aren't needed for regalloc, in order to update
9642cab237bSDimitry Andric   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
9652cab237bSDimitry Andric   // flags, and postRA passes will use a live register utility instead.
getRegUnitLI(unsigned Unit)9662cab237bSDimitry Andric   LiveRange *getRegUnitLI(unsigned Unit) {
9672cab237bSDimitry Andric     if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
9682cab237bSDimitry Andric       return &LIS.getRegUnit(Unit);
9692cab237bSDimitry Andric     return LIS.getCachedRegUnit(Unit);
9702cab237bSDimitry Andric   }
9712cab237bSDimitry Andric 
9722cab237bSDimitry Andric   /// Update all live ranges touched by MI, assuming a move from OldIdx to
9732cab237bSDimitry Andric   /// NewIdx.
updateAllRanges(MachineInstr * MI)9742cab237bSDimitry Andric   void updateAllRanges(MachineInstr *MI) {
975*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
976*4ba319b5SDimitry Andric                       << *MI);
9772cab237bSDimitry Andric     bool hasRegMask = false;
9782cab237bSDimitry Andric     for (MachineOperand &MO : MI->operands()) {
9792cab237bSDimitry Andric       if (MO.isRegMask())
9802cab237bSDimitry Andric         hasRegMask = true;
9812cab237bSDimitry Andric       if (!MO.isReg())
9822cab237bSDimitry Andric         continue;
9832cab237bSDimitry Andric       if (MO.isUse()) {
9842cab237bSDimitry Andric         if (!MO.readsReg())
9852cab237bSDimitry Andric           continue;
9862cab237bSDimitry Andric         // Aggressively clear all kill flags.
9872cab237bSDimitry Andric         // They are reinserted by VirtRegRewriter.
9882cab237bSDimitry Andric         MO.setIsKill(false);
9892cab237bSDimitry Andric       }
9902cab237bSDimitry Andric 
9912cab237bSDimitry Andric       unsigned Reg = MO.getReg();
9922cab237bSDimitry Andric       if (!Reg)
9932cab237bSDimitry Andric         continue;
9942cab237bSDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9952cab237bSDimitry Andric         LiveInterval &LI = LIS.getInterval(Reg);
9962cab237bSDimitry Andric         if (LI.hasSubRanges()) {
9972cab237bSDimitry Andric           unsigned SubReg = MO.getSubReg();
9982cab237bSDimitry Andric           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
9992cab237bSDimitry Andric                                         : MRI.getMaxLaneMaskForVReg(Reg);
10002cab237bSDimitry Andric           for (LiveInterval::SubRange &S : LI.subranges()) {
10012cab237bSDimitry Andric             if ((S.LaneMask & LaneMask).none())
10022cab237bSDimitry Andric               continue;
10032cab237bSDimitry Andric             updateRange(S, Reg, S.LaneMask);
10042cab237bSDimitry Andric           }
10052cab237bSDimitry Andric         }
10062cab237bSDimitry Andric         updateRange(LI, Reg, LaneBitmask::getNone());
10072cab237bSDimitry Andric         continue;
10082cab237bSDimitry Andric       }
10092cab237bSDimitry Andric 
10102cab237bSDimitry Andric       // For physregs, only update the regunits that actually have a
10112cab237bSDimitry Andric       // precomputed live range.
10122cab237bSDimitry Andric       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
10132cab237bSDimitry Andric         if (LiveRange *LR = getRegUnitLI(*Units))
10142cab237bSDimitry Andric           updateRange(*LR, *Units, LaneBitmask::getNone());
10152cab237bSDimitry Andric     }
10162cab237bSDimitry Andric     if (hasRegMask)
10172cab237bSDimitry Andric       updateRegMaskSlots();
10182cab237bSDimitry Andric   }
10192cab237bSDimitry Andric 
10202cab237bSDimitry Andric private:
10212cab237bSDimitry Andric   /// Update a single live range, assuming an instruction has been moved from
10222cab237bSDimitry Andric   /// OldIdx to NewIdx.
updateRange(LiveRange & LR,unsigned Reg,LaneBitmask LaneMask)10232cab237bSDimitry Andric   void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
10242cab237bSDimitry Andric     if (!Updated.insert(&LR).second)
10252cab237bSDimitry Andric       return;
1026*4ba319b5SDimitry Andric     LLVM_DEBUG({
10272cab237bSDimitry Andric       dbgs() << "     ";
10282cab237bSDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
10292cab237bSDimitry Andric         dbgs() << printReg(Reg);
10302cab237bSDimitry Andric         if (LaneMask.any())
10312cab237bSDimitry Andric           dbgs() << " L" << PrintLaneMask(LaneMask);
10322cab237bSDimitry Andric       } else {
10332cab237bSDimitry Andric         dbgs() << printRegUnit(Reg, &TRI);
10342cab237bSDimitry Andric       }
10352cab237bSDimitry Andric       dbgs() << ":\t" << LR << '\n';
10362cab237bSDimitry Andric     });
10372cab237bSDimitry Andric     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
10382cab237bSDimitry Andric       handleMoveDown(LR);
10392cab237bSDimitry Andric     else
10402cab237bSDimitry Andric       handleMoveUp(LR, Reg, LaneMask);
1041*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "        -->\t" << LR << '\n');
10422cab237bSDimitry Andric     LR.verify();
10432cab237bSDimitry Andric   }
10442cab237bSDimitry Andric 
10452cab237bSDimitry Andric   /// Update LR to reflect an instruction has been moved downwards from OldIdx
10462cab237bSDimitry Andric   /// to NewIdx (OldIdx < NewIdx).
handleMoveDown(LiveRange & LR)10472cab237bSDimitry Andric   void handleMoveDown(LiveRange &LR) {
10482cab237bSDimitry Andric     LiveRange::iterator E = LR.end();
10492cab237bSDimitry Andric     // Segment going into OldIdx.
10502cab237bSDimitry Andric     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
10512cab237bSDimitry Andric 
10522cab237bSDimitry Andric     // No value live before or after OldIdx? Nothing to do.
10532cab237bSDimitry Andric     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
10542cab237bSDimitry Andric       return;
10552cab237bSDimitry Andric 
10562cab237bSDimitry Andric     LiveRange::iterator OldIdxOut;
10572cab237bSDimitry Andric     // Do we have a value live-in to OldIdx?
10582cab237bSDimitry Andric     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
10592cab237bSDimitry Andric       // If the live-in value already extends to NewIdx, there is nothing to do.
10602cab237bSDimitry Andric       if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
10612cab237bSDimitry Andric         return;
10622cab237bSDimitry Andric       // Aggressively remove all kill flags from the old kill point.
10632cab237bSDimitry Andric       // Kill flags shouldn't be used while live intervals exist, they will be
10642cab237bSDimitry Andric       // reinserted by VirtRegRewriter.
10652cab237bSDimitry Andric       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
10662cab237bSDimitry Andric         for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
10672cab237bSDimitry Andric           if (MO->isReg() && MO->isUse())
10682cab237bSDimitry Andric             MO->setIsKill(false);
10692cab237bSDimitry Andric 
10702cab237bSDimitry Andric       // Is there a def before NewIdx which is not OldIdx?
10712cab237bSDimitry Andric       LiveRange::iterator Next = std::next(OldIdxIn);
10722cab237bSDimitry Andric       if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
10732cab237bSDimitry Andric           SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
10742cab237bSDimitry Andric         // If we are here then OldIdx was just a use but not a def. We only have
10752cab237bSDimitry Andric         // to ensure liveness extends to NewIdx.
10762cab237bSDimitry Andric         LiveRange::iterator NewIdxIn =
10772cab237bSDimitry Andric           LR.advanceTo(Next, NewIdx.getBaseIndex());
10782cab237bSDimitry Andric         // Extend the segment before NewIdx if necessary.
10792cab237bSDimitry Andric         if (NewIdxIn == E ||
10802cab237bSDimitry Andric             !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
10812cab237bSDimitry Andric           LiveRange::iterator Prev = std::prev(NewIdxIn);
10822cab237bSDimitry Andric           Prev->end = NewIdx.getRegSlot();
10832cab237bSDimitry Andric         }
10842cab237bSDimitry Andric         // Extend OldIdxIn.
10852cab237bSDimitry Andric         OldIdxIn->end = Next->start;
10862cab237bSDimitry Andric         return;
10872cab237bSDimitry Andric       }
10882cab237bSDimitry Andric 
10892cab237bSDimitry Andric       // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
10902cab237bSDimitry Andric       // invalid by overlapping ranges.
10912cab237bSDimitry Andric       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
10922cab237bSDimitry Andric       OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
10932cab237bSDimitry Andric       // If this was not a kill, then there was no def and we're done.
10942cab237bSDimitry Andric       if (!isKill)
10952cab237bSDimitry Andric         return;
10962cab237bSDimitry Andric 
10972cab237bSDimitry Andric       // Did we have a Def at OldIdx?
10982cab237bSDimitry Andric       OldIdxOut = Next;
10992cab237bSDimitry Andric       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
11002cab237bSDimitry Andric         return;
11012cab237bSDimitry Andric     } else {
11022cab237bSDimitry Andric       OldIdxOut = OldIdxIn;
11032cab237bSDimitry Andric     }
11042cab237bSDimitry Andric 
11052cab237bSDimitry Andric     // If we are here then there is a Definition at OldIdx. OldIdxOut points
11062cab237bSDimitry Andric     // to the segment starting there.
11072cab237bSDimitry Andric     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
11082cab237bSDimitry Andric            "No def?");
11092cab237bSDimitry Andric     VNInfo *OldIdxVNI = OldIdxOut->valno;
11102cab237bSDimitry Andric     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
11112cab237bSDimitry Andric 
11122cab237bSDimitry Andric     // If the defined value extends beyond NewIdx, just move the beginning
11132cab237bSDimitry Andric     // of the segment to NewIdx.
11142cab237bSDimitry Andric     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
11152cab237bSDimitry Andric     if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
11162cab237bSDimitry Andric       OldIdxVNI->def = NewIdxDef;
11172cab237bSDimitry Andric       OldIdxOut->start = OldIdxVNI->def;
11182cab237bSDimitry Andric       return;
11192cab237bSDimitry Andric     }
11202cab237bSDimitry Andric 
11212cab237bSDimitry Andric     // If we are here then we have a Definition at OldIdx which ends before
11222cab237bSDimitry Andric     // NewIdx.
11232cab237bSDimitry Andric 
11242cab237bSDimitry Andric     // Is there an existing Def at NewIdx?
11252cab237bSDimitry Andric     LiveRange::iterator AfterNewIdx
11262cab237bSDimitry Andric       = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
11272cab237bSDimitry Andric     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
11282cab237bSDimitry Andric     if (!OldIdxDefIsDead &&
11292cab237bSDimitry Andric         SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
11302cab237bSDimitry Andric       // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
11312cab237bSDimitry Andric       VNInfo *DefVNI;
11322cab237bSDimitry Andric       if (OldIdxOut != LR.begin() &&
11332cab237bSDimitry Andric           !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
11342cab237bSDimitry Andric                                      OldIdxOut->start)) {
11352cab237bSDimitry Andric         // There is no gap between OldIdxOut and its predecessor anymore,
11362cab237bSDimitry Andric         // merge them.
11372cab237bSDimitry Andric         LiveRange::iterator IPrev = std::prev(OldIdxOut);
11382cab237bSDimitry Andric         DefVNI = OldIdxVNI;
11392cab237bSDimitry Andric         IPrev->end = OldIdxOut->end;
11402cab237bSDimitry Andric       } else {
11412cab237bSDimitry Andric         // The value is live in to OldIdx
11422cab237bSDimitry Andric         LiveRange::iterator INext = std::next(OldIdxOut);
11432cab237bSDimitry Andric         assert(INext != E && "Must have following segment");
11442cab237bSDimitry Andric         // We merge OldIdxOut and its successor. As we're dealing with subreg
11452cab237bSDimitry Andric         // reordering, there is always a successor to OldIdxOut in the same BB
11462cab237bSDimitry Andric         // We don't need INext->valno anymore and will reuse for the new segment
11472cab237bSDimitry Andric         // we create later.
11482cab237bSDimitry Andric         DefVNI = OldIdxVNI;
11492cab237bSDimitry Andric         INext->start = OldIdxOut->end;
11502cab237bSDimitry Andric         INext->valno->def = INext->start;
11512cab237bSDimitry Andric       }
11522cab237bSDimitry Andric       // If NewIdx is behind the last segment, extend that and append a new one.
11532cab237bSDimitry Andric       if (AfterNewIdx == E) {
11542cab237bSDimitry Andric         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
11552cab237bSDimitry Andric         // one position.
11562cab237bSDimitry Andric         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
11572cab237bSDimitry Andric         // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
11582cab237bSDimitry Andric         std::copy(std::next(OldIdxOut), E, OldIdxOut);
11592cab237bSDimitry Andric         // The last segment is undefined now, reuse it for a dead def.
11602cab237bSDimitry Andric         LiveRange::iterator NewSegment = std::prev(E);
11612cab237bSDimitry Andric         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
11622cab237bSDimitry Andric                                          DefVNI);
11632cab237bSDimitry Andric         DefVNI->def = NewIdxDef;
11642cab237bSDimitry Andric 
11652cab237bSDimitry Andric         LiveRange::iterator Prev = std::prev(NewSegment);
11662cab237bSDimitry Andric         Prev->end = NewIdxDef;
11672cab237bSDimitry Andric       } else {
11682cab237bSDimitry Andric         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
11692cab237bSDimitry Andric         // one position.
11702cab237bSDimitry Andric         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
11712cab237bSDimitry Andric         // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
11722cab237bSDimitry Andric         std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
11732cab237bSDimitry Andric         LiveRange::iterator Prev = std::prev(AfterNewIdx);
11742cab237bSDimitry Andric         // We have two cases:
11752cab237bSDimitry Andric         if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
11762cab237bSDimitry Andric           // Case 1: NewIdx is inside a liverange. Split this liverange at
11772cab237bSDimitry Andric           // NewIdxDef into the segment "Prev" followed by "NewSegment".
11782cab237bSDimitry Andric           LiveRange::iterator NewSegment = AfterNewIdx;
11792cab237bSDimitry Andric           *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
11802cab237bSDimitry Andric           Prev->valno->def = NewIdxDef;
11812cab237bSDimitry Andric 
11822cab237bSDimitry Andric           *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
11832cab237bSDimitry Andric           DefVNI->def = Prev->start;
11842cab237bSDimitry Andric         } else {
11852cab237bSDimitry Andric           // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
11862cab237bSDimitry Andric           // turn Prev into a segment from NewIdx to AfterNewIdx->start.
11872cab237bSDimitry Andric           *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
11882cab237bSDimitry Andric           DefVNI->def = NewIdxDef;
11892cab237bSDimitry Andric           assert(DefVNI != AfterNewIdx->valno);
11902cab237bSDimitry Andric         }
11912cab237bSDimitry Andric       }
11922cab237bSDimitry Andric       return;
11932cab237bSDimitry Andric     }
11942cab237bSDimitry Andric 
11952cab237bSDimitry Andric     if (AfterNewIdx != E &&
11962cab237bSDimitry Andric         SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
11972cab237bSDimitry Andric       // There is an existing def at NewIdx. The def at OldIdx is coalesced into
11982cab237bSDimitry Andric       // that value.
11992cab237bSDimitry Andric       assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
12002cab237bSDimitry Andric       LR.removeValNo(OldIdxVNI);
12012cab237bSDimitry Andric     } else {
12022cab237bSDimitry Andric       // There was no existing def at NewIdx. We need to create a dead def
12032cab237bSDimitry Andric       // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
12042cab237bSDimitry Andric       // a new segment at the place where we want to construct the dead def.
12052cab237bSDimitry Andric       //    |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
12062cab237bSDimitry Andric       // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
12072cab237bSDimitry Andric       assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
12082cab237bSDimitry Andric       std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
12092cab237bSDimitry Andric       // We can reuse OldIdxVNI now.
12102cab237bSDimitry Andric       LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
12112cab237bSDimitry Andric       VNInfo *NewSegmentVNI = OldIdxVNI;
12122cab237bSDimitry Andric       NewSegmentVNI->def = NewIdxDef;
12132cab237bSDimitry Andric       *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
12142cab237bSDimitry Andric                                        NewSegmentVNI);
12152cab237bSDimitry Andric     }
12162cab237bSDimitry Andric   }
12172cab237bSDimitry Andric 
12182cab237bSDimitry Andric   /// Update LR to reflect an instruction has been moved upwards from OldIdx
12192cab237bSDimitry Andric   /// to NewIdx (NewIdx < OldIdx).
handleMoveUp(LiveRange & LR,unsigned Reg,LaneBitmask LaneMask)12202cab237bSDimitry Andric   void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
12212cab237bSDimitry Andric     LiveRange::iterator E = LR.end();
12222cab237bSDimitry Andric     // Segment going into OldIdx.
12232cab237bSDimitry Andric     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
12242cab237bSDimitry Andric 
12252cab237bSDimitry Andric     // No value live before or after OldIdx? Nothing to do.
12262cab237bSDimitry Andric     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
12272cab237bSDimitry Andric       return;
12282cab237bSDimitry Andric 
12292cab237bSDimitry Andric     LiveRange::iterator OldIdxOut;
12302cab237bSDimitry Andric     // Do we have a value live-in to OldIdx?
12312cab237bSDimitry Andric     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
12322cab237bSDimitry Andric       // If the live-in value isn't killed here, then we have no Def at
12332cab237bSDimitry Andric       // OldIdx, moreover the value must be live at NewIdx so there is nothing
12342cab237bSDimitry Andric       // to do.
12352cab237bSDimitry Andric       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
12362cab237bSDimitry Andric       if (!isKill)
12372cab237bSDimitry Andric         return;
12382cab237bSDimitry Andric 
12392cab237bSDimitry Andric       // At this point we have to move OldIdxIn->end back to the nearest
12402cab237bSDimitry Andric       // previous use or (dead-)def but no further than NewIdx.
12412cab237bSDimitry Andric       SlotIndex DefBeforeOldIdx
12422cab237bSDimitry Andric         = std::max(OldIdxIn->start.getDeadSlot(),
12432cab237bSDimitry Andric                    NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
12442cab237bSDimitry Andric       OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
12452cab237bSDimitry Andric 
12462cab237bSDimitry Andric       // Did we have a Def at OldIdx? If not we are done now.
12472cab237bSDimitry Andric       OldIdxOut = std::next(OldIdxIn);
12482cab237bSDimitry Andric       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
12492cab237bSDimitry Andric         return;
12502cab237bSDimitry Andric     } else {
12512cab237bSDimitry Andric       OldIdxOut = OldIdxIn;
12522cab237bSDimitry Andric       OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
12532cab237bSDimitry Andric     }
12542cab237bSDimitry Andric 
12552cab237bSDimitry Andric     // If we are here then there is a Definition at OldIdx. OldIdxOut points
12562cab237bSDimitry Andric     // to the segment starting there.
12572cab237bSDimitry Andric     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
12582cab237bSDimitry Andric            "No def?");
12592cab237bSDimitry Andric     VNInfo *OldIdxVNI = OldIdxOut->valno;
12602cab237bSDimitry Andric     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
12612cab237bSDimitry Andric     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
12622cab237bSDimitry Andric 
12632cab237bSDimitry Andric     // Is there an existing def at NewIdx?
12642cab237bSDimitry Andric     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
12652cab237bSDimitry Andric     LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
12662cab237bSDimitry Andric     if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
12672cab237bSDimitry Andric       assert(NewIdxOut->valno != OldIdxVNI &&
12682cab237bSDimitry Andric              "Same value defined more than once?");
12692cab237bSDimitry Andric       // If OldIdx was a dead def remove it.
12702cab237bSDimitry Andric       if (!OldIdxDefIsDead) {
12712cab237bSDimitry Andric         // Remove segment starting at NewIdx and move begin of OldIdxOut to
12722cab237bSDimitry Andric         // NewIdx so it can take its place.
12732cab237bSDimitry Andric         OldIdxVNI->def = NewIdxDef;
12742cab237bSDimitry Andric         OldIdxOut->start = NewIdxDef;
12752cab237bSDimitry Andric         LR.removeValNo(NewIdxOut->valno);
12762cab237bSDimitry Andric       } else {
12772cab237bSDimitry Andric         // Simply remove the dead def at OldIdx.
12782cab237bSDimitry Andric         LR.removeValNo(OldIdxVNI);
12792cab237bSDimitry Andric       }
12802cab237bSDimitry Andric     } else {
12812cab237bSDimitry Andric       // Previously nothing was live after NewIdx, so all we have to do now is
12822cab237bSDimitry Andric       // move the begin of OldIdxOut to NewIdx.
12832cab237bSDimitry Andric       if (!OldIdxDefIsDead) {
12842cab237bSDimitry Andric         // Do we have any intermediate Defs between OldIdx and NewIdx?
12852cab237bSDimitry Andric         if (OldIdxIn != E &&
12862cab237bSDimitry Andric             SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
12872cab237bSDimitry Andric           // OldIdx is not a dead def and NewIdx is before predecessor start.
12882cab237bSDimitry Andric           LiveRange::iterator NewIdxIn = NewIdxOut;
12892cab237bSDimitry Andric           assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
12902cab237bSDimitry Andric           const SlotIndex SplitPos = NewIdxDef;
12912cab237bSDimitry Andric           OldIdxVNI = OldIdxIn->valno;
12922cab237bSDimitry Andric 
12932cab237bSDimitry Andric           // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
12942cab237bSDimitry Andric           OldIdxOut->valno->def = OldIdxIn->start;
12952cab237bSDimitry Andric           *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
12962cab237bSDimitry Andric                                           OldIdxOut->valno);
12972cab237bSDimitry Andric           // OldIdxIn and OldIdxVNI are now undef and can be overridden.
12982cab237bSDimitry Andric           // We Slide [NewIdxIn, OldIdxIn) down one position.
12992cab237bSDimitry Andric           //    |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
13002cab237bSDimitry Andric           // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
13012cab237bSDimitry Andric           std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
13022cab237bSDimitry Andric           // NewIdxIn is now considered undef so we can reuse it for the moved
13032cab237bSDimitry Andric           // value.
13042cab237bSDimitry Andric           LiveRange::iterator NewSegment = NewIdxIn;
13052cab237bSDimitry Andric           LiveRange::iterator Next = std::next(NewSegment);
13062cab237bSDimitry Andric           if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
13072cab237bSDimitry Andric             // There is no gap between NewSegment and its predecessor.
13082cab237bSDimitry Andric             *NewSegment = LiveRange::Segment(Next->start, SplitPos,
13092cab237bSDimitry Andric                                              Next->valno);
13102cab237bSDimitry Andric             *Next = LiveRange::Segment(SplitPos, Next->end, OldIdxVNI);
13112cab237bSDimitry Andric             Next->valno->def = SplitPos;
13122cab237bSDimitry Andric           } else {
13132cab237bSDimitry Andric             // There is a gap between NewSegment and its predecessor
13142cab237bSDimitry Andric             // Value becomes live in.
13152cab237bSDimitry Andric             *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
13162cab237bSDimitry Andric             NewSegment->valno->def = SplitPos;
13172cab237bSDimitry Andric           }
13182cab237bSDimitry Andric         } else {
13192cab237bSDimitry Andric           // Leave the end point of a live def.
13202cab237bSDimitry Andric           OldIdxOut->start = NewIdxDef;
13212cab237bSDimitry Andric           OldIdxVNI->def = NewIdxDef;
13222cab237bSDimitry Andric           if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
13232cab237bSDimitry Andric             OldIdxIn->end = NewIdx.getRegSlot();
13242cab237bSDimitry Andric         }
1325*4ba319b5SDimitry Andric       } else if (OldIdxIn != E
1326*4ba319b5SDimitry Andric           && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1327*4ba319b5SDimitry Andric           && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1328*4ba319b5SDimitry Andric         // OldIdxVNI is a dead def that has been moved into the middle of
1329*4ba319b5SDimitry Andric         // another value in LR. That can happen when LR is a whole register,
1330*4ba319b5SDimitry Andric         // but the dead def is a write to a subreg that is dead at NewIdx.
1331*4ba319b5SDimitry Andric         // The dead def may have been moved across other values
1332*4ba319b5SDimitry Andric         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1333*4ba319b5SDimitry Andric         // down one position.
1334*4ba319b5SDimitry Andric         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1335*4ba319b5SDimitry Andric         // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1336*4ba319b5SDimitry Andric         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1337*4ba319b5SDimitry Andric         // Modify the segment at NewIdxOut and the following segment to meet at
1338*4ba319b5SDimitry Andric         // the point of the dead def, with the following segment getting
1339*4ba319b5SDimitry Andric         // OldIdxVNI as its value number.
1340*4ba319b5SDimitry Andric         *NewIdxOut = LiveRange::Segment(
1341*4ba319b5SDimitry Andric             NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1342*4ba319b5SDimitry Andric         *(NewIdxOut + 1) = LiveRange::Segment(
1343*4ba319b5SDimitry Andric             NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1344*4ba319b5SDimitry Andric         OldIdxVNI->def = NewIdxDef;
1345*4ba319b5SDimitry Andric         // Modify subsequent segments to be defined by the moved def OldIdxVNI.
1346*4ba319b5SDimitry Andric         for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
1347*4ba319b5SDimitry Andric           Idx->valno = OldIdxVNI;
1348*4ba319b5SDimitry Andric         // Aggressively remove all dead flags from the former dead definition.
1349*4ba319b5SDimitry Andric         // Kill/dead flags shouldn't be used while live intervals exist; they
1350*4ba319b5SDimitry Andric         // will be reinserted by VirtRegRewriter.
1351*4ba319b5SDimitry Andric         if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1352*4ba319b5SDimitry Andric           for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1353*4ba319b5SDimitry Andric             if (MO->isReg() && !MO->isUse())
1354*4ba319b5SDimitry Andric               MO->setIsDead(false);
13552cab237bSDimitry Andric       } else {
13562cab237bSDimitry Andric         // OldIdxVNI is a dead def. It may have been moved across other values
13572cab237bSDimitry Andric         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
13582cab237bSDimitry Andric         // down one position.
13592cab237bSDimitry Andric         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
13602cab237bSDimitry Andric         // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
13612cab237bSDimitry Andric         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
13622cab237bSDimitry Andric         // OldIdxVNI can be reused now to build a new dead def segment.
13632cab237bSDimitry Andric         LiveRange::iterator NewSegment = NewIdxOut;
13642cab237bSDimitry Andric         VNInfo *NewSegmentVNI = OldIdxVNI;
13652cab237bSDimitry Andric         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
13662cab237bSDimitry Andric                                          NewSegmentVNI);
13672cab237bSDimitry Andric         NewSegmentVNI->def = NewIdxDef;
13682cab237bSDimitry Andric       }
13692cab237bSDimitry Andric     }
13702cab237bSDimitry Andric   }
13712cab237bSDimitry Andric 
updateRegMaskSlots()13722cab237bSDimitry Andric   void updateRegMaskSlots() {
13732cab237bSDimitry Andric     SmallVectorImpl<SlotIndex>::iterator RI =
13742cab237bSDimitry Andric       std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
13752cab237bSDimitry Andric                        OldIdx);
13762cab237bSDimitry Andric     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
13772cab237bSDimitry Andric            "No RegMask at OldIdx.");
13782cab237bSDimitry Andric     *RI = NewIdx.getRegSlot();
13792cab237bSDimitry Andric     assert((RI == LIS.RegMaskSlots.begin() ||
13802cab237bSDimitry Andric             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
13812cab237bSDimitry Andric            "Cannot move regmask instruction above another call");
13822cab237bSDimitry Andric     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
13832cab237bSDimitry Andric             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
13842cab237bSDimitry Andric            "Cannot move regmask instruction below another call");
13852cab237bSDimitry Andric   }
13862cab237bSDimitry Andric 
13872cab237bSDimitry Andric   // Return the last use of reg between NewIdx and OldIdx.
findLastUseBefore(SlotIndex Before,unsigned Reg,LaneBitmask LaneMask)13882cab237bSDimitry Andric   SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
13892cab237bSDimitry Andric                               LaneBitmask LaneMask) {
13902cab237bSDimitry Andric     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
13912cab237bSDimitry Andric       SlotIndex LastUse = Before;
13922cab237bSDimitry Andric       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
13932cab237bSDimitry Andric         if (MO.isUndef())
13942cab237bSDimitry Andric           continue;
13952cab237bSDimitry Andric         unsigned SubReg = MO.getSubReg();
13962cab237bSDimitry Andric         if (SubReg != 0 && LaneMask.any()
13972cab237bSDimitry Andric             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
13982cab237bSDimitry Andric           continue;
13992cab237bSDimitry Andric 
14002cab237bSDimitry Andric         const MachineInstr &MI = *MO.getParent();
14012cab237bSDimitry Andric         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
14022cab237bSDimitry Andric         if (InstSlot > LastUse && InstSlot < OldIdx)
14032cab237bSDimitry Andric           LastUse = InstSlot.getRegSlot();
14042cab237bSDimitry Andric       }
14052cab237bSDimitry Andric       return LastUse;
14062cab237bSDimitry Andric     }
14072cab237bSDimitry Andric 
14082cab237bSDimitry Andric     // This is a regunit interval, so scanning the use list could be very
14092cab237bSDimitry Andric     // expensive. Scan upwards from OldIdx instead.
14102cab237bSDimitry Andric     assert(Before < OldIdx && "Expected upwards move");
14112cab237bSDimitry Andric     SlotIndexes *Indexes = LIS.getSlotIndexes();
14122cab237bSDimitry Andric     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
14132cab237bSDimitry Andric 
14142cab237bSDimitry Andric     // OldIdx may not correspond to an instruction any longer, so set MII to
14152cab237bSDimitry Andric     // point to the next instruction after OldIdx, or MBB->end().
14162cab237bSDimitry Andric     MachineBasicBlock::iterator MII = MBB->end();
14172cab237bSDimitry Andric     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
14182cab237bSDimitry Andric                            Indexes->getNextNonNullIndex(OldIdx)))
14192cab237bSDimitry Andric       if (MI->getParent() == MBB)
14202cab237bSDimitry Andric         MII = MI;
14212cab237bSDimitry Andric 
14222cab237bSDimitry Andric     MachineBasicBlock::iterator Begin = MBB->begin();
14232cab237bSDimitry Andric     while (MII != Begin) {
1424*4ba319b5SDimitry Andric       if ((--MII)->isDebugInstr())
14252cab237bSDimitry Andric         continue;
14262cab237bSDimitry Andric       SlotIndex Idx = Indexes->getInstructionIndex(*MII);
14272cab237bSDimitry Andric 
14282cab237bSDimitry Andric       // Stop searching when Before is reached.
14292cab237bSDimitry Andric       if (!SlotIndex::isEarlierInstr(Before, Idx))
14302cab237bSDimitry Andric         return Before;
14312cab237bSDimitry Andric 
14322cab237bSDimitry Andric       // Check if MII uses Reg.
14332cab237bSDimitry Andric       for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
14342cab237bSDimitry Andric         if (MO->isReg() && !MO->isUndef() &&
14352cab237bSDimitry Andric             TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
14362cab237bSDimitry Andric             TRI.hasRegUnit(MO->getReg(), Reg))
14372cab237bSDimitry Andric           return Idx.getRegSlot();
14382cab237bSDimitry Andric     }
14392cab237bSDimitry Andric     // Didn't reach Before. It must be the first instruction in the block.
14402cab237bSDimitry Andric     return Before;
14412cab237bSDimitry Andric   }
14422cab237bSDimitry Andric };
14432cab237bSDimitry Andric 
handleMove(MachineInstr & MI,bool UpdateFlags)14442cab237bSDimitry Andric void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
14452cab237bSDimitry Andric   assert(!MI.isBundled() && "Can't handle bundled instructions yet.");
14462cab237bSDimitry Andric   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
14472cab237bSDimitry Andric   Indexes->removeMachineInstrFromMaps(MI);
14482cab237bSDimitry Andric   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
14492cab237bSDimitry Andric   assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
14502cab237bSDimitry Andric          OldIndex < getMBBEndIdx(MI.getParent()) &&
14512cab237bSDimitry Andric          "Cannot handle moves across basic block boundaries.");
14522cab237bSDimitry Andric 
14532cab237bSDimitry Andric   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
14542cab237bSDimitry Andric   HME.updateAllRanges(&MI);
14552cab237bSDimitry Andric }
14562cab237bSDimitry Andric 
handleMoveIntoBundle(MachineInstr & MI,MachineInstr & BundleStart,bool UpdateFlags)14572cab237bSDimitry Andric void LiveIntervals::handleMoveIntoBundle(MachineInstr &MI,
14582cab237bSDimitry Andric                                          MachineInstr &BundleStart,
14592cab237bSDimitry Andric                                          bool UpdateFlags) {
14602cab237bSDimitry Andric   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
14612cab237bSDimitry Andric   SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
14622cab237bSDimitry Andric   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
14632cab237bSDimitry Andric   HME.updateAllRanges(&MI);
14642cab237bSDimitry Andric }
14652cab237bSDimitry Andric 
repairOldRegInRange(const MachineBasicBlock::iterator Begin,const MachineBasicBlock::iterator End,const SlotIndex endIdx,LiveRange & LR,const unsigned Reg,LaneBitmask LaneMask)14662cab237bSDimitry Andric void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
14672cab237bSDimitry Andric                                         const MachineBasicBlock::iterator End,
14682cab237bSDimitry Andric                                         const SlotIndex endIdx,
14692cab237bSDimitry Andric                                         LiveRange &LR, const unsigned Reg,
14702cab237bSDimitry Andric                                         LaneBitmask LaneMask) {
14712cab237bSDimitry Andric   LiveInterval::iterator LII = LR.find(endIdx);
14722cab237bSDimitry Andric   SlotIndex lastUseIdx;
14732cab237bSDimitry Andric   if (LII == LR.begin()) {
14742cab237bSDimitry Andric     // This happens when the function is called for a subregister that only
14752cab237bSDimitry Andric     // occurs _after_ the range that is to be repaired.
14762cab237bSDimitry Andric     return;
14772cab237bSDimitry Andric   }
14782cab237bSDimitry Andric   if (LII != LR.end() && LII->start < endIdx)
14792cab237bSDimitry Andric     lastUseIdx = LII->end;
14802cab237bSDimitry Andric   else
14812cab237bSDimitry Andric     --LII;
14822cab237bSDimitry Andric 
14832cab237bSDimitry Andric   for (MachineBasicBlock::iterator I = End; I != Begin;) {
14842cab237bSDimitry Andric     --I;
14852cab237bSDimitry Andric     MachineInstr &MI = *I;
1486*4ba319b5SDimitry Andric     if (MI.isDebugInstr())
14872cab237bSDimitry Andric       continue;
14882cab237bSDimitry Andric 
14892cab237bSDimitry Andric     SlotIndex instrIdx = getInstructionIndex(MI);
14902cab237bSDimitry Andric     bool isStartValid = getInstructionFromIndex(LII->start);
14912cab237bSDimitry Andric     bool isEndValid = getInstructionFromIndex(LII->end);
14922cab237bSDimitry Andric 
14932cab237bSDimitry Andric     // FIXME: This doesn't currently handle early-clobber or multiple removed
14942cab237bSDimitry Andric     // defs inside of the region to repair.
14952cab237bSDimitry Andric     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
14962cab237bSDimitry Andric                                     OE = MI.operands_end();
14972cab237bSDimitry Andric          OI != OE; ++OI) {
14982cab237bSDimitry Andric       const MachineOperand &MO = *OI;
14992cab237bSDimitry Andric       if (!MO.isReg() || MO.getReg() != Reg)
15002cab237bSDimitry Andric         continue;
15012cab237bSDimitry Andric 
15022cab237bSDimitry Andric       unsigned SubReg = MO.getSubReg();
15032cab237bSDimitry Andric       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
15042cab237bSDimitry Andric       if ((Mask & LaneMask).none())
15052cab237bSDimitry Andric         continue;
15062cab237bSDimitry Andric 
15072cab237bSDimitry Andric       if (MO.isDef()) {
15082cab237bSDimitry Andric         if (!isStartValid) {
15092cab237bSDimitry Andric           if (LII->end.isDead()) {
15102cab237bSDimitry Andric             SlotIndex prevStart;
15112cab237bSDimitry Andric             if (LII != LR.begin())
15122cab237bSDimitry Andric               prevStart = std::prev(LII)->start;
15132cab237bSDimitry Andric 
15142cab237bSDimitry Andric             // FIXME: This could be more efficient if there was a
15152cab237bSDimitry Andric             // removeSegment method that returned an iterator.
15162cab237bSDimitry Andric             LR.removeSegment(*LII, true);
15172cab237bSDimitry Andric             if (prevStart.isValid())
15182cab237bSDimitry Andric               LII = LR.find(prevStart);
15192cab237bSDimitry Andric             else
15202cab237bSDimitry Andric               LII = LR.begin();
15212cab237bSDimitry Andric           } else {
15222cab237bSDimitry Andric             LII->start = instrIdx.getRegSlot();
15232cab237bSDimitry Andric             LII->valno->def = instrIdx.getRegSlot();
15242cab237bSDimitry Andric             if (MO.getSubReg() && !MO.isUndef())
15252cab237bSDimitry Andric               lastUseIdx = instrIdx.getRegSlot();
15262cab237bSDimitry Andric             else
15272cab237bSDimitry Andric               lastUseIdx = SlotIndex();
15282cab237bSDimitry Andric             continue;
15292cab237bSDimitry Andric           }
15302cab237bSDimitry Andric         }
15312cab237bSDimitry Andric 
15322cab237bSDimitry Andric         if (!lastUseIdx.isValid()) {
15332cab237bSDimitry Andric           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
15342cab237bSDimitry Andric           LiveRange::Segment S(instrIdx.getRegSlot(),
15352cab237bSDimitry Andric                                instrIdx.getDeadSlot(), VNI);
15362cab237bSDimitry Andric           LII = LR.addSegment(S);
15372cab237bSDimitry Andric         } else if (LII->start != instrIdx.getRegSlot()) {
15382cab237bSDimitry Andric           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
15392cab237bSDimitry Andric           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
15402cab237bSDimitry Andric           LII = LR.addSegment(S);
15412cab237bSDimitry Andric         }
15422cab237bSDimitry Andric 
15432cab237bSDimitry Andric         if (MO.getSubReg() && !MO.isUndef())
15442cab237bSDimitry Andric           lastUseIdx = instrIdx.getRegSlot();
15452cab237bSDimitry Andric         else
15462cab237bSDimitry Andric           lastUseIdx = SlotIndex();
15472cab237bSDimitry Andric       } else if (MO.isUse()) {
15482cab237bSDimitry Andric         // FIXME: This should probably be handled outside of this branch,
15492cab237bSDimitry Andric         // either as part of the def case (for defs inside of the region) or
15502cab237bSDimitry Andric         // after the loop over the region.
15512cab237bSDimitry Andric         if (!isEndValid && !LII->end.isBlock())
15522cab237bSDimitry Andric           LII->end = instrIdx.getRegSlot();
15532cab237bSDimitry Andric         if (!lastUseIdx.isValid())
15542cab237bSDimitry Andric           lastUseIdx = instrIdx.getRegSlot();
15552cab237bSDimitry Andric       }
15562cab237bSDimitry Andric     }
15572cab237bSDimitry Andric   }
15582cab237bSDimitry Andric }
15592cab237bSDimitry Andric 
15602cab237bSDimitry Andric void
repairIntervalsInRange(MachineBasicBlock * MBB,MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,ArrayRef<unsigned> OrigRegs)15612cab237bSDimitry Andric LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
15622cab237bSDimitry Andric                                       MachineBasicBlock::iterator Begin,
15632cab237bSDimitry Andric                                       MachineBasicBlock::iterator End,
15642cab237bSDimitry Andric                                       ArrayRef<unsigned> OrigRegs) {
15652cab237bSDimitry Andric   // Find anchor points, which are at the beginning/end of blocks or at
15662cab237bSDimitry Andric   // instructions that already have indexes.
15672cab237bSDimitry Andric   while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
15682cab237bSDimitry Andric     --Begin;
15692cab237bSDimitry Andric   while (End != MBB->end() && !Indexes->hasIndex(*End))
15702cab237bSDimitry Andric     ++End;
15712cab237bSDimitry Andric 
15722cab237bSDimitry Andric   SlotIndex endIdx;
15732cab237bSDimitry Andric   if (End == MBB->end())
15742cab237bSDimitry Andric     endIdx = getMBBEndIdx(MBB).getPrevSlot();
15752cab237bSDimitry Andric   else
15762cab237bSDimitry Andric     endIdx = getInstructionIndex(*End);
15772cab237bSDimitry Andric 
15782cab237bSDimitry Andric   Indexes->repairIndexesInRange(MBB, Begin, End);
15792cab237bSDimitry Andric 
15802cab237bSDimitry Andric   for (MachineBasicBlock::iterator I = End; I != Begin;) {
15812cab237bSDimitry Andric     --I;
15822cab237bSDimitry Andric     MachineInstr &MI = *I;
1583*4ba319b5SDimitry Andric     if (MI.isDebugInstr())
15842cab237bSDimitry Andric       continue;
15852cab237bSDimitry Andric     for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
15862cab237bSDimitry Andric                                           MOE = MI.operands_end();
15872cab237bSDimitry Andric          MOI != MOE; ++MOI) {
15882cab237bSDimitry Andric       if (MOI->isReg() &&
15892cab237bSDimitry Andric           TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
15902cab237bSDimitry Andric           !hasInterval(MOI->getReg())) {
15912cab237bSDimitry Andric         createAndComputeVirtRegInterval(MOI->getReg());
15922cab237bSDimitry Andric       }
15932cab237bSDimitry Andric     }
15942cab237bSDimitry Andric   }
15952cab237bSDimitry Andric 
15962cab237bSDimitry Andric   for (unsigned Reg : OrigRegs) {
15972cab237bSDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
15982cab237bSDimitry Andric       continue;
15992cab237bSDimitry Andric 
16002cab237bSDimitry Andric     LiveInterval &LI = getInterval(Reg);
16012cab237bSDimitry Andric     // FIXME: Should we support undefs that gain defs?
16022cab237bSDimitry Andric     if (!LI.hasAtLeastOneValue())
16032cab237bSDimitry Andric       continue;
16042cab237bSDimitry Andric 
16052cab237bSDimitry Andric     for (LiveInterval::SubRange &S : LI.subranges())
16062cab237bSDimitry Andric       repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
16072cab237bSDimitry Andric 
16082cab237bSDimitry Andric     repairOldRegInRange(Begin, End, endIdx, LI, Reg);
16092cab237bSDimitry Andric   }
16102cab237bSDimitry Andric }
16112cab237bSDimitry Andric 
removePhysRegDefAt(unsigned Reg,SlotIndex Pos)16122cab237bSDimitry Andric void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
16132cab237bSDimitry Andric   for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
16142cab237bSDimitry Andric     if (LiveRange *LR = getCachedRegUnit(*Unit))
16152cab237bSDimitry Andric       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
16162cab237bSDimitry Andric         LR->removeValNo(VNI);
16172cab237bSDimitry Andric   }
16182cab237bSDimitry Andric }
16192cab237bSDimitry Andric 
removeVRegDefAt(LiveInterval & LI,SlotIndex Pos)16202cab237bSDimitry Andric void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
16212cab237bSDimitry Andric   // LI may not have the main range computed yet, but its subranges may
16222cab237bSDimitry Andric   // be present.
16232cab237bSDimitry Andric   VNInfo *VNI = LI.getVNInfoAt(Pos);
16242cab237bSDimitry Andric   if (VNI != nullptr) {
16252cab237bSDimitry Andric     assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
16262cab237bSDimitry Andric     LI.removeValNo(VNI);
16272cab237bSDimitry Andric   }
16282cab237bSDimitry Andric 
16292cab237bSDimitry Andric   // Also remove the value defined in subranges.
16302cab237bSDimitry Andric   for (LiveInterval::SubRange &S : LI.subranges()) {
16312cab237bSDimitry Andric     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
16322cab237bSDimitry Andric       if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
16332cab237bSDimitry Andric         S.removeValNo(SVNI);
16342cab237bSDimitry Andric   }
16352cab237bSDimitry Andric   LI.removeEmptySubRanges();
16362cab237bSDimitry Andric }
16372cab237bSDimitry Andric 
splitSeparateComponents(LiveInterval & LI,SmallVectorImpl<LiveInterval * > & SplitLIs)16382cab237bSDimitry Andric void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
16392cab237bSDimitry Andric     SmallVectorImpl<LiveInterval*> &SplitLIs) {
16402cab237bSDimitry Andric   ConnectedVNInfoEqClasses ConEQ(*this);
16412cab237bSDimitry Andric   unsigned NumComp = ConEQ.Classify(LI);
16422cab237bSDimitry Andric   if (NumComp <= 1)
16432cab237bSDimitry Andric     return;
1644*4ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Split " << NumComp << " components: " << LI << '\n');
16452cab237bSDimitry Andric   unsigned Reg = LI.reg;
16462cab237bSDimitry Andric   const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
16472cab237bSDimitry Andric   for (unsigned I = 1; I < NumComp; ++I) {
16482cab237bSDimitry Andric     unsigned NewVReg = MRI->createVirtualRegister(RegClass);
16492cab237bSDimitry Andric     LiveInterval &NewLI = createEmptyInterval(NewVReg);
16502cab237bSDimitry Andric     SplitLIs.push_back(&NewLI);
16512cab237bSDimitry Andric   }
16522cab237bSDimitry Andric   ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
16532cab237bSDimitry Andric }
16542cab237bSDimitry Andric 
constructMainRangeFromSubranges(LiveInterval & LI)16552cab237bSDimitry Andric void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
16562cab237bSDimitry Andric   assert(LRCalc && "LRCalc not initialized.");
16572cab237bSDimitry Andric   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
16582cab237bSDimitry Andric   LRCalc->constructMainRangeFromSubranges(LI);
16592cab237bSDimitry Andric }
1660