1//===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file This file implements the LiveInterval analysis pass which is used
10/// by the Linear Scan Register allocator. This pass linearizes the
11/// basic blocks of the function in DFS order and computes live intervals for
12/// each virtual and physical register.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/CodeGen/LiveIntervals.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DepthFirstIterator.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/iterator_range.h"
22#include "llvm/CodeGen/LiveInterval.h"
23#include "llvm/CodeGen/LiveIntervalCalc.h"
24#include "llvm/CodeGen/LiveVariables.h"
25#include "llvm/CodeGen/MachineBasicBlock.h"
26#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27#include "llvm/CodeGen/MachineDominators.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/MachineInstrBundle.h"
31#include "llvm/CodeGen/MachineOperand.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/MachineSizeOpts.h"
34#include "llvm/CodeGen/Passes.h"
35#include "llvm/CodeGen/SlotIndexes.h"
36#include "llvm/CodeGen/StackMaps.h"
37#include "llvm/CodeGen/TargetRegisterInfo.h"
38#include "llvm/CodeGen/TargetSubtargetInfo.h"
39#include "llvm/CodeGen/VirtRegMap.h"
40#include "llvm/Config/llvm-config.h"
41#include "llvm/IR/ProfileSummary.h"
42#include "llvm/IR/Statepoint.h"
43#include "llvm/InitializePasses.h"
44#include "llvm/MC/LaneBitmask.h"
45#include "llvm/MC/MCRegisterInfo.h"
46#include "llvm/Pass.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/raw_ostream.h"
52#include <algorithm>
53#include <cassert>
54#include <cstdint>
55#include <iterator>
56#include <tuple>
57#include <utility>
58
59using namespace llvm;
60
61#define DEBUG_TYPE "regalloc"
62
63AnalysisKey LiveIntervalsAnalysis::Key;
64
65LiveIntervalsAnalysis::Result
66LiveIntervalsAnalysis::run(MachineFunction &MF,
67 MachineFunctionAnalysisManager &MFAM) {
68 auto Res = Result(MF, MFAM.getResult<SlotIndexesAnalysis>(IR&: MF),
69 MFAM.getResult<MachineDominatorTreeAnalysis>(IR&: MF));
70 LLVM_DEBUG(Res.dump());
71 return Res;
72}
73
74PreservedAnalyses
75LiveIntervalsPrinterPass::run(MachineFunction &MF,
76 MachineFunctionAnalysisManager &MFAM) {
77 OS << "Live intervals for machine function: " << MF.getName() << ":\n";
78 MFAM.getResult<LiveIntervalsAnalysis>(IR&: MF).print(O&: OS);
79 return PreservedAnalyses::all();
80}
81
82char LiveIntervalsWrapperPass::ID = 0;
83char &llvm::LiveIntervalsID = LiveIntervalsWrapperPass::ID;
84INITIALIZE_PASS_BEGIN(LiveIntervalsWrapperPass, "liveintervals",
85 "Live Interval Analysis", false, false)
86INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
87INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
88INITIALIZE_PASS_END(LiveIntervalsWrapperPass, "liveintervals",
89 "Live Interval Analysis", false, true)
90
91bool LiveIntervalsWrapperPass::runOnMachineFunction(MachineFunction &MF) {
92 LIS.Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
93 LIS.DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
94 LIS.analyze(MF);
95 LLVM_DEBUG(dump());
96 return false;
97}
98
99#ifndef NDEBUG
100static cl::opt<bool> EnablePrecomputePhysRegs(
101 "precompute-phys-liveness", cl::Hidden,
102 cl::desc("Eagerly compute live intervals for all physreg units."));
103#else
104static bool EnablePrecomputePhysRegs = false;
105#endif // NDEBUG
106
107static cl::opt<bool> UseSegmentSetForPhysRegs(
108 "use-segment-set-for-physregs", cl::Hidden, cl::init(Val: true),
109 cl::desc(
110 "Use segment set for the computation of the live ranges of physregs."));
111
112void LiveIntervalsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
114 AU.addPreserved<LiveVariablesWrapperPass>();
115 AU.addPreservedID(ID&: MachineLoopInfoID);
116 AU.addRequiredTransitiveID(ID&: MachineDominatorsID);
117 AU.addPreservedID(ID&: MachineDominatorsID);
118 AU.addPreserved<SlotIndexesWrapperPass>();
119 AU.addRequiredTransitive<SlotIndexesWrapperPass>();
120 MachineFunctionPass::getAnalysisUsage(AU);
121}
122
123LiveIntervalsWrapperPass::LiveIntervalsWrapperPass()
124 : MachineFunctionPass(ID) {}
125
126LiveIntervals::~LiveIntervals() { clear(); }
127
128bool LiveIntervals::invalidate(
129 MachineFunction &MF, const PreservedAnalyses &PA,
130 MachineFunctionAnalysisManager::Invalidator &Inv) {
131 auto PAC = PA.getChecker<LiveIntervalsAnalysis>();
132
133 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<MachineFunction>>())
134 return true;
135
136 // LiveIntervals holds pointers to these results, so check for their
137 // invalidation.
138 return Inv.invalidate<SlotIndexesAnalysis>(IR&: MF, PA) ||
139 Inv.invalidate<MachineDominatorTreeAnalysis>(IR&: MF, PA);
140}
141
142void LiveIntervals::clear() {
143 // Free the live intervals themselves.
144 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
145 delete VirtRegIntervals[Register::index2VirtReg(Index: i)];
146 VirtRegIntervals.clear();
147 RegMaskSlots.clear();
148 RegMaskBits.clear();
149 RegMaskBlocks.clear();
150
151 for (LiveRange *LR : RegUnitRanges)
152 delete LR;
153 RegUnitRanges.clear();
154
155 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
156 VNInfoAllocator.Reset();
157}
158
159void LiveIntervals::analyze(MachineFunction &fn) {
160 MF = &fn;
161 MRI = &MF->getRegInfo();
162 TRI = MF->getSubtarget().getRegisterInfo();
163 TII = MF->getSubtarget().getInstrInfo();
164
165 if (!LICalc)
166 LICalc = std::make_unique<LiveIntervalCalc>();
167
168 // Allocate space for all virtual registers.
169 VirtRegIntervals.resize(S: MRI->getNumVirtRegs());
170
171 computeVirtRegs();
172 computeRegMasks();
173 computeLiveInRegUnits();
174
175 if (EnablePrecomputePhysRegs) {
176 // For stress testing, precompute live ranges of all physical register
177 // units, including reserved registers.
178 for (MCRegUnit Unit : TRI->regunits())
179 getRegUnit(Unit);
180 }
181}
182
183void LiveIntervals::print(raw_ostream &OS) const {
184 OS << "********** INTERVALS **********\n";
185
186 // Dump the regunits.
187 for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
188 if (LiveRange *LR = RegUnitRanges[Unit])
189 OS << printRegUnit(Unit: static_cast<MCRegUnit>(Unit), TRI) << ' ' << *LR
190 << '\n';
191
192 // Dump the virtregs.
193 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
194 Register Reg = Register::index2VirtReg(Index: i);
195 if (hasInterval(Reg))
196 OS << getInterval(Reg) << '\n';
197 }
198
199 OS << "RegMasks:";
200 for (SlotIndex Idx : RegMaskSlots)
201 OS << ' ' << Idx;
202 OS << '\n';
203
204 printInstrs(O&: OS);
205}
206
207void LiveIntervals::printInstrs(raw_ostream &OS) const {
208 OS << "********** MACHINEINSTRS **********\n";
209 MF->print(OS, Indexes);
210}
211
212#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
213LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
214 printInstrs(dbgs());
215}
216#endif
217
218#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
219LLVM_DUMP_METHOD void LiveIntervals::dump() const { print(dbgs()); }
220#endif
221
222LiveInterval *LiveIntervals::createInterval(Register reg) {
223 float Weight = reg.isPhysical() ? huge_valf : 0.0F;
224 return new LiveInterval(reg, Weight);
225}
226
227LiveRange *LiveIntervals::createRegUnitRange() {
228 // Use segment set to speed-up initial computation of the live range.
229 return new LiveRange(UseSegmentSetForPhysRegs);
230}
231
232/// Compute the live interval of a virtual register, based on defs and uses.
233bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
234 assert(LICalc && "LICalc not initialized.");
235 assert(LI.empty() && "Should only compute empty intervals.");
236 LICalc->reset(mf: MF, SI: getSlotIndexes(), MDT: DomTree, VNIA: &getVNInfoAllocator());
237 LICalc->calculate(LI, TrackSubRegs: MRI->shouldTrackSubRegLiveness(VReg: LI.reg()));
238 return computeDeadValues(LI, dead: nullptr);
239}
240
241void LiveIntervals::computeVirtRegs() {
242 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
243 Register Reg = Register::index2VirtReg(Index: i);
244 if (MRI->reg_nodbg_empty(RegNo: Reg))
245 continue;
246 LiveInterval &LI = createEmptyInterval(Reg);
247 bool NeedSplit = computeVirtRegInterval(LI);
248 if (NeedSplit) {
249 SmallVector<LiveInterval*, 8> SplitLIs;
250 splitSeparateComponents(LI, SplitLIs);
251 }
252 }
253}
254
255void LiveIntervals::computeRegMasks() {
256 RegMaskBlocks.resize(N: MF->getNumBlockIDs());
257
258 // Find all instructions with regmask operands.
259 for (const MachineBasicBlock &MBB : *MF) {
260 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
261 RMB.first = RegMaskSlots.size();
262
263 // Some block starts, such as EH funclets, create masks.
264 if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
265 RegMaskSlots.push_back(Elt: Indexes->getMBBStartIdx(mbb: &MBB));
266 RegMaskBits.push_back(Elt: Mask);
267 }
268
269 // Unwinders may clobber additional registers.
270 // FIXME: This functionality can possibly be merged into
271 // MachineBasicBlock::getBeginClobberMask().
272 if (MBB.isEHPad())
273 if (auto *Mask = TRI->getCustomEHPadPreservedMask(MF: *MBB.getParent())) {
274 RegMaskSlots.push_back(Elt: Indexes->getMBBStartIdx(mbb: &MBB));
275 RegMaskBits.push_back(Elt: Mask);
276 }
277
278 for (const MachineInstr &MI : MBB) {
279 for (const MachineOperand &MO : MI.operands()) {
280 if (!MO.isRegMask())
281 continue;
282 RegMaskSlots.push_back(Elt: Indexes->getInstructionIndex(MI).getRegSlot());
283 RegMaskBits.push_back(Elt: MO.getRegMask());
284 }
285 }
286
287 // Some block ends, such as funclet returns, create masks. Put the mask on
288 // the last instruction of the block, because MBB slot index intervals are
289 // half-open.
290 if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
291 assert(!MBB.empty() && "empty return block?");
292 RegMaskSlots.push_back(
293 Elt: Indexes->getInstructionIndex(MI: MBB.back()).getRegSlot());
294 RegMaskBits.push_back(Elt: Mask);
295 }
296
297 // Compute the number of register mask instructions in this block.
298 RMB.second = RegMaskSlots.size() - RMB.first;
299 }
300}
301
302void LiveIntervals::reassignRegMaskSlots(MachineBasicBlock &Orig,
303 MachineBasicBlock &SplitBB) {
304 assert(&Orig != &SplitBB && "expected distinct blocks");
305 std::pair<unsigned, unsigned> &OrigRMB = RegMaskBlocks[Orig.getNumber()];
306 std::pair<unsigned, unsigned> &SplitRMB = RegMaskBlocks[SplitBB.getNumber()];
307
308 // RegMaskSlots is sorted, so the slots that moved are those at or after
309 // SplitBB's start index.
310 ArrayRef<SlotIndex> OrigSlots =
311 getRegMaskSlots().slice(N: OrigRMB.first, M: OrigRMB.second);
312 unsigned KeptCount = llvm::lower_bound(Range&: OrigSlots, Value: getMBBStartIdx(mbb: &SplitBB)) -
313 OrigSlots.begin();
314 if (KeptCount == OrigRMB.second)
315 return; // No regmask slots moved into SplitBB.
316
317 SplitRMB.first = OrigRMB.first + KeptCount;
318 SplitRMB.second = OrigRMB.second - KeptCount;
319 OrigRMB.second = KeptCount;
320}
321
322void LiveIntervals::insertMBBInMapsImpl(
323 MachineBasicBlock *MBB, [[maybe_unused]] bool AssumeRegMaskEmpty) {
324#ifdef EXPENSIVE_CHECKS
325 assert((!AssumeRegMaskEmpty ||
326 none_of(*MBB,
327 [](const MachineInstr &MI) {
328 return any_of(MI.operands(), [](const MachineOperand &MO) {
329 return MO.isRegMask();
330 });
331 })) &&
332 "insertMBBInMaps expects a block with no regmask operands; use "
333 "LiveIntervals::splitAt() to split a block containing calls");
334#endif
335 Indexes->insertMBBInMaps(mbb: MBB);
336 assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
337 "Blocks must be added in order.");
338 RegMaskBlocks.push_back(Elt: std::make_pair(x: RegMaskSlots.size(), y: 0));
339}
340
341//===----------------------------------------------------------------------===//
342// Register Unit Liveness
343//===----------------------------------------------------------------------===//
344//
345// Fixed interference typically comes from ABI boundaries: Function arguments
346// and return values are passed in fixed registers, and so are exception
347// pointers entering landing pads. Certain instructions require values to be
348// present in specific registers. That is also represented through fixed
349// interference.
350//
351
352/// Compute the live range of a register unit, based on the uses and defs of
353/// aliasing registers. The range should be empty, or contain only dead
354/// phi-defs from ABI blocks.
355void LiveIntervals::computeRegUnitRange(LiveRange &LR, MCRegUnit Unit) {
356 assert(LICalc && "LICalc not initialized.");
357 LICalc->reset(mf: MF, SI: getSlotIndexes(), MDT: DomTree, VNIA: &getVNInfoAllocator());
358
359 // The physregs aliasing Unit are the roots and their super-registers.
360 // Create all values as dead defs before extending to uses. Note that roots
361 // may share super-registers. That's OK because createDeadDefs() is
362 // idempotent. It is very rare for a register unit to have multiple roots, so
363 // uniquing super-registers is probably not worthwhile.
364 bool IsReserved = false;
365 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
366 bool IsRootReserved = true;
367 for (MCPhysReg Reg : TRI->superregs_inclusive(Reg: *Root)) {
368 if (!MRI->reg_empty(RegNo: Reg))
369 LICalc->createDeadDefs(LR, Reg);
370 // A register unit is considered reserved if all its roots and all their
371 // super registers are reserved.
372 if (!MRI->isReserved(PhysReg: Reg))
373 IsRootReserved = false;
374 }
375 IsReserved |= IsRootReserved;
376 }
377 assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
378 "reserved computation mismatch");
379
380 // Now extend LR to reach all uses.
381 // Ignore uses of reserved registers. We only track defs of those.
382 if (!IsReserved) {
383 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
384 for (MCPhysReg Reg : TRI->superregs_inclusive(Reg: *Root)) {
385 if (!MRI->reg_empty(RegNo: Reg))
386 LICalc->extendToUses(LR, PhysReg: Reg);
387 }
388 }
389 }
390
391 // Flush the segment set to the segment vector.
392 if (UseSegmentSetForPhysRegs)
393 LR.flushSegmentSet();
394}
395
396/// Precompute the live ranges of any register units that are live-in to an ABI
397/// block somewhere. Register values can appear without a corresponding def when
398/// entering the entry block or a landing pad.
399void LiveIntervals::computeLiveInRegUnits() {
400 RegUnitRanges.resize(N: TRI->getNumRegUnits());
401 LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
402
403 // Keep track of the live range sets allocated.
404 SmallVector<MCRegUnit, 8> NewRanges;
405
406 // Check all basic blocks for live-ins.
407 for (const MachineBasicBlock &MBB : *MF) {
408 // We only care about ABI blocks: Entry + landing pads.
409 if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
410 continue;
411
412 // Create phi-defs at Begin for all live-in registers.
413 SlotIndex Begin = Indexes->getMBBStartIdx(mbb: &MBB);
414 LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
415 for (const auto &LI : MBB.liveins()) {
416 for (MCRegUnit Unit : TRI->regunits(Reg: LI.PhysReg)) {
417 LiveRange *LR = RegUnitRanges[static_cast<unsigned>(Unit)];
418 if (!LR) {
419 LR = RegUnitRanges[static_cast<unsigned>(Unit)] =
420 createRegUnitRange();
421 NewRanges.push_back(Elt: Unit);
422 }
423 VNInfo *VNI = LR->createDeadDef(Def: Begin, VNIAlloc&: getVNInfoAllocator());
424 (void)VNI;
425 LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
426 }
427 }
428 LLVM_DEBUG(dbgs() << '\n');
429 }
430 LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
431
432 // Compute the 'normal' part of the ranges.
433 for (MCRegUnit Unit : NewRanges)
434 computeRegUnitRange(LR&: *RegUnitRanges[static_cast<unsigned>(Unit)], Unit);
435}
436
437static void createSegmentsForValues(LiveRange &LR,
438 iterator_range<LiveInterval::vni_iterator> VNIs) {
439 for (VNInfo *VNI : VNIs) {
440 if (VNI->isUnused())
441 continue;
442 SlotIndex Def = VNI->def;
443 LR.addSegment(S: LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
444 }
445}
446
447void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
448 ShrinkToUsesWorkList &WorkList,
449 Register Reg, LaneBitmask LaneMask) {
450 // Keep track of the PHIs that are in use.
451 SmallPtrSet<VNInfo*, 8> UsedPHIs;
452 // Blocks that have already been added to WorkList as live-out.
453 SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
454
455 auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
456 -> const LiveRange& {
457 if (M.none())
458 return I;
459 for (const LiveInterval::SubRange &SR : I.subranges()) {
460 if ((SR.LaneMask & M).any()) {
461 assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
462 return SR;
463 }
464 }
465 llvm_unreachable("Subrange for mask not found");
466 };
467
468 const LiveInterval &LI = getInterval(Reg);
469 const LiveRange &OldRange = getSubRange(LI, LaneMask);
470
471 // Extend intervals to reach all uses in WorkList.
472 while (!WorkList.empty()) {
473 SlotIndex Idx = WorkList.back().first;
474 VNInfo *VNI = WorkList.back().second;
475 WorkList.pop_back();
476 const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(index: Idx.getPrevSlot());
477 SlotIndex BlockStart = Indexes->getMBBStartIdx(mbb: MBB);
478
479 // Extend the live range for VNI to be live at Idx.
480 if (VNInfo *ExtVNI = Segments.extendInBlock(StartIdx: BlockStart, Kill: Idx)) {
481 assert(ExtVNI == VNI && "Unexpected existing value number");
482 (void)ExtVNI;
483 // Is this a PHIDef we haven't seen before?
484 if (!VNI->isPHIDef() || VNI->def != BlockStart ||
485 !UsedPHIs.insert(Ptr: VNI).second)
486 continue;
487 // The PHI is live, make sure the predecessors are live-out.
488 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
489 if (!LiveOut.insert(Ptr: Pred).second)
490 continue;
491 SlotIndex Stop = Indexes->getMBBEndIdx(mbb: Pred);
492 // A predecessor is not required to have a live-out value for a PHI.
493 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Idx: Stop))
494 WorkList.push_back(Elt: std::make_pair(x&: Stop, y&: PVNI));
495 }
496 continue;
497 }
498
499 // VNI is live-in to MBB.
500 LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
501 Segments.addSegment(S: LiveRange::Segment(BlockStart, Idx, VNI));
502
503 // Make sure VNI is live-out from the predecessors.
504 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
505 if (!LiveOut.insert(Ptr: Pred).second)
506 continue;
507 SlotIndex Stop = Indexes->getMBBEndIdx(mbb: Pred);
508 if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Idx: Stop)) {
509 assert(OldVNI == VNI && "Wrong value out of predecessor");
510 (void)OldVNI;
511 WorkList.push_back(Elt: std::make_pair(x&: Stop, y&: VNI));
512 } else {
513#ifndef NDEBUG
514 // There was no old VNI. Verify that Stop is jointly dominated
515 // by <undef>s for this live range.
516 assert(LaneMask.any() &&
517 "Missing value out of predecessor for main range");
518 SmallVector<SlotIndex,8> Undefs;
519 LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
520 assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
521 "Missing value out of predecessor for subrange");
522#endif
523 }
524 }
525 }
526}
527
528bool LiveIntervals::shrinkToUses(LiveInterval *li,
529 SmallVectorImpl<MachineInstr*> *dead) {
530 LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
531 assert(li->reg().isVirtual() && "Can only shrink virtual registers");
532
533 // Shrink subregister live ranges.
534 bool NeedsCleanup = false;
535 for (LiveInterval::SubRange &S : li->subranges()) {
536 shrinkToUses(SR&: S, Reg: li->reg());
537 if (S.empty())
538 NeedsCleanup = true;
539 }
540 if (NeedsCleanup)
541 li->removeEmptySubRanges();
542
543 // Find all the values used, including PHI kills.
544 ShrinkToUsesWorkList WorkList;
545
546 // Visit all instructions reading li->reg().
547 Register Reg = li->reg();
548 for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
549 if (UseMI.isDebugInstr() || !UseMI.readsVirtualRegister(Reg))
550 continue;
551 SlotIndex Idx = getInstructionIndex(Instr: UseMI).getRegSlot();
552 LiveQueryResult LRQ = li->Query(Idx);
553 VNInfo *VNI = LRQ.valueIn();
554 if (!VNI) {
555 // This shouldn't happen: readsVirtualRegister returns true, but there is
556 // no live value. It is likely caused by a target getting <undef> flags
557 // wrong.
558 LLVM_DEBUG(
559 dbgs() << Idx << '\t' << UseMI
560 << "Warning: Instr claims to read non-existent value in "
561 << *li << '\n');
562 continue;
563 }
564 // Special case: An early-clobber tied operand reads and writes the
565 // register one slot early.
566 if (VNInfo *DefVNI = LRQ.valueDefined())
567 Idx = DefVNI->def;
568
569 WorkList.push_back(Elt: std::make_pair(x&: Idx, y&: VNI));
570 }
571
572 // Create new live ranges with only minimal live segments per def.
573 LiveRange NewLR;
574 createSegmentsForValues(LR&: NewLR, VNIs: li->vnis());
575 extendSegmentsToUses(Segments&: NewLR, WorkList, Reg, LaneMask: LaneBitmask::getNone());
576
577 // Move the trimmed segments back.
578 li->segments.swap(RHS&: NewLR.segments);
579
580 // Handle dead values.
581 bool CanSeparate = computeDeadValues(LI&: *li, dead);
582 LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
583 return CanSeparate;
584}
585
586bool LiveIntervals::computeDeadValues(LiveInterval &LI,
587 SmallVectorImpl<MachineInstr*> *dead) {
588 bool MayHaveSplitComponents = false;
589
590 for (VNInfo *VNI : LI.valnos) {
591 if (VNI->isUnused())
592 continue;
593 SlotIndex Def = VNI->def;
594 LiveRange::iterator I = LI.FindSegmentContaining(Idx: Def);
595 assert(I != LI.end() && "Missing segment for VNI");
596
597 // Is the register live before? Otherwise we may have to add a read-undef
598 // flag for subregister defs.
599 Register VReg = LI.reg();
600 if (MRI->shouldTrackSubRegLiveness(VReg)) {
601 if ((I == LI.begin() || std::prev(x: I)->end < Def) && !VNI->isPHIDef()) {
602 MachineInstr *MI = getInstructionFromIndex(index: Def);
603 MI->setRegisterDefReadUndef(Reg: VReg);
604 }
605 }
606
607 if (I->end != Def.getDeadSlot())
608 continue;
609 if (VNI->isPHIDef()) {
610 // This is a dead PHI. Remove it.
611 VNI->markUnused();
612 LI.removeSegment(I);
613 LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
614 } else {
615 // This is a dead def. Make sure the instruction knows.
616 MachineInstr *MI = getInstructionFromIndex(index: Def);
617 assert(MI && "No instruction defining live value");
618 MI->addRegisterDead(Reg: LI.reg(), RegInfo: TRI);
619
620 if (dead && MI->allDefsAreDead()) {
621 LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
622 dead->push_back(Elt: MI);
623 }
624 }
625 MayHaveSplitComponents = true;
626 }
627 return MayHaveSplitComponents;
628}
629
630void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, Register Reg) {
631 LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
632 assert(Reg.isVirtual() && "Can only shrink virtual registers");
633 // Find all the values used, including PHI kills.
634 ShrinkToUsesWorkList WorkList;
635
636 // Visit all instructions reading Reg.
637 SlotIndex LastIdx;
638 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
639 // Skip "undef" uses.
640 if (!MO.readsReg())
641 continue;
642 // Maybe the operand is for a subregister we don't care about.
643 unsigned SubReg = MO.getSubReg();
644 if (SubReg != 0) {
645 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubIdx: SubReg);
646 if ((LaneMask & SR.LaneMask).none())
647 continue;
648 }
649 // We only need to visit each instruction once.
650 MachineInstr *UseMI = MO.getParent();
651 SlotIndex Idx = getInstructionIndex(Instr: *UseMI).getRegSlot();
652 if (Idx == LastIdx)
653 continue;
654 LastIdx = Idx;
655
656 LiveQueryResult LRQ = SR.Query(Idx);
657 VNInfo *VNI = LRQ.valueIn();
658 // For Subranges it is possible that only undef values are left in that
659 // part of the subregister, so there is no real liverange at the use
660 if (!VNI)
661 continue;
662
663 // Special case: An early-clobber tied operand reads and writes the
664 // register one slot early.
665 if (VNInfo *DefVNI = LRQ.valueDefined())
666 Idx = DefVNI->def;
667
668 WorkList.push_back(Elt: std::make_pair(x&: Idx, y&: VNI));
669 }
670
671 // Create a new live ranges with only minimal live segments per def.
672 LiveRange NewLR;
673 createSegmentsForValues(LR&: NewLR, VNIs: SR.vnis());
674 extendSegmentsToUses(Segments&: NewLR, WorkList, Reg, LaneMask: SR.LaneMask);
675
676 // Move the trimmed ranges back.
677 SR.segments.swap(RHS&: NewLR.segments);
678
679 // Remove dead PHI value numbers
680 for (VNInfo *VNI : SR.valnos) {
681 if (VNI->isUnused())
682 continue;
683 const LiveRange::Segment *Segment = SR.getSegmentContaining(Idx: VNI->def);
684 assert(Segment != nullptr && "Missing segment for VNI");
685 if (Segment->end != VNI->def.getDeadSlot())
686 continue;
687 if (VNI->isPHIDef()) {
688 // This is a dead PHI. Remove it.
689 LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
690 << " may separate interval\n");
691 VNI->markUnused();
692 SR.removeSegment(S: *Segment);
693 }
694 }
695
696 LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
697}
698
699void LiveIntervals::extendToIndices(LiveRange &LR,
700 ArrayRef<SlotIndex> Indices,
701 ArrayRef<SlotIndex> Undefs) {
702 assert(LICalc && "LICalc not initialized.");
703 LICalc->reset(mf: MF, SI: getSlotIndexes(), MDT: DomTree, VNIA: &getVNInfoAllocator());
704 for (SlotIndex Idx : Indices)
705 LICalc->extend(LR, Use: Idx, /*PhysReg=*/0, Undefs);
706}
707
708void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
709 SmallVectorImpl<SlotIndex> *EndPoints) {
710 LiveQueryResult LRQ = LR.Query(Idx: Kill);
711 // LR may have liveness reachable from early clobber slot, which may be
712 // only live-in instead of live-out of the instruction.
713 // For example, LR =[1r, 3r), Kill = 3e, we have to prune [3e, 3r) of LR.
714 VNInfo *VNI = LRQ.valueOutOrDead() ? LRQ.valueOutOrDead() : LRQ.valueIn();
715 if (!VNI)
716 return;
717
718 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(index: Kill);
719 SlotIndex MBBEnd = Indexes->getMBBEndIdx(mbb: KillMBB);
720
721 // If VNI isn't live out from KillMBB, the value is trivially pruned.
722 if (LRQ.endPoint() < MBBEnd) {
723 LR.removeSegment(Start: Kill, End: LRQ.endPoint());
724 if (EndPoints) EndPoints->push_back(Elt: LRQ.endPoint());
725 return;
726 }
727
728 // VNI is live out of KillMBB.
729 LR.removeSegment(Start: Kill, End: MBBEnd);
730 if (EndPoints) EndPoints->push_back(Elt: MBBEnd);
731
732 // Find all blocks that are reachable from KillMBB without leaving VNI's live
733 // range. It is possible that KillMBB itself is reachable, so start a DFS
734 // from each successor.
735 using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
736 VisitedTy Visited;
737 for (MachineBasicBlock *Succ : KillMBB->successors()) {
738 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
739 I = df_ext_begin(G: Succ, S&: Visited), E = df_ext_end(G: Succ, S&: Visited);
740 I != E;) {
741 MachineBasicBlock *MBB = *I;
742
743 // Check if VNI is live in to MBB.
744 SlotIndex MBBStart, MBBEnd;
745 std::tie(args&: MBBStart, args&: MBBEnd) = Indexes->getMBBRange(MBB);
746 LiveQueryResult LRQ = LR.Query(Idx: MBBStart);
747 if (LRQ.valueIn() != VNI) {
748 // This block isn't part of the VNI segment. Prune the search.
749 I.skipChildren();
750 continue;
751 }
752
753 // Prune the search if VNI is killed in MBB.
754 if (LRQ.endPoint() < MBBEnd) {
755 LR.removeSegment(Start: MBBStart, End: LRQ.endPoint());
756 if (EndPoints) EndPoints->push_back(Elt: LRQ.endPoint());
757 I.skipChildren();
758 continue;
759 }
760
761 // VNI is live through MBB.
762 LR.removeSegment(Start: MBBStart, End: MBBEnd);
763 if (EndPoints) EndPoints->push_back(Elt: MBBEnd);
764 ++I;
765 }
766 }
767}
768
769//===----------------------------------------------------------------------===//
770// Register allocator hooks.
771//
772
773void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
774 // Keep track of regunit ranges.
775 SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
776
777 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
778 Register Reg = Register::index2VirtReg(Index: i);
779 if (MRI->reg_nodbg_empty(RegNo: Reg))
780 continue;
781 const LiveInterval &LI = getInterval(Reg);
782 if (LI.empty())
783 continue;
784
785 // Target may have not allocated this yet.
786 Register PhysReg = VRM->getPhys(virtReg: Reg);
787 if (!PhysReg)
788 continue;
789
790 // Find the regunit intervals for the assigned register. They may overlap
791 // the virtual register live range, cancelling any kills.
792 RU.clear();
793 LaneBitmask ArtificialLanes;
794 for (MCRegUnitMaskIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
795 auto [Unit, Bitmask] = *UI;
796 // Record lane mask for all artificial RegUnits for this physreg.
797 if (TRI->isArtificialRegUnit(Unit))
798 ArtificialLanes |= Bitmask;
799 const LiveRange &RURange = getRegUnit(Unit);
800 if (RURange.empty())
801 continue;
802 RU.push_back(Elt: std::make_pair(x: &RURange, y: RURange.find(Pos: LI.begin()->end)));
803 }
804 // Every instruction that kills Reg corresponds to a segment range end
805 // point.
806 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
807 ++RI) {
808 // A block index indicates an MBB edge.
809 if (RI->end.isBlock())
810 continue;
811 MachineInstr *MI = getInstructionFromIndex(index: RI->end);
812 if (!MI)
813 continue;
814
815 // Check if any of the regunits are live beyond the end of RI. That could
816 // happen when a physreg is defined as a copy of a virtreg:
817 //
818 // %eax = COPY %5
819 // FOO %5 <--- MI, cancel kill because %eax is live.
820 // BAR killed %eax
821 //
822 // There should be no kill flag on FOO when %5 is rewritten as %eax.
823 for (auto &RUP : RU) {
824 const LiveRange &RURange = *RUP.first;
825 LiveRange::const_iterator &I = RUP.second;
826 if (I == RURange.end())
827 continue;
828 I = RURange.advanceTo(I, Pos: RI->end);
829 if (I == RURange.end() || I->start >= RI->end)
830 continue;
831 // I is overlapping RI.
832 goto CancelKill;
833 }
834
835 if (MRI->subRegLivenessEnabled()) {
836 // When reading a partial undefined value we must not add a kill flag.
837 // The regalloc might have used the undef lane for something else.
838 // Example:
839 // %1 = ... ; R32: %1
840 // %2:high16 = ... ; R64: %2
841 // = read killed %2 ; R64: %2
842 // = read %1 ; R32: %1
843 // The <kill> flag is correct for %2, but the register allocator may
844 // assign R0L to %1, and R0 to %2 because the low 32bits of R0
845 // are actually never written by %2. After assignment the <kill>
846 // flag at the read instruction is invalid.
847 LaneBitmask DefinedLanesMask;
848 if (LI.hasSubRanges()) {
849 // Compute a mask of lanes that are defined.
850 // Artificial regunits are not independently allocatable so the
851 // register allocator cannot have used them to represent any other
852 // values. That's why we mark them as 'defined' here, as this
853 // otherwise prevents kill flags from being added.
854 DefinedLanesMask = ArtificialLanes;
855 for (const LiveInterval::SubRange &SR : LI.subranges())
856 for (const LiveRange::Segment &Segment : SR.segments) {
857 if (Segment.start >= RI->end)
858 break;
859 if (Segment.end == RI->end) {
860 DefinedLanesMask |= SR.LaneMask;
861 break;
862 }
863 }
864 } else
865 DefinedLanesMask = LaneBitmask::getAll();
866
867 bool IsFullWrite = false;
868 for (const MachineOperand &MO : MI->operands()) {
869 if (!MO.isReg() || MO.getReg() != Reg)
870 continue;
871 if (MO.isUse()) {
872 // Reading any undefined lanes?
873 unsigned SubReg = MO.getSubReg();
874 LaneBitmask UseMask = SubReg ? TRI->getSubRegIndexLaneMask(SubIdx: SubReg)
875 : MRI->getMaxLaneMaskForVReg(Reg);
876 if ((UseMask & ~DefinedLanesMask).any())
877 goto CancelKill;
878 } else if (MO.getSubReg() == 0) {
879 // Writing to the full register?
880 assert(MO.isDef());
881 IsFullWrite = true;
882 }
883 }
884
885 // If an instruction writes to a subregister, a new segment starts in
886 // the LiveInterval. But as this is only overriding part of the register
887 // adding kill-flags is not correct here after registers have been
888 // assigned.
889 if (!IsFullWrite) {
890 // Next segment has to be adjacent in the subregister write case.
891 LiveRange::const_iterator N = std::next(x: RI);
892 if (N != LI.end() && N->start == RI->end)
893 goto CancelKill;
894 }
895 }
896
897 MI->addRegisterKilled(IncomingReg: Reg, RegInfo: nullptr);
898 continue;
899CancelKill:
900 MI->clearRegisterKills(Reg, RegInfo: nullptr);
901 }
902 }
903}
904
905MachineBasicBlock*
906LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
907 assert(!LI.empty() && "LiveInterval is empty.");
908
909 // A local live range must be fully contained inside the block, meaning it is
910 // defined and killed at instructions, not at block boundaries. It is not
911 // live in or out of any block.
912 //
913 // It is technically possible to have a PHI-defined live range identical to a
914 // single block, but we are going to return false in that case.
915
916 SlotIndex Start = LI.beginIndex();
917 if (Start.isBlock())
918 return nullptr;
919
920 SlotIndex Stop = LI.endIndex();
921 if (Stop.isBlock())
922 return nullptr;
923
924 // getMBBFromIndex doesn't need to search the MBB table when both indexes
925 // belong to proper instructions.
926 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(index: Start);
927 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(index: Stop);
928 return MBB1 == MBB2 ? MBB1 : nullptr;
929}
930
931bool
932LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
933 for (const VNInfo *PHI : LI.valnos) {
934 if (PHI->isUnused() || !PHI->isPHIDef())
935 continue;
936 const MachineBasicBlock *PHIMBB = getMBBFromIndex(index: PHI->def);
937 // Conservatively return true instead of scanning huge predecessor lists.
938 if (PHIMBB->pred_size() > 100)
939 return true;
940 for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
941 if (VNI == LI.getVNInfoBefore(Idx: Indexes->getMBBEndIdx(mbb: Pred)))
942 return true;
943 }
944 return false;
945}
946
947float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
948 const MachineBlockFrequencyInfo *MBFI,
949 const MachineInstr &MI,
950 ProfileSummaryInfo *PSI) {
951 return getSpillWeight(isDef, isUse, MBFI, MBB: MI.getParent(), PSI);
952}
953
954float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
955 const MachineBlockFrequencyInfo *MBFI,
956 const MachineBasicBlock *MBB,
957 ProfileSummaryInfo *PSI) {
958 const auto *MF = MBB->getParent();
959 return getSpillWeight(isDef, isUse, MBFI, MBB,
960 OptForSize: PSI && llvm::shouldOptimizeForSize(MF, PSI, BFI: MBFI));
961}
962
963float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
964 const MachineBlockFrequencyInfo *MBFI,
965 const MachineInstr &MI, bool OptForSize) {
966 return getSpillWeight(isDef, isUse, MBFI, MBB: MI.getParent(), OptForSize);
967}
968
969float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
970 const MachineBlockFrequencyInfo *MBFI,
971 const MachineBasicBlock *MBB,
972 bool OptForSize) {
973 float Weight = isDef + isUse;
974 // When optimizing for size we only consider the codesize impact of spilling
975 // the register, not the runtime impact.
976 if (OptForSize)
977 return Weight;
978 return Weight * MBFI->getBlockFreqRelativeToEntryBlock(MBB);
979}
980
981LiveRange::Segment
982LiveIntervals::addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst) {
983 LiveInterval &Interval = getOrCreateEmptyInterval(Reg);
984 VNInfo *VN = Interval.getNextValue(
985 Def: SlotIndex(getInstructionIndex(Instr: startInst).getRegSlot()),
986 VNInfoAllocator&: getVNInfoAllocator());
987 LiveRange::Segment S(SlotIndex(getInstructionIndex(Instr: startInst).getRegSlot()),
988 getMBBEndIdx(mbb: startInst.getParent()), VN);
989 Interval.addSegment(S);
990
991 return S;
992}
993
994//===----------------------------------------------------------------------===//
995// Register mask functions
996//===----------------------------------------------------------------------===//
997/// Check whether use of reg in MI is live-through. Live-through means that
998/// the value is alive on exit from Machine instruction. The example of such
999/// use is a deopt value in statepoint instruction.
1000static bool hasLiveThroughUse(const MachineInstr *MI, Register Reg) {
1001 if (MI->getOpcode() != TargetOpcode::STATEPOINT)
1002 return false;
1003 StatepointOpers SO(MI);
1004 if (SO.getFlags() & (uint64_t)StatepointFlags::DeoptLiveIn)
1005 return false;
1006 for (unsigned Idx = SO.getNumDeoptArgsIdx(), E = SO.getNumGCPtrIdx(); Idx < E;
1007 ++Idx) {
1008 const MachineOperand &MO = MI->getOperand(i: Idx);
1009 if (MO.isReg() && MO.getReg() == Reg)
1010 return true;
1011 }
1012 return false;
1013}
1014
1015bool LiveIntervals::checkRegMaskInterference(const LiveInterval &LI,
1016 BitVector &UsableRegs) {
1017 if (LI.empty())
1018 return false;
1019 LiveInterval::const_iterator LiveI = LI.begin(), LiveE = LI.end();
1020
1021 // Use a smaller arrays for local live ranges.
1022 ArrayRef<SlotIndex> Slots;
1023 ArrayRef<const uint32_t*> Bits;
1024 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
1025 Slots = getRegMaskSlotsInBlock(MBBNum: MBB->getNumber());
1026 Bits = getRegMaskBitsInBlock(MBBNum: MBB->getNumber());
1027 } else {
1028 Slots = getRegMaskSlots();
1029 Bits = getRegMaskBits();
1030 }
1031
1032 // We are going to enumerate all the register mask slots contained in LI.
1033 // Start with a binary search of RegMaskSlots to find a starting point.
1034 ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Range&: Slots, Value: LiveI->start);
1035 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
1036
1037 // No slots in range, LI begins after the last call.
1038 if (SlotI == SlotE)
1039 return false;
1040
1041 bool Found = false;
1042 // Utility to union regmasks.
1043 auto unionBitMask = [&](unsigned Idx) {
1044 if (!Found) {
1045 // This is the first overlap. Initialize UsableRegs to all ones.
1046 UsableRegs.clear();
1047 UsableRegs.resize(N: TRI->getNumRegs(), t: true);
1048 Found = true;
1049 }
1050 // Remove usable registers clobbered by this mask.
1051 UsableRegs.clearBitsNotInMask(Mask: Bits[Idx]);
1052 };
1053 while (true) {
1054 assert(*SlotI >= LiveI->start);
1055 // Loop over all slots overlapping this segment.
1056 while (*SlotI < LiveI->end) {
1057 // *SlotI overlaps LI. Collect mask bits.
1058 unionBitMask(SlotI - Slots.begin());
1059 if (++SlotI == SlotE)
1060 return Found;
1061 }
1062 // If segment ends with live-through use we need to collect its regmask.
1063 if (*SlotI == LiveI->end)
1064 if (MachineInstr *MI = getInstructionFromIndex(index: *SlotI))
1065 if (hasLiveThroughUse(MI, Reg: LI.reg()))
1066 unionBitMask(SlotI++ - Slots.begin());
1067 // *SlotI is beyond the current LI segment.
1068 // Special advance implementation to not miss next LiveI->end.
1069 if (++LiveI == LiveE || SlotI == SlotE || *SlotI > LI.endIndex())
1070 return Found;
1071 while (LiveI->end < *SlotI)
1072 ++LiveI;
1073 // Advance SlotI until it overlaps.
1074 while (*SlotI < LiveI->start)
1075 if (++SlotI == SlotE)
1076 return Found;
1077 }
1078}
1079
1080//===----------------------------------------------------------------------===//
1081// IntervalUpdate class.
1082//===----------------------------------------------------------------------===//
1083
1084/// Toolkit used by handleMove to trim or extend live intervals.
1085class LiveIntervals::HMEditor {
1086private:
1087 LiveIntervals& LIS;
1088 const MachineRegisterInfo& MRI;
1089 const TargetRegisterInfo& TRI;
1090 SlotIndex OldIdx;
1091 SlotIndex NewIdx;
1092 SmallPtrSet<LiveRange*, 8> Updated;
1093 bool UpdateFlags;
1094
1095public:
1096 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
1097 const TargetRegisterInfo& TRI,
1098 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
1099 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
1100 UpdateFlags(UpdateFlags) {}
1101
1102 // FIXME: UpdateFlags is a workaround that creates live intervals for all
1103 // physregs, even those that aren't needed for regalloc, in order to update
1104 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
1105 // flags, and postRA passes will use a live register utility instead.
1106 LiveRange *getRegUnitLI(MCRegUnit Unit) {
1107 if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
1108 return &LIS.getRegUnit(Unit);
1109 return LIS.getCachedRegUnit(Unit);
1110 }
1111
1112 /// Update all live ranges touched by MI, assuming a move from OldIdx to
1113 /// NewIdx.
1114 void updateAllRanges(MachineInstr *MI) {
1115 LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
1116 << *MI);
1117 bool hasRegMask = false;
1118 for (MachineOperand &MO : MI->operands()) {
1119 if (MO.isRegMask())
1120 hasRegMask = true;
1121 if (!MO.isReg())
1122 continue;
1123 if (MO.isUse()) {
1124 if (!MO.readsReg())
1125 continue;
1126 // Aggressively clear all kill flags.
1127 // They are reinserted by VirtRegRewriter.
1128 MO.setIsKill(false);
1129 }
1130
1131 Register Reg = MO.getReg();
1132 if (!Reg)
1133 continue;
1134 if (Reg.isVirtual()) {
1135 LiveInterval &LI = LIS.getInterval(Reg);
1136 if (LI.hasSubRanges()) {
1137 unsigned SubReg = MO.getSubReg();
1138 LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubIdx: SubReg)
1139 : MRI.getMaxLaneMaskForVReg(Reg);
1140 for (LiveInterval::SubRange &S : LI.subranges()) {
1141 if ((S.LaneMask & LaneMask).none())
1142 continue;
1143 updateRange(LR&: S, VRegOrUnit: VirtRegOrUnit(Reg), LaneMask: S.LaneMask);
1144 }
1145 }
1146 updateRange(LR&: LI, VRegOrUnit: VirtRegOrUnit(Reg), LaneMask: LaneBitmask::getNone());
1147 // If main range has a hole and we are moving a subrange use across
1148 // the hole updateRange() cannot properly handle it since it only
1149 // gets the LiveRange and not the whole LiveInterval. As a result
1150 // we may end up with a main range not covering all subranges.
1151 // This is extremely rare case, so let's check and reconstruct the
1152 // main range.
1153 if (LI.hasSubRanges()) {
1154 unsigned SubReg = MO.getSubReg();
1155 LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubIdx: SubReg)
1156 : MRI.getMaxLaneMaskForVReg(Reg);
1157 for (LiveInterval::SubRange &S : LI.subranges()) {
1158 if ((S.LaneMask & LaneMask).none() || LI.covers(Other: S))
1159 continue;
1160 LI.clear();
1161 LIS.constructMainRangeFromSubranges(LI);
1162 break;
1163 }
1164 }
1165
1166 continue;
1167 }
1168
1169 // For physregs, only update the regunits that actually have a
1170 // precomputed live range.
1171 for (MCRegUnit Unit : TRI.regunits(Reg: Reg.asMCReg()))
1172 if (LiveRange *LR = getRegUnitLI(Unit))
1173 updateRange(LR&: *LR, VRegOrUnit: VirtRegOrUnit(Unit), LaneMask: LaneBitmask::getNone());
1174 }
1175 if (hasRegMask)
1176 updateRegMaskSlots();
1177 }
1178
1179private:
1180 /// Update a single live range, assuming an instruction has been moved from
1181 /// OldIdx to NewIdx.
1182 void updateRange(LiveRange &LR, VirtRegOrUnit VRegOrUnit,
1183 LaneBitmask LaneMask) {
1184 if (!Updated.insert(Ptr: &LR).second)
1185 return;
1186 LLVM_DEBUG({
1187 dbgs() << " ";
1188 if (VRegOrUnit.isVirtualReg()) {
1189 dbgs() << printReg(VRegOrUnit.asVirtualReg());
1190 if (LaneMask.any())
1191 dbgs() << " L" << PrintLaneMask(LaneMask);
1192 } else {
1193 dbgs() << printRegUnit(VRegOrUnit.asMCRegUnit(), &TRI);
1194 }
1195 dbgs() << ":\t" << LR << '\n';
1196 });
1197 if (SlotIndex::isEarlierInstr(A: OldIdx, B: NewIdx))
1198 handleMoveDown(LR);
1199 else
1200 handleMoveUp(LR, VRegOrUnit, LaneMask);
1201 LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n');
1202 assert(LR.verify());
1203 }
1204
1205 /// Update LR to reflect an instruction has been moved downwards from OldIdx
1206 /// to NewIdx (OldIdx < NewIdx).
1207 void handleMoveDown(LiveRange &LR) {
1208 LiveRange::iterator E = LR.end();
1209 // Segment going into OldIdx.
1210 LiveRange::iterator OldIdxIn = LR.find(Pos: OldIdx.getBaseIndex());
1211
1212 // No value live before or after OldIdx? Nothing to do.
1213 if (OldIdxIn == E || SlotIndex::isEarlierInstr(A: OldIdx, B: OldIdxIn->start))
1214 return;
1215
1216 LiveRange::iterator OldIdxOut;
1217 // Do we have a value live-in to OldIdx?
1218 if (SlotIndex::isEarlierInstr(A: OldIdxIn->start, B: OldIdx)) {
1219 // If the live-in value already extends to NewIdx, there is nothing to do.
1220 if (SlotIndex::isEarlierEqualInstr(A: NewIdx, B: OldIdxIn->end))
1221 return;
1222 // Aggressively remove all kill flags from the old kill point.
1223 // Kill flags shouldn't be used while live intervals exist, they will be
1224 // reinserted by VirtRegRewriter.
1225 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(index: OldIdxIn->end))
1226 for (MachineOperand &MOP : mi_bundle_ops(MI&: *KillMI))
1227 if (MOP.isReg() && MOP.isUse())
1228 MOP.setIsKill(false);
1229
1230 // Is there a def before NewIdx which is not OldIdx?
1231 LiveRange::iterator Next = std::next(x: OldIdxIn);
1232 if (Next != E && !SlotIndex::isSameInstr(A: OldIdx, B: Next->start) &&
1233 SlotIndex::isEarlierInstr(A: Next->start, B: NewIdx)) {
1234 // If we are here then OldIdx was just a use but not a def. We only have
1235 // to ensure liveness extends to NewIdx.
1236 LiveRange::iterator NewIdxIn =
1237 LR.advanceTo(I: Next, Pos: NewIdx.getBaseIndex());
1238 // Extend the segment before NewIdx if necessary.
1239 if (NewIdxIn == E ||
1240 !SlotIndex::isEarlierInstr(A: NewIdxIn->start, B: NewIdx)) {
1241 LiveRange::iterator Prev = std::prev(x: NewIdxIn);
1242 Prev->end = NewIdx.getRegSlot();
1243 }
1244 // Extend OldIdxIn.
1245 OldIdxIn->end = Next->start;
1246 return;
1247 }
1248
1249 // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1250 // invalid by overlapping ranges.
1251 bool isKill = SlotIndex::isSameInstr(A: OldIdx, B: OldIdxIn->end);
1252 OldIdxIn->end = NewIdx.getRegSlot(EC: OldIdxIn->end.isEarlyClobber());
1253 // If this was not a kill, then there was no def and we're done.
1254 if (!isKill)
1255 return;
1256
1257 // Did we have a Def at OldIdx?
1258 OldIdxOut = Next;
1259 if (OldIdxOut == E || !SlotIndex::isSameInstr(A: OldIdx, B: OldIdxOut->start))
1260 return;
1261 } else {
1262 OldIdxOut = OldIdxIn;
1263 }
1264
1265 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1266 // to the segment starting there.
1267 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1268 "No def?");
1269 VNInfo *OldIdxVNI = OldIdxOut->valno;
1270 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1271
1272 // If the defined value extends beyond NewIdx, just move the beginning
1273 // of the segment to NewIdx.
1274 SlotIndex NewIdxDef = NewIdx.getRegSlot(EC: OldIdxOut->start.isEarlyClobber());
1275 if (SlotIndex::isEarlierInstr(A: NewIdxDef, B: OldIdxOut->end)) {
1276 OldIdxVNI->def = NewIdxDef;
1277 OldIdxOut->start = OldIdxVNI->def;
1278 return;
1279 }
1280
1281 // If we are here then we have a Definition at OldIdx which ends before
1282 // NewIdx.
1283
1284 // Is there an existing Def at NewIdx?
1285 LiveRange::iterator AfterNewIdx
1286 = LR.advanceTo(I: OldIdxOut, Pos: NewIdx.getRegSlot());
1287 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1288 if (!OldIdxDefIsDead &&
1289 SlotIndex::isEarlierInstr(A: OldIdxOut->end, B: NewIdxDef)) {
1290 // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1291 VNInfo *DefVNI;
1292 if (OldIdxOut != LR.begin() &&
1293 !SlotIndex::isEarlierInstr(A: std::prev(x: OldIdxOut)->end,
1294 B: OldIdxOut->start)) {
1295 // There is no gap between OldIdxOut and its predecessor anymore,
1296 // merge them.
1297 LiveRange::iterator IPrev = std::prev(x: OldIdxOut);
1298 DefVNI = OldIdxVNI;
1299 IPrev->end = OldIdxOut->end;
1300 } else {
1301 // The value is live in to OldIdx
1302 LiveRange::iterator INext = std::next(x: OldIdxOut);
1303 assert(INext != E && "Must have following segment");
1304 // We merge OldIdxOut and its successor. As we're dealing with subreg
1305 // reordering, there is always a successor to OldIdxOut in the same BB
1306 // We don't need INext->valno anymore and will reuse for the new segment
1307 // we create later.
1308 DefVNI = OldIdxVNI;
1309 INext->start = OldIdxOut->end;
1310 INext->valno->def = INext->start;
1311 }
1312 // If NewIdx is behind the last segment, extend that and append a new one.
1313 if (AfterNewIdx == E) {
1314 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1315 // one position.
1316 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1317 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1318 std::copy(first: std::next(x: OldIdxOut), last: E, result: OldIdxOut);
1319 // The last segment is undefined now, reuse it for a dead def.
1320 LiveRange::iterator NewSegment = std::prev(x: E);
1321 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1322 DefVNI);
1323 DefVNI->def = NewIdxDef;
1324
1325 LiveRange::iterator Prev = std::prev(x: NewSegment);
1326 Prev->end = NewIdxDef;
1327 } else {
1328 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1329 // one position.
1330 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1331 // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1332 std::copy(first: std::next(x: OldIdxOut), last: std::next(x: AfterNewIdx), result: OldIdxOut);
1333 LiveRange::iterator Prev = std::prev(x: AfterNewIdx);
1334 // We have two cases:
1335 if (SlotIndex::isEarlierInstr(A: Prev->start, B: NewIdxDef)) {
1336 // Case 1: NewIdx is inside a liverange. Split this liverange at
1337 // NewIdxDef into the segment "Prev" followed by "NewSegment".
1338 LiveRange::iterator NewSegment = AfterNewIdx;
1339 *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1340 Prev->valno->def = NewIdxDef;
1341
1342 *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1343 DefVNI->def = Prev->start;
1344 } else {
1345 // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1346 // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1347 *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1348 DefVNI->def = NewIdxDef;
1349 assert(DefVNI != AfterNewIdx->valno);
1350 }
1351 }
1352 return;
1353 }
1354
1355 if (AfterNewIdx != E &&
1356 SlotIndex::isSameInstr(A: AfterNewIdx->start, B: NewIdxDef)) {
1357 // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1358 // that value.
1359 assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1360 LR.removeValNo(ValNo: OldIdxVNI);
1361 } else {
1362 // There was no existing def at NewIdx. We need to create a dead def
1363 // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1364 // a new segment at the place where we want to construct the dead def.
1365 // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1366 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1367 assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1368 std::copy(first: std::next(x: OldIdxOut), last: AfterNewIdx, result: OldIdxOut);
1369 // We can reuse OldIdxVNI now.
1370 LiveRange::iterator NewSegment = std::prev(x: AfterNewIdx);
1371 VNInfo *NewSegmentVNI = OldIdxVNI;
1372 NewSegmentVNI->def = NewIdxDef;
1373 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1374 NewSegmentVNI);
1375 }
1376 }
1377
1378 /// Update LR to reflect an instruction has been moved upwards from OldIdx
1379 /// to NewIdx (NewIdx < OldIdx).
1380 void handleMoveUp(LiveRange &LR, VirtRegOrUnit VRegOrUnit,
1381 LaneBitmask LaneMask) {
1382 LiveRange::iterator E = LR.end();
1383 // Segment going into OldIdx.
1384 LiveRange::iterator OldIdxIn = LR.find(Pos: OldIdx.getBaseIndex());
1385
1386 // No value live before or after OldIdx? Nothing to do.
1387 if (OldIdxIn == E || SlotIndex::isEarlierInstr(A: OldIdx, B: OldIdxIn->start))
1388 return;
1389
1390 LiveRange::iterator OldIdxOut;
1391 // Do we have a value live-in to OldIdx?
1392 if (SlotIndex::isEarlierInstr(A: OldIdxIn->start, B: OldIdx)) {
1393 // If the live-in value isn't killed here, then we have no Def at
1394 // OldIdx, moreover the value must be live at NewIdx so there is nothing
1395 // to do.
1396 bool isKill = SlotIndex::isSameInstr(A: OldIdx, B: OldIdxIn->end);
1397 if (!isKill)
1398 return;
1399
1400 // At this point we have to move OldIdxIn->end back to the nearest
1401 // previous use or (dead-)def but no further than NewIdx.
1402 SlotIndex DefBeforeOldIdx
1403 = std::max(a: OldIdxIn->start.getDeadSlot(),
1404 b: NewIdx.getRegSlot(EC: OldIdxIn->end.isEarlyClobber()));
1405 OldIdxIn->end = findLastUseBefore(Before: DefBeforeOldIdx, VRegOrUnit, LaneMask);
1406
1407 // Did we have a Def at OldIdx? If not we are done now.
1408 OldIdxOut = std::next(x: OldIdxIn);
1409 if (OldIdxOut == E || !SlotIndex::isSameInstr(A: OldIdx, B: OldIdxOut->start))
1410 return;
1411 } else {
1412 OldIdxOut = OldIdxIn;
1413 OldIdxIn = OldIdxOut != LR.begin() ? std::prev(x: OldIdxOut) : E;
1414 }
1415
1416 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1417 // to the segment starting there.
1418 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1419 "No def?");
1420 VNInfo *OldIdxVNI = OldIdxOut->valno;
1421 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1422 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1423
1424 // Is there an existing def at NewIdx?
1425 SlotIndex NewIdxDef = NewIdx.getRegSlot(EC: OldIdxOut->start.isEarlyClobber());
1426 LiveRange::iterator NewIdxOut = LR.find(Pos: NewIdx.getRegSlot());
1427 if (SlotIndex::isSameInstr(A: NewIdxOut->start, B: NewIdx)) {
1428 assert(NewIdxOut->valno != OldIdxVNI &&
1429 "Same value defined more than once?");
1430 // If OldIdx was a dead def remove it.
1431 if (!OldIdxDefIsDead) {
1432 // Remove segment starting at NewIdx and move begin of OldIdxOut to
1433 // NewIdx so it can take its place.
1434 OldIdxVNI->def = NewIdxDef;
1435 OldIdxOut->start = NewIdxDef;
1436 LR.removeValNo(ValNo: NewIdxOut->valno);
1437 } else {
1438 // Simply remove the dead def at OldIdx.
1439 LR.removeValNo(ValNo: OldIdxVNI);
1440 }
1441 } else {
1442 // Previously nothing was live after NewIdx, so all we have to do now is
1443 // move the begin of OldIdxOut to NewIdx.
1444 if (!OldIdxDefIsDead) {
1445 // Do we have any intermediate Defs between OldIdx and NewIdx?
1446 if (OldIdxIn != E &&
1447 SlotIndex::isEarlierInstr(A: NewIdxDef, B: OldIdxIn->start)) {
1448 // OldIdx is not a dead def and NewIdx is before predecessor start.
1449 LiveRange::iterator NewIdxIn = NewIdxOut;
1450 assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1451 const SlotIndex SplitPos = NewIdxDef;
1452 OldIdxVNI = OldIdxIn->valno;
1453
1454 SlotIndex NewDefEndPoint = std::next(x: NewIdxIn)->end;
1455 LiveRange::iterator Prev = std::prev(x: OldIdxIn);
1456 if (OldIdxIn != LR.begin() &&
1457 SlotIndex::isEarlierInstr(A: NewIdx, B: Prev->end)) {
1458 // If the segment before OldIdx read a value defined earlier than
1459 // NewIdx, the moved instruction also reads and forwards that
1460 // value. Extend the lifetime of the new def point.
1461
1462 // Extend to where the previous range started, unless there is
1463 // another redef first.
1464 NewDefEndPoint = std::min(a: OldIdxIn->start,
1465 b: std::next(x: NewIdxOut)->start);
1466 }
1467
1468 // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1469 OldIdxOut->valno->def = OldIdxIn->start;
1470 *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1471 OldIdxOut->valno);
1472 // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1473 // We Slide [NewIdxIn, OldIdxIn) down one position.
1474 // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1475 // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1476 std::copy_backward(first: NewIdxIn, last: OldIdxIn, result: OldIdxOut);
1477 // NewIdxIn is now considered undef so we can reuse it for the moved
1478 // value.
1479 LiveRange::iterator NewSegment = NewIdxIn;
1480 LiveRange::iterator Next = std::next(x: NewSegment);
1481 if (SlotIndex::isEarlierInstr(A: Next->start, B: NewIdx)) {
1482 // There is no gap between NewSegment and its predecessor.
1483 *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1484 Next->valno);
1485
1486 *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
1487 Next->valno->def = SplitPos;
1488 } else {
1489 // There is a gap between NewSegment and its predecessor
1490 // Value becomes live in.
1491 *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1492 NewSegment->valno->def = SplitPos;
1493 }
1494 } else {
1495 // Leave the end point of a live def.
1496 OldIdxOut->start = NewIdxDef;
1497 OldIdxVNI->def = NewIdxDef;
1498 if (OldIdxIn != E && SlotIndex::isEarlierInstr(A: NewIdx, B: OldIdxIn->end))
1499 OldIdxIn->end = NewIdxDef;
1500 }
1501 } else if (OldIdxIn != E
1502 && SlotIndex::isEarlierInstr(A: NewIdxOut->start, B: NewIdx)
1503 && SlotIndex::isEarlierInstr(A: NewIdx, B: NewIdxOut->end)) {
1504 // OldIdxVNI is a dead def that has been moved into the middle of
1505 // another value in LR. That can happen when LR is a whole register,
1506 // but the dead def is a write to a subreg that is dead at NewIdx.
1507 // The dead def may have been moved across other values
1508 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1509 // down one position.
1510 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1511 // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1512 std::copy_backward(first: NewIdxOut, last: OldIdxOut, result: std::next(x: OldIdxOut));
1513 // Modify the segment at NewIdxOut and the following segment to meet at
1514 // the point of the dead def, with the following segment getting
1515 // OldIdxVNI as its value number.
1516 *NewIdxOut = LiveRange::Segment(
1517 NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1518 *(NewIdxOut + 1) = LiveRange::Segment(
1519 NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1520 OldIdxVNI->def = NewIdxDef;
1521 // Retag the segments that were shifted down from [NewIdxOut + 2,
1522 // OldIdxOut]. Retagging can make a segment touch another segment with
1523 // the same value number, so merge as we go. Stop at the original end
1524 // slot instead of using a segment count because merging may erase
1525 // segments.
1526 const SlotIndex RetagEnd = OldIdxOut->end;
1527 for (LiveRange::iterator Idx = NewIdxOut + 2;
1528 Idx != LR.end() && Idx->start < RetagEnd;) {
1529 Idx->valno = OldIdxVNI;
1530 Idx = std::next(x: LR.mergeAdjacentSegments(I: Idx));
1531 }
1532 // Aggressively remove all dead flags from the former dead definition.
1533 // Kill/dead flags shouldn't be used while live intervals exist; they
1534 // will be reinserted by VirtRegRewriter.
1535 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(index: NewIdx))
1536 for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1537 if (MO->isReg() && !MO->isUse())
1538 MO->setIsDead(false);
1539 } else {
1540 // OldIdxVNI is a dead def. It may have been moved across other values
1541 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1542 // down one position.
1543 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1544 // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1545 std::copy_backward(first: NewIdxOut, last: OldIdxOut, result: std::next(x: OldIdxOut));
1546 // OldIdxVNI can be reused now to build a new dead def segment.
1547 LiveRange::iterator NewSegment = NewIdxOut;
1548 VNInfo *NewSegmentVNI = OldIdxVNI;
1549 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1550 NewSegmentVNI);
1551 NewSegmentVNI->def = NewIdxDef;
1552 }
1553 }
1554 }
1555
1556 void updateRegMaskSlots() {
1557 SmallVectorImpl<SlotIndex>::iterator RI =
1558 llvm::lower_bound(Range&: LIS.RegMaskSlots, Value&: OldIdx);
1559 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1560 "No RegMask at OldIdx.");
1561 *RI = NewIdx.getRegSlot();
1562 assert((RI == LIS.RegMaskSlots.begin() ||
1563 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1564 "Cannot move regmask instruction above another call");
1565 assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1566 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1567 "Cannot move regmask instruction below another call");
1568 }
1569
1570 // Return the last use of reg between NewIdx and OldIdx.
1571 SlotIndex findLastUseBefore(SlotIndex Before, VirtRegOrUnit VRegOrUnit,
1572 LaneBitmask LaneMask) {
1573 if (VRegOrUnit.isVirtualReg()) {
1574 SlotIndex LastUse = Before;
1575 for (MachineOperand &MO :
1576 MRI.use_nodbg_operands(Reg: VRegOrUnit.asVirtualReg())) {
1577 if (MO.isUndef())
1578 continue;
1579 unsigned SubReg = MO.getSubReg();
1580 if (SubReg != 0 && LaneMask.any()
1581 && (TRI.getSubRegIndexLaneMask(SubIdx: SubReg) & LaneMask).none())
1582 continue;
1583
1584 const MachineInstr &MI = *MO.getParent();
1585 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1586 if (InstSlot > LastUse && InstSlot < OldIdx)
1587 LastUse = InstSlot.getRegSlot();
1588 }
1589 return LastUse;
1590 }
1591
1592 // This is a regunit interval, so scanning the use list could be very
1593 // expensive. Scan upwards from OldIdx instead.
1594 assert(Before < OldIdx && "Expected upwards move");
1595 SlotIndexes *Indexes = LIS.getSlotIndexes();
1596 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(index: Before);
1597
1598 // OldIdx may not correspond to an instruction any longer, so set MII to
1599 // point to the next instruction after OldIdx, or MBB->end().
1600 MachineBasicBlock::iterator MII = MBB->end();
1601 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1602 index: Indexes->getNextNonNullIndex(Index: OldIdx)))
1603 if (MI->getParent() == MBB)
1604 MII = MI;
1605
1606 MachineBasicBlock::iterator Begin = MBB->begin();
1607 while (MII != Begin) {
1608 if ((--MII)->isDebugOrPseudoInstr())
1609 continue;
1610 SlotIndex Idx = Indexes->getInstructionIndex(MI: *MII);
1611
1612 // Stop searching when Before is reached.
1613 if (!SlotIndex::isEarlierInstr(A: Before, B: Idx))
1614 return Before;
1615
1616 // Check if MII uses Reg.
1617 for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1618 if (MO->isReg() && !MO->isUndef() && MO->getReg().isPhysical() &&
1619 TRI.hasRegUnit(Reg: MO->getReg(), RegUnit: VRegOrUnit.asMCRegUnit()))
1620 return Idx.getRegSlot();
1621 }
1622 // Didn't reach Before. It must be the first instruction in the block.
1623 return Before;
1624 }
1625};
1626
1627void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
1628 // It is fine to move a bundle as a whole, but not an individual instruction
1629 // inside it.
1630 assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
1631 "Cannot move instruction in bundle");
1632 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1633 Indexes->removeMachineInstrFromMaps(MI);
1634 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1635 assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1636 OldIndex < getMBBEndIdx(MI.getParent()) &&
1637 "Cannot handle moves across basic block boundaries.");
1638
1639 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1640 HME.updateAllRanges(MI: &MI);
1641}
1642
1643void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart,
1644 bool UpdateFlags) {
1645 assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
1646 "Bundle start is not a bundle");
1647 SmallVector<SlotIndex, 16> ToProcess;
1648 const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI&: BundleStart);
1649 auto BundleEnd = getBundleEnd(I: BundleStart.getIterator());
1650
1651 auto I = BundleStart.getIterator();
1652 I++;
1653 while (I != BundleEnd) {
1654 if (!Indexes->hasIndex(instr: *I))
1655 continue;
1656 SlotIndex OldIndex = Indexes->getInstructionIndex(MI: *I, IgnoreBundle: true);
1657 ToProcess.push_back(Elt: OldIndex);
1658 Indexes->removeMachineInstrFromMaps(MI&: *I, AllowBundled: true);
1659 I++;
1660 }
1661 for (SlotIndex OldIndex : ToProcess) {
1662 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1663 HME.updateAllRanges(MI: &BundleStart);
1664 }
1665
1666 // Fix up dead defs
1667 const SlotIndex Index = getInstructionIndex(Instr: BundleStart);
1668 for (MachineOperand &MO : BundleStart.operands()) {
1669 if (!MO.isReg())
1670 continue;
1671 Register Reg = MO.getReg();
1672 if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
1673 LiveInterval &LI = getInterval(Reg);
1674 LiveQueryResult LRQ = LI.Query(Idx: Index);
1675 if (LRQ.isDeadDef())
1676 MO.setIsDead();
1677 }
1678 }
1679}
1680
1681void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1682 const MachineBasicBlock::iterator End,
1683 const SlotIndex EndIdx, LiveRange &LR,
1684 const Register Reg,
1685 LaneBitmask LaneMask) {
1686 LiveInterval::iterator LII = LR.find(Pos: EndIdx);
1687 SlotIndex lastUseIdx;
1688 if (LII != LR.end() && LII->start < EndIdx) {
1689 lastUseIdx = LII->end;
1690 } else if (LII == LR.begin()) {
1691 // We may not have a liverange at all if this is a subregister untouched
1692 // between \p Begin and \p End.
1693 } else {
1694 --LII;
1695 }
1696
1697 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1698 --I;
1699 MachineInstr &MI = *I;
1700 if (MI.isDebugOrPseudoInstr())
1701 continue;
1702
1703 SlotIndex instrIdx = getInstructionIndex(Instr: MI);
1704 bool isStartValid = getInstructionFromIndex(index: LII->start);
1705 bool isEndValid = getInstructionFromIndex(index: LII->end);
1706
1707 // FIXME: This doesn't currently handle early-clobber or multiple removed
1708 // defs inside of the region to repair.
1709 for (const MachineOperand &MO : MI.operands()) {
1710 if (!MO.isReg() || MO.getReg() != Reg)
1711 continue;
1712
1713 unsigned SubReg = MO.getSubReg();
1714 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubIdx: SubReg);
1715 if ((Mask & LaneMask).none())
1716 continue;
1717
1718 if (MO.isDef()) {
1719 if (!isStartValid) {
1720 if (LII->end.isDead()) {
1721 LII = LR.removeSegment(I: LII, RemoveDeadValNo: true);
1722 if (LII != LR.begin())
1723 --LII;
1724 } else {
1725 LII->start = instrIdx.getRegSlot();
1726 LII->valno->def = instrIdx.getRegSlot();
1727 if (MO.getSubReg() && !MO.isUndef())
1728 lastUseIdx = instrIdx.getRegSlot();
1729 else
1730 lastUseIdx = SlotIndex();
1731 continue;
1732 }
1733 }
1734
1735 if (!lastUseIdx.isValid()) {
1736 VNInfo *VNI = LR.getNextValue(Def: instrIdx.getRegSlot(), VNInfoAllocator);
1737 LiveRange::Segment S(instrIdx.getRegSlot(),
1738 instrIdx.getDeadSlot(), VNI);
1739 LII = LR.addSegment(S);
1740 } else if (LII->start != instrIdx.getRegSlot()) {
1741 VNInfo *VNI = LR.getNextValue(Def: instrIdx.getRegSlot(), VNInfoAllocator);
1742 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1743 LII = LR.addSegment(S);
1744 }
1745
1746 if (MO.getSubReg() && !MO.isUndef())
1747 lastUseIdx = instrIdx.getRegSlot();
1748 else
1749 lastUseIdx = SlotIndex();
1750 } else if (MO.isUse()) {
1751 // FIXME: This should probably be handled outside of this branch,
1752 // either as part of the def case (for defs inside of the region) or
1753 // after the loop over the region.
1754 if (!isEndValid && !LII->end.isBlock())
1755 LII->end = instrIdx.getRegSlot();
1756 if (!lastUseIdx.isValid())
1757 lastUseIdx = instrIdx.getRegSlot();
1758 }
1759 }
1760 }
1761
1762 bool isStartValid = getInstructionFromIndex(index: LII->start);
1763 if (!isStartValid && LII->end.isDead())
1764 LR.removeSegment(S: *LII, RemoveDeadValNo: true);
1765}
1766
1767void
1768LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1769 MachineBasicBlock::iterator Begin,
1770 MachineBasicBlock::iterator End,
1771 ArrayRef<Register> OrigRegs) {
1772 // Find anchor points, which are at the beginning/end of blocks or at
1773 // instructions that already have indexes.
1774 while (Begin != MBB->begin() && !Indexes->hasIndex(instr: *std::prev(x: Begin)))
1775 --Begin;
1776 while (End != MBB->end() && !Indexes->hasIndex(instr: *End))
1777 ++End;
1778
1779 SlotIndex EndIdx;
1780 if (End == MBB->end())
1781 EndIdx = getMBBEndIdx(mbb: MBB).getPrevSlot();
1782 else
1783 EndIdx = getInstructionIndex(Instr: *End);
1784
1785 Indexes->repairIndexesInRange(MBB, Begin, End);
1786
1787 // Make sure a live interval exists for all register operands in the range.
1788 SmallVector<Register> RegsToRepair(OrigRegs);
1789 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1790 --I;
1791 MachineInstr &MI = *I;
1792 if (MI.isDebugOrPseudoInstr())
1793 continue;
1794 for (const MachineOperand &MO : MI.operands()) {
1795 if (MO.isReg() && MO.getReg().isVirtual()) {
1796 Register Reg = MO.getReg();
1797 if (MO.getSubReg() && hasInterval(Reg) &&
1798 MRI->shouldTrackSubRegLiveness(VReg: Reg)) {
1799 LiveInterval &LI = getInterval(Reg);
1800 if (!LI.hasSubRanges()) {
1801 // If the new instructions refer to subregs but the old instructions
1802 // did not, throw away any old live interval so it will be
1803 // recomputed with subranges.
1804 removeInterval(Reg);
1805 } else if (MO.isDef()) {
1806 // Similarly if a subreg def has no precise subrange match then
1807 // assume we need to recompute all subranges.
1808 unsigned SubReg = MO.getSubReg();
1809 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubIdx: SubReg);
1810 if (llvm::none_of(Range: LI.subranges(),
1811 P: [Mask](LiveInterval::SubRange &SR) {
1812 return SR.LaneMask == Mask;
1813 })) {
1814 removeInterval(Reg);
1815 }
1816 }
1817 }
1818 if (!hasInterval(Reg)) {
1819 createAndComputeVirtRegInterval(Reg);
1820 // Don't bother to repair a freshly calculated live interval.
1821 llvm::erase(C&: RegsToRepair, V: Reg);
1822 }
1823 }
1824 }
1825 }
1826
1827 for (Register Reg : RegsToRepair) {
1828 if (!Reg.isVirtual())
1829 continue;
1830
1831 LiveInterval &LI = getInterval(Reg);
1832 // FIXME: Should we support undefs that gain defs?
1833 if (!LI.hasAtLeastOneValue())
1834 continue;
1835
1836 for (LiveInterval::SubRange &S : LI.subranges())
1837 repairOldRegInRange(Begin, End, EndIdx, LR&: S, Reg, LaneMask: S.LaneMask);
1838 LI.removeEmptySubRanges();
1839
1840 repairOldRegInRange(Begin, End, EndIdx, LR&: LI, Reg);
1841 }
1842}
1843
1844void LiveIntervals::removePhysRegDefAt(MCRegister Reg, SlotIndex Pos) {
1845 for (MCRegUnit Unit : TRI->regunits(Reg)) {
1846 if (LiveRange *LR = getCachedRegUnit(Unit))
1847 if (VNInfo *VNI = LR->getVNInfoAt(Idx: Pos))
1848 LR->removeValNo(ValNo: VNI);
1849 }
1850}
1851
1852void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1853 // LI may not have the main range computed yet, but its subranges may
1854 // be present.
1855 VNInfo *VNI = LI.getVNInfoAt(Idx: Pos);
1856 if (VNI != nullptr) {
1857 assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1858 LI.removeValNo(ValNo: VNI);
1859 }
1860
1861 // Also remove the value defined in subranges.
1862 for (LiveInterval::SubRange &S : LI.subranges()) {
1863 if (VNInfo *SVNI = S.getVNInfoAt(Idx: Pos))
1864 if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1865 S.removeValNo(ValNo: SVNI);
1866 }
1867 LI.removeEmptySubRanges();
1868}
1869
1870void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1871 SmallVectorImpl<LiveInterval*> &SplitLIs) {
1872 ConnectedVNInfoEqClasses ConEQ(*this);
1873 unsigned NumComp = ConEQ.Classify(LR: LI);
1874 if (NumComp <= 1)
1875 return;
1876 LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1877 Register Reg = LI.reg();
1878 for (unsigned I = 1; I < NumComp; ++I) {
1879 Register NewVReg = MRI->cloneVirtualRegister(VReg: Reg);
1880 LiveInterval &NewLI = createEmptyInterval(Reg: NewVReg);
1881 SplitLIs.push_back(Elt: &NewLI);
1882 }
1883 ConEQ.Distribute(LI, LIV: SplitLIs.data(), MRI&: *MRI);
1884}
1885
1886void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
1887 assert(LICalc && "LICalc not initialized.");
1888 LICalc->reset(mf: MF, SI: getSlotIndexes(), MDT: DomTree, VNIA: &getVNInfoAllocator());
1889 LICalc->constructMainRangeFromSubranges(LI);
1890}
1891