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