1 //===- SplitKit.cpp - Toolkit for splitting live ranges -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains the SplitAnalysis class as well as mutator functions for
10 // live range splitting.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/CodeGen/LiveRangeEdit.h"
20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetInstrInfo.h"
28 #include "llvm/CodeGen/TargetOpcodes.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/CodeGen/VirtRegMap.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/DebugLoc.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/BlockFrequency.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
47 #define DEBUG_TYPE "regalloc"
49 STATISTIC(NumFinished
, "Number of splits finished");
50 STATISTIC(NumSimple
, "Number of splits that were simple");
51 STATISTIC(NumCopies
, "Number of copies inserted for splitting");
52 STATISTIC(NumRemats
, "Number of rematerialized defs for splitting");
53 STATISTIC(NumRepairs
, "Number of invalid live ranges repaired");
55 //===----------------------------------------------------------------------===//
56 // Last Insert Point Analysis
57 //===----------------------------------------------------------------------===//
59 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals
&lis
,
61 : LIS(lis
), LastInsertPoint(BBNum
) {}
64 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval
&CurLI
,
65 const MachineBasicBlock
&MBB
) {
66 unsigned Num
= MBB
.getNumber();
67 std::pair
<SlotIndex
, SlotIndex
> &LIP
= LastInsertPoint
[Num
];
68 SlotIndex MBBEnd
= LIS
.getMBBEndIdx(&MBB
);
70 SmallVector
<const MachineBasicBlock
*, 1> ExceptionalSuccessors
;
71 bool EHPadSuccessor
= false;
72 for (const MachineBasicBlock
*SMBB
: MBB
.successors()) {
73 if (SMBB
->isEHPad()) {
74 ExceptionalSuccessors
.push_back(SMBB
);
75 EHPadSuccessor
= true;
76 } else if (SMBB
->isInlineAsmBrIndirectTarget())
77 ExceptionalSuccessors
.push_back(SMBB
);
80 // Compute insert points on the first call. The pair is independent of the
81 // current live interval.
82 if (!LIP
.first
.isValid()) {
83 MachineBasicBlock::const_iterator FirstTerm
= MBB
.getFirstTerminator();
84 if (FirstTerm
== MBB
.end())
87 LIP
.first
= LIS
.getInstructionIndex(*FirstTerm
);
89 // If there is a landing pad or inlineasm_br successor, also find the
90 // instruction. If there is no such instruction, we don't need to do
91 // anything special. We assume there cannot be multiple instructions that
92 // are Calls with EHPad successors or INLINEASM_BR in a block. Further, we
93 // assume that if there are any, they will be after any other call
94 // instructions in the block.
95 if (ExceptionalSuccessors
.empty())
97 for (const MachineInstr
&MI
: llvm::reverse(MBB
)) {
98 if ((EHPadSuccessor
&& MI
.isCall()) ||
99 MI
.getOpcode() == TargetOpcode::INLINEASM_BR
) {
100 LIP
.second
= LIS
.getInstructionIndex(MI
);
106 // If CurLI is live into a landing pad successor, move the last insert point
107 // back to the call that may throw.
111 if (none_of(ExceptionalSuccessors
, [&](const MachineBasicBlock
*EHPad
) {
112 return LIS
.isLiveInToMBB(CurLI
, EHPad
);
116 // Find the value leaving MBB.
117 const VNInfo
*VNI
= CurLI
.getVNInfoBefore(MBBEnd
);
121 // The def of statepoint instruction is a gc relocation and it should be alive
122 // in landing pad. So we cannot split interval after statepoint instruction.
123 if (SlotIndex::isSameInstr(VNI
->def
, LIP
.second
))
124 if (auto *I
= LIS
.getInstructionFromIndex(LIP
.second
))
125 if (I
->getOpcode() == TargetOpcode::STATEPOINT
)
128 // If the value leaving MBB was defined after the call in MBB, it can't
129 // really be live-in to the landing pad. This can happen if the landing pad
130 // has a PHI, and this register is undef on the exceptional edge.
131 // <rdar://problem/10664933>
132 if (!SlotIndex::isEarlierInstr(VNI
->def
, LIP
.second
) && VNI
->def
< MBBEnd
)
135 // Value is properly live-in to the landing pad.
136 // Only allow inserts before the call.
140 MachineBasicBlock::iterator
141 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval
&CurLI
,
142 MachineBasicBlock
&MBB
) {
143 SlotIndex LIP
= getLastInsertPoint(CurLI
, MBB
);
144 if (LIP
== LIS
.getMBBEndIdx(&MBB
))
146 return LIS
.getInstructionFromIndex(LIP
);
149 //===----------------------------------------------------------------------===//
151 //===----------------------------------------------------------------------===//
153 SplitAnalysis::SplitAnalysis(const VirtRegMap
&vrm
, const LiveIntervals
&lis
,
154 const MachineLoopInfo
&mli
)
155 : MF(vrm
.getMachineFunction()), VRM(vrm
), LIS(lis
), Loops(mli
),
156 TII(*MF
.getSubtarget().getInstrInfo()), IPA(lis
, MF
.getNumBlockIDs()) {}
158 void SplitAnalysis::clear() {
161 ThroughBlocks
.clear();
163 DidRepairRange
= false;
166 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
167 void SplitAnalysis::analyzeUses() {
168 assert(UseSlots
.empty() && "Call clear first");
170 // First get all the defs from the interval values. This provides the correct
171 // slots for early clobbers.
172 for (const VNInfo
*VNI
: CurLI
->valnos
)
173 if (!VNI
->isPHIDef() && !VNI
->isUnused())
174 UseSlots
.push_back(VNI
->def
);
176 // Get use slots form the use-def chain.
177 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
178 for (MachineOperand
&MO
: MRI
.use_nodbg_operands(CurLI
->reg()))
180 UseSlots
.push_back(LIS
.getInstructionIndex(*MO
.getParent()).getRegSlot());
182 array_pod_sort(UseSlots
.begin(), UseSlots
.end());
184 // Remove duplicates, keeping the smaller slot for each instruction.
185 // That is what we want for early clobbers.
186 UseSlots
.erase(std::unique(UseSlots
.begin(), UseSlots
.end(),
187 SlotIndex::isSameInstr
),
190 // Compute per-live block info.
191 if (!calcLiveBlockInfo()) {
192 // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
193 // I am looking at you, RegisterCoalescer!
194 DidRepairRange
= true;
196 LLVM_DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
197 const_cast<LiveIntervals
&>(LIS
)
198 .shrinkToUses(const_cast<LiveInterval
*>(CurLI
));
200 ThroughBlocks
.clear();
201 bool fixed
= calcLiveBlockInfo();
203 assert(fixed
&& "Couldn't fix broken live interval");
206 LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots
.size() << " instrs in "
207 << UseBlocks
.size() << " blocks, through "
208 << NumThroughBlocks
<< " blocks.\n");
211 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
212 /// where CurLI is live.
213 bool SplitAnalysis::calcLiveBlockInfo() {
214 ThroughBlocks
.resize(MF
.getNumBlockIDs());
215 NumThroughBlocks
= NumGapBlocks
= 0;
219 LiveInterval::const_iterator LVI
= CurLI
->begin();
220 LiveInterval::const_iterator LVE
= CurLI
->end();
222 SmallVectorImpl
<SlotIndex
>::const_iterator UseI
, UseE
;
223 UseI
= UseSlots
.begin();
224 UseE
= UseSlots
.end();
226 // Loop over basic blocks where CurLI is live.
227 MachineFunction::iterator MFI
=
228 LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
232 SlotIndex Start
, Stop
;
233 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
235 // If the block contains no uses, the range must be live through. At one
236 // point, RegisterCoalescer could create dangling ranges that ended
238 if (UseI
== UseE
|| *UseI
>= Stop
) {
240 ThroughBlocks
.set(BI
.MBB
->getNumber());
241 // The range shouldn't end mid-block if there are no uses. This shouldn't
246 // This block has uses. Find the first and last uses in the block.
247 BI
.FirstInstr
= *UseI
;
248 assert(BI
.FirstInstr
>= Start
);
250 while (UseI
!= UseE
&& *UseI
< Stop
);
251 BI
.LastInstr
= UseI
[-1];
252 assert(BI
.LastInstr
< Stop
);
254 // LVI is the first live segment overlapping MBB.
255 BI
.LiveIn
= LVI
->start
<= Start
;
257 // When not live in, the first use should be a def.
259 assert(LVI
->start
== LVI
->valno
->def
&& "Dangling Segment start");
260 assert(LVI
->start
== BI
.FirstInstr
&& "First instr should be a def");
261 BI
.FirstDef
= BI
.FirstInstr
;
264 // Look for gaps in the live range.
266 while (LVI
->end
< Stop
) {
267 SlotIndex LastStop
= LVI
->end
;
268 if (++LVI
== LVE
|| LVI
->start
>= Stop
) {
270 BI
.LastInstr
= LastStop
;
274 if (LastStop
< LVI
->start
) {
275 // There is a gap in the live range. Create duplicate entries for the
276 // live-in snippet and the live-out snippet.
279 // Push the Live-in part.
281 UseBlocks
.push_back(BI
);
282 UseBlocks
.back().LastInstr
= LastStop
;
284 // Set up BI for the live-out part.
287 BI
.FirstInstr
= BI
.FirstDef
= LVI
->start
;
290 // A Segment that starts in the middle of the block must be a def.
291 assert(LVI
->start
== LVI
->valno
->def
&& "Dangling Segment start");
293 BI
.FirstDef
= LVI
->start
;
296 UseBlocks
.push_back(BI
);
298 // LVI is now at LVE or LVI->end >= Stop.
303 // Live segment ends exactly at Stop. Move to the next segment.
304 if (LVI
->end
== Stop
&& ++LVI
== LVE
)
307 // Pick the next basic block.
308 if (LVI
->start
< Stop
)
311 MFI
= LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
314 assert(getNumLiveBlocks() == countLiveBlocks(CurLI
) && "Bad block count");
318 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval
*cli
) const {
321 LiveInterval
*li
= const_cast<LiveInterval
*>(cli
);
322 LiveInterval::iterator LVI
= li
->begin();
323 LiveInterval::iterator LVE
= li
->end();
326 // Loop over basic blocks where li is live.
327 MachineFunction::const_iterator MFI
=
328 LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
329 SlotIndex Stop
= LIS
.getMBBEndIdx(&*MFI
);
332 LVI
= li
->advanceTo(LVI
, Stop
);
337 Stop
= LIS
.getMBBEndIdx(&*MFI
);
338 } while (Stop
<= LVI
->start
);
342 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx
) const {
343 unsigned OrigReg
= VRM
.getOriginal(CurLI
->reg());
344 const LiveInterval
&Orig
= LIS
.getInterval(OrigReg
);
345 assert(!Orig
.empty() && "Splitting empty interval?");
346 LiveInterval::const_iterator I
= Orig
.find(Idx
);
348 // Range containing Idx should begin at Idx.
349 if (I
!= Orig
.end() && I
->start
<= Idx
)
350 return I
->start
== Idx
;
352 // Range does not contain Idx, previous must end at Idx.
353 return I
!= Orig
.begin() && (--I
)->end
== Idx
;
356 void SplitAnalysis::analyze(const LiveInterval
*li
) {
362 //===----------------------------------------------------------------------===//
364 //===----------------------------------------------------------------------===//
366 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
367 SplitEditor::SplitEditor(SplitAnalysis
&SA
, AliasAnalysis
&AA
,
368 LiveIntervals
&LIS
, VirtRegMap
&VRM
,
369 MachineDominatorTree
&MDT
,
370 MachineBlockFrequencyInfo
&MBFI
, VirtRegAuxInfo
&VRAI
)
371 : SA(SA
), AA(AA
), LIS(LIS
), VRM(VRM
),
372 MRI(VRM
.getMachineFunction().getRegInfo()), MDT(MDT
),
373 TII(*VRM
.getMachineFunction().getSubtarget().getInstrInfo()),
374 TRI(*VRM
.getMachineFunction().getSubtarget().getRegisterInfo()),
375 MBFI(MBFI
), VRAI(VRAI
), RegAssign(Allocator
) {}
377 void SplitEditor::reset(LiveRangeEdit
&LRE
, ComplementSpillMode SM
) {
384 // Reset the LiveIntervalCalc instances needed for this spill mode.
385 LICalc
[0].reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
386 &LIS
.getVNInfoAllocator());
388 LICalc
[1].reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
389 &LIS
.getVNInfoAllocator());
391 // We don't need an AliasAnalysis since we will only be performing
392 // cheap-as-a-copy remats anyway.
393 Edit
->anyRematerializable(nullptr);
396 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
397 LLVM_DUMP_METHOD
void SplitEditor::dump() const {
398 if (RegAssign
.empty()) {
399 dbgs() << " empty\n";
403 for (RegAssignMap::const_iterator I
= RegAssign
.begin(); I
.valid(); ++I
)
404 dbgs() << " [" << I
.start() << ';' << I
.stop() << "):" << I
.value();
409 LiveInterval::SubRange
&SplitEditor::getSubRangeForMaskExact(LaneBitmask LM
,
411 for (LiveInterval::SubRange
&S
: LI
.subranges())
412 if (S
.LaneMask
== LM
)
414 llvm_unreachable("SubRange for this mask not found");
417 LiveInterval::SubRange
&SplitEditor::getSubRangeForMask(LaneBitmask LM
,
419 for (LiveInterval::SubRange
&S
: LI
.subranges())
420 if ((S
.LaneMask
& LM
) == LM
)
422 llvm_unreachable("SubRange for this mask not found");
425 void SplitEditor::addDeadDef(LiveInterval
&LI
, VNInfo
*VNI
, bool Original
) {
426 if (!LI
.hasSubRanges()) {
427 LI
.createDeadDef(VNI
);
431 SlotIndex Def
= VNI
->def
;
433 // If we are transferring a def from the original interval, make sure
434 // to only update the subranges for which the original subranges had
435 // a def at this location.
436 for (LiveInterval::SubRange
&S
: LI
.subranges()) {
437 auto &PS
= getSubRangeForMask(S
.LaneMask
, Edit
->getParent());
438 VNInfo
*PV
= PS
.getVNInfoAt(Def
);
439 if (PV
!= nullptr && PV
->def
== Def
)
440 S
.createDeadDef(Def
, LIS
.getVNInfoAllocator());
443 // This is a new def: either from rematerialization, or from an inserted
444 // copy. Since rematerialization can regenerate a definition of a sub-
445 // register, we need to check which subranges need to be updated.
446 const MachineInstr
*DefMI
= LIS
.getInstructionFromIndex(Def
);
447 assert(DefMI
!= nullptr);
449 for (const MachineOperand
&DefOp
: DefMI
->defs()) {
450 Register R
= DefOp
.getReg();
453 if (unsigned SR
= DefOp
.getSubReg())
454 LM
|= TRI
.getSubRegIndexLaneMask(SR
);
456 LM
= MRI
.getMaxLaneMaskForVReg(R
);
460 for (LiveInterval::SubRange
&S
: LI
.subranges())
461 if ((S
.LaneMask
& LM
).any())
462 S
.createDeadDef(Def
, LIS
.getVNInfoAllocator());
466 VNInfo
*SplitEditor::defValue(unsigned RegIdx
,
467 const VNInfo
*ParentVNI
,
470 assert(ParentVNI
&& "Mapping NULL value");
471 assert(Idx
.isValid() && "Invalid SlotIndex");
472 assert(Edit
->getParent().getVNInfoAt(Idx
) == ParentVNI
&& "Bad Parent VNI");
473 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(RegIdx
));
475 // Create a new value.
476 VNInfo
*VNI
= LI
->getNextValue(Idx
, LIS
.getVNInfoAllocator());
478 bool Force
= LI
->hasSubRanges();
479 ValueForcePair
FP(Force
? nullptr : VNI
, Force
);
480 // Use insert for lookup, so we can add missing values with a second lookup.
481 std::pair
<ValueMap::iterator
, bool> InsP
=
482 Values
.insert(std::make_pair(std::make_pair(RegIdx
, ParentVNI
->id
), FP
));
484 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not
485 // forced. Keep it as a simple def without any liveness.
486 if (!Force
&& InsP
.second
)
489 // If the previous value was a simple mapping, add liveness for it now.
490 if (VNInfo
*OldVNI
= InsP
.first
->second
.getPointer()) {
491 addDeadDef(*LI
, OldVNI
, Original
);
493 // No longer a simple mapping. Switch to a complex mapping. If the
494 // interval has subranges, make it a forced mapping.
495 InsP
.first
->second
= ValueForcePair(nullptr, Force
);
498 // This is a complex mapping, add liveness for VNI
499 addDeadDef(*LI
, VNI
, Original
);
503 void SplitEditor::forceRecompute(unsigned RegIdx
, const VNInfo
&ParentVNI
) {
504 ValueForcePair
&VFP
= Values
[std::make_pair(RegIdx
, ParentVNI
.id
)];
505 VNInfo
*VNI
= VFP
.getPointer();
507 // ParentVNI was either unmapped or already complex mapped. Either way, just
508 // set the force bit.
514 // This was previously a single mapping. Make sure the old def is represented
515 // by a trivial live range.
516 addDeadDef(LIS
.getInterval(Edit
->get(RegIdx
)), VNI
, false);
518 // Mark as complex mapped, forced.
519 VFP
= ValueForcePair(nullptr, true);
522 SlotIndex
SplitEditor::buildSingleSubRegCopy(Register FromReg
, Register ToReg
,
523 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator InsertBefore
,
524 unsigned SubIdx
, LiveInterval
&DestLI
, bool Late
, SlotIndex Def
) {
525 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::COPY
);
526 bool FirstCopy
= !Def
.isValid();
527 MachineInstr
*CopyMI
= BuildMI(MBB
, InsertBefore
, DebugLoc(), Desc
)
528 .addReg(ToReg
, RegState::Define
| getUndefRegState(FirstCopy
)
529 | getInternalReadRegState(!FirstCopy
), SubIdx
)
530 .addReg(FromReg
, 0, SubIdx
);
532 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
534 Def
= Indexes
.insertMachineInstrInMaps(*CopyMI
, Late
).getRegSlot();
536 CopyMI
->bundleWithPred();
541 SlotIndex
SplitEditor::buildCopy(Register FromReg
, Register ToReg
,
542 LaneBitmask LaneMask
, MachineBasicBlock
&MBB
,
543 MachineBasicBlock::iterator InsertBefore
, bool Late
, unsigned RegIdx
) {
544 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::COPY
);
545 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
546 if (LaneMask
.all() || LaneMask
== MRI
.getMaxLaneMaskForVReg(FromReg
)) {
547 // The full vreg is copied.
548 MachineInstr
*CopyMI
=
549 BuildMI(MBB
, InsertBefore
, DebugLoc(), Desc
, ToReg
).addReg(FromReg
);
550 return Indexes
.insertMachineInstrInMaps(*CopyMI
, Late
).getRegSlot();
553 // Only a subset of lanes needs to be copied. The following is a simple
554 // heuristic to construct a sequence of COPYs. We could add a target
555 // specific callback if this turns out to be suboptimal.
556 LiveInterval
&DestLI
= LIS
.getInterval(Edit
->get(RegIdx
));
558 // First pass: Try to find a perfectly matching subregister index. If none
559 // exists find the one covering the most lanemask bits.
560 const TargetRegisterClass
*RC
= MRI
.getRegClass(FromReg
);
561 assert(RC
== MRI
.getRegClass(ToReg
) && "Should have same reg class");
563 SmallVector
<unsigned, 8> SubIndexes
;
565 // Abort if we cannot possibly implement the COPY with the given indexes.
566 if (!TRI
.getCoveringSubRegIndexes(MRI
, RC
, LaneMask
, SubIndexes
))
567 report_fatal_error("Impossible to implement partial COPY");
570 for (unsigned BestIdx
: SubIndexes
) {
571 Def
= buildSingleSubRegCopy(FromReg
, ToReg
, MBB
, InsertBefore
, BestIdx
,
575 BumpPtrAllocator
&Allocator
= LIS
.getVNInfoAllocator();
576 DestLI
.refineSubRanges(
578 [Def
, &Allocator
](LiveInterval::SubRange
&SR
) {
579 SR
.createDeadDef(Def
, Allocator
);
586 VNInfo
*SplitEditor::defFromParent(unsigned RegIdx
,
589 MachineBasicBlock
&MBB
,
590 MachineBasicBlock::iterator I
) {
592 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(RegIdx
));
594 // We may be trying to avoid interference that ends at a deleted instruction,
595 // so always begin RegIdx 0 early and all others late.
596 bool Late
= RegIdx
!= 0;
598 // Attempt cheap-as-a-copy rematerialization.
599 unsigned Original
= VRM
.getOriginal(Edit
->get(RegIdx
));
600 LiveInterval
&OrigLI
= LIS
.getInterval(Original
);
601 VNInfo
*OrigVNI
= OrigLI
.getVNInfoAt(UseIdx
);
603 Register Reg
= LI
->reg();
604 bool DidRemat
= false;
606 LiveRangeEdit::Remat
RM(ParentVNI
);
607 RM
.OrigMI
= LIS
.getInstructionFromIndex(OrigVNI
->def
);
608 if (Edit
->canRematerializeAt(RM
, OrigVNI
, UseIdx
, true)) {
609 Def
= Edit
->rematerializeAt(MBB
, I
, Reg
, RM
, TRI
, Late
);
615 LaneBitmask LaneMask
;
616 if (OrigLI
.hasSubRanges()) {
617 LaneMask
= LaneBitmask::getNone();
618 for (LiveInterval::SubRange
&S
: OrigLI
.subranges()) {
619 if (S
.liveAt(UseIdx
))
620 LaneMask
|= S
.LaneMask
;
623 LaneMask
= LaneBitmask::getAll();
626 if (LaneMask
.none()) {
627 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::IMPLICIT_DEF
);
628 MachineInstr
*ImplicitDef
= BuildMI(MBB
, I
, DebugLoc(), Desc
, Reg
);
629 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
630 Def
= Indexes
.insertMachineInstrInMaps(*ImplicitDef
, Late
).getRegSlot();
633 Def
= buildCopy(Edit
->getReg(), Reg
, LaneMask
, MBB
, I
, Late
, RegIdx
);
637 // Define the value in Reg.
638 return defValue(RegIdx
, ParentVNI
, Def
, false);
641 /// Create a new virtual register and live interval.
642 unsigned SplitEditor::openIntv() {
643 // Create the complement as index 0.
645 Edit
->createEmptyInterval();
647 // Create the open interval.
648 OpenIdx
= Edit
->size();
649 Edit
->createEmptyInterval();
653 void SplitEditor::selectIntv(unsigned Idx
) {
654 assert(Idx
!= 0 && "Cannot select the complement interval");
655 assert(Idx
< Edit
->size() && "Can only select previously opened interval");
656 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx
<< " -> " << Idx
<< '\n');
660 SlotIndex
SplitEditor::enterIntvBefore(SlotIndex Idx
) {
661 assert(OpenIdx
&& "openIntv not called before enterIntvBefore");
662 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx
);
663 Idx
= Idx
.getBaseIndex();
664 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
666 LLVM_DEBUG(dbgs() << ": not live\n");
669 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
670 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
671 assert(MI
&& "enterIntvBefore called with invalid index");
673 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Idx
, *MI
->getParent(), MI
);
677 SlotIndex
SplitEditor::enterIntvAfter(SlotIndex Idx
) {
678 assert(OpenIdx
&& "openIntv not called before enterIntvAfter");
679 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx
);
680 Idx
= Idx
.getBoundaryIndex();
681 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
683 LLVM_DEBUG(dbgs() << ": not live\n");
686 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
687 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
688 assert(MI
&& "enterIntvAfter called with invalid index");
690 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Idx
, *MI
->getParent(),
691 std::next(MachineBasicBlock::iterator(MI
)));
695 SlotIndex
SplitEditor::enterIntvAtEnd(MachineBasicBlock
&MBB
) {
696 assert(OpenIdx
&& "openIntv not called before enterIntvAtEnd");
697 SlotIndex End
= LIS
.getMBBEndIdx(&MBB
);
698 SlotIndex Last
= End
.getPrevSlot();
699 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB
) << ", "
701 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Last
);
703 LLVM_DEBUG(dbgs() << ": not live\n");
706 SlotIndex LSP
= SA
.getLastSplitPoint(&MBB
);
708 // It could be that the use after LSP is a def, and thus the ParentVNI
709 // just selected starts at that def. For this case to exist, the def
710 // must be part of a tied def/use pair (as otherwise we'd have split
711 // distinct live ranges into individual live intervals), and thus we
712 // can insert the def into the VNI of the use and the tied def/use
713 // pair can live in the resulting interval.
715 ParentVNI
= Edit
->getParent().getVNInfoAt(Last
);
717 // undef use --> undef tied def
718 LLVM_DEBUG(dbgs() << ": tied use not live\n");
723 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
);
724 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Last
, MBB
,
725 SA
.getLastSplitPointIter(&MBB
));
726 RegAssign
.insert(VNI
->def
, End
, OpenIdx
);
731 /// useIntv - indicate that all instructions in MBB should use OpenLI.
732 void SplitEditor::useIntv(const MachineBasicBlock
&MBB
) {
733 useIntv(LIS
.getMBBStartIdx(&MBB
), LIS
.getMBBEndIdx(&MBB
));
736 void SplitEditor::useIntv(SlotIndex Start
, SlotIndex End
) {
737 assert(OpenIdx
&& "openIntv not called before useIntv");
738 LLVM_DEBUG(dbgs() << " useIntv [" << Start
<< ';' << End
<< "):");
739 RegAssign
.insert(Start
, End
, OpenIdx
);
743 SlotIndex
SplitEditor::leaveIntvAfter(SlotIndex Idx
) {
744 assert(OpenIdx
&& "openIntv not called before leaveIntvAfter");
745 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx
);
747 // The interval must be live beyond the instruction at Idx.
748 SlotIndex Boundary
= Idx
.getBoundaryIndex();
749 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Boundary
);
751 LLVM_DEBUG(dbgs() << ": not live\n");
752 return Boundary
.getNextSlot();
754 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
755 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Boundary
);
756 assert(MI
&& "No instruction at index");
758 // In spill mode, make live ranges as short as possible by inserting the copy
759 // before MI. This is only possible if that instruction doesn't redefine the
760 // value. The inserted COPY is not a kill, and we don't need to recompute
761 // the source live range. The spiller also won't try to hoist this copy.
762 if (SpillMode
&& !SlotIndex::isSameInstr(ParentVNI
->def
, Idx
) &&
763 MI
->readsVirtualRegister(Edit
->getReg())) {
764 forceRecompute(0, *ParentVNI
);
765 defFromParent(0, ParentVNI
, Idx
, *MI
->getParent(), MI
);
769 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Boundary
, *MI
->getParent(),
770 std::next(MachineBasicBlock::iterator(MI
)));
774 SlotIndex
SplitEditor::leaveIntvBefore(SlotIndex Idx
) {
775 assert(OpenIdx
&& "openIntv not called before leaveIntvBefore");
776 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx
);
778 // The interval must be live into the instruction at Idx.
779 Idx
= Idx
.getBaseIndex();
780 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
782 LLVM_DEBUG(dbgs() << ": not live\n");
783 return Idx
.getNextSlot();
785 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
787 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
788 assert(MI
&& "No instruction at index");
789 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Idx
, *MI
->getParent(), MI
);
793 SlotIndex
SplitEditor::leaveIntvAtTop(MachineBasicBlock
&MBB
) {
794 assert(OpenIdx
&& "openIntv not called before leaveIntvAtTop");
795 SlotIndex Start
= LIS
.getMBBStartIdx(&MBB
);
796 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB
) << ", "
799 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Start
);
801 LLVM_DEBUG(dbgs() << ": not live\n");
805 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Start
, MBB
,
806 MBB
.SkipPHIsLabelsAndDebug(MBB
.begin()));
807 RegAssign
.insert(Start
, VNI
->def
, OpenIdx
);
812 static bool hasTiedUseOf(MachineInstr
&MI
, unsigned Reg
) {
813 return any_of(MI
.defs(), [Reg
](const MachineOperand
&MO
) {
814 return MO
.isReg() && MO
.isTied() && MO
.getReg() == Reg
;
818 void SplitEditor::overlapIntv(SlotIndex Start
, SlotIndex End
) {
819 assert(OpenIdx
&& "openIntv not called before overlapIntv");
820 const VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Start
);
821 assert(ParentVNI
== Edit
->getParent().getVNInfoBefore(End
) &&
822 "Parent changes value in extended range");
823 assert(LIS
.getMBBFromIndex(Start
) == LIS
.getMBBFromIndex(End
) &&
824 "Range cannot span basic blocks");
826 // The complement interval will be extended as needed by LICalc.extend().
828 forceRecompute(0, *ParentVNI
);
830 // If the last use is tied to a def, we can't mark it as live for the
831 // interval which includes only the use. That would cause the tied pair
832 // to end up in two different intervals.
833 if (auto *MI
= LIS
.getInstructionFromIndex(End
))
834 if (hasTiedUseOf(*MI
, Edit
->getReg())) {
835 LLVM_DEBUG(dbgs() << "skip overlap due to tied def at end\n");
839 LLVM_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 LLVM_DEBUG(dbgs() << "Removing " << Copies
.size() << " back-copies.\n");
851 RegAssignMap::iterator AssignI
;
852 AssignI
.setMap(RegAssign
);
854 for (const VNInfo
*C
: Copies
) {
855 SlotIndex Def
= C
->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
)->isDebugOrPseudoInstr());
865 LLVM_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 // We could hoist back-copy right after another back-copy. As a result
880 // MMBI points to copy instruction which is actually dead now.
881 // We cannot set its stop to MBBI which will be the same as start and
882 // interval does not support that.
884 AtBegin
? SlotIndex() : LIS
.getInstructionIndex(*MBBI
).getRegSlot();
885 if (AtBegin
|| !MBBI
->readsVirtualRegister(Edit
->getReg()) ||
886 Kill
<= AssignI
.start()) {
887 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx
889 forceRecompute(RegIdx
, *Edit
->getParent().getVNInfoAt(Def
));
891 LLVM_DEBUG(dbgs() << " move kill to " << Kill
<< '\t' << *MBBI
);
892 AssignI
.setStop(Kill
);
898 SplitEditor::findShallowDominator(MachineBasicBlock
*MBB
,
899 MachineBasicBlock
*DefMBB
) {
902 assert(MDT
.dominates(DefMBB
, MBB
) && "MBB must be dominated by the def.");
904 const MachineLoopInfo
&Loops
= SA
.Loops
;
905 const MachineLoop
*DefLoop
= Loops
.getLoopFor(DefMBB
);
906 MachineDomTreeNode
*DefDomNode
= MDT
[DefMBB
];
908 // Best candidate so far.
909 MachineBasicBlock
*BestMBB
= MBB
;
910 unsigned BestDepth
= std::numeric_limits
<unsigned>::max();
913 const MachineLoop
*Loop
= Loops
.getLoopFor(MBB
);
915 // MBB isn't in a loop, it doesn't get any better. All dominators have a
916 // higher frequency by definition.
918 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
919 << " dominates " << printMBBReference(*MBB
)
924 // We'll never be able to exit the DefLoop.
925 if (Loop
== DefLoop
) {
926 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
927 << " dominates " << printMBBReference(*MBB
)
928 << " in the same loop\n");
932 // Least busy dominator seen so far.
933 unsigned Depth
= Loop
->getLoopDepth();
934 if (Depth
< BestDepth
) {
937 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
938 << " dominates " << printMBBReference(*MBB
)
939 << " at depth " << Depth
<< '\n');
942 // Leave loop by going to the immediate dominator of the loop header.
943 // This is a bigger stride than simply walking up the dominator tree.
944 MachineDomTreeNode
*IDom
= MDT
[Loop
->getHeader()]->getIDom();
946 // Too far up the dominator tree?
947 if (!IDom
|| !MDT
.dominates(DefDomNode
, IDom
))
950 MBB
= IDom
->getBlock();
954 void SplitEditor::computeRedundantBackCopies(
955 DenseSet
<unsigned> &NotToHoistSet
, SmallVectorImpl
<VNInfo
*> &BackCopies
) {
956 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
957 LiveInterval
*Parent
= &Edit
->getParent();
958 SmallVector
<SmallPtrSet
<VNInfo
*, 8>, 8> EqualVNs(Parent
->getNumValNums());
959 SmallPtrSet
<VNInfo
*, 8> DominatedVNIs
;
961 // Aggregate VNIs having the same value as ParentVNI.
962 for (VNInfo
*VNI
: LI
->valnos
) {
965 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
966 EqualVNs
[ParentVNI
->id
].insert(VNI
);
969 // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
970 // redundant VNIs to BackCopies.
971 for (unsigned i
= 0, e
= Parent
->getNumValNums(); i
!= e
; ++i
) {
972 VNInfo
*ParentVNI
= Parent
->getValNumInfo(i
);
973 if (!NotToHoistSet
.count(ParentVNI
->id
))
975 SmallPtrSetIterator
<VNInfo
*> It1
= EqualVNs
[ParentVNI
->id
].begin();
976 SmallPtrSetIterator
<VNInfo
*> It2
= It1
;
977 for (; It1
!= EqualVNs
[ParentVNI
->id
].end(); ++It1
) {
979 for (++It2
; It2
!= EqualVNs
[ParentVNI
->id
].end(); ++It2
) {
980 if (DominatedVNIs
.count(*It1
) || DominatedVNIs
.count(*It2
))
983 MachineBasicBlock
*MBB1
= LIS
.getMBBFromIndex((*It1
)->def
);
984 MachineBasicBlock
*MBB2
= LIS
.getMBBFromIndex((*It2
)->def
);
986 DominatedVNIs
.insert((*It1
)->def
< (*It2
)->def
? (*It2
) : (*It1
));
987 } else if (MDT
.dominates(MBB1
, MBB2
)) {
988 DominatedVNIs
.insert(*It2
);
989 } else if (MDT
.dominates(MBB2
, MBB1
)) {
990 DominatedVNIs
.insert(*It1
);
994 if (!DominatedVNIs
.empty()) {
995 forceRecompute(0, *ParentVNI
);
996 append_range(BackCopies
, DominatedVNIs
);
997 DominatedVNIs
.clear();
1002 /// For SM_Size mode, find a common dominator for all the back-copies for
1003 /// the same ParentVNI and hoist the backcopies to the dominator BB.
1004 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial
1005 /// to do the hoisting, simply remove the dominated backcopies for the same
1007 void SplitEditor::hoistCopies() {
1008 // Get the complement interval, always RegIdx 0.
1009 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
1010 LiveInterval
*Parent
= &Edit
->getParent();
1012 // Track the nearest common dominator for all back-copies for each ParentVNI,
1013 // indexed by ParentVNI->id.
1014 using DomPair
= std::pair
<MachineBasicBlock
*, SlotIndex
>;
1015 SmallVector
<DomPair
, 8> NearestDom(Parent
->getNumValNums());
1016 // The total cost of all the back-copies for each ParentVNI.
1017 SmallVector
<BlockFrequency
, 8> Costs(Parent
->getNumValNums());
1018 // The ParentVNI->id set for which hoisting back-copies are not beneficial
1020 DenseSet
<unsigned> NotToHoistSet
;
1022 // Find the nearest common dominator for parent values with multiple
1023 // back-copies. If a single back-copy dominates, put it in DomPair.second.
1024 for (VNInfo
*VNI
: LI
->valnos
) {
1025 if (VNI
->isUnused())
1027 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
1028 assert(ParentVNI
&& "Parent not live at complement def");
1030 // Don't hoist remats. The complement is probably going to disappear
1031 // completely anyway.
1032 if (Edit
->didRematerialize(ParentVNI
))
1035 MachineBasicBlock
*ValMBB
= LIS
.getMBBFromIndex(VNI
->def
);
1037 DomPair
&Dom
= NearestDom
[ParentVNI
->id
];
1039 // Keep directly defined parent values. This is either a PHI or an
1040 // instruction in the complement range. All other copies of ParentVNI
1041 // should be eliminated.
1042 if (VNI
->def
== ParentVNI
->def
) {
1043 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI
->def
<< '\n');
1044 Dom
= DomPair(ValMBB
, VNI
->def
);
1047 // Skip the singly mapped values. There is nothing to gain from hoisting a
1048 // single back-copy.
1049 if (Values
.lookup(std::make_pair(0, ParentVNI
->id
)).getPointer()) {
1050 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI
->def
<< '\n');
1055 // First time we see ParentVNI. VNI dominates itself.
1056 Dom
= DomPair(ValMBB
, VNI
->def
);
1057 } else if (Dom
.first
== ValMBB
) {
1058 // Two defs in the same block. Pick the earlier def.
1059 if (!Dom
.second
.isValid() || VNI
->def
< Dom
.second
)
1060 Dom
.second
= VNI
->def
;
1062 // Different basic blocks. Check if one dominates.
1063 MachineBasicBlock
*Near
=
1064 MDT
.findNearestCommonDominator(Dom
.first
, ValMBB
);
1066 // Def ValMBB dominates.
1067 Dom
= DomPair(ValMBB
, VNI
->def
);
1068 else if (Near
!= Dom
.first
)
1069 // None dominate. Hoist to common dominator, need new def.
1070 Dom
= DomPair(Near
, SlotIndex());
1071 Costs
[ParentVNI
->id
] += MBFI
.getBlockFreq(ValMBB
);
1074 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI
->id
<< '@'
1075 << VNI
->def
<< " for parent " << ParentVNI
->id
<< '@'
1076 << ParentVNI
->def
<< " hoist to "
1077 << printMBBReference(*Dom
.first
) << ' ' << Dom
.second
1081 // Insert the hoisted copies.
1082 for (unsigned i
= 0, e
= Parent
->getNumValNums(); i
!= e
; ++i
) {
1083 DomPair
&Dom
= NearestDom
[i
];
1084 if (!Dom
.first
|| Dom
.second
.isValid())
1086 // This value needs a hoisted copy inserted at the end of Dom.first.
1087 VNInfo
*ParentVNI
= Parent
->getValNumInfo(i
);
1088 MachineBasicBlock
*DefMBB
= LIS
.getMBBFromIndex(ParentVNI
->def
);
1089 // Get a less loopy dominator than Dom.first.
1090 Dom
.first
= findShallowDominator(Dom
.first
, DefMBB
);
1091 if (SpillMode
== SM_Speed
&&
1092 MBFI
.getBlockFreq(Dom
.first
) > Costs
[ParentVNI
->id
]) {
1093 NotToHoistSet
.insert(ParentVNI
->id
);
1096 SlotIndex LSP
= SA
.getLastSplitPoint(Dom
.first
);
1097 if (LSP
<= ParentVNI
->def
) {
1098 NotToHoistSet
.insert(ParentVNI
->id
);
1101 Dom
.second
= defFromParent(0, ParentVNI
, LSP
, *Dom
.first
,
1102 SA
.getLastSplitPointIter(Dom
.first
))->def
;
1105 // Remove redundant back-copies that are now known to be dominated by another
1106 // def with the same value.
1107 SmallVector
<VNInfo
*, 8> BackCopies
;
1108 for (VNInfo
*VNI
: LI
->valnos
) {
1109 if (VNI
->isUnused())
1111 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
1112 const DomPair
&Dom
= NearestDom
[ParentVNI
->id
];
1113 if (!Dom
.first
|| Dom
.second
== VNI
->def
||
1114 NotToHoistSet
.count(ParentVNI
->id
))
1116 BackCopies
.push_back(VNI
);
1117 forceRecompute(0, *ParentVNI
);
1120 // If it is not beneficial to hoist all the BackCopies, simply remove
1121 // redundant BackCopies in speed mode.
1122 if (SpillMode
== SM_Speed
&& !NotToHoistSet
.empty())
1123 computeRedundantBackCopies(NotToHoistSet
, BackCopies
);
1125 removeBackCopies(BackCopies
);
1128 /// transferValues - Transfer all possible values to the new live ranges.
1129 /// Values that were rematerialized are left alone, they need LICalc.extend().
1130 bool SplitEditor::transferValues() {
1131 bool Skipped
= false;
1132 RegAssignMap::const_iterator AssignI
= RegAssign
.begin();
1133 for (const LiveRange::Segment
&S
: Edit
->getParent()) {
1134 LLVM_DEBUG(dbgs() << " blit " << S
<< ':');
1135 VNInfo
*ParentVNI
= S
.valno
;
1136 // RegAssign has holes where RegIdx 0 should be used.
1137 SlotIndex Start
= S
.start
;
1138 AssignI
.advanceTo(Start
);
1141 SlotIndex End
= S
.end
;
1142 if (!AssignI
.valid()) {
1144 } else if (AssignI
.start() <= Start
) {
1145 RegIdx
= AssignI
.value();
1146 if (AssignI
.stop() < End
) {
1147 End
= AssignI
.stop();
1152 End
= std::min(End
, AssignI
.start());
1155 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
1156 LLVM_DEBUG(dbgs() << " [" << Start
<< ';' << End
<< ")=" << RegIdx
<< '('
1157 << printReg(Edit
->get(RegIdx
)) << ')');
1158 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1160 // Check for a simply defined value that can be blitted directly.
1161 ValueForcePair VFP
= Values
.lookup(std::make_pair(RegIdx
, ParentVNI
->id
));
1162 if (VNInfo
*VNI
= VFP
.getPointer()) {
1163 LLVM_DEBUG(dbgs() << ':' << VNI
->id
);
1164 LI
.addSegment(LiveInterval::Segment(Start
, End
, VNI
));
1169 // Skip values with forced recomputation.
1171 LLVM_DEBUG(dbgs() << "(recalc)");
1177 LiveIntervalCalc
&LIC
= getLICalc(RegIdx
);
1179 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
1180 // so the live range is accurate. Add live-in blocks in [Start;End) to the
1182 MachineFunction::iterator MBB
= LIS
.getMBBFromIndex(Start
)->getIterator();
1183 SlotIndex BlockStart
, BlockEnd
;
1184 std::tie(BlockStart
, BlockEnd
) = LIS
.getSlotIndexes()->getMBBRange(&*MBB
);
1186 // The first block may be live-in, or it may have its own def.
1187 if (Start
!= BlockStart
) {
1188 VNInfo
*VNI
= LI
.extendInBlock(BlockStart
, std::min(BlockEnd
, End
));
1189 assert(VNI
&& "Missing def for complex mapped value");
1190 LLVM_DEBUG(dbgs() << ':' << VNI
->id
<< "*" << printMBBReference(*MBB
));
1191 // MBB has its own def. Is it also live-out?
1192 if (BlockEnd
<= End
)
1193 LIC
.setLiveOutValue(&*MBB
, VNI
);
1195 // Skip to the next block for live-in.
1197 BlockStart
= BlockEnd
;
1200 // Handle the live-in blocks covered by [Start;End).
1201 assert(Start
<= BlockStart
&& "Expected live-in block");
1202 while (BlockStart
< End
) {
1203 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB
));
1204 BlockEnd
= LIS
.getMBBEndIdx(&*MBB
);
1205 if (BlockStart
== ParentVNI
->def
) {
1206 // This block has the def of a parent PHI, so it isn't live-in.
1207 assert(ParentVNI
->isPHIDef() && "Non-phi defined at block start?");
1208 VNInfo
*VNI
= LI
.extendInBlock(BlockStart
, std::min(BlockEnd
, End
));
1209 assert(VNI
&& "Missing def for complex mapped parent PHI");
1210 if (End
>= BlockEnd
)
1211 LIC
.setLiveOutValue(&*MBB
, VNI
); // Live-out as well.
1213 // This block needs a live-in value. The last block covered may not
1216 LIC
.addLiveInBlock(LI
, MDT
[&*MBB
], End
);
1218 // Live-through, and we don't know the value.
1219 LIC
.addLiveInBlock(LI
, MDT
[&*MBB
]);
1220 LIC
.setLiveOutValue(&*MBB
, nullptr);
1223 BlockStart
= BlockEnd
;
1227 } while (Start
!= S
.end
);
1228 LLVM_DEBUG(dbgs() << '\n');
1231 LICalc
[0].calculateValues();
1233 LICalc
[1].calculateValues();
1238 static bool removeDeadSegment(SlotIndex Def
, LiveRange
&LR
) {
1239 const LiveRange::Segment
*Seg
= LR
.getSegmentContaining(Def
);
1242 if (Seg
->end
!= Def
.getDeadSlot())
1244 // This is a dead PHI. Remove it.
1245 LR
.removeSegment(*Seg
, true);
1249 void SplitEditor::extendPHIRange(MachineBasicBlock
&B
, LiveIntervalCalc
&LIC
,
1250 LiveRange
&LR
, LaneBitmask LM
,
1251 ArrayRef
<SlotIndex
> Undefs
) {
1252 for (MachineBasicBlock
*P
: B
.predecessors()) {
1253 SlotIndex End
= LIS
.getMBBEndIdx(P
);
1254 SlotIndex LastUse
= End
.getPrevSlot();
1255 // The predecessor may not have a live-out value. That is OK, like an
1256 // undef PHI operand.
1257 LiveInterval
&PLI
= Edit
->getParent();
1258 // Need the cast because the inputs to ?: would otherwise be deemed
1259 // "incompatible": SubRange vs LiveInterval.
1260 LiveRange
&PSR
= !LM
.all() ? getSubRangeForMaskExact(LM
, PLI
)
1261 : static_cast<LiveRange
&>(PLI
);
1262 if (PSR
.liveAt(LastUse
))
1263 LIC
.extend(LR
, End
, /*PhysReg=*/0, Undefs
);
1267 void SplitEditor::extendPHIKillRanges() {
1268 // Extend live ranges to be live-out for successor PHI values.
1270 // Visit each PHI def slot in the parent live interval. If the def is dead,
1271 // remove it. Otherwise, extend the live interval to reach the end indexes
1272 // of all predecessor blocks.
1274 LiveInterval
&ParentLI
= Edit
->getParent();
1275 for (const VNInfo
*V
: ParentLI
.valnos
) {
1276 if (V
->isUnused() || !V
->isPHIDef())
1279 unsigned RegIdx
= RegAssign
.lookup(V
->def
);
1280 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1281 LiveIntervalCalc
&LIC
= getLICalc(RegIdx
);
1282 MachineBasicBlock
&B
= *LIS
.getMBBFromIndex(V
->def
);
1283 if (!removeDeadSegment(V
->def
, LI
))
1284 extendPHIRange(B
, LIC
, LI
, LaneBitmask::getAll(), /*Undefs=*/{});
1287 SmallVector
<SlotIndex
, 4> Undefs
;
1288 LiveIntervalCalc SubLIC
;
1290 for (LiveInterval::SubRange
&PS
: ParentLI
.subranges()) {
1291 for (const VNInfo
*V
: PS
.valnos
) {
1292 if (V
->isUnused() || !V
->isPHIDef())
1294 unsigned RegIdx
= RegAssign
.lookup(V
->def
);
1295 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1296 LiveInterval::SubRange
&S
= getSubRangeForMaskExact(PS
.LaneMask
, LI
);
1297 if (removeDeadSegment(V
->def
, S
))
1300 MachineBasicBlock
&B
= *LIS
.getMBBFromIndex(V
->def
);
1301 SubLIC
.reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
1302 &LIS
.getVNInfoAllocator());
1304 LI
.computeSubRangeUndefs(Undefs
, PS
.LaneMask
, MRI
, *LIS
.getSlotIndexes());
1305 extendPHIRange(B
, SubLIC
, S
, PS
.LaneMask
, Undefs
);
1310 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
1311 void SplitEditor::rewriteAssigned(bool ExtendRanges
) {
1313 ExtPoint(const MachineOperand
&O
, unsigned R
, SlotIndex N
)
1314 : MO(O
), RegIdx(R
), Next(N
) {}
1321 SmallVector
<ExtPoint
,4> ExtPoints
;
1323 for (MachineOperand
&MO
:
1324 llvm::make_early_inc_range(MRI
.reg_operands(Edit
->getReg()))) {
1325 MachineInstr
*MI
= MO
.getParent();
1326 // LiveDebugVariables should have handled all DBG_VALUE instructions.
1327 if (MI
->isDebugValue()) {
1328 LLVM_DEBUG(dbgs() << "Zapping " << *MI
);
1333 // <undef> operands don't really read the register, so it doesn't matter
1334 // which register we choose. When the use operand is tied to a def, we must
1335 // use the same register as the def, so just do that always.
1336 SlotIndex Idx
= LIS
.getInstructionIndex(*MI
);
1337 if (MO
.isDef() || MO
.isUndef())
1338 Idx
= Idx
.getRegSlot(MO
.isEarlyClobber());
1340 // Rewrite to the mapped register at Idx.
1341 unsigned RegIdx
= RegAssign
.lookup(Idx
);
1342 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1343 MO
.setReg(LI
.reg());
1344 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI
->getParent())
1345 << '\t' << Idx
<< ':' << RegIdx
<< '\t' << *MI
);
1347 // Extend liveness to Idx if the instruction reads reg.
1348 if (!ExtendRanges
|| MO
.isUndef())
1351 // Skip instructions that don't read Reg.
1353 if (!MO
.getSubReg() && !MO
.isEarlyClobber())
1355 // We may want to extend a live range for a partial redef, or for a use
1356 // tied to an early clobber.
1357 Idx
= Idx
.getPrevSlot();
1358 if (!Edit
->getParent().liveAt(Idx
))
1361 Idx
= Idx
.getRegSlot(true);
1363 SlotIndex Next
= Idx
.getNextSlot();
1364 if (LI
.hasSubRanges()) {
1365 // We have to delay extending subranges until we have seen all operands
1366 // defining the register. This is because a <def,read-undef> operand
1367 // will create an "undef" point, and we cannot extend any subranges
1368 // until all of them have been accounted for.
1370 ExtPoints
.push_back(ExtPoint(MO
, RegIdx
, Next
));
1372 LiveIntervalCalc
&LIC
= getLICalc(RegIdx
);
1373 LIC
.extend(LI
, Next
, 0, ArrayRef
<SlotIndex
>());
1377 for (ExtPoint
&EP
: ExtPoints
) {
1378 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(EP
.RegIdx
));
1379 assert(LI
.hasSubRanges());
1381 LiveIntervalCalc SubLIC
;
1382 Register Reg
= EP
.MO
.getReg(), Sub
= EP
.MO
.getSubReg();
1383 LaneBitmask LM
= Sub
!= 0 ? TRI
.getSubRegIndexLaneMask(Sub
)
1384 : MRI
.getMaxLaneMaskForVReg(Reg
);
1385 for (LiveInterval::SubRange
&S
: LI
.subranges()) {
1386 if ((S
.LaneMask
& LM
).none())
1388 // The problem here can be that the new register may have been created
1389 // for a partially defined original register. For example:
1390 // %0:subreg_hireg<def,read-undef> = ...
1395 SubLIC
.reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
1396 &LIS
.getVNInfoAllocator());
1397 SmallVector
<SlotIndex
, 4> Undefs
;
1398 LI
.computeSubRangeUndefs(Undefs
, S
.LaneMask
, MRI
, *LIS
.getSlotIndexes());
1399 SubLIC
.extend(S
, EP
.Next
, 0, Undefs
);
1403 for (Register R
: *Edit
) {
1404 LiveInterval
&LI
= LIS
.getInterval(R
);
1405 if (!LI
.hasSubRanges())
1408 LI
.removeEmptySubRanges();
1409 LIS
.constructMainRangeFromSubranges(LI
);
1413 void SplitEditor::deleteRematVictims() {
1414 SmallVector
<MachineInstr
*, 8> Dead
;
1415 for (const Register
&R
: *Edit
) {
1416 LiveInterval
*LI
= &LIS
.getInterval(R
);
1417 for (const LiveRange::Segment
&S
: LI
->segments
) {
1418 // Dead defs end at the dead slot.
1419 if (S
.end
!= S
.valno
->def
.getDeadSlot())
1421 if (S
.valno
->isPHIDef())
1423 MachineInstr
*MI
= LIS
.getInstructionFromIndex(S
.valno
->def
);
1424 assert(MI
&& "Missing instruction for dead def");
1425 MI
->addRegisterDead(LI
->reg(), &TRI
);
1427 if (!MI
->allDefsAreDead())
1430 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI
);
1438 Edit
->eliminateDeadDefs(Dead
, None
, &AA
);
1441 void SplitEditor::forceRecomputeVNI(const VNInfo
&ParentVNI
) {
1442 // Fast-path for common case.
1443 if (!ParentVNI
.isPHIDef()) {
1444 for (unsigned I
= 0, E
= Edit
->size(); I
!= E
; ++I
)
1445 forceRecompute(I
, ParentVNI
);
1449 // Trace value through phis.
1450 SmallPtrSet
<const VNInfo
*, 8> Visited
; ///< whether VNI was/is in worklist.
1451 SmallVector
<const VNInfo
*, 4> WorkList
;
1452 Visited
.insert(&ParentVNI
);
1453 WorkList
.push_back(&ParentVNI
);
1455 const LiveInterval
&ParentLI
= Edit
->getParent();
1456 const SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
1458 const VNInfo
&VNI
= *WorkList
.back();
1459 WorkList
.pop_back();
1460 for (unsigned I
= 0, E
= Edit
->size(); I
!= E
; ++I
)
1461 forceRecompute(I
, VNI
);
1462 if (!VNI
.isPHIDef())
1465 MachineBasicBlock
&MBB
= *Indexes
.getMBBFromIndex(VNI
.def
);
1466 for (const MachineBasicBlock
*Pred
: MBB
.predecessors()) {
1467 SlotIndex PredEnd
= Indexes
.getMBBEndIdx(Pred
);
1468 VNInfo
*PredVNI
= ParentLI
.getVNInfoBefore(PredEnd
);
1469 assert(PredVNI
&& "Value available in PhiVNI predecessor");
1470 if (Visited
.insert(PredVNI
).second
)
1471 WorkList
.push_back(PredVNI
);
1473 } while(!WorkList
.empty());
1476 void SplitEditor::finish(SmallVectorImpl
<unsigned> *LRMap
) {
1479 // At this point, the live intervals in Edit contain VNInfos corresponding to
1480 // the inserted copies.
1482 // Add the original defs from the parent interval.
1483 for (const VNInfo
*ParentVNI
: Edit
->getParent().valnos
) {
1484 if (ParentVNI
->isUnused())
1486 unsigned RegIdx
= RegAssign
.lookup(ParentVNI
->def
);
1487 defValue(RegIdx
, ParentVNI
, ParentVNI
->def
, true);
1489 // Force rematted values to be recomputed everywhere.
1490 // The new live ranges may be truncated.
1491 if (Edit
->didRematerialize(ParentVNI
))
1492 forceRecomputeVNI(*ParentVNI
);
1495 // Hoist back-copies to the complement interval when in spill mode.
1496 switch (SpillMode
) {
1498 // Leave all back-copies as is.
1502 // hoistCopies will behave differently between size and speed.
1506 // Transfer the simply mapped values, check if any are skipped.
1507 bool Skipped
= transferValues();
1509 // Rewrite virtual registers, possibly extending ranges.
1510 rewriteAssigned(Skipped
);
1513 extendPHIKillRanges();
1517 // Delete defs that were rematted everywhere.
1519 deleteRematVictims();
1521 // Get rid of unused values and set phi-kill flags.
1522 for (Register Reg
: *Edit
) {
1523 LiveInterval
&LI
= LIS
.getInterval(Reg
);
1524 LI
.removeEmptySubRanges();
1525 LI
.RenumberValues();
1528 // Provide a reverse mapping from original indices to Edit ranges.
1531 for (unsigned i
= 0, e
= Edit
->size(); i
!= e
; ++i
)
1532 LRMap
->push_back(i
);
1535 // Now check if any registers were separated into multiple components.
1536 ConnectedVNInfoEqClasses
ConEQ(LIS
);
1537 for (unsigned i
= 0, e
= Edit
->size(); i
!= e
; ++i
) {
1538 // Don't use iterators, they are invalidated by create() below.
1539 Register VReg
= Edit
->get(i
);
1540 LiveInterval
&LI
= LIS
.getInterval(VReg
);
1541 SmallVector
<LiveInterval
*, 8> SplitLIs
;
1542 LIS
.splitSeparateComponents(LI
, SplitLIs
);
1543 Register Original
= VRM
.getOriginal(VReg
);
1544 for (LiveInterval
*SplitLI
: SplitLIs
)
1545 VRM
.setIsSplitFromReg(SplitLI
->reg(), Original
);
1547 // The new intervals all map back to i.
1549 LRMap
->resize(Edit
->size(), i
);
1552 // Calculate spill weight and allocation hints for new intervals.
1553 Edit
->calculateRegClassAndHint(VRM
.getMachineFunction(), VRAI
);
1555 assert(!LRMap
|| LRMap
->size() == Edit
->size());
1558 //===----------------------------------------------------------------------===//
1559 // Single Block Splitting
1560 //===----------------------------------------------------------------------===//
1562 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo
&BI
,
1563 bool SingleInstrs
) const {
1564 // Always split for multiple instructions.
1565 if (!BI
.isOneInstr())
1567 // Don't split for single instructions unless explicitly requested.
1570 // Splitting a live-through range always makes progress.
1571 if (BI
.LiveIn
&& BI
.LiveOut
)
1573 // No point in isolating a copy. It has no register class constraints.
1574 if (LIS
.getInstructionFromIndex(BI
.FirstInstr
)->isCopyLike())
1576 // Finally, don't isolate an end point that was created by earlier splits.
1577 return isOriginalEndpoint(BI
.FirstInstr
);
1580 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo
&BI
) {
1582 SlotIndex LastSplitPoint
= SA
.getLastSplitPoint(BI
.MBB
);
1583 SlotIndex SegStart
= enterIntvBefore(std::min(BI
.FirstInstr
,
1585 if (!BI
.LiveOut
|| BI
.LastInstr
< LastSplitPoint
) {
1586 useIntv(SegStart
, leaveIntvAfter(BI
.LastInstr
));
1588 // The last use is after the last valid split point.
1589 SlotIndex SegStop
= leaveIntvBefore(LastSplitPoint
);
1590 useIntv(SegStart
, SegStop
);
1591 overlapIntv(SegStop
, BI
.LastInstr
);
1595 //===----------------------------------------------------------------------===//
1596 // Global Live Range Splitting Support
1597 //===----------------------------------------------------------------------===//
1599 // These methods support a method of global live range splitting that uses a
1600 // global algorithm to decide intervals for CFG edges. They will insert split
1601 // points and color intervals in basic blocks while avoiding interference.
1603 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1604 // are on the stack.
1606 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum
,
1607 unsigned IntvIn
, SlotIndex LeaveBefore
,
1608 unsigned IntvOut
, SlotIndex EnterAfter
){
1609 SlotIndex Start
, Stop
;
1610 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(MBBNum
);
1612 LLVM_DEBUG(dbgs() << "%bb." << MBBNum
<< " [" << Start
<< ';' << Stop
1613 << ") intf " << LeaveBefore
<< '-' << EnterAfter
1614 << ", live-through " << IntvIn
<< " -> " << IntvOut
);
1616 assert((IntvIn
|| IntvOut
) && "Use splitSingleBlock for isolated blocks");
1618 assert((!LeaveBefore
|| LeaveBefore
< Stop
) && "Interference after block");
1619 assert((!IntvIn
|| !LeaveBefore
|| LeaveBefore
> Start
) && "Impossible intf");
1620 assert((!EnterAfter
|| EnterAfter
>= Start
) && "Interference before block");
1622 MachineBasicBlock
*MBB
= VRM
.getMachineFunction().getBlockNumbered(MBBNum
);
1625 LLVM_DEBUG(dbgs() << ", spill on entry.\n");
1627 // <<<<<<<<< Possible LeaveBefore interference.
1628 // |-----------| Live through.
1629 // -____________ Spill on entry.
1632 SlotIndex Idx
= leaveIntvAtTop(*MBB
);
1633 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1639 LLVM_DEBUG(dbgs() << ", reload on exit.\n");
1641 // >>>>>>> Possible EnterAfter interference.
1642 // |-----------| Live through.
1643 // ___________-- Reload on exit.
1645 selectIntv(IntvOut
);
1646 SlotIndex Idx
= enterIntvAtEnd(*MBB
);
1647 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1652 if (IntvIn
== IntvOut
&& !LeaveBefore
&& !EnterAfter
) {
1653 LLVM_DEBUG(dbgs() << ", straight through.\n");
1655 // |-----------| Live through.
1656 // ------------- Straight through, same intv, no interference.
1658 selectIntv(IntvOut
);
1659 useIntv(Start
, Stop
);
1663 // We cannot legally insert splits after LSP.
1664 SlotIndex LSP
= SA
.getLastSplitPoint(MBBNum
);
1665 assert((!IntvOut
|| !EnterAfter
|| EnterAfter
< LSP
) && "Impossible intf");
1667 if (IntvIn
!= IntvOut
&& (!LeaveBefore
|| !EnterAfter
||
1668 LeaveBefore
.getBaseIndex() > EnterAfter
.getBoundaryIndex())) {
1669 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n");
1671 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1672 // |-----------| Live through.
1673 // ------======= Switch intervals between interference.
1675 selectIntv(IntvOut
);
1677 if (LeaveBefore
&& LeaveBefore
< LSP
) {
1678 Idx
= enterIntvBefore(LeaveBefore
);
1681 Idx
= enterIntvAtEnd(*MBB
);
1684 useIntv(Start
, Idx
);
1685 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1686 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1690 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n");
1692 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1693 // |-----------| Live through.
1694 // ==---------== Switch intervals before/after interference.
1696 assert(LeaveBefore
<= EnterAfter
&& "Missed case");
1698 selectIntv(IntvOut
);
1699 SlotIndex Idx
= enterIntvAfter(EnterAfter
);
1701 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1704 Idx
= leaveIntvBefore(LeaveBefore
);
1705 useIntv(Start
, Idx
);
1706 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1709 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo
&BI
,
1710 unsigned IntvIn
, SlotIndex LeaveBefore
) {
1711 SlotIndex Start
, Stop
;
1712 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
1714 LLVM_DEBUG(dbgs() << printMBBReference(*BI
.MBB
) << " [" << Start
<< ';'
1715 << Stop
<< "), uses " << BI
.FirstInstr
<< '-'
1716 << BI
.LastInstr
<< ", reg-in " << IntvIn
1717 << ", leave before " << LeaveBefore
1718 << (BI
.LiveOut
? ", stack-out" : ", killed in block"));
1720 assert(IntvIn
&& "Must have register in");
1721 assert(BI
.LiveIn
&& "Must be live-in");
1722 assert((!LeaveBefore
|| LeaveBefore
> Start
) && "Bad interference");
1724 if (!BI
.LiveOut
&& (!LeaveBefore
|| LeaveBefore
>= BI
.LastInstr
)) {
1725 LLVM_DEBUG(dbgs() << " before interference.\n");
1727 // <<< Interference after kill.
1728 // |---o---x | Killed in block.
1729 // ========= Use IntvIn everywhere.
1732 useIntv(Start
, BI
.LastInstr
);
1736 SlotIndex LSP
= SA
.getLastSplitPoint(BI
.MBB
);
1738 if (!LeaveBefore
|| LeaveBefore
> BI
.LastInstr
.getBoundaryIndex()) {
1740 // <<< Possible interference after last use.
1741 // |---o---o---| Live-out on stack.
1742 // =========____ Leave IntvIn after last use.
1744 // < Interference after last use.
1745 // |---o---o--o| Live-out on stack, late last use.
1746 // ============ Copy to stack after LSP, overlap IntvIn.
1747 // \_____ Stack interval is live-out.
1749 if (BI
.LastInstr
< LSP
) {
1750 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n");
1752 SlotIndex Idx
= leaveIntvAfter(BI
.LastInstr
);
1753 useIntv(Start
, Idx
);
1754 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1756 LLVM_DEBUG(dbgs() << ", spill before last split point.\n");
1758 SlotIndex Idx
= leaveIntvBefore(LSP
);
1759 overlapIntv(Idx
, BI
.LastInstr
);
1760 useIntv(Start
, Idx
);
1761 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1766 // The interference is overlapping somewhere we wanted to use IntvIn. That
1767 // means we need to create a local interval that can be allocated a
1768 // different register.
1769 unsigned LocalIntv
= openIntv();
1771 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv
<< ".\n");
1773 if (!BI
.LiveOut
|| BI
.LastInstr
< LSP
) {
1775 // <<<<<<< Interference overlapping uses.
1776 // |---o---o---| Live-out on stack.
1777 // =====----____ Leave IntvIn before interference, then spill.
1779 SlotIndex To
= leaveIntvAfter(BI
.LastInstr
);
1780 SlotIndex From
= enterIntvBefore(LeaveBefore
);
1783 useIntv(Start
, From
);
1784 assert((!LeaveBefore
|| From
<= LeaveBefore
) && "Interference");
1788 // <<<<<<< Interference overlapping uses.
1789 // |---o---o--o| Live-out on stack, late last use.
1790 // =====------- Copy to stack before LSP, overlap LocalIntv.
1791 // \_____ Stack interval is live-out.
1793 SlotIndex To
= leaveIntvBefore(LSP
);
1794 overlapIntv(To
, BI
.LastInstr
);
1795 SlotIndex From
= enterIntvBefore(std::min(To
, LeaveBefore
));
1798 useIntv(Start
, From
);
1799 assert((!LeaveBefore
|| From
<= LeaveBefore
) && "Interference");
1802 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo
&BI
,
1803 unsigned IntvOut
, SlotIndex EnterAfter
) {
1804 SlotIndex Start
, Stop
;
1805 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
1807 LLVM_DEBUG(dbgs() << printMBBReference(*BI
.MBB
) << " [" << Start
<< ';'
1808 << Stop
<< "), uses " << BI
.FirstInstr
<< '-'
1809 << BI
.LastInstr
<< ", reg-out " << IntvOut
1810 << ", enter after " << EnterAfter
1811 << (BI
.LiveIn
? ", stack-in" : ", defined in block"));
1813 SlotIndex LSP
= SA
.getLastSplitPoint(BI
.MBB
);
1815 assert(IntvOut
&& "Must have register out");
1816 assert(BI
.LiveOut
&& "Must be live-out");
1817 assert((!EnterAfter
|| EnterAfter
< LSP
) && "Bad interference");
1819 if (!BI
.LiveIn
&& (!EnterAfter
|| EnterAfter
<= BI
.FirstInstr
)) {
1820 LLVM_DEBUG(dbgs() << " after interference.\n");
1822 // >>>> Interference before def.
1823 // | o---o---| Defined in block.
1824 // ========= Use IntvOut everywhere.
1826 selectIntv(IntvOut
);
1827 useIntv(BI
.FirstInstr
, Stop
);
1831 if (!EnterAfter
|| EnterAfter
< BI
.FirstInstr
.getBaseIndex()) {
1832 LLVM_DEBUG(dbgs() << ", reload after interference.\n");
1834 // >>>> Interference before def.
1835 // |---o---o---| Live-through, stack-in.
1836 // ____========= Enter IntvOut before first use.
1838 selectIntv(IntvOut
);
1839 SlotIndex Idx
= enterIntvBefore(std::min(LSP
, BI
.FirstInstr
));
1841 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1845 // The interference is overlapping somewhere we wanted to use IntvOut. That
1846 // means we need to create a local interval that can be allocated a
1847 // different register.
1848 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n");
1850 // >>>>>>> Interference overlapping uses.
1851 // |---o---o---| Live-through, stack-in.
1852 // ____---====== Create local interval for interference range.
1854 selectIntv(IntvOut
);
1855 SlotIndex Idx
= enterIntvAfter(EnterAfter
);
1857 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1860 SlotIndex From
= enterIntvBefore(std::min(Idx
, BI
.FirstInstr
));
1864 void SplitAnalysis::BlockInfo::print(raw_ostream
&OS
) const {
1865 OS
<< "{" << printMBBReference(*MBB
) << ", "
1866 << "uses " << FirstInstr
<< " to " << LastInstr
<< ", "
1867 << "1st def " << FirstDef
<< ", "
1868 << (LiveIn
? "live in" : "dead in") << ", "
1869 << (LiveOut
? "live out" : "dead out") << "}";
1872 void SplitAnalysis::BlockInfo::dump() const {