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 "LiveRangeCalc.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/LiveInterval.h"
24 #include "llvm/CodeGen/LiveIntervals.h"
25 #include "llvm/CodeGen/LiveRangeEdit.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SlotIndexes.h"
36 #include "llvm/CodeGen/TargetInstrInfo.h"
37 #include "llvm/CodeGen/TargetOpcodes.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/CodeGen/VirtRegMap.h"
41 #include "llvm/Config/llvm-config.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 LLVM_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 LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots
.size() << " instrs in "
205 << UseBlocks
.size() << " blocks, through "
206 << NumThroughBlocks
<< " blocks.\n");
209 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
210 /// where CurLI is live.
211 bool SplitAnalysis::calcLiveBlockInfo() {
212 ThroughBlocks
.resize(MF
.getNumBlockIDs());
213 NumThroughBlocks
= NumGapBlocks
= 0;
217 LiveInterval::const_iterator LVI
= CurLI
->begin();
218 LiveInterval::const_iterator LVE
= CurLI
->end();
220 SmallVectorImpl
<SlotIndex
>::const_iterator UseI
, UseE
;
221 UseI
= UseSlots
.begin();
222 UseE
= UseSlots
.end();
224 // Loop over basic blocks where CurLI is live.
225 MachineFunction::iterator MFI
=
226 LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
230 SlotIndex Start
, Stop
;
231 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
233 // If the block contains no uses, the range must be live through. At one
234 // point, RegisterCoalescer could create dangling ranges that ended
236 if (UseI
== UseE
|| *UseI
>= Stop
) {
238 ThroughBlocks
.set(BI
.MBB
->getNumber());
239 // The range shouldn't end mid-block if there are no uses. This shouldn't
244 // This block has uses. Find the first and last uses in the block.
245 BI
.FirstInstr
= *UseI
;
246 assert(BI
.FirstInstr
>= Start
);
248 while (UseI
!= UseE
&& *UseI
< Stop
);
249 BI
.LastInstr
= UseI
[-1];
250 assert(BI
.LastInstr
< Stop
);
252 // LVI is the first live segment overlapping MBB.
253 BI
.LiveIn
= LVI
->start
<= Start
;
255 // When not live in, the first use should be a def.
257 assert(LVI
->start
== LVI
->valno
->def
&& "Dangling Segment start");
258 assert(LVI
->start
== BI
.FirstInstr
&& "First instr should be a def");
259 BI
.FirstDef
= BI
.FirstInstr
;
262 // Look for gaps in the live range.
264 while (LVI
->end
< Stop
) {
265 SlotIndex LastStop
= LVI
->end
;
266 if (++LVI
== LVE
|| LVI
->start
>= Stop
) {
268 BI
.LastInstr
= LastStop
;
272 if (LastStop
< LVI
->start
) {
273 // There is a gap in the live range. Create duplicate entries for the
274 // live-in snippet and the live-out snippet.
277 // Push the Live-in part.
279 UseBlocks
.push_back(BI
);
280 UseBlocks
.back().LastInstr
= LastStop
;
282 // Set up BI for the live-out part.
285 BI
.FirstInstr
= BI
.FirstDef
= LVI
->start
;
288 // A Segment that starts in the middle of the block must be a def.
289 assert(LVI
->start
== LVI
->valno
->def
&& "Dangling Segment start");
291 BI
.FirstDef
= LVI
->start
;
294 UseBlocks
.push_back(BI
);
296 // LVI is now at LVE or LVI->end >= Stop.
301 // Live segment ends exactly at Stop. Move to the next segment.
302 if (LVI
->end
== Stop
&& ++LVI
== LVE
)
305 // Pick the next basic block.
306 if (LVI
->start
< Stop
)
309 MFI
= LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
312 assert(getNumLiveBlocks() == countLiveBlocks(CurLI
) && "Bad block count");
316 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval
*cli
) const {
319 LiveInterval
*li
= const_cast<LiveInterval
*>(cli
);
320 LiveInterval::iterator LVI
= li
->begin();
321 LiveInterval::iterator LVE
= li
->end();
324 // Loop over basic blocks where li is live.
325 MachineFunction::const_iterator MFI
=
326 LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
327 SlotIndex Stop
= LIS
.getMBBEndIdx(&*MFI
);
330 LVI
= li
->advanceTo(LVI
, Stop
);
335 Stop
= LIS
.getMBBEndIdx(&*MFI
);
336 } while (Stop
<= LVI
->start
);
340 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx
) const {
341 unsigned OrigReg
= VRM
.getOriginal(CurLI
->reg
);
342 const LiveInterval
&Orig
= LIS
.getInterval(OrigReg
);
343 assert(!Orig
.empty() && "Splitting empty interval?");
344 LiveInterval::const_iterator I
= Orig
.find(Idx
);
346 // Range containing Idx should begin at Idx.
347 if (I
!= Orig
.end() && I
->start
<= Idx
)
348 return I
->start
== Idx
;
350 // Range does not contain Idx, previous must end at Idx.
351 return I
!= Orig
.begin() && (--I
)->end
== Idx
;
354 void SplitAnalysis::analyze(const LiveInterval
*li
) {
360 //===----------------------------------------------------------------------===//
362 //===----------------------------------------------------------------------===//
364 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
365 SplitEditor::SplitEditor(SplitAnalysis
&sa
, AliasAnalysis
&aa
,
366 LiveIntervals
&lis
, VirtRegMap
&vrm
,
367 MachineDominatorTree
&mdt
,
368 MachineBlockFrequencyInfo
&mbfi
)
369 : SA(sa
), AA(aa
), LIS(lis
), VRM(vrm
),
370 MRI(vrm
.getMachineFunction().getRegInfo()), MDT(mdt
),
371 TII(*vrm
.getMachineFunction().getSubtarget().getInstrInfo()),
372 TRI(*vrm
.getMachineFunction().getSubtarget().getRegisterInfo()),
373 MBFI(mbfi
), RegAssign(Allocator
) {}
375 void SplitEditor::reset(LiveRangeEdit
&LRE
, ComplementSpillMode SM
) {
382 // Reset the LiveRangeCalc instances needed for this spill mode.
383 LRCalc
[0].reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
384 &LIS
.getVNInfoAllocator());
386 LRCalc
[1].reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
387 &LIS
.getVNInfoAllocator());
389 // We don't need an AliasAnalysis since we will only be performing
390 // cheap-as-a-copy remats anyway.
391 Edit
->anyRematerializable(nullptr);
394 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
395 LLVM_DUMP_METHOD
void SplitEditor::dump() const {
396 if (RegAssign
.empty()) {
397 dbgs() << " empty\n";
401 for (RegAssignMap::const_iterator I
= RegAssign
.begin(); I
.valid(); ++I
)
402 dbgs() << " [" << I
.start() << ';' << I
.stop() << "):" << I
.value();
407 LiveInterval::SubRange
&SplitEditor::getSubRangeForMask(LaneBitmask LM
,
409 for (LiveInterval::SubRange
&S
: LI
.subranges())
410 if (S
.LaneMask
== LM
)
412 llvm_unreachable("SubRange for this mask not found");
415 void SplitEditor::addDeadDef(LiveInterval
&LI
, VNInfo
*VNI
, bool Original
) {
416 if (!LI
.hasSubRanges()) {
417 LI
.createDeadDef(VNI
);
421 SlotIndex Def
= VNI
->def
;
423 // If we are transferring a def from the original interval, make sure
424 // to only update the subranges for which the original subranges had
425 // a def at this location.
426 for (LiveInterval::SubRange
&S
: LI
.subranges()) {
427 auto &PS
= getSubRangeForMask(S
.LaneMask
, Edit
->getParent());
428 VNInfo
*PV
= PS
.getVNInfoAt(Def
);
429 if (PV
!= nullptr && PV
->def
== Def
)
430 S
.createDeadDef(Def
, LIS
.getVNInfoAllocator());
433 // This is a new def: either from rematerialization, or from an inserted
434 // copy. Since rematerialization can regenerate a definition of a sub-
435 // register, we need to check which subranges need to be updated.
436 const MachineInstr
*DefMI
= LIS
.getInstructionFromIndex(Def
);
437 assert(DefMI
!= nullptr);
439 for (const MachineOperand
&DefOp
: DefMI
->defs()) {
440 unsigned R
= DefOp
.getReg();
443 if (unsigned SR
= DefOp
.getSubReg())
444 LM
|= TRI
.getSubRegIndexLaneMask(SR
);
446 LM
= MRI
.getMaxLaneMaskForVReg(R
);
450 for (LiveInterval::SubRange
&S
: LI
.subranges())
451 if ((S
.LaneMask
& LM
).any())
452 S
.createDeadDef(Def
, LIS
.getVNInfoAllocator());
456 VNInfo
*SplitEditor::defValue(unsigned RegIdx
,
457 const VNInfo
*ParentVNI
,
460 assert(ParentVNI
&& "Mapping NULL value");
461 assert(Idx
.isValid() && "Invalid SlotIndex");
462 assert(Edit
->getParent().getVNInfoAt(Idx
) == ParentVNI
&& "Bad Parent VNI");
463 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(RegIdx
));
465 // Create a new value.
466 VNInfo
*VNI
= LI
->getNextValue(Idx
, LIS
.getVNInfoAllocator());
468 bool Force
= LI
->hasSubRanges();
469 ValueForcePair
FP(Force
? nullptr : VNI
, Force
);
470 // Use insert for lookup, so we can add missing values with a second lookup.
471 std::pair
<ValueMap::iterator
, bool> InsP
=
472 Values
.insert(std::make_pair(std::make_pair(RegIdx
, ParentVNI
->id
), FP
));
474 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not
475 // forced. Keep it as a simple def without any liveness.
476 if (!Force
&& InsP
.second
)
479 // If the previous value was a simple mapping, add liveness for it now.
480 if (VNInfo
*OldVNI
= InsP
.first
->second
.getPointer()) {
481 addDeadDef(*LI
, OldVNI
, Original
);
483 // No longer a simple mapping. Switch to a complex mapping. If the
484 // interval has subranges, make it a forced mapping.
485 InsP
.first
->second
= ValueForcePair(nullptr, Force
);
488 // This is a complex mapping, add liveness for VNI
489 addDeadDef(*LI
, VNI
, Original
);
493 void SplitEditor::forceRecompute(unsigned RegIdx
, const VNInfo
&ParentVNI
) {
494 ValueForcePair
&VFP
= Values
[std::make_pair(RegIdx
, ParentVNI
.id
)];
495 VNInfo
*VNI
= VFP
.getPointer();
497 // ParentVNI was either unmapped or already complex mapped. Either way, just
498 // set the force bit.
504 // This was previously a single mapping. Make sure the old def is represented
505 // by a trivial live range.
506 addDeadDef(LIS
.getInterval(Edit
->get(RegIdx
)), VNI
, false);
508 // Mark as complex mapped, forced.
509 VFP
= ValueForcePair(nullptr, true);
512 SlotIndex
SplitEditor::buildSingleSubRegCopy(unsigned FromReg
, unsigned ToReg
,
513 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator InsertBefore
,
514 unsigned SubIdx
, LiveInterval
&DestLI
, bool Late
, SlotIndex Def
) {
515 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::COPY
);
516 bool FirstCopy
= !Def
.isValid();
517 MachineInstr
*CopyMI
= BuildMI(MBB
, InsertBefore
, DebugLoc(), Desc
)
518 .addReg(ToReg
, RegState::Define
| getUndefRegState(FirstCopy
)
519 | getInternalReadRegState(!FirstCopy
), SubIdx
)
520 .addReg(FromReg
, 0, SubIdx
);
522 BumpPtrAllocator
&Allocator
= LIS
.getVNInfoAllocator();
524 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
525 Def
= Indexes
.insertMachineInstrInMaps(*CopyMI
, Late
).getRegSlot();
527 CopyMI
->bundleWithPred();
529 LaneBitmask LaneMask
= TRI
.getSubRegIndexLaneMask(SubIdx
);
530 DestLI
.refineSubRanges(Allocator
, LaneMask
,
531 [Def
, &Allocator
](LiveInterval::SubRange
& SR
) {
532 SR
.createDeadDef(Def
, Allocator
);
537 SlotIndex
SplitEditor::buildCopy(unsigned FromReg
, unsigned ToReg
,
538 LaneBitmask LaneMask
, MachineBasicBlock
&MBB
,
539 MachineBasicBlock::iterator InsertBefore
, bool Late
, unsigned RegIdx
) {
540 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::COPY
);
541 if (LaneMask
.all() || LaneMask
== MRI
.getMaxLaneMaskForVReg(FromReg
)) {
542 // The full vreg is copied.
543 MachineInstr
*CopyMI
=
544 BuildMI(MBB
, InsertBefore
, DebugLoc(), Desc
, ToReg
).addReg(FromReg
);
545 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
546 return Indexes
.insertMachineInstrInMaps(*CopyMI
, Late
).getRegSlot();
549 // Only a subset of lanes needs to be copied. The following is a simple
550 // heuristic to construct a sequence of COPYs. We could add a target
551 // specific callback if this turns out to be suboptimal.
552 LiveInterval
&DestLI
= LIS
.getInterval(Edit
->get(RegIdx
));
554 // First pass: Try to find a perfectly matching subregister index. If none
555 // exists find the one covering the most lanemask bits.
556 SmallVector
<unsigned, 8> PossibleIndexes
;
557 unsigned BestIdx
= 0;
558 unsigned BestCover
= 0;
559 const TargetRegisterClass
*RC
= MRI
.getRegClass(FromReg
);
560 assert(RC
== MRI
.getRegClass(ToReg
) && "Should have same reg class");
561 for (unsigned Idx
= 1, E
= TRI
.getNumSubRegIndices(); Idx
< E
; ++Idx
) {
562 // Is this index even compatible with the given class?
563 if (TRI
.getSubClassWithSubReg(RC
, Idx
) != RC
)
565 LaneBitmask SubRegMask
= TRI
.getSubRegIndexLaneMask(Idx
);
566 // Early exit if we found a perfect match.
567 if (SubRegMask
== LaneMask
) {
572 // The index must not cover any lanes outside \p LaneMask.
573 if ((SubRegMask
& ~LaneMask
).any())
576 unsigned PopCount
= SubRegMask
.getNumLanes();
577 PossibleIndexes
.push_back(Idx
);
578 if (PopCount
> BestCover
) {
579 BestCover
= PopCount
;
584 // Abort if we cannot possibly implement the COPY with the given indexes.
586 report_fatal_error("Impossible to implement partial COPY");
588 SlotIndex Def
= buildSingleSubRegCopy(FromReg
, ToReg
, MBB
, InsertBefore
,
589 BestIdx
, DestLI
, Late
, SlotIndex());
591 // Greedy heuristic: Keep iterating keeping the best covering subreg index
593 LaneBitmask LanesLeft
= LaneMask
& ~(TRI
.getSubRegIndexLaneMask(BestIdx
));
594 while (LanesLeft
.any()) {
595 unsigned BestIdx
= 0;
596 int BestCover
= std::numeric_limits
<int>::min();
597 for (unsigned Idx
: PossibleIndexes
) {
598 LaneBitmask SubRegMask
= TRI
.getSubRegIndexLaneMask(Idx
);
599 // Early exit if we found a perfect match.
600 if (SubRegMask
== LanesLeft
) {
605 // Try to cover as much of the remaining lanes as possible but
606 // as few of the already covered lanes as possible.
607 int Cover
= (SubRegMask
& LanesLeft
).getNumLanes()
608 - (SubRegMask
& ~LanesLeft
).getNumLanes();
609 if (Cover
> BestCover
) {
616 report_fatal_error("Impossible to implement partial COPY");
618 buildSingleSubRegCopy(FromReg
, ToReg
, MBB
, InsertBefore
, BestIdx
,
620 LanesLeft
&= ~TRI
.getSubRegIndexLaneMask(BestIdx
);
626 VNInfo
*SplitEditor::defFromParent(unsigned RegIdx
,
629 MachineBasicBlock
&MBB
,
630 MachineBasicBlock::iterator I
) {
632 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(RegIdx
));
634 // We may be trying to avoid interference that ends at a deleted instruction,
635 // so always begin RegIdx 0 early and all others late.
636 bool Late
= RegIdx
!= 0;
638 // Attempt cheap-as-a-copy rematerialization.
639 unsigned Original
= VRM
.getOriginal(Edit
->get(RegIdx
));
640 LiveInterval
&OrigLI
= LIS
.getInterval(Original
);
641 VNInfo
*OrigVNI
= OrigLI
.getVNInfoAt(UseIdx
);
643 unsigned Reg
= LI
->reg
;
644 bool DidRemat
= false;
646 LiveRangeEdit::Remat
RM(ParentVNI
);
647 RM
.OrigMI
= LIS
.getInstructionFromIndex(OrigVNI
->def
);
648 if (Edit
->canRematerializeAt(RM
, OrigVNI
, UseIdx
, true)) {
649 Def
= Edit
->rematerializeAt(MBB
, I
, Reg
, RM
, TRI
, Late
);
655 LaneBitmask LaneMask
;
656 if (LI
->hasSubRanges()) {
657 LaneMask
= LaneBitmask::getNone();
658 for (LiveInterval::SubRange
&S
: LI
->subranges())
659 LaneMask
|= S
.LaneMask
;
661 LaneMask
= LaneBitmask::getAll();
665 Def
= buildCopy(Edit
->getReg(), Reg
, LaneMask
, MBB
, I
, Late
, RegIdx
);
668 // Define the value in Reg.
669 return defValue(RegIdx
, ParentVNI
, Def
, false);
672 /// Create a new virtual register and live interval.
673 unsigned SplitEditor::openIntv() {
674 // Create the complement as index 0.
676 Edit
->createEmptyInterval();
678 // Create the open interval.
679 OpenIdx
= Edit
->size();
680 Edit
->createEmptyInterval();
684 void SplitEditor::selectIntv(unsigned Idx
) {
685 assert(Idx
!= 0 && "Cannot select the complement interval");
686 assert(Idx
< Edit
->size() && "Can only select previously opened interval");
687 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx
<< " -> " << Idx
<< '\n');
691 SlotIndex
SplitEditor::enterIntvBefore(SlotIndex Idx
) {
692 assert(OpenIdx
&& "openIntv not called before enterIntvBefore");
693 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx
);
694 Idx
= Idx
.getBaseIndex();
695 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
697 LLVM_DEBUG(dbgs() << ": not live\n");
700 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
701 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
702 assert(MI
&& "enterIntvBefore called with invalid index");
704 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Idx
, *MI
->getParent(), MI
);
708 SlotIndex
SplitEditor::enterIntvAfter(SlotIndex Idx
) {
709 assert(OpenIdx
&& "openIntv not called before enterIntvAfter");
710 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx
);
711 Idx
= Idx
.getBoundaryIndex();
712 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
714 LLVM_DEBUG(dbgs() << ": not live\n");
717 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
718 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
719 assert(MI
&& "enterIntvAfter called with invalid index");
721 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Idx
, *MI
->getParent(),
722 std::next(MachineBasicBlock::iterator(MI
)));
726 SlotIndex
SplitEditor::enterIntvAtEnd(MachineBasicBlock
&MBB
) {
727 assert(OpenIdx
&& "openIntv not called before enterIntvAtEnd");
728 SlotIndex End
= LIS
.getMBBEndIdx(&MBB
);
729 SlotIndex Last
= End
.getPrevSlot();
730 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB
) << ", "
732 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Last
);
734 LLVM_DEBUG(dbgs() << ": not live\n");
737 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
);
738 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Last
, MBB
,
739 SA
.getLastSplitPointIter(&MBB
));
740 RegAssign
.insert(VNI
->def
, End
, OpenIdx
);
745 /// useIntv - indicate that all instructions in MBB should use OpenLI.
746 void SplitEditor::useIntv(const MachineBasicBlock
&MBB
) {
747 useIntv(LIS
.getMBBStartIdx(&MBB
), LIS
.getMBBEndIdx(&MBB
));
750 void SplitEditor::useIntv(SlotIndex Start
, SlotIndex End
) {
751 assert(OpenIdx
&& "openIntv not called before useIntv");
752 LLVM_DEBUG(dbgs() << " useIntv [" << Start
<< ';' << End
<< "):");
753 RegAssign
.insert(Start
, End
, OpenIdx
);
757 SlotIndex
SplitEditor::leaveIntvAfter(SlotIndex Idx
) {
758 assert(OpenIdx
&& "openIntv not called before leaveIntvAfter");
759 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx
);
761 // The interval must be live beyond the instruction at Idx.
762 SlotIndex Boundary
= Idx
.getBoundaryIndex();
763 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Boundary
);
765 LLVM_DEBUG(dbgs() << ": not live\n");
766 return Boundary
.getNextSlot();
768 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
769 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Boundary
);
770 assert(MI
&& "No instruction at index");
772 // In spill mode, make live ranges as short as possible by inserting the copy
773 // before MI. This is only possible if that instruction doesn't redefine the
774 // value. The inserted COPY is not a kill, and we don't need to recompute
775 // the source live range. The spiller also won't try to hoist this copy.
776 if (SpillMode
&& !SlotIndex::isSameInstr(ParentVNI
->def
, Idx
) &&
777 MI
->readsVirtualRegister(Edit
->getReg())) {
778 forceRecompute(0, *ParentVNI
);
779 defFromParent(0, ParentVNI
, Idx
, *MI
->getParent(), MI
);
783 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Boundary
, *MI
->getParent(),
784 std::next(MachineBasicBlock::iterator(MI
)));
788 SlotIndex
SplitEditor::leaveIntvBefore(SlotIndex Idx
) {
789 assert(OpenIdx
&& "openIntv not called before leaveIntvBefore");
790 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx
);
792 // The interval must be live into the instruction at Idx.
793 Idx
= Idx
.getBaseIndex();
794 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
796 LLVM_DEBUG(dbgs() << ": not live\n");
797 return Idx
.getNextSlot();
799 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
801 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
802 assert(MI
&& "No instruction at index");
803 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Idx
, *MI
->getParent(), MI
);
807 SlotIndex
SplitEditor::leaveIntvAtTop(MachineBasicBlock
&MBB
) {
808 assert(OpenIdx
&& "openIntv not called before leaveIntvAtTop");
809 SlotIndex Start
= LIS
.getMBBStartIdx(&MBB
);
810 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB
) << ", "
813 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Start
);
815 LLVM_DEBUG(dbgs() << ": not live\n");
819 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Start
, MBB
,
820 MBB
.SkipPHIsLabelsAndDebug(MBB
.begin()));
821 RegAssign
.insert(Start
, VNI
->def
, OpenIdx
);
826 void SplitEditor::overlapIntv(SlotIndex Start
, SlotIndex End
) {
827 assert(OpenIdx
&& "openIntv not called before overlapIntv");
828 const VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Start
);
829 assert(ParentVNI
== Edit
->getParent().getVNInfoBefore(End
) &&
830 "Parent changes value in extended range");
831 assert(LIS
.getMBBFromIndex(Start
) == LIS
.getMBBFromIndex(End
) &&
832 "Range cannot span basic blocks");
834 // The complement interval will be extended as needed by LRCalc.extend().
836 forceRecompute(0, *ParentVNI
);
837 LLVM_DEBUG(dbgs() << " overlapIntv [" << Start
<< ';' << End
<< "):");
838 RegAssign
.insert(Start
, End
, OpenIdx
);
842 //===----------------------------------------------------------------------===//
844 //===----------------------------------------------------------------------===//
846 void SplitEditor::removeBackCopies(SmallVectorImpl
<VNInfo
*> &Copies
) {
847 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
848 LLVM_DEBUG(dbgs() << "Removing " << Copies
.size() << " back-copies.\n");
849 RegAssignMap::iterator AssignI
;
850 AssignI
.setMap(RegAssign
);
852 for (unsigned i
= 0, e
= Copies
.size(); i
!= e
; ++i
) {
853 SlotIndex Def
= Copies
[i
]->def
;
854 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Def
);
855 assert(MI
&& "No instruction for back-copy");
857 MachineBasicBlock
*MBB
= MI
->getParent();
858 MachineBasicBlock::iterator
MBBI(MI
);
860 do AtBegin
= MBBI
== MBB
->begin();
861 while (!AtBegin
&& (--MBBI
)->isDebugInstr());
863 LLVM_DEBUG(dbgs() << "Removing " << Def
<< '\t' << *MI
);
864 LIS
.removeVRegDefAt(*LI
, Def
);
865 LIS
.RemoveMachineInstrFromMaps(*MI
);
866 MI
->eraseFromParent();
868 // Adjust RegAssign if a register assignment is killed at Def. We want to
869 // avoid calculating the live range of the source register if possible.
870 AssignI
.find(Def
.getPrevSlot());
871 if (!AssignI
.valid() || AssignI
.start() >= Def
)
873 // If MI doesn't kill the assigned register, just leave it.
874 if (AssignI
.stop() != Def
)
876 unsigned RegIdx
= AssignI
.value();
877 if (AtBegin
|| !MBBI
->readsVirtualRegister(Edit
->getReg())) {
878 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx
880 forceRecompute(RegIdx
, *Edit
->getParent().getVNInfoAt(Def
));
882 SlotIndex Kill
= LIS
.getInstructionIndex(*MBBI
).getRegSlot();
883 LLVM_DEBUG(dbgs() << " move kill to " << Kill
<< '\t' << *MBBI
);
884 AssignI
.setStop(Kill
);
890 SplitEditor::findShallowDominator(MachineBasicBlock
*MBB
,
891 MachineBasicBlock
*DefMBB
) {
894 assert(MDT
.dominates(DefMBB
, MBB
) && "MBB must be dominated by the def.");
896 const MachineLoopInfo
&Loops
= SA
.Loops
;
897 const MachineLoop
*DefLoop
= Loops
.getLoopFor(DefMBB
);
898 MachineDomTreeNode
*DefDomNode
= MDT
[DefMBB
];
900 // Best candidate so far.
901 MachineBasicBlock
*BestMBB
= MBB
;
902 unsigned BestDepth
= std::numeric_limits
<unsigned>::max();
905 const MachineLoop
*Loop
= Loops
.getLoopFor(MBB
);
907 // MBB isn't in a loop, it doesn't get any better. All dominators have a
908 // higher frequency by definition.
910 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
911 << " dominates " << printMBBReference(*MBB
)
916 // We'll never be able to exit the DefLoop.
917 if (Loop
== DefLoop
) {
918 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
919 << " dominates " << printMBBReference(*MBB
)
920 << " in the same loop\n");
924 // Least busy dominator seen so far.
925 unsigned Depth
= Loop
->getLoopDepth();
926 if (Depth
< BestDepth
) {
929 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
930 << " dominates " << printMBBReference(*MBB
)
931 << " at depth " << Depth
<< '\n');
934 // Leave loop by going to the immediate dominator of the loop header.
935 // This is a bigger stride than simply walking up the dominator tree.
936 MachineDomTreeNode
*IDom
= MDT
[Loop
->getHeader()]->getIDom();
938 // Too far up the dominator tree?
939 if (!IDom
|| !MDT
.dominates(DefDomNode
, IDom
))
942 MBB
= IDom
->getBlock();
946 void SplitEditor::computeRedundantBackCopies(
947 DenseSet
<unsigned> &NotToHoistSet
, SmallVectorImpl
<VNInfo
*> &BackCopies
) {
948 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
949 LiveInterval
*Parent
= &Edit
->getParent();
950 SmallVector
<SmallPtrSet
<VNInfo
*, 8>, 8> EqualVNs(Parent
->getNumValNums());
951 SmallPtrSet
<VNInfo
*, 8> DominatedVNIs
;
953 // Aggregate VNIs having the same value as ParentVNI.
954 for (VNInfo
*VNI
: LI
->valnos
) {
957 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
958 EqualVNs
[ParentVNI
->id
].insert(VNI
);
961 // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
962 // redundant VNIs to BackCopies.
963 for (unsigned i
= 0, e
= Parent
->getNumValNums(); i
!= e
; ++i
) {
964 VNInfo
*ParentVNI
= Parent
->getValNumInfo(i
);
965 if (!NotToHoistSet
.count(ParentVNI
->id
))
967 SmallPtrSetIterator
<VNInfo
*> It1
= EqualVNs
[ParentVNI
->id
].begin();
968 SmallPtrSetIterator
<VNInfo
*> It2
= It1
;
969 for (; It1
!= EqualVNs
[ParentVNI
->id
].end(); ++It1
) {
971 for (++It2
; It2
!= EqualVNs
[ParentVNI
->id
].end(); ++It2
) {
972 if (DominatedVNIs
.count(*It1
) || DominatedVNIs
.count(*It2
))
975 MachineBasicBlock
*MBB1
= LIS
.getMBBFromIndex((*It1
)->def
);
976 MachineBasicBlock
*MBB2
= LIS
.getMBBFromIndex((*It2
)->def
);
978 DominatedVNIs
.insert((*It1
)->def
< (*It2
)->def
? (*It2
) : (*It1
));
979 } else if (MDT
.dominates(MBB1
, MBB2
)) {
980 DominatedVNIs
.insert(*It2
);
981 } else if (MDT
.dominates(MBB2
, MBB1
)) {
982 DominatedVNIs
.insert(*It1
);
986 if (!DominatedVNIs
.empty()) {
987 forceRecompute(0, *ParentVNI
);
988 for (auto VNI
: DominatedVNIs
) {
989 BackCopies
.push_back(VNI
);
991 DominatedVNIs
.clear();
996 /// For SM_Size mode, find a common dominator for all the back-copies for
997 /// the same ParentVNI and hoist the backcopies to the dominator BB.
998 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial
999 /// to do the hoisting, simply remove the dominated backcopies for the same
1001 void SplitEditor::hoistCopies() {
1002 // Get the complement interval, always RegIdx 0.
1003 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
1004 LiveInterval
*Parent
= &Edit
->getParent();
1006 // Track the nearest common dominator for all back-copies for each ParentVNI,
1007 // indexed by ParentVNI->id.
1008 using DomPair
= std::pair
<MachineBasicBlock
*, SlotIndex
>;
1009 SmallVector
<DomPair
, 8> NearestDom(Parent
->getNumValNums());
1010 // The total cost of all the back-copies for each ParentVNI.
1011 SmallVector
<BlockFrequency
, 8> Costs(Parent
->getNumValNums());
1012 // The ParentVNI->id set for which hoisting back-copies are not beneficial
1014 DenseSet
<unsigned> NotToHoistSet
;
1016 // Find the nearest common dominator for parent values with multiple
1017 // back-copies. If a single back-copy dominates, put it in DomPair.second.
1018 for (VNInfo
*VNI
: LI
->valnos
) {
1019 if (VNI
->isUnused())
1021 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
1022 assert(ParentVNI
&& "Parent not live at complement def");
1024 // Don't hoist remats. The complement is probably going to disappear
1025 // completely anyway.
1026 if (Edit
->didRematerialize(ParentVNI
))
1029 MachineBasicBlock
*ValMBB
= LIS
.getMBBFromIndex(VNI
->def
);
1031 DomPair
&Dom
= NearestDom
[ParentVNI
->id
];
1033 // Keep directly defined parent values. This is either a PHI or an
1034 // instruction in the complement range. All other copies of ParentVNI
1035 // should be eliminated.
1036 if (VNI
->def
== ParentVNI
->def
) {
1037 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI
->def
<< '\n');
1038 Dom
= DomPair(ValMBB
, VNI
->def
);
1041 // Skip the singly mapped values. There is nothing to gain from hoisting a
1042 // single back-copy.
1043 if (Values
.lookup(std::make_pair(0, ParentVNI
->id
)).getPointer()) {
1044 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI
->def
<< '\n');
1049 // First time we see ParentVNI. VNI dominates itself.
1050 Dom
= DomPair(ValMBB
, VNI
->def
);
1051 } else if (Dom
.first
== ValMBB
) {
1052 // Two defs in the same block. Pick the earlier def.
1053 if (!Dom
.second
.isValid() || VNI
->def
< Dom
.second
)
1054 Dom
.second
= VNI
->def
;
1056 // Different basic blocks. Check if one dominates.
1057 MachineBasicBlock
*Near
=
1058 MDT
.findNearestCommonDominator(Dom
.first
, ValMBB
);
1060 // Def ValMBB dominates.
1061 Dom
= DomPair(ValMBB
, VNI
->def
);
1062 else if (Near
!= Dom
.first
)
1063 // None dominate. Hoist to common dominator, need new def.
1064 Dom
= DomPair(Near
, SlotIndex());
1065 Costs
[ParentVNI
->id
] += MBFI
.getBlockFreq(ValMBB
);
1068 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI
->id
<< '@'
1069 << VNI
->def
<< " for parent " << ParentVNI
->id
<< '@'
1070 << ParentVNI
->def
<< " hoist to "
1071 << printMBBReference(*Dom
.first
) << ' ' << Dom
.second
1075 // Insert the hoisted copies.
1076 for (unsigned i
= 0, e
= Parent
->getNumValNums(); i
!= e
; ++i
) {
1077 DomPair
&Dom
= NearestDom
[i
];
1078 if (!Dom
.first
|| Dom
.second
.isValid())
1080 // This value needs a hoisted copy inserted at the end of Dom.first.
1081 VNInfo
*ParentVNI
= Parent
->getValNumInfo(i
);
1082 MachineBasicBlock
*DefMBB
= LIS
.getMBBFromIndex(ParentVNI
->def
);
1083 // Get a less loopy dominator than Dom.first.
1084 Dom
.first
= findShallowDominator(Dom
.first
, DefMBB
);
1085 if (SpillMode
== SM_Speed
&&
1086 MBFI
.getBlockFreq(Dom
.first
) > Costs
[ParentVNI
->id
]) {
1087 NotToHoistSet
.insert(ParentVNI
->id
);
1090 SlotIndex Last
= LIS
.getMBBEndIdx(Dom
.first
).getPrevSlot();
1092 defFromParent(0, ParentVNI
, Last
, *Dom
.first
,
1093 SA
.getLastSplitPointIter(Dom
.first
))->def
;
1096 // Remove redundant back-copies that are now known to be dominated by another
1097 // def with the same value.
1098 SmallVector
<VNInfo
*, 8> BackCopies
;
1099 for (VNInfo
*VNI
: LI
->valnos
) {
1100 if (VNI
->isUnused())
1102 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
1103 const DomPair
&Dom
= NearestDom
[ParentVNI
->id
];
1104 if (!Dom
.first
|| Dom
.second
== VNI
->def
||
1105 NotToHoistSet
.count(ParentVNI
->id
))
1107 BackCopies
.push_back(VNI
);
1108 forceRecompute(0, *ParentVNI
);
1111 // If it is not beneficial to hoist all the BackCopies, simply remove
1112 // redundant BackCopies in speed mode.
1113 if (SpillMode
== SM_Speed
&& !NotToHoistSet
.empty())
1114 computeRedundantBackCopies(NotToHoistSet
, BackCopies
);
1116 removeBackCopies(BackCopies
);
1119 /// transferValues - Transfer all possible values to the new live ranges.
1120 /// Values that were rematerialized are left alone, they need LRCalc.extend().
1121 bool SplitEditor::transferValues() {
1122 bool Skipped
= false;
1123 RegAssignMap::const_iterator AssignI
= RegAssign
.begin();
1124 for (const LiveRange::Segment
&S
: Edit
->getParent()) {
1125 LLVM_DEBUG(dbgs() << " blit " << S
<< ':');
1126 VNInfo
*ParentVNI
= S
.valno
;
1127 // RegAssign has holes where RegIdx 0 should be used.
1128 SlotIndex Start
= S
.start
;
1129 AssignI
.advanceTo(Start
);
1132 SlotIndex End
= S
.end
;
1133 if (!AssignI
.valid()) {
1135 } else if (AssignI
.start() <= Start
) {
1136 RegIdx
= AssignI
.value();
1137 if (AssignI
.stop() < End
) {
1138 End
= AssignI
.stop();
1143 End
= std::min(End
, AssignI
.start());
1146 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
1147 LLVM_DEBUG(dbgs() << " [" << Start
<< ';' << End
<< ")=" << RegIdx
<< '('
1148 << printReg(Edit
->get(RegIdx
)) << ')');
1149 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1151 // Check for a simply defined value that can be blitted directly.
1152 ValueForcePair VFP
= Values
.lookup(std::make_pair(RegIdx
, ParentVNI
->id
));
1153 if (VNInfo
*VNI
= VFP
.getPointer()) {
1154 LLVM_DEBUG(dbgs() << ':' << VNI
->id
);
1155 LI
.addSegment(LiveInterval::Segment(Start
, End
, VNI
));
1160 // Skip values with forced recomputation.
1162 LLVM_DEBUG(dbgs() << "(recalc)");
1168 LiveRangeCalc
&LRC
= getLRCalc(RegIdx
);
1170 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
1171 // so the live range is accurate. Add live-in blocks in [Start;End) to the
1173 MachineFunction::iterator MBB
= LIS
.getMBBFromIndex(Start
)->getIterator();
1174 SlotIndex BlockStart
, BlockEnd
;
1175 std::tie(BlockStart
, BlockEnd
) = LIS
.getSlotIndexes()->getMBBRange(&*MBB
);
1177 // The first block may be live-in, or it may have its own def.
1178 if (Start
!= BlockStart
) {
1179 VNInfo
*VNI
= LI
.extendInBlock(BlockStart
, std::min(BlockEnd
, End
));
1180 assert(VNI
&& "Missing def for complex mapped value");
1181 LLVM_DEBUG(dbgs() << ':' << VNI
->id
<< "*" << printMBBReference(*MBB
));
1182 // MBB has its own def. Is it also live-out?
1183 if (BlockEnd
<= End
)
1184 LRC
.setLiveOutValue(&*MBB
, VNI
);
1186 // Skip to the next block for live-in.
1188 BlockStart
= BlockEnd
;
1191 // Handle the live-in blocks covered by [Start;End).
1192 assert(Start
<= BlockStart
&& "Expected live-in block");
1193 while (BlockStart
< End
) {
1194 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB
));
1195 BlockEnd
= LIS
.getMBBEndIdx(&*MBB
);
1196 if (BlockStart
== ParentVNI
->def
) {
1197 // This block has the def of a parent PHI, so it isn't live-in.
1198 assert(ParentVNI
->isPHIDef() && "Non-phi defined at block start?");
1199 VNInfo
*VNI
= LI
.extendInBlock(BlockStart
, std::min(BlockEnd
, End
));
1200 assert(VNI
&& "Missing def for complex mapped parent PHI");
1201 if (End
>= BlockEnd
)
1202 LRC
.setLiveOutValue(&*MBB
, VNI
); // Live-out as well.
1204 // This block needs a live-in value. The last block covered may not
1207 LRC
.addLiveInBlock(LI
, MDT
[&*MBB
], End
);
1209 // Live-through, and we don't know the value.
1210 LRC
.addLiveInBlock(LI
, MDT
[&*MBB
]);
1211 LRC
.setLiveOutValue(&*MBB
, nullptr);
1214 BlockStart
= BlockEnd
;
1218 } while (Start
!= S
.end
);
1219 LLVM_DEBUG(dbgs() << '\n');
1222 LRCalc
[0].calculateValues();
1224 LRCalc
[1].calculateValues();
1229 static bool removeDeadSegment(SlotIndex Def
, LiveRange
&LR
) {
1230 const LiveRange::Segment
*Seg
= LR
.getSegmentContaining(Def
);
1233 if (Seg
->end
!= Def
.getDeadSlot())
1235 // This is a dead PHI. Remove it.
1236 LR
.removeSegment(*Seg
, true);
1240 void SplitEditor::extendPHIRange(MachineBasicBlock
&B
, LiveRangeCalc
&LRC
,
1241 LiveRange
&LR
, LaneBitmask LM
,
1242 ArrayRef
<SlotIndex
> Undefs
) {
1243 for (MachineBasicBlock
*P
: B
.predecessors()) {
1244 SlotIndex End
= LIS
.getMBBEndIdx(P
);
1245 SlotIndex LastUse
= End
.getPrevSlot();
1246 // The predecessor may not have a live-out value. That is OK, like an
1247 // undef PHI operand.
1248 LiveInterval
&PLI
= Edit
->getParent();
1249 // Need the cast because the inputs to ?: would otherwise be deemed
1250 // "incompatible": SubRange vs LiveInterval.
1251 LiveRange
&PSR
= !LM
.all() ? getSubRangeForMask(LM
, PLI
)
1252 : static_cast<LiveRange
&>(PLI
);
1253 if (PSR
.liveAt(LastUse
))
1254 LRC
.extend(LR
, End
, /*PhysReg=*/0, Undefs
);
1258 void SplitEditor::extendPHIKillRanges() {
1259 // Extend live ranges to be live-out for successor PHI values.
1261 // Visit each PHI def slot in the parent live interval. If the def is dead,
1262 // remove it. Otherwise, extend the live interval to reach the end indexes
1263 // of all predecessor blocks.
1265 LiveInterval
&ParentLI
= Edit
->getParent();
1266 for (const VNInfo
*V
: ParentLI
.valnos
) {
1267 if (V
->isUnused() || !V
->isPHIDef())
1270 unsigned RegIdx
= RegAssign
.lookup(V
->def
);
1271 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1272 LiveRangeCalc
&LRC
= getLRCalc(RegIdx
);
1273 MachineBasicBlock
&B
= *LIS
.getMBBFromIndex(V
->def
);
1274 if (!removeDeadSegment(V
->def
, LI
))
1275 extendPHIRange(B
, LRC
, LI
, LaneBitmask::getAll(), /*Undefs=*/{});
1278 SmallVector
<SlotIndex
, 4> Undefs
;
1279 LiveRangeCalc SubLRC
;
1281 for (LiveInterval::SubRange
&PS
: ParentLI
.subranges()) {
1282 for (const VNInfo
*V
: PS
.valnos
) {
1283 if (V
->isUnused() || !V
->isPHIDef())
1285 unsigned RegIdx
= RegAssign
.lookup(V
->def
);
1286 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1287 LiveInterval::SubRange
&S
= getSubRangeForMask(PS
.LaneMask
, LI
);
1288 if (removeDeadSegment(V
->def
, S
))
1291 MachineBasicBlock
&B
= *LIS
.getMBBFromIndex(V
->def
);
1292 SubLRC
.reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
1293 &LIS
.getVNInfoAllocator());
1295 LI
.computeSubRangeUndefs(Undefs
, PS
.LaneMask
, MRI
, *LIS
.getSlotIndexes());
1296 extendPHIRange(B
, SubLRC
, S
, PS
.LaneMask
, Undefs
);
1301 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
1302 void SplitEditor::rewriteAssigned(bool ExtendRanges
) {
1304 ExtPoint(const MachineOperand
&O
, unsigned R
, SlotIndex N
)
1305 : MO(O
), RegIdx(R
), Next(N
) {}
1312 SmallVector
<ExtPoint
,4> ExtPoints
;
1314 for (MachineRegisterInfo::reg_iterator RI
= MRI
.reg_begin(Edit
->getReg()),
1315 RE
= MRI
.reg_end(); RI
!= RE
;) {
1316 MachineOperand
&MO
= *RI
;
1317 MachineInstr
*MI
= MO
.getParent();
1319 // LiveDebugVariables should have handled all DBG_VALUE instructions.
1320 if (MI
->isDebugValue()) {
1321 LLVM_DEBUG(dbgs() << "Zapping " << *MI
);
1326 // <undef> operands don't really read the register, so it doesn't matter
1327 // which register we choose. When the use operand is tied to a def, we must
1328 // use the same register as the def, so just do that always.
1329 SlotIndex Idx
= LIS
.getInstructionIndex(*MI
);
1330 if (MO
.isDef() || MO
.isUndef())
1331 Idx
= Idx
.getRegSlot(MO
.isEarlyClobber());
1333 // Rewrite to the mapped register at Idx.
1334 unsigned RegIdx
= RegAssign
.lookup(Idx
);
1335 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1337 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI
->getParent())
1338 << '\t' << Idx
<< ':' << RegIdx
<< '\t' << *MI
);
1340 // Extend liveness to Idx if the instruction reads reg.
1341 if (!ExtendRanges
|| MO
.isUndef())
1344 // Skip instructions that don't read Reg.
1346 if (!MO
.getSubReg() && !MO
.isEarlyClobber())
1348 // We may want to extend a live range for a partial redef, or for a use
1349 // tied to an early clobber.
1350 Idx
= Idx
.getPrevSlot();
1351 if (!Edit
->getParent().liveAt(Idx
))
1354 Idx
= Idx
.getRegSlot(true);
1356 SlotIndex Next
= Idx
.getNextSlot();
1357 if (LI
.hasSubRanges()) {
1358 // We have to delay extending subranges until we have seen all operands
1359 // defining the register. This is because a <def,read-undef> operand
1360 // will create an "undef" point, and we cannot extend any subranges
1361 // until all of them have been accounted for.
1363 ExtPoints
.push_back(ExtPoint(MO
, RegIdx
, Next
));
1365 LiveRangeCalc
&LRC
= getLRCalc(RegIdx
);
1366 LRC
.extend(LI
, Next
, 0, ArrayRef
<SlotIndex
>());
1370 for (ExtPoint
&EP
: ExtPoints
) {
1371 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(EP
.RegIdx
));
1372 assert(LI
.hasSubRanges());
1374 LiveRangeCalc SubLRC
;
1375 unsigned Reg
= EP
.MO
.getReg(), Sub
= EP
.MO
.getSubReg();
1376 LaneBitmask LM
= Sub
!= 0 ? TRI
.getSubRegIndexLaneMask(Sub
)
1377 : MRI
.getMaxLaneMaskForVReg(Reg
);
1378 for (LiveInterval::SubRange
&S
: LI
.subranges()) {
1379 if ((S
.LaneMask
& LM
).none())
1381 // The problem here can be that the new register may have been created
1382 // for a partially defined original register. For example:
1383 // %0:subreg_hireg<def,read-undef> = ...
1388 SubLRC
.reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
1389 &LIS
.getVNInfoAllocator());
1390 SmallVector
<SlotIndex
, 4> Undefs
;
1391 LI
.computeSubRangeUndefs(Undefs
, S
.LaneMask
, MRI
, *LIS
.getSlotIndexes());
1392 SubLRC
.extend(S
, EP
.Next
, 0, Undefs
);
1396 for (unsigned R
: *Edit
) {
1397 LiveInterval
&LI
= LIS
.getInterval(R
);
1398 if (!LI
.hasSubRanges())
1401 LI
.removeEmptySubRanges();
1402 LIS
.constructMainRangeFromSubranges(LI
);
1406 void SplitEditor::deleteRematVictims() {
1407 SmallVector
<MachineInstr
*, 8> Dead
;
1408 for (LiveRangeEdit::iterator I
= Edit
->begin(), E
= Edit
->end(); I
!= E
; ++I
){
1409 LiveInterval
*LI
= &LIS
.getInterval(*I
);
1410 for (const LiveRange::Segment
&S
: LI
->segments
) {
1411 // Dead defs end at the dead slot.
1412 if (S
.end
!= S
.valno
->def
.getDeadSlot())
1414 if (S
.valno
->isPHIDef())
1416 MachineInstr
*MI
= LIS
.getInstructionFromIndex(S
.valno
->def
);
1417 assert(MI
&& "Missing instruction for dead def");
1418 MI
->addRegisterDead(LI
->reg
, &TRI
);
1420 if (!MI
->allDefsAreDead())
1423 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI
);
1431 Edit
->eliminateDeadDefs(Dead
, None
, &AA
);
1434 void SplitEditor::forceRecomputeVNI(const VNInfo
&ParentVNI
) {
1435 // Fast-path for common case.
1436 if (!ParentVNI
.isPHIDef()) {
1437 for (unsigned I
= 0, E
= Edit
->size(); I
!= E
; ++I
)
1438 forceRecompute(I
, ParentVNI
);
1442 // Trace value through phis.
1443 SmallPtrSet
<const VNInfo
*, 8> Visited
; ///< whether VNI was/is in worklist.
1444 SmallVector
<const VNInfo
*, 4> WorkList
;
1445 Visited
.insert(&ParentVNI
);
1446 WorkList
.push_back(&ParentVNI
);
1448 const LiveInterval
&ParentLI
= Edit
->getParent();
1449 const SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
1451 const VNInfo
&VNI
= *WorkList
.back();
1452 WorkList
.pop_back();
1453 for (unsigned I
= 0, E
= Edit
->size(); I
!= E
; ++I
)
1454 forceRecompute(I
, VNI
);
1455 if (!VNI
.isPHIDef())
1458 MachineBasicBlock
&MBB
= *Indexes
.getMBBFromIndex(VNI
.def
);
1459 for (const MachineBasicBlock
*Pred
: MBB
.predecessors()) {
1460 SlotIndex PredEnd
= Indexes
.getMBBEndIdx(Pred
);
1461 VNInfo
*PredVNI
= ParentLI
.getVNInfoBefore(PredEnd
);
1462 assert(PredVNI
&& "Value available in PhiVNI predecessor");
1463 if (Visited
.insert(PredVNI
).second
)
1464 WorkList
.push_back(PredVNI
);
1466 } while(!WorkList
.empty());
1469 void SplitEditor::finish(SmallVectorImpl
<unsigned> *LRMap
) {
1472 // At this point, the live intervals in Edit contain VNInfos corresponding to
1473 // the inserted copies.
1475 // Add the original defs from the parent interval.
1476 for (const VNInfo
*ParentVNI
: Edit
->getParent().valnos
) {
1477 if (ParentVNI
->isUnused())
1479 unsigned RegIdx
= RegAssign
.lookup(ParentVNI
->def
);
1480 defValue(RegIdx
, ParentVNI
, ParentVNI
->def
, true);
1482 // Force rematted values to be recomputed everywhere.
1483 // The new live ranges may be truncated.
1484 if (Edit
->didRematerialize(ParentVNI
))
1485 forceRecomputeVNI(*ParentVNI
);
1488 // Hoist back-copies to the complement interval when in spill mode.
1489 switch (SpillMode
) {
1491 // Leave all back-copies as is.
1495 // hoistCopies will behave differently between size and speed.
1499 // Transfer the simply mapped values, check if any are skipped.
1500 bool Skipped
= transferValues();
1502 // Rewrite virtual registers, possibly extending ranges.
1503 rewriteAssigned(Skipped
);
1506 extendPHIKillRanges();
1510 // Delete defs that were rematted everywhere.
1512 deleteRematVictims();
1514 // Get rid of unused values and set phi-kill flags.
1515 for (unsigned Reg
: *Edit
) {
1516 LiveInterval
&LI
= LIS
.getInterval(Reg
);
1517 LI
.removeEmptySubRanges();
1518 LI
.RenumberValues();
1521 // Provide a reverse mapping from original indices to Edit ranges.
1524 for (unsigned i
= 0, e
= Edit
->size(); i
!= e
; ++i
)
1525 LRMap
->push_back(i
);
1528 // Now check if any registers were separated into multiple components.
1529 ConnectedVNInfoEqClasses
ConEQ(LIS
);
1530 for (unsigned i
= 0, e
= Edit
->size(); i
!= e
; ++i
) {
1531 // Don't use iterators, they are invalidated by create() below.
1532 unsigned VReg
= Edit
->get(i
);
1533 LiveInterval
&LI
= LIS
.getInterval(VReg
);
1534 SmallVector
<LiveInterval
*, 8> SplitLIs
;
1535 LIS
.splitSeparateComponents(LI
, SplitLIs
);
1536 unsigned Original
= VRM
.getOriginal(VReg
);
1537 for (LiveInterval
*SplitLI
: SplitLIs
)
1538 VRM
.setIsSplitFromReg(SplitLI
->reg
, Original
);
1540 // The new intervals all map back to i.
1542 LRMap
->resize(Edit
->size(), i
);
1545 // Calculate spill weight and allocation hints for new intervals.
1546 Edit
->calculateRegClassAndHint(VRM
.getMachineFunction(), SA
.Loops
, MBFI
);
1548 assert(!LRMap
|| LRMap
->size() == Edit
->size());
1551 //===----------------------------------------------------------------------===//
1552 // Single Block Splitting
1553 //===----------------------------------------------------------------------===//
1555 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo
&BI
,
1556 bool SingleInstrs
) const {
1557 // Always split for multiple instructions.
1558 if (!BI
.isOneInstr())
1560 // Don't split for single instructions unless explicitly requested.
1563 // Splitting a live-through range always makes progress.
1564 if (BI
.LiveIn
&& BI
.LiveOut
)
1566 // No point in isolating a copy. It has no register class constraints.
1567 if (LIS
.getInstructionFromIndex(BI
.FirstInstr
)->isCopyLike())
1569 // Finally, don't isolate an end point that was created by earlier splits.
1570 return isOriginalEndpoint(BI
.FirstInstr
);
1573 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo
&BI
) {
1575 SlotIndex LastSplitPoint
= SA
.getLastSplitPoint(BI
.MBB
->getNumber());
1576 SlotIndex SegStart
= enterIntvBefore(std::min(BI
.FirstInstr
,
1578 if (!BI
.LiveOut
|| BI
.LastInstr
< LastSplitPoint
) {
1579 useIntv(SegStart
, leaveIntvAfter(BI
.LastInstr
));
1581 // The last use is after the last valid split point.
1582 SlotIndex SegStop
= leaveIntvBefore(LastSplitPoint
);
1583 useIntv(SegStart
, SegStop
);
1584 overlapIntv(SegStop
, BI
.LastInstr
);
1588 //===----------------------------------------------------------------------===//
1589 // Global Live Range Splitting Support
1590 //===----------------------------------------------------------------------===//
1592 // These methods support a method of global live range splitting that uses a
1593 // global algorithm to decide intervals for CFG edges. They will insert split
1594 // points and color intervals in basic blocks while avoiding interference.
1596 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1597 // are on the stack.
1599 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum
,
1600 unsigned IntvIn
, SlotIndex LeaveBefore
,
1601 unsigned IntvOut
, SlotIndex EnterAfter
){
1602 SlotIndex Start
, Stop
;
1603 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(MBBNum
);
1605 LLVM_DEBUG(dbgs() << "%bb." << MBBNum
<< " [" << Start
<< ';' << Stop
1606 << ") intf " << LeaveBefore
<< '-' << EnterAfter
1607 << ", live-through " << IntvIn
<< " -> " << IntvOut
);
1609 assert((IntvIn
|| IntvOut
) && "Use splitSingleBlock for isolated blocks");
1611 assert((!LeaveBefore
|| LeaveBefore
< Stop
) && "Interference after block");
1612 assert((!IntvIn
|| !LeaveBefore
|| LeaveBefore
> Start
) && "Impossible intf");
1613 assert((!EnterAfter
|| EnterAfter
>= Start
) && "Interference before block");
1615 MachineBasicBlock
*MBB
= VRM
.getMachineFunction().getBlockNumbered(MBBNum
);
1618 LLVM_DEBUG(dbgs() << ", spill on entry.\n");
1620 // <<<<<<<<< Possible LeaveBefore interference.
1621 // |-----------| Live through.
1622 // -____________ Spill on entry.
1625 SlotIndex Idx
= leaveIntvAtTop(*MBB
);
1626 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1632 LLVM_DEBUG(dbgs() << ", reload on exit.\n");
1634 // >>>>>>> Possible EnterAfter interference.
1635 // |-----------| Live through.
1636 // ___________-- Reload on exit.
1638 selectIntv(IntvOut
);
1639 SlotIndex Idx
= enterIntvAtEnd(*MBB
);
1640 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1645 if (IntvIn
== IntvOut
&& !LeaveBefore
&& !EnterAfter
) {
1646 LLVM_DEBUG(dbgs() << ", straight through.\n");
1648 // |-----------| Live through.
1649 // ------------- Straight through, same intv, no interference.
1651 selectIntv(IntvOut
);
1652 useIntv(Start
, Stop
);
1656 // We cannot legally insert splits after LSP.
1657 SlotIndex LSP
= SA
.getLastSplitPoint(MBBNum
);
1658 assert((!IntvOut
|| !EnterAfter
|| EnterAfter
< LSP
) && "Impossible intf");
1660 if (IntvIn
!= IntvOut
&& (!LeaveBefore
|| !EnterAfter
||
1661 LeaveBefore
.getBaseIndex() > EnterAfter
.getBoundaryIndex())) {
1662 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n");
1664 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1665 // |-----------| Live through.
1666 // ------======= Switch intervals between interference.
1668 selectIntv(IntvOut
);
1670 if (LeaveBefore
&& LeaveBefore
< LSP
) {
1671 Idx
= enterIntvBefore(LeaveBefore
);
1674 Idx
= enterIntvAtEnd(*MBB
);
1677 useIntv(Start
, Idx
);
1678 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1679 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1683 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n");
1685 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1686 // |-----------| Live through.
1687 // ==---------== Switch intervals before/after interference.
1689 assert(LeaveBefore
<= EnterAfter
&& "Missed case");
1691 selectIntv(IntvOut
);
1692 SlotIndex Idx
= enterIntvAfter(EnterAfter
);
1694 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1697 Idx
= leaveIntvBefore(LeaveBefore
);
1698 useIntv(Start
, Idx
);
1699 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1702 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo
&BI
,
1703 unsigned IntvIn
, SlotIndex LeaveBefore
) {
1704 SlotIndex Start
, Stop
;
1705 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
1707 LLVM_DEBUG(dbgs() << printMBBReference(*BI
.MBB
) << " [" << Start
<< ';'
1708 << Stop
<< "), uses " << BI
.FirstInstr
<< '-'
1709 << BI
.LastInstr
<< ", reg-in " << IntvIn
1710 << ", leave before " << LeaveBefore
1711 << (BI
.LiveOut
? ", stack-out" : ", killed in block"));
1713 assert(IntvIn
&& "Must have register in");
1714 assert(BI
.LiveIn
&& "Must be live-in");
1715 assert((!LeaveBefore
|| LeaveBefore
> Start
) && "Bad interference");
1717 if (!BI
.LiveOut
&& (!LeaveBefore
|| LeaveBefore
>= BI
.LastInstr
)) {
1718 LLVM_DEBUG(dbgs() << " before interference.\n");
1720 // <<< Interference after kill.
1721 // |---o---x | Killed in block.
1722 // ========= Use IntvIn everywhere.
1725 useIntv(Start
, BI
.LastInstr
);
1729 SlotIndex LSP
= SA
.getLastSplitPoint(BI
.MBB
->getNumber());
1731 if (!LeaveBefore
|| LeaveBefore
> BI
.LastInstr
.getBoundaryIndex()) {
1733 // <<< Possible interference after last use.
1734 // |---o---o---| Live-out on stack.
1735 // =========____ Leave IntvIn after last use.
1737 // < Interference after last use.
1738 // |---o---o--o| Live-out on stack, late last use.
1739 // ============ Copy to stack after LSP, overlap IntvIn.
1740 // \_____ Stack interval is live-out.
1742 if (BI
.LastInstr
< LSP
) {
1743 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n");
1745 SlotIndex Idx
= leaveIntvAfter(BI
.LastInstr
);
1746 useIntv(Start
, Idx
);
1747 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1749 LLVM_DEBUG(dbgs() << ", spill before last split point.\n");
1751 SlotIndex Idx
= leaveIntvBefore(LSP
);
1752 overlapIntv(Idx
, BI
.LastInstr
);
1753 useIntv(Start
, Idx
);
1754 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1759 // The interference is overlapping somewhere we wanted to use IntvIn. That
1760 // means we need to create a local interval that can be allocated a
1761 // different register.
1762 unsigned LocalIntv
= openIntv();
1764 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv
<< ".\n");
1766 if (!BI
.LiveOut
|| BI
.LastInstr
< LSP
) {
1768 // <<<<<<< Interference overlapping uses.
1769 // |---o---o---| Live-out on stack.
1770 // =====----____ Leave IntvIn before interference, then spill.
1772 SlotIndex To
= leaveIntvAfter(BI
.LastInstr
);
1773 SlotIndex From
= enterIntvBefore(LeaveBefore
);
1776 useIntv(Start
, From
);
1777 assert((!LeaveBefore
|| From
<= LeaveBefore
) && "Interference");
1781 // <<<<<<< Interference overlapping uses.
1782 // |---o---o--o| Live-out on stack, late last use.
1783 // =====------- Copy to stack before LSP, overlap LocalIntv.
1784 // \_____ Stack interval is live-out.
1786 SlotIndex To
= leaveIntvBefore(LSP
);
1787 overlapIntv(To
, BI
.LastInstr
);
1788 SlotIndex From
= enterIntvBefore(std::min(To
, LeaveBefore
));
1791 useIntv(Start
, From
);
1792 assert((!LeaveBefore
|| From
<= LeaveBefore
) && "Interference");
1795 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo
&BI
,
1796 unsigned IntvOut
, SlotIndex EnterAfter
) {
1797 SlotIndex Start
, Stop
;
1798 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
1800 LLVM_DEBUG(dbgs() << printMBBReference(*BI
.MBB
) << " [" << Start
<< ';'
1801 << Stop
<< "), uses " << BI
.FirstInstr
<< '-'
1802 << BI
.LastInstr
<< ", reg-out " << IntvOut
1803 << ", enter after " << EnterAfter
1804 << (BI
.LiveIn
? ", stack-in" : ", defined in block"));
1806 SlotIndex LSP
= SA
.getLastSplitPoint(BI
.MBB
->getNumber());
1808 assert(IntvOut
&& "Must have register out");
1809 assert(BI
.LiveOut
&& "Must be live-out");
1810 assert((!EnterAfter
|| EnterAfter
< LSP
) && "Bad interference");
1812 if (!BI
.LiveIn
&& (!EnterAfter
|| EnterAfter
<= BI
.FirstInstr
)) {
1813 LLVM_DEBUG(dbgs() << " after interference.\n");
1815 // >>>> Interference before def.
1816 // | o---o---| Defined in block.
1817 // ========= Use IntvOut everywhere.
1819 selectIntv(IntvOut
);
1820 useIntv(BI
.FirstInstr
, Stop
);
1824 if (!EnterAfter
|| EnterAfter
< BI
.FirstInstr
.getBaseIndex()) {
1825 LLVM_DEBUG(dbgs() << ", reload after interference.\n");
1827 // >>>> Interference before def.
1828 // |---o---o---| Live-through, stack-in.
1829 // ____========= Enter IntvOut before first use.
1831 selectIntv(IntvOut
);
1832 SlotIndex Idx
= enterIntvBefore(std::min(LSP
, BI
.FirstInstr
));
1834 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1838 // The interference is overlapping somewhere we wanted to use IntvOut. That
1839 // means we need to create a local interval that can be allocated a
1840 // different register.
1841 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n");
1843 // >>>>>>> Interference overlapping uses.
1844 // |---o---o---| Live-through, stack-in.
1845 // ____---====== Create local interval for interference range.
1847 selectIntv(IntvOut
);
1848 SlotIndex Idx
= enterIntvAfter(EnterAfter
);
1850 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1853 SlotIndex From
= enterIntvBefore(std::min(Idx
, BI
.FirstInstr
));