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