1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "LiveRangeCalc.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/BlockFrequency.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "regalloc"
46 char LiveIntervals::ID = 0;
47 char &llvm::LiveIntervalsID = LiveIntervals::ID;
48 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
49 "Live Interval Analysis", false, false)
50 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
51 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
52 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
53 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
54 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
55 "Live Interval Analysis", false, false)
58 static cl::opt<bool> EnablePrecomputePhysRegs(
59 "precompute-phys-liveness", cl::Hidden,
60 cl::desc("Eagerly compute live intervals for all physreg units."));
62 static bool EnablePrecomputePhysRegs = false;
65 static cl::opt<bool> EnableSubRegLiveness(
66 "enable-subreg-liveness", cl::Hidden, cl::init(true),
67 cl::desc("Enable subregister liveness tracking."));
70 cl::opt<bool> UseSegmentSetForPhysRegs(
71 "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
73 "Use segment set for the computation of the live ranges of physregs."));
76 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<AAResultsWrapperPass>();
79 AU.addPreserved<AAResultsWrapperPass>();
80 // LiveVariables isn't really required by this analysis, it is only required
81 // here to make sure it is live during TwoAddressInstructionPass and
82 // PHIElimination. This is temporary.
83 AU.addRequired<LiveVariables>();
84 AU.addPreserved<LiveVariables>();
85 AU.addPreservedID(MachineLoopInfoID);
86 AU.addRequiredTransitiveID(MachineDominatorsID);
87 AU.addPreservedID(MachineDominatorsID);
88 AU.addPreserved<SlotIndexes>();
89 AU.addRequiredTransitive<SlotIndexes>();
90 MachineFunctionPass::getAnalysisUsage(AU);
93 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
94 DomTree(nullptr), LRCalc(nullptr) {
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
98 LiveIntervals::~LiveIntervals() {
102 void LiveIntervals::releaseMemory() {
103 // Free the live intervals themselves.
104 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
105 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
106 VirtRegIntervals.clear();
107 RegMaskSlots.clear();
109 RegMaskBlocks.clear();
111 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
112 delete RegUnitRanges[i];
113 RegUnitRanges.clear();
115 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
116 VNInfoAllocator.Reset();
119 /// runOnMachineFunction - calculates LiveIntervals
121 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
123 MRI = &MF->getRegInfo();
124 TRI = MF->getSubtarget().getRegisterInfo();
125 TII = MF->getSubtarget().getInstrInfo();
126 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
127 Indexes = &getAnalysis<SlotIndexes>();
128 DomTree = &getAnalysis<MachineDominatorTree>();
130 if (EnableSubRegLiveness && MF->getSubtarget().enableSubRegLiveness())
131 MRI->enableSubRegLiveness(true);
134 LRCalc = new LiveRangeCalc();
136 // Allocate space for all virtual registers.
137 VirtRegIntervals.resize(MRI->getNumVirtRegs());
141 computeLiveInRegUnits();
143 if (EnablePrecomputePhysRegs) {
144 // For stress testing, precompute live ranges of all physical register
145 // units, including reserved registers.
146 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
153 /// print - Implement the dump method.
154 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
155 OS << "********** INTERVALS **********\n";
157 // Dump the regunits.
158 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
159 if (LiveRange *LR = RegUnitRanges[i])
160 OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
162 // Dump the virtregs.
163 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
164 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
165 if (hasInterval(Reg))
166 OS << getInterval(Reg) << '\n';
170 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
171 OS << ' ' << RegMaskSlots[i];
177 void LiveIntervals::printInstrs(raw_ostream &OS) const {
178 OS << "********** MACHINEINSTRS **********\n";
179 MF->print(OS, Indexes);
182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
183 void LiveIntervals::dumpInstrs() const {
188 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
189 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
190 llvm::huge_valf : 0.0F;
191 return new LiveInterval(reg, Weight);
195 /// computeVirtRegInterval - Compute the live interval of a virtual register,
196 /// based on defs and uses.
197 void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
198 assert(LRCalc && "LRCalc not initialized.");
199 assert(LI.empty() && "Should only compute empty intervals.");
200 bool ShouldTrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(LI.reg);
201 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
202 LRCalc->calculate(LI, ShouldTrackSubRegLiveness);
203 bool SeparatedComponents = computeDeadValues(LI, nullptr);
204 if (SeparatedComponents) {
205 assert(ShouldTrackSubRegLiveness
206 && "Separated components should only occur for unused subreg defs");
207 SmallVector<LiveInterval*, 8> SplitLIs;
208 splitSeparateComponents(LI, SplitLIs);
212 void LiveIntervals::computeVirtRegs() {
213 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
214 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
215 if (MRI->reg_nodbg_empty(Reg))
217 createAndComputeVirtRegInterval(Reg);
221 void LiveIntervals::computeRegMasks() {
222 RegMaskBlocks.resize(MF->getNumBlockIDs());
224 // Find all instructions with regmask operands.
225 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
227 MachineBasicBlock *MBB = &*MBBI;
228 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
229 RMB.first = RegMaskSlots.size();
230 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
232 for (const MachineOperand &MO : MI->operands()) {
235 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
236 RegMaskBits.push_back(MO.getRegMask());
238 // Compute the number of register mask instructions in this block.
239 RMB.second = RegMaskSlots.size() - RMB.first;
243 //===----------------------------------------------------------------------===//
244 // Register Unit Liveness
245 //===----------------------------------------------------------------------===//
247 // Fixed interference typically comes from ABI boundaries: Function arguments
248 // and return values are passed in fixed registers, and so are exception
249 // pointers entering landing pads. Certain instructions require values to be
250 // present in specific registers. That is also represented through fixed
254 /// computeRegUnitInterval - Compute the live range of a register unit, based
255 /// on the uses and defs of aliasing registers. The range should be empty,
256 /// or contain only dead phi-defs from ABI blocks.
257 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
258 assert(LRCalc && "LRCalc not initialized.");
259 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
261 // The physregs aliasing Unit are the roots and their super-registers.
262 // Create all values as dead defs before extending to uses. Note that roots
263 // may share super-registers. That's OK because createDeadDefs() is
264 // idempotent. It is very rare for a register unit to have multiple roots, so
265 // uniquing super-registers is probably not worthwhile.
266 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
267 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
268 Supers.isValid(); ++Supers) {
269 if (!MRI->reg_empty(*Supers))
270 LRCalc->createDeadDefs(LR, *Supers);
274 // Now extend LR to reach all uses.
275 // Ignore uses of reserved registers. We only track defs of those.
276 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
277 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
278 Supers.isValid(); ++Supers) {
279 unsigned Reg = *Supers;
280 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
281 LRCalc->extendToUses(LR, Reg);
285 // Flush the segment set to the segment vector.
286 if (UseSegmentSetForPhysRegs)
287 LR.flushSegmentSet();
291 /// computeLiveInRegUnits - Precompute the live ranges of any register units
292 /// that are live-in to an ABI block somewhere. Register values can appear
293 /// without a corresponding def when entering the entry block or a landing pad.
295 void LiveIntervals::computeLiveInRegUnits() {
296 RegUnitRanges.resize(TRI->getNumRegUnits());
297 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
299 // Keep track of the live range sets allocated.
300 SmallVector<unsigned, 8> NewRanges;
302 // Check all basic blocks for live-ins.
303 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
305 const MachineBasicBlock *MBB = &*MFI;
307 // We only care about ABI blocks: Entry + landing pads.
308 if ((MFI != MF->begin() && !MBB->isEHPad()) || MBB->livein_empty())
311 // Create phi-defs at Begin for all live-in registers.
312 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
313 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
314 for (const auto &LI : MBB->liveins()) {
315 for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
316 unsigned Unit = *Units;
317 LiveRange *LR = RegUnitRanges[Unit];
319 // Use segment set to speed-up initial computation of the live range.
320 LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
321 NewRanges.push_back(Unit);
323 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
325 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
328 DEBUG(dbgs() << '\n');
330 DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
332 // Compute the 'normal' part of the ranges.
333 for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
334 unsigned Unit = NewRanges[i];
335 computeRegUnitRange(*RegUnitRanges[Unit], Unit);
340 static void createSegmentsForValues(LiveRange &LR,
341 iterator_range<LiveInterval::vni_iterator> VNIs) {
342 for (auto VNI : VNIs) {
345 SlotIndex Def = VNI->def;
346 LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
350 typedef SmallVector<std::pair<SlotIndex, VNInfo*>, 16> ShrinkToUsesWorkList;
352 static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
353 ShrinkToUsesWorkList &WorkList,
354 const LiveRange &OldRange) {
355 // Keep track of the PHIs that are in use.
356 SmallPtrSet<VNInfo*, 8> UsedPHIs;
357 // Blocks that have already been added to WorkList as live-out.
358 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
360 // Extend intervals to reach all uses in WorkList.
361 while (!WorkList.empty()) {
362 SlotIndex Idx = WorkList.back().first;
363 VNInfo *VNI = WorkList.back().second;
365 const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
366 SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
368 // Extend the live range for VNI to be live at Idx.
369 if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
370 assert(ExtVNI == VNI && "Unexpected existing value number");
372 // Is this a PHIDef we haven't seen before?
373 if (!VNI->isPHIDef() || VNI->def != BlockStart ||
374 !UsedPHIs.insert(VNI).second)
376 // The PHI is live, make sure the predecessors are live-out.
377 for (auto &Pred : MBB->predecessors()) {
378 if (!LiveOut.insert(Pred).second)
380 SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
381 // A predecessor is not required to have a live-out value for a PHI.
382 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
383 WorkList.push_back(std::make_pair(Stop, PVNI));
388 // VNI is live-in to MBB.
389 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
390 LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
392 // Make sure VNI is live-out from the predecessors.
393 for (auto &Pred : MBB->predecessors()) {
394 if (!LiveOut.insert(Pred).second)
396 SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
397 assert(OldRange.getVNInfoBefore(Stop) == VNI &&
398 "Wrong value out of predecessor");
399 WorkList.push_back(std::make_pair(Stop, VNI));
404 bool LiveIntervals::shrinkToUses(LiveInterval *li,
405 SmallVectorImpl<MachineInstr*> *dead) {
406 DEBUG(dbgs() << "Shrink: " << *li << '\n');
407 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
408 && "Can only shrink virtual registers");
410 // Shrink subregister live ranges.
411 bool NeedsCleanup = false;
412 for (LiveInterval::SubRange &S : li->subranges()) {
413 shrinkToUses(S, li->reg);
418 li->removeEmptySubRanges();
420 // Find all the values used, including PHI kills.
421 ShrinkToUsesWorkList WorkList;
423 // Visit all instructions reading li->reg.
424 for (MachineRegisterInfo::reg_instr_iterator
425 I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
427 MachineInstr *UseMI = &*(I++);
428 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
430 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
431 LiveQueryResult LRQ = li->Query(Idx);
432 VNInfo *VNI = LRQ.valueIn();
434 // This shouldn't happen: readsVirtualRegister returns true, but there is
435 // no live value. It is likely caused by a target getting <undef> flags
437 DEBUG(dbgs() << Idx << '\t' << *UseMI
438 << "Warning: Instr claims to read non-existent value in "
442 // Special case: An early-clobber tied operand reads and writes the
443 // register one slot early.
444 if (VNInfo *DefVNI = LRQ.valueDefined())
447 WorkList.push_back(std::make_pair(Idx, VNI));
450 // Create new live ranges with only minimal live segments per def.
452 createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
453 extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
455 // Move the trimmed segments back.
456 li->segments.swap(NewLR.segments);
458 // Handle dead values.
459 bool CanSeparate = computeDeadValues(*li, dead);
460 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
464 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
465 SmallVectorImpl<MachineInstr*> *dead) {
466 bool MayHaveSplitComponents = false;
467 for (auto VNI : LI.valnos) {
470 SlotIndex Def = VNI->def;
471 LiveRange::iterator I = LI.FindSegmentContaining(Def);
472 assert(I != LI.end() && "Missing segment for VNI");
474 // Is the register live before? Otherwise we may have to add a read-undef
475 // flag for subregister defs.
476 bool DeadBeforeDef = false;
477 unsigned VReg = LI.reg;
478 if (MRI->shouldTrackSubRegLiveness(VReg)) {
479 if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
480 MachineInstr *MI = getInstructionFromIndex(Def);
481 MI->addRegisterDefReadUndef(VReg);
482 DeadBeforeDef = true;
486 if (I->end != Def.getDeadSlot())
488 if (VNI->isPHIDef()) {
489 // This is a dead PHI. Remove it.
492 DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
493 MayHaveSplitComponents = true;
495 // This is a dead def. Make sure the instruction knows.
496 MachineInstr *MI = getInstructionFromIndex(Def);
497 assert(MI && "No instruction defining live value");
498 MI->addRegisterDead(VReg, TRI);
500 // If we have a dead def that is completely separate from the rest of
501 // the liverange then we rewrite it to use a different VReg to not violate
502 // the rule that the liveness of a virtual register forms a connected
503 // component. This should only happen if subregister liveness is tracked.
505 MayHaveSplitComponents = true;
507 if (dead && MI->allDefsAreDead()) {
508 DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
513 return MayHaveSplitComponents;
516 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg)
518 DEBUG(dbgs() << "Shrink: " << SR << '\n');
519 assert(TargetRegisterInfo::isVirtualRegister(Reg)
520 && "Can only shrink virtual registers");
521 // Find all the values used, including PHI kills.
522 ShrinkToUsesWorkList WorkList;
524 // Visit all instructions reading Reg.
526 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
527 MachineInstr *UseMI = MO.getParent();
528 if (UseMI->isDebugValue())
530 // Maybe the operand is for a subregister we don't care about.
531 unsigned SubReg = MO.getSubReg();
533 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
534 if ((LaneMask & SR.LaneMask) == 0)
537 // We only need to visit each instruction once.
538 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
543 LiveQueryResult LRQ = SR.Query(Idx);
544 VNInfo *VNI = LRQ.valueIn();
545 // For Subranges it is possible that only undef values are left in that
546 // part of the subregister, so there is no real liverange at the use
550 // Special case: An early-clobber tied operand reads and writes the
551 // register one slot early.
552 if (VNInfo *DefVNI = LRQ.valueDefined())
555 WorkList.push_back(std::make_pair(Idx, VNI));
558 // Create a new live ranges with only minimal live segments per def.
560 createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
561 extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
563 // Move the trimmed ranges back.
564 SR.segments.swap(NewLR.segments);
566 // Remove dead PHI value numbers
567 for (auto VNI : SR.valnos) {
570 const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
571 assert(Segment != nullptr && "Missing segment for VNI");
572 if (Segment->end != VNI->def.getDeadSlot())
574 if (VNI->isPHIDef()) {
575 // This is a dead PHI. Remove it.
577 SR.removeSegment(*Segment);
578 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
582 DEBUG(dbgs() << "Shrunk: " << SR << '\n');
585 void LiveIntervals::extendToIndices(LiveRange &LR,
586 ArrayRef<SlotIndex> Indices) {
587 assert(LRCalc && "LRCalc not initialized.");
588 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
589 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
590 LRCalc->extend(LR, Indices[i]);
593 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
594 SmallVectorImpl<SlotIndex> *EndPoints) {
595 LiveQueryResult LRQ = LR.Query(Kill);
596 VNInfo *VNI = LRQ.valueOutOrDead();
600 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
601 SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
603 // If VNI isn't live out from KillMBB, the value is trivially pruned.
604 if (LRQ.endPoint() < MBBEnd) {
605 LR.removeSegment(Kill, LRQ.endPoint());
606 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
610 // VNI is live out of KillMBB.
611 LR.removeSegment(Kill, MBBEnd);
612 if (EndPoints) EndPoints->push_back(MBBEnd);
614 // Find all blocks that are reachable from KillMBB without leaving VNI's live
615 // range. It is possible that KillMBB itself is reachable, so start a DFS
616 // from each successor.
617 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
619 for (MachineBasicBlock::succ_iterator
620 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
621 SuccI != SuccE; ++SuccI) {
622 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
623 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
625 MachineBasicBlock *MBB = *I;
627 // Check if VNI is live in to MBB.
628 SlotIndex MBBStart, MBBEnd;
629 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
630 LiveQueryResult LRQ = LR.Query(MBBStart);
631 if (LRQ.valueIn() != VNI) {
632 // This block isn't part of the VNI segment. Prune the search.
637 // Prune the search if VNI is killed in MBB.
638 if (LRQ.endPoint() < MBBEnd) {
639 LR.removeSegment(MBBStart, LRQ.endPoint());
640 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
645 // VNI is live through MBB.
646 LR.removeSegment(MBBStart, MBBEnd);
647 if (EndPoints) EndPoints->push_back(MBBEnd);
653 //===----------------------------------------------------------------------===//
654 // Register allocator hooks.
657 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
658 // Keep track of regunit ranges.
659 SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
660 // Keep track of subregister ranges.
661 SmallVector<std::pair<const LiveInterval::SubRange*,
662 LiveRange::const_iterator>, 4> SRs;
664 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
665 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
666 if (MRI->reg_nodbg_empty(Reg))
668 const LiveInterval &LI = getInterval(Reg);
672 // Find the regunit intervals for the assigned register. They may overlap
673 // the virtual register live range, cancelling any kills.
675 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
677 const LiveRange &RURange = getRegUnit(*Units);
680 RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
683 if (MRI->subRegLivenessEnabled()) {
685 for (const LiveInterval::SubRange &SR : LI.subranges()) {
686 SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
690 // Every instruction that kills Reg corresponds to a segment range end
692 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
694 // A block index indicates an MBB edge.
695 if (RI->end.isBlock())
697 MachineInstr *MI = getInstructionFromIndex(RI->end);
701 // Check if any of the regunits are live beyond the end of RI. That could
702 // happen when a physreg is defined as a copy of a virtreg:
704 // %EAX = COPY %vreg5
705 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
708 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
709 for (auto &RUP : RU) {
710 const LiveRange &RURange = *RUP.first;
711 LiveRange::const_iterator &I = RUP.second;
712 if (I == RURange.end())
714 I = RURange.advanceTo(I, RI->end);
715 if (I == RURange.end() || I->start >= RI->end)
717 // I is overlapping RI.
721 if (MRI->subRegLivenessEnabled()) {
722 // When reading a partial undefined value we must not add a kill flag.
723 // The regalloc might have used the undef lane for something else.
725 // %vreg1 = ... ; R32: %vreg1
726 // %vreg2:high16 = ... ; R64: %vreg2
727 // = read %vreg2<kill> ; R64: %vreg2
728 // = read %vreg1 ; R32: %vreg1
729 // The <kill> flag is correct for %vreg2, but the register allocator may
730 // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
731 // are actually never written by %vreg2. After assignment the <kill>
732 // flag at the read instruction is invalid.
733 LaneBitmask DefinedLanesMask;
735 // Compute a mask of lanes that are defined.
736 DefinedLanesMask = 0;
737 for (auto &SRP : SRs) {
738 const LiveInterval::SubRange &SR = *SRP.first;
739 LiveRange::const_iterator &I = SRP.second;
742 I = SR.advanceTo(I, RI->end);
743 if (I == SR.end() || I->start >= RI->end)
745 // I is overlapping RI
746 DefinedLanesMask |= SR.LaneMask;
749 DefinedLanesMask = ~0u;
751 bool IsFullWrite = false;
752 for (const MachineOperand &MO : MI->operands()) {
753 if (!MO.isReg() || MO.getReg() != Reg)
756 // Reading any undefined lanes?
757 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
758 if ((UseMask & ~DefinedLanesMask) != 0)
760 } else if (MO.getSubReg() == 0) {
761 // Writing to the full register?
767 // If an instruction writes to a subregister, a new segment starts in
768 // the LiveInterval. But as this is only overriding part of the register
769 // adding kill-flags is not correct here after registers have been
772 // Next segment has to be adjacent in the subregister write case.
773 LiveRange::const_iterator N = std::next(RI);
774 if (N != LI.end() && N->start == RI->end)
779 MI->addRegisterKilled(Reg, nullptr);
782 MI->clearRegisterKills(Reg, nullptr);
788 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
789 // A local live range must be fully contained inside the block, meaning it is
790 // defined and killed at instructions, not at block boundaries. It is not
791 // live in or or out of any block.
793 // It is technically possible to have a PHI-defined live range identical to a
794 // single block, but we are going to return false in that case.
796 SlotIndex Start = LI.beginIndex();
800 SlotIndex Stop = LI.endIndex();
804 // getMBBFromIndex doesn't need to search the MBB table when both indexes
805 // belong to proper instructions.
806 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
807 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
808 return MBB1 == MBB2 ? MBB1 : nullptr;
812 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
813 for (const VNInfo *PHI : LI.valnos) {
814 if (PHI->isUnused() || !PHI->isPHIDef())
816 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
817 // Conservatively return true instead of scanning huge predecessor lists.
818 if (PHIMBB->pred_size() > 100)
820 for (MachineBasicBlock::const_pred_iterator
821 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
822 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
829 LiveIntervals::getSpillWeight(bool isDef, bool isUse,
830 const MachineBlockFrequencyInfo *MBFI,
831 const MachineInstr *MI) {
832 BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
833 const float Scale = 1.0f / MBFI->getEntryFreq();
834 return (isDef + isUse) * (Freq.getFrequency() * Scale);
838 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
839 LiveInterval& Interval = createEmptyInterval(reg);
840 VNInfo* VN = Interval.getNextValue(
841 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
842 getVNInfoAllocator());
843 LiveRange::Segment S(
844 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
845 getMBBEndIdx(startInst->getParent()), VN);
846 Interval.addSegment(S);
852 //===----------------------------------------------------------------------===//
853 // Register mask functions
854 //===----------------------------------------------------------------------===//
856 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
857 BitVector &UsableRegs) {
860 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
862 // Use a smaller arrays for local live ranges.
863 ArrayRef<SlotIndex> Slots;
864 ArrayRef<const uint32_t*> Bits;
865 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
866 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
867 Bits = getRegMaskBitsInBlock(MBB->getNumber());
869 Slots = getRegMaskSlots();
870 Bits = getRegMaskBits();
873 // We are going to enumerate all the register mask slots contained in LI.
874 // Start with a binary search of RegMaskSlots to find a starting point.
875 ArrayRef<SlotIndex>::iterator SlotI =
876 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
877 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
879 // No slots in range, LI begins after the last call.
885 assert(*SlotI >= LiveI->start);
886 // Loop over all slots overlapping this segment.
887 while (*SlotI < LiveI->end) {
888 // *SlotI overlaps LI. Collect mask bits.
890 // This is the first overlap. Initialize UsableRegs to all ones.
892 UsableRegs.resize(TRI->getNumRegs(), true);
895 // Remove usable registers clobbered by this mask.
896 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
897 if (++SlotI == SlotE)
900 // *SlotI is beyond the current LI segment.
901 LiveI = LI.advanceTo(LiveI, *SlotI);
904 // Advance SlotI until it overlaps.
905 while (*SlotI < LiveI->start)
906 if (++SlotI == SlotE)
911 //===----------------------------------------------------------------------===//
912 // IntervalUpdate class.
913 //===----------------------------------------------------------------------===//
915 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
916 class LiveIntervals::HMEditor {
919 const MachineRegisterInfo& MRI;
920 const TargetRegisterInfo& TRI;
923 SmallPtrSet<LiveRange*, 8> Updated;
927 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
928 const TargetRegisterInfo& TRI,
929 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
930 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
931 UpdateFlags(UpdateFlags) {}
933 // FIXME: UpdateFlags is a workaround that creates live intervals for all
934 // physregs, even those that aren't needed for regalloc, in order to update
935 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
936 // flags, and postRA passes will use a live register utility instead.
937 LiveRange *getRegUnitLI(unsigned Unit) {
939 return &LIS.getRegUnit(Unit);
940 return LIS.getCachedRegUnit(Unit);
943 /// Update all live ranges touched by MI, assuming a move from OldIdx to
945 void updateAllRanges(MachineInstr *MI) {
946 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
947 bool hasRegMask = false;
948 for (MachineOperand &MO : MI->operands()) {
953 // Aggressively clear all kill flags.
954 // They are reinserted by VirtRegRewriter.
958 unsigned Reg = MO.getReg();
961 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
962 LiveInterval &LI = LIS.getInterval(Reg);
963 if (LI.hasSubRanges()) {
964 unsigned SubReg = MO.getSubReg();
965 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
966 for (LiveInterval::SubRange &S : LI.subranges()) {
967 if ((S.LaneMask & LaneMask) == 0)
969 updateRange(S, Reg, S.LaneMask);
972 updateRange(LI, Reg, 0);
976 // For physregs, only update the regunits that actually have a
977 // precomputed live range.
978 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
979 if (LiveRange *LR = getRegUnitLI(*Units))
980 updateRange(*LR, *Units, 0);
983 updateRegMaskSlots();
987 /// Update a single live range, assuming an instruction has been moved from
988 /// OldIdx to NewIdx.
989 void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
990 if (!Updated.insert(&LR).second)
994 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
995 dbgs() << PrintReg(Reg);
997 dbgs() << " L" << PrintLaneMask(LaneMask);
999 dbgs() << PrintRegUnit(Reg, &TRI);
1001 dbgs() << ":\t" << LR << '\n';
1003 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1006 handleMoveUp(LR, Reg, LaneMask);
1007 DEBUG(dbgs() << " -->\t" << LR << '\n');
1011 /// Update LR to reflect an instruction has been moved downwards from OldIdx
1014 /// 1. Live def at OldIdx:
1015 /// Move def to NewIdx, assert endpoint after NewIdx.
1017 /// 2. Live def at OldIdx, killed at NewIdx:
1018 /// Change to dead def at NewIdx.
1019 /// (Happens when bundling def+kill together).
1021 /// 3. Dead def at OldIdx:
1022 /// Move def to NewIdx, possibly across another live value.
1024 /// 4. Def at OldIdx AND at NewIdx:
1025 /// Remove segment [OldIdx;NewIdx) and value defined at OldIdx.
1026 /// (Happens when bundling multiple defs together).
1028 /// 5. Value read at OldIdx, killed before NewIdx:
1029 /// Extend kill to NewIdx.
1031 void handleMoveDown(LiveRange &LR) {
1032 // First look for a kill at OldIdx.
1033 LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
1034 LiveRange::iterator E = LR.end();
1035 // Is LR even live at OldIdx?
1036 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1039 // Handle a live-in value.
1040 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1041 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
1042 // If the live-in value already extends to NewIdx, there is nothing to do.
1043 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
1045 // Aggressively remove all kill flags from the old kill point.
1046 // Kill flags shouldn't be used while live intervals exist, they will be
1047 // reinserted by VirtRegRewriter.
1048 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
1049 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
1050 if (MO->isReg() && MO->isUse())
1051 MO->setIsKill(false);
1052 // Adjust I->end to reach NewIdx. This may temporarily make LR invalid by
1053 // overlapping ranges. Case 5 above.
1054 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1055 // If this was a kill, there may also be a def. Otherwise we're done.
1061 // Check for a def at OldIdx.
1062 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
1064 // We have a def at OldIdx.
1065 VNInfo *DefVNI = I->valno;
1066 assert(DefVNI->def == I->start && "Inconsistent def");
1067 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1068 // If the defined value extends beyond NewIdx, just move the def down.
1069 // This is case 1 above.
1070 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
1071 I->start = DefVNI->def;
1074 // The remaining possibilities are now:
1075 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
1076 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
1077 // In either case, it is possible that there is an existing def at NewIdx.
1078 assert((I->end == OldIdx.getDeadSlot() ||
1079 SlotIndex::isSameInstr(I->end, NewIdx)) &&
1080 "Cannot move def below kill");
1081 LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
1082 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1083 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
1084 // coalesced into that value.
1085 assert(NewI->valno != DefVNI && "Multiple defs of value?");
1086 LR.removeValNo(DefVNI);
1089 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
1090 // If the def at OldIdx was dead, we allow it to be moved across other LR
1091 // values. The new range should be placed immediately before NewI, move any
1092 // intermediate ranges up.
1093 assert(NewI != I && "Inconsistent iterators");
1094 std::copy(std::next(I), NewI, I);
1096 = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1099 /// Update LR to reflect an instruction has been moved upwards from OldIdx
1102 /// 1. Live def at OldIdx:
1103 /// Hoist def to NewIdx.
1105 /// 2. Dead def at OldIdx:
1106 /// Hoist def+end to NewIdx, possibly move across other values.
1108 /// 3. Dead def at OldIdx AND existing def at NewIdx:
1109 /// Remove value defined at OldIdx, coalescing it with existing value.
1111 /// 4. Live def at OldIdx AND existing def at NewIdx:
1112 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
1113 /// (Happens when bundling multiple defs together).
1115 /// 5. Value killed at OldIdx:
1116 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
1119 void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1120 // First look for a kill at OldIdx.
1121 LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
1122 LiveRange::iterator E = LR.end();
1123 // Is LR even live at OldIdx?
1124 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1127 // Handle a live-in value.
1128 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1129 // If the live-in value isn't killed here, there is nothing to do.
1130 if (!SlotIndex::isSameInstr(OldIdx, I->end))
1132 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
1133 // another use, we need to search for that use. Case 5 above.
1134 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1136 // If OldIdx also defines a value, there couldn't have been another use.
1137 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
1138 // No def, search for the new kill.
1139 // This can never be an early clobber kill since there is no def.
1140 std::prev(I)->end = findLastUseBefore(Reg, LaneMask).getRegSlot();
1145 // Now deal with the def at OldIdx.
1146 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
1147 VNInfo *DefVNI = I->valno;
1148 assert(DefVNI->def == I->start && "Inconsistent def");
1149 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1151 // Check for an existing def at NewIdx.
1152 LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
1153 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1154 assert(NewI->valno != DefVNI && "Same value defined more than once?");
1155 // There is an existing def at NewIdx.
1156 if (I->end.isDead()) {
1157 // Case 3: Remove the dead def at OldIdx.
1158 LR.removeValNo(DefVNI);
1161 // Case 4: Replace def at NewIdx with live def at OldIdx.
1162 I->start = DefVNI->def;
1163 LR.removeValNo(NewI->valno);
1167 // There is no existing def at NewIdx. Hoist DefVNI.
1168 if (!I->end.isDead()) {
1169 // Leave the end point of a live def.
1170 I->start = DefVNI->def;
1174 // DefVNI is a dead def. It may have been moved across other values in LR,
1175 // so move I up to NewI. Slide [NewI;I) down one position.
1176 std::copy_backward(NewI, I, std::next(I));
1177 *NewI = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1180 void updateRegMaskSlots() {
1181 SmallVectorImpl<SlotIndex>::iterator RI =
1182 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1184 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1185 "No RegMask at OldIdx.");
1186 *RI = NewIdx.getRegSlot();
1187 assert((RI == LIS.RegMaskSlots.begin() ||
1188 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1189 "Cannot move regmask instruction above another call");
1190 assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1191 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1192 "Cannot move regmask instruction below another call");
1195 // Return the last use of reg between NewIdx and OldIdx.
1196 SlotIndex findLastUseBefore(unsigned Reg, LaneBitmask LaneMask) {
1198 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1199 SlotIndex LastUse = NewIdx;
1200 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1201 unsigned SubReg = MO.getSubReg();
1202 if (SubReg != 0 && LaneMask != 0
1203 && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask) == 0)
1206 const MachineInstr *MI = MO.getParent();
1207 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1208 if (InstSlot > LastUse && InstSlot < OldIdx)
1214 // This is a regunit interval, so scanning the use list could be very
1215 // expensive. Scan upwards from OldIdx instead.
1216 assert(NewIdx < OldIdx && "Expected upwards move");
1217 SlotIndexes *Indexes = LIS.getSlotIndexes();
1218 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
1220 // OldIdx may not correspond to an instruction any longer, so set MII to
1221 // point to the next instruction after OldIdx, or MBB->end().
1222 MachineBasicBlock::iterator MII = MBB->end();
1223 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1224 Indexes->getNextNonNullIndex(OldIdx)))
1225 if (MI->getParent() == MBB)
1228 MachineBasicBlock::iterator Begin = MBB->begin();
1229 while (MII != Begin) {
1230 if ((--MII)->isDebugValue())
1232 SlotIndex Idx = Indexes->getInstructionIndex(MII);
1234 // Stop searching when NewIdx is reached.
1235 if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
1238 // Check if MII uses Reg.
1239 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1241 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1242 TRI.hasRegUnit(MO->getReg(), Reg))
1245 // Didn't reach NewIdx. It must be the first instruction in the block.
1250 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
1251 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1252 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1253 Indexes->removeMachineInstrFromMaps(MI);
1254 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1255 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1256 OldIndex < getMBBEndIdx(MI->getParent()) &&
1257 "Cannot handle moves across basic block boundaries.");
1259 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1260 HME.updateAllRanges(MI);
1263 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1264 MachineInstr* BundleStart,
1266 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1267 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1268 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1269 HME.updateAllRanges(MI);
1272 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1273 const MachineBasicBlock::iterator End,
1274 const SlotIndex endIdx,
1275 LiveRange &LR, const unsigned Reg,
1276 LaneBitmask LaneMask) {
1277 LiveInterval::iterator LII = LR.find(endIdx);
1278 SlotIndex lastUseIdx;
1279 if (LII != LR.end() && LII->start < endIdx)
1280 lastUseIdx = LII->end;
1284 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1286 MachineInstr *MI = I;
1287 if (MI->isDebugValue())
1290 SlotIndex instrIdx = getInstructionIndex(MI);
1291 bool isStartValid = getInstructionFromIndex(LII->start);
1292 bool isEndValid = getInstructionFromIndex(LII->end);
1294 // FIXME: This doesn't currently handle early-clobber or multiple removed
1295 // defs inside of the region to repair.
1296 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1297 OE = MI->operands_end(); OI != OE; ++OI) {
1298 const MachineOperand &MO = *OI;
1299 if (!MO.isReg() || MO.getReg() != Reg)
1302 unsigned SubReg = MO.getSubReg();
1303 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1304 if ((Mask & LaneMask) == 0)
1308 if (!isStartValid) {
1309 if (LII->end.isDead()) {
1310 SlotIndex prevStart;
1311 if (LII != LR.begin())
1312 prevStart = std::prev(LII)->start;
1314 // FIXME: This could be more efficient if there was a
1315 // removeSegment method that returned an iterator.
1316 LR.removeSegment(*LII, true);
1317 if (prevStart.isValid())
1318 LII = LR.find(prevStart);
1322 LII->start = instrIdx.getRegSlot();
1323 LII->valno->def = instrIdx.getRegSlot();
1324 if (MO.getSubReg() && !MO.isUndef())
1325 lastUseIdx = instrIdx.getRegSlot();
1327 lastUseIdx = SlotIndex();
1332 if (!lastUseIdx.isValid()) {
1333 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1334 LiveRange::Segment S(instrIdx.getRegSlot(),
1335 instrIdx.getDeadSlot(), VNI);
1336 LII = LR.addSegment(S);
1337 } else if (LII->start != instrIdx.getRegSlot()) {
1338 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1339 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1340 LII = LR.addSegment(S);
1343 if (MO.getSubReg() && !MO.isUndef())
1344 lastUseIdx = instrIdx.getRegSlot();
1346 lastUseIdx = SlotIndex();
1347 } else if (MO.isUse()) {
1348 // FIXME: This should probably be handled outside of this branch,
1349 // either as part of the def case (for defs inside of the region) or
1350 // after the loop over the region.
1351 if (!isEndValid && !LII->end.isBlock())
1352 LII->end = instrIdx.getRegSlot();
1353 if (!lastUseIdx.isValid())
1354 lastUseIdx = instrIdx.getRegSlot();
1361 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1362 MachineBasicBlock::iterator Begin,
1363 MachineBasicBlock::iterator End,
1364 ArrayRef<unsigned> OrigRegs) {
1365 // Find anchor points, which are at the beginning/end of blocks or at
1366 // instructions that already have indexes.
1367 while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1369 while (End != MBB->end() && !Indexes->hasIndex(End))
1373 if (End == MBB->end())
1374 endIdx = getMBBEndIdx(MBB).getPrevSlot();
1376 endIdx = getInstructionIndex(End);
1378 Indexes->repairIndexesInRange(MBB, Begin, End);
1380 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1382 MachineInstr *MI = I;
1383 if (MI->isDebugValue())
1385 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1386 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1388 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1389 !hasInterval(MOI->getReg())) {
1390 createAndComputeVirtRegInterval(MOI->getReg());
1395 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1396 unsigned Reg = OrigRegs[i];
1397 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1400 LiveInterval &LI = getInterval(Reg);
1401 // FIXME: Should we support undefs that gain defs?
1402 if (!LI.hasAtLeastOneValue())
1405 for (LiveInterval::SubRange &S : LI.subranges()) {
1406 repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1408 repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1412 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1413 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1414 if (LiveRange *LR = getCachedRegUnit(*Units))
1415 if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1416 LR->removeValNo(VNI);
1420 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1421 VNInfo *VNI = LI.getVNInfoAt(Pos);
1424 LI.removeValNo(VNI);
1426 // Also remove the value in subranges.
1427 for (LiveInterval::SubRange &S : LI.subranges()) {
1428 if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1429 S.removeValNo(SVNI);
1431 LI.removeEmptySubRanges();
1434 void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1435 SmallVectorImpl<LiveInterval*> &SplitLIs) {
1436 ConnectedVNInfoEqClasses ConEQ(*this);
1437 unsigned NumComp = ConEQ.Classify(&LI);
1440 DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1441 unsigned Reg = LI.reg;
1442 const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1443 for (unsigned I = 1; I < NumComp; ++I) {
1444 unsigned NewVReg = MRI->createVirtualRegister(RegClass);
1445 LiveInterval &NewLI = createEmptyInterval(NewVReg);
1446 SplitLIs.push_back(&NewLI);
1448 ConEQ.Distribute(LI, SplitLIs.data(), *MRI);