1044eb2f6SDimitry Andric //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
971d5a254SDimitry Andric /// \file This file implements the LiveInterval analysis pass which is used
1071d5a254SDimitry Andric /// by the Linear Scan Register allocator. This pass linearizes the
1171d5a254SDimitry Andric /// basic blocks of the function in DFS order and computes live intervals for
1271d5a254SDimitry Andric /// each virtual and physical register.
13009b1c42SEd Schouten //
14009b1c42SEd Schouten //===----------------------------------------------------------------------===//
15009b1c42SEd Schouten
16044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
17ab44ce3dSDimitry Andric #include "llvm/ADT/ArrayRef.h"
18ab44ce3dSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
19ab44ce3dSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
20ab44ce3dSDimitry Andric #include "llvm/ADT/SmallVector.h"
217ab83427SDimitry Andric #include "llvm/ADT/iterator_range.h"
22ab44ce3dSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
23cfca06d7SDimitry Andric #include "llvm/CodeGen/LiveIntervalCalc.h"
24009b1c42SEd Schouten #include "llvm/CodeGen/LiveVariables.h"
25ab44ce3dSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
265ca98fd9SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
2758b69754SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
28ab44ce3dSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
29009b1c42SEd Schouten #include "llvm/CodeGen/MachineInstr.h"
30ab44ce3dSDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
31ab44ce3dSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
32009b1c42SEd Schouten #include "llvm/CodeGen/MachineRegisterInfo.h"
33009b1c42SEd Schouten #include "llvm/CodeGen/Passes.h"
34ab44ce3dSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
35145449b1SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
36044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
37044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
384a16efa3SDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
39eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
40344a3780SDimitry Andric #include "llvm/IR/Statepoint.h"
41ab44ce3dSDimitry Andric #include "llvm/MC/LaneBitmask.h"
42ab44ce3dSDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
43ab44ce3dSDimitry Andric #include "llvm/Pass.h"
44009b1c42SEd Schouten #include "llvm/Support/CommandLine.h"
45ab44ce3dSDimitry Andric #include "llvm/Support/Compiler.h"
46009b1c42SEd Schouten #include "llvm/Support/Debug.h"
47ab44ce3dSDimitry Andric #include "llvm/Support/MathExtras.h"
4859850d08SRoman Divacky #include "llvm/Support/raw_ostream.h"
49009b1c42SEd Schouten #include <algorithm>
50ab44ce3dSDimitry Andric #include <cassert>
51ab44ce3dSDimitry Andric #include <cstdint>
52ab44ce3dSDimitry Andric #include <iterator>
53ab44ce3dSDimitry Andric #include <tuple>
54ab44ce3dSDimitry Andric #include <utility>
55ab44ce3dSDimitry Andric
56009b1c42SEd Schouten using namespace llvm;
57009b1c42SEd Schouten
585ca98fd9SDimitry Andric #define DEBUG_TYPE "regalloc"
595ca98fd9SDimitry Andric
60ac9a064cSDimitry Andric AnalysisKey LiveIntervalsAnalysis::Key;
61ac9a064cSDimitry Andric
62ac9a064cSDimitry Andric LiveIntervalsAnalysis::Result
run(MachineFunction & MF,MachineFunctionAnalysisManager & MFAM)63ac9a064cSDimitry Andric LiveIntervalsAnalysis::run(MachineFunction &MF,
64ac9a064cSDimitry Andric MachineFunctionAnalysisManager &MFAM) {
65ac9a064cSDimitry Andric return Result(MF, MFAM.getResult<SlotIndexesAnalysis>(MF),
66ac9a064cSDimitry Andric MFAM.getResult<MachineDominatorTreeAnalysis>(MF));
67ac9a064cSDimitry Andric }
68ac9a064cSDimitry Andric
69ac9a064cSDimitry Andric PreservedAnalyses
run(MachineFunction & MF,MachineFunctionAnalysisManager & MFAM)70ac9a064cSDimitry Andric LiveIntervalsPrinterPass::run(MachineFunction &MF,
71ac9a064cSDimitry Andric MachineFunctionAnalysisManager &MFAM) {
72ac9a064cSDimitry Andric OS << "Live intervals for machine function: " << MF.getName() << ":\n";
73ac9a064cSDimitry Andric MFAM.getResult<LiveIntervalsAnalysis>(MF).print(OS);
74ac9a064cSDimitry Andric return PreservedAnalyses::all();
75ac9a064cSDimitry Andric }
76ac9a064cSDimitry Andric
77ac9a064cSDimitry Andric char LiveIntervalsWrapperPass::ID = 0;
78ac9a064cSDimitry Andric char &llvm::LiveIntervalsID = LiveIntervalsWrapperPass::ID;
79ac9a064cSDimitry Andric INITIALIZE_PASS_BEGIN(LiveIntervalsWrapperPass, "liveintervals",
80cf099d11SDimitry Andric "Live Interval Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)81ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
82ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
83ac9a064cSDimitry Andric INITIALIZE_PASS_END(LiveIntervalsWrapperPass, "liveintervals",
84ac9a064cSDimitry Andric "Live Interval Analysis", false, false)
85ac9a064cSDimitry Andric
86ac9a064cSDimitry Andric bool LiveIntervalsWrapperPass::runOnMachineFunction(MachineFunction &MF) {
87ac9a064cSDimitry Andric LIS.Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
88ac9a064cSDimitry Andric LIS.DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
89ac9a064cSDimitry Andric LIS.analyze(MF);
90ac9a064cSDimitry Andric LLVM_DEBUG(dump());
91ac9a064cSDimitry Andric return false;
92ac9a064cSDimitry Andric }
93009b1c42SEd Schouten
94f8af5cf6SDimitry Andric #ifndef NDEBUG
95f8af5cf6SDimitry Andric static cl::opt<bool> EnablePrecomputePhysRegs(
96f8af5cf6SDimitry Andric "precompute-phys-liveness", cl::Hidden,
97f8af5cf6SDimitry Andric cl::desc("Eagerly compute live intervals for all physreg units."));
98f8af5cf6SDimitry Andric #else
99f8af5cf6SDimitry Andric static bool EnablePrecomputePhysRegs = false;
100f8af5cf6SDimitry Andric #endif // NDEBUG
101f8af5cf6SDimitry Andric
1025a5ac124SDimitry Andric namespace llvm {
103ab44ce3dSDimitry Andric
1045a5ac124SDimitry Andric cl::opt<bool> UseSegmentSetForPhysRegs(
1055a5ac124SDimitry Andric "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
1065a5ac124SDimitry Andric cl::desc(
1075a5ac124SDimitry Andric "Use segment set for the computation of the live ranges of physregs."));
108ab44ce3dSDimitry Andric
109ab44ce3dSDimitry Andric } // end namespace llvm
1105a5ac124SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const111ac9a064cSDimitry Andric void LiveIntervalsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11259850d08SRoman Divacky AU.setPreservesCFG();
113ac9a064cSDimitry Andric AU.addPreserved<LiveVariablesWrapperPass>();
11463faed5bSDimitry Andric AU.addPreservedID(MachineLoopInfoID);
11558b69754SDimitry Andric AU.addRequiredTransitiveID(MachineDominatorsID);
116009b1c42SEd Schouten AU.addPreservedID(MachineDominatorsID);
117ac9a064cSDimitry Andric AU.addPreserved<SlotIndexesWrapperPass>();
118ac9a064cSDimitry Andric AU.addRequiredTransitive<SlotIndexesWrapperPass>();
119009b1c42SEd Schouten MachineFunctionPass::getAnalysisUsage(AU);
120009b1c42SEd Schouten }
121009b1c42SEd Schouten
LiveIntervalsWrapperPass()122ac9a064cSDimitry Andric LiveIntervalsWrapperPass::LiveIntervalsWrapperPass() : MachineFunctionPass(ID) {
123ac9a064cSDimitry Andric initializeLiveIntervalsWrapperPassPass(*PassRegistry::getPassRegistry());
12458b69754SDimitry Andric }
12558b69754SDimitry Andric
~LiveIntervals()126ac9a064cSDimitry Andric LiveIntervals::~LiveIntervals() { clear(); }
12758b69754SDimitry Andric
clear()128ac9a064cSDimitry Andric void LiveIntervals::clear() {
129009b1c42SEd Schouten // Free the live intervals themselves.
13058b69754SDimitry Andric for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
1311d5ae102SDimitry Andric delete VirtRegIntervals[Register::index2VirtReg(i)];
13258b69754SDimitry Andric VirtRegIntervals.clear();
13363faed5bSDimitry Andric RegMaskSlots.clear();
13463faed5bSDimitry Andric RegMaskBits.clear();
13563faed5bSDimitry Andric RegMaskBlocks.clear();
13659850d08SRoman Divacky
13771d5a254SDimitry Andric for (LiveRange *LR : RegUnitRanges)
13871d5a254SDimitry Andric delete LR;
139f8af5cf6SDimitry Andric RegUnitRanges.clear();
14058b69754SDimitry Andric
14166e41e3cSRoman Divacky // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
14266e41e3cSRoman Divacky VNInfoAllocator.Reset();
143009b1c42SEd Schouten }
144009b1c42SEd Schouten
analyze(MachineFunction & fn)145ac9a064cSDimitry Andric void LiveIntervals::analyze(MachineFunction &fn) {
14658b69754SDimitry Andric MF = &fn;
14758b69754SDimitry Andric MRI = &MF->getRegInfo();
14867c32a98SDimitry Andric TRI = MF->getSubtarget().getRegisterInfo();
14967c32a98SDimitry Andric TII = MF->getSubtarget().getInstrInfo();
15067c32a98SDimitry Andric
151cfca06d7SDimitry Andric if (!LICalc)
152ac9a064cSDimitry Andric LICalc = std::make_unique<LiveIntervalCalc>();
153009b1c42SEd Schouten
15458b69754SDimitry Andric // Allocate space for all virtual registers.
15558b69754SDimitry Andric VirtRegIntervals.resize(MRI->getNumVirtRegs());
15658b69754SDimitry Andric
15758b69754SDimitry Andric computeVirtRegs();
15858b69754SDimitry Andric computeRegMasks();
15958b69754SDimitry Andric computeLiveInRegUnits();
160009b1c42SEd Schouten
161f8af5cf6SDimitry Andric if (EnablePrecomputePhysRegs) {
162f8af5cf6SDimitry Andric // For stress testing, precompute live ranges of all physical register
163f8af5cf6SDimitry Andric // units, including reserved registers.
164f8af5cf6SDimitry Andric for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
165f8af5cf6SDimitry Andric getRegUnit(i);
166f8af5cf6SDimitry Andric }
167009b1c42SEd Schouten }
168009b1c42SEd Schouten
print(raw_ostream & OS) const169ac9a064cSDimitry Andric void LiveIntervals::print(raw_ostream &OS) const {
17059850d08SRoman Divacky OS << "********** INTERVALS **********\n";
17163faed5bSDimitry Andric
17258b69754SDimitry Andric // Dump the regunits.
17371d5a254SDimitry Andric for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
17471d5a254SDimitry Andric if (LiveRange *LR = RegUnitRanges[Unit])
175044eb2f6SDimitry Andric OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
17663faed5bSDimitry Andric
17763faed5bSDimitry Andric // Dump the virtregs.
17858b69754SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
179b60736ecSDimitry Andric Register Reg = Register::index2VirtReg(i);
18058b69754SDimitry Andric if (hasInterval(Reg))
181f8af5cf6SDimitry Andric OS << getInterval(Reg) << '\n';
182009b1c42SEd Schouten }
183009b1c42SEd Schouten
184522600a2SDimitry Andric OS << "RegMasks:";
18571d5a254SDimitry Andric for (SlotIndex Idx : RegMaskSlots)
18671d5a254SDimitry Andric OS << ' ' << Idx;
187522600a2SDimitry Andric OS << '\n';
188522600a2SDimitry Andric
18959850d08SRoman Divacky printInstrs(OS);
19059850d08SRoman Divacky }
19159850d08SRoman Divacky
printInstrs(raw_ostream & OS) const19259850d08SRoman Divacky void LiveIntervals::printInstrs(raw_ostream &OS) const {
19359850d08SRoman Divacky OS << "********** MACHINEINSTRS **********\n";
19458b69754SDimitry Andric MF->print(OS, Indexes);
195009b1c42SEd Schouten }
196009b1c42SEd Schouten
197522600a2SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpInstrs() const19871d5a254SDimitry Andric LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
199829000e0SRoman Divacky printInstrs(dbgs());
20059850d08SRoman Divacky }
201522600a2SDimitry Andric #endif
20259850d08SRoman Divacky
203ac9a064cSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const204ac9a064cSDimitry Andric LLVM_DUMP_METHOD void LiveIntervals::dump() const { print(dbgs()); }
205ac9a064cSDimitry Andric #endif
206ac9a064cSDimitry Andric
createInterval(Register reg)207b60736ecSDimitry Andric LiveInterval *LiveIntervals::createInterval(Register reg) {
208e3b55780SDimitry Andric float Weight = reg.isPhysical() ? huge_valf : 0.0F;
209009b1c42SEd Schouten return new LiveInterval(reg, Weight);
210009b1c42SEd Schouten }
211009b1c42SEd Schouten
21271d5a254SDimitry Andric /// Compute the live interval of a virtual register, based on defs and uses.
computeVirtRegInterval(LiveInterval & LI)213706b4fc4SDimitry Andric bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
214cfca06d7SDimitry Andric assert(LICalc && "LICalc not initialized.");
215f8af5cf6SDimitry Andric assert(LI.empty() && "Should only compute empty intervals.");
216cfca06d7SDimitry Andric LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
217b60736ecSDimitry Andric LICalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg()));
218706b4fc4SDimitry Andric return computeDeadValues(LI, nullptr);
219009b1c42SEd Schouten }
220009b1c42SEd Schouten
computeVirtRegs()22158b69754SDimitry Andric void LiveIntervals::computeVirtRegs() {
22258b69754SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
223b60736ecSDimitry Andric Register Reg = Register::index2VirtReg(i);
22458b69754SDimitry Andric if (MRI->reg_nodbg_empty(Reg))
22558b69754SDimitry Andric continue;
226706b4fc4SDimitry Andric LiveInterval &LI = createEmptyInterval(Reg);
227706b4fc4SDimitry Andric bool NeedSplit = computeVirtRegInterval(LI);
228706b4fc4SDimitry Andric if (NeedSplit) {
229706b4fc4SDimitry Andric SmallVector<LiveInterval*, 8> SplitLIs;
230706b4fc4SDimitry Andric splitSeparateComponents(LI, SplitLIs);
231706b4fc4SDimitry Andric }
23258b69754SDimitry Andric }
23358b69754SDimitry Andric }
23458b69754SDimitry Andric
computeRegMasks()23558b69754SDimitry Andric void LiveIntervals::computeRegMasks() {
23658b69754SDimitry Andric RegMaskBlocks.resize(MF->getNumBlockIDs());
23758b69754SDimitry Andric
23858b69754SDimitry Andric // Find all instructions with regmask operands.
23971d5a254SDimitry Andric for (const MachineBasicBlock &MBB : *MF) {
240dd58ef01SDimitry Andric std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
24158b69754SDimitry Andric RMB.first = RegMaskSlots.size();
242dd58ef01SDimitry Andric
243dd58ef01SDimitry Andric // Some block starts, such as EH funclets, create masks.
244dd58ef01SDimitry Andric if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
245dd58ef01SDimitry Andric RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
246dd58ef01SDimitry Andric RegMaskBits.push_back(Mask);
247dd58ef01SDimitry Andric }
248dd58ef01SDimitry Andric
249b60736ecSDimitry Andric // Unwinders may clobber additional registers.
250b60736ecSDimitry Andric // FIXME: This functionality can possibly be merged into
251b60736ecSDimitry Andric // MachineBasicBlock::getBeginClobberMask().
252b60736ecSDimitry Andric if (MBB.isEHPad())
253b60736ecSDimitry Andric if (auto *Mask = TRI->getCustomEHPadPreservedMask(*MBB.getParent())) {
254b60736ecSDimitry Andric RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
255b60736ecSDimitry Andric RegMaskBits.push_back(Mask);
256b60736ecSDimitry Andric }
257b60736ecSDimitry Andric
25871d5a254SDimitry Andric for (const MachineInstr &MI : MBB) {
259dd58ef01SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
26085d8b2bbSDimitry Andric if (!MO.isRegMask())
26158b69754SDimitry Andric continue;
26201095a5dSDimitry Andric RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
26385d8b2bbSDimitry Andric RegMaskBits.push_back(MO.getRegMask());
26458b69754SDimitry Andric }
265dd58ef01SDimitry Andric }
266dd58ef01SDimitry Andric
26701095a5dSDimitry Andric // Some block ends, such as funclet returns, create masks. Put the mask on
26801095a5dSDimitry Andric // the last instruction of the block, because MBB slot index intervals are
26901095a5dSDimitry Andric // half-open.
270dd58ef01SDimitry Andric if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
27101095a5dSDimitry Andric assert(!MBB.empty() && "empty return block?");
27201095a5dSDimitry Andric RegMaskSlots.push_back(
27301095a5dSDimitry Andric Indexes->getInstructionIndex(MBB.back()).getRegSlot());
274dd58ef01SDimitry Andric RegMaskBits.push_back(Mask);
275dd58ef01SDimitry Andric }
276dd58ef01SDimitry Andric
27758b69754SDimitry Andric // Compute the number of register mask instructions in this block.
278522600a2SDimitry Andric RMB.second = RegMaskSlots.size() - RMB.first;
27958b69754SDimitry Andric }
28058b69754SDimitry Andric }
28158b69754SDimitry Andric
28258b69754SDimitry Andric //===----------------------------------------------------------------------===//
28358b69754SDimitry Andric // Register Unit Liveness
28458b69754SDimitry Andric //===----------------------------------------------------------------------===//
28558b69754SDimitry Andric //
28658b69754SDimitry Andric // Fixed interference typically comes from ABI boundaries: Function arguments
28758b69754SDimitry Andric // and return values are passed in fixed registers, and so are exception
28858b69754SDimitry Andric // pointers entering landing pads. Certain instructions require values to be
28958b69754SDimitry Andric // present in specific registers. That is also represented through fixed
29058b69754SDimitry Andric // interference.
29158b69754SDimitry Andric //
29258b69754SDimitry Andric
29371d5a254SDimitry Andric /// Compute the live range of a register unit, based on the uses and defs of
29471d5a254SDimitry Andric /// aliasing registers. The range should be empty, or contain only dead
29571d5a254SDimitry Andric /// phi-defs from ABI blocks.
computeRegUnitRange(LiveRange & LR,unsigned Unit)296f8af5cf6SDimitry Andric void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
297cfca06d7SDimitry Andric assert(LICalc && "LICalc not initialized.");
298cfca06d7SDimitry Andric LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
29958b69754SDimitry Andric
30058b69754SDimitry Andric // The physregs aliasing Unit are the roots and their super-registers.
30158b69754SDimitry Andric // Create all values as dead defs before extending to uses. Note that roots
30258b69754SDimitry Andric // may share super-registers. That's OK because createDeadDefs() is
30358b69754SDimitry Andric // idempotent. It is very rare for a register unit to have multiple roots, so
30458b69754SDimitry Andric // uniquing super-registers is probably not worthwhile.
305edad5bcbSDimitry Andric bool IsReserved = false;
30671d5a254SDimitry Andric for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
307edad5bcbSDimitry Andric bool IsRootReserved = true;
3087fa27ce4SDimitry Andric for (MCPhysReg Reg : TRI->superregs_inclusive(*Root)) {
30971d5a254SDimitry Andric if (!MRI->reg_empty(Reg))
310cfca06d7SDimitry Andric LICalc->createDeadDefs(LR, Reg);
31171d5a254SDimitry Andric // A register unit is considered reserved if all its roots and all their
31271d5a254SDimitry Andric // super registers are reserved.
31371d5a254SDimitry Andric if (!MRI->isReserved(Reg))
314edad5bcbSDimitry Andric IsRootReserved = false;
31558b69754SDimitry Andric }
316edad5bcbSDimitry Andric IsReserved |= IsRootReserved;
31758b69754SDimitry Andric }
318edad5bcbSDimitry Andric assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
319edad5bcbSDimitry Andric "reserved computation mismatch");
32058b69754SDimitry Andric
321f8af5cf6SDimitry Andric // Now extend LR to reach all uses.
32258b69754SDimitry Andric // Ignore uses of reserved registers. We only track defs of those.
32371d5a254SDimitry Andric if (!IsReserved) {
32471d5a254SDimitry Andric for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
3257fa27ce4SDimitry Andric for (MCPhysReg Reg : TRI->superregs_inclusive(*Root)) {
32671d5a254SDimitry Andric if (!MRI->reg_empty(Reg))
327cfca06d7SDimitry Andric LICalc->extendToUses(LR, Reg);
32858b69754SDimitry Andric }
32958b69754SDimitry Andric }
33071d5a254SDimitry Andric }
3315a5ac124SDimitry Andric
3325a5ac124SDimitry Andric // Flush the segment set to the segment vector.
3335a5ac124SDimitry Andric if (UseSegmentSetForPhysRegs)
3345a5ac124SDimitry Andric LR.flushSegmentSet();
33558b69754SDimitry Andric }
33658b69754SDimitry Andric
33771d5a254SDimitry Andric /// Precompute the live ranges of any register units that are live-in to an ABI
33871d5a254SDimitry Andric /// block somewhere. Register values can appear without a corresponding def when
33971d5a254SDimitry Andric /// entering the entry block or a landing pad.
computeLiveInRegUnits()34058b69754SDimitry Andric void LiveIntervals::computeLiveInRegUnits() {
341f8af5cf6SDimitry Andric RegUnitRanges.resize(TRI->getNumRegUnits());
342eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
34358b69754SDimitry Andric
344f8af5cf6SDimitry Andric // Keep track of the live range sets allocated.
345f8af5cf6SDimitry Andric SmallVector<unsigned, 8> NewRanges;
34658b69754SDimitry Andric
34758b69754SDimitry Andric // Check all basic blocks for live-ins.
34871d5a254SDimitry Andric for (const MachineBasicBlock &MBB : *MF) {
34958b69754SDimitry Andric // We only care about ABI blocks: Entry + landing pads.
35071d5a254SDimitry Andric if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
35158b69754SDimitry Andric continue;
35258b69754SDimitry Andric
35358b69754SDimitry Andric // Create phi-defs at Begin for all live-in registers.
35471d5a254SDimitry Andric SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
355eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
35671d5a254SDimitry Andric for (const auto &LI : MBB.liveins()) {
3577fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
358f8af5cf6SDimitry Andric LiveRange *LR = RegUnitRanges[Unit];
359f8af5cf6SDimitry Andric if (!LR) {
3605a5ac124SDimitry Andric // Use segment set to speed-up initial computation of the live range.
3615a5ac124SDimitry Andric LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
362f8af5cf6SDimitry Andric NewRanges.push_back(Unit);
36358b69754SDimitry Andric }
364f8af5cf6SDimitry Andric VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
36558b69754SDimitry Andric (void)VNI;
366eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
36758b69754SDimitry Andric }
36858b69754SDimitry Andric }
369eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << '\n');
37058b69754SDimitry Andric }
371eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
37258b69754SDimitry Andric
373f8af5cf6SDimitry Andric // Compute the 'normal' part of the ranges.
37471d5a254SDimitry Andric for (unsigned Unit : NewRanges)
375f8af5cf6SDimitry Andric computeRegUnitRange(*RegUnitRanges[Unit], Unit);
376f8af5cf6SDimitry Andric }
37758b69754SDimitry Andric
createSegmentsForValues(LiveRange & LR,iterator_range<LiveInterval::vni_iterator> VNIs)37867c32a98SDimitry Andric static void createSegmentsForValues(LiveRange &LR,
37967c32a98SDimitry Andric iterator_range<LiveInterval::vni_iterator> VNIs) {
38071d5a254SDimitry Andric for (VNInfo *VNI : VNIs) {
38167c32a98SDimitry Andric if (VNI->isUnused())
38267c32a98SDimitry Andric continue;
38367c32a98SDimitry Andric SlotIndex Def = VNI->def;
38467c32a98SDimitry Andric LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
38567c32a98SDimitry Andric }
38667c32a98SDimitry Andric }
38767c32a98SDimitry Andric
extendSegmentsToUses(LiveRange & Segments,ShrinkToUsesWorkList & WorkList,Register Reg,LaneBitmask LaneMask)388eb11fae6SDimitry Andric void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
38967c32a98SDimitry Andric ShrinkToUsesWorkList &WorkList,
390b60736ecSDimitry Andric Register Reg, LaneBitmask LaneMask) {
39167c32a98SDimitry Andric // Keep track of the PHIs that are in use.
39267c32a98SDimitry Andric SmallPtrSet<VNInfo*, 8> UsedPHIs;
39367c32a98SDimitry Andric // Blocks that have already been added to WorkList as live-out.
39471d5a254SDimitry Andric SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
39567c32a98SDimitry Andric
396eb11fae6SDimitry Andric auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
397eb11fae6SDimitry Andric -> const LiveRange& {
398eb11fae6SDimitry Andric if (M.none())
399eb11fae6SDimitry Andric return I;
400eb11fae6SDimitry Andric for (const LiveInterval::SubRange &SR : I.subranges()) {
401eb11fae6SDimitry Andric if ((SR.LaneMask & M).any()) {
402eb11fae6SDimitry Andric assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
403eb11fae6SDimitry Andric return SR;
404eb11fae6SDimitry Andric }
405eb11fae6SDimitry Andric }
406eb11fae6SDimitry Andric llvm_unreachable("Subrange for mask not found");
407eb11fae6SDimitry Andric };
408eb11fae6SDimitry Andric
409eb11fae6SDimitry Andric const LiveInterval &LI = getInterval(Reg);
410eb11fae6SDimitry Andric const LiveRange &OldRange = getSubRange(LI, LaneMask);
411eb11fae6SDimitry Andric
41267c32a98SDimitry Andric // Extend intervals to reach all uses in WorkList.
41367c32a98SDimitry Andric while (!WorkList.empty()) {
41467c32a98SDimitry Andric SlotIndex Idx = WorkList.back().first;
41567c32a98SDimitry Andric VNInfo *VNI = WorkList.back().second;
41667c32a98SDimitry Andric WorkList.pop_back();
417eb11fae6SDimitry Andric const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
418eb11fae6SDimitry Andric SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
41967c32a98SDimitry Andric
42067c32a98SDimitry Andric // Extend the live range for VNI to be live at Idx.
421eb11fae6SDimitry Andric if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
42267c32a98SDimitry Andric assert(ExtVNI == VNI && "Unexpected existing value number");
42367c32a98SDimitry Andric (void)ExtVNI;
42467c32a98SDimitry Andric // Is this a PHIDef we haven't seen before?
42567c32a98SDimitry Andric if (!VNI->isPHIDef() || VNI->def != BlockStart ||
42667c32a98SDimitry Andric !UsedPHIs.insert(VNI).second)
42767c32a98SDimitry Andric continue;
42867c32a98SDimitry Andric // The PHI is live, make sure the predecessors are live-out.
42971d5a254SDimitry Andric for (const MachineBasicBlock *Pred : MBB->predecessors()) {
43067c32a98SDimitry Andric if (!LiveOut.insert(Pred).second)
43167c32a98SDimitry Andric continue;
432eb11fae6SDimitry Andric SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
43367c32a98SDimitry Andric // A predecessor is not required to have a live-out value for a PHI.
43467c32a98SDimitry Andric if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
43567c32a98SDimitry Andric WorkList.push_back(std::make_pair(Stop, PVNI));
43667c32a98SDimitry Andric }
43767c32a98SDimitry Andric continue;
43867c32a98SDimitry Andric }
43967c32a98SDimitry Andric
44067c32a98SDimitry Andric // VNI is live-in to MBB.
441eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
442eb11fae6SDimitry Andric Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
44367c32a98SDimitry Andric
44467c32a98SDimitry Andric // Make sure VNI is live-out from the predecessors.
44571d5a254SDimitry Andric for (const MachineBasicBlock *Pred : MBB->predecessors()) {
44667c32a98SDimitry Andric if (!LiveOut.insert(Pred).second)
44767c32a98SDimitry Andric continue;
448eb11fae6SDimitry Andric SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
449eb11fae6SDimitry Andric if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
450eb11fae6SDimitry Andric assert(OldVNI == VNI && "Wrong value out of predecessor");
451eb11fae6SDimitry Andric (void)OldVNI;
45267c32a98SDimitry Andric WorkList.push_back(std::make_pair(Stop, VNI));
453eb11fae6SDimitry Andric } else {
454eb11fae6SDimitry Andric #ifndef NDEBUG
455eb11fae6SDimitry Andric // There was no old VNI. Verify that Stop is jointly dominated
456eb11fae6SDimitry Andric // by <undef>s for this live range.
457eb11fae6SDimitry Andric assert(LaneMask.any() &&
458eb11fae6SDimitry Andric "Missing value out of predecessor for main range");
459eb11fae6SDimitry Andric SmallVector<SlotIndex,8> Undefs;
460eb11fae6SDimitry Andric LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
461eb11fae6SDimitry Andric assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
462eb11fae6SDimitry Andric "Missing value out of predecessor for subrange");
463eb11fae6SDimitry Andric #endif
464eb11fae6SDimitry Andric }
46567c32a98SDimitry Andric }
46667c32a98SDimitry Andric }
46767c32a98SDimitry Andric }
46867c32a98SDimitry Andric
shrinkToUses(LiveInterval * li,SmallVectorImpl<MachineInstr * > * dead)4696b943ff3SDimitry Andric bool LiveIntervals::shrinkToUses(LiveInterval *li,
4706b943ff3SDimitry Andric SmallVectorImpl<MachineInstr*> *dead) {
471eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
472e3b55780SDimitry Andric assert(li->reg().isVirtual() && "Can only shrink virtual registers");
473cf099d11SDimitry Andric
47467c32a98SDimitry Andric // Shrink subregister live ranges.
475dd58ef01SDimitry Andric bool NeedsCleanup = false;
47667c32a98SDimitry Andric for (LiveInterval::SubRange &S : li->subranges()) {
477b60736ecSDimitry Andric shrinkToUses(S, li->reg());
478dd58ef01SDimitry Andric if (S.empty())
479dd58ef01SDimitry Andric NeedsCleanup = true;
48067c32a98SDimitry Andric }
481dd58ef01SDimitry Andric if (NeedsCleanup)
482dd58ef01SDimitry Andric li->removeEmptySubRanges();
48367c32a98SDimitry Andric
48467c32a98SDimitry Andric // Find all the values used, including PHI kills.
48567c32a98SDimitry Andric ShrinkToUsesWorkList WorkList;
48630815c53SDimitry Andric
487b60736ecSDimitry Andric // Visit all instructions reading li->reg().
488b60736ecSDimitry Andric Register Reg = li->reg();
48971d5a254SDimitry Andric for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
490344a3780SDimitry Andric if (UseMI.isDebugInstr() || !UseMI.readsVirtualRegister(Reg))
491cf099d11SDimitry Andric continue;
49271d5a254SDimitry Andric SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
493f8af5cf6SDimitry Andric LiveQueryResult LRQ = li->Query(Idx);
49458b69754SDimitry Andric VNInfo *VNI = LRQ.valueIn();
4956b943ff3SDimitry Andric if (!VNI) {
4966b943ff3SDimitry Andric // This shouldn't happen: readsVirtualRegister returns true, but there is
4976b943ff3SDimitry Andric // no live value. It is likely caused by a target getting <undef> flags
4986b943ff3SDimitry Andric // wrong.
499eb11fae6SDimitry Andric LLVM_DEBUG(
500eb11fae6SDimitry Andric dbgs() << Idx << '\t' << UseMI
5016b943ff3SDimitry Andric << "Warning: Instr claims to read non-existent value in "
5026b943ff3SDimitry Andric << *li << '\n');
5036b943ff3SDimitry Andric continue;
5046b943ff3SDimitry Andric }
505cf099d11SDimitry Andric // Special case: An early-clobber tied operand reads and writes the
50658b69754SDimitry Andric // register one slot early.
50758b69754SDimitry Andric if (VNInfo *DefVNI = LRQ.valueDefined())
50858b69754SDimitry Andric Idx = DefVNI->def;
50958b69754SDimitry Andric
510cf099d11SDimitry Andric WorkList.push_back(std::make_pair(Idx, VNI));
511cf099d11SDimitry Andric }
512cf099d11SDimitry Andric
513f8af5cf6SDimitry Andric // Create new live ranges with only minimal live segments per def.
514f8af5cf6SDimitry Andric LiveRange NewLR;
515145449b1SDimitry Andric createSegmentsForValues(NewLR, li->vnis());
516eb11fae6SDimitry Andric extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
5175ca98fd9SDimitry Andric
5185ca98fd9SDimitry Andric // Move the trimmed segments back.
5195ca98fd9SDimitry Andric li->segments.swap(NewLR.segments);
52067c32a98SDimitry Andric
52167c32a98SDimitry Andric // Handle dead values.
52267c32a98SDimitry Andric bool CanSeparate = computeDeadValues(*li, dead);
523eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
5245ca98fd9SDimitry Andric return CanSeparate;
5255ca98fd9SDimitry Andric }
5265ca98fd9SDimitry Andric
computeDeadValues(LiveInterval & LI,SmallVectorImpl<MachineInstr * > * dead)52767c32a98SDimitry Andric bool LiveIntervals::computeDeadValues(LiveInterval &LI,
5285ca98fd9SDimitry Andric SmallVectorImpl<MachineInstr*> *dead) {
529dd58ef01SDimitry Andric bool MayHaveSplitComponents = false;
530706b4fc4SDimitry Andric
53171d5a254SDimitry Andric for (VNInfo *VNI : LI.valnos) {
532cf099d11SDimitry Andric if (VNI->isUnused())
533cf099d11SDimitry Andric continue;
5345a5ac124SDimitry Andric SlotIndex Def = VNI->def;
5355a5ac124SDimitry Andric LiveRange::iterator I = LI.FindSegmentContaining(Def);
53667c32a98SDimitry Andric assert(I != LI.end() && "Missing segment for VNI");
5375a5ac124SDimitry Andric
5385a5ac124SDimitry Andric // Is the register live before? Otherwise we may have to add a read-undef
5395a5ac124SDimitry Andric // flag for subregister defs.
540b60736ecSDimitry Andric Register VReg = LI.reg();
541dd58ef01SDimitry Andric if (MRI->shouldTrackSubRegLiveness(VReg)) {
5425a5ac124SDimitry Andric if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
5435a5ac124SDimitry Andric MachineInstr *MI = getInstructionFromIndex(Def);
544dd58ef01SDimitry Andric MI->setRegisterDefReadUndef(VReg);
5455a5ac124SDimitry Andric }
5465a5ac124SDimitry Andric }
5475a5ac124SDimitry Andric
5485a5ac124SDimitry Andric if (I->end != Def.getDeadSlot())
549cf099d11SDimitry Andric continue;
5506b943ff3SDimitry Andric if (VNI->isPHIDef()) {
551cf099d11SDimitry Andric // This is a dead PHI. Remove it.
55258b69754SDimitry Andric VNI->markUnused();
55367c32a98SDimitry Andric LI.removeSegment(I);
554eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
555cf099d11SDimitry Andric } else {
556cf099d11SDimitry Andric // This is a dead def. Make sure the instruction knows.
5575a5ac124SDimitry Andric MachineInstr *MI = getInstructionFromIndex(Def);
558cf099d11SDimitry Andric assert(MI && "No instruction defining live value");
559b60736ecSDimitry Andric MI->addRegisterDead(LI.reg(), TRI);
560706b4fc4SDimitry Andric
5616b943ff3SDimitry Andric if (dead && MI->allDefsAreDead()) {
562eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
5636b943ff3SDimitry Andric dead->push_back(MI);
5646b943ff3SDimitry Andric }
565cf099d11SDimitry Andric }
566e3b55780SDimitry Andric MayHaveSplitComponents = true;
567cf099d11SDimitry Andric }
568dd58ef01SDimitry Andric return MayHaveSplitComponents;
56967c32a98SDimitry Andric }
57067c32a98SDimitry Andric
shrinkToUses(LiveInterval::SubRange & SR,Register Reg)571b60736ecSDimitry Andric void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, Register Reg) {
572eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
573e3b55780SDimitry Andric assert(Reg.isVirtual() && "Can only shrink virtual registers");
57467c32a98SDimitry Andric // Find all the values used, including PHI kills.
57567c32a98SDimitry Andric ShrinkToUsesWorkList WorkList;
57667c32a98SDimitry Andric
57767c32a98SDimitry Andric // Visit all instructions reading Reg.
57867c32a98SDimitry Andric SlotIndex LastIdx;
579b915e9e0SDimitry Andric for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
580b915e9e0SDimitry Andric // Skip "undef" uses.
581b915e9e0SDimitry Andric if (!MO.readsReg())
58267c32a98SDimitry Andric continue;
58367c32a98SDimitry Andric // Maybe the operand is for a subregister we don't care about.
58467c32a98SDimitry Andric unsigned SubReg = MO.getSubReg();
58567c32a98SDimitry Andric if (SubReg != 0) {
586dd58ef01SDimitry Andric LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
587b915e9e0SDimitry Andric if ((LaneMask & SR.LaneMask).none())
58867c32a98SDimitry Andric continue;
58967c32a98SDimitry Andric }
59067c32a98SDimitry Andric // We only need to visit each instruction once.
591b915e9e0SDimitry Andric MachineInstr *UseMI = MO.getParent();
59201095a5dSDimitry Andric SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
59367c32a98SDimitry Andric if (Idx == LastIdx)
59467c32a98SDimitry Andric continue;
59567c32a98SDimitry Andric LastIdx = Idx;
59667c32a98SDimitry Andric
59767c32a98SDimitry Andric LiveQueryResult LRQ = SR.Query(Idx);
59867c32a98SDimitry Andric VNInfo *VNI = LRQ.valueIn();
59967c32a98SDimitry Andric // For Subranges it is possible that only undef values are left in that
60067c32a98SDimitry Andric // part of the subregister, so there is no real liverange at the use
60167c32a98SDimitry Andric if (!VNI)
60267c32a98SDimitry Andric continue;
60367c32a98SDimitry Andric
60467c32a98SDimitry Andric // Special case: An early-clobber tied operand reads and writes the
60567c32a98SDimitry Andric // register one slot early.
60667c32a98SDimitry Andric if (VNInfo *DefVNI = LRQ.valueDefined())
60767c32a98SDimitry Andric Idx = DefVNI->def;
60867c32a98SDimitry Andric
60967c32a98SDimitry Andric WorkList.push_back(std::make_pair(Idx, VNI));
61067c32a98SDimitry Andric }
61167c32a98SDimitry Andric
61267c32a98SDimitry Andric // Create a new live ranges with only minimal live segments per def.
61367c32a98SDimitry Andric LiveRange NewLR;
614145449b1SDimitry Andric createSegmentsForValues(NewLR, SR.vnis());
615eb11fae6SDimitry Andric extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
61667c32a98SDimitry Andric
61767c32a98SDimitry Andric // Move the trimmed ranges back.
61867c32a98SDimitry Andric SR.segments.swap(NewLR.segments);
61967c32a98SDimitry Andric
62067c32a98SDimitry Andric // Remove dead PHI value numbers
62171d5a254SDimitry Andric for (VNInfo *VNI : SR.valnos) {
62267c32a98SDimitry Andric if (VNI->isUnused())
62367c32a98SDimitry Andric continue;
62467c32a98SDimitry Andric const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
62567c32a98SDimitry Andric assert(Segment != nullptr && "Missing segment for VNI");
62667c32a98SDimitry Andric if (Segment->end != VNI->def.getDeadSlot())
62767c32a98SDimitry Andric continue;
62867c32a98SDimitry Andric if (VNI->isPHIDef()) {
62967c32a98SDimitry Andric // This is a dead PHI. Remove it.
630eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
631eb11fae6SDimitry Andric << " may separate interval\n");
63267c32a98SDimitry Andric VNI->markUnused();
63367c32a98SDimitry Andric SR.removeSegment(*Segment);
63467c32a98SDimitry Andric }
63567c32a98SDimitry Andric }
63667c32a98SDimitry Andric
637eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
638cf099d11SDimitry Andric }
639cf099d11SDimitry Andric
extendToIndices(LiveRange & LR,ArrayRef<SlotIndex> Indices,ArrayRef<SlotIndex> Undefs)640f8af5cf6SDimitry Andric void LiveIntervals::extendToIndices(LiveRange &LR,
641b915e9e0SDimitry Andric ArrayRef<SlotIndex> Indices,
642b915e9e0SDimitry Andric ArrayRef<SlotIndex> Undefs) {
643cfca06d7SDimitry Andric assert(LICalc && "LICalc not initialized.");
644cfca06d7SDimitry Andric LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
64571d5a254SDimitry Andric for (SlotIndex Idx : Indices)
646cfca06d7SDimitry Andric LICalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
647522600a2SDimitry Andric }
648522600a2SDimitry Andric
pruneValue(LiveRange & LR,SlotIndex Kill,SmallVectorImpl<SlotIndex> * EndPoints)64967c32a98SDimitry Andric void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
650522600a2SDimitry Andric SmallVectorImpl<SlotIndex> *EndPoints) {
65167c32a98SDimitry Andric LiveQueryResult LRQ = LR.Query(Kill);
65267c32a98SDimitry Andric VNInfo *VNI = LRQ.valueOutOrDead();
653522600a2SDimitry Andric if (!VNI)
654522600a2SDimitry Andric return;
655522600a2SDimitry Andric
656522600a2SDimitry Andric MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
65767c32a98SDimitry Andric SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
658522600a2SDimitry Andric
659522600a2SDimitry Andric // If VNI isn't live out from KillMBB, the value is trivially pruned.
660522600a2SDimitry Andric if (LRQ.endPoint() < MBBEnd) {
66167c32a98SDimitry Andric LR.removeSegment(Kill, LRQ.endPoint());
662522600a2SDimitry Andric if (EndPoints) EndPoints->push_back(LRQ.endPoint());
663522600a2SDimitry Andric return;
664522600a2SDimitry Andric }
665522600a2SDimitry Andric
666522600a2SDimitry Andric // VNI is live out of KillMBB.
66767c32a98SDimitry Andric LR.removeSegment(Kill, MBBEnd);
668522600a2SDimitry Andric if (EndPoints) EndPoints->push_back(MBBEnd);
669522600a2SDimitry Andric
670522600a2SDimitry Andric // Find all blocks that are reachable from KillMBB without leaving VNI's live
671522600a2SDimitry Andric // range. It is possible that KillMBB itself is reachable, so start a DFS
672522600a2SDimitry Andric // from each successor.
673ab44ce3dSDimitry Andric using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
674522600a2SDimitry Andric VisitedTy Visited;
67571d5a254SDimitry Andric for (MachineBasicBlock *Succ : KillMBB->successors()) {
676522600a2SDimitry Andric for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
67771d5a254SDimitry Andric I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
678522600a2SDimitry Andric I != E;) {
679522600a2SDimitry Andric MachineBasicBlock *MBB = *I;
680522600a2SDimitry Andric
681522600a2SDimitry Andric // Check if VNI is live in to MBB.
68267c32a98SDimitry Andric SlotIndex MBBStart, MBBEnd;
6835ca98fd9SDimitry Andric std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
68467c32a98SDimitry Andric LiveQueryResult LRQ = LR.Query(MBBStart);
685522600a2SDimitry Andric if (LRQ.valueIn() != VNI) {
686f8af5cf6SDimitry Andric // This block isn't part of the VNI segment. Prune the search.
687522600a2SDimitry Andric I.skipChildren();
688522600a2SDimitry Andric continue;
689522600a2SDimitry Andric }
690522600a2SDimitry Andric
691522600a2SDimitry Andric // Prune the search if VNI is killed in MBB.
692522600a2SDimitry Andric if (LRQ.endPoint() < MBBEnd) {
69367c32a98SDimitry Andric LR.removeSegment(MBBStart, LRQ.endPoint());
694522600a2SDimitry Andric if (EndPoints) EndPoints->push_back(LRQ.endPoint());
695522600a2SDimitry Andric I.skipChildren();
696522600a2SDimitry Andric continue;
697522600a2SDimitry Andric }
698522600a2SDimitry Andric
699522600a2SDimitry Andric // VNI is live through MBB.
70067c32a98SDimitry Andric LR.removeSegment(MBBStart, MBBEnd);
701522600a2SDimitry Andric if (EndPoints) EndPoints->push_back(MBBEnd);
702522600a2SDimitry Andric ++I;
703522600a2SDimitry Andric }
704522600a2SDimitry Andric }
705522600a2SDimitry Andric }
706cf099d11SDimitry Andric
707009b1c42SEd Schouten //===----------------------------------------------------------------------===//
708009b1c42SEd Schouten // Register allocator hooks.
709009b1c42SEd Schouten //
710009b1c42SEd Schouten
addKillFlags(const VirtRegMap * VRM)711522600a2SDimitry Andric void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
712522600a2SDimitry Andric // Keep track of regunit ranges.
71367c32a98SDimitry Andric SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
714522600a2SDimitry Andric
71558b69754SDimitry Andric for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
716b60736ecSDimitry Andric Register Reg = Register::index2VirtReg(i);
71758b69754SDimitry Andric if (MRI->reg_nodbg_empty(Reg))
718cf099d11SDimitry Andric continue;
71967c32a98SDimitry Andric const LiveInterval &LI = getInterval(Reg);
72067c32a98SDimitry Andric if (LI.empty())
721522600a2SDimitry Andric continue;
722522600a2SDimitry Andric
723344a3780SDimitry Andric // Target may have not allocated this yet.
724344a3780SDimitry Andric Register PhysReg = VRM->getPhys(Reg);
725344a3780SDimitry Andric if (!PhysReg)
726344a3780SDimitry Andric continue;
727344a3780SDimitry Andric
728522600a2SDimitry Andric // Find the regunit intervals for the assigned register. They may overlap
729522600a2SDimitry Andric // the virtual register live range, cancelling any kills.
730522600a2SDimitry Andric RU.clear();
7317fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
7327fa27ce4SDimitry Andric const LiveRange &RURange = getRegUnit(Unit);
73367c32a98SDimitry Andric if (RURange.empty())
734522600a2SDimitry Andric continue;
73567c32a98SDimitry Andric RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
73667c32a98SDimitry Andric }
737f8af5cf6SDimitry Andric // Every instruction that kills Reg corresponds to a segment range end
738f8af5cf6SDimitry Andric // point.
73967c32a98SDimitry Andric for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
740cf099d11SDimitry Andric ++RI) {
74163faed5bSDimitry Andric // A block index indicates an MBB edge.
74263faed5bSDimitry Andric if (RI->end.isBlock())
743cf099d11SDimitry Andric continue;
744cf099d11SDimitry Andric MachineInstr *MI = getInstructionFromIndex(RI->end);
745cf099d11SDimitry Andric if (!MI)
746cf099d11SDimitry Andric continue;
747522600a2SDimitry Andric
748f8af5cf6SDimitry Andric // Check if any of the regunits are live beyond the end of RI. That could
749522600a2SDimitry Andric // happen when a physreg is defined as a copy of a virtreg:
750522600a2SDimitry Andric //
751044eb2f6SDimitry Andric // %eax = COPY %5
752044eb2f6SDimitry Andric // FOO %5 <--- MI, cancel kill because %eax is live.
753044eb2f6SDimitry Andric // BAR killed %eax
754522600a2SDimitry Andric //
755044eb2f6SDimitry Andric // There should be no kill flag on FOO when %5 is rewritten as %eax.
75667c32a98SDimitry Andric for (auto &RUP : RU) {
75767c32a98SDimitry Andric const LiveRange &RURange = *RUP.first;
75867c32a98SDimitry Andric LiveRange::const_iterator &I = RUP.second;
75967c32a98SDimitry Andric if (I == RURange.end())
760522600a2SDimitry Andric continue;
76167c32a98SDimitry Andric I = RURange.advanceTo(I, RI->end);
76267c32a98SDimitry Andric if (I == RURange.end() || I->start >= RI->end)
763522600a2SDimitry Andric continue;
764522600a2SDimitry Andric // I is overlapping RI.
76567c32a98SDimitry Andric goto CancelKill;
766522600a2SDimitry Andric }
76767c32a98SDimitry Andric
7685a5ac124SDimitry Andric if (MRI->subRegLivenessEnabled()) {
76967c32a98SDimitry Andric // When reading a partial undefined value we must not add a kill flag.
77067c32a98SDimitry Andric // The regalloc might have used the undef lane for something else.
77167c32a98SDimitry Andric // Example:
772044eb2f6SDimitry Andric // %1 = ... ; R32: %1
773044eb2f6SDimitry Andric // %2:high16 = ... ; R64: %2
774044eb2f6SDimitry Andric // = read killed %2 ; R64: %2
775044eb2f6SDimitry Andric // = read %1 ; R32: %1
776044eb2f6SDimitry Andric // The <kill> flag is correct for %2, but the register allocator may
777044eb2f6SDimitry Andric // assign R0L to %1, and R0 to %2 because the low 32bits of R0
778044eb2f6SDimitry Andric // are actually never written by %2. After assignment the <kill>
77967c32a98SDimitry Andric // flag at the read instruction is invalid.
780dd58ef01SDimitry Andric LaneBitmask DefinedLanesMask;
781344a3780SDimitry Andric if (LI.hasSubRanges()) {
78267c32a98SDimitry Andric // Compute a mask of lanes that are defined.
783b915e9e0SDimitry Andric DefinedLanesMask = LaneBitmask::getNone();
784344a3780SDimitry Andric for (const LiveInterval::SubRange &SR : LI.subranges())
785344a3780SDimitry Andric for (const LiveRange::Segment &Segment : SR.segments) {
786344a3780SDimitry Andric if (Segment.start >= RI->end)
787344a3780SDimitry Andric break;
788344a3780SDimitry Andric if (Segment.end == RI->end) {
78967c32a98SDimitry Andric DefinedLanesMask |= SR.LaneMask;
790344a3780SDimitry Andric break;
791344a3780SDimitry Andric }
79267c32a98SDimitry Andric }
79367c32a98SDimitry Andric } else
794b915e9e0SDimitry Andric DefinedLanesMask = LaneBitmask::getAll();
79567c32a98SDimitry Andric
79667c32a98SDimitry Andric bool IsFullWrite = false;
79767c32a98SDimitry Andric for (const MachineOperand &MO : MI->operands()) {
79867c32a98SDimitry Andric if (!MO.isReg() || MO.getReg() != Reg)
79967c32a98SDimitry Andric continue;
80067c32a98SDimitry Andric if (MO.isUse()) {
80167c32a98SDimitry Andric // Reading any undefined lanes?
802344a3780SDimitry Andric unsigned SubReg = MO.getSubReg();
803344a3780SDimitry Andric LaneBitmask UseMask = SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
804344a3780SDimitry Andric : MRI->getMaxLaneMaskForVReg(Reg);
805b915e9e0SDimitry Andric if ((UseMask & ~DefinedLanesMask).any())
80667c32a98SDimitry Andric goto CancelKill;
80767c32a98SDimitry Andric } else if (MO.getSubReg() == 0) {
80867c32a98SDimitry Andric // Writing to the full register?
80967c32a98SDimitry Andric assert(MO.isDef());
81067c32a98SDimitry Andric IsFullWrite = true;
81167c32a98SDimitry Andric }
81267c32a98SDimitry Andric }
81367c32a98SDimitry Andric
81467c32a98SDimitry Andric // If an instruction writes to a subregister, a new segment starts in
81567c32a98SDimitry Andric // the LiveInterval. But as this is only overriding part of the register
81667c32a98SDimitry Andric // adding kill-flags is not correct here after registers have been
81767c32a98SDimitry Andric // assigned.
81867c32a98SDimitry Andric if (!IsFullWrite) {
81967c32a98SDimitry Andric // Next segment has to be adjacent in the subregister write case.
82067c32a98SDimitry Andric LiveRange::const_iterator N = std::next(RI);
82167c32a98SDimitry Andric if (N != LI.end() && N->start == RI->end)
82267c32a98SDimitry Andric goto CancelKill;
82367c32a98SDimitry Andric }
82467c32a98SDimitry Andric }
82567c32a98SDimitry Andric
8265ca98fd9SDimitry Andric MI->addRegisterKilled(Reg, nullptr);
82767c32a98SDimitry Andric continue;
82867c32a98SDimitry Andric CancelKill:
82967c32a98SDimitry Andric MI->clearRegisterKills(Reg, nullptr);
830cf099d11SDimitry Andric }
831cf099d11SDimitry Andric }
832cf099d11SDimitry Andric }
833cf099d11SDimitry Andric
83463faed5bSDimitry Andric MachineBasicBlock*
intervalIsInOneMBB(const LiveInterval & LI) const83563faed5bSDimitry Andric LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
8366f8fc217SDimitry Andric assert(!LI.empty() && "LiveInterval is empty.");
8376f8fc217SDimitry Andric
83863faed5bSDimitry Andric // A local live range must be fully contained inside the block, meaning it is
83963faed5bSDimitry Andric // defined and killed at instructions, not at block boundaries. It is not
840eb11fae6SDimitry Andric // live in or out of any block.
841009b1c42SEd Schouten //
84263faed5bSDimitry Andric // It is technically possible to have a PHI-defined live range identical to a
84363faed5bSDimitry Andric // single block, but we are going to return false in that case.
844009b1c42SEd Schouten
84563faed5bSDimitry Andric SlotIndex Start = LI.beginIndex();
84663faed5bSDimitry Andric if (Start.isBlock())
8475ca98fd9SDimitry Andric return nullptr;
84806f9d401SRoman Divacky
84963faed5bSDimitry Andric SlotIndex Stop = LI.endIndex();
85063faed5bSDimitry Andric if (Stop.isBlock())
8515ca98fd9SDimitry Andric return nullptr;
852009b1c42SEd Schouten
85363faed5bSDimitry Andric // getMBBFromIndex doesn't need to search the MBB table when both indexes
85463faed5bSDimitry Andric // belong to proper instructions.
85558b69754SDimitry Andric MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
85658b69754SDimitry Andric MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
8575ca98fd9SDimitry Andric return MBB1 == MBB2 ? MBB1 : nullptr;
858009b1c42SEd Schouten }
859009b1c42SEd Schouten
86058b69754SDimitry Andric bool
hasPHIKill(const LiveInterval & LI,const VNInfo * VNI) const86158b69754SDimitry Andric LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
86267c32a98SDimitry Andric for (const VNInfo *PHI : LI.valnos) {
86358b69754SDimitry Andric if (PHI->isUnused() || !PHI->isPHIDef())
86458b69754SDimitry Andric continue;
86558b69754SDimitry Andric const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
86658b69754SDimitry Andric // Conservatively return true instead of scanning huge predecessor lists.
86758b69754SDimitry Andric if (PHIMBB->pred_size() > 100)
86858b69754SDimitry Andric return true;
86971d5a254SDimitry Andric for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
87071d5a254SDimitry Andric if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
87158b69754SDimitry Andric return true;
87258b69754SDimitry Andric }
87358b69754SDimitry Andric return false;
87458b69754SDimitry Andric }
87558b69754SDimitry Andric
getSpillWeight(bool isDef,bool isUse,const MachineBlockFrequencyInfo * MBFI,const MachineInstr & MI)87601095a5dSDimitry Andric float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
8775ca98fd9SDimitry Andric const MachineBlockFrequencyInfo *MBFI,
87801095a5dSDimitry Andric const MachineInstr &MI) {
879044eb2f6SDimitry Andric return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
880044eb2f6SDimitry Andric }
881044eb2f6SDimitry Andric
getSpillWeight(bool isDef,bool isUse,const MachineBlockFrequencyInfo * MBFI,const MachineBasicBlock * MBB)882044eb2f6SDimitry Andric float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
883044eb2f6SDimitry Andric const MachineBlockFrequencyInfo *MBFI,
884044eb2f6SDimitry Andric const MachineBasicBlock *MBB) {
885b60736ecSDimitry Andric return (isDef + isUse) * MBFI->getBlockFreqRelativeToEntryBlock(MBB);
88667a71b31SRoman Divacky }
88767a71b31SRoman Divacky
888f8af5cf6SDimitry Andric LiveRange::Segment
addSegmentToEndOfBlock(Register Reg,MachineInstr & startInst)889b60736ecSDimitry Andric LiveIntervals::addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst) {
890b1c73532SDimitry Andric LiveInterval &Interval = getOrCreateEmptyInterval(Reg);
891009b1c42SEd Schouten VNInfo *VN = Interval.getNextValue(
89263faed5bSDimitry Andric SlotIndex(getInstructionIndex(startInst).getRegSlot()),
89363faed5bSDimitry Andric getVNInfoAllocator());
89401095a5dSDimitry Andric LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
89501095a5dSDimitry Andric getMBBEndIdx(startInst.getParent()), VN);
896f8af5cf6SDimitry Andric Interval.addSegment(S);
897009b1c42SEd Schouten
898f8af5cf6SDimitry Andric return S;
899009b1c42SEd Schouten }
90059850d08SRoman Divacky
90163faed5bSDimitry Andric //===----------------------------------------------------------------------===//
90263faed5bSDimitry Andric // Register mask functions
90363faed5bSDimitry Andric //===----------------------------------------------------------------------===//
904344a3780SDimitry Andric /// Check whether use of reg in MI is live-through. Live-through means that
905344a3780SDimitry Andric /// the value is alive on exit from Machine instruction. The example of such
906344a3780SDimitry Andric /// use is a deopt value in statepoint instruction.
hasLiveThroughUse(const MachineInstr * MI,Register Reg)907344a3780SDimitry Andric static bool hasLiveThroughUse(const MachineInstr *MI, Register Reg) {
908344a3780SDimitry Andric if (MI->getOpcode() != TargetOpcode::STATEPOINT)
909344a3780SDimitry Andric return false;
910344a3780SDimitry Andric StatepointOpers SO(MI);
911344a3780SDimitry Andric if (SO.getFlags() & (uint64_t)StatepointFlags::DeoptLiveIn)
912344a3780SDimitry Andric return false;
913344a3780SDimitry Andric for (unsigned Idx = SO.getNumDeoptArgsIdx(), E = SO.getNumGCPtrIdx(); Idx < E;
914344a3780SDimitry Andric ++Idx) {
915344a3780SDimitry Andric const MachineOperand &MO = MI->getOperand(Idx);
916344a3780SDimitry Andric if (MO.isReg() && MO.getReg() == Reg)
917344a3780SDimitry Andric return true;
918344a3780SDimitry Andric }
919344a3780SDimitry Andric return false;
920344a3780SDimitry Andric }
92163faed5bSDimitry Andric
checkRegMaskInterference(const LiveInterval & LI,BitVector & UsableRegs)922145449b1SDimitry Andric bool LiveIntervals::checkRegMaskInterference(const LiveInterval &LI,
92363faed5bSDimitry Andric BitVector &UsableRegs) {
92463faed5bSDimitry Andric if (LI.empty())
92563faed5bSDimitry Andric return false;
926145449b1SDimitry Andric LiveInterval::const_iterator LiveI = LI.begin(), LiveE = LI.end();
92763faed5bSDimitry Andric
92863faed5bSDimitry Andric // Use a smaller arrays for local live ranges.
92963faed5bSDimitry Andric ArrayRef<SlotIndex> Slots;
93063faed5bSDimitry Andric ArrayRef<const uint32_t*> Bits;
93163faed5bSDimitry Andric if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
93263faed5bSDimitry Andric Slots = getRegMaskSlotsInBlock(MBB->getNumber());
93363faed5bSDimitry Andric Bits = getRegMaskBitsInBlock(MBB->getNumber());
93463faed5bSDimitry Andric } else {
93563faed5bSDimitry Andric Slots = getRegMaskSlots();
93663faed5bSDimitry Andric Bits = getRegMaskBits();
93763faed5bSDimitry Andric }
93863faed5bSDimitry Andric
93963faed5bSDimitry Andric // We are going to enumerate all the register mask slots contained in LI.
94063faed5bSDimitry Andric // Start with a binary search of RegMaskSlots to find a starting point.
941e6d15924SDimitry Andric ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
94263faed5bSDimitry Andric ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
94363faed5bSDimitry Andric
94463faed5bSDimitry Andric // No slots in range, LI begins after the last call.
94563faed5bSDimitry Andric if (SlotI == SlotE)
94663faed5bSDimitry Andric return false;
94763faed5bSDimitry Andric
94863faed5bSDimitry Andric bool Found = false;
949344a3780SDimitry Andric // Utility to union regmasks.
950344a3780SDimitry Andric auto unionBitMask = [&](unsigned Idx) {
95163faed5bSDimitry Andric if (!Found) {
95263faed5bSDimitry Andric // This is the first overlap. Initialize UsableRegs to all ones.
95363faed5bSDimitry Andric UsableRegs.clear();
95458b69754SDimitry Andric UsableRegs.resize(TRI->getNumRegs(), true);
95563faed5bSDimitry Andric Found = true;
95663faed5bSDimitry Andric }
95763faed5bSDimitry Andric // Remove usable registers clobbered by this mask.
958344a3780SDimitry Andric UsableRegs.clearBitsNotInMask(Bits[Idx]);
959344a3780SDimitry Andric };
960344a3780SDimitry Andric while (true) {
961344a3780SDimitry Andric assert(*SlotI >= LiveI->start);
962344a3780SDimitry Andric // Loop over all slots overlapping this segment.
963344a3780SDimitry Andric while (*SlotI < LiveI->end) {
964344a3780SDimitry Andric // *SlotI overlaps LI. Collect mask bits.
965344a3780SDimitry Andric unionBitMask(SlotI - Slots.begin());
96663faed5bSDimitry Andric if (++SlotI == SlotE)
96763faed5bSDimitry Andric return Found;
96863faed5bSDimitry Andric }
969344a3780SDimitry Andric // If segment ends with live-through use we need to collect its regmask.
970344a3780SDimitry Andric if (*SlotI == LiveI->end)
971344a3780SDimitry Andric if (MachineInstr *MI = getInstructionFromIndex(*SlotI))
972344a3780SDimitry Andric if (hasLiveThroughUse(MI, LI.reg()))
973344a3780SDimitry Andric unionBitMask(SlotI++ - Slots.begin());
97463faed5bSDimitry Andric // *SlotI is beyond the current LI segment.
975344a3780SDimitry Andric // Special advance implementation to not miss next LiveI->end.
976344a3780SDimitry Andric if (++LiveI == LiveE || SlotI == SlotE || *SlotI > LI.endIndex())
97763faed5bSDimitry Andric return Found;
978344a3780SDimitry Andric while (LiveI->end < *SlotI)
979344a3780SDimitry Andric ++LiveI;
98063faed5bSDimitry Andric // Advance SlotI until it overlaps.
98163faed5bSDimitry Andric while (*SlotI < LiveI->start)
98263faed5bSDimitry Andric if (++SlotI == SlotE)
98363faed5bSDimitry Andric return Found;
98463faed5bSDimitry Andric }
98563faed5bSDimitry Andric }
98663faed5bSDimitry Andric
98763faed5bSDimitry Andric //===----------------------------------------------------------------------===//
98863faed5bSDimitry Andric // IntervalUpdate class.
98963faed5bSDimitry Andric //===----------------------------------------------------------------------===//
99063faed5bSDimitry Andric
99171d5a254SDimitry Andric /// Toolkit used by handleMove to trim or extend live intervals.
99263faed5bSDimitry Andric class LiveIntervals::HMEditor {
99363faed5bSDimitry Andric private:
99463faed5bSDimitry Andric LiveIntervals& LIS;
99563faed5bSDimitry Andric const MachineRegisterInfo& MRI;
99663faed5bSDimitry Andric const TargetRegisterInfo& TRI;
997522600a2SDimitry Andric SlotIndex OldIdx;
99863faed5bSDimitry Andric SlotIndex NewIdx;
999f8af5cf6SDimitry Andric SmallPtrSet<LiveRange*, 8> Updated;
1000522600a2SDimitry Andric bool UpdateFlags;
100163faed5bSDimitry Andric
100263faed5bSDimitry Andric public:
HMEditor(LiveIntervals & LIS,const MachineRegisterInfo & MRI,const TargetRegisterInfo & TRI,SlotIndex OldIdx,SlotIndex NewIdx,bool UpdateFlags)100363faed5bSDimitry Andric HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
1004522600a2SDimitry Andric const TargetRegisterInfo& TRI,
1005522600a2SDimitry Andric SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
1006522600a2SDimitry Andric : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
1007522600a2SDimitry Andric UpdateFlags(UpdateFlags) {}
100863faed5bSDimitry Andric
1009522600a2SDimitry Andric // FIXME: UpdateFlags is a workaround that creates live intervals for all
1010522600a2SDimitry Andric // physregs, even those that aren't needed for regalloc, in order to update
1011522600a2SDimitry Andric // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
1012522600a2SDimitry Andric // flags, and postRA passes will use a live register utility instead.
getRegUnitLI(unsigned Unit)1013f8af5cf6SDimitry Andric LiveRange *getRegUnitLI(unsigned Unit) {
1014edad5bcbSDimitry Andric if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
1015522600a2SDimitry Andric return &LIS.getRegUnit(Unit);
1016522600a2SDimitry Andric return LIS.getCachedRegUnit(Unit);
101763faed5bSDimitry Andric }
101863faed5bSDimitry Andric
1019522600a2SDimitry Andric /// Update all live ranges touched by MI, assuming a move from OldIdx to
1020522600a2SDimitry Andric /// NewIdx.
updateAllRanges(MachineInstr * MI)1021522600a2SDimitry Andric void updateAllRanges(MachineInstr *MI) {
1022eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
1023eb11fae6SDimitry Andric << *MI);
1024522600a2SDimitry Andric bool hasRegMask = false;
102585d8b2bbSDimitry Andric for (MachineOperand &MO : MI->operands()) {
102685d8b2bbSDimitry Andric if (MO.isRegMask())
1027522600a2SDimitry Andric hasRegMask = true;
102885d8b2bbSDimitry Andric if (!MO.isReg())
102963faed5bSDimitry Andric continue;
103001095a5dSDimitry Andric if (MO.isUse()) {
103101095a5dSDimitry Andric if (!MO.readsReg())
103201095a5dSDimitry Andric continue;
1033522600a2SDimitry Andric // Aggressively clear all kill flags.
1034522600a2SDimitry Andric // They are reinserted by VirtRegRewriter.
103585d8b2bbSDimitry Andric MO.setIsKill(false);
103601095a5dSDimitry Andric }
103763faed5bSDimitry Andric
10381d5ae102SDimitry Andric Register Reg = MO.getReg();
1039522600a2SDimitry Andric if (!Reg)
1040522600a2SDimitry Andric continue;
1041e3b55780SDimitry Andric if (Reg.isVirtual()) {
1042f8af5cf6SDimitry Andric LiveInterval &LI = LIS.getInterval(Reg);
104367c32a98SDimitry Andric if (LI.hasSubRanges()) {
104485d8b2bbSDimitry Andric unsigned SubReg = MO.getSubReg();
1045b915e9e0SDimitry Andric LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1046b915e9e0SDimitry Andric : MRI.getMaxLaneMaskForVReg(Reg);
104767c32a98SDimitry Andric for (LiveInterval::SubRange &S : LI.subranges()) {
1048b915e9e0SDimitry Andric if ((S.LaneMask & LaneMask).none())
104967c32a98SDimitry Andric continue;
105067c32a98SDimitry Andric updateRange(S, Reg, S.LaneMask);
105167c32a98SDimitry Andric }
105267c32a98SDimitry Andric }
1053b915e9e0SDimitry Andric updateRange(LI, Reg, LaneBitmask::getNone());
1054cfca06d7SDimitry Andric // If main range has a hole and we are moving a subrange use across
1055cfca06d7SDimitry Andric // the hole updateRange() cannot properly handle it since it only
1056cfca06d7SDimitry Andric // gets the LiveRange and not the whole LiveInterval. As a result
1057cfca06d7SDimitry Andric // we may end up with a main range not covering all subranges.
1058cfca06d7SDimitry Andric // This is extremely rare case, so let's check and reconstruct the
1059cfca06d7SDimitry Andric // main range.
10601f917f69SDimitry Andric if (LI.hasSubRanges()) {
10611f917f69SDimitry Andric unsigned SubReg = MO.getSubReg();
10621f917f69SDimitry Andric LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
10631f917f69SDimitry Andric : MRI.getMaxLaneMaskForVReg(Reg);
1064cfca06d7SDimitry Andric for (LiveInterval::SubRange &S : LI.subranges()) {
10651f917f69SDimitry Andric if ((S.LaneMask & LaneMask).none() || LI.covers(S))
1066cfca06d7SDimitry Andric continue;
1067cfca06d7SDimitry Andric LI.clear();
1068cfca06d7SDimitry Andric LIS.constructMainRangeFromSubranges(LI);
1069cfca06d7SDimitry Andric break;
1070cfca06d7SDimitry Andric }
10711f917f69SDimitry Andric }
1072cfca06d7SDimitry Andric
107363faed5bSDimitry Andric continue;
107463faed5bSDimitry Andric }
107563faed5bSDimitry Andric
1076522600a2SDimitry Andric // For physregs, only update the regunits that actually have a
1077522600a2SDimitry Andric // precomputed live range.
10787fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI.regunits(Reg.asMCReg()))
10797fa27ce4SDimitry Andric if (LiveRange *LR = getRegUnitLI(Unit))
10807fa27ce4SDimitry Andric updateRange(*LR, Unit, LaneBitmask::getNone());
108158b69754SDimitry Andric }
1082522600a2SDimitry Andric if (hasRegMask)
1083522600a2SDimitry Andric updateRegMaskSlots();
108458b69754SDimitry Andric }
108563faed5bSDimitry Andric
1086522600a2SDimitry Andric private:
1087522600a2SDimitry Andric /// Update a single live range, assuming an instruction has been moved from
1088522600a2SDimitry Andric /// OldIdx to NewIdx.
updateRange(LiveRange & LR,Register Reg,LaneBitmask LaneMask)1089b60736ecSDimitry Andric void updateRange(LiveRange &LR, Register Reg, LaneBitmask LaneMask) {
109067c32a98SDimitry Andric if (!Updated.insert(&LR).second)
1091522600a2SDimitry Andric return;
1092eb11fae6SDimitry Andric LLVM_DEBUG({
1093522600a2SDimitry Andric dbgs() << " ";
1094e3b55780SDimitry Andric if (Reg.isVirtual()) {
1095044eb2f6SDimitry Andric dbgs() << printReg(Reg);
1096b915e9e0SDimitry Andric if (LaneMask.any())
1097dd58ef01SDimitry Andric dbgs() << " L" << PrintLaneMask(LaneMask);
109867c32a98SDimitry Andric } else {
1099044eb2f6SDimitry Andric dbgs() << printRegUnit(Reg, &TRI);
110067c32a98SDimitry Andric }
1101f8af5cf6SDimitry Andric dbgs() << ":\t" << LR << '\n';
1102522600a2SDimitry Andric });
1103522600a2SDimitry Andric if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1104f8af5cf6SDimitry Andric handleMoveDown(LR);
1105522600a2SDimitry Andric else
110667c32a98SDimitry Andric handleMoveUp(LR, Reg, LaneMask);
1107eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n');
1108f8af5cf6SDimitry Andric LR.verify();
1109522600a2SDimitry Andric }
1110522600a2SDimitry Andric
1111f8af5cf6SDimitry Andric /// Update LR to reflect an instruction has been moved downwards from OldIdx
111201095a5dSDimitry Andric /// to NewIdx (OldIdx < NewIdx).
handleMoveDown(LiveRange & LR)1113f8af5cf6SDimitry Andric void handleMoveDown(LiveRange &LR) {
1114f8af5cf6SDimitry Andric LiveRange::iterator E = LR.end();
111501095a5dSDimitry Andric // Segment going into OldIdx.
111601095a5dSDimitry Andric LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
111701095a5dSDimitry Andric
111801095a5dSDimitry Andric // No value live before or after OldIdx? Nothing to do.
111901095a5dSDimitry Andric if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1120522600a2SDimitry Andric return;
1121522600a2SDimitry Andric
112201095a5dSDimitry Andric LiveRange::iterator OldIdxOut;
112301095a5dSDimitry Andric // Do we have a value live-in to OldIdx?
112401095a5dSDimitry Andric if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1125522600a2SDimitry Andric // If the live-in value already extends to NewIdx, there is nothing to do.
112601095a5dSDimitry Andric if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1127522600a2SDimitry Andric return;
1128522600a2SDimitry Andric // Aggressively remove all kill flags from the old kill point.
1129522600a2SDimitry Andric // Kill flags shouldn't be used while live intervals exist, they will be
1130522600a2SDimitry Andric // reinserted by VirtRegRewriter.
113101095a5dSDimitry Andric if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1132706b4fc4SDimitry Andric for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1133706b4fc4SDimitry Andric if (MOP.isReg() && MOP.isUse())
1134706b4fc4SDimitry Andric MOP.setIsKill(false);
113501095a5dSDimitry Andric
113601095a5dSDimitry Andric // Is there a def before NewIdx which is not OldIdx?
113701095a5dSDimitry Andric LiveRange::iterator Next = std::next(OldIdxIn);
113801095a5dSDimitry Andric if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
113901095a5dSDimitry Andric SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
114001095a5dSDimitry Andric // If we are here then OldIdx was just a use but not a def. We only have
114101095a5dSDimitry Andric // to ensure liveness extends to NewIdx.
114201095a5dSDimitry Andric LiveRange::iterator NewIdxIn =
114301095a5dSDimitry Andric LR.advanceTo(Next, NewIdx.getBaseIndex());
114401095a5dSDimitry Andric // Extend the segment before NewIdx if necessary.
114501095a5dSDimitry Andric if (NewIdxIn == E ||
114601095a5dSDimitry Andric !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
114701095a5dSDimitry Andric LiveRange::iterator Prev = std::prev(NewIdxIn);
114801095a5dSDimitry Andric Prev->end = NewIdx.getRegSlot();
114901095a5dSDimitry Andric }
1150b915e9e0SDimitry Andric // Extend OldIdxIn.
1151b915e9e0SDimitry Andric OldIdxIn->end = Next->start;
1152522600a2SDimitry Andric return;
1153522600a2SDimitry Andric }
1154522600a2SDimitry Andric
115501095a5dSDimitry Andric // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
115601095a5dSDimitry Andric // invalid by overlapping ranges.
115701095a5dSDimitry Andric bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
115801095a5dSDimitry Andric OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
115901095a5dSDimitry Andric // If this was not a kill, then there was no def and we're done.
116001095a5dSDimitry Andric if (!isKill)
1161522600a2SDimitry Andric return;
116201095a5dSDimitry Andric
116301095a5dSDimitry Andric // Did we have a Def at OldIdx?
116401095a5dSDimitry Andric OldIdxOut = Next;
116501095a5dSDimitry Andric if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
116601095a5dSDimitry Andric return;
116701095a5dSDimitry Andric } else {
116801095a5dSDimitry Andric OldIdxOut = OldIdxIn;
116901095a5dSDimitry Andric }
117001095a5dSDimitry Andric
117101095a5dSDimitry Andric // If we are here then there is a Definition at OldIdx. OldIdxOut points
117201095a5dSDimitry Andric // to the segment starting there.
117301095a5dSDimitry Andric assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
117401095a5dSDimitry Andric "No def?");
117501095a5dSDimitry Andric VNInfo *OldIdxVNI = OldIdxOut->valno;
117601095a5dSDimitry Andric assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
117701095a5dSDimitry Andric
117801095a5dSDimitry Andric // If the defined value extends beyond NewIdx, just move the beginning
117901095a5dSDimitry Andric // of the segment to NewIdx.
118001095a5dSDimitry Andric SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
118101095a5dSDimitry Andric if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
118201095a5dSDimitry Andric OldIdxVNI->def = NewIdxDef;
118301095a5dSDimitry Andric OldIdxOut->start = OldIdxVNI->def;
1184522600a2SDimitry Andric return;
1185522600a2SDimitry Andric }
118601095a5dSDimitry Andric
118701095a5dSDimitry Andric // If we are here then we have a Definition at OldIdx which ends before
118801095a5dSDimitry Andric // NewIdx.
118901095a5dSDimitry Andric
119001095a5dSDimitry Andric // Is there an existing Def at NewIdx?
119101095a5dSDimitry Andric LiveRange::iterator AfterNewIdx
119201095a5dSDimitry Andric = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
119301095a5dSDimitry Andric bool OldIdxDefIsDead = OldIdxOut->end.isDead();
119401095a5dSDimitry Andric if (!OldIdxDefIsDead &&
119501095a5dSDimitry Andric SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
119601095a5dSDimitry Andric // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
119701095a5dSDimitry Andric VNInfo *DefVNI;
119801095a5dSDimitry Andric if (OldIdxOut != LR.begin() &&
119901095a5dSDimitry Andric !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
120001095a5dSDimitry Andric OldIdxOut->start)) {
120101095a5dSDimitry Andric // There is no gap between OldIdxOut and its predecessor anymore,
120201095a5dSDimitry Andric // merge them.
120301095a5dSDimitry Andric LiveRange::iterator IPrev = std::prev(OldIdxOut);
120401095a5dSDimitry Andric DefVNI = OldIdxVNI;
120501095a5dSDimitry Andric IPrev->end = OldIdxOut->end;
120601095a5dSDimitry Andric } else {
120701095a5dSDimitry Andric // The value is live in to OldIdx
120801095a5dSDimitry Andric LiveRange::iterator INext = std::next(OldIdxOut);
120901095a5dSDimitry Andric assert(INext != E && "Must have following segment");
121001095a5dSDimitry Andric // We merge OldIdxOut and its successor. As we're dealing with subreg
121101095a5dSDimitry Andric // reordering, there is always a successor to OldIdxOut in the same BB
121201095a5dSDimitry Andric // We don't need INext->valno anymore and will reuse for the new segment
121301095a5dSDimitry Andric // we create later.
121401095a5dSDimitry Andric DefVNI = OldIdxVNI;
121501095a5dSDimitry Andric INext->start = OldIdxOut->end;
121601095a5dSDimitry Andric INext->valno->def = INext->start;
121701095a5dSDimitry Andric }
121801095a5dSDimitry Andric // If NewIdx is behind the last segment, extend that and append a new one.
121901095a5dSDimitry Andric if (AfterNewIdx == E) {
122001095a5dSDimitry Andric // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
122101095a5dSDimitry Andric // one position.
122201095a5dSDimitry Andric // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
122301095a5dSDimitry Andric // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
122401095a5dSDimitry Andric std::copy(std::next(OldIdxOut), E, OldIdxOut);
122501095a5dSDimitry Andric // The last segment is undefined now, reuse it for a dead def.
122601095a5dSDimitry Andric LiveRange::iterator NewSegment = std::prev(E);
122701095a5dSDimitry Andric *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
122801095a5dSDimitry Andric DefVNI);
122901095a5dSDimitry Andric DefVNI->def = NewIdxDef;
123001095a5dSDimitry Andric
123101095a5dSDimitry Andric LiveRange::iterator Prev = std::prev(NewSegment);
123201095a5dSDimitry Andric Prev->end = NewIdxDef;
123301095a5dSDimitry Andric } else {
123401095a5dSDimitry Andric // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
123501095a5dSDimitry Andric // one position.
123601095a5dSDimitry Andric // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
123701095a5dSDimitry Andric // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
123801095a5dSDimitry Andric std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
123901095a5dSDimitry Andric LiveRange::iterator Prev = std::prev(AfterNewIdx);
124001095a5dSDimitry Andric // We have two cases:
124101095a5dSDimitry Andric if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
124201095a5dSDimitry Andric // Case 1: NewIdx is inside a liverange. Split this liverange at
124301095a5dSDimitry Andric // NewIdxDef into the segment "Prev" followed by "NewSegment".
124401095a5dSDimitry Andric LiveRange::iterator NewSegment = AfterNewIdx;
124501095a5dSDimitry Andric *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
124601095a5dSDimitry Andric Prev->valno->def = NewIdxDef;
124701095a5dSDimitry Andric
124801095a5dSDimitry Andric *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
124901095a5dSDimitry Andric DefVNI->def = Prev->start;
125001095a5dSDimitry Andric } else {
125101095a5dSDimitry Andric // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
125201095a5dSDimitry Andric // turn Prev into a segment from NewIdx to AfterNewIdx->start.
125301095a5dSDimitry Andric *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
125401095a5dSDimitry Andric DefVNI->def = NewIdxDef;
125501095a5dSDimitry Andric assert(DefVNI != AfterNewIdx->valno);
125601095a5dSDimitry Andric }
125701095a5dSDimitry Andric }
1258522600a2SDimitry Andric return;
1259522600a2SDimitry Andric }
126001095a5dSDimitry Andric
126101095a5dSDimitry Andric if (AfterNewIdx != E &&
126201095a5dSDimitry Andric SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
126301095a5dSDimitry Andric // There is an existing def at NewIdx. The def at OldIdx is coalesced into
126401095a5dSDimitry Andric // that value.
126501095a5dSDimitry Andric assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
126601095a5dSDimitry Andric LR.removeValNo(OldIdxVNI);
126701095a5dSDimitry Andric } else {
126801095a5dSDimitry Andric // There was no existing def at NewIdx. We need to create a dead def
126901095a5dSDimitry Andric // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
127001095a5dSDimitry Andric // a new segment at the place where we want to construct the dead def.
127101095a5dSDimitry Andric // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
127201095a5dSDimitry Andric // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
127301095a5dSDimitry Andric assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
127401095a5dSDimitry Andric std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
127501095a5dSDimitry Andric // We can reuse OldIdxVNI now.
127601095a5dSDimitry Andric LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
127701095a5dSDimitry Andric VNInfo *NewSegmentVNI = OldIdxVNI;
127801095a5dSDimitry Andric NewSegmentVNI->def = NewIdxDef;
127901095a5dSDimitry Andric *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
128001095a5dSDimitry Andric NewSegmentVNI);
128101095a5dSDimitry Andric }
1282522600a2SDimitry Andric }
1283522600a2SDimitry Andric
1284f8af5cf6SDimitry Andric /// Update LR to reflect an instruction has been moved upwards from OldIdx
128501095a5dSDimitry Andric /// to NewIdx (NewIdx < OldIdx).
handleMoveUp(LiveRange & LR,Register Reg,LaneBitmask LaneMask)1286b60736ecSDimitry Andric void handleMoveUp(LiveRange &LR, Register Reg, LaneBitmask LaneMask) {
1287f8af5cf6SDimitry Andric LiveRange::iterator E = LR.end();
128801095a5dSDimitry Andric // Segment going into OldIdx.
128901095a5dSDimitry Andric LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
129001095a5dSDimitry Andric
129101095a5dSDimitry Andric // No value live before or after OldIdx? Nothing to do.
129201095a5dSDimitry Andric if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1293522600a2SDimitry Andric return;
1294522600a2SDimitry Andric
129501095a5dSDimitry Andric LiveRange::iterator OldIdxOut;
129601095a5dSDimitry Andric // Do we have a value live-in to OldIdx?
129701095a5dSDimitry Andric if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
129801095a5dSDimitry Andric // If the live-in value isn't killed here, then we have no Def at
129901095a5dSDimitry Andric // OldIdx, moreover the value must be live at NewIdx so there is nothing
130001095a5dSDimitry Andric // to do.
130101095a5dSDimitry Andric bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
130201095a5dSDimitry Andric if (!isKill)
1303522600a2SDimitry Andric return;
130401095a5dSDimitry Andric
130501095a5dSDimitry Andric // At this point we have to move OldIdxIn->end back to the nearest
130601095a5dSDimitry Andric // previous use or (dead-)def but no further than NewIdx.
130701095a5dSDimitry Andric SlotIndex DefBeforeOldIdx
130801095a5dSDimitry Andric = std::max(OldIdxIn->start.getDeadSlot(),
130901095a5dSDimitry Andric NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
131001095a5dSDimitry Andric OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
131101095a5dSDimitry Andric
131201095a5dSDimitry Andric // Did we have a Def at OldIdx? If not we are done now.
131301095a5dSDimitry Andric OldIdxOut = std::next(OldIdxIn);
131401095a5dSDimitry Andric if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1315522600a2SDimitry Andric return;
131601095a5dSDimitry Andric } else {
131701095a5dSDimitry Andric OldIdxOut = OldIdxIn;
131801095a5dSDimitry Andric OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
131963faed5bSDimitry Andric }
132063faed5bSDimitry Andric
132101095a5dSDimitry Andric // If we are here then there is a Definition at OldIdx. OldIdxOut points
132201095a5dSDimitry Andric // to the segment starting there.
132301095a5dSDimitry Andric assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
132401095a5dSDimitry Andric "No def?");
132501095a5dSDimitry Andric VNInfo *OldIdxVNI = OldIdxOut->valno;
132601095a5dSDimitry Andric assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
132701095a5dSDimitry Andric bool OldIdxDefIsDead = OldIdxOut->end.isDead();
132863faed5bSDimitry Andric
132901095a5dSDimitry Andric // Is there an existing def at NewIdx?
133001095a5dSDimitry Andric SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
133101095a5dSDimitry Andric LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
133201095a5dSDimitry Andric if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
133301095a5dSDimitry Andric assert(NewIdxOut->valno != OldIdxVNI &&
133401095a5dSDimitry Andric "Same value defined more than once?");
133501095a5dSDimitry Andric // If OldIdx was a dead def remove it.
133601095a5dSDimitry Andric if (!OldIdxDefIsDead) {
133701095a5dSDimitry Andric // Remove segment starting at NewIdx and move begin of OldIdxOut to
133801095a5dSDimitry Andric // NewIdx so it can take its place.
133901095a5dSDimitry Andric OldIdxVNI->def = NewIdxDef;
134001095a5dSDimitry Andric OldIdxOut->start = NewIdxDef;
134101095a5dSDimitry Andric LR.removeValNo(NewIdxOut->valno);
134201095a5dSDimitry Andric } else {
134301095a5dSDimitry Andric // Simply remove the dead def at OldIdx.
134401095a5dSDimitry Andric LR.removeValNo(OldIdxVNI);
1345522600a2SDimitry Andric }
134601095a5dSDimitry Andric } else {
134701095a5dSDimitry Andric // Previously nothing was live after NewIdx, so all we have to do now is
134801095a5dSDimitry Andric // move the begin of OldIdxOut to NewIdx.
134901095a5dSDimitry Andric if (!OldIdxDefIsDead) {
135001095a5dSDimitry Andric // Do we have any intermediate Defs between OldIdx and NewIdx?
135101095a5dSDimitry Andric if (OldIdxIn != E &&
135201095a5dSDimitry Andric SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
135301095a5dSDimitry Andric // OldIdx is not a dead def and NewIdx is before predecessor start.
135401095a5dSDimitry Andric LiveRange::iterator NewIdxIn = NewIdxOut;
135501095a5dSDimitry Andric assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
135601095a5dSDimitry Andric const SlotIndex SplitPos = NewIdxDef;
135771d5a254SDimitry Andric OldIdxVNI = OldIdxIn->valno;
135863faed5bSDimitry Andric
13591d5ae102SDimitry Andric SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
13601d5ae102SDimitry Andric LiveRange::iterator Prev = std::prev(OldIdxIn);
13611d5ae102SDimitry Andric if (OldIdxIn != LR.begin() &&
13621d5ae102SDimitry Andric SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
13631d5ae102SDimitry Andric // If the segment before OldIdx read a value defined earlier than
13641d5ae102SDimitry Andric // NewIdx, the moved instruction also reads and forwards that
13651d5ae102SDimitry Andric // value. Extend the lifetime of the new def point.
13661d5ae102SDimitry Andric
13671d5ae102SDimitry Andric // Extend to where the previous range started, unless there is
13681d5ae102SDimitry Andric // another redef first.
13691d5ae102SDimitry Andric NewDefEndPoint = std::min(OldIdxIn->start,
13701d5ae102SDimitry Andric std::next(NewIdxOut)->start);
13711d5ae102SDimitry Andric }
13721d5ae102SDimitry Andric
137301095a5dSDimitry Andric // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
137471d5a254SDimitry Andric OldIdxOut->valno->def = OldIdxIn->start;
137501095a5dSDimitry Andric *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
137671d5a254SDimitry Andric OldIdxOut->valno);
137701095a5dSDimitry Andric // OldIdxIn and OldIdxVNI are now undef and can be overridden.
137801095a5dSDimitry Andric // We Slide [NewIdxIn, OldIdxIn) down one position.
137901095a5dSDimitry Andric // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
138001095a5dSDimitry Andric // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
138101095a5dSDimitry Andric std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
138201095a5dSDimitry Andric // NewIdxIn is now considered undef so we can reuse it for the moved
138301095a5dSDimitry Andric // value.
138401095a5dSDimitry Andric LiveRange::iterator NewSegment = NewIdxIn;
138501095a5dSDimitry Andric LiveRange::iterator Next = std::next(NewSegment);
138601095a5dSDimitry Andric if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
138701095a5dSDimitry Andric // There is no gap between NewSegment and its predecessor.
138801095a5dSDimitry Andric *NewSegment = LiveRange::Segment(Next->start, SplitPos,
138901095a5dSDimitry Andric Next->valno);
13901d5ae102SDimitry Andric
13911d5ae102SDimitry Andric *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
139201095a5dSDimitry Andric Next->valno->def = SplitPos;
139301095a5dSDimitry Andric } else {
139401095a5dSDimitry Andric // There is a gap between NewSegment and its predecessor
139501095a5dSDimitry Andric // Value becomes live in.
139601095a5dSDimitry Andric *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
139701095a5dSDimitry Andric NewSegment->valno->def = SplitPos;
139801095a5dSDimitry Andric }
139901095a5dSDimitry Andric } else {
1400522600a2SDimitry Andric // Leave the end point of a live def.
140101095a5dSDimitry Andric OldIdxOut->start = NewIdxDef;
140201095a5dSDimitry Andric OldIdxVNI->def = NewIdxDef;
140301095a5dSDimitry Andric if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1404cfca06d7SDimitry Andric OldIdxIn->end = NewIdxDef;
140563faed5bSDimitry Andric }
1406eb11fae6SDimitry Andric } else if (OldIdxIn != E
1407eb11fae6SDimitry Andric && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1408eb11fae6SDimitry Andric && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1409eb11fae6SDimitry Andric // OldIdxVNI is a dead def that has been moved into the middle of
1410eb11fae6SDimitry Andric // another value in LR. That can happen when LR is a whole register,
1411eb11fae6SDimitry Andric // but the dead def is a write to a subreg that is dead at NewIdx.
1412eb11fae6SDimitry Andric // The dead def may have been moved across other values
1413eb11fae6SDimitry Andric // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1414eb11fae6SDimitry Andric // down one position.
1415eb11fae6SDimitry Andric // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1416eb11fae6SDimitry Andric // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1417eb11fae6SDimitry Andric std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1418eb11fae6SDimitry Andric // Modify the segment at NewIdxOut and the following segment to meet at
1419eb11fae6SDimitry Andric // the point of the dead def, with the following segment getting
1420eb11fae6SDimitry Andric // OldIdxVNI as its value number.
1421eb11fae6SDimitry Andric *NewIdxOut = LiveRange::Segment(
1422eb11fae6SDimitry Andric NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1423eb11fae6SDimitry Andric *(NewIdxOut + 1) = LiveRange::Segment(
1424eb11fae6SDimitry Andric NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1425eb11fae6SDimitry Andric OldIdxVNI->def = NewIdxDef;
1426eb11fae6SDimitry Andric // Modify subsequent segments to be defined by the moved def OldIdxVNI.
14274b4fe385SDimitry Andric for (auto *Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
1428eb11fae6SDimitry Andric Idx->valno = OldIdxVNI;
1429eb11fae6SDimitry Andric // Aggressively remove all dead flags from the former dead definition.
1430eb11fae6SDimitry Andric // Kill/dead flags shouldn't be used while live intervals exist; they
1431eb11fae6SDimitry Andric // will be reinserted by VirtRegRewriter.
1432eb11fae6SDimitry Andric if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1433eb11fae6SDimitry Andric for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1434eb11fae6SDimitry Andric if (MO->isReg() && !MO->isUse())
1435eb11fae6SDimitry Andric MO->setIsDead(false);
143601095a5dSDimitry Andric } else {
143701095a5dSDimitry Andric // OldIdxVNI is a dead def. It may have been moved across other values
143801095a5dSDimitry Andric // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
143901095a5dSDimitry Andric // down one position.
144001095a5dSDimitry Andric // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
144101095a5dSDimitry Andric // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
144201095a5dSDimitry Andric std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
144301095a5dSDimitry Andric // OldIdxVNI can be reused now to build a new dead def segment.
144401095a5dSDimitry Andric LiveRange::iterator NewSegment = NewIdxOut;
144501095a5dSDimitry Andric VNInfo *NewSegmentVNI = OldIdxVNI;
144601095a5dSDimitry Andric *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
144701095a5dSDimitry Andric NewSegmentVNI);
144801095a5dSDimitry Andric NewSegmentVNI->def = NewIdxDef;
144901095a5dSDimitry Andric }
145001095a5dSDimitry Andric }
145163faed5bSDimitry Andric }
145263faed5bSDimitry Andric
updateRegMaskSlots()1453522600a2SDimitry Andric void updateRegMaskSlots() {
145463faed5bSDimitry Andric SmallVectorImpl<SlotIndex>::iterator RI =
1455e6d15924SDimitry Andric llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
1456522600a2SDimitry Andric assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1457522600a2SDimitry Andric "No RegMask at OldIdx.");
1458522600a2SDimitry Andric *RI = NewIdx.getRegSlot();
1459522600a2SDimitry Andric assert((RI == LIS.RegMaskSlots.begin() ||
14605ca98fd9SDimitry Andric SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1461522600a2SDimitry Andric "Cannot move regmask instruction above another call");
14625ca98fd9SDimitry Andric assert((std::next(RI) == LIS.RegMaskSlots.end() ||
14635ca98fd9SDimitry Andric SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1464522600a2SDimitry Andric "Cannot move regmask instruction below another call");
146563faed5bSDimitry Andric }
146663faed5bSDimitry Andric
146763faed5bSDimitry Andric // Return the last use of reg between NewIdx and OldIdx.
findLastUseBefore(SlotIndex Before,Register Reg,LaneBitmask LaneMask)1468b60736ecSDimitry Andric SlotIndex findLastUseBefore(SlotIndex Before, Register Reg,
146901095a5dSDimitry Andric LaneBitmask LaneMask) {
1470e3b55780SDimitry Andric if (Reg.isVirtual()) {
147101095a5dSDimitry Andric SlotIndex LastUse = Before;
147267c32a98SDimitry Andric for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
147301095a5dSDimitry Andric if (MO.isUndef())
147401095a5dSDimitry Andric continue;
147567c32a98SDimitry Andric unsigned SubReg = MO.getSubReg();
1476b915e9e0SDimitry Andric if (SubReg != 0 && LaneMask.any()
1477b915e9e0SDimitry Andric && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
147867c32a98SDimitry Andric continue;
147967c32a98SDimitry Andric
148001095a5dSDimitry Andric const MachineInstr &MI = *MO.getParent();
148163faed5bSDimitry Andric SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
148263faed5bSDimitry Andric if (InstSlot > LastUse && InstSlot < OldIdx)
148301095a5dSDimitry Andric LastUse = InstSlot.getRegSlot();
148463faed5bSDimitry Andric }
148563faed5bSDimitry Andric return LastUse;
148663faed5bSDimitry Andric }
14874a16efa3SDimitry Andric
14884a16efa3SDimitry Andric // This is a regunit interval, so scanning the use list could be very
14894a16efa3SDimitry Andric // expensive. Scan upwards from OldIdx instead.
149001095a5dSDimitry Andric assert(Before < OldIdx && "Expected upwards move");
14914a16efa3SDimitry Andric SlotIndexes *Indexes = LIS.getSlotIndexes();
149201095a5dSDimitry Andric MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
14934a16efa3SDimitry Andric
14944a16efa3SDimitry Andric // OldIdx may not correspond to an instruction any longer, so set MII to
14954a16efa3SDimitry Andric // point to the next instruction after OldIdx, or MBB->end().
14964a16efa3SDimitry Andric MachineBasicBlock::iterator MII = MBB->end();
14974a16efa3SDimitry Andric if (MachineInstr *MI = Indexes->getInstructionFromIndex(
14984a16efa3SDimitry Andric Indexes->getNextNonNullIndex(OldIdx)))
14994a16efa3SDimitry Andric if (MI->getParent() == MBB)
15004a16efa3SDimitry Andric MII = MI;
15014a16efa3SDimitry Andric
15024a16efa3SDimitry Andric MachineBasicBlock::iterator Begin = MBB->begin();
15034a16efa3SDimitry Andric while (MII != Begin) {
1504344a3780SDimitry Andric if ((--MII)->isDebugOrPseudoInstr())
15054a16efa3SDimitry Andric continue;
150601095a5dSDimitry Andric SlotIndex Idx = Indexes->getInstructionIndex(*MII);
15074a16efa3SDimitry Andric
150801095a5dSDimitry Andric // Stop searching when Before is reached.
150901095a5dSDimitry Andric if (!SlotIndex::isEarlierInstr(Before, Idx))
151001095a5dSDimitry Andric return Before;
15114a16efa3SDimitry Andric
15124a16efa3SDimitry Andric // Check if MII uses Reg.
151301095a5dSDimitry Andric for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1514e3b55780SDimitry Andric if (MO->isReg() && !MO->isUndef() && MO->getReg().isPhysical() &&
15154a16efa3SDimitry Andric TRI.hasRegUnit(MO->getReg(), Reg))
151601095a5dSDimitry Andric return Idx.getRegSlot();
15174a16efa3SDimitry Andric }
151801095a5dSDimitry Andric // Didn't reach Before. It must be the first instruction in the block.
151901095a5dSDimitry Andric return Before;
15204a16efa3SDimitry Andric }
152163faed5bSDimitry Andric };
152263faed5bSDimitry Andric
handleMove(MachineInstr & MI,bool UpdateFlags)152301095a5dSDimitry Andric void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
15241d5ae102SDimitry Andric // It is fine to move a bundle as a whole, but not an individual instruction
15251d5ae102SDimitry Andric // inside it.
15261d5ae102SDimitry Andric assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
15271d5ae102SDimitry Andric "Cannot move instruction in bundle");
152858b69754SDimitry Andric SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
152958b69754SDimitry Andric Indexes->removeMachineInstrFromMaps(MI);
1530522600a2SDimitry Andric SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
153101095a5dSDimitry Andric assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
153201095a5dSDimitry Andric OldIndex < getMBBEndIdx(MI.getParent()) &&
153363faed5bSDimitry Andric "Cannot handle moves across basic block boundaries.");
153463faed5bSDimitry Andric
1535522600a2SDimitry Andric HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
153601095a5dSDimitry Andric HME.updateAllRanges(&MI);
153763faed5bSDimitry Andric }
153863faed5bSDimitry Andric
handleMoveIntoNewBundle(MachineInstr & BundleStart,bool UpdateFlags)1539cfca06d7SDimitry Andric void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart,
1540522600a2SDimitry Andric bool UpdateFlags) {
1541cfca06d7SDimitry Andric assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
1542cfca06d7SDimitry Andric "Bundle start is not a bundle");
1543cfca06d7SDimitry Andric SmallVector<SlotIndex, 16> ToProcess;
1544cfca06d7SDimitry Andric const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart);
1545cfca06d7SDimitry Andric auto BundleEnd = getBundleEnd(BundleStart.getIterator());
1546cfca06d7SDimitry Andric
1547cfca06d7SDimitry Andric auto I = BundleStart.getIterator();
1548cfca06d7SDimitry Andric I++;
1549cfca06d7SDimitry Andric while (I != BundleEnd) {
1550cfca06d7SDimitry Andric if (!Indexes->hasIndex(*I))
1551cfca06d7SDimitry Andric continue;
1552cfca06d7SDimitry Andric SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true);
1553cfca06d7SDimitry Andric ToProcess.push_back(OldIndex);
1554cfca06d7SDimitry Andric Indexes->removeMachineInstrFromMaps(*I, true);
1555cfca06d7SDimitry Andric I++;
1556cfca06d7SDimitry Andric }
1557cfca06d7SDimitry Andric for (SlotIndex OldIndex : ToProcess) {
1558522600a2SDimitry Andric HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1559cfca06d7SDimitry Andric HME.updateAllRanges(&BundleStart);
1560cfca06d7SDimitry Andric }
1561cfca06d7SDimitry Andric
1562cfca06d7SDimitry Andric // Fix up dead defs
1563cfca06d7SDimitry Andric const SlotIndex Index = getInstructionIndex(BundleStart);
1564ac9a064cSDimitry Andric for (MachineOperand &MO : BundleStart.operands()) {
1565cfca06d7SDimitry Andric if (!MO.isReg())
1566cfca06d7SDimitry Andric continue;
1567cfca06d7SDimitry Andric Register Reg = MO.getReg();
1568cfca06d7SDimitry Andric if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
1569cfca06d7SDimitry Andric LiveInterval &LI = getInterval(Reg);
1570cfca06d7SDimitry Andric LiveQueryResult LRQ = LI.Query(Index);
1571cfca06d7SDimitry Andric if (LRQ.isDeadDef())
1572cfca06d7SDimitry Andric MO.setIsDead();
1573cfca06d7SDimitry Andric }
1574cfca06d7SDimitry Andric }
157563faed5bSDimitry Andric }
15764a16efa3SDimitry Andric
repairOldRegInRange(const MachineBasicBlock::iterator Begin,const MachineBasicBlock::iterator End,const SlotIndex EndIdx,LiveRange & LR,const Register Reg,LaneBitmask LaneMask)157767c32a98SDimitry Andric void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
157867c32a98SDimitry Andric const MachineBasicBlock::iterator End,
1579b60736ecSDimitry Andric const SlotIndex EndIdx, LiveRange &LR,
1580b60736ecSDimitry Andric const Register Reg,
1581dd58ef01SDimitry Andric LaneBitmask LaneMask) {
1582b60736ecSDimitry Andric LiveInterval::iterator LII = LR.find(EndIdx);
158367c32a98SDimitry Andric SlotIndex lastUseIdx;
1584c0981da4SDimitry Andric if (LII != LR.end() && LII->start < EndIdx) {
158567c32a98SDimitry Andric lastUseIdx = LII->end;
1586c0981da4SDimitry Andric } else if (LII == LR.begin()) {
1587c0981da4SDimitry Andric // We may not have a liverange at all if this is a subregister untouched
1588c0981da4SDimitry Andric // between \p Begin and \p End.
1589c0981da4SDimitry Andric } else {
159067c32a98SDimitry Andric --LII;
1591c0981da4SDimitry Andric }
159267c32a98SDimitry Andric
159367c32a98SDimitry Andric for (MachineBasicBlock::iterator I = End; I != Begin;) {
159467c32a98SDimitry Andric --I;
159501095a5dSDimitry Andric MachineInstr &MI = *I;
1596344a3780SDimitry Andric if (MI.isDebugOrPseudoInstr())
159767c32a98SDimitry Andric continue;
159867c32a98SDimitry Andric
159967c32a98SDimitry Andric SlotIndex instrIdx = getInstructionIndex(MI);
160067c32a98SDimitry Andric bool isStartValid = getInstructionFromIndex(LII->start);
160167c32a98SDimitry Andric bool isEndValid = getInstructionFromIndex(LII->end);
160267c32a98SDimitry Andric
160367c32a98SDimitry Andric // FIXME: This doesn't currently handle early-clobber or multiple removed
160467c32a98SDimitry Andric // defs inside of the region to repair.
1605c0981da4SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
160667c32a98SDimitry Andric if (!MO.isReg() || MO.getReg() != Reg)
160767c32a98SDimitry Andric continue;
160867c32a98SDimitry Andric
160967c32a98SDimitry Andric unsigned SubReg = MO.getSubReg();
1610dd58ef01SDimitry Andric LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1611b915e9e0SDimitry Andric if ((Mask & LaneMask).none())
161267c32a98SDimitry Andric continue;
161367c32a98SDimitry Andric
161467c32a98SDimitry Andric if (MO.isDef()) {
161567c32a98SDimitry Andric if (!isStartValid) {
161667c32a98SDimitry Andric if (LII->end.isDead()) {
1617c0981da4SDimitry Andric LII = LR.removeSegment(LII, true);
161867c32a98SDimitry Andric if (LII != LR.begin())
1619c0981da4SDimitry Andric --LII;
162067c32a98SDimitry Andric } else {
162167c32a98SDimitry Andric LII->start = instrIdx.getRegSlot();
162267c32a98SDimitry Andric LII->valno->def = instrIdx.getRegSlot();
162367c32a98SDimitry Andric if (MO.getSubReg() && !MO.isUndef())
162467c32a98SDimitry Andric lastUseIdx = instrIdx.getRegSlot();
162567c32a98SDimitry Andric else
162667c32a98SDimitry Andric lastUseIdx = SlotIndex();
162767c32a98SDimitry Andric continue;
162867c32a98SDimitry Andric }
162967c32a98SDimitry Andric }
163067c32a98SDimitry Andric
163167c32a98SDimitry Andric if (!lastUseIdx.isValid()) {
163267c32a98SDimitry Andric VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
163367c32a98SDimitry Andric LiveRange::Segment S(instrIdx.getRegSlot(),
163467c32a98SDimitry Andric instrIdx.getDeadSlot(), VNI);
163567c32a98SDimitry Andric LII = LR.addSegment(S);
163667c32a98SDimitry Andric } else if (LII->start != instrIdx.getRegSlot()) {
163767c32a98SDimitry Andric VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
163867c32a98SDimitry Andric LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
163967c32a98SDimitry Andric LII = LR.addSegment(S);
164067c32a98SDimitry Andric }
164167c32a98SDimitry Andric
164267c32a98SDimitry Andric if (MO.getSubReg() && !MO.isUndef())
164367c32a98SDimitry Andric lastUseIdx = instrIdx.getRegSlot();
164467c32a98SDimitry Andric else
164567c32a98SDimitry Andric lastUseIdx = SlotIndex();
164667c32a98SDimitry Andric } else if (MO.isUse()) {
164767c32a98SDimitry Andric // FIXME: This should probably be handled outside of this branch,
164867c32a98SDimitry Andric // either as part of the def case (for defs inside of the region) or
164967c32a98SDimitry Andric // after the loop over the region.
165067c32a98SDimitry Andric if (!isEndValid && !LII->end.isBlock())
165167c32a98SDimitry Andric LII->end = instrIdx.getRegSlot();
165267c32a98SDimitry Andric if (!lastUseIdx.isValid())
165367c32a98SDimitry Andric lastUseIdx = instrIdx.getRegSlot();
165467c32a98SDimitry Andric }
165567c32a98SDimitry Andric }
165667c32a98SDimitry Andric }
1657c0981da4SDimitry Andric
1658c0981da4SDimitry Andric bool isStartValid = getInstructionFromIndex(LII->start);
1659c0981da4SDimitry Andric if (!isStartValid && LII->end.isDead())
1660c0981da4SDimitry Andric LR.removeSegment(*LII, true);
166167c32a98SDimitry Andric }
166267c32a98SDimitry Andric
16634a16efa3SDimitry Andric void
repairIntervalsInRange(MachineBasicBlock * MBB,MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,ArrayRef<Register> OrigRegs)16644a16efa3SDimitry Andric LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
16654a16efa3SDimitry Andric MachineBasicBlock::iterator Begin,
16664a16efa3SDimitry Andric MachineBasicBlock::iterator End,
1667cfca06d7SDimitry Andric ArrayRef<Register> OrigRegs) {
16684a16efa3SDimitry Andric // Find anchor points, which are at the beginning/end of blocks or at
16694a16efa3SDimitry Andric // instructions that already have indexes.
16704b4fe385SDimitry Andric while (Begin != MBB->begin() && !Indexes->hasIndex(*std::prev(Begin)))
16714a16efa3SDimitry Andric --Begin;
167201095a5dSDimitry Andric while (End != MBB->end() && !Indexes->hasIndex(*End))
16734a16efa3SDimitry Andric ++End;
16744a16efa3SDimitry Andric
1675b60736ecSDimitry Andric SlotIndex EndIdx;
16764a16efa3SDimitry Andric if (End == MBB->end())
1677b60736ecSDimitry Andric EndIdx = getMBBEndIdx(MBB).getPrevSlot();
16784a16efa3SDimitry Andric else
1679b60736ecSDimitry Andric EndIdx = getInstructionIndex(*End);
16804a16efa3SDimitry Andric
16814a16efa3SDimitry Andric Indexes->repairIndexesInRange(MBB, Begin, End);
16824a16efa3SDimitry Andric
1683c0981da4SDimitry Andric // Make sure a live interval exists for all register operands in the range.
1684c0981da4SDimitry Andric SmallVector<Register> RegsToRepair(OrigRegs.begin(), OrigRegs.end());
16854a16efa3SDimitry Andric for (MachineBasicBlock::iterator I = End; I != Begin;) {
16864a16efa3SDimitry Andric --I;
168701095a5dSDimitry Andric MachineInstr &MI = *I;
1688344a3780SDimitry Andric if (MI.isDebugOrPseudoInstr())
16894a16efa3SDimitry Andric continue;
1690c0981da4SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
1691c0981da4SDimitry Andric if (MO.isReg() && MO.getReg().isVirtual()) {
1692c0981da4SDimitry Andric Register Reg = MO.getReg();
1693c0981da4SDimitry Andric if (MO.getSubReg() && hasInterval(Reg) &&
1694ac9a064cSDimitry Andric MRI->shouldTrackSubRegLiveness(Reg)) {
1695ac9a064cSDimitry Andric LiveInterval &LI = getInterval(Reg);
1696ac9a064cSDimitry Andric if (!LI.hasSubRanges()) {
1697ac9a064cSDimitry Andric // If the new instructions refer to subregs but the old instructions
1698ac9a064cSDimitry Andric // did not, throw away any old live interval so it will be
1699ac9a064cSDimitry Andric // recomputed with subranges.
1700c0981da4SDimitry Andric removeInterval(Reg);
1701ac9a064cSDimitry Andric } else if (MO.isDef()) {
1702ac9a064cSDimitry Andric // Similarly if a subreg def has no precise subrange match then
1703ac9a064cSDimitry Andric // assume we need to recompute all subranges.
1704ac9a064cSDimitry Andric unsigned SubReg = MO.getSubReg();
1705ac9a064cSDimitry Andric LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1706ac9a064cSDimitry Andric if (llvm::none_of(LI.subranges(),
1707ac9a064cSDimitry Andric [Mask](LiveInterval::SubRange &SR) {
1708ac9a064cSDimitry Andric return SR.LaneMask == Mask;
1709ac9a064cSDimitry Andric })) {
1710ac9a064cSDimitry Andric removeInterval(Reg);
1711ac9a064cSDimitry Andric }
1712ac9a064cSDimitry Andric }
1713ac9a064cSDimitry Andric }
1714c0981da4SDimitry Andric if (!hasInterval(Reg)) {
1715c0981da4SDimitry Andric createAndComputeVirtRegInterval(Reg);
1716c0981da4SDimitry Andric // Don't bother to repair a freshly calculated live interval.
1717b1c73532SDimitry Andric llvm::erase(RegsToRepair, Reg);
1718c0981da4SDimitry Andric }
17194a16efa3SDimitry Andric }
17204a16efa3SDimitry Andric }
17214a16efa3SDimitry Andric }
17224a16efa3SDimitry Andric
1723c0981da4SDimitry Andric for (Register Reg : RegsToRepair) {
1724cfca06d7SDimitry Andric if (!Reg.isVirtual())
17254a16efa3SDimitry Andric continue;
17264a16efa3SDimitry Andric
17274a16efa3SDimitry Andric LiveInterval &LI = getInterval(Reg);
17284a16efa3SDimitry Andric // FIXME: Should we support undefs that gain defs?
17294a16efa3SDimitry Andric if (!LI.hasAtLeastOneValue())
17304a16efa3SDimitry Andric continue;
17314a16efa3SDimitry Andric
173271d5a254SDimitry Andric for (LiveInterval::SubRange &S : LI.subranges())
1733b60736ecSDimitry Andric repairOldRegInRange(Begin, End, EndIdx, S, Reg, S.LaneMask);
1734c0981da4SDimitry Andric LI.removeEmptySubRanges();
173571d5a254SDimitry Andric
1736b60736ecSDimitry Andric repairOldRegInRange(Begin, End, EndIdx, LI, Reg);
17374a16efa3SDimitry Andric }
17384a16efa3SDimitry Andric }
17395a5ac124SDimitry Andric
removePhysRegDefAt(MCRegister Reg,SlotIndex Pos)1740b60736ecSDimitry Andric void LiveIntervals::removePhysRegDefAt(MCRegister Reg, SlotIndex Pos) {
17417fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(Reg)) {
17427fa27ce4SDimitry Andric if (LiveRange *LR = getCachedRegUnit(Unit))
17435a5ac124SDimitry Andric if (VNInfo *VNI = LR->getVNInfoAt(Pos))
17445a5ac124SDimitry Andric LR->removeValNo(VNI);
17455a5ac124SDimitry Andric }
17465a5ac124SDimitry Andric }
17475a5ac124SDimitry Andric
removeVRegDefAt(LiveInterval & LI,SlotIndex Pos)17485a5ac124SDimitry Andric void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1749b915e9e0SDimitry Andric // LI may not have the main range computed yet, but its subranges may
1750b915e9e0SDimitry Andric // be present.
17515a5ac124SDimitry Andric VNInfo *VNI = LI.getVNInfoAt(Pos);
1752b915e9e0SDimitry Andric if (VNI != nullptr) {
1753b915e9e0SDimitry Andric assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
17545a5ac124SDimitry Andric LI.removeValNo(VNI);
1755b915e9e0SDimitry Andric }
17565a5ac124SDimitry Andric
1757b915e9e0SDimitry Andric // Also remove the value defined in subranges.
17585a5ac124SDimitry Andric for (LiveInterval::SubRange &S : LI.subranges()) {
17595a5ac124SDimitry Andric if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1760b915e9e0SDimitry Andric if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
17615a5ac124SDimitry Andric S.removeValNo(SVNI);
17625a5ac124SDimitry Andric }
17635a5ac124SDimitry Andric LI.removeEmptySubRanges();
17645a5ac124SDimitry Andric }
1765dd58ef01SDimitry Andric
splitSeparateComponents(LiveInterval & LI,SmallVectorImpl<LiveInterval * > & SplitLIs)1766dd58ef01SDimitry Andric void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1767dd58ef01SDimitry Andric SmallVectorImpl<LiveInterval*> &SplitLIs) {
1768dd58ef01SDimitry Andric ConnectedVNInfoEqClasses ConEQ(*this);
1769050e163aSDimitry Andric unsigned NumComp = ConEQ.Classify(LI);
1770dd58ef01SDimitry Andric if (NumComp <= 1)
1771dd58ef01SDimitry Andric return;
1772eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1773b60736ecSDimitry Andric Register Reg = LI.reg();
1774dd58ef01SDimitry Andric for (unsigned I = 1; I < NumComp; ++I) {
1775e3b55780SDimitry Andric Register NewVReg = MRI->cloneVirtualRegister(Reg);
1776dd58ef01SDimitry Andric LiveInterval &NewLI = createEmptyInterval(NewVReg);
1777dd58ef01SDimitry Andric SplitLIs.push_back(&NewLI);
1778dd58ef01SDimitry Andric }
1779dd58ef01SDimitry Andric ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1780dd58ef01SDimitry Andric }
178101095a5dSDimitry Andric
constructMainRangeFromSubranges(LiveInterval & LI)178201095a5dSDimitry Andric void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
1783cfca06d7SDimitry Andric assert(LICalc && "LICalc not initialized.");
1784cfca06d7SDimitry Andric LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1785cfca06d7SDimitry Andric LICalc->constructMainRangeFromSubranges(LI);
178601095a5dSDimitry Andric }
1787