xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/LiveIntervals.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file This file implements the LiveInterval analysis pass which is used
100b57cec5SDimitry Andric /// by the Linear Scan Register allocator. This pass linearizes the
110b57cec5SDimitry Andric /// basic blocks of the function in DFS order and computes live intervals for
120b57cec5SDimitry Andric /// each virtual and physical register.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
170b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
235ffd83dbSDimitry Andric #include "llvm/CodeGen/LiveIntervalCalc.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
3581ad6265SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
390b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
40fe6060f1SDimitry Andric #include "llvm/IR/Statepoint.h"
410b57cec5SDimitry Andric #include "llvm/MC/LaneBitmask.h"
420b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
430b57cec5SDimitry Andric #include "llvm/Pass.h"
440b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
450b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
460b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
470b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
480b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
490b57cec5SDimitry Andric #include <algorithm>
500b57cec5SDimitry Andric #include <cassert>
510b57cec5SDimitry Andric #include <cstdint>
520b57cec5SDimitry Andric #include <iterator>
530b57cec5SDimitry Andric #include <tuple>
540b57cec5SDimitry Andric #include <utility>
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric using namespace llvm;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric #define DEBUG_TYPE "regalloc"
590b57cec5SDimitry Andric 
60*0fca6ea1SDimitry Andric AnalysisKey LiveIntervalsAnalysis::Key;
61*0fca6ea1SDimitry Andric 
62*0fca6ea1SDimitry Andric LiveIntervalsAnalysis::Result
63*0fca6ea1SDimitry Andric LiveIntervalsAnalysis::run(MachineFunction &MF,
64*0fca6ea1SDimitry Andric                            MachineFunctionAnalysisManager &MFAM) {
65*0fca6ea1SDimitry Andric   return Result(MF, MFAM.getResult<SlotIndexesAnalysis>(MF),
66*0fca6ea1SDimitry Andric                 MFAM.getResult<MachineDominatorTreeAnalysis>(MF));
67*0fca6ea1SDimitry Andric }
68*0fca6ea1SDimitry Andric 
69*0fca6ea1SDimitry Andric PreservedAnalyses
70*0fca6ea1SDimitry Andric LiveIntervalsPrinterPass::run(MachineFunction &MF,
71*0fca6ea1SDimitry Andric                               MachineFunctionAnalysisManager &MFAM) {
72*0fca6ea1SDimitry Andric   OS << "Live intervals for machine function: " << MF.getName() << ":\n";
73*0fca6ea1SDimitry Andric   MFAM.getResult<LiveIntervalsAnalysis>(MF).print(OS);
74*0fca6ea1SDimitry Andric   return PreservedAnalyses::all();
75*0fca6ea1SDimitry Andric }
76*0fca6ea1SDimitry Andric 
77*0fca6ea1SDimitry Andric char LiveIntervalsWrapperPass::ID = 0;
78*0fca6ea1SDimitry Andric char &llvm::LiveIntervalsID = LiveIntervalsWrapperPass::ID;
79*0fca6ea1SDimitry Andric INITIALIZE_PASS_BEGIN(LiveIntervalsWrapperPass, "liveintervals",
800b57cec5SDimitry Andric                       "Live Interval Analysis", false, false)
81*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
82*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
83*0fca6ea1SDimitry Andric INITIALIZE_PASS_END(LiveIntervalsWrapperPass, "liveintervals",
84*0fca6ea1SDimitry Andric                     "Live Interval Analysis", false, false)
85*0fca6ea1SDimitry Andric 
86*0fca6ea1SDimitry Andric bool LiveIntervalsWrapperPass::runOnMachineFunction(MachineFunction &MF) {
87*0fca6ea1SDimitry Andric   LIS.Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
88*0fca6ea1SDimitry Andric   LIS.DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
89*0fca6ea1SDimitry Andric   LIS.analyze(MF);
90*0fca6ea1SDimitry Andric   LLVM_DEBUG(dump());
91*0fca6ea1SDimitry Andric   return false;
92*0fca6ea1SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric #ifndef NDEBUG
950b57cec5SDimitry Andric static cl::opt<bool> EnablePrecomputePhysRegs(
960b57cec5SDimitry Andric   "precompute-phys-liveness", cl::Hidden,
970b57cec5SDimitry Andric   cl::desc("Eagerly compute live intervals for all physreg units."));
980b57cec5SDimitry Andric #else
990b57cec5SDimitry Andric static bool EnablePrecomputePhysRegs = false;
1000b57cec5SDimitry Andric #endif // NDEBUG
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric namespace llvm {
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric cl::opt<bool> UseSegmentSetForPhysRegs(
1050b57cec5SDimitry Andric     "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
1060b57cec5SDimitry Andric     cl::desc(
1070b57cec5SDimitry Andric         "Use segment set for the computation of the live ranges of physregs."));
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric } // end namespace llvm
1100b57cec5SDimitry Andric 
111*0fca6ea1SDimitry Andric void LiveIntervalsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1120b57cec5SDimitry Andric   AU.setPreservesCFG();
113*0fca6ea1SDimitry Andric   AU.addPreserved<LiveVariablesWrapperPass>();
1140b57cec5SDimitry Andric   AU.addPreservedID(MachineLoopInfoID);
1150b57cec5SDimitry Andric   AU.addRequiredTransitiveID(MachineDominatorsID);
1160b57cec5SDimitry Andric   AU.addPreservedID(MachineDominatorsID);
117*0fca6ea1SDimitry Andric   AU.addPreserved<SlotIndexesWrapperPass>();
118*0fca6ea1SDimitry Andric   AU.addRequiredTransitive<SlotIndexesWrapperPass>();
1190b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
122*0fca6ea1SDimitry Andric LiveIntervalsWrapperPass::LiveIntervalsWrapperPass() : MachineFunctionPass(ID) {
123*0fca6ea1SDimitry Andric   initializeLiveIntervalsWrapperPassPass(*PassRegistry::getPassRegistry());
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric 
126*0fca6ea1SDimitry Andric LiveIntervals::~LiveIntervals() { clear(); }
1270b57cec5SDimitry Andric 
128*0fca6ea1SDimitry Andric void LiveIntervals::clear() {
1290b57cec5SDimitry Andric   // Free the live intervals themselves.
1300b57cec5SDimitry Andric   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
1318bcb0991SDimitry Andric     delete VirtRegIntervals[Register::index2VirtReg(i)];
1320b57cec5SDimitry Andric   VirtRegIntervals.clear();
1330b57cec5SDimitry Andric   RegMaskSlots.clear();
1340b57cec5SDimitry Andric   RegMaskBits.clear();
1350b57cec5SDimitry Andric   RegMaskBlocks.clear();
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   for (LiveRange *LR : RegUnitRanges)
1380b57cec5SDimitry Andric     delete LR;
1390b57cec5SDimitry Andric   RegUnitRanges.clear();
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
1420b57cec5SDimitry Andric   VNInfoAllocator.Reset();
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
145*0fca6ea1SDimitry Andric void LiveIntervals::analyze(MachineFunction &fn) {
1460b57cec5SDimitry Andric   MF = &fn;
1470b57cec5SDimitry Andric   MRI = &MF->getRegInfo();
1480b57cec5SDimitry Andric   TRI = MF->getSubtarget().getRegisterInfo();
1490b57cec5SDimitry Andric   TII = MF->getSubtarget().getInstrInfo();
1500b57cec5SDimitry Andric 
1515ffd83dbSDimitry Andric   if (!LICalc)
152*0fca6ea1SDimitry Andric     LICalc = std::make_unique<LiveIntervalCalc>();
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   // Allocate space for all virtual registers.
1550b57cec5SDimitry Andric   VirtRegIntervals.resize(MRI->getNumVirtRegs());
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   computeVirtRegs();
1580b57cec5SDimitry Andric   computeRegMasks();
1590b57cec5SDimitry Andric   computeLiveInRegUnits();
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   if (EnablePrecomputePhysRegs) {
1620b57cec5SDimitry Andric     // For stress testing, precompute live ranges of all physical register
1630b57cec5SDimitry Andric     // units, including reserved registers.
1640b57cec5SDimitry Andric     for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1650b57cec5SDimitry Andric       getRegUnit(i);
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric 
169*0fca6ea1SDimitry Andric void LiveIntervals::print(raw_ostream &OS) const {
1700b57cec5SDimitry Andric   OS << "********** INTERVALS **********\n";
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   // Dump the regunits.
1730b57cec5SDimitry Andric   for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
1740b57cec5SDimitry Andric     if (LiveRange *LR = RegUnitRanges[Unit])
1750b57cec5SDimitry Andric       OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   // Dump the virtregs.
1780b57cec5SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
179e8d8bef9SDimitry Andric     Register Reg = Register::index2VirtReg(i);
1800b57cec5SDimitry Andric     if (hasInterval(Reg))
1810b57cec5SDimitry Andric       OS << getInterval(Reg) << '\n';
1820b57cec5SDimitry Andric   }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   OS << "RegMasks:";
1850b57cec5SDimitry Andric   for (SlotIndex Idx : RegMaskSlots)
1860b57cec5SDimitry Andric     OS << ' ' << Idx;
1870b57cec5SDimitry Andric   OS << '\n';
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   printInstrs(OS);
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric void LiveIntervals::printInstrs(raw_ostream &OS) const {
1930b57cec5SDimitry Andric   OS << "********** MACHINEINSTRS **********\n";
1940b57cec5SDimitry Andric   MF->print(OS, Indexes);
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1980b57cec5SDimitry Andric LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
1990b57cec5SDimitry Andric   printInstrs(dbgs());
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric #endif
2020b57cec5SDimitry Andric 
203*0fca6ea1SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
204*0fca6ea1SDimitry Andric LLVM_DUMP_METHOD void LiveIntervals::dump() const { print(dbgs()); }
205*0fca6ea1SDimitry Andric #endif
206*0fca6ea1SDimitry Andric 
207e8d8bef9SDimitry Andric LiveInterval *LiveIntervals::createInterval(Register reg) {
208bdd1243dSDimitry Andric   float Weight = reg.isPhysical() ? huge_valf : 0.0F;
2090b57cec5SDimitry Andric   return new LiveInterval(reg, Weight);
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric /// Compute the live interval of a virtual register, based on defs and uses.
213480093f4SDimitry Andric bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
2145ffd83dbSDimitry Andric   assert(LICalc && "LICalc not initialized.");
2150b57cec5SDimitry Andric   assert(LI.empty() && "Should only compute empty intervals.");
2165ffd83dbSDimitry Andric   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
217e8d8bef9SDimitry Andric   LICalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg()));
218480093f4SDimitry Andric   return computeDeadValues(LI, nullptr);
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric void LiveIntervals::computeVirtRegs() {
2220b57cec5SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
223e8d8bef9SDimitry Andric     Register Reg = Register::index2VirtReg(i);
2240b57cec5SDimitry Andric     if (MRI->reg_nodbg_empty(Reg))
2250b57cec5SDimitry Andric       continue;
226480093f4SDimitry Andric     LiveInterval &LI = createEmptyInterval(Reg);
227480093f4SDimitry Andric     bool NeedSplit = computeVirtRegInterval(LI);
228480093f4SDimitry Andric     if (NeedSplit) {
229480093f4SDimitry Andric       SmallVector<LiveInterval*, 8> SplitLIs;
230480093f4SDimitry Andric       splitSeparateComponents(LI, SplitLIs);
231480093f4SDimitry Andric     }
2320b57cec5SDimitry Andric   }
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric void LiveIntervals::computeRegMasks() {
2360b57cec5SDimitry Andric   RegMaskBlocks.resize(MF->getNumBlockIDs());
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // Find all instructions with regmask operands.
2390b57cec5SDimitry Andric   for (const MachineBasicBlock &MBB : *MF) {
2400b57cec5SDimitry Andric     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
2410b57cec5SDimitry Andric     RMB.first = RegMaskSlots.size();
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric     // Some block starts, such as EH funclets, create masks.
2440b57cec5SDimitry Andric     if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
2450b57cec5SDimitry Andric       RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
2460b57cec5SDimitry Andric       RegMaskBits.push_back(Mask);
2470b57cec5SDimitry Andric     }
2480b57cec5SDimitry Andric 
249e8d8bef9SDimitry Andric     // Unwinders may clobber additional registers.
250e8d8bef9SDimitry Andric     // FIXME: This functionality can possibly be merged into
251e8d8bef9SDimitry Andric     // MachineBasicBlock::getBeginClobberMask().
252e8d8bef9SDimitry Andric     if (MBB.isEHPad())
253e8d8bef9SDimitry Andric       if (auto *Mask = TRI->getCustomEHPadPreservedMask(*MBB.getParent())) {
254e8d8bef9SDimitry Andric         RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
255e8d8bef9SDimitry Andric         RegMaskBits.push_back(Mask);
256e8d8bef9SDimitry Andric       }
257e8d8bef9SDimitry Andric 
2580b57cec5SDimitry Andric     for (const MachineInstr &MI : MBB) {
2590b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
2600b57cec5SDimitry Andric         if (!MO.isRegMask())
2610b57cec5SDimitry Andric           continue;
2620b57cec5SDimitry Andric         RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
2630b57cec5SDimitry Andric         RegMaskBits.push_back(MO.getRegMask());
2640b57cec5SDimitry Andric       }
2650b57cec5SDimitry Andric     }
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric     // Some block ends, such as funclet returns, create masks. Put the mask on
2680b57cec5SDimitry Andric     // the last instruction of the block, because MBB slot index intervals are
2690b57cec5SDimitry Andric     // half-open.
2700b57cec5SDimitry Andric     if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
2710b57cec5SDimitry Andric       assert(!MBB.empty() && "empty return block?");
2720b57cec5SDimitry Andric       RegMaskSlots.push_back(
2730b57cec5SDimitry Andric           Indexes->getInstructionIndex(MBB.back()).getRegSlot());
2740b57cec5SDimitry Andric       RegMaskBits.push_back(Mask);
2750b57cec5SDimitry Andric     }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric     // Compute the number of register mask instructions in this block.
2780b57cec5SDimitry Andric     RMB.second = RegMaskSlots.size() - RMB.first;
2790b57cec5SDimitry Andric   }
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2830b57cec5SDimitry Andric //                           Register Unit Liveness
2840b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2850b57cec5SDimitry Andric //
2860b57cec5SDimitry Andric // Fixed interference typically comes from ABI boundaries: Function arguments
2870b57cec5SDimitry Andric // and return values are passed in fixed registers, and so are exception
2880b57cec5SDimitry Andric // pointers entering landing pads. Certain instructions require values to be
2890b57cec5SDimitry Andric // present in specific registers. That is also represented through fixed
2900b57cec5SDimitry Andric // interference.
2910b57cec5SDimitry Andric //
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric /// Compute the live range of a register unit, based on the uses and defs of
2940b57cec5SDimitry Andric /// aliasing registers.  The range should be empty, or contain only dead
2950b57cec5SDimitry Andric /// phi-defs from ABI blocks.
2960b57cec5SDimitry Andric void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
2975ffd83dbSDimitry Andric   assert(LICalc && "LICalc not initialized.");
2985ffd83dbSDimitry Andric   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   // The physregs aliasing Unit are the roots and their super-registers.
3010b57cec5SDimitry Andric   // Create all values as dead defs before extending to uses. Note that roots
3020b57cec5SDimitry Andric   // may share super-registers. That's OK because createDeadDefs() is
3030b57cec5SDimitry Andric   // idempotent. It is very rare for a register unit to have multiple roots, so
3040b57cec5SDimitry Andric   // uniquing super-registers is probably not worthwhile.
3050b57cec5SDimitry Andric   bool IsReserved = false;
3060b57cec5SDimitry Andric   for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
3070b57cec5SDimitry Andric     bool IsRootReserved = true;
30806c3fb27SDimitry Andric     for (MCPhysReg Reg : TRI->superregs_inclusive(*Root)) {
3090b57cec5SDimitry Andric       if (!MRI->reg_empty(Reg))
3105ffd83dbSDimitry Andric         LICalc->createDeadDefs(LR, Reg);
3110b57cec5SDimitry Andric       // A register unit is considered reserved if all its roots and all their
3120b57cec5SDimitry Andric       // super registers are reserved.
3130b57cec5SDimitry Andric       if (!MRI->isReserved(Reg))
3140b57cec5SDimitry Andric         IsRootReserved = false;
3150b57cec5SDimitry Andric     }
3160b57cec5SDimitry Andric     IsReserved |= IsRootReserved;
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric   assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
3190b57cec5SDimitry Andric          "reserved computation mismatch");
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   // Now extend LR to reach all uses.
3220b57cec5SDimitry Andric   // Ignore uses of reserved registers. We only track defs of those.
3230b57cec5SDimitry Andric   if (!IsReserved) {
3240b57cec5SDimitry Andric     for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
32506c3fb27SDimitry Andric       for (MCPhysReg Reg : TRI->superregs_inclusive(*Root)) {
3260b57cec5SDimitry Andric         if (!MRI->reg_empty(Reg))
3275ffd83dbSDimitry Andric           LICalc->extendToUses(LR, Reg);
3280b57cec5SDimitry Andric       }
3290b57cec5SDimitry Andric     }
3300b57cec5SDimitry Andric   }
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   // Flush the segment set to the segment vector.
3330b57cec5SDimitry Andric   if (UseSegmentSetForPhysRegs)
3340b57cec5SDimitry Andric     LR.flushSegmentSet();
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric /// Precompute the live ranges of any register units that are live-in to an ABI
3380b57cec5SDimitry Andric /// block somewhere. Register values can appear without a corresponding def when
3390b57cec5SDimitry Andric /// entering the entry block or a landing pad.
3400b57cec5SDimitry Andric void LiveIntervals::computeLiveInRegUnits() {
3410b57cec5SDimitry Andric   RegUnitRanges.resize(TRI->getNumRegUnits());
3420b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   // Keep track of the live range sets allocated.
3450b57cec5SDimitry Andric   SmallVector<unsigned, 8> NewRanges;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   // Check all basic blocks for live-ins.
3480b57cec5SDimitry Andric   for (const MachineBasicBlock &MBB : *MF) {
3490b57cec5SDimitry Andric     // We only care about ABI blocks: Entry + landing pads.
3500b57cec5SDimitry Andric     if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
3510b57cec5SDimitry Andric       continue;
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     // Create phi-defs at Begin for all live-in registers.
3540b57cec5SDimitry Andric     SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
3550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
3560b57cec5SDimitry Andric     for (const auto &LI : MBB.liveins()) {
35706c3fb27SDimitry Andric       for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
3580b57cec5SDimitry Andric         LiveRange *LR = RegUnitRanges[Unit];
3590b57cec5SDimitry Andric         if (!LR) {
3600b57cec5SDimitry Andric           // Use segment set to speed-up initial computation of the live range.
3610b57cec5SDimitry Andric           LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
3620b57cec5SDimitry Andric           NewRanges.push_back(Unit);
3630b57cec5SDimitry Andric         }
3640b57cec5SDimitry Andric         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
3650b57cec5SDimitry Andric         (void)VNI;
3660b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
3670b57cec5SDimitry Andric       }
3680b57cec5SDimitry Andric     }
3690b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // Compute the 'normal' part of the ranges.
3740b57cec5SDimitry Andric   for (unsigned Unit : NewRanges)
3750b57cec5SDimitry Andric     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
3760b57cec5SDimitry Andric }
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric static void createSegmentsForValues(LiveRange &LR,
3790b57cec5SDimitry Andric     iterator_range<LiveInterval::vni_iterator> VNIs) {
3800b57cec5SDimitry Andric   for (VNInfo *VNI : VNIs) {
3810b57cec5SDimitry Andric     if (VNI->isUnused())
3820b57cec5SDimitry Andric       continue;
3830b57cec5SDimitry Andric     SlotIndex Def = VNI->def;
3840b57cec5SDimitry Andric     LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
3850b57cec5SDimitry Andric   }
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
3890b57cec5SDimitry Andric                                          ShrinkToUsesWorkList &WorkList,
390e8d8bef9SDimitry Andric                                          Register Reg, LaneBitmask LaneMask) {
3910b57cec5SDimitry Andric   // Keep track of the PHIs that are in use.
3920b57cec5SDimitry Andric   SmallPtrSet<VNInfo*, 8> UsedPHIs;
3930b57cec5SDimitry Andric   // Blocks that have already been added to WorkList as live-out.
3940b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
3970b57cec5SDimitry Andric         -> const LiveRange& {
3980b57cec5SDimitry Andric     if (M.none())
3990b57cec5SDimitry Andric       return I;
4000b57cec5SDimitry Andric     for (const LiveInterval::SubRange &SR : I.subranges()) {
4010b57cec5SDimitry Andric       if ((SR.LaneMask & M).any()) {
4020b57cec5SDimitry Andric         assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
4030b57cec5SDimitry Andric         return SR;
4040b57cec5SDimitry Andric       }
4050b57cec5SDimitry Andric     }
4060b57cec5SDimitry Andric     llvm_unreachable("Subrange for mask not found");
4070b57cec5SDimitry Andric   };
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   const LiveInterval &LI = getInterval(Reg);
4100b57cec5SDimitry Andric   const LiveRange &OldRange = getSubRange(LI, LaneMask);
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   // Extend intervals to reach all uses in WorkList.
4130b57cec5SDimitry Andric   while (!WorkList.empty()) {
4140b57cec5SDimitry Andric     SlotIndex Idx = WorkList.back().first;
4150b57cec5SDimitry Andric     VNInfo *VNI = WorkList.back().second;
4160b57cec5SDimitry Andric     WorkList.pop_back();
4170b57cec5SDimitry Andric     const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
4180b57cec5SDimitry Andric     SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric     // Extend the live range for VNI to be live at Idx.
4210b57cec5SDimitry Andric     if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
4220b57cec5SDimitry Andric       assert(ExtVNI == VNI && "Unexpected existing value number");
4230b57cec5SDimitry Andric       (void)ExtVNI;
4240b57cec5SDimitry Andric       // Is this a PHIDef we haven't seen before?
4250b57cec5SDimitry Andric       if (!VNI->isPHIDef() || VNI->def != BlockStart ||
4260b57cec5SDimitry Andric           !UsedPHIs.insert(VNI).second)
4270b57cec5SDimitry Andric         continue;
4280b57cec5SDimitry Andric       // The PHI is live, make sure the predecessors are live-out.
4290b57cec5SDimitry Andric       for (const MachineBasicBlock *Pred : MBB->predecessors()) {
4300b57cec5SDimitry Andric         if (!LiveOut.insert(Pred).second)
4310b57cec5SDimitry Andric           continue;
4320b57cec5SDimitry Andric         SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
4330b57cec5SDimitry Andric         // A predecessor is not required to have a live-out value for a PHI.
4340b57cec5SDimitry Andric         if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
4350b57cec5SDimitry Andric           WorkList.push_back(std::make_pair(Stop, PVNI));
4360b57cec5SDimitry Andric       }
4370b57cec5SDimitry Andric       continue;
4380b57cec5SDimitry Andric     }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     // VNI is live-in to MBB.
4410b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
4420b57cec5SDimitry Andric     Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric     // Make sure VNI is live-out from the predecessors.
4450b57cec5SDimitry Andric     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
4460b57cec5SDimitry Andric       if (!LiveOut.insert(Pred).second)
4470b57cec5SDimitry Andric         continue;
4480b57cec5SDimitry Andric       SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
4490b57cec5SDimitry Andric       if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
4500b57cec5SDimitry Andric         assert(OldVNI == VNI && "Wrong value out of predecessor");
4510b57cec5SDimitry Andric         (void)OldVNI;
4520b57cec5SDimitry Andric         WorkList.push_back(std::make_pair(Stop, VNI));
4530b57cec5SDimitry Andric       } else {
4540b57cec5SDimitry Andric #ifndef NDEBUG
4550b57cec5SDimitry Andric         // There was no old VNI. Verify that Stop is jointly dominated
4560b57cec5SDimitry Andric         // by <undef>s for this live range.
4570b57cec5SDimitry Andric         assert(LaneMask.any() &&
4580b57cec5SDimitry Andric                "Missing value out of predecessor for main range");
4590b57cec5SDimitry Andric         SmallVector<SlotIndex,8> Undefs;
4600b57cec5SDimitry Andric         LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
4610b57cec5SDimitry Andric         assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
4620b57cec5SDimitry Andric                "Missing value out of predecessor for subrange");
4630b57cec5SDimitry Andric #endif
4640b57cec5SDimitry Andric       }
4650b57cec5SDimitry Andric     }
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric }
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric bool LiveIntervals::shrinkToUses(LiveInterval *li,
4700b57cec5SDimitry Andric                                  SmallVectorImpl<MachineInstr*> *dead) {
4710b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
472bdd1243dSDimitry Andric   assert(li->reg().isVirtual() && "Can only shrink virtual registers");
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   // Shrink subregister live ranges.
4750b57cec5SDimitry Andric   bool NeedsCleanup = false;
4760b57cec5SDimitry Andric   for (LiveInterval::SubRange &S : li->subranges()) {
477e8d8bef9SDimitry Andric     shrinkToUses(S, li->reg());
4780b57cec5SDimitry Andric     if (S.empty())
4790b57cec5SDimitry Andric       NeedsCleanup = true;
4800b57cec5SDimitry Andric   }
4810b57cec5SDimitry Andric   if (NeedsCleanup)
4820b57cec5SDimitry Andric     li->removeEmptySubRanges();
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   // Find all the values used, including PHI kills.
4850b57cec5SDimitry Andric   ShrinkToUsesWorkList WorkList;
4860b57cec5SDimitry Andric 
487e8d8bef9SDimitry Andric   // Visit all instructions reading li->reg().
488e8d8bef9SDimitry Andric   Register Reg = li->reg();
4890b57cec5SDimitry Andric   for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
490fe6060f1SDimitry Andric     if (UseMI.isDebugInstr() || !UseMI.readsVirtualRegister(Reg))
4910b57cec5SDimitry Andric       continue;
4920b57cec5SDimitry Andric     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
4930b57cec5SDimitry Andric     LiveQueryResult LRQ = li->Query(Idx);
4940b57cec5SDimitry Andric     VNInfo *VNI = LRQ.valueIn();
4950b57cec5SDimitry Andric     if (!VNI) {
4960b57cec5SDimitry Andric       // This shouldn't happen: readsVirtualRegister returns true, but there is
4970b57cec5SDimitry Andric       // no live value. It is likely caused by a target getting <undef> flags
4980b57cec5SDimitry Andric       // wrong.
4990b57cec5SDimitry Andric       LLVM_DEBUG(
5000b57cec5SDimitry Andric           dbgs() << Idx << '\t' << UseMI
5010b57cec5SDimitry Andric                  << "Warning: Instr claims to read non-existent value in "
5020b57cec5SDimitry Andric                  << *li << '\n');
5030b57cec5SDimitry Andric       continue;
5040b57cec5SDimitry Andric     }
5050b57cec5SDimitry Andric     // Special case: An early-clobber tied operand reads and writes the
5060b57cec5SDimitry Andric     // register one slot early.
5070b57cec5SDimitry Andric     if (VNInfo *DefVNI = LRQ.valueDefined())
5080b57cec5SDimitry Andric       Idx = DefVNI->def;
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric     WorkList.push_back(std::make_pair(Idx, VNI));
5110b57cec5SDimitry Andric   }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   // Create new live ranges with only minimal live segments per def.
5140b57cec5SDimitry Andric   LiveRange NewLR;
51581ad6265SDimitry Andric   createSegmentsForValues(NewLR, li->vnis());
5160b57cec5SDimitry Andric   extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // Move the trimmed segments back.
5190b57cec5SDimitry Andric   li->segments.swap(NewLR.segments);
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   // Handle dead values.
5220b57cec5SDimitry Andric   bool CanSeparate = computeDeadValues(*li, dead);
5230b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
5240b57cec5SDimitry Andric   return CanSeparate;
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric bool LiveIntervals::computeDeadValues(LiveInterval &LI,
5280b57cec5SDimitry Andric                                       SmallVectorImpl<MachineInstr*> *dead) {
5290b57cec5SDimitry Andric   bool MayHaveSplitComponents = false;
530480093f4SDimitry Andric 
5310b57cec5SDimitry Andric   for (VNInfo *VNI : LI.valnos) {
5320b57cec5SDimitry Andric     if (VNI->isUnused())
5330b57cec5SDimitry Andric       continue;
5340b57cec5SDimitry Andric     SlotIndex Def = VNI->def;
5350b57cec5SDimitry Andric     LiveRange::iterator I = LI.FindSegmentContaining(Def);
5360b57cec5SDimitry Andric     assert(I != LI.end() && "Missing segment for VNI");
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric     // Is the register live before? Otherwise we may have to add a read-undef
5390b57cec5SDimitry Andric     // flag for subregister defs.
540e8d8bef9SDimitry Andric     Register VReg = LI.reg();
5410b57cec5SDimitry Andric     if (MRI->shouldTrackSubRegLiveness(VReg)) {
5420b57cec5SDimitry Andric       if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
5430b57cec5SDimitry Andric         MachineInstr *MI = getInstructionFromIndex(Def);
5440b57cec5SDimitry Andric         MI->setRegisterDefReadUndef(VReg);
5450b57cec5SDimitry Andric       }
5460b57cec5SDimitry Andric     }
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric     if (I->end != Def.getDeadSlot())
5490b57cec5SDimitry Andric       continue;
5500b57cec5SDimitry Andric     if (VNI->isPHIDef()) {
5510b57cec5SDimitry Andric       // This is a dead PHI. Remove it.
5520b57cec5SDimitry Andric       VNI->markUnused();
5530b57cec5SDimitry Andric       LI.removeSegment(I);
5540b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
5550b57cec5SDimitry Andric     } else {
5560b57cec5SDimitry Andric       // This is a dead def. Make sure the instruction knows.
5570b57cec5SDimitry Andric       MachineInstr *MI = getInstructionFromIndex(Def);
5580b57cec5SDimitry Andric       assert(MI && "No instruction defining live value");
559e8d8bef9SDimitry Andric       MI->addRegisterDead(LI.reg(), TRI);
560480093f4SDimitry Andric 
5610b57cec5SDimitry Andric       if (dead && MI->allDefsAreDead()) {
5620b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
5630b57cec5SDimitry Andric         dead->push_back(MI);
5640b57cec5SDimitry Andric       }
5650b57cec5SDimitry Andric     }
566bdd1243dSDimitry Andric     MayHaveSplitComponents = true;
5670b57cec5SDimitry Andric   }
5680b57cec5SDimitry Andric   return MayHaveSplitComponents;
5690b57cec5SDimitry Andric }
5700b57cec5SDimitry Andric 
571e8d8bef9SDimitry Andric void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, Register Reg) {
5720b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
573bdd1243dSDimitry Andric   assert(Reg.isVirtual() && "Can only shrink virtual registers");
5740b57cec5SDimitry Andric   // Find all the values used, including PHI kills.
5750b57cec5SDimitry Andric   ShrinkToUsesWorkList WorkList;
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   // Visit all instructions reading Reg.
5780b57cec5SDimitry Andric   SlotIndex LastIdx;
5790b57cec5SDimitry Andric   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
5800b57cec5SDimitry Andric     // Skip "undef" uses.
5810b57cec5SDimitry Andric     if (!MO.readsReg())
5820b57cec5SDimitry Andric       continue;
5830b57cec5SDimitry Andric     // Maybe the operand is for a subregister we don't care about.
5840b57cec5SDimitry Andric     unsigned SubReg = MO.getSubReg();
5850b57cec5SDimitry Andric     if (SubReg != 0) {
5860b57cec5SDimitry Andric       LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
5870b57cec5SDimitry Andric       if ((LaneMask & SR.LaneMask).none())
5880b57cec5SDimitry Andric         continue;
5890b57cec5SDimitry Andric     }
5900b57cec5SDimitry Andric     // We only need to visit each instruction once.
5910b57cec5SDimitry Andric     MachineInstr *UseMI = MO.getParent();
5920b57cec5SDimitry Andric     SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
5930b57cec5SDimitry Andric     if (Idx == LastIdx)
5940b57cec5SDimitry Andric       continue;
5950b57cec5SDimitry Andric     LastIdx = Idx;
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     LiveQueryResult LRQ = SR.Query(Idx);
5980b57cec5SDimitry Andric     VNInfo *VNI = LRQ.valueIn();
5990b57cec5SDimitry Andric     // For Subranges it is possible that only undef values are left in that
6000b57cec5SDimitry Andric     // part of the subregister, so there is no real liverange at the use
6010b57cec5SDimitry Andric     if (!VNI)
6020b57cec5SDimitry Andric       continue;
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric     // Special case: An early-clobber tied operand reads and writes the
6050b57cec5SDimitry Andric     // register one slot early.
6060b57cec5SDimitry Andric     if (VNInfo *DefVNI = LRQ.valueDefined())
6070b57cec5SDimitry Andric       Idx = DefVNI->def;
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric     WorkList.push_back(std::make_pair(Idx, VNI));
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   // Create a new live ranges with only minimal live segments per def.
6130b57cec5SDimitry Andric   LiveRange NewLR;
61481ad6265SDimitry Andric   createSegmentsForValues(NewLR, SR.vnis());
6150b57cec5SDimitry Andric   extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric   // Move the trimmed ranges back.
6180b57cec5SDimitry Andric   SR.segments.swap(NewLR.segments);
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   // Remove dead PHI value numbers
6210b57cec5SDimitry Andric   for (VNInfo *VNI : SR.valnos) {
6220b57cec5SDimitry Andric     if (VNI->isUnused())
6230b57cec5SDimitry Andric       continue;
6240b57cec5SDimitry Andric     const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
6250b57cec5SDimitry Andric     assert(Segment != nullptr && "Missing segment for VNI");
6260b57cec5SDimitry Andric     if (Segment->end != VNI->def.getDeadSlot())
6270b57cec5SDimitry Andric       continue;
6280b57cec5SDimitry Andric     if (VNI->isPHIDef()) {
6290b57cec5SDimitry Andric       // This is a dead PHI. Remove it.
6300b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
6310b57cec5SDimitry Andric                         << " may separate interval\n");
6320b57cec5SDimitry Andric       VNI->markUnused();
6330b57cec5SDimitry Andric       SR.removeSegment(*Segment);
6340b57cec5SDimitry Andric     }
6350b57cec5SDimitry Andric   }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
6380b57cec5SDimitry Andric }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric void LiveIntervals::extendToIndices(LiveRange &LR,
6410b57cec5SDimitry Andric                                     ArrayRef<SlotIndex> Indices,
6420b57cec5SDimitry Andric                                     ArrayRef<SlotIndex> Undefs) {
6435ffd83dbSDimitry Andric   assert(LICalc && "LICalc not initialized.");
6445ffd83dbSDimitry Andric   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
6450b57cec5SDimitry Andric   for (SlotIndex Idx : Indices)
6465ffd83dbSDimitry Andric     LICalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
6500b57cec5SDimitry Andric                                SmallVectorImpl<SlotIndex> *EndPoints) {
6510b57cec5SDimitry Andric   LiveQueryResult LRQ = LR.Query(Kill);
6520b57cec5SDimitry Andric   VNInfo *VNI = LRQ.valueOutOrDead();
6530b57cec5SDimitry Andric   if (!VNI)
6540b57cec5SDimitry Andric     return;
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
6570b57cec5SDimitry Andric   SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   // If VNI isn't live out from KillMBB, the value is trivially pruned.
6600b57cec5SDimitry Andric   if (LRQ.endPoint() < MBBEnd) {
6610b57cec5SDimitry Andric     LR.removeSegment(Kill, LRQ.endPoint());
6620b57cec5SDimitry Andric     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
6630b57cec5SDimitry Andric     return;
6640b57cec5SDimitry Andric   }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   // VNI is live out of KillMBB.
6670b57cec5SDimitry Andric   LR.removeSegment(Kill, MBBEnd);
6680b57cec5SDimitry Andric   if (EndPoints) EndPoints->push_back(MBBEnd);
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   // Find all blocks that are reachable from KillMBB without leaving VNI's live
6710b57cec5SDimitry Andric   // range. It is possible that KillMBB itself is reachable, so start a DFS
6720b57cec5SDimitry Andric   // from each successor.
6730b57cec5SDimitry Andric   using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
6740b57cec5SDimitry Andric   VisitedTy Visited;
6750b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : KillMBB->successors()) {
6760b57cec5SDimitry Andric     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
6770b57cec5SDimitry Andric          I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
6780b57cec5SDimitry Andric          I != E;) {
6790b57cec5SDimitry Andric       MachineBasicBlock *MBB = *I;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric       // Check if VNI is live in to MBB.
6820b57cec5SDimitry Andric       SlotIndex MBBStart, MBBEnd;
6830b57cec5SDimitry Andric       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
6840b57cec5SDimitry Andric       LiveQueryResult LRQ = LR.Query(MBBStart);
6850b57cec5SDimitry Andric       if (LRQ.valueIn() != VNI) {
6860b57cec5SDimitry Andric         // This block isn't part of the VNI segment. Prune the search.
6870b57cec5SDimitry Andric         I.skipChildren();
6880b57cec5SDimitry Andric         continue;
6890b57cec5SDimitry Andric       }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric       // Prune the search if VNI is killed in MBB.
6920b57cec5SDimitry Andric       if (LRQ.endPoint() < MBBEnd) {
6930b57cec5SDimitry Andric         LR.removeSegment(MBBStart, LRQ.endPoint());
6940b57cec5SDimitry Andric         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
6950b57cec5SDimitry Andric         I.skipChildren();
6960b57cec5SDimitry Andric         continue;
6970b57cec5SDimitry Andric       }
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric       // VNI is live through MBB.
7000b57cec5SDimitry Andric       LR.removeSegment(MBBStart, MBBEnd);
7010b57cec5SDimitry Andric       if (EndPoints) EndPoints->push_back(MBBEnd);
7020b57cec5SDimitry Andric       ++I;
7030b57cec5SDimitry Andric     }
7040b57cec5SDimitry Andric   }
7050b57cec5SDimitry Andric }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7080b57cec5SDimitry Andric // Register allocator hooks.
7090b57cec5SDimitry Andric //
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
7120b57cec5SDimitry Andric   // Keep track of regunit ranges.
7130b57cec5SDimitry Andric   SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
716e8d8bef9SDimitry Andric     Register Reg = Register::index2VirtReg(i);
7170b57cec5SDimitry Andric     if (MRI->reg_nodbg_empty(Reg))
7180b57cec5SDimitry Andric       continue;
7190b57cec5SDimitry Andric     const LiveInterval &LI = getInterval(Reg);
7200b57cec5SDimitry Andric     if (LI.empty())
7210b57cec5SDimitry Andric       continue;
7220b57cec5SDimitry Andric 
723fe6060f1SDimitry Andric     // Target may have not allocated this yet.
724fe6060f1SDimitry Andric     Register PhysReg = VRM->getPhys(Reg);
725fe6060f1SDimitry Andric     if (!PhysReg)
726fe6060f1SDimitry Andric       continue;
727fe6060f1SDimitry Andric 
7280b57cec5SDimitry Andric     // Find the regunit intervals for the assigned register. They may overlap
7290b57cec5SDimitry Andric     // the virtual register live range, cancelling any kills.
7300b57cec5SDimitry Andric     RU.clear();
73106c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
73206c3fb27SDimitry Andric       const LiveRange &RURange = getRegUnit(Unit);
7330b57cec5SDimitry Andric       if (RURange.empty())
7340b57cec5SDimitry Andric         continue;
7350b57cec5SDimitry Andric       RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
7360b57cec5SDimitry Andric     }
7370b57cec5SDimitry Andric     // Every instruction that kills Reg corresponds to a segment range end
7380b57cec5SDimitry Andric     // point.
7390b57cec5SDimitry Andric     for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
7400b57cec5SDimitry Andric          ++RI) {
7410b57cec5SDimitry Andric       // A block index indicates an MBB edge.
7420b57cec5SDimitry Andric       if (RI->end.isBlock())
7430b57cec5SDimitry Andric         continue;
7440b57cec5SDimitry Andric       MachineInstr *MI = getInstructionFromIndex(RI->end);
7450b57cec5SDimitry Andric       if (!MI)
7460b57cec5SDimitry Andric         continue;
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric       // Check if any of the regunits are live beyond the end of RI. That could
7490b57cec5SDimitry Andric       // happen when a physreg is defined as a copy of a virtreg:
7500b57cec5SDimitry Andric       //
7510b57cec5SDimitry Andric       //   %eax = COPY %5
7520b57cec5SDimitry Andric       //   FOO %5             <--- MI, cancel kill because %eax is live.
7530b57cec5SDimitry Andric       //   BAR killed %eax
7540b57cec5SDimitry Andric       //
7550b57cec5SDimitry Andric       // There should be no kill flag on FOO when %5 is rewritten as %eax.
7560b57cec5SDimitry Andric       for (auto &RUP : RU) {
7570b57cec5SDimitry Andric         const LiveRange &RURange = *RUP.first;
7580b57cec5SDimitry Andric         LiveRange::const_iterator &I = RUP.second;
7590b57cec5SDimitry Andric         if (I == RURange.end())
7600b57cec5SDimitry Andric           continue;
7610b57cec5SDimitry Andric         I = RURange.advanceTo(I, RI->end);
7620b57cec5SDimitry Andric         if (I == RURange.end() || I->start >= RI->end)
7630b57cec5SDimitry Andric           continue;
7640b57cec5SDimitry Andric         // I is overlapping RI.
7650b57cec5SDimitry Andric         goto CancelKill;
7660b57cec5SDimitry Andric       }
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric       if (MRI->subRegLivenessEnabled()) {
7690b57cec5SDimitry Andric         // When reading a partial undefined value we must not add a kill flag.
7700b57cec5SDimitry Andric         // The regalloc might have used the undef lane for something else.
7710b57cec5SDimitry Andric         // Example:
7720b57cec5SDimitry Andric         //     %1 = ...                  ; R32: %1
7730b57cec5SDimitry Andric         //     %2:high16 = ...           ; R64: %2
7740b57cec5SDimitry Andric         //        = read killed %2        ; R64: %2
7750b57cec5SDimitry Andric         //        = read %1              ; R32: %1
7760b57cec5SDimitry Andric         // The <kill> flag is correct for %2, but the register allocator may
7770b57cec5SDimitry Andric         // assign R0L to %1, and R0 to %2 because the low 32bits of R0
7780b57cec5SDimitry Andric         // are actually never written by %2. After assignment the <kill>
7790b57cec5SDimitry Andric         // flag at the read instruction is invalid.
7800b57cec5SDimitry Andric         LaneBitmask DefinedLanesMask;
781fe6060f1SDimitry Andric         if (LI.hasSubRanges()) {
7820b57cec5SDimitry Andric           // Compute a mask of lanes that are defined.
7830b57cec5SDimitry Andric           DefinedLanesMask = LaneBitmask::getNone();
784fe6060f1SDimitry Andric           for (const LiveInterval::SubRange &SR : LI.subranges())
785fe6060f1SDimitry Andric             for (const LiveRange::Segment &Segment : SR.segments) {
786fe6060f1SDimitry Andric               if (Segment.start >= RI->end)
787fe6060f1SDimitry Andric                 break;
788fe6060f1SDimitry Andric               if (Segment.end == RI->end) {
7890b57cec5SDimitry Andric                 DefinedLanesMask |= SR.LaneMask;
790fe6060f1SDimitry Andric                 break;
791fe6060f1SDimitry Andric               }
7920b57cec5SDimitry Andric             }
7930b57cec5SDimitry Andric         } else
7940b57cec5SDimitry Andric           DefinedLanesMask = LaneBitmask::getAll();
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric         bool IsFullWrite = false;
7970b57cec5SDimitry Andric         for (const MachineOperand &MO : MI->operands()) {
7980b57cec5SDimitry Andric           if (!MO.isReg() || MO.getReg() != Reg)
7990b57cec5SDimitry Andric             continue;
8000b57cec5SDimitry Andric           if (MO.isUse()) {
8010b57cec5SDimitry Andric             // Reading any undefined lanes?
802fe6060f1SDimitry Andric             unsigned SubReg = MO.getSubReg();
803fe6060f1SDimitry Andric             LaneBitmask UseMask = SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
804fe6060f1SDimitry Andric                                          : MRI->getMaxLaneMaskForVReg(Reg);
8050b57cec5SDimitry Andric             if ((UseMask & ~DefinedLanesMask).any())
8060b57cec5SDimitry Andric               goto CancelKill;
8070b57cec5SDimitry Andric           } else if (MO.getSubReg() == 0) {
8080b57cec5SDimitry Andric             // Writing to the full register?
8090b57cec5SDimitry Andric             assert(MO.isDef());
8100b57cec5SDimitry Andric             IsFullWrite = true;
8110b57cec5SDimitry Andric           }
8120b57cec5SDimitry Andric         }
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric         // If an instruction writes to a subregister, a new segment starts in
8150b57cec5SDimitry Andric         // the LiveInterval. But as this is only overriding part of the register
8160b57cec5SDimitry Andric         // adding kill-flags is not correct here after registers have been
8170b57cec5SDimitry Andric         // assigned.
8180b57cec5SDimitry Andric         if (!IsFullWrite) {
8190b57cec5SDimitry Andric           // Next segment has to be adjacent in the subregister write case.
8200b57cec5SDimitry Andric           LiveRange::const_iterator N = std::next(RI);
8210b57cec5SDimitry Andric           if (N != LI.end() && N->start == RI->end)
8220b57cec5SDimitry Andric             goto CancelKill;
8230b57cec5SDimitry Andric         }
8240b57cec5SDimitry Andric       }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric       MI->addRegisterKilled(Reg, nullptr);
8270b57cec5SDimitry Andric       continue;
8280b57cec5SDimitry Andric CancelKill:
8290b57cec5SDimitry Andric       MI->clearRegisterKills(Reg, nullptr);
8300b57cec5SDimitry Andric     }
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric MachineBasicBlock*
8350b57cec5SDimitry Andric LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
83604eeddc0SDimitry Andric   assert(!LI.empty() && "LiveInterval is empty.");
83704eeddc0SDimitry Andric 
8380b57cec5SDimitry Andric   // A local live range must be fully contained inside the block, meaning it is
8390b57cec5SDimitry Andric   // defined and killed at instructions, not at block boundaries. It is not
8400b57cec5SDimitry Andric   // live in or out of any block.
8410b57cec5SDimitry Andric   //
8420b57cec5SDimitry Andric   // It is technically possible to have a PHI-defined live range identical to a
8430b57cec5SDimitry Andric   // single block, but we are going to return false in that case.
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   SlotIndex Start = LI.beginIndex();
8460b57cec5SDimitry Andric   if (Start.isBlock())
8470b57cec5SDimitry Andric     return nullptr;
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   SlotIndex Stop = LI.endIndex();
8500b57cec5SDimitry Andric   if (Stop.isBlock())
8510b57cec5SDimitry Andric     return nullptr;
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   // getMBBFromIndex doesn't need to search the MBB table when both indexes
8540b57cec5SDimitry Andric   // belong to proper instructions.
8550b57cec5SDimitry Andric   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
8560b57cec5SDimitry Andric   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
8570b57cec5SDimitry Andric   return MBB1 == MBB2 ? MBB1 : nullptr;
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric bool
8610b57cec5SDimitry Andric LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
8620b57cec5SDimitry Andric   for (const VNInfo *PHI : LI.valnos) {
8630b57cec5SDimitry Andric     if (PHI->isUnused() || !PHI->isPHIDef())
8640b57cec5SDimitry Andric       continue;
8650b57cec5SDimitry Andric     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
8660b57cec5SDimitry Andric     // Conservatively return true instead of scanning huge predecessor lists.
8670b57cec5SDimitry Andric     if (PHIMBB->pred_size() > 100)
8680b57cec5SDimitry Andric       return true;
8690b57cec5SDimitry Andric     for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
8700b57cec5SDimitry Andric       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
8710b57cec5SDimitry Andric         return true;
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric   return false;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
8770b57cec5SDimitry Andric                                     const MachineBlockFrequencyInfo *MBFI,
8780b57cec5SDimitry Andric                                     const MachineInstr &MI) {
8790b57cec5SDimitry Andric   return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
8800b57cec5SDimitry Andric }
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
8830b57cec5SDimitry Andric                                     const MachineBlockFrequencyInfo *MBFI,
8840b57cec5SDimitry Andric                                     const MachineBasicBlock *MBB) {
885e8d8bef9SDimitry Andric   return (isDef + isUse) * MBFI->getBlockFreqRelativeToEntryBlock(MBB);
8860b57cec5SDimitry Andric }
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric LiveRange::Segment
889e8d8bef9SDimitry Andric LiveIntervals::addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst) {
8905f757f3fSDimitry Andric   LiveInterval &Interval = getOrCreateEmptyInterval(Reg);
8910b57cec5SDimitry Andric   VNInfo *VN = Interval.getNextValue(
8920b57cec5SDimitry Andric       SlotIndex(getInstructionIndex(startInst).getRegSlot()),
8930b57cec5SDimitry Andric       getVNInfoAllocator());
8940b57cec5SDimitry Andric   LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
8950b57cec5SDimitry Andric                        getMBBEndIdx(startInst.getParent()), VN);
8960b57cec5SDimitry Andric   Interval.addSegment(S);
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   return S;
8990b57cec5SDimitry Andric }
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9020b57cec5SDimitry Andric //                          Register mask functions
9030b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
904fe6060f1SDimitry Andric /// Check whether use of reg in MI is live-through. Live-through means that
905fe6060f1SDimitry Andric /// the value is alive on exit from Machine instruction. The example of such
906fe6060f1SDimitry Andric /// use is a deopt value in statepoint instruction.
907fe6060f1SDimitry Andric static bool hasLiveThroughUse(const MachineInstr *MI, Register Reg) {
908fe6060f1SDimitry Andric   if (MI->getOpcode() != TargetOpcode::STATEPOINT)
909fe6060f1SDimitry Andric     return false;
910fe6060f1SDimitry Andric   StatepointOpers SO(MI);
911fe6060f1SDimitry Andric   if (SO.getFlags() & (uint64_t)StatepointFlags::DeoptLiveIn)
912fe6060f1SDimitry Andric     return false;
913fe6060f1SDimitry Andric   for (unsigned Idx = SO.getNumDeoptArgsIdx(), E = SO.getNumGCPtrIdx(); Idx < E;
914fe6060f1SDimitry Andric        ++Idx) {
915fe6060f1SDimitry Andric     const MachineOperand &MO = MI->getOperand(Idx);
916fe6060f1SDimitry Andric     if (MO.isReg() && MO.getReg() == Reg)
917fe6060f1SDimitry Andric       return true;
918fe6060f1SDimitry Andric   }
919fe6060f1SDimitry Andric   return false;
920fe6060f1SDimitry Andric }
9210b57cec5SDimitry Andric 
92281ad6265SDimitry Andric bool LiveIntervals::checkRegMaskInterference(const LiveInterval &LI,
9230b57cec5SDimitry Andric                                              BitVector &UsableRegs) {
9240b57cec5SDimitry Andric   if (LI.empty())
9250b57cec5SDimitry Andric     return false;
92681ad6265SDimitry Andric   LiveInterval::const_iterator LiveI = LI.begin(), LiveE = LI.end();
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   // Use a smaller arrays for local live ranges.
9290b57cec5SDimitry Andric   ArrayRef<SlotIndex> Slots;
9300b57cec5SDimitry Andric   ArrayRef<const uint32_t*> Bits;
9310b57cec5SDimitry Andric   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
9320b57cec5SDimitry Andric     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
9330b57cec5SDimitry Andric     Bits = getRegMaskBitsInBlock(MBB->getNumber());
9340b57cec5SDimitry Andric   } else {
9350b57cec5SDimitry Andric     Slots = getRegMaskSlots();
9360b57cec5SDimitry Andric     Bits = getRegMaskBits();
9370b57cec5SDimitry Andric   }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   // We are going to enumerate all the register mask slots contained in LI.
9400b57cec5SDimitry Andric   // Start with a binary search of RegMaskSlots to find a starting point.
9410b57cec5SDimitry Andric   ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
9420b57cec5SDimitry Andric   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   // No slots in range, LI begins after the last call.
9450b57cec5SDimitry Andric   if (SlotI == SlotE)
9460b57cec5SDimitry Andric     return false;
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   bool Found = false;
949fe6060f1SDimitry Andric   // Utility to union regmasks.
950fe6060f1SDimitry Andric   auto unionBitMask = [&](unsigned Idx) {
9510b57cec5SDimitry Andric       if (!Found) {
9520b57cec5SDimitry Andric         // This is the first overlap. Initialize UsableRegs to all ones.
9530b57cec5SDimitry Andric         UsableRegs.clear();
9540b57cec5SDimitry Andric         UsableRegs.resize(TRI->getNumRegs(), true);
9550b57cec5SDimitry Andric         Found = true;
9560b57cec5SDimitry Andric       }
9570b57cec5SDimitry Andric       // Remove usable registers clobbered by this mask.
958fe6060f1SDimitry Andric       UsableRegs.clearBitsNotInMask(Bits[Idx]);
959fe6060f1SDimitry Andric   };
960fe6060f1SDimitry Andric   while (true) {
961fe6060f1SDimitry Andric     assert(*SlotI >= LiveI->start);
962fe6060f1SDimitry Andric     // Loop over all slots overlapping this segment.
963fe6060f1SDimitry Andric     while (*SlotI < LiveI->end) {
964fe6060f1SDimitry Andric       // *SlotI overlaps LI. Collect mask bits.
965fe6060f1SDimitry Andric       unionBitMask(SlotI - Slots.begin());
9660b57cec5SDimitry Andric       if (++SlotI == SlotE)
9670b57cec5SDimitry Andric         return Found;
9680b57cec5SDimitry Andric     }
969fe6060f1SDimitry Andric     // If segment ends with live-through use we need to collect its regmask.
970fe6060f1SDimitry Andric     if (*SlotI == LiveI->end)
971fe6060f1SDimitry Andric       if (MachineInstr *MI = getInstructionFromIndex(*SlotI))
972fe6060f1SDimitry Andric         if (hasLiveThroughUse(MI, LI.reg()))
973fe6060f1SDimitry Andric           unionBitMask(SlotI++ - Slots.begin());
9740b57cec5SDimitry Andric     // *SlotI is beyond the current LI segment.
975fe6060f1SDimitry Andric     // Special advance implementation to not miss next LiveI->end.
976fe6060f1SDimitry Andric     if (++LiveI == LiveE || SlotI == SlotE || *SlotI > LI.endIndex())
9770b57cec5SDimitry Andric       return Found;
978fe6060f1SDimitry Andric     while (LiveI->end < *SlotI)
979fe6060f1SDimitry Andric       ++LiveI;
9800b57cec5SDimitry Andric     // Advance SlotI until it overlaps.
9810b57cec5SDimitry Andric     while (*SlotI < LiveI->start)
9820b57cec5SDimitry Andric       if (++SlotI == SlotE)
9830b57cec5SDimitry Andric         return Found;
9840b57cec5SDimitry Andric   }
9850b57cec5SDimitry Andric }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9880b57cec5SDimitry Andric //                         IntervalUpdate class.
9890b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric /// Toolkit used by handleMove to trim or extend live intervals.
9920b57cec5SDimitry Andric class LiveIntervals::HMEditor {
9930b57cec5SDimitry Andric private:
9940b57cec5SDimitry Andric   LiveIntervals& LIS;
9950b57cec5SDimitry Andric   const MachineRegisterInfo& MRI;
9960b57cec5SDimitry Andric   const TargetRegisterInfo& TRI;
9970b57cec5SDimitry Andric   SlotIndex OldIdx;
9980b57cec5SDimitry Andric   SlotIndex NewIdx;
9990b57cec5SDimitry Andric   SmallPtrSet<LiveRange*, 8> Updated;
10000b57cec5SDimitry Andric   bool UpdateFlags;
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric public:
10030b57cec5SDimitry Andric   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
10040b57cec5SDimitry Andric            const TargetRegisterInfo& TRI,
10050b57cec5SDimitry Andric            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
10060b57cec5SDimitry Andric     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
10070b57cec5SDimitry Andric       UpdateFlags(UpdateFlags) {}
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   // FIXME: UpdateFlags is a workaround that creates live intervals for all
10100b57cec5SDimitry Andric   // physregs, even those that aren't needed for regalloc, in order to update
10110b57cec5SDimitry Andric   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
10120b57cec5SDimitry Andric   // flags, and postRA passes will use a live register utility instead.
10130b57cec5SDimitry Andric   LiveRange *getRegUnitLI(unsigned Unit) {
10140b57cec5SDimitry Andric     if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
10150b57cec5SDimitry Andric       return &LIS.getRegUnit(Unit);
10160b57cec5SDimitry Andric     return LIS.getCachedRegUnit(Unit);
10170b57cec5SDimitry Andric   }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   /// Update all live ranges touched by MI, assuming a move from OldIdx to
10200b57cec5SDimitry Andric   /// NewIdx.
10210b57cec5SDimitry Andric   void updateAllRanges(MachineInstr *MI) {
10220b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
10230b57cec5SDimitry Andric                       << *MI);
10240b57cec5SDimitry Andric     bool hasRegMask = false;
10250b57cec5SDimitry Andric     for (MachineOperand &MO : MI->operands()) {
10260b57cec5SDimitry Andric       if (MO.isRegMask())
10270b57cec5SDimitry Andric         hasRegMask = true;
10280b57cec5SDimitry Andric       if (!MO.isReg())
10290b57cec5SDimitry Andric         continue;
10300b57cec5SDimitry Andric       if (MO.isUse()) {
10310b57cec5SDimitry Andric         if (!MO.readsReg())
10320b57cec5SDimitry Andric           continue;
10330b57cec5SDimitry Andric         // Aggressively clear all kill flags.
10340b57cec5SDimitry Andric         // They are reinserted by VirtRegRewriter.
10350b57cec5SDimitry Andric         MO.setIsKill(false);
10360b57cec5SDimitry Andric       }
10370b57cec5SDimitry Andric 
10388bcb0991SDimitry Andric       Register Reg = MO.getReg();
10390b57cec5SDimitry Andric       if (!Reg)
10400b57cec5SDimitry Andric         continue;
1041bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
10420b57cec5SDimitry Andric         LiveInterval &LI = LIS.getInterval(Reg);
10430b57cec5SDimitry Andric         if (LI.hasSubRanges()) {
10440b57cec5SDimitry Andric           unsigned SubReg = MO.getSubReg();
10450b57cec5SDimitry Andric           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
10460b57cec5SDimitry Andric                                         : MRI.getMaxLaneMaskForVReg(Reg);
10470b57cec5SDimitry Andric           for (LiveInterval::SubRange &S : LI.subranges()) {
10480b57cec5SDimitry Andric             if ((S.LaneMask & LaneMask).none())
10490b57cec5SDimitry Andric               continue;
10500b57cec5SDimitry Andric             updateRange(S, Reg, S.LaneMask);
10510b57cec5SDimitry Andric           }
10520b57cec5SDimitry Andric         }
10530b57cec5SDimitry Andric         updateRange(LI, Reg, LaneBitmask::getNone());
10545ffd83dbSDimitry Andric         // If main range has a hole and we are moving a subrange use across
10555ffd83dbSDimitry Andric         // the hole updateRange() cannot properly handle it since it only
10565ffd83dbSDimitry Andric         // gets the LiveRange and not the whole LiveInterval. As a result
10575ffd83dbSDimitry Andric         // we may end up with a main range not covering all subranges.
10585ffd83dbSDimitry Andric         // This is extremely rare case, so let's check and reconstruct the
10595ffd83dbSDimitry Andric         // main range.
1060753f127fSDimitry Andric         if (LI.hasSubRanges()) {
1061753f127fSDimitry Andric           unsigned SubReg = MO.getSubReg();
1062753f127fSDimitry Andric           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1063753f127fSDimitry Andric                                         : MRI.getMaxLaneMaskForVReg(Reg);
10645ffd83dbSDimitry Andric           for (LiveInterval::SubRange &S : LI.subranges()) {
1065753f127fSDimitry Andric             if ((S.LaneMask & LaneMask).none() || LI.covers(S))
10665ffd83dbSDimitry Andric               continue;
10675ffd83dbSDimitry Andric             LI.clear();
10685ffd83dbSDimitry Andric             LIS.constructMainRangeFromSubranges(LI);
10695ffd83dbSDimitry Andric             break;
10705ffd83dbSDimitry Andric           }
1071753f127fSDimitry Andric         }
10725ffd83dbSDimitry Andric 
10730b57cec5SDimitry Andric         continue;
10740b57cec5SDimitry Andric       }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric       // For physregs, only update the regunits that actually have a
10770b57cec5SDimitry Andric       // precomputed live range.
107806c3fb27SDimitry Andric       for (MCRegUnit Unit : TRI.regunits(Reg.asMCReg()))
107906c3fb27SDimitry Andric         if (LiveRange *LR = getRegUnitLI(Unit))
108006c3fb27SDimitry Andric           updateRange(*LR, Unit, LaneBitmask::getNone());
10810b57cec5SDimitry Andric     }
10820b57cec5SDimitry Andric     if (hasRegMask)
10830b57cec5SDimitry Andric       updateRegMaskSlots();
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric private:
10870b57cec5SDimitry Andric   /// Update a single live range, assuming an instruction has been moved from
10880b57cec5SDimitry Andric   /// OldIdx to NewIdx.
1089e8d8bef9SDimitry Andric   void updateRange(LiveRange &LR, Register Reg, LaneBitmask LaneMask) {
10900b57cec5SDimitry Andric     if (!Updated.insert(&LR).second)
10910b57cec5SDimitry Andric       return;
10920b57cec5SDimitry Andric     LLVM_DEBUG({
10930b57cec5SDimitry Andric       dbgs() << "     ";
1094bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
10950b57cec5SDimitry Andric         dbgs() << printReg(Reg);
10960b57cec5SDimitry Andric         if (LaneMask.any())
10970b57cec5SDimitry Andric           dbgs() << " L" << PrintLaneMask(LaneMask);
10980b57cec5SDimitry Andric       } else {
10990b57cec5SDimitry Andric         dbgs() << printRegUnit(Reg, &TRI);
11000b57cec5SDimitry Andric       }
11010b57cec5SDimitry Andric       dbgs() << ":\t" << LR << '\n';
11020b57cec5SDimitry Andric     });
11030b57cec5SDimitry Andric     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
11040b57cec5SDimitry Andric       handleMoveDown(LR);
11050b57cec5SDimitry Andric     else
11060b57cec5SDimitry Andric       handleMoveUp(LR, Reg, LaneMask);
11070b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "        -->\t" << LR << '\n');
11080b57cec5SDimitry Andric     LR.verify();
11090b57cec5SDimitry Andric   }
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   /// Update LR to reflect an instruction has been moved downwards from OldIdx
11120b57cec5SDimitry Andric   /// to NewIdx (OldIdx < NewIdx).
11130b57cec5SDimitry Andric   void handleMoveDown(LiveRange &LR) {
11140b57cec5SDimitry Andric     LiveRange::iterator E = LR.end();
11150b57cec5SDimitry Andric     // Segment going into OldIdx.
11160b57cec5SDimitry Andric     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric     // No value live before or after OldIdx? Nothing to do.
11190b57cec5SDimitry Andric     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
11200b57cec5SDimitry Andric       return;
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     LiveRange::iterator OldIdxOut;
11230b57cec5SDimitry Andric     // Do we have a value live-in to OldIdx?
11240b57cec5SDimitry Andric     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
11250b57cec5SDimitry Andric       // If the live-in value already extends to NewIdx, there is nothing to do.
11260b57cec5SDimitry Andric       if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
11270b57cec5SDimitry Andric         return;
11280b57cec5SDimitry Andric       // Aggressively remove all kill flags from the old kill point.
11290b57cec5SDimitry Andric       // Kill flags shouldn't be used while live intervals exist, they will be
11300b57cec5SDimitry Andric       // reinserted by VirtRegRewriter.
11310b57cec5SDimitry Andric       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1132480093f4SDimitry Andric         for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1133480093f4SDimitry Andric           if (MOP.isReg() && MOP.isUse())
1134480093f4SDimitry Andric             MOP.setIsKill(false);
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric       // Is there a def before NewIdx which is not OldIdx?
11370b57cec5SDimitry Andric       LiveRange::iterator Next = std::next(OldIdxIn);
11380b57cec5SDimitry Andric       if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
11390b57cec5SDimitry Andric           SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
11400b57cec5SDimitry Andric         // If we are here then OldIdx was just a use but not a def. We only have
11410b57cec5SDimitry Andric         // to ensure liveness extends to NewIdx.
11420b57cec5SDimitry Andric         LiveRange::iterator NewIdxIn =
11430b57cec5SDimitry Andric           LR.advanceTo(Next, NewIdx.getBaseIndex());
11440b57cec5SDimitry Andric         // Extend the segment before NewIdx if necessary.
11450b57cec5SDimitry Andric         if (NewIdxIn == E ||
11460b57cec5SDimitry Andric             !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
11470b57cec5SDimitry Andric           LiveRange::iterator Prev = std::prev(NewIdxIn);
11480b57cec5SDimitry Andric           Prev->end = NewIdx.getRegSlot();
11490b57cec5SDimitry Andric         }
11500b57cec5SDimitry Andric         // Extend OldIdxIn.
11510b57cec5SDimitry Andric         OldIdxIn->end = Next->start;
11520b57cec5SDimitry Andric         return;
11530b57cec5SDimitry Andric       }
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric       // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
11560b57cec5SDimitry Andric       // invalid by overlapping ranges.
11570b57cec5SDimitry Andric       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
11580b57cec5SDimitry Andric       OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
11590b57cec5SDimitry Andric       // If this was not a kill, then there was no def and we're done.
11600b57cec5SDimitry Andric       if (!isKill)
11610b57cec5SDimitry Andric         return;
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric       // Did we have a Def at OldIdx?
11640b57cec5SDimitry Andric       OldIdxOut = Next;
11650b57cec5SDimitry Andric       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
11660b57cec5SDimitry Andric         return;
11670b57cec5SDimitry Andric     } else {
11680b57cec5SDimitry Andric       OldIdxOut = OldIdxIn;
11690b57cec5SDimitry Andric     }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric     // If we are here then there is a Definition at OldIdx. OldIdxOut points
11720b57cec5SDimitry Andric     // to the segment starting there.
11730b57cec5SDimitry Andric     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
11740b57cec5SDimitry Andric            "No def?");
11750b57cec5SDimitry Andric     VNInfo *OldIdxVNI = OldIdxOut->valno;
11760b57cec5SDimitry Andric     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric     // If the defined value extends beyond NewIdx, just move the beginning
11790b57cec5SDimitry Andric     // of the segment to NewIdx.
11800b57cec5SDimitry Andric     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
11810b57cec5SDimitry Andric     if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
11820b57cec5SDimitry Andric       OldIdxVNI->def = NewIdxDef;
11830b57cec5SDimitry Andric       OldIdxOut->start = OldIdxVNI->def;
11840b57cec5SDimitry Andric       return;
11850b57cec5SDimitry Andric     }
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric     // If we are here then we have a Definition at OldIdx which ends before
11880b57cec5SDimitry Andric     // NewIdx.
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric     // Is there an existing Def at NewIdx?
11910b57cec5SDimitry Andric     LiveRange::iterator AfterNewIdx
11920b57cec5SDimitry Andric       = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
11930b57cec5SDimitry Andric     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
11940b57cec5SDimitry Andric     if (!OldIdxDefIsDead &&
11950b57cec5SDimitry Andric         SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
11960b57cec5SDimitry Andric       // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
11970b57cec5SDimitry Andric       VNInfo *DefVNI;
11980b57cec5SDimitry Andric       if (OldIdxOut != LR.begin() &&
11990b57cec5SDimitry Andric           !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
12000b57cec5SDimitry Andric                                      OldIdxOut->start)) {
12010b57cec5SDimitry Andric         // There is no gap between OldIdxOut and its predecessor anymore,
12020b57cec5SDimitry Andric         // merge them.
12030b57cec5SDimitry Andric         LiveRange::iterator IPrev = std::prev(OldIdxOut);
12040b57cec5SDimitry Andric         DefVNI = OldIdxVNI;
12050b57cec5SDimitry Andric         IPrev->end = OldIdxOut->end;
12060b57cec5SDimitry Andric       } else {
12070b57cec5SDimitry Andric         // The value is live in to OldIdx
12080b57cec5SDimitry Andric         LiveRange::iterator INext = std::next(OldIdxOut);
12090b57cec5SDimitry Andric         assert(INext != E && "Must have following segment");
12100b57cec5SDimitry Andric         // We merge OldIdxOut and its successor. As we're dealing with subreg
12110b57cec5SDimitry Andric         // reordering, there is always a successor to OldIdxOut in the same BB
12120b57cec5SDimitry Andric         // We don't need INext->valno anymore and will reuse for the new segment
12130b57cec5SDimitry Andric         // we create later.
12140b57cec5SDimitry Andric         DefVNI = OldIdxVNI;
12150b57cec5SDimitry Andric         INext->start = OldIdxOut->end;
12160b57cec5SDimitry Andric         INext->valno->def = INext->start;
12170b57cec5SDimitry Andric       }
12180b57cec5SDimitry Andric       // If NewIdx is behind the last segment, extend that and append a new one.
12190b57cec5SDimitry Andric       if (AfterNewIdx == E) {
12200b57cec5SDimitry Andric         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
12210b57cec5SDimitry Andric         // one position.
12220b57cec5SDimitry Andric         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
12230b57cec5SDimitry Andric         // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
12240b57cec5SDimitry Andric         std::copy(std::next(OldIdxOut), E, OldIdxOut);
12250b57cec5SDimitry Andric         // The last segment is undefined now, reuse it for a dead def.
12260b57cec5SDimitry Andric         LiveRange::iterator NewSegment = std::prev(E);
12270b57cec5SDimitry Andric         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
12280b57cec5SDimitry Andric                                          DefVNI);
12290b57cec5SDimitry Andric         DefVNI->def = NewIdxDef;
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric         LiveRange::iterator Prev = std::prev(NewSegment);
12320b57cec5SDimitry Andric         Prev->end = NewIdxDef;
12330b57cec5SDimitry Andric       } else {
12340b57cec5SDimitry Andric         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
12350b57cec5SDimitry Andric         // one position.
12360b57cec5SDimitry Andric         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
12370b57cec5SDimitry Andric         // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
12380b57cec5SDimitry Andric         std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
12390b57cec5SDimitry Andric         LiveRange::iterator Prev = std::prev(AfterNewIdx);
12400b57cec5SDimitry Andric         // We have two cases:
12410b57cec5SDimitry Andric         if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
12420b57cec5SDimitry Andric           // Case 1: NewIdx is inside a liverange. Split this liverange at
12430b57cec5SDimitry Andric           // NewIdxDef into the segment "Prev" followed by "NewSegment".
12440b57cec5SDimitry Andric           LiveRange::iterator NewSegment = AfterNewIdx;
12450b57cec5SDimitry Andric           *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
12460b57cec5SDimitry Andric           Prev->valno->def = NewIdxDef;
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric           *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
12490b57cec5SDimitry Andric           DefVNI->def = Prev->start;
12500b57cec5SDimitry Andric         } else {
12510b57cec5SDimitry Andric           // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
12520b57cec5SDimitry Andric           // turn Prev into a segment from NewIdx to AfterNewIdx->start.
12530b57cec5SDimitry Andric           *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
12540b57cec5SDimitry Andric           DefVNI->def = NewIdxDef;
12550b57cec5SDimitry Andric           assert(DefVNI != AfterNewIdx->valno);
12560b57cec5SDimitry Andric         }
12570b57cec5SDimitry Andric       }
12580b57cec5SDimitry Andric       return;
12590b57cec5SDimitry Andric     }
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric     if (AfterNewIdx != E &&
12620b57cec5SDimitry Andric         SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
12630b57cec5SDimitry Andric       // There is an existing def at NewIdx. The def at OldIdx is coalesced into
12640b57cec5SDimitry Andric       // that value.
12650b57cec5SDimitry Andric       assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
12660b57cec5SDimitry Andric       LR.removeValNo(OldIdxVNI);
12670b57cec5SDimitry Andric     } else {
12680b57cec5SDimitry Andric       // There was no existing def at NewIdx. We need to create a dead def
12690b57cec5SDimitry Andric       // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
12700b57cec5SDimitry Andric       // a new segment at the place where we want to construct the dead def.
12710b57cec5SDimitry Andric       //    |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
12720b57cec5SDimitry Andric       // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
12730b57cec5SDimitry Andric       assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
12740b57cec5SDimitry Andric       std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
12750b57cec5SDimitry Andric       // We can reuse OldIdxVNI now.
12760b57cec5SDimitry Andric       LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
12770b57cec5SDimitry Andric       VNInfo *NewSegmentVNI = OldIdxVNI;
12780b57cec5SDimitry Andric       NewSegmentVNI->def = NewIdxDef;
12790b57cec5SDimitry Andric       *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
12800b57cec5SDimitry Andric                                        NewSegmentVNI);
12810b57cec5SDimitry Andric     }
12820b57cec5SDimitry Andric   }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   /// Update LR to reflect an instruction has been moved upwards from OldIdx
12850b57cec5SDimitry Andric   /// to NewIdx (NewIdx < OldIdx).
1286e8d8bef9SDimitry Andric   void handleMoveUp(LiveRange &LR, Register Reg, LaneBitmask LaneMask) {
12870b57cec5SDimitry Andric     LiveRange::iterator E = LR.end();
12880b57cec5SDimitry Andric     // Segment going into OldIdx.
12890b57cec5SDimitry Andric     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric     // No value live before or after OldIdx? Nothing to do.
12920b57cec5SDimitry Andric     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
12930b57cec5SDimitry Andric       return;
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric     LiveRange::iterator OldIdxOut;
12960b57cec5SDimitry Andric     // Do we have a value live-in to OldIdx?
12970b57cec5SDimitry Andric     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
12980b57cec5SDimitry Andric       // If the live-in value isn't killed here, then we have no Def at
12990b57cec5SDimitry Andric       // OldIdx, moreover the value must be live at NewIdx so there is nothing
13000b57cec5SDimitry Andric       // to do.
13010b57cec5SDimitry Andric       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
13020b57cec5SDimitry Andric       if (!isKill)
13030b57cec5SDimitry Andric         return;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric       // At this point we have to move OldIdxIn->end back to the nearest
13060b57cec5SDimitry Andric       // previous use or (dead-)def but no further than NewIdx.
13070b57cec5SDimitry Andric       SlotIndex DefBeforeOldIdx
13080b57cec5SDimitry Andric         = std::max(OldIdxIn->start.getDeadSlot(),
13090b57cec5SDimitry Andric                    NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
13100b57cec5SDimitry Andric       OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric       // Did we have a Def at OldIdx? If not we are done now.
13130b57cec5SDimitry Andric       OldIdxOut = std::next(OldIdxIn);
13140b57cec5SDimitry Andric       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
13150b57cec5SDimitry Andric         return;
13160b57cec5SDimitry Andric     } else {
13170b57cec5SDimitry Andric       OldIdxOut = OldIdxIn;
13180b57cec5SDimitry Andric       OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
13190b57cec5SDimitry Andric     }
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric     // If we are here then there is a Definition at OldIdx. OldIdxOut points
13220b57cec5SDimitry Andric     // to the segment starting there.
13230b57cec5SDimitry Andric     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
13240b57cec5SDimitry Andric            "No def?");
13250b57cec5SDimitry Andric     VNInfo *OldIdxVNI = OldIdxOut->valno;
13260b57cec5SDimitry Andric     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
13270b57cec5SDimitry Andric     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric     // Is there an existing def at NewIdx?
13300b57cec5SDimitry Andric     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
13310b57cec5SDimitry Andric     LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
13320b57cec5SDimitry Andric     if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
13330b57cec5SDimitry Andric       assert(NewIdxOut->valno != OldIdxVNI &&
13340b57cec5SDimitry Andric              "Same value defined more than once?");
13350b57cec5SDimitry Andric       // If OldIdx was a dead def remove it.
13360b57cec5SDimitry Andric       if (!OldIdxDefIsDead) {
13370b57cec5SDimitry Andric         // Remove segment starting at NewIdx and move begin of OldIdxOut to
13380b57cec5SDimitry Andric         // NewIdx so it can take its place.
13390b57cec5SDimitry Andric         OldIdxVNI->def = NewIdxDef;
13400b57cec5SDimitry Andric         OldIdxOut->start = NewIdxDef;
13410b57cec5SDimitry Andric         LR.removeValNo(NewIdxOut->valno);
13420b57cec5SDimitry Andric       } else {
13430b57cec5SDimitry Andric         // Simply remove the dead def at OldIdx.
13440b57cec5SDimitry Andric         LR.removeValNo(OldIdxVNI);
13450b57cec5SDimitry Andric       }
13460b57cec5SDimitry Andric     } else {
13470b57cec5SDimitry Andric       // Previously nothing was live after NewIdx, so all we have to do now is
13480b57cec5SDimitry Andric       // move the begin of OldIdxOut to NewIdx.
13490b57cec5SDimitry Andric       if (!OldIdxDefIsDead) {
13500b57cec5SDimitry Andric         // Do we have any intermediate Defs between OldIdx and NewIdx?
13510b57cec5SDimitry Andric         if (OldIdxIn != E &&
13520b57cec5SDimitry Andric             SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
13530b57cec5SDimitry Andric           // OldIdx is not a dead def and NewIdx is before predecessor start.
13540b57cec5SDimitry Andric           LiveRange::iterator NewIdxIn = NewIdxOut;
13550b57cec5SDimitry Andric           assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
13560b57cec5SDimitry Andric           const SlotIndex SplitPos = NewIdxDef;
13570b57cec5SDimitry Andric           OldIdxVNI = OldIdxIn->valno;
13580b57cec5SDimitry Andric 
13598bcb0991SDimitry Andric           SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
13608bcb0991SDimitry Andric           LiveRange::iterator Prev = std::prev(OldIdxIn);
13618bcb0991SDimitry Andric           if (OldIdxIn != LR.begin() &&
13628bcb0991SDimitry Andric               SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
13638bcb0991SDimitry Andric             // If the segment before OldIdx read a value defined earlier than
13648bcb0991SDimitry Andric             // NewIdx, the moved instruction also reads and forwards that
13658bcb0991SDimitry Andric             // value. Extend the lifetime of the new def point.
13668bcb0991SDimitry Andric 
13678bcb0991SDimitry Andric             // Extend to where the previous range started, unless there is
13688bcb0991SDimitry Andric             // another redef first.
13698bcb0991SDimitry Andric             NewDefEndPoint = std::min(OldIdxIn->start,
13708bcb0991SDimitry Andric                                       std::next(NewIdxOut)->start);
13718bcb0991SDimitry Andric           }
13728bcb0991SDimitry Andric 
13730b57cec5SDimitry Andric           // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
13740b57cec5SDimitry Andric           OldIdxOut->valno->def = OldIdxIn->start;
13750b57cec5SDimitry Andric           *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
13760b57cec5SDimitry Andric                                           OldIdxOut->valno);
13770b57cec5SDimitry Andric           // OldIdxIn and OldIdxVNI are now undef and can be overridden.
13780b57cec5SDimitry Andric           // We Slide [NewIdxIn, OldIdxIn) down one position.
13790b57cec5SDimitry Andric           //    |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
13800b57cec5SDimitry Andric           // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
13810b57cec5SDimitry Andric           std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
13820b57cec5SDimitry Andric           // NewIdxIn is now considered undef so we can reuse it for the moved
13830b57cec5SDimitry Andric           // value.
13840b57cec5SDimitry Andric           LiveRange::iterator NewSegment = NewIdxIn;
13850b57cec5SDimitry Andric           LiveRange::iterator Next = std::next(NewSegment);
13860b57cec5SDimitry Andric           if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
13870b57cec5SDimitry Andric             // There is no gap between NewSegment and its predecessor.
13880b57cec5SDimitry Andric             *NewSegment = LiveRange::Segment(Next->start, SplitPos,
13890b57cec5SDimitry Andric                                              Next->valno);
13908bcb0991SDimitry Andric 
13918bcb0991SDimitry Andric             *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
13920b57cec5SDimitry Andric             Next->valno->def = SplitPos;
13930b57cec5SDimitry Andric           } else {
13940b57cec5SDimitry Andric             // There is a gap between NewSegment and its predecessor
13950b57cec5SDimitry Andric             // Value becomes live in.
13960b57cec5SDimitry Andric             *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
13970b57cec5SDimitry Andric             NewSegment->valno->def = SplitPos;
13980b57cec5SDimitry Andric           }
13990b57cec5SDimitry Andric         } else {
14000b57cec5SDimitry Andric           // Leave the end point of a live def.
14010b57cec5SDimitry Andric           OldIdxOut->start = NewIdxDef;
14020b57cec5SDimitry Andric           OldIdxVNI->def = NewIdxDef;
14030b57cec5SDimitry Andric           if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
14045ffd83dbSDimitry Andric             OldIdxIn->end = NewIdxDef;
14050b57cec5SDimitry Andric         }
14060b57cec5SDimitry Andric       } else if (OldIdxIn != E
14070b57cec5SDimitry Andric           && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
14080b57cec5SDimitry Andric           && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
14090b57cec5SDimitry Andric         // OldIdxVNI is a dead def that has been moved into the middle of
14100b57cec5SDimitry Andric         // another value in LR. That can happen when LR is a whole register,
14110b57cec5SDimitry Andric         // but the dead def is a write to a subreg that is dead at NewIdx.
14120b57cec5SDimitry Andric         // The dead def may have been moved across other values
14130b57cec5SDimitry Andric         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
14140b57cec5SDimitry Andric         // down one position.
14150b57cec5SDimitry Andric         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
14160b57cec5SDimitry Andric         // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
14170b57cec5SDimitry Andric         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
14180b57cec5SDimitry Andric         // Modify the segment at NewIdxOut and the following segment to meet at
14190b57cec5SDimitry Andric         // the point of the dead def, with the following segment getting
14200b57cec5SDimitry Andric         // OldIdxVNI as its value number.
14210b57cec5SDimitry Andric         *NewIdxOut = LiveRange::Segment(
14220b57cec5SDimitry Andric             NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
14230b57cec5SDimitry Andric         *(NewIdxOut + 1) = LiveRange::Segment(
14240b57cec5SDimitry Andric             NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
14250b57cec5SDimitry Andric         OldIdxVNI->def = NewIdxDef;
14260b57cec5SDimitry Andric         // Modify subsequent segments to be defined by the moved def OldIdxVNI.
1427fcaf7f86SDimitry Andric         for (auto *Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
14280b57cec5SDimitry Andric           Idx->valno = OldIdxVNI;
14290b57cec5SDimitry Andric         // Aggressively remove all dead flags from the former dead definition.
14300b57cec5SDimitry Andric         // Kill/dead flags shouldn't be used while live intervals exist; they
14310b57cec5SDimitry Andric         // will be reinserted by VirtRegRewriter.
14320b57cec5SDimitry Andric         if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
14330b57cec5SDimitry Andric           for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
14340b57cec5SDimitry Andric             if (MO->isReg() && !MO->isUse())
14350b57cec5SDimitry Andric               MO->setIsDead(false);
14360b57cec5SDimitry Andric       } else {
14370b57cec5SDimitry Andric         // OldIdxVNI is a dead def. It may have been moved across other values
14380b57cec5SDimitry Andric         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
14390b57cec5SDimitry Andric         // down one position.
14400b57cec5SDimitry Andric         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
14410b57cec5SDimitry Andric         // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
14420b57cec5SDimitry Andric         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
14430b57cec5SDimitry Andric         // OldIdxVNI can be reused now to build a new dead def segment.
14440b57cec5SDimitry Andric         LiveRange::iterator NewSegment = NewIdxOut;
14450b57cec5SDimitry Andric         VNInfo *NewSegmentVNI = OldIdxVNI;
14460b57cec5SDimitry Andric         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
14470b57cec5SDimitry Andric                                          NewSegmentVNI);
14480b57cec5SDimitry Andric         NewSegmentVNI->def = NewIdxDef;
14490b57cec5SDimitry Andric       }
14500b57cec5SDimitry Andric     }
14510b57cec5SDimitry Andric   }
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   void updateRegMaskSlots() {
14540b57cec5SDimitry Andric     SmallVectorImpl<SlotIndex>::iterator RI =
14550b57cec5SDimitry Andric         llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
14560b57cec5SDimitry Andric     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
14570b57cec5SDimitry Andric            "No RegMask at OldIdx.");
14580b57cec5SDimitry Andric     *RI = NewIdx.getRegSlot();
14590b57cec5SDimitry Andric     assert((RI == LIS.RegMaskSlots.begin() ||
14600b57cec5SDimitry Andric             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
14610b57cec5SDimitry Andric            "Cannot move regmask instruction above another call");
14620b57cec5SDimitry Andric     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
14630b57cec5SDimitry Andric             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
14640b57cec5SDimitry Andric            "Cannot move regmask instruction below another call");
14650b57cec5SDimitry Andric   }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric   // Return the last use of reg between NewIdx and OldIdx.
1468e8d8bef9SDimitry Andric   SlotIndex findLastUseBefore(SlotIndex Before, Register Reg,
14690b57cec5SDimitry Andric                               LaneBitmask LaneMask) {
1470bdd1243dSDimitry Andric     if (Reg.isVirtual()) {
14710b57cec5SDimitry Andric       SlotIndex LastUse = Before;
14720b57cec5SDimitry Andric       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
14730b57cec5SDimitry Andric         if (MO.isUndef())
14740b57cec5SDimitry Andric           continue;
14750b57cec5SDimitry Andric         unsigned SubReg = MO.getSubReg();
14760b57cec5SDimitry Andric         if (SubReg != 0 && LaneMask.any()
14770b57cec5SDimitry Andric             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
14780b57cec5SDimitry Andric           continue;
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric         const MachineInstr &MI = *MO.getParent();
14810b57cec5SDimitry Andric         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
14820b57cec5SDimitry Andric         if (InstSlot > LastUse && InstSlot < OldIdx)
14830b57cec5SDimitry Andric           LastUse = InstSlot.getRegSlot();
14840b57cec5SDimitry Andric       }
14850b57cec5SDimitry Andric       return LastUse;
14860b57cec5SDimitry Andric     }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     // This is a regunit interval, so scanning the use list could be very
14890b57cec5SDimitry Andric     // expensive. Scan upwards from OldIdx instead.
14900b57cec5SDimitry Andric     assert(Before < OldIdx && "Expected upwards move");
14910b57cec5SDimitry Andric     SlotIndexes *Indexes = LIS.getSlotIndexes();
14920b57cec5SDimitry Andric     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric     // OldIdx may not correspond to an instruction any longer, so set MII to
14950b57cec5SDimitry Andric     // point to the next instruction after OldIdx, or MBB->end().
14960b57cec5SDimitry Andric     MachineBasicBlock::iterator MII = MBB->end();
14970b57cec5SDimitry Andric     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
14980b57cec5SDimitry Andric                            Indexes->getNextNonNullIndex(OldIdx)))
14990b57cec5SDimitry Andric       if (MI->getParent() == MBB)
15000b57cec5SDimitry Andric         MII = MI;
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric     MachineBasicBlock::iterator Begin = MBB->begin();
15030b57cec5SDimitry Andric     while (MII != Begin) {
1504fe6060f1SDimitry Andric       if ((--MII)->isDebugOrPseudoInstr())
15050b57cec5SDimitry Andric         continue;
15060b57cec5SDimitry Andric       SlotIndex Idx = Indexes->getInstructionIndex(*MII);
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric       // Stop searching when Before is reached.
15090b57cec5SDimitry Andric       if (!SlotIndex::isEarlierInstr(Before, Idx))
15100b57cec5SDimitry Andric         return Before;
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric       // Check if MII uses Reg.
15130b57cec5SDimitry Andric       for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1514bdd1243dSDimitry Andric         if (MO->isReg() && !MO->isUndef() && MO->getReg().isPhysical() &&
15150b57cec5SDimitry Andric             TRI.hasRegUnit(MO->getReg(), Reg))
15160b57cec5SDimitry Andric           return Idx.getRegSlot();
15170b57cec5SDimitry Andric     }
15180b57cec5SDimitry Andric     // Didn't reach Before. It must be the first instruction in the block.
15190b57cec5SDimitry Andric     return Before;
15200b57cec5SDimitry Andric   }
15210b57cec5SDimitry Andric };
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
15248bcb0991SDimitry Andric   // It is fine to move a bundle as a whole, but not an individual instruction
15258bcb0991SDimitry Andric   // inside it.
15268bcb0991SDimitry Andric   assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
15278bcb0991SDimitry Andric          "Cannot move instruction in bundle");
15280b57cec5SDimitry Andric   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
15290b57cec5SDimitry Andric   Indexes->removeMachineInstrFromMaps(MI);
15300b57cec5SDimitry Andric   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
15310b57cec5SDimitry Andric   assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
15320b57cec5SDimitry Andric          OldIndex < getMBBEndIdx(MI.getParent()) &&
15330b57cec5SDimitry Andric          "Cannot handle moves across basic block boundaries.");
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
15360b57cec5SDimitry Andric   HME.updateAllRanges(&MI);
15370b57cec5SDimitry Andric }
15380b57cec5SDimitry Andric 
15395ffd83dbSDimitry Andric void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart,
15400b57cec5SDimitry Andric                                             bool UpdateFlags) {
15415ffd83dbSDimitry Andric   assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
15425ffd83dbSDimitry Andric          "Bundle start is not a bundle");
15435ffd83dbSDimitry Andric   SmallVector<SlotIndex, 16> ToProcess;
15445ffd83dbSDimitry Andric   const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart);
15455ffd83dbSDimitry Andric   auto BundleEnd = getBundleEnd(BundleStart.getIterator());
15465ffd83dbSDimitry Andric 
15475ffd83dbSDimitry Andric   auto I = BundleStart.getIterator();
15485ffd83dbSDimitry Andric   I++;
15495ffd83dbSDimitry Andric   while (I != BundleEnd) {
15505ffd83dbSDimitry Andric     if (!Indexes->hasIndex(*I))
15515ffd83dbSDimitry Andric       continue;
15525ffd83dbSDimitry Andric     SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true);
15535ffd83dbSDimitry Andric     ToProcess.push_back(OldIndex);
15545ffd83dbSDimitry Andric     Indexes->removeMachineInstrFromMaps(*I, true);
15555ffd83dbSDimitry Andric     I++;
15565ffd83dbSDimitry Andric   }
15575ffd83dbSDimitry Andric   for (SlotIndex OldIndex : ToProcess) {
15580b57cec5SDimitry Andric     HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
15595ffd83dbSDimitry Andric     HME.updateAllRanges(&BundleStart);
15605ffd83dbSDimitry Andric   }
15615ffd83dbSDimitry Andric 
15625ffd83dbSDimitry Andric   // Fix up dead defs
15635ffd83dbSDimitry Andric   const SlotIndex Index = getInstructionIndex(BundleStart);
1564*0fca6ea1SDimitry Andric   for (MachineOperand &MO : BundleStart.operands()) {
15655ffd83dbSDimitry Andric     if (!MO.isReg())
15665ffd83dbSDimitry Andric       continue;
15675ffd83dbSDimitry Andric     Register Reg = MO.getReg();
15685ffd83dbSDimitry Andric     if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
15695ffd83dbSDimitry Andric       LiveInterval &LI = getInterval(Reg);
15705ffd83dbSDimitry Andric       LiveQueryResult LRQ = LI.Query(Index);
15715ffd83dbSDimitry Andric       if (LRQ.isDeadDef())
15725ffd83dbSDimitry Andric         MO.setIsDead();
15735ffd83dbSDimitry Andric     }
15745ffd83dbSDimitry Andric   }
15750b57cec5SDimitry Andric }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
15780b57cec5SDimitry Andric                                         const MachineBasicBlock::iterator End,
1579e8d8bef9SDimitry Andric                                         const SlotIndex EndIdx, LiveRange &LR,
1580e8d8bef9SDimitry Andric                                         const Register Reg,
15810b57cec5SDimitry Andric                                         LaneBitmask LaneMask) {
1582e8d8bef9SDimitry Andric   LiveInterval::iterator LII = LR.find(EndIdx);
15830b57cec5SDimitry Andric   SlotIndex lastUseIdx;
1584349cc55cSDimitry Andric   if (LII != LR.end() && LII->start < EndIdx) {
15850b57cec5SDimitry Andric     lastUseIdx = LII->end;
1586349cc55cSDimitry Andric   } else if (LII == LR.begin()) {
1587349cc55cSDimitry Andric     // We may not have a liverange at all if this is a subregister untouched
1588349cc55cSDimitry Andric     // between \p Begin and \p End.
1589349cc55cSDimitry Andric   } else {
15900b57cec5SDimitry Andric     --LII;
1591349cc55cSDimitry Andric   }
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric   for (MachineBasicBlock::iterator I = End; I != Begin;) {
15940b57cec5SDimitry Andric     --I;
15950b57cec5SDimitry Andric     MachineInstr &MI = *I;
1596fe6060f1SDimitry Andric     if (MI.isDebugOrPseudoInstr())
15970b57cec5SDimitry Andric       continue;
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric     SlotIndex instrIdx = getInstructionIndex(MI);
16000b57cec5SDimitry Andric     bool isStartValid = getInstructionFromIndex(LII->start);
16010b57cec5SDimitry Andric     bool isEndValid = getInstructionFromIndex(LII->end);
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric     // FIXME: This doesn't currently handle early-clobber or multiple removed
16040b57cec5SDimitry Andric     // defs inside of the region to repair.
1605349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
16060b57cec5SDimitry Andric       if (!MO.isReg() || MO.getReg() != Reg)
16070b57cec5SDimitry Andric         continue;
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric       unsigned SubReg = MO.getSubReg();
16100b57cec5SDimitry Andric       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
16110b57cec5SDimitry Andric       if ((Mask & LaneMask).none())
16120b57cec5SDimitry Andric         continue;
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric       if (MO.isDef()) {
16150b57cec5SDimitry Andric         if (!isStartValid) {
16160b57cec5SDimitry Andric           if (LII->end.isDead()) {
1617349cc55cSDimitry Andric             LII = LR.removeSegment(LII, true);
16180b57cec5SDimitry Andric             if (LII != LR.begin())
1619349cc55cSDimitry Andric               --LII;
16200b57cec5SDimitry Andric           } else {
16210b57cec5SDimitry Andric             LII->start = instrIdx.getRegSlot();
16220b57cec5SDimitry Andric             LII->valno->def = instrIdx.getRegSlot();
16230b57cec5SDimitry Andric             if (MO.getSubReg() && !MO.isUndef())
16240b57cec5SDimitry Andric               lastUseIdx = instrIdx.getRegSlot();
16250b57cec5SDimitry Andric             else
16260b57cec5SDimitry Andric               lastUseIdx = SlotIndex();
16270b57cec5SDimitry Andric             continue;
16280b57cec5SDimitry Andric           }
16290b57cec5SDimitry Andric         }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric         if (!lastUseIdx.isValid()) {
16320b57cec5SDimitry Andric           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
16330b57cec5SDimitry Andric           LiveRange::Segment S(instrIdx.getRegSlot(),
16340b57cec5SDimitry Andric                                instrIdx.getDeadSlot(), VNI);
16350b57cec5SDimitry Andric           LII = LR.addSegment(S);
16360b57cec5SDimitry Andric         } else if (LII->start != instrIdx.getRegSlot()) {
16370b57cec5SDimitry Andric           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
16380b57cec5SDimitry Andric           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
16390b57cec5SDimitry Andric           LII = LR.addSegment(S);
16400b57cec5SDimitry Andric         }
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric         if (MO.getSubReg() && !MO.isUndef())
16430b57cec5SDimitry Andric           lastUseIdx = instrIdx.getRegSlot();
16440b57cec5SDimitry Andric         else
16450b57cec5SDimitry Andric           lastUseIdx = SlotIndex();
16460b57cec5SDimitry Andric       } else if (MO.isUse()) {
16470b57cec5SDimitry Andric         // FIXME: This should probably be handled outside of this branch,
16480b57cec5SDimitry Andric         // either as part of the def case (for defs inside of the region) or
16490b57cec5SDimitry Andric         // after the loop over the region.
16500b57cec5SDimitry Andric         if (!isEndValid && !LII->end.isBlock())
16510b57cec5SDimitry Andric           LII->end = instrIdx.getRegSlot();
16520b57cec5SDimitry Andric         if (!lastUseIdx.isValid())
16530b57cec5SDimitry Andric           lastUseIdx = instrIdx.getRegSlot();
16540b57cec5SDimitry Andric       }
16550b57cec5SDimitry Andric     }
16560b57cec5SDimitry Andric   }
1657349cc55cSDimitry Andric 
1658349cc55cSDimitry Andric   bool isStartValid = getInstructionFromIndex(LII->start);
1659349cc55cSDimitry Andric   if (!isStartValid && LII->end.isDead())
1660349cc55cSDimitry Andric     LR.removeSegment(*LII, true);
16610b57cec5SDimitry Andric }
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric void
16640b57cec5SDimitry Andric LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
16650b57cec5SDimitry Andric                                       MachineBasicBlock::iterator Begin,
16660b57cec5SDimitry Andric                                       MachineBasicBlock::iterator End,
16675ffd83dbSDimitry Andric                                       ArrayRef<Register> OrigRegs) {
16680b57cec5SDimitry Andric   // Find anchor points, which are at the beginning/end of blocks or at
16690b57cec5SDimitry Andric   // instructions that already have indexes.
1670fcaf7f86SDimitry Andric   while (Begin != MBB->begin() && !Indexes->hasIndex(*std::prev(Begin)))
16710b57cec5SDimitry Andric     --Begin;
16720b57cec5SDimitry Andric   while (End != MBB->end() && !Indexes->hasIndex(*End))
16730b57cec5SDimitry Andric     ++End;
16740b57cec5SDimitry Andric 
1675e8d8bef9SDimitry Andric   SlotIndex EndIdx;
16760b57cec5SDimitry Andric   if (End == MBB->end())
1677e8d8bef9SDimitry Andric     EndIdx = getMBBEndIdx(MBB).getPrevSlot();
16780b57cec5SDimitry Andric   else
1679e8d8bef9SDimitry Andric     EndIdx = getInstructionIndex(*End);
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   Indexes->repairIndexesInRange(MBB, Begin, End);
16820b57cec5SDimitry Andric 
1683349cc55cSDimitry Andric   // Make sure a live interval exists for all register operands in the range.
1684349cc55cSDimitry Andric   SmallVector<Register> RegsToRepair(OrigRegs.begin(), OrigRegs.end());
16850b57cec5SDimitry Andric   for (MachineBasicBlock::iterator I = End; I != Begin;) {
16860b57cec5SDimitry Andric     --I;
16870b57cec5SDimitry Andric     MachineInstr &MI = *I;
1688fe6060f1SDimitry Andric     if (MI.isDebugOrPseudoInstr())
16890b57cec5SDimitry Andric       continue;
1690349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1691349cc55cSDimitry Andric       if (MO.isReg() && MO.getReg().isVirtual()) {
1692349cc55cSDimitry Andric         Register Reg = MO.getReg();
1693349cc55cSDimitry Andric         if (MO.getSubReg() && hasInterval(Reg) &&
1694*0fca6ea1SDimitry Andric             MRI->shouldTrackSubRegLiveness(Reg)) {
1695*0fca6ea1SDimitry Andric           LiveInterval &LI = getInterval(Reg);
1696*0fca6ea1SDimitry Andric           if (!LI.hasSubRanges()) {
1697*0fca6ea1SDimitry Andric             // If the new instructions refer to subregs but the old instructions
1698*0fca6ea1SDimitry Andric             // did not, throw away any old live interval so it will be
1699*0fca6ea1SDimitry Andric             // recomputed with subranges.
1700349cc55cSDimitry Andric             removeInterval(Reg);
1701*0fca6ea1SDimitry Andric           } else if (MO.isDef()) {
1702*0fca6ea1SDimitry Andric             // Similarly if a subreg def has no precise subrange match then
1703*0fca6ea1SDimitry Andric             // assume we need to recompute all subranges.
1704*0fca6ea1SDimitry Andric             unsigned SubReg = MO.getSubReg();
1705*0fca6ea1SDimitry Andric             LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1706*0fca6ea1SDimitry Andric             if (llvm::none_of(LI.subranges(),
1707*0fca6ea1SDimitry Andric                               [Mask](LiveInterval::SubRange &SR) {
1708*0fca6ea1SDimitry Andric                                 return SR.LaneMask == Mask;
1709*0fca6ea1SDimitry Andric                               })) {
1710*0fca6ea1SDimitry Andric               removeInterval(Reg);
1711*0fca6ea1SDimitry Andric             }
1712*0fca6ea1SDimitry Andric           }
1713*0fca6ea1SDimitry Andric         }
1714349cc55cSDimitry Andric         if (!hasInterval(Reg)) {
1715349cc55cSDimitry Andric           createAndComputeVirtRegInterval(Reg);
1716349cc55cSDimitry Andric           // Don't bother to repair a freshly calculated live interval.
17175f757f3fSDimitry Andric           llvm::erase(RegsToRepair, Reg);
1718349cc55cSDimitry Andric         }
17190b57cec5SDimitry Andric       }
17200b57cec5SDimitry Andric     }
17210b57cec5SDimitry Andric   }
17220b57cec5SDimitry Andric 
1723349cc55cSDimitry Andric   for (Register Reg : RegsToRepair) {
17245ffd83dbSDimitry Andric     if (!Reg.isVirtual())
17250b57cec5SDimitry Andric       continue;
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric     LiveInterval &LI = getInterval(Reg);
17280b57cec5SDimitry Andric     // FIXME: Should we support undefs that gain defs?
17290b57cec5SDimitry Andric     if (!LI.hasAtLeastOneValue())
17300b57cec5SDimitry Andric       continue;
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric     for (LiveInterval::SubRange &S : LI.subranges())
1733e8d8bef9SDimitry Andric       repairOldRegInRange(Begin, End, EndIdx, S, Reg, S.LaneMask);
1734349cc55cSDimitry Andric     LI.removeEmptySubRanges();
17350b57cec5SDimitry Andric 
1736e8d8bef9SDimitry Andric     repairOldRegInRange(Begin, End, EndIdx, LI, Reg);
17370b57cec5SDimitry Andric   }
17380b57cec5SDimitry Andric }
17390b57cec5SDimitry Andric 
1740e8d8bef9SDimitry Andric void LiveIntervals::removePhysRegDefAt(MCRegister Reg, SlotIndex Pos) {
174106c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(Reg)) {
174206c3fb27SDimitry Andric     if (LiveRange *LR = getCachedRegUnit(Unit))
17430b57cec5SDimitry Andric       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
17440b57cec5SDimitry Andric         LR->removeValNo(VNI);
17450b57cec5SDimitry Andric   }
17460b57cec5SDimitry Andric }
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
17490b57cec5SDimitry Andric   // LI may not have the main range computed yet, but its subranges may
17500b57cec5SDimitry Andric   // be present.
17510b57cec5SDimitry Andric   VNInfo *VNI = LI.getVNInfoAt(Pos);
17520b57cec5SDimitry Andric   if (VNI != nullptr) {
17530b57cec5SDimitry Andric     assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
17540b57cec5SDimitry Andric     LI.removeValNo(VNI);
17550b57cec5SDimitry Andric   }
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   // Also remove the value defined in subranges.
17580b57cec5SDimitry Andric   for (LiveInterval::SubRange &S : LI.subranges()) {
17590b57cec5SDimitry Andric     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
17600b57cec5SDimitry Andric       if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
17610b57cec5SDimitry Andric         S.removeValNo(SVNI);
17620b57cec5SDimitry Andric   }
17630b57cec5SDimitry Andric   LI.removeEmptySubRanges();
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
17670b57cec5SDimitry Andric     SmallVectorImpl<LiveInterval*> &SplitLIs) {
17680b57cec5SDimitry Andric   ConnectedVNInfoEqClasses ConEQ(*this);
17690b57cec5SDimitry Andric   unsigned NumComp = ConEQ.Classify(LI);
17700b57cec5SDimitry Andric   if (NumComp <= 1)
17710b57cec5SDimitry Andric     return;
17720b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Split " << NumComp << " components: " << LI << '\n');
1773e8d8bef9SDimitry Andric   Register Reg = LI.reg();
17740b57cec5SDimitry Andric   for (unsigned I = 1; I < NumComp; ++I) {
1775bdd1243dSDimitry Andric     Register NewVReg = MRI->cloneVirtualRegister(Reg);
17760b57cec5SDimitry Andric     LiveInterval &NewLI = createEmptyInterval(NewVReg);
17770b57cec5SDimitry Andric     SplitLIs.push_back(&NewLI);
17780b57cec5SDimitry Andric   }
17790b57cec5SDimitry Andric   ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
17800b57cec5SDimitry Andric }
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
17835ffd83dbSDimitry Andric   assert(LICalc && "LICalc not initialized.");
17845ffd83dbSDimitry Andric   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
17855ffd83dbSDimitry Andric   LICalc->constructMainRangeFromSubranges(LI);
17860b57cec5SDimitry Andric }
1787