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 //===----------------------------------------------------------------------===//
16 #include "LiveRangeCalc.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/CodeGen/LiveIntervals.h"
26 #include "llvm/CodeGen/LiveRangeEdit.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SlotIndexes.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetOpcodes.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/CodeGen/VirtRegMap.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/MC/LaneBitmask.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/BlockFrequency.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/raw_ostream.h"
59 #define DEBUG_TYPE "regalloc"
61 STATISTIC(NumFinished, "Number of splits finished");
62 STATISTIC(NumSimple, "Number of splits that were simple");
63 STATISTIC(NumCopies, "Number of copies inserted for splitting");
64 STATISTIC(NumRemats, "Number of rematerialized defs for splitting");
65 STATISTIC(NumRepairs, "Number of invalid live ranges repaired");
67 //===----------------------------------------------------------------------===//
68 // Last Insert Point Analysis
69 //===----------------------------------------------------------------------===//
71 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis,
73 : LIS(lis), LastInsertPoint(BBNum) {}
76 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI,
77 const MachineBasicBlock &MBB) {
78 unsigned Num = MBB.getNumber();
79 std::pair<SlotIndex, SlotIndex> &LIP = LastInsertPoint[Num];
80 SlotIndex MBBEnd = LIS.getMBBEndIdx(&MBB);
82 SmallVector<const MachineBasicBlock *, 1> EHPadSuccessors;
83 for (const MachineBasicBlock *SMBB : MBB.successors())
85 EHPadSuccessors.push_back(SMBB);
87 // Compute insert points on the first call. The pair is independent of the
88 // current live interval.
89 if (!LIP.first.isValid()) {
90 MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator();
91 if (FirstTerm == MBB.end())
94 LIP.first = LIS.getInstructionIndex(*FirstTerm);
96 // If there is a landing pad successor, also find the call instruction.
97 if (EHPadSuccessors.empty())
99 // There may not be a call instruction (?) in which case we ignore LPad.
100 LIP.second = LIP.first;
101 for (MachineBasicBlock::const_iterator I = MBB.end(), E = MBB.begin();
105 LIP.second = LIS.getInstructionIndex(*I);
111 // If CurLI is live into a landing pad successor, move the last insert point
112 // back to the call that may throw.
116 if (none_of(EHPadSuccessors, [&](const MachineBasicBlock *EHPad) {
117 return LIS.isLiveInToMBB(CurLI, EHPad);
121 // Find the value leaving MBB.
122 const VNInfo *VNI = CurLI.getVNInfoBefore(MBBEnd);
126 // If the value leaving MBB was defined after the call in MBB, it can't
127 // really be live-in to the landing pad. This can happen if the landing pad
128 // has a PHI, and this register is undef on the exceptional edge.
129 // <rdar://problem/10664933>
130 if (!SlotIndex::isEarlierInstr(VNI->def, LIP.second) && VNI->def < MBBEnd)
133 // Value is properly live-in to the landing pad.
134 // Only allow inserts before the call.
138 MachineBasicBlock::iterator
139 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI,
140 MachineBasicBlock &MBB) {
141 SlotIndex LIP = getLastInsertPoint(CurLI, MBB);
142 if (LIP == LIS.getMBBEndIdx(&MBB))
144 return LIS.getInstructionFromIndex(LIP);
147 //===----------------------------------------------------------------------===//
149 //===----------------------------------------------------------------------===//
151 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
152 const MachineLoopInfo &mli)
153 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
154 TII(*MF.getSubtarget().getInstrInfo()), IPA(lis, MF.getNumBlockIDs()) {}
156 void SplitAnalysis::clear() {
159 ThroughBlocks.clear();
161 DidRepairRange = false;
164 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
165 void SplitAnalysis::analyzeUses() {
166 assert(UseSlots.empty() && "Call clear first");
168 // First get all the defs from the interval values. This provides the correct
169 // slots for early clobbers.
170 for (const VNInfo *VNI : CurLI->valnos)
171 if (!VNI->isPHIDef() && !VNI->isUnused())
172 UseSlots.push_back(VNI->def);
174 // Get use slots form the use-def chain.
175 const MachineRegisterInfo &MRI = MF.getRegInfo();
176 for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg))
178 UseSlots.push_back(LIS.getInstructionIndex(*MO.getParent()).getRegSlot());
180 array_pod_sort(UseSlots.begin(), UseSlots.end());
182 // Remove duplicates, keeping the smaller slot for each instruction.
183 // That is what we want for early clobbers.
184 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
185 SlotIndex::isSameInstr),
188 // Compute per-live block info.
189 if (!calcLiveBlockInfo()) {
190 // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
191 // I am looking at you, RegisterCoalescer!
192 DidRepairRange = true;
194 DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
195 const_cast<LiveIntervals&>(LIS)
196 .shrinkToUses(const_cast<LiveInterval*>(CurLI));
198 ThroughBlocks.clear();
199 bool fixed = calcLiveBlockInfo();
201 assert(fixed && "Couldn't fix broken live interval");
204 DEBUG(dbgs() << "Analyze counted "
205 << UseSlots.size() << " instrs in "
206 << UseBlocks.size() << " blocks, through "
207 << NumThroughBlocks << " blocks.\n");
210 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
211 /// where CurLI is live.
212 bool SplitAnalysis::calcLiveBlockInfo() {
213 ThroughBlocks.resize(MF.getNumBlockIDs());
214 NumThroughBlocks = NumGapBlocks = 0;
218 LiveInterval::const_iterator LVI = CurLI->begin();
219 LiveInterval::const_iterator LVE = CurLI->end();
221 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
222 UseI = UseSlots.begin();
223 UseE = UseSlots.end();
225 // Loop over basic blocks where CurLI is live.
226 MachineFunction::iterator MFI =
227 LIS.getMBBFromIndex(LVI->start)->getIterator();
231 SlotIndex Start, Stop;
232 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
234 // If the block contains no uses, the range must be live through. At one
235 // point, RegisterCoalescer could create dangling ranges that ended
237 if (UseI == UseE || *UseI >= Stop) {
239 ThroughBlocks.set(BI.MBB->getNumber());
240 // The range shouldn't end mid-block if there are no uses. This shouldn't
245 // This block has uses. Find the first and last uses in the block.
246 BI.FirstInstr = *UseI;
247 assert(BI.FirstInstr >= Start);
249 while (UseI != UseE && *UseI < Stop);
250 BI.LastInstr = UseI[-1];
251 assert(BI.LastInstr < Stop);
253 // LVI is the first live segment overlapping MBB.
254 BI.LiveIn = LVI->start <= Start;
256 // When not live in, the first use should be a def.
258 assert(LVI->start == LVI->valno->def && "Dangling Segment start");
259 assert(LVI->start == BI.FirstInstr && "First instr should be a def");
260 BI.FirstDef = BI.FirstInstr;
263 // Look for gaps in the live range.
265 while (LVI->end < Stop) {
266 SlotIndex LastStop = LVI->end;
267 if (++LVI == LVE || LVI->start >= Stop) {
269 BI.LastInstr = LastStop;
273 if (LastStop < LVI->start) {
274 // There is a gap in the live range. Create duplicate entries for the
275 // live-in snippet and the live-out snippet.
278 // Push the Live-in part.
280 UseBlocks.push_back(BI);
281 UseBlocks.back().LastInstr = LastStop;
283 // Set up BI for the live-out part.
286 BI.FirstInstr = BI.FirstDef = LVI->start;
289 // A Segment that starts in the middle of the block must be a def.
290 assert(LVI->start == LVI->valno->def && "Dangling Segment start");
292 BI.FirstDef = LVI->start;
295 UseBlocks.push_back(BI);
297 // LVI is now at LVE or LVI->end >= Stop.
302 // Live segment ends exactly at Stop. Move to the next segment.
303 if (LVI->end == Stop && ++LVI == LVE)
306 // Pick the next basic block.
307 if (LVI->start < Stop)
310 MFI = LIS.getMBBFromIndex(LVI->start)->getIterator();
313 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
317 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
320 LiveInterval *li = const_cast<LiveInterval*>(cli);
321 LiveInterval::iterator LVI = li->begin();
322 LiveInterval::iterator LVE = li->end();
325 // Loop over basic blocks where li is live.
326 MachineFunction::const_iterator MFI =
327 LIS.getMBBFromIndex(LVI->start)->getIterator();
328 SlotIndex Stop = LIS.getMBBEndIdx(&*MFI);
331 LVI = li->advanceTo(LVI, Stop);
336 Stop = LIS.getMBBEndIdx(&*MFI);
337 } while (Stop <= LVI->start);
341 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
342 unsigned OrigReg = VRM.getOriginal(CurLI->reg);
343 const LiveInterval &Orig = LIS.getInterval(OrigReg);
344 assert(!Orig.empty() && "Splitting empty interval?");
345 LiveInterval::const_iterator I = Orig.find(Idx);
347 // Range containing Idx should begin at Idx.
348 if (I != Orig.end() && I->start <= Idx)
349 return I->start == Idx;
351 // Range does not contain Idx, previous must end at Idx.
352 return I != Orig.begin() && (--I)->end == Idx;
355 void SplitAnalysis::analyze(const LiveInterval *li) {
361 //===----------------------------------------------------------------------===//
363 //===----------------------------------------------------------------------===//
365 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
366 SplitEditor::SplitEditor(SplitAnalysis &sa, AliasAnalysis &aa,
367 LiveIntervals &lis, VirtRegMap &vrm,
368 MachineDominatorTree &mdt,
369 MachineBlockFrequencyInfo &mbfi)
370 : SA(sa), AA(aa), LIS(lis), VRM(vrm),
371 MRI(vrm.getMachineFunction().getRegInfo()), MDT(mdt),
372 TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()),
373 TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()),
374 MBFI(mbfi), RegAssign(Allocator) {}
376 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
383 // Reset the LiveRangeCalc instances needed for this spill mode.
384 LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
385 &LIS.getVNInfoAllocator());
387 LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
388 &LIS.getVNInfoAllocator());
390 // We don't need an AliasAnalysis since we will only be performing
391 // cheap-as-a-copy remats anyway.
392 Edit->anyRematerializable(nullptr);
395 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
396 LLVM_DUMP_METHOD void SplitEditor::dump() const {
397 if (RegAssign.empty()) {
398 dbgs() << " empty\n";
402 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
403 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
408 LiveInterval::SubRange &SplitEditor::getSubRangeForMask(LaneBitmask LM,
410 for (LiveInterval::SubRange &S : LI.subranges())
411 if (S.LaneMask == LM)
413 llvm_unreachable("SubRange for this mask not found");
416 void SplitEditor::addDeadDef(LiveInterval &LI, VNInfo *VNI, bool Original) {
417 if (!LI.hasSubRanges()) {
418 LI.createDeadDef(VNI);
422 SlotIndex Def = VNI->def;
424 // If we are transferring a def from the original interval, make sure
425 // to only update the subranges for which the original subranges had
426 // a def at this location.
427 for (LiveInterval::SubRange &S : LI.subranges()) {
428 auto &PS = getSubRangeForMask(S.LaneMask, Edit->getParent());
429 VNInfo *PV = PS.getVNInfoAt(Def);
430 if (PV != nullptr && PV->def == Def)
431 S.createDeadDef(Def, LIS.getVNInfoAllocator());
434 // This is a new def: either from rematerialization, or from an inserted
435 // copy. Since rematerialization can regenerate a definition of a sub-
436 // register, we need to check which subranges need to be updated.
437 const MachineInstr *DefMI = LIS.getInstructionFromIndex(Def);
438 assert(DefMI != nullptr);
440 for (const MachineOperand &DefOp : DefMI->defs()) {
441 unsigned R = DefOp.getReg();
444 if (unsigned SR = DefOp.getSubReg())
445 LM |= TRI.getSubRegIndexLaneMask(SR);
447 LM = MRI.getMaxLaneMaskForVReg(R);
451 for (LiveInterval::SubRange &S : LI.subranges())
452 if ((S.LaneMask & LM).any())
453 S.createDeadDef(Def, LIS.getVNInfoAllocator());
457 VNInfo *SplitEditor::defValue(unsigned RegIdx,
458 const VNInfo *ParentVNI,
461 assert(ParentVNI && "Mapping NULL value");
462 assert(Idx.isValid() && "Invalid SlotIndex");
463 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
464 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
466 // Create a new value.
467 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
469 bool Force = LI->hasSubRanges();
470 ValueForcePair FP(Force ? nullptr : VNI, Force);
471 // Use insert for lookup, so we can add missing values with a second lookup.
472 std::pair<ValueMap::iterator, bool> InsP =
473 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), FP));
475 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not
476 // forced. Keep it as a simple def without any liveness.
477 if (!Force && InsP.second)
480 // If the previous value was a simple mapping, add liveness for it now.
481 if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
482 addDeadDef(*LI, OldVNI, Original);
484 // No longer a simple mapping. Switch to a complex mapping. If the
485 // interval has subranges, make it a forced mapping.
486 InsP.first->second = ValueForcePair(nullptr, Force);
489 // This is a complex mapping, add liveness for VNI
490 addDeadDef(*LI, VNI, Original);
494 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
495 assert(ParentVNI && "Mapping NULL value");
496 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
497 VNInfo *VNI = VFP.getPointer();
499 // ParentVNI was either unmapped or already complex mapped. Either way, just
500 // set the force bit.
506 // This was previously a single mapping. Make sure the old def is represented
507 // by a trivial live range.
508 addDeadDef(LIS.getInterval(Edit->get(RegIdx)), VNI, false);
510 // Mark as complex mapped, forced.
511 VFP = ValueForcePair(nullptr, true);
514 SlotIndex SplitEditor::buildSingleSubRegCopy(unsigned FromReg, unsigned ToReg,
515 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
516 unsigned SubIdx, LiveInterval &DestLI, bool Late, SlotIndex Def) {
517 const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY);
518 bool FirstCopy = !Def.isValid();
519 MachineInstr *CopyMI = BuildMI(MBB, InsertBefore, DebugLoc(), Desc)
520 .addReg(ToReg, RegState::Define | getUndefRegState(FirstCopy)
521 | getInternalReadRegState(!FirstCopy), SubIdx)
522 .addReg(FromReg, 0, SubIdx);
524 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
526 SlotIndexes &Indexes = *LIS.getSlotIndexes();
527 Def = Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot();
529 CopyMI->bundleWithPred();
531 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubIdx);
532 DestLI.refineSubRanges(Allocator, LaneMask,
533 [Def, &Allocator](LiveInterval::SubRange& SR) {
534 SR.createDeadDef(Def, Allocator);
539 SlotIndex SplitEditor::buildCopy(unsigned FromReg, unsigned ToReg,
540 LaneBitmask LaneMask, MachineBasicBlock &MBB,
541 MachineBasicBlock::iterator InsertBefore, bool Late, unsigned RegIdx) {
542 const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY);
543 if (LaneMask.all() || LaneMask == MRI.getMaxLaneMaskForVReg(FromReg)) {
544 // The full vreg is copied.
545 MachineInstr *CopyMI =
546 BuildMI(MBB, InsertBefore, DebugLoc(), Desc, ToReg).addReg(FromReg);
547 SlotIndexes &Indexes = *LIS.getSlotIndexes();
548 return Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot();
551 // Only a subset of lanes needs to be copied. The following is a simple
552 // heuristic to construct a sequence of COPYs. We could add a target
553 // specific callback if this turns out to be suboptimal.
554 LiveInterval &DestLI = LIS.getInterval(Edit->get(RegIdx));
556 // First pass: Try to find a perfectly matching subregister index. If none
557 // exists find the one covering the most lanemask bits.
558 SmallVector<unsigned, 8> PossibleIndexes;
559 unsigned BestIdx = 0;
560 unsigned BestCover = 0;
561 const TargetRegisterClass *RC = MRI.getRegClass(FromReg);
562 assert(RC == MRI.getRegClass(ToReg) && "Should have same reg class");
563 for (unsigned Idx = 1, E = TRI.getNumSubRegIndices(); Idx < E; ++Idx) {
564 // Is this index even compatible with the given class?
565 if (TRI.getSubClassWithSubReg(RC, Idx) != RC)
567 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(Idx);
568 // Early exit if we found a perfect match.
569 if (SubRegMask == LaneMask) {
574 // The index must not cover any lanes outside \p LaneMask.
575 if ((SubRegMask & ~LaneMask).any())
578 unsigned PopCount = SubRegMask.getNumLanes();
579 PossibleIndexes.push_back(Idx);
580 if (PopCount > BestCover) {
581 BestCover = PopCount;
586 // Abort if we cannot possibly implement the COPY with the given indexes.
588 report_fatal_error("Impossible to implement partial COPY");
590 SlotIndex Def = buildSingleSubRegCopy(FromReg, ToReg, MBB, InsertBefore,
591 BestIdx, DestLI, Late, SlotIndex());
593 // Greedy heuristic: Keep iterating keeping the best covering subreg index
595 LaneBitmask LanesLeft = LaneMask & ~(TRI.getSubRegIndexLaneMask(BestIdx));
596 while (LanesLeft.any()) {
597 unsigned BestIdx = 0;
598 int BestCover = std::numeric_limits<int>::min();
599 for (unsigned Idx : PossibleIndexes) {
600 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(Idx);
601 // Early exit if we found a perfect match.
602 if (SubRegMask == LanesLeft) {
607 // Try to cover as much of the remaining lanes as possible but
608 // as few of the already covered lanes as possible.
609 int Cover = (SubRegMask & LanesLeft).getNumLanes()
610 - (SubRegMask & ~LanesLeft).getNumLanes();
611 if (Cover > BestCover) {
618 report_fatal_error("Impossible to implement partial COPY");
620 buildSingleSubRegCopy(FromReg, ToReg, MBB, InsertBefore, BestIdx,
622 LanesLeft &= ~TRI.getSubRegIndexLaneMask(BestIdx);
628 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
631 MachineBasicBlock &MBB,
632 MachineBasicBlock::iterator I) {
634 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
636 // We may be trying to avoid interference that ends at a deleted instruction,
637 // so always begin RegIdx 0 early and all others late.
638 bool Late = RegIdx != 0;
640 // Attempt cheap-as-a-copy rematerialization.
641 unsigned Original = VRM.getOriginal(Edit->get(RegIdx));
642 LiveInterval &OrigLI = LIS.getInterval(Original);
643 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
645 unsigned Reg = LI->reg;
646 bool DidRemat = false;
648 LiveRangeEdit::Remat RM(ParentVNI);
649 RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
650 if (Edit->canRematerializeAt(RM, OrigVNI, UseIdx, true)) {
651 Def = Edit->rematerializeAt(MBB, I, Reg, RM, TRI, Late);
657 LaneBitmask LaneMask;
658 if (LI->hasSubRanges()) {
659 LaneMask = LaneBitmask::getNone();
660 for (LiveInterval::SubRange &S : LI->subranges())
661 LaneMask |= S.LaneMask;
663 LaneMask = LaneBitmask::getAll();
667 Def = buildCopy(Edit->getReg(), Reg, LaneMask, MBB, I, Late, RegIdx);
670 // Define the value in Reg.
671 return defValue(RegIdx, ParentVNI, Def, false);
674 /// Create a new virtual register and live interval.
675 unsigned SplitEditor::openIntv() {
676 // Create the complement as index 0.
678 Edit->createEmptyInterval();
680 // Create the open interval.
681 OpenIdx = Edit->size();
682 Edit->createEmptyInterval();
686 void SplitEditor::selectIntv(unsigned Idx) {
687 assert(Idx != 0 && "Cannot select the complement interval");
688 assert(Idx < Edit->size() && "Can only select previously opened interval");
689 DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n');
693 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
694 assert(OpenIdx && "openIntv not called before enterIntvBefore");
695 DEBUG(dbgs() << " enterIntvBefore " << Idx);
696 Idx = Idx.getBaseIndex();
697 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
699 DEBUG(dbgs() << ": not live\n");
702 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
703 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
704 assert(MI && "enterIntvBefore called with invalid index");
706 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
710 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
711 assert(OpenIdx && "openIntv not called before enterIntvAfter");
712 DEBUG(dbgs() << " enterIntvAfter " << Idx);
713 Idx = Idx.getBoundaryIndex();
714 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
716 DEBUG(dbgs() << ": not live\n");
719 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
720 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
721 assert(MI && "enterIntvAfter called with invalid index");
723 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
724 std::next(MachineBasicBlock::iterator(MI)));
728 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
729 assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
730 SlotIndex End = LIS.getMBBEndIdx(&MBB);
731 SlotIndex Last = End.getPrevSlot();
732 DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB) << ", "
734 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
736 DEBUG(dbgs() << ": not live\n");
739 DEBUG(dbgs() << ": valno " << ParentVNI->id);
740 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
741 SA.getLastSplitPointIter(&MBB));
742 RegAssign.insert(VNI->def, End, OpenIdx);
747 /// useIntv - indicate that all instructions in MBB should use OpenLI.
748 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
749 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
752 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
753 assert(OpenIdx && "openIntv not called before useIntv");
754 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
755 RegAssign.insert(Start, End, OpenIdx);
759 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
760 assert(OpenIdx && "openIntv not called before leaveIntvAfter");
761 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
763 // The interval must be live beyond the instruction at Idx.
764 SlotIndex Boundary = Idx.getBoundaryIndex();
765 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
767 DEBUG(dbgs() << ": not live\n");
768 return Boundary.getNextSlot();
770 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
771 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
772 assert(MI && "No instruction at index");
774 // In spill mode, make live ranges as short as possible by inserting the copy
775 // before MI. This is only possible if that instruction doesn't redefine the
776 // value. The inserted COPY is not a kill, and we don't need to recompute
777 // the source live range. The spiller also won't try to hoist this copy.
778 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
779 MI->readsVirtualRegister(Edit->getReg())) {
780 forceRecompute(0, ParentVNI);
781 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
785 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
786 std::next(MachineBasicBlock::iterator(MI)));
790 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
791 assert(OpenIdx && "openIntv not called before leaveIntvBefore");
792 DEBUG(dbgs() << " leaveIntvBefore " << Idx);
794 // The interval must be live into the instruction at Idx.
795 Idx = Idx.getBaseIndex();
796 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
798 DEBUG(dbgs() << ": not live\n");
799 return Idx.getNextSlot();
801 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
803 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
804 assert(MI && "No instruction at index");
805 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
809 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
810 assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
811 SlotIndex Start = LIS.getMBBStartIdx(&MBB);
812 DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB) << ", "
815 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
817 DEBUG(dbgs() << ": not live\n");
821 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
822 MBB.SkipPHIsLabelsAndDebug(MBB.begin()));
823 RegAssign.insert(Start, VNI->def, OpenIdx);
828 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
829 assert(OpenIdx && "openIntv not called before overlapIntv");
830 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
831 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
832 "Parent changes value in extended range");
833 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
834 "Range cannot span basic blocks");
836 // The complement interval will be extended as needed by LRCalc.extend().
838 forceRecompute(0, ParentVNI);
839 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
840 RegAssign.insert(Start, End, OpenIdx);
844 //===----------------------------------------------------------------------===//
846 //===----------------------------------------------------------------------===//
848 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
849 LiveInterval *LI = &LIS.getInterval(Edit->get(0));
850 DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
851 RegAssignMap::iterator AssignI;
852 AssignI.setMap(RegAssign);
854 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
855 SlotIndex Def = Copies[i]->def;
856 MachineInstr *MI = LIS.getInstructionFromIndex(Def);
857 assert(MI && "No instruction for back-copy");
859 MachineBasicBlock *MBB = MI->getParent();
860 MachineBasicBlock::iterator MBBI(MI);
862 do AtBegin = MBBI == MBB->begin();
863 while (!AtBegin && (--MBBI)->isDebugValue());
865 DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
866 LIS.removeVRegDefAt(*LI, Def);
867 LIS.RemoveMachineInstrFromMaps(*MI);
868 MI->eraseFromParent();
870 // Adjust RegAssign if a register assignment is killed at Def. We want to
871 // avoid calculating the live range of the source register if possible.
872 AssignI.find(Def.getPrevSlot());
873 if (!AssignI.valid() || AssignI.start() >= Def)
875 // If MI doesn't kill the assigned register, just leave it.
876 if (AssignI.stop() != Def)
878 unsigned RegIdx = AssignI.value();
879 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
880 DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n');
881 forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
883 SlotIndex Kill = LIS.getInstructionIndex(*MBBI).getRegSlot();
884 DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI);
885 AssignI.setStop(Kill);
891 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
892 MachineBasicBlock *DefMBB) {
895 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
897 const MachineLoopInfo &Loops = SA.Loops;
898 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
899 MachineDomTreeNode *DefDomNode = MDT[DefMBB];
901 // Best candidate so far.
902 MachineBasicBlock *BestMBB = MBB;
903 unsigned BestDepth = std::numeric_limits<unsigned>::max();
906 const MachineLoop *Loop = Loops.getLoopFor(MBB);
908 // MBB isn't in a loop, it doesn't get any better. All dominators have a
909 // higher frequency by definition.
911 DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) << " dominates "
912 << printMBBReference(*MBB) << " at depth 0\n");
916 // We'll never be able to exit the DefLoop.
917 if (Loop == DefLoop) {
918 DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) << " dominates "
919 << printMBBReference(*MBB) << " in the same loop\n");
923 // Least busy dominator seen so far.
924 unsigned Depth = Loop->getLoopDepth();
925 if (Depth < BestDepth) {
928 DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) << " dominates "
929 << printMBBReference(*MBB) << " at depth " << Depth << '\n');
932 // Leave loop by going to the immediate dominator of the loop header.
933 // This is a bigger stride than simply walking up the dominator tree.
934 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
936 // Too far up the dominator tree?
937 if (!IDom || !MDT.dominates(DefDomNode, IDom))
940 MBB = IDom->getBlock();
944 void SplitEditor::computeRedundantBackCopies(
945 DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) {
946 LiveInterval *LI = &LIS.getInterval(Edit->get(0));
947 LiveInterval *Parent = &Edit->getParent();
948 SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums());
949 SmallPtrSet<VNInfo *, 8> DominatedVNIs;
951 // Aggregate VNIs having the same value as ParentVNI.
952 for (VNInfo *VNI : LI->valnos) {
955 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
956 EqualVNs[ParentVNI->id].insert(VNI);
959 // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
960 // redundant VNIs to BackCopies.
961 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
962 VNInfo *ParentVNI = Parent->getValNumInfo(i);
963 if (!NotToHoistSet.count(ParentVNI->id))
965 SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin();
966 SmallPtrSetIterator<VNInfo *> It2 = It1;
967 for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) {
969 for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) {
970 if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2))
973 MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def);
974 MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def);
976 DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1));
977 } else if (MDT.dominates(MBB1, MBB2)) {
978 DominatedVNIs.insert(*It2);
979 } else if (MDT.dominates(MBB2, MBB1)) {
980 DominatedVNIs.insert(*It1);
984 if (!DominatedVNIs.empty()) {
985 forceRecompute(0, ParentVNI);
986 for (auto VNI : DominatedVNIs) {
987 BackCopies.push_back(VNI);
989 DominatedVNIs.clear();
994 /// For SM_Size mode, find a common dominator for all the back-copies for
995 /// the same ParentVNI and hoist the backcopies to the dominator BB.
996 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial
997 /// to do the hoisting, simply remove the dominated backcopies for the same
999 void SplitEditor::hoistCopies() {
1000 // Get the complement interval, always RegIdx 0.
1001 LiveInterval *LI = &LIS.getInterval(Edit->get(0));
1002 LiveInterval *Parent = &Edit->getParent();
1004 // Track the nearest common dominator for all back-copies for each ParentVNI,
1005 // indexed by ParentVNI->id.
1006 using DomPair = std::pair<MachineBasicBlock *, SlotIndex>;
1007 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
1008 // The total cost of all the back-copies for each ParentVNI.
1009 SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums());
1010 // The ParentVNI->id set for which hoisting back-copies are not beneficial
1012 DenseSet<unsigned> NotToHoistSet;
1014 // Find the nearest common dominator for parent values with multiple
1015 // back-copies. If a single back-copy dominates, put it in DomPair.second.
1016 for (VNInfo *VNI : LI->valnos) {
1017 if (VNI->isUnused())
1019 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
1020 assert(ParentVNI && "Parent not live at complement def");
1022 // Don't hoist remats. The complement is probably going to disappear
1023 // completely anyway.
1024 if (Edit->didRematerialize(ParentVNI))
1027 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
1029 DomPair &Dom = NearestDom[ParentVNI->id];
1031 // Keep directly defined parent values. This is either a PHI or an
1032 // instruction in the complement range. All other copies of ParentVNI
1033 // should be eliminated.
1034 if (VNI->def == ParentVNI->def) {
1035 DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
1036 Dom = DomPair(ValMBB, VNI->def);
1039 // Skip the singly mapped values. There is nothing to gain from hoisting a
1040 // single back-copy.
1041 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
1042 DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
1047 // First time we see ParentVNI. VNI dominates itself.
1048 Dom = DomPair(ValMBB, VNI->def);
1049 } else if (Dom.first == ValMBB) {
1050 // Two defs in the same block. Pick the earlier def.
1051 if (!Dom.second.isValid() || VNI->def < Dom.second)
1052 Dom.second = VNI->def;
1054 // Different basic blocks. Check if one dominates.
1055 MachineBasicBlock *Near =
1056 MDT.findNearestCommonDominator(Dom.first, ValMBB);
1058 // Def ValMBB dominates.
1059 Dom = DomPair(ValMBB, VNI->def);
1060 else if (Near != Dom.first)
1061 // None dominate. Hoist to common dominator, need new def.
1062 Dom = DomPair(Near, SlotIndex());
1063 Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB);
1066 DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
1067 << " for parent " << ParentVNI->id << '@' << ParentVNI->def
1068 << " hoist to " << printMBBReference(*Dom.first) << ' '
1069 << Dom.second << '\n');
1072 // Insert the hoisted copies.
1073 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
1074 DomPair &Dom = NearestDom[i];
1075 if (!Dom.first || Dom.second.isValid())
1077 // This value needs a hoisted copy inserted at the end of Dom.first.
1078 VNInfo *ParentVNI = Parent->getValNumInfo(i);
1079 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
1080 // Get a less loopy dominator than Dom.first.
1081 Dom.first = findShallowDominator(Dom.first, DefMBB);
1082 if (SpillMode == SM_Speed &&
1083 MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) {
1084 NotToHoistSet.insert(ParentVNI->id);
1087 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
1089 defFromParent(0, ParentVNI, Last, *Dom.first,
1090 SA.getLastSplitPointIter(Dom.first))->def;
1093 // Remove redundant back-copies that are now known to be dominated by another
1094 // def with the same value.
1095 SmallVector<VNInfo*, 8> BackCopies;
1096 for (VNInfo *VNI : LI->valnos) {
1097 if (VNI->isUnused())
1099 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
1100 const DomPair &Dom = NearestDom[ParentVNI->id];
1101 if (!Dom.first || Dom.second == VNI->def ||
1102 NotToHoistSet.count(ParentVNI->id))
1104 BackCopies.push_back(VNI);
1105 forceRecompute(0, ParentVNI);
1108 // If it is not beneficial to hoist all the BackCopies, simply remove
1109 // redundant BackCopies in speed mode.
1110 if (SpillMode == SM_Speed && !NotToHoistSet.empty())
1111 computeRedundantBackCopies(NotToHoistSet, BackCopies);
1113 removeBackCopies(BackCopies);
1116 /// transferValues - Transfer all possible values to the new live ranges.
1117 /// Values that were rematerialized are left alone, they need LRCalc.extend().
1118 bool SplitEditor::transferValues() {
1119 bool Skipped = false;
1120 RegAssignMap::const_iterator AssignI = RegAssign.begin();
1121 for (const LiveRange::Segment &S : Edit->getParent()) {
1122 DEBUG(dbgs() << " blit " << S << ':');
1123 VNInfo *ParentVNI = S.valno;
1124 // RegAssign has holes where RegIdx 0 should be used.
1125 SlotIndex Start = S.start;
1126 AssignI.advanceTo(Start);
1129 SlotIndex End = S.end;
1130 if (!AssignI.valid()) {
1132 } else if (AssignI.start() <= Start) {
1133 RegIdx = AssignI.value();
1134 if (AssignI.stop() < End) {
1135 End = AssignI.stop();
1140 End = std::min(End, AssignI.start());
1143 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
1144 DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx
1145 << '(' << printReg(Edit->get(RegIdx)) << ')');
1146 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
1148 // Check for a simply defined value that can be blitted directly.
1149 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
1150 if (VNInfo *VNI = VFP.getPointer()) {
1151 DEBUG(dbgs() << ':' << VNI->id);
1152 LI.addSegment(LiveInterval::Segment(Start, End, VNI));
1157 // Skip values with forced recomputation.
1159 DEBUG(dbgs() << "(recalc)");
1165 LiveRangeCalc &LRC = getLRCalc(RegIdx);
1167 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
1168 // so the live range is accurate. Add live-in blocks in [Start;End) to the
1170 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1171 SlotIndex BlockStart, BlockEnd;
1172 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB);
1174 // The first block may be live-in, or it may have its own def.
1175 if (Start != BlockStart) {
1176 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End));
1177 assert(VNI && "Missing def for complex mapped value");
1178 DEBUG(dbgs() << ':' << VNI->id << "*" << printMBBReference(*MBB));
1179 // MBB has its own def. Is it also live-out?
1180 if (BlockEnd <= End)
1181 LRC.setLiveOutValue(&*MBB, VNI);
1183 // Skip to the next block for live-in.
1185 BlockStart = BlockEnd;
1188 // Handle the live-in blocks covered by [Start;End).
1189 assert(Start <= BlockStart && "Expected live-in block");
1190 while (BlockStart < End) {
1191 DEBUG(dbgs() << ">" << printMBBReference(*MBB));
1192 BlockEnd = LIS.getMBBEndIdx(&*MBB);
1193 if (BlockStart == ParentVNI->def) {
1194 // This block has the def of a parent PHI, so it isn't live-in.
1195 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
1196 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End));
1197 assert(VNI && "Missing def for complex mapped parent PHI");
1198 if (End >= BlockEnd)
1199 LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well.
1201 // This block needs a live-in value. The last block covered may not
1204 LRC.addLiveInBlock(LI, MDT[&*MBB], End);
1206 // Live-through, and we don't know the value.
1207 LRC.addLiveInBlock(LI, MDT[&*MBB]);
1208 LRC.setLiveOutValue(&*MBB, nullptr);
1211 BlockStart = BlockEnd;
1215 } while (Start != S.end);
1216 DEBUG(dbgs() << '\n');
1219 LRCalc[0].calculateValues();
1221 LRCalc[1].calculateValues();
1226 static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) {
1227 const LiveRange::Segment *Seg = LR.getSegmentContaining(Def);
1230 if (Seg->end != Def.getDeadSlot())
1232 // This is a dead PHI. Remove it.
1233 LR.removeSegment(*Seg, true);
1237 void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveRangeCalc &LRC,
1238 LiveRange &LR, LaneBitmask LM,
1239 ArrayRef<SlotIndex> Undefs) {
1240 for (MachineBasicBlock *P : B.predecessors()) {
1241 SlotIndex End = LIS.getMBBEndIdx(P);
1242 SlotIndex LastUse = End.getPrevSlot();
1243 // The predecessor may not have a live-out value. That is OK, like an
1244 // undef PHI operand.
1245 LiveInterval &PLI = Edit->getParent();
1246 // Need the cast because the inputs to ?: would otherwise be deemed
1247 // "incompatible": SubRange vs LiveInterval.
1248 LiveRange &PSR = !LM.all() ? getSubRangeForMask(LM, PLI)
1249 : static_cast<LiveRange&>(PLI);
1250 if (PSR.liveAt(LastUse))
1251 LRC.extend(LR, End, /*PhysReg=*/0, Undefs);
1255 void SplitEditor::extendPHIKillRanges() {
1256 // Extend live ranges to be live-out for successor PHI values.
1258 // Visit each PHI def slot in the parent live interval. If the def is dead,
1259 // remove it. Otherwise, extend the live interval to reach the end indexes
1260 // of all predecessor blocks.
1262 LiveInterval &ParentLI = Edit->getParent();
1263 for (const VNInfo *V : ParentLI.valnos) {
1264 if (V->isUnused() || !V->isPHIDef())
1267 unsigned RegIdx = RegAssign.lookup(V->def);
1268 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
1269 LiveRangeCalc &LRC = getLRCalc(RegIdx);
1270 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def);
1271 if (!removeDeadSegment(V->def, LI))
1272 extendPHIRange(B, LRC, LI, LaneBitmask::getAll(), /*Undefs=*/{});
1275 SmallVector<SlotIndex, 4> Undefs;
1276 LiveRangeCalc SubLRC;
1278 for (LiveInterval::SubRange &PS : ParentLI.subranges()) {
1279 for (const VNInfo *V : PS.valnos) {
1280 if (V->isUnused() || !V->isPHIDef())
1282 unsigned RegIdx = RegAssign.lookup(V->def);
1283 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
1284 LiveInterval::SubRange &S = getSubRangeForMask(PS.LaneMask, LI);
1285 if (removeDeadSegment(V->def, S))
1288 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def);
1289 SubLRC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
1290 &LIS.getVNInfoAllocator());
1292 LI.computeSubRangeUndefs(Undefs, PS.LaneMask, MRI, *LIS.getSlotIndexes());
1293 extendPHIRange(B, SubLRC, S, PS.LaneMask, Undefs);
1298 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
1299 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
1301 ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N)
1302 : MO(O), RegIdx(R), Next(N) {}
1309 SmallVector<ExtPoint,4> ExtPoints;
1311 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
1312 RE = MRI.reg_end(); RI != RE;) {
1313 MachineOperand &MO = *RI;
1314 MachineInstr *MI = MO.getParent();
1316 // LiveDebugVariables should have handled all DBG_VALUE instructions.
1317 if (MI->isDebugValue()) {
1318 DEBUG(dbgs() << "Zapping " << *MI);
1323 // <undef> operands don't really read the register, so it doesn't matter
1324 // which register we choose. When the use operand is tied to a def, we must
1325 // use the same register as the def, so just do that always.
1326 SlotIndex Idx = LIS.getInstructionIndex(*MI);
1327 if (MO.isDef() || MO.isUndef())
1328 Idx = Idx.getRegSlot(MO.isEarlyClobber());
1330 // Rewrite to the mapped register at Idx.
1331 unsigned RegIdx = RegAssign.lookup(Idx);
1332 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx));
1334 DEBUG(dbgs() << " rewr " << printMBBReference(*MI->getParent()) << '\t'
1335 << Idx << ':' << RegIdx << '\t' << *MI);
1337 // Extend liveness to Idx if the instruction reads reg.
1338 if (!ExtendRanges || MO.isUndef())
1341 // Skip instructions that don't read Reg.
1343 if (!MO.getSubReg() && !MO.isEarlyClobber())
1345 // We may want to extend a live range for a partial redef, or for a use
1346 // tied to an early clobber.
1347 Idx = Idx.getPrevSlot();
1348 if (!Edit->getParent().liveAt(Idx))
1351 Idx = Idx.getRegSlot(true);
1353 SlotIndex Next = Idx.getNextSlot();
1354 if (LI.hasSubRanges()) {
1355 // We have to delay extending subranges until we have seen all operands
1356 // defining the register. This is because a <def,read-undef> operand
1357 // will create an "undef" point, and we cannot extend any subranges
1358 // until all of them have been accounted for.
1360 ExtPoints.push_back(ExtPoint(MO, RegIdx, Next));
1362 LiveRangeCalc &LRC = getLRCalc(RegIdx);
1363 LRC.extend(LI, Next, 0, ArrayRef<SlotIndex>());
1367 for (ExtPoint &EP : ExtPoints) {
1368 LiveInterval &LI = LIS.getInterval(Edit->get(EP.RegIdx));
1369 assert(LI.hasSubRanges());
1371 LiveRangeCalc SubLRC;
1372 unsigned Reg = EP.MO.getReg(), Sub = EP.MO.getSubReg();
1373 LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(Sub)
1374 : MRI.getMaxLaneMaskForVReg(Reg);
1375 for (LiveInterval::SubRange &S : LI.subranges()) {
1376 if ((S.LaneMask & LM).none())
1378 // The problem here can be that the new register may have been created
1379 // for a partially defined original register. For example:
1380 // %0:subreg_hireg<def,read-undef> = ...
1385 SubLRC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
1386 &LIS.getVNInfoAllocator());
1387 SmallVector<SlotIndex, 4> Undefs;
1388 LI.computeSubRangeUndefs(Undefs, S.LaneMask, MRI, *LIS.getSlotIndexes());
1389 SubLRC.extend(S, EP.Next, 0, Undefs);
1393 for (unsigned R : *Edit) {
1394 LiveInterval &LI = LIS.getInterval(R);
1395 if (!LI.hasSubRanges())
1398 LI.removeEmptySubRanges();
1399 LIS.constructMainRangeFromSubranges(LI);
1403 void SplitEditor::deleteRematVictims() {
1404 SmallVector<MachineInstr*, 8> Dead;
1405 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
1406 LiveInterval *LI = &LIS.getInterval(*I);
1407 for (const LiveRange::Segment &S : LI->segments) {
1408 // Dead defs end at the dead slot.
1409 if (S.end != S.valno->def.getDeadSlot())
1411 if (S.valno->isPHIDef())
1413 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def);
1414 assert(MI && "Missing instruction for dead def");
1415 MI->addRegisterDead(LI->reg, &TRI);
1417 if (!MI->allDefsAreDead())
1420 DEBUG(dbgs() << "All defs dead: " << *MI);
1428 Edit->eliminateDeadDefs(Dead, None, &AA);
1431 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
1434 // At this point, the live intervals in Edit contain VNInfos corresponding to
1435 // the inserted copies.
1437 // Add the original defs from the parent interval.
1438 for (const VNInfo *ParentVNI : Edit->getParent().valnos) {
1439 if (ParentVNI->isUnused())
1441 unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
1442 defValue(RegIdx, ParentVNI, ParentVNI->def, true);
1444 // Force rematted values to be recomputed everywhere.
1445 // The new live ranges may be truncated.
1446 if (Edit->didRematerialize(ParentVNI))
1447 for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1448 forceRecompute(i, ParentVNI);
1451 // Hoist back-copies to the complement interval when in spill mode.
1452 switch (SpillMode) {
1454 // Leave all back-copies as is.
1458 // hoistCopies will behave differently between size and speed.
1462 // Transfer the simply mapped values, check if any are skipped.
1463 bool Skipped = transferValues();
1465 // Rewrite virtual registers, possibly extending ranges.
1466 rewriteAssigned(Skipped);
1469 extendPHIKillRanges();
1473 // Delete defs that were rematted everywhere.
1475 deleteRematVictims();
1477 // Get rid of unused values and set phi-kill flags.
1478 for (unsigned Reg : *Edit) {
1479 LiveInterval &LI = LIS.getInterval(Reg);
1480 LI.removeEmptySubRanges();
1481 LI.RenumberValues();
1484 // Provide a reverse mapping from original indices to Edit ranges.
1487 for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1488 LRMap->push_back(i);
1491 // Now check if any registers were separated into multiple components.
1492 ConnectedVNInfoEqClasses ConEQ(LIS);
1493 for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
1494 // Don't use iterators, they are invalidated by create() below.
1495 unsigned VReg = Edit->get(i);
1496 LiveInterval &LI = LIS.getInterval(VReg);
1497 SmallVector<LiveInterval*, 8> SplitLIs;
1498 LIS.splitSeparateComponents(LI, SplitLIs);
1499 unsigned Original = VRM.getOriginal(VReg);
1500 for (LiveInterval *SplitLI : SplitLIs)
1501 VRM.setIsSplitFromReg(SplitLI->reg, Original);
1503 // The new intervals all map back to i.
1505 LRMap->resize(Edit->size(), i);
1508 // Calculate spill weight and allocation hints for new intervals.
1509 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI);
1511 assert(!LRMap || LRMap->size() == Edit->size());
1514 //===----------------------------------------------------------------------===//
1515 // Single Block Splitting
1516 //===----------------------------------------------------------------------===//
1518 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
1519 bool SingleInstrs) const {
1520 // Always split for multiple instructions.
1521 if (!BI.isOneInstr())
1523 // Don't split for single instructions unless explicitly requested.
1526 // Splitting a live-through range always makes progress.
1527 if (BI.LiveIn && BI.LiveOut)
1529 // No point in isolating a copy. It has no register class constraints.
1530 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
1532 // Finally, don't isolate an end point that was created by earlier splits.
1533 return isOriginalEndpoint(BI.FirstInstr);
1536 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
1538 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
1539 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
1541 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
1542 useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
1544 // The last use is after the last valid split point.
1545 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
1546 useIntv(SegStart, SegStop);
1547 overlapIntv(SegStop, BI.LastInstr);
1551 //===----------------------------------------------------------------------===//
1552 // Global Live Range Splitting Support
1553 //===----------------------------------------------------------------------===//
1555 // These methods support a method of global live range splitting that uses a
1556 // global algorithm to decide intervals for CFG edges. They will insert split
1557 // points and color intervals in basic blocks while avoiding interference.
1559 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1560 // are on the stack.
1562 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
1563 unsigned IntvIn, SlotIndex LeaveBefore,
1564 unsigned IntvOut, SlotIndex EnterAfter){
1565 SlotIndex Start, Stop;
1566 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
1568 DEBUG(dbgs() << "%bb." << MBBNum << " [" << Start << ';' << Stop << ") intf "
1569 << LeaveBefore << '-' << EnterAfter << ", live-through "
1570 << IntvIn << " -> " << IntvOut);
1572 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
1574 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
1575 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
1576 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
1578 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
1581 DEBUG(dbgs() << ", spill on entry.\n");
1583 // <<<<<<<<< Possible LeaveBefore interference.
1584 // |-----------| Live through.
1585 // -____________ Spill on entry.
1588 SlotIndex Idx = leaveIntvAtTop(*MBB);
1589 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1595 DEBUG(dbgs() << ", reload on exit.\n");
1597 // >>>>>>> Possible EnterAfter interference.
1598 // |-----------| Live through.
1599 // ___________-- Reload on exit.
1601 selectIntv(IntvOut);
1602 SlotIndex Idx = enterIntvAtEnd(*MBB);
1603 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1608 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
1609 DEBUG(dbgs() << ", straight through.\n");
1611 // |-----------| Live through.
1612 // ------------- Straight through, same intv, no interference.
1614 selectIntv(IntvOut);
1615 useIntv(Start, Stop);
1619 // We cannot legally insert splits after LSP.
1620 SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
1621 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
1623 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
1624 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
1625 DEBUG(dbgs() << ", switch avoiding interference.\n");
1627 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1628 // |-----------| Live through.
1629 // ------======= Switch intervals between interference.
1631 selectIntv(IntvOut);
1633 if (LeaveBefore && LeaveBefore < LSP) {
1634 Idx = enterIntvBefore(LeaveBefore);
1637 Idx = enterIntvAtEnd(*MBB);
1640 useIntv(Start, Idx);
1641 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1642 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1646 DEBUG(dbgs() << ", create local intv for interference.\n");
1648 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1649 // |-----------| Live through.
1650 // ==---------== Switch intervals before/after interference.
1652 assert(LeaveBefore <= EnterAfter && "Missed case");
1654 selectIntv(IntvOut);
1655 SlotIndex Idx = enterIntvAfter(EnterAfter);
1657 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1660 Idx = leaveIntvBefore(LeaveBefore);
1661 useIntv(Start, Idx);
1662 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1665 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
1666 unsigned IntvIn, SlotIndex LeaveBefore) {
1667 SlotIndex Start, Stop;
1668 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1670 DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' << Stop
1671 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1672 << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
1673 << (BI.LiveOut ? ", stack-out" : ", killed in block"));
1675 assert(IntvIn && "Must have register in");
1676 assert(BI.LiveIn && "Must be live-in");
1677 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
1679 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
1680 DEBUG(dbgs() << " before interference.\n");
1682 // <<< Interference after kill.
1683 // |---o---x | Killed in block.
1684 // ========= Use IntvIn everywhere.
1687 useIntv(Start, BI.LastInstr);
1691 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1693 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
1695 // <<< Possible interference after last use.
1696 // |---o---o---| Live-out on stack.
1697 // =========____ Leave IntvIn after last use.
1699 // < Interference after last use.
1700 // |---o---o--o| Live-out on stack, late last use.
1701 // ============ Copy to stack after LSP, overlap IntvIn.
1702 // \_____ Stack interval is live-out.
1704 if (BI.LastInstr < LSP) {
1705 DEBUG(dbgs() << ", spill after last use before interference.\n");
1707 SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
1708 useIntv(Start, Idx);
1709 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1711 DEBUG(dbgs() << ", spill before last split point.\n");
1713 SlotIndex Idx = leaveIntvBefore(LSP);
1714 overlapIntv(Idx, BI.LastInstr);
1715 useIntv(Start, Idx);
1716 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1721 // The interference is overlapping somewhere we wanted to use IntvIn. That
1722 // means we need to create a local interval that can be allocated a
1723 // different register.
1724 unsigned LocalIntv = openIntv();
1726 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
1728 if (!BI.LiveOut || BI.LastInstr < LSP) {
1730 // <<<<<<< Interference overlapping uses.
1731 // |---o---o---| Live-out on stack.
1732 // =====----____ Leave IntvIn before interference, then spill.
1734 SlotIndex To = leaveIntvAfter(BI.LastInstr);
1735 SlotIndex From = enterIntvBefore(LeaveBefore);
1738 useIntv(Start, From);
1739 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1743 // <<<<<<< Interference overlapping uses.
1744 // |---o---o--o| Live-out on stack, late last use.
1745 // =====------- Copy to stack before LSP, overlap LocalIntv.
1746 // \_____ Stack interval is live-out.
1748 SlotIndex To = leaveIntvBefore(LSP);
1749 overlapIntv(To, BI.LastInstr);
1750 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
1753 useIntv(Start, From);
1754 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1757 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
1758 unsigned IntvOut, SlotIndex EnterAfter) {
1759 SlotIndex Start, Stop;
1760 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1762 DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' << Stop
1763 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1764 << ", reg-out " << IntvOut << ", enter after " << EnterAfter
1765 << (BI.LiveIn ? ", stack-in" : ", defined in block"));
1767 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1769 assert(IntvOut && "Must have register out");
1770 assert(BI.LiveOut && "Must be live-out");
1771 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
1773 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
1774 DEBUG(dbgs() << " after interference.\n");
1776 // >>>> Interference before def.
1777 // | o---o---| Defined in block.
1778 // ========= Use IntvOut everywhere.
1780 selectIntv(IntvOut);
1781 useIntv(BI.FirstInstr, Stop);
1785 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
1786 DEBUG(dbgs() << ", reload after interference.\n");
1788 // >>>> Interference before def.
1789 // |---o---o---| Live-through, stack-in.
1790 // ____========= Enter IntvOut before first use.
1792 selectIntv(IntvOut);
1793 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
1795 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1799 // The interference is overlapping somewhere we wanted to use IntvOut. That
1800 // means we need to create a local interval that can be allocated a
1801 // different register.
1802 DEBUG(dbgs() << ", interference overlaps uses.\n");
1804 // >>>>>>> Interference overlapping uses.
1805 // |---o---o---| Live-through, stack-in.
1806 // ____---====== Create local interval for interference range.
1808 selectIntv(IntvOut);
1809 SlotIndex Idx = enterIntvAfter(EnterAfter);
1811 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1814 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));