1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
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 contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveRangeEdit.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/VirtRegMap.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
32 STATISTIC(NumFinished, "Number of splits finished");
33 STATISTIC(NumSimple, "Number of splits that were simple");
34 STATISTIC(NumCopies, "Number of copies inserted for splitting");
35 STATISTIC(NumRemats, "Number of rematerialized defs for splitting");
36 STATISTIC(NumRepairs, "Number of invalid live ranges repaired");
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm,
43 const LiveIntervals &lis,
44 const MachineLoopInfo &mli)
45 : MF(vrm.getMachineFunction()),
49 TII(*MF.getTarget().getInstrInfo()),
51 LastSplitPoint(MF.getNumBlockIDs()) {}
53 void SplitAnalysis::clear() {
56 ThroughBlocks.clear();
58 DidRepairRange = false;
61 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) {
62 const MachineBasicBlock *MBB = MF.getBlockNumbered(Num);
63 const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor();
64 std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num];
65 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
67 // Compute split points on the first call. The pair is independent of the
68 // current live interval.
69 if (!LSP.first.isValid()) {
70 MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator();
71 if (FirstTerm == MBB->end())
74 LSP.first = LIS.getInstructionIndex(FirstTerm);
76 // If there is a landing pad successor, also find the call instruction.
79 // There may not be a call instruction (?) in which case we ignore LPad.
80 LSP.second = LSP.first;
81 for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin();
85 LSP.second = LIS.getInstructionIndex(I);
91 // If CurLI is live into a landing pad successor, move the last split point
92 // back to the call that may throw.
93 if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
96 // Find the value leaving MBB.
97 const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd);
101 // If the value leaving MBB was defined after the call in MBB, it can't
102 // really be live-in to the landing pad. This can happen if the landing pad
103 // has a PHI, and this register is undef on the exceptional edge.
104 // <rdar://problem/10664933>
105 if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd)
108 // Value is properly live-in to the landing pad.
109 // Only allow splits before the call.
113 MachineBasicBlock::iterator
114 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
115 SlotIndex LSP = getLastSplitPoint(MBB->getNumber());
116 if (LSP == LIS.getMBBEndIdx(MBB))
118 return LIS.getInstructionFromIndex(LSP);
121 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
122 void SplitAnalysis::analyzeUses() {
123 assert(UseSlots.empty() && "Call clear first");
125 // First get all the defs from the interval values. This provides the correct
126 // slots for early clobbers.
127 for (LiveInterval::const_vni_iterator I = CurLI->vni_begin(),
128 E = CurLI->vni_end(); I != E; ++I)
129 if (!(*I)->isPHIDef() && !(*I)->isUnused())
130 UseSlots.push_back((*I)->def);
132 // Get use slots form the use-def chain.
133 const MachineRegisterInfo &MRI = MF.getRegInfo();
134 for (MachineRegisterInfo::use_nodbg_iterator
135 I = MRI.use_nodbg_begin(CurLI->reg), E = MRI.use_nodbg_end(); I != E;
137 if (!I.getOperand().isUndef())
138 UseSlots.push_back(LIS.getInstructionIndex(&*I).getRegSlot());
140 array_pod_sort(UseSlots.begin(), UseSlots.end());
142 // Remove duplicates, keeping the smaller slot for each instruction.
143 // That is what we want for early clobbers.
144 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
145 SlotIndex::isSameInstr),
148 // Compute per-live block info.
149 if (!calcLiveBlockInfo()) {
150 // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
151 // I am looking at you, RegisterCoalescer!
152 DidRepairRange = true;
154 DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
155 const_cast<LiveIntervals&>(LIS)
156 .shrinkToUses(const_cast<LiveInterval*>(CurLI));
158 ThroughBlocks.clear();
159 bool fixed = calcLiveBlockInfo();
161 assert(fixed && "Couldn't fix broken live interval");
164 DEBUG(dbgs() << "Analyze counted "
165 << UseSlots.size() << " instrs in "
166 << UseBlocks.size() << " blocks, through "
167 << NumThroughBlocks << " blocks.\n");
170 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
171 /// where CurLI is live.
172 bool SplitAnalysis::calcLiveBlockInfo() {
173 ThroughBlocks.resize(MF.getNumBlockIDs());
174 NumThroughBlocks = NumGapBlocks = 0;
178 LiveInterval::const_iterator LVI = CurLI->begin();
179 LiveInterval::const_iterator LVE = CurLI->end();
181 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
182 UseI = UseSlots.begin();
183 UseE = UseSlots.end();
185 // Loop over basic blocks where CurLI is live.
186 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
190 SlotIndex Start, Stop;
191 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
193 // If the block contains no uses, the range must be live through. At one
194 // point, RegisterCoalescer could create dangling ranges that ended
196 if (UseI == UseE || *UseI >= Stop) {
198 ThroughBlocks.set(BI.MBB->getNumber());
199 // The range shouldn't end mid-block if there are no uses. This shouldn't
204 // This block has uses. Find the first and last uses in the block.
205 BI.FirstInstr = *UseI;
206 assert(BI.FirstInstr >= Start);
208 while (UseI != UseE && *UseI < Stop);
209 BI.LastInstr = UseI[-1];
210 assert(BI.LastInstr < Stop);
212 // LVI is the first live segment overlapping MBB.
213 BI.LiveIn = LVI->start <= Start;
215 // When not live in, the first use should be a def.
217 assert(LVI->start == LVI->valno->def && "Dangling LiveRange start");
218 assert(LVI->start == BI.FirstInstr && "First instr should be a def");
219 BI.FirstDef = BI.FirstInstr;
222 // Look for gaps in the live range.
224 while (LVI->end < Stop) {
225 SlotIndex LastStop = LVI->end;
226 if (++LVI == LVE || LVI->start >= Stop) {
228 BI.LastInstr = LastStop;
232 if (LastStop < LVI->start) {
233 // There is a gap in the live range. Create duplicate entries for the
234 // live-in snippet and the live-out snippet.
237 // Push the Live-in part.
239 UseBlocks.push_back(BI);
240 UseBlocks.back().LastInstr = LastStop;
242 // Set up BI for the live-out part.
245 BI.FirstInstr = BI.FirstDef = LVI->start;
248 // A LiveRange that starts in the middle of the block must be a def.
249 assert(LVI->start == LVI->valno->def && "Dangling LiveRange start");
251 BI.FirstDef = LVI->start;
254 UseBlocks.push_back(BI);
256 // LVI is now at LVE or LVI->end >= Stop.
261 // Live segment ends exactly at Stop. Move to the next segment.
262 if (LVI->end == Stop && ++LVI == LVE)
265 // Pick the next basic block.
266 if (LVI->start < Stop)
269 MFI = LIS.getMBBFromIndex(LVI->start);
272 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
276 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
279 LiveInterval *li = const_cast<LiveInterval*>(cli);
280 LiveInterval::iterator LVI = li->begin();
281 LiveInterval::iterator LVE = li->end();
284 // Loop over basic blocks where li is live.
285 MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
286 SlotIndex Stop = LIS.getMBBEndIdx(MFI);
289 LVI = li->advanceTo(LVI, Stop);
294 Stop = LIS.getMBBEndIdx(MFI);
295 } while (Stop <= LVI->start);
299 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
300 unsigned OrigReg = VRM.getOriginal(CurLI->reg);
301 const LiveInterval &Orig = LIS.getInterval(OrigReg);
302 assert(!Orig.empty() && "Splitting empty interval?");
303 LiveInterval::const_iterator I = Orig.find(Idx);
305 // Range containing Idx should begin at Idx.
306 if (I != Orig.end() && I->start <= Idx)
307 return I->start == Idx;
309 // Range does not contain Idx, previous must end at Idx.
310 return I != Orig.begin() && (--I)->end == Idx;
313 void SplitAnalysis::analyze(const LiveInterval *li) {
320 //===----------------------------------------------------------------------===//
322 //===----------------------------------------------------------------------===//
324 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
325 SplitEditor::SplitEditor(SplitAnalysis &sa,
328 MachineDominatorTree &mdt)
329 : SA(sa), LIS(lis), VRM(vrm),
330 MRI(vrm.getMachineFunction().getRegInfo()),
332 TII(*vrm.getMachineFunction().getTarget().getInstrInfo()),
333 TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
336 SpillMode(SM_Partition),
340 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
347 // Reset the LiveRangeCalc instances needed for this spill mode.
348 LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
349 &LIS.getVNInfoAllocator());
351 LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
352 &LIS.getVNInfoAllocator());
354 // We don't need an AliasAnalysis since we will only be performing
355 // cheap-as-a-copy remats anyway.
356 Edit->anyRematerializable(0);
359 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
360 void SplitEditor::dump() const {
361 if (RegAssign.empty()) {
362 dbgs() << " empty\n";
366 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
367 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
372 VNInfo *SplitEditor::defValue(unsigned RegIdx,
373 const VNInfo *ParentVNI,
375 assert(ParentVNI && "Mapping NULL value");
376 assert(Idx.isValid() && "Invalid SlotIndex");
377 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
378 LiveInterval *LI = Edit->get(RegIdx);
380 // Create a new value.
381 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
383 // Use insert for lookup, so we can add missing values with a second lookup.
384 std::pair<ValueMap::iterator, bool> InsP =
385 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
386 ValueForcePair(VNI, false)));
388 // This was the first time (RegIdx, ParentVNI) was mapped.
389 // Keep it as a simple def without any liveness.
393 // If the previous value was a simple mapping, add liveness for it now.
394 if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
395 SlotIndex Def = OldVNI->def;
396 LI->addRange(LiveRange(Def, Def.getDeadSlot(), OldVNI));
397 // No longer a simple mapping. Switch to a complex, non-forced mapping.
398 InsP.first->second = ValueForcePair();
401 // This is a complex mapping, add liveness for VNI
402 SlotIndex Def = VNI->def;
403 LI->addRange(LiveRange(Def, Def.getDeadSlot(), VNI));
408 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
409 assert(ParentVNI && "Mapping NULL value");
410 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
411 VNInfo *VNI = VFP.getPointer();
413 // ParentVNI was either unmapped or already complex mapped. Either way, just
414 // set the force bit.
420 // This was previously a single mapping. Make sure the old def is represented
421 // by a trivial live range.
422 SlotIndex Def = VNI->def;
423 Edit->get(RegIdx)->addRange(LiveRange(Def, Def.getDeadSlot(), VNI));
424 // Mark as complex mapped, forced.
425 VFP = ValueForcePair(0, true);
428 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
431 MachineBasicBlock &MBB,
432 MachineBasicBlock::iterator I) {
433 MachineInstr *CopyMI = 0;
435 LiveInterval *LI = Edit->get(RegIdx);
437 // We may be trying to avoid interference that ends at a deleted instruction,
438 // so always begin RegIdx 0 early and all others late.
439 bool Late = RegIdx != 0;
441 // Attempt cheap-as-a-copy rematerialization.
442 LiveRangeEdit::Remat RM(ParentVNI);
443 if (Edit->canRematerializeAt(RM, UseIdx, true)) {
444 Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
447 // Can't remat, just insert a copy from parent.
448 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
449 .addReg(Edit->getReg());
450 Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
455 // Define the value in Reg.
456 return defValue(RegIdx, ParentVNI, Def);
459 /// Create a new virtual register and live interval.
460 unsigned SplitEditor::openIntv() {
461 // Create the complement as index 0.
465 // Create the open interval.
466 OpenIdx = Edit->size();
471 void SplitEditor::selectIntv(unsigned Idx) {
472 assert(Idx != 0 && "Cannot select the complement interval");
473 assert(Idx < Edit->size() && "Can only select previously opened interval");
474 DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n');
478 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
479 assert(OpenIdx && "openIntv not called before enterIntvBefore");
480 DEBUG(dbgs() << " enterIntvBefore " << Idx);
481 Idx = Idx.getBaseIndex();
482 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
484 DEBUG(dbgs() << ": not live\n");
487 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
488 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
489 assert(MI && "enterIntvBefore called with invalid index");
491 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
495 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
496 assert(OpenIdx && "openIntv not called before enterIntvAfter");
497 DEBUG(dbgs() << " enterIntvAfter " << Idx);
498 Idx = Idx.getBoundaryIndex();
499 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
501 DEBUG(dbgs() << ": not live\n");
504 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
505 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
506 assert(MI && "enterIntvAfter called with invalid index");
508 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
509 llvm::next(MachineBasicBlock::iterator(MI)));
513 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
514 assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
515 SlotIndex End = LIS.getMBBEndIdx(&MBB);
516 SlotIndex Last = End.getPrevSlot();
517 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
518 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
520 DEBUG(dbgs() << ": not live\n");
523 DEBUG(dbgs() << ": valno " << ParentVNI->id);
524 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
525 SA.getLastSplitPointIter(&MBB));
526 RegAssign.insert(VNI->def, End, OpenIdx);
531 /// useIntv - indicate that all instructions in MBB should use OpenLI.
532 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
533 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
536 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
537 assert(OpenIdx && "openIntv not called before useIntv");
538 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
539 RegAssign.insert(Start, End, OpenIdx);
543 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
544 assert(OpenIdx && "openIntv not called before leaveIntvAfter");
545 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
547 // The interval must be live beyond the instruction at Idx.
548 SlotIndex Boundary = Idx.getBoundaryIndex();
549 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
551 DEBUG(dbgs() << ": not live\n");
552 return Boundary.getNextSlot();
554 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
555 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
556 assert(MI && "No instruction at index");
558 // In spill mode, make live ranges as short as possible by inserting the copy
559 // before MI. This is only possible if that instruction doesn't redefine the
560 // value. The inserted COPY is not a kill, and we don't need to recompute
561 // the source live range. The spiller also won't try to hoist this copy.
562 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
563 MI->readsVirtualRegister(Edit->getReg())) {
564 forceRecompute(0, ParentVNI);
565 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
569 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
570 llvm::next(MachineBasicBlock::iterator(MI)));
574 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
575 assert(OpenIdx && "openIntv not called before leaveIntvBefore");
576 DEBUG(dbgs() << " leaveIntvBefore " << Idx);
578 // The interval must be live into the instruction at Idx.
579 Idx = Idx.getBaseIndex();
580 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
582 DEBUG(dbgs() << ": not live\n");
583 return Idx.getNextSlot();
585 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
587 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
588 assert(MI && "No instruction at index");
589 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
593 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
594 assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
595 SlotIndex Start = LIS.getMBBStartIdx(&MBB);
596 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
598 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
600 DEBUG(dbgs() << ": not live\n");
604 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
605 MBB.SkipPHIsAndLabels(MBB.begin()));
606 RegAssign.insert(Start, VNI->def, OpenIdx);
611 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
612 assert(OpenIdx && "openIntv not called before overlapIntv");
613 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
614 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
615 "Parent changes value in extended range");
616 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
617 "Range cannot span basic blocks");
619 // The complement interval will be extended as needed by LRCalc.extend().
621 forceRecompute(0, ParentVNI);
622 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
623 RegAssign.insert(Start, End, OpenIdx);
627 //===----------------------------------------------------------------------===//
629 //===----------------------------------------------------------------------===//
631 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
632 LiveInterval *LI = Edit->get(0);
633 DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
634 RegAssignMap::iterator AssignI;
635 AssignI.setMap(RegAssign);
637 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
638 VNInfo *VNI = Copies[i];
639 SlotIndex Def = VNI->def;
640 MachineInstr *MI = LIS.getInstructionFromIndex(Def);
641 assert(MI && "No instruction for back-copy");
643 MachineBasicBlock *MBB = MI->getParent();
644 MachineBasicBlock::iterator MBBI(MI);
646 do AtBegin = MBBI == MBB->begin();
647 while (!AtBegin && (--MBBI)->isDebugValue());
649 DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
650 LI->removeValNo(VNI);
651 LIS.RemoveMachineInstrFromMaps(MI);
652 MI->eraseFromParent();
654 // Adjust RegAssign if a register assignment is killed at VNI->def. We
655 // want to avoid calculating the live range of the source register if
657 AssignI.find(Def.getPrevSlot());
658 if (!AssignI.valid() || AssignI.start() >= Def)
660 // If MI doesn't kill the assigned register, just leave it.
661 if (AssignI.stop() != Def)
663 unsigned RegIdx = AssignI.value();
664 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
665 DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n');
666 forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
668 SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot();
669 DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI);
670 AssignI.setStop(Kill);
676 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
677 MachineBasicBlock *DefMBB) {
680 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
682 const MachineLoopInfo &Loops = SA.Loops;
683 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
684 MachineDomTreeNode *DefDomNode = MDT[DefMBB];
686 // Best candidate so far.
687 MachineBasicBlock *BestMBB = MBB;
688 unsigned BestDepth = UINT_MAX;
691 const MachineLoop *Loop = Loops.getLoopFor(MBB);
693 // MBB isn't in a loop, it doesn't get any better. All dominators have a
694 // higher frequency by definition.
696 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
697 << MBB->getNumber() << " at depth 0\n");
701 // We'll never be able to exit the DefLoop.
702 if (Loop == DefLoop) {
703 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
704 << MBB->getNumber() << " in the same loop\n");
708 // Least busy dominator seen so far.
709 unsigned Depth = Loop->getLoopDepth();
710 if (Depth < BestDepth) {
713 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
714 << MBB->getNumber() << " at depth " << Depth << '\n');
717 // Leave loop by going to the immediate dominator of the loop header.
718 // This is a bigger stride than simply walking up the dominator tree.
719 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
721 // Too far up the dominator tree?
722 if (!IDom || !MDT.dominates(DefDomNode, IDom))
725 MBB = IDom->getBlock();
729 void SplitEditor::hoistCopiesForSize() {
730 // Get the complement interval, always RegIdx 0.
731 LiveInterval *LI = Edit->get(0);
732 LiveInterval *Parent = &Edit->getParent();
734 // Track the nearest common dominator for all back-copies for each ParentVNI,
735 // indexed by ParentVNI->id.
736 typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
737 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
739 // Find the nearest common dominator for parent values with multiple
740 // back-copies. If a single back-copy dominates, put it in DomPair.second.
741 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
746 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
747 assert(ParentVNI && "Parent not live at complement def");
749 // Don't hoist remats. The complement is probably going to disappear
750 // completely anyway.
751 if (Edit->didRematerialize(ParentVNI))
754 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
755 DomPair &Dom = NearestDom[ParentVNI->id];
757 // Keep directly defined parent values. This is either a PHI or an
758 // instruction in the complement range. All other copies of ParentVNI
759 // should be eliminated.
760 if (VNI->def == ParentVNI->def) {
761 DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
762 Dom = DomPair(ValMBB, VNI->def);
765 // Skip the singly mapped values. There is nothing to gain from hoisting a
767 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
768 DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
773 // First time we see ParentVNI. VNI dominates itself.
774 Dom = DomPair(ValMBB, VNI->def);
775 } else if (Dom.first == ValMBB) {
776 // Two defs in the same block. Pick the earlier def.
777 if (!Dom.second.isValid() || VNI->def < Dom.second)
778 Dom.second = VNI->def;
780 // Different basic blocks. Check if one dominates.
781 MachineBasicBlock *Near =
782 MDT.findNearestCommonDominator(Dom.first, ValMBB);
784 // Def ValMBB dominates.
785 Dom = DomPair(ValMBB, VNI->def);
786 else if (Near != Dom.first)
787 // None dominate. Hoist to common dominator, need new def.
788 Dom = DomPair(Near, SlotIndex());
791 DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
792 << " for parent " << ParentVNI->id << '@' << ParentVNI->def
793 << " hoist to BB#" << Dom.first->getNumber() << ' '
794 << Dom.second << '\n');
797 // Insert the hoisted copies.
798 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
799 DomPair &Dom = NearestDom[i];
800 if (!Dom.first || Dom.second.isValid())
802 // This value needs a hoisted copy inserted at the end of Dom.first.
803 VNInfo *ParentVNI = Parent->getValNumInfo(i);
804 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
805 // Get a less loopy dominator than Dom.first.
806 Dom.first = findShallowDominator(Dom.first, DefMBB);
807 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
809 defFromParent(0, ParentVNI, Last, *Dom.first,
810 SA.getLastSplitPointIter(Dom.first))->def;
813 // Remove redundant back-copies that are now known to be dominated by another
814 // def with the same value.
815 SmallVector<VNInfo*, 8> BackCopies;
816 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
821 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
822 const DomPair &Dom = NearestDom[ParentVNI->id];
823 if (!Dom.first || Dom.second == VNI->def)
825 BackCopies.push_back(VNI);
826 forceRecompute(0, ParentVNI);
828 removeBackCopies(BackCopies);
832 /// transferValues - Transfer all possible values to the new live ranges.
833 /// Values that were rematerialized are left alone, they need LRCalc.extend().
834 bool SplitEditor::transferValues() {
835 bool Skipped = false;
836 RegAssignMap::const_iterator AssignI = RegAssign.begin();
837 for (LiveInterval::const_iterator ParentI = Edit->getParent().begin(),
838 ParentE = Edit->getParent().end(); ParentI != ParentE; ++ParentI) {
839 DEBUG(dbgs() << " blit " << *ParentI << ':');
840 VNInfo *ParentVNI = ParentI->valno;
841 // RegAssign has holes where RegIdx 0 should be used.
842 SlotIndex Start = ParentI->start;
843 AssignI.advanceTo(Start);
846 SlotIndex End = ParentI->end;
847 if (!AssignI.valid()) {
849 } else if (AssignI.start() <= Start) {
850 RegIdx = AssignI.value();
851 if (AssignI.stop() < End) {
852 End = AssignI.stop();
857 End = std::min(End, AssignI.start());
860 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
861 DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
862 LiveInterval *LI = Edit->get(RegIdx);
864 // Check for a simply defined value that can be blitted directly.
865 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
866 if (VNInfo *VNI = VFP.getPointer()) {
867 DEBUG(dbgs() << ':' << VNI->id);
868 LI->addRange(LiveRange(Start, End, VNI));
873 // Skip values with forced recomputation.
875 DEBUG(dbgs() << "(recalc)");
881 LiveRangeCalc &LRC = getLRCalc(RegIdx);
883 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
884 // so the live range is accurate. Add live-in blocks in [Start;End) to the
886 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
887 SlotIndex BlockStart, BlockEnd;
888 tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
890 // The first block may be live-in, or it may have its own def.
891 if (Start != BlockStart) {
892 VNInfo *VNI = LI->extendInBlock(BlockStart, std::min(BlockEnd, End));
893 assert(VNI && "Missing def for complex mapped value");
894 DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
895 // MBB has its own def. Is it also live-out?
897 LRC.setLiveOutValue(MBB, VNI);
899 // Skip to the next block for live-in.
901 BlockStart = BlockEnd;
904 // Handle the live-in blocks covered by [Start;End).
905 assert(Start <= BlockStart && "Expected live-in block");
906 while (BlockStart < End) {
907 DEBUG(dbgs() << ">BB#" << MBB->getNumber());
908 BlockEnd = LIS.getMBBEndIdx(MBB);
909 if (BlockStart == ParentVNI->def) {
910 // This block has the def of a parent PHI, so it isn't live-in.
911 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
912 VNInfo *VNI = LI->extendInBlock(BlockStart, std::min(BlockEnd, End));
913 assert(VNI && "Missing def for complex mapped parent PHI");
915 LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
917 // This block needs a live-in value. The last block covered may not
920 LRC.addLiveInBlock(LI, MDT[MBB], End);
922 // Live-through, and we don't know the value.
923 LRC.addLiveInBlock(LI, MDT[MBB]);
924 LRC.setLiveOutValue(MBB, 0);
927 BlockStart = BlockEnd;
931 } while (Start != ParentI->end);
932 DEBUG(dbgs() << '\n');
935 LRCalc[0].calculateValues();
937 LRCalc[1].calculateValues();
942 void SplitEditor::extendPHIKillRanges() {
943 // Extend live ranges to be live-out for successor PHI values.
944 for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
945 E = Edit->getParent().vni_end(); I != E; ++I) {
946 const VNInfo *PHIVNI = *I;
947 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
949 unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
950 LiveInterval *LI = Edit->get(RegIdx);
951 LiveRangeCalc &LRC = getLRCalc(RegIdx);
952 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
953 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
954 PE = MBB->pred_end(); PI != PE; ++PI) {
955 SlotIndex End = LIS.getMBBEndIdx(*PI);
956 SlotIndex LastUse = End.getPrevSlot();
957 // The predecessor may not have a live-out value. That is OK, like an
958 // undef PHI operand.
959 if (Edit->getParent().liveAt(LastUse)) {
960 assert(RegAssign.lookup(LastUse) == RegIdx &&
961 "Different register assignment in phi predecessor");
968 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
969 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
970 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
971 RE = MRI.reg_end(); RI != RE;) {
972 MachineOperand &MO = RI.getOperand();
973 MachineInstr *MI = MO.getParent();
975 // LiveDebugVariables should have handled all DBG_VALUE instructions.
976 if (MI->isDebugValue()) {
977 DEBUG(dbgs() << "Zapping " << *MI);
982 // <undef> operands don't really read the register, so it doesn't matter
983 // which register we choose. When the use operand is tied to a def, we must
984 // use the same register as the def, so just do that always.
985 SlotIndex Idx = LIS.getInstructionIndex(MI);
986 if (MO.isDef() || MO.isUndef())
987 Idx = Idx.getRegSlot(MO.isEarlyClobber());
989 // Rewrite to the mapped register at Idx.
990 unsigned RegIdx = RegAssign.lookup(Idx);
991 LiveInterval *LI = Edit->get(RegIdx);
993 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'
994 << Idx << ':' << RegIdx << '\t' << *MI);
996 // Extend liveness to Idx if the instruction reads reg.
997 if (!ExtendRanges || MO.isUndef())
1000 // Skip instructions that don't read Reg.
1002 if (!MO.getSubReg() && !MO.isEarlyClobber())
1004 // We may wan't to extend a live range for a partial redef, or for a use
1005 // tied to an early clobber.
1006 Idx = Idx.getPrevSlot();
1007 if (!Edit->getParent().liveAt(Idx))
1010 Idx = Idx.getRegSlot(true);
1012 getLRCalc(RegIdx).extend(LI, Idx.getNextSlot());
1016 void SplitEditor::deleteRematVictims() {
1017 SmallVector<MachineInstr*, 8> Dead;
1018 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
1019 LiveInterval *LI = *I;
1020 for (LiveInterval::const_iterator LII = LI->begin(), LIE = LI->end();
1021 LII != LIE; ++LII) {
1022 // Dead defs end at the dead slot.
1023 if (LII->end != LII->valno->def.getDeadSlot())
1025 MachineInstr *MI = LIS.getInstructionFromIndex(LII->valno->def);
1026 assert(MI && "Missing instruction for dead def");
1027 MI->addRegisterDead(LI->reg, &TRI);
1029 if (!MI->allDefsAreDead())
1032 DEBUG(dbgs() << "All defs dead: " << *MI);
1040 Edit->eliminateDeadDefs(Dead);
1043 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
1046 // At this point, the live intervals in Edit contain VNInfos corresponding to
1047 // the inserted copies.
1049 // Add the original defs from the parent interval.
1050 for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
1051 E = Edit->getParent().vni_end(); I != E; ++I) {
1052 const VNInfo *ParentVNI = *I;
1053 if (ParentVNI->isUnused())
1055 unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
1056 defValue(RegIdx, ParentVNI, ParentVNI->def);
1058 // Force rematted values to be recomputed everywhere.
1059 // The new live ranges may be truncated.
1060 if (Edit->didRematerialize(ParentVNI))
1061 for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1062 forceRecompute(i, ParentVNI);
1065 // Hoist back-copies to the complement interval when in spill mode.
1066 switch (SpillMode) {
1068 // Leave all back-copies as is.
1071 hoistCopiesForSize();
1074 llvm_unreachable("Spill mode 'speed' not implemented yet");
1077 // Transfer the simply mapped values, check if any are skipped.
1078 bool Skipped = transferValues();
1080 extendPHIKillRanges();
1084 // Rewrite virtual registers, possibly extending ranges.
1085 rewriteAssigned(Skipped);
1087 // Delete defs that were rematted everywhere.
1089 deleteRematVictims();
1091 // Get rid of unused values and set phi-kill flags.
1092 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I)
1093 (*I)->RenumberValues(LIS);
1095 // Provide a reverse mapping from original indices to Edit ranges.
1098 for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1099 LRMap->push_back(i);
1102 // Now check if any registers were separated into multiple components.
1103 ConnectedVNInfoEqClasses ConEQ(LIS);
1104 for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
1105 // Don't use iterators, they are invalidated by create() below.
1106 LiveInterval *li = Edit->get(i);
1107 unsigned NumComp = ConEQ.Classify(li);
1110 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1111 SmallVector<LiveInterval*, 8> dups;
1113 for (unsigned j = 1; j != NumComp; ++j)
1114 dups.push_back(&Edit->create());
1115 ConEQ.Distribute(&dups[0], MRI);
1116 // The new intervals all map back to i.
1118 LRMap->resize(Edit->size(), i);
1121 // Calculate spill weight and allocation hints for new intervals.
1122 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops);
1124 assert(!LRMap || LRMap->size() == Edit->size());
1128 //===----------------------------------------------------------------------===//
1129 // Single Block Splitting
1130 //===----------------------------------------------------------------------===//
1132 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
1133 bool SingleInstrs) const {
1134 // Always split for multiple instructions.
1135 if (!BI.isOneInstr())
1137 // Don't split for single instructions unless explicitly requested.
1140 // Splitting a live-through range always makes progress.
1141 if (BI.LiveIn && BI.LiveOut)
1143 // No point in isolating a copy. It has no register class constraints.
1144 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
1146 // Finally, don't isolate an end point that was created by earlier splits.
1147 return isOriginalEndpoint(BI.FirstInstr);
1150 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
1152 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
1153 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
1155 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
1156 useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
1158 // The last use is after the last valid split point.
1159 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
1160 useIntv(SegStart, SegStop);
1161 overlapIntv(SegStop, BI.LastInstr);
1166 //===----------------------------------------------------------------------===//
1167 // Global Live Range Splitting Support
1168 //===----------------------------------------------------------------------===//
1170 // These methods support a method of global live range splitting that uses a
1171 // global algorithm to decide intervals for CFG edges. They will insert split
1172 // points and color intervals in basic blocks while avoiding interference.
1174 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1175 // are on the stack.
1177 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
1178 unsigned IntvIn, SlotIndex LeaveBefore,
1179 unsigned IntvOut, SlotIndex EnterAfter){
1180 SlotIndex Start, Stop;
1181 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
1183 DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
1184 << ") intf " << LeaveBefore << '-' << EnterAfter
1185 << ", live-through " << IntvIn << " -> " << IntvOut);
1187 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
1189 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
1190 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
1191 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
1193 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
1196 DEBUG(dbgs() << ", spill on entry.\n");
1198 // <<<<<<<<< Possible LeaveBefore interference.
1199 // |-----------| Live through.
1200 // -____________ Spill on entry.
1203 SlotIndex Idx = leaveIntvAtTop(*MBB);
1204 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1210 DEBUG(dbgs() << ", reload on exit.\n");
1212 // >>>>>>> Possible EnterAfter interference.
1213 // |-----------| Live through.
1214 // ___________-- Reload on exit.
1216 selectIntv(IntvOut);
1217 SlotIndex Idx = enterIntvAtEnd(*MBB);
1218 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1223 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
1224 DEBUG(dbgs() << ", straight through.\n");
1226 // |-----------| Live through.
1227 // ------------- Straight through, same intv, no interference.
1229 selectIntv(IntvOut);
1230 useIntv(Start, Stop);
1234 // We cannot legally insert splits after LSP.
1235 SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
1236 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
1238 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
1239 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
1240 DEBUG(dbgs() << ", switch avoiding interference.\n");
1242 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1243 // |-----------| Live through.
1244 // ------======= Switch intervals between interference.
1246 selectIntv(IntvOut);
1248 if (LeaveBefore && LeaveBefore < LSP) {
1249 Idx = enterIntvBefore(LeaveBefore);
1252 Idx = enterIntvAtEnd(*MBB);
1255 useIntv(Start, Idx);
1256 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1257 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1261 DEBUG(dbgs() << ", create local intv for interference.\n");
1263 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1264 // |-----------| Live through.
1265 // ==---------== Switch intervals before/after interference.
1267 assert(LeaveBefore <= EnterAfter && "Missed case");
1269 selectIntv(IntvOut);
1270 SlotIndex Idx = enterIntvAfter(EnterAfter);
1272 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1275 Idx = leaveIntvBefore(LeaveBefore);
1276 useIntv(Start, Idx);
1277 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1281 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
1282 unsigned IntvIn, SlotIndex LeaveBefore) {
1283 SlotIndex Start, Stop;
1284 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1286 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
1287 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1288 << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
1289 << (BI.LiveOut ? ", stack-out" : ", killed in block"));
1291 assert(IntvIn && "Must have register in");
1292 assert(BI.LiveIn && "Must be live-in");
1293 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
1295 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
1296 DEBUG(dbgs() << " before interference.\n");
1298 // <<< Interference after kill.
1299 // |---o---x | Killed in block.
1300 // ========= Use IntvIn everywhere.
1303 useIntv(Start, BI.LastInstr);
1307 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1309 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
1311 // <<< Possible interference after last use.
1312 // |---o---o---| Live-out on stack.
1313 // =========____ Leave IntvIn after last use.
1315 // < Interference after last use.
1316 // |---o---o--o| Live-out on stack, late last use.
1317 // ============ Copy to stack after LSP, overlap IntvIn.
1318 // \_____ Stack interval is live-out.
1320 if (BI.LastInstr < LSP) {
1321 DEBUG(dbgs() << ", spill after last use before interference.\n");
1323 SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
1324 useIntv(Start, Idx);
1325 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1327 DEBUG(dbgs() << ", spill before last split point.\n");
1329 SlotIndex Idx = leaveIntvBefore(LSP);
1330 overlapIntv(Idx, BI.LastInstr);
1331 useIntv(Start, Idx);
1332 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1337 // The interference is overlapping somewhere we wanted to use IntvIn. That
1338 // means we need to create a local interval that can be allocated a
1339 // different register.
1340 unsigned LocalIntv = openIntv();
1342 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
1344 if (!BI.LiveOut || BI.LastInstr < LSP) {
1346 // <<<<<<< Interference overlapping uses.
1347 // |---o---o---| Live-out on stack.
1348 // =====----____ Leave IntvIn before interference, then spill.
1350 SlotIndex To = leaveIntvAfter(BI.LastInstr);
1351 SlotIndex From = enterIntvBefore(LeaveBefore);
1354 useIntv(Start, From);
1355 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1359 // <<<<<<< Interference overlapping uses.
1360 // |---o---o--o| Live-out on stack, late last use.
1361 // =====------- Copy to stack before LSP, overlap LocalIntv.
1362 // \_____ Stack interval is live-out.
1364 SlotIndex To = leaveIntvBefore(LSP);
1365 overlapIntv(To, BI.LastInstr);
1366 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
1369 useIntv(Start, From);
1370 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1373 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
1374 unsigned IntvOut, SlotIndex EnterAfter) {
1375 SlotIndex Start, Stop;
1376 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1378 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
1379 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1380 << ", reg-out " << IntvOut << ", enter after " << EnterAfter
1381 << (BI.LiveIn ? ", stack-in" : ", defined in block"));
1383 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1385 assert(IntvOut && "Must have register out");
1386 assert(BI.LiveOut && "Must be live-out");
1387 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
1389 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
1390 DEBUG(dbgs() << " after interference.\n");
1392 // >>>> Interference before def.
1393 // | o---o---| Defined in block.
1394 // ========= Use IntvOut everywhere.
1396 selectIntv(IntvOut);
1397 useIntv(BI.FirstInstr, Stop);
1401 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
1402 DEBUG(dbgs() << ", reload after interference.\n");
1404 // >>>> Interference before def.
1405 // |---o---o---| Live-through, stack-in.
1406 // ____========= Enter IntvOut before first use.
1408 selectIntv(IntvOut);
1409 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
1411 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1415 // The interference is overlapping somewhere we wanted to use IntvOut. That
1416 // means we need to create a local interval that can be allocated a
1417 // different register.
1418 DEBUG(dbgs() << ", interference overlaps uses.\n");
1420 // >>>>>>> Interference overlapping uses.
1421 // |---o---o---| Live-through, stack-in.
1422 // ____---====== Create local interval for interference range.
1424 selectIntv(IntvOut);
1425 SlotIndex Idx = enterIntvAfter(EnterAfter);
1427 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1430 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));