1//===- SplitKit.cpp - Toolkit for splitting live ranges -------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the SplitAnalysis class as well as mutator functions for
10// live range splitting.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SplitKit.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/CodeGen/LiveRangeEdit.h"
18#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
19#include "llvm/CodeGen/MachineDominators.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineLoopInfo.h"
23#include "llvm/CodeGen/MachineOperand.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/TargetInstrInfo.h"
26#include "llvm/CodeGen/TargetOpcodes.h"
27#include "llvm/CodeGen/TargetRegisterInfo.h"
28#include "llvm/CodeGen/TargetSubtargetInfo.h"
29#include "llvm/CodeGen/VirtRegMap.h"
30#include "llvm/Config/llvm-config.h"
31#include "llvm/IR/DebugLoc.h"
32#include "llvm/Support/Allocator.h"
33#include "llvm/Support/BlockFrequency.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
37#include <algorithm>
38#include <cassert>
39#include <iterator>
40#include <limits>
41#include <tuple>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "regalloc"
46
47static cl::opt<bool>
48 EnableLoopIVHeuristic("enable-split-loopiv-heuristic",
49 cl::desc("Enable loop iv regalloc heuristic"),
50 cl::init(Val: true));
51
52STATISTIC(NumFinished, "Number of splits finished");
53STATISTIC(NumSimple, "Number of splits that were simple");
54STATISTIC(NumCopies, "Number of copies inserted for splitting");
55STATISTIC(NumRemats, "Number of rematerialized defs for splitting");
56
57//===----------------------------------------------------------------------===//
58// Last Insert Point Analysis
59//===----------------------------------------------------------------------===//
60
61InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis,
62 unsigned BBNum)
63 : LIS(lis), LastInsertPoint(BBNum) {}
64
65SlotIndex
66InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI,
67 const MachineBasicBlock &MBB) {
68 unsigned Num = MBB.getNumber();
69 std::pair<SlotIndex, SlotIndex> &LIP = LastInsertPoint[Num];
70 SlotIndex MBBEnd = LIS.getMBBEndIdx(mbb: &MBB);
71
72 SmallVector<const MachineBasicBlock *, 1> ExceptionalSuccessors;
73 bool EHPadSuccessor = false;
74 for (const MachineBasicBlock *SMBB : MBB.successors()) {
75 if (SMBB->isEHPad()) {
76 ExceptionalSuccessors.push_back(Elt: SMBB);
77 EHPadSuccessor = true;
78 } else if (SMBB->isInlineAsmBrIndirectTarget())
79 ExceptionalSuccessors.push_back(Elt: SMBB);
80 }
81
82 // Compute insert points on the first call. The pair is independent of the
83 // current live interval.
84 if (!LIP.first.isValid()) {
85 MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator();
86 if (FirstTerm == MBB.end())
87 LIP.first = MBBEnd;
88 else
89 LIP.first = LIS.getInstructionIndex(Instr: *FirstTerm);
90
91 // If there is a landing pad or inlineasm_br successor, also find the
92 // instruction. If there is no such instruction, we don't need to do
93 // anything special. We assume there cannot be multiple instructions that
94 // are Calls with EHPad successors or INLINEASM_BR in a block. Further, we
95 // assume that if there are any, they will be after any other call
96 // instructions in the block.
97 if (ExceptionalSuccessors.empty())
98 return LIP.first;
99 for (const MachineInstr &MI : llvm::reverse(C: MBB)) {
100 if ((EHPadSuccessor && MI.isCall()) ||
101 MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
102 LIP.second = LIS.getInstructionIndex(Instr: MI);
103 break;
104 }
105 }
106 }
107
108 // If CurLI is live into a landing pad successor, move the last insert point
109 // back to the call that may throw.
110 if (!LIP.second)
111 return LIP.first;
112
113 if (none_of(Range&: ExceptionalSuccessors, P: [&](const MachineBasicBlock *EHPad) {
114 return LIS.isLiveInToMBB(LR: CurLI, mbb: EHPad);
115 }))
116 return LIP.first;
117
118 // Find the value leaving MBB.
119 const VNInfo *VNI = CurLI.getVNInfoBefore(Idx: MBBEnd);
120 if (!VNI)
121 return LIP.first;
122
123 // The def of statepoint instruction is a gc relocation and it should be alive
124 // in landing pad. So we cannot split interval after statepoint instruction.
125 if (SlotIndex::isSameInstr(A: VNI->def, B: LIP.second))
126 if (auto *I = LIS.getInstructionFromIndex(index: LIP.second))
127 if (I->getOpcode() == TargetOpcode::STATEPOINT)
128 return LIP.second;
129
130 // If the value leaving MBB was defined after the call in MBB, it can't
131 // really be live-in to the landing pad. This can happen if the landing pad
132 // has a PHI, and this register is undef on the exceptional edge.
133 if (!SlotIndex::isEarlierInstr(A: VNI->def, B: LIP.second) && VNI->def < MBBEnd)
134 return LIP.first;
135
136 // Value is properly live-in to the landing pad.
137 // Only allow inserts before the call.
138 return LIP.second;
139}
140
141MachineBasicBlock::iterator
142InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI,
143 MachineBasicBlock &MBB) {
144 SlotIndex LIP = getLastInsertPoint(CurLI, MBB);
145 if (LIP == LIS.getMBBEndIdx(mbb: &MBB))
146 return MBB.end();
147 return LIS.getInstructionFromIndex(index: LIP);
148}
149
150//===----------------------------------------------------------------------===//
151// Split Analysis
152//===----------------------------------------------------------------------===//
153
154SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
155 const MachineLoopInfo &mli)
156 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
157 TII(*MF.getSubtarget().getInstrInfo()), IPA(lis, MF.getNumBlockIDs()) {}
158
159void SplitAnalysis::clear() {
160 UseSlots.clear();
161 UseBlocks.clear();
162 ThroughBlocks.clear();
163 CurLI = nullptr;
164}
165
166/// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
167void SplitAnalysis::analyzeUses() {
168 assert(UseSlots.empty() && "Call clear first");
169
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(Elt: VNI->def);
175
176 // Get use slots form the use-def chain.
177 const MachineRegisterInfo &MRI = MF.getRegInfo();
178 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg: CurLI->reg()))
179 if (!MO.isUndef())
180 UseSlots.push_back(Elt: LIS.getInstructionIndex(Instr: *MO.getParent()).getRegSlot());
181
182 array_pod_sort(Start: UseSlots.begin(), End: UseSlots.end());
183
184 // Remove duplicates, keeping the smaller slot for each instruction.
185 // That is what we want for early clobbers.
186 UseSlots.erase(CS: llvm::unique(R&: UseSlots, P: SlotIndex::isSameInstr),
187 CE: UseSlots.end());
188
189 // Compute per-live block info.
190 calcLiveBlockInfo();
191
192 LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots.size() << " instrs in "
193 << UseBlocks.size() << " blocks, through "
194 << NumThroughBlocks << " blocks.\n");
195}
196
197/// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
198/// where CurLI is live.
199void SplitAnalysis::calcLiveBlockInfo() {
200 ThroughBlocks.resize(N: MF.getNumBlockIDs());
201 NumThroughBlocks = NumGapBlocks = 0;
202 if (CurLI->empty())
203 return;
204
205 LiveInterval::const_iterator LVI = CurLI->begin();
206 LiveInterval::const_iterator LVE = CurLI->end();
207
208 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
209 UseI = UseSlots.begin();
210 UseE = UseSlots.end();
211
212 // Loop over basic blocks where CurLI is live.
213 MachineFunction::iterator MFI =
214 LIS.getMBBFromIndex(index: LVI->start)->getIterator();
215 while (true) {
216 BlockInfo BI;
217 BI.MBB = &*MFI;
218 SlotIndex Start, Stop;
219 std::tie(args&: Start, args&: Stop) = LIS.getSlotIndexes()->getMBBRange(MBB: BI.MBB);
220
221 // If the block contains no uses, the range must be live through. At one
222 // point, RegisterCoalescer could create dangling ranges that ended
223 // mid-block.
224 if (UseI == UseE || *UseI >= Stop) {
225 ++NumThroughBlocks;
226 ThroughBlocks.set(BI.MBB->getNumber());
227 // The range shouldn't end mid-block if there are no uses. This shouldn't
228 // happen.
229 assert(LVI->end >= Stop && "range ends mid block with no uses");
230 } else {
231 // This block has uses. Find the first and last uses in the block.
232 BI.FirstInstr = *UseI;
233 assert(BI.FirstInstr >= Start);
234 do ++UseI;
235 while (UseI != UseE && *UseI < Stop);
236 BI.LastInstr = UseI[-1];
237 assert(BI.LastInstr < Stop);
238
239 // LVI is the first live segment overlapping MBB.
240 BI.LiveIn = LVI->start <= Start;
241
242 // When not live in, the first use should be a def.
243 if (!BI.LiveIn) {
244 assert(LVI->start == LVI->valno->def && "Dangling Segment start");
245 assert(LVI->start == BI.FirstInstr && "First instr should be a def");
246 BI.FirstDef = BI.FirstInstr;
247 }
248
249 // Look for gaps in the live range.
250 BI.LiveOut = true;
251 while (LVI->end < Stop) {
252 SlotIndex LastStop = LVI->end;
253 if (++LVI == LVE || LVI->start >= Stop) {
254 BI.LiveOut = false;
255 BI.LastInstr = LastStop;
256 break;
257 }
258
259 if (LastStop < LVI->start) {
260 // There is a gap in the live range. Create duplicate entries for the
261 // live-in snippet and the live-out snippet.
262 ++NumGapBlocks;
263
264 // Push the Live-in part.
265 BI.LiveOut = false;
266 UseBlocks.push_back(Elt: BI);
267 UseBlocks.back().LastInstr = LastStop;
268
269 // Set up BI for the live-out part.
270 BI.LiveIn = false;
271 BI.LiveOut = true;
272 BI.FirstInstr = BI.FirstDef = LVI->start;
273 }
274
275 // A Segment that starts in the middle of the block must be a def.
276 assert(LVI->start == LVI->valno->def && "Dangling Segment start");
277 if (!BI.FirstDef)
278 BI.FirstDef = LVI->start;
279 }
280
281 UseBlocks.push_back(Elt: BI);
282
283 // LVI is now at LVE or LVI->end >= Stop.
284 if (LVI == LVE)
285 break;
286 }
287
288 // Live segment ends exactly at Stop. Move to the next segment.
289 if (LVI->end == Stop && ++LVI == LVE)
290 break;
291
292 // Pick the next basic block.
293 if (LVI->start < Stop)
294 ++MFI;
295 else
296 MFI = LIS.getMBBFromIndex(index: LVI->start)->getIterator();
297 }
298
299 LooksLikeLoopIV = EnableLoopIVHeuristic && UseBlocks.size() == 2 &&
300 any_of(Range&: UseBlocks, P: [this](BlockInfo &BI) {
301 MachineLoop *L = Loops.getLoopFor(BB: BI.MBB);
302 return BI.LiveIn && BI.LiveOut && BI.FirstDef && L &&
303 L->isLoopLatch(BB: BI.MBB);
304 });
305
306 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
307}
308
309unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
310 if (cli->empty())
311 return 0;
312 LiveInterval *li = const_cast<LiveInterval*>(cli);
313 LiveInterval::iterator LVI = li->begin();
314 LiveInterval::iterator LVE = li->end();
315 unsigned Count = 0;
316
317 // Loop over basic blocks where li is live.
318 MachineFunction::const_iterator MFI =
319 LIS.getMBBFromIndex(index: LVI->start)->getIterator();
320 SlotIndex Stop = LIS.getMBBEndIdx(mbb: &*MFI);
321 while (true) {
322 ++Count;
323 LVI = li->advanceTo(I: LVI, Pos: Stop);
324 if (LVI == LVE)
325 return Count;
326 do {
327 ++MFI;
328 Stop = LIS.getMBBEndIdx(mbb: &*MFI);
329 } while (Stop <= LVI->start);
330 }
331}
332
333bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
334 Register OrigReg = VRM.getOriginal(VirtReg: CurLI->reg());
335 const LiveInterval &Orig = LIS.getInterval(Reg: OrigReg);
336 assert(!Orig.empty() && "Splitting empty interval?");
337 LiveInterval::const_iterator I = Orig.find(Pos: Idx);
338
339 // Range containing Idx should begin at Idx.
340 if (I != Orig.end() && I->start <= Idx)
341 return I->start == Idx;
342
343 // Range does not contain Idx, previous must end at Idx.
344 return I != Orig.begin() && (--I)->end == Idx;
345}
346
347void SplitAnalysis::analyze(const LiveInterval *li) {
348 clear();
349 CurLI = li;
350 analyzeUses();
351}
352
353//===----------------------------------------------------------------------===//
354// Split Editor
355//===----------------------------------------------------------------------===//
356
357/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
358SplitEditor::SplitEditor(SplitAnalysis &SA, LiveIntervals &LIS, VirtRegMap &VRM,
359 MachineDominatorTree &MDT,
360 MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo &VRAI)
361 : SA(SA), LIS(LIS), VRM(VRM), MRI(VRM.getMachineFunction().getRegInfo()),
362 MDT(MDT), TII(*VRM.getMachineFunction().getSubtarget().getInstrInfo()),
363 TRI(*VRM.getMachineFunction().getSubtarget().getRegisterInfo()),
364 MBFI(MBFI), VRAI(VRAI), RegAssign(Allocator) {}
365
366void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
367 Edit = &LRE;
368 SpillMode = SM;
369 OpenIdx = 0;
370 RegAssign.clear();
371 Values.clear();
372
373 // Reset the LiveIntervalCalc instances needed for this spill mode.
374 LICalc[0].reset(mf: &VRM.getMachineFunction(), SI: LIS.getSlotIndexes(), MDT: &MDT,
375 VNIA: &LIS.getVNInfoAllocator());
376 if (SpillMode)
377 LICalc[1].reset(mf: &VRM.getMachineFunction(), SI: LIS.getSlotIndexes(), MDT: &MDT,
378 VNIA: &LIS.getVNInfoAllocator());
379}
380
381#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
382LLVM_DUMP_METHOD void SplitEditor::dump() const {
383 if (RegAssign.empty()) {
384 dbgs() << " empty\n";
385 return;
386 }
387
388 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
389 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
390 dbgs() << '\n';
391}
392#endif
393
394/// Find a subrange corresponding to the exact lane mask @p LM in the live
395/// interval @p LI. The interval @p LI is assumed to contain such a subrange.
396/// This function is used to find corresponding subranges between the
397/// original interval and the new intervals.
398template <typename T> auto &getSubrangeImpl(LaneBitmask LM, T &LI) {
399 for (auto &S : LI.subranges())
400 if (S.LaneMask == LM)
401 return S;
402 llvm_unreachable("SubRange for this mask not found");
403}
404
405LiveInterval::SubRange &getSubRangeForMaskExact(LaneBitmask LM,
406 LiveInterval &LI) {
407 return getSubrangeImpl(LM, LI);
408}
409
410const LiveInterval::SubRange &getSubRangeForMaskExact(LaneBitmask LM,
411 const LiveInterval &LI) {
412 return getSubrangeImpl(LM, LI);
413}
414
415/// Find a subrange corresponding to the lane mask @p LM, or a superset of it,
416/// in the live interval @p LI.
417/// \return nullptr is such subrange is not found.
418const LiveInterval::SubRange *findSubRangeForMask(LaneBitmask LM,
419 const LiveInterval &LI) {
420 for (const LiveInterval::SubRange &S : LI.subranges())
421 if ((S.LaneMask & LM) == LM)
422 return &S;
423 return nullptr;
424}
425
426LaneBitmask getLiveLaneMaskAt(const LiveInterval &LI, SlotIndex Idx,
427 const MachineRegisterInfo &MRI) {
428 if (!LI.hasSubRanges())
429 return MRI.getMaxLaneMaskForVReg(Reg: LI.reg());
430
431 LaneBitmask LaneMask;
432 for (const LiveInterval::SubRange &S : LI.subranges())
433 if (S.liveAt(index: Idx))
434 LaneMask |= S.LaneMask;
435 return LaneMask;
436}
437
438void SplitEditor::addDeadDef(LiveInterval &LI, VNInfo *VNI, bool Original) {
439 if (!LI.hasSubRanges()) {
440 LI.createDeadDef(VNI);
441 return;
442 }
443
444 SlotIndex Def = VNI->def;
445 if (Original) {
446 // If we are transferring a def from the original interval, make sure
447 // to only update the subranges for which the original subranges had
448 // a def at this location.
449 for (LiveInterval::SubRange &S : LI.subranges()) {
450 const LiveInterval::SubRange *PS =
451 findSubRangeForMask(LM: S.LaneMask, LI: Edit->getParent());
452 if (PS == nullptr)
453 continue;
454 VNInfo *PV = PS->getVNInfoAt(Idx: Def);
455 if (PV != nullptr && PV->def == Def)
456 S.createDeadDef(Def, VNIAlloc&: LIS.getVNInfoAllocator());
457 }
458 } else {
459 // This is a new def: either from rematerialization, or from an inserted
460 // copy. Since rematerialization can regenerate a definition of a sub-
461 // register, we need to check which subranges need to be updated.
462 const MachineInstr *DefMI = LIS.getInstructionFromIndex(index: Def);
463 assert(DefMI != nullptr);
464 LaneBitmask LM;
465 for (const MachineOperand &DefOp : DefMI->defs()) {
466 Register R = DefOp.getReg();
467 if (R != LI.reg())
468 continue;
469 if (unsigned SR = DefOp.getSubReg())
470 LM |= TRI.getSubRegIndexLaneMask(SubIdx: SR);
471 else {
472 LM = MRI.getMaxLaneMaskForVReg(Reg: R);
473 break;
474 }
475 }
476 for (LiveInterval::SubRange &S : LI.subranges())
477 if ((S.LaneMask & LM).any())
478 S.createDeadDef(Def, VNIAlloc&: LIS.getVNInfoAllocator());
479 }
480}
481
482VNInfo *SplitEditor::defValue(unsigned RegIdx,
483 const VNInfo *ParentVNI,
484 SlotIndex Idx,
485 bool Original) {
486 assert(ParentVNI && "Mapping NULL value");
487 assert(Idx.isValid() && "Invalid SlotIndex");
488 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
489 LiveInterval *LI = &LIS.getInterval(Reg: Edit->get(idx: RegIdx));
490
491 // Create a new value.
492 VNInfo *VNI = LI->getNextValue(Def: Idx, VNInfoAllocator&: LIS.getVNInfoAllocator());
493
494 bool Force = LI->hasSubRanges();
495 ValueForcePair FP(Force ? nullptr : VNI, Force);
496 // Use insert for lookup, so we can add missing values with a second lookup.
497 std::pair<ValueMap::iterator, bool> InsP =
498 Values.insert(KV: std::make_pair(x: std::make_pair(x&: RegIdx, y: ParentVNI->id), y&: FP));
499
500 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not
501 // forced. Keep it as a simple def without any liveness.
502 if (!Force && InsP.second)
503 return VNI;
504
505 // If the previous value was a simple mapping, add liveness for it now.
506 if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
507 addDeadDef(LI&: *LI, VNI: OldVNI, Original);
508
509 // No longer a simple mapping. Switch to a complex mapping. If the
510 // interval has subranges, make it a forced mapping.
511 InsP.first->second = ValueForcePair(nullptr, Force);
512 }
513
514 // This is a complex mapping, add liveness for VNI
515 addDeadDef(LI&: *LI, VNI, Original);
516 return VNI;
517}
518
519void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo &ParentVNI) {
520 ValueForcePair &VFP = Values[std::make_pair(x&: RegIdx, y: ParentVNI.id)];
521 VNInfo *VNI = VFP.getPointer();
522
523 // ParentVNI was either unmapped or already complex mapped. Either way, just
524 // set the force bit.
525 if (!VNI) {
526 VFP.setInt(true);
527 return;
528 }
529
530 // This was previously a single mapping. Make sure the old def is represented
531 // by a trivial live range.
532 addDeadDef(LI&: LIS.getInterval(Reg: Edit->get(idx: RegIdx)), VNI, Original: false);
533
534 // Mark as complex mapped, forced.
535 VFP = ValueForcePair(nullptr, true);
536}
537
538SlotIndex SplitEditor::buildSingleSubRegCopy(
539 Register FromReg, Register ToReg, MachineBasicBlock &MBB,
540 MachineBasicBlock::iterator InsertBefore, unsigned SubIdx,
541 LiveInterval &DestLI, bool Late, SlotIndex Def, const MCInstrDesc &Desc) {
542 bool FirstCopy = !Def.isValid();
543 MachineInstr *CopyMI =
544 BuildMI(BB&: MBB, I: InsertBefore, MIMD: DebugLoc(), MCID: Desc)
545 .addReg(RegNo: ToReg,
546 Flags: RegState::Define | getUndefRegState(B: FirstCopy) |
547 getInternalReadRegState(B: !FirstCopy),
548 SubReg: SubIdx)
549 .addReg(RegNo: FromReg, Flags: {}, SubReg: SubIdx);
550
551 CopyMI->setFlag(MachineInstr::LRSplit);
552 SlotIndexes &Indexes = *LIS.getSlotIndexes();
553 if (FirstCopy) {
554 Def = Indexes.insertMachineInstrInMaps(MI&: *CopyMI, Late).getRegSlot();
555 } else {
556 CopyMI->bundleWithPred();
557 }
558 return Def;
559}
560
561SlotIndex SplitEditor::buildCopy(Register FromReg, Register ToReg,
562 LaneBitmask LaneMask, MachineBasicBlock &MBB,
563 MachineBasicBlock::iterator InsertBefore, bool Late, unsigned RegIdx) {
564 const MCInstrDesc &Desc =
565 TII.get(Opcode: TII.getLiveRangeSplitOpcode(Reg: FromReg, MF: *MBB.getParent()));
566 SlotIndexes &Indexes = *LIS.getSlotIndexes();
567 if (LaneMask.all() || LaneMask == MRI.getMaxLaneMaskForVReg(Reg: FromReg)) {
568 // The full vreg is copied.
569 MachineInstr *CopyMI =
570 BuildMI(BB&: MBB, I: InsertBefore, MIMD: DebugLoc(), MCID: Desc, DestReg: ToReg).addReg(RegNo: FromReg);
571 CopyMI->setFlag(MachineInstr::LRSplit);
572 return Indexes.insertMachineInstrInMaps(MI&: *CopyMI, Late).getRegSlot();
573 }
574
575 // Only a subset of lanes needs to be copied. The following is a simple
576 // heuristic to construct a sequence of COPYs. We could add a target
577 // specific callback if this turns out to be suboptimal.
578 LiveInterval &DestLI = LIS.getInterval(Reg: Edit->get(idx: RegIdx));
579
580 // First pass: Try to find a perfectly matching subregister index. If none
581 // exists find the one covering the most lanemask bits.
582 const TargetRegisterClass *RC = MRI.getRegClass(Reg: FromReg);
583 assert(RC == MRI.getRegClass(ToReg) && "Should have same reg class");
584
585 SmallVector<unsigned, 8> SubIndexes;
586
587 // Abort if we cannot possibly implement the COPY with the given indexes.
588 if (!TRI.getCoveringSubRegIndexes(RC, LaneMask, Indexes&: SubIndexes))
589 report_fatal_error(reason: "Impossible to implement partial COPY");
590
591 SlotIndex Def;
592 for (unsigned BestIdx : SubIndexes) {
593 Def = buildSingleSubRegCopy(FromReg, ToReg, MBB, InsertBefore, SubIdx: BestIdx,
594 DestLI, Late, Def, Desc);
595 }
596
597 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
598 DestLI.refineSubRanges(
599 Allocator, LaneMask,
600 Apply: [Def, &Allocator](LiveInterval::SubRange &SR) {
601 SR.createDeadDef(Def, VNIAlloc&: Allocator);
602 },
603 Indexes, TRI);
604
605 return Def;
606}
607
608bool SplitEditor::rematWillIncreaseRestriction(const MachineInstr *DefMI,
609 MachineBasicBlock &MBB,
610 SlotIndex UseIdx) const {
611 const MachineInstr *UseMI = LIS.getInstructionFromIndex(index: UseIdx);
612 if (!UseMI)
613 return false;
614
615 // Currently code assumes rematerialization only happens for a def at 0.
616 const unsigned DefOperandIdx = 0;
617 // We want to compute the static register class constraint for the instruction
618 // def. If it is a smaller subclass than getLargestLegalSuperClass at the use
619 // site, then rematerializing it will increase the constraints.
620 const TargetRegisterClass *DefConstrainRC =
621 DefMI->getRegClassConstraint(OpIdx: DefOperandIdx, TII: &TII, TRI: &TRI);
622 if (!DefConstrainRC)
623 return false;
624
625 const TargetRegisterClass *RC = MRI.getRegClass(Reg: Edit->getReg());
626
627 // We want to find the register class that can be inflated to after the split
628 // occurs in recomputeRegClass
629 const TargetRegisterClass *SuperRC =
630 TRI.getLargestLegalSuperClass(RC, *MBB.getParent());
631
632 Register DefReg = DefMI->getOperand(i: DefOperandIdx).getReg();
633 const TargetRegisterClass *UseConstrainRC =
634 UseMI->getRegClassConstraintEffectForVReg(Reg: DefReg, CurRC: SuperRC, TII: &TII, TRI: &TRI,
635 /*ExploreBundle=*/true);
636 return UseConstrainRC->hasSubClass(RC: DefConstrainRC);
637}
638
639VNInfo *SplitEditor::defFromParent(unsigned RegIdx, const VNInfo *ParentVNI,
640 SlotIndex UseIdx, MachineBasicBlock &MBB,
641 MachineBasicBlock::iterator I) {
642 LiveInterval *LI = &LIS.getInterval(Reg: Edit->get(idx: RegIdx));
643
644 // We may be trying to avoid interference that ends at a deleted instruction,
645 // so always begin RegIdx 0 early and all others late.
646 bool Late = RegIdx != 0;
647
648 // Attempt cheap-as-a-copy rematerialization.
649 Register Original = VRM.getOriginal(VirtReg: Edit->get(idx: RegIdx));
650 LiveInterval &OrigLI = LIS.getInterval(Reg: Original);
651 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx: UseIdx);
652
653 Register Reg = LI->reg();
654 LaneBitmask LaneMask = getLiveLaneMaskAt(LI: Edit->getParent(), Idx: UseIdx, MRI);
655 if (OrigVNI && LaneMask.any()) {
656 LiveRangeEdit::Remat RM(ParentVNI);
657 RM.OrigMI = LIS.getInstructionFromIndex(index: OrigVNI->def);
658 if (RM.OrigMI && TII.isAsCheapAsAMove(MI: *RM.OrigMI) &&
659 Edit->canRematerializeAt(RM, UseIdx)) {
660 if (!rematWillIncreaseRestriction(DefMI: RM.OrigMI, MBB, UseIdx)) {
661 SlotIndex Def = Edit->rematerializeAt(MBB, MI: I, DestReg: Reg, RM, TRI, Late, SubIdx: 0,
662 ReplaceIndexMI: nullptr, UsedLanes: LaneMask);
663 ++NumRemats;
664 // Define the value in Reg.
665 return defValue(RegIdx, ParentVNI, Idx: Def, Original: false);
666 }
667 LLVM_DEBUG(
668 dbgs() << "skipping rematerialize of " << printReg(Reg) << " at "
669 << UseIdx
670 << " since it will increase register class restrictions\n");
671 }
672 }
673
674 SlotIndex Def;
675 if (LaneMask.none()) {
676 const MCInstrDesc &Desc = TII.get(Opcode: TargetOpcode::IMPLICIT_DEF);
677 MachineInstr *ImplicitDef = BuildMI(BB&: MBB, I, MIMD: DebugLoc(), MCID: Desc, DestReg: Reg);
678 SlotIndexes &Indexes = *LIS.getSlotIndexes();
679 Def = Indexes.insertMachineInstrInMaps(MI&: *ImplicitDef, Late).getRegSlot();
680 } else {
681 ++NumCopies;
682 Def = buildCopy(FromReg: Edit->getReg(), ToReg: Reg, LaneMask, MBB, InsertBefore: I, Late, RegIdx);
683 }
684
685 // Define the value in Reg.
686 return defValue(RegIdx, ParentVNI, Idx: Def, Original: false);
687}
688
689/// Create a new virtual register and live interval.
690unsigned SplitEditor::openIntv() {
691 // Create the complement as index 0.
692 if (Edit->empty())
693 Edit->createEmptyInterval();
694
695 // Create the open interval.
696 OpenIdx = Edit->size();
697 Edit->createEmptyInterval();
698 return OpenIdx;
699}
700
701void SplitEditor::selectIntv(unsigned Idx) {
702 assert(Idx != 0 && "Cannot select the complement interval");
703 assert(Idx < Edit->size() && "Can only select previously opened interval");
704 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n');
705 OpenIdx = Idx;
706}
707
708SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
709 assert(OpenIdx && "openIntv not called before enterIntvBefore");
710 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx);
711 Idx = Idx.getBaseIndex();
712 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
713 if (!ParentVNI) {
714 LLVM_DEBUG(dbgs() << ": not live\n");
715 return Idx;
716 }
717 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
718 MachineInstr *MI = LIS.getInstructionFromIndex(index: Idx);
719 assert(MI && "enterIntvBefore called with invalid index");
720
721 VNInfo *VNI = defFromParent(RegIdx: OpenIdx, ParentVNI, UseIdx: Idx, MBB&: *MI->getParent(), I: MI);
722 return VNI->def;
723}
724
725SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
726 assert(OpenIdx && "openIntv not called before enterIntvAfter");
727 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx);
728 Idx = Idx.getBoundaryIndex();
729 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
730 if (!ParentVNI) {
731 LLVM_DEBUG(dbgs() << ": not live\n");
732 return Idx;
733 }
734 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
735 MachineInstr *MI = LIS.getInstructionFromIndex(index: Idx);
736 assert(MI && "enterIntvAfter called with invalid index");
737
738 VNInfo *VNI = defFromParent(RegIdx: OpenIdx, ParentVNI, UseIdx: Idx, MBB&: *MI->getParent(),
739 I: std::next(x: MachineBasicBlock::iterator(MI)));
740 return VNI->def;
741}
742
743SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
744 assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
745 SlotIndex End = LIS.getMBBEndIdx(mbb: &MBB);
746 SlotIndex Last = End.getPrevSlot();
747 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB) << ", "
748 << Last);
749 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: Last);
750 if (!ParentVNI) {
751 LLVM_DEBUG(dbgs() << ": not live\n");
752 return End;
753 }
754 SlotIndex LSP = SA.getLastSplitPoint(BB: &MBB);
755 if (LSP < Last) {
756 // It could be that the use after LSP is a def, and thus the ParentVNI
757 // just selected starts at that def. For this case to exist, the def
758 // must be part of a tied def/use pair (as otherwise we'd have split
759 // distinct live ranges into individual live intervals), and thus we
760 // can insert the def into the VNI of the use and the tied def/use
761 // pair can live in the resulting interval.
762 Last = LSP;
763 ParentVNI = Edit->getParent().getVNInfoAt(Idx: Last);
764 if (!ParentVNI) {
765 // undef use --> undef tied def
766 LLVM_DEBUG(dbgs() << ": tied use not live\n");
767 return End;
768 }
769 }
770
771 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id);
772 VNInfo *VNI = defFromParent(RegIdx: OpenIdx, ParentVNI, UseIdx: Last, MBB,
773 I: SA.getLastSplitPointIter(BB: &MBB));
774 RegAssign.insert(a: VNI->def, b: End, y: OpenIdx);
775 LLVM_DEBUG(dump());
776 return VNI->def;
777}
778
779/// useIntv - indicate that all instructions in MBB should use OpenLI.
780void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
781 useIntv(Start: LIS.getMBBStartIdx(mbb: &MBB), End: LIS.getMBBEndIdx(mbb: &MBB));
782}
783
784void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
785 assert(OpenIdx && "openIntv not called before useIntv");
786 LLVM_DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
787 RegAssign.insert(a: Start, b: End, y: OpenIdx);
788 LLVM_DEBUG(dump());
789}
790
791SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
792 assert(OpenIdx && "openIntv not called before leaveIntvAfter");
793 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx);
794
795 // The interval must be live beyond the instruction at Idx.
796 SlotIndex Boundary = Idx.getBoundaryIndex();
797 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: Boundary);
798 if (!ParentVNI) {
799 LLVM_DEBUG(dbgs() << ": not live\n");
800 return Boundary.getNextSlot();
801 }
802 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
803 MachineInstr *MI = LIS.getInstructionFromIndex(index: Boundary);
804 assert(MI && "No instruction at index");
805
806 // In spill mode, make live ranges as short as possible by inserting the copy
807 // before MI. This is only possible if that instruction doesn't redefine the
808 // value. The inserted COPY is not a kill, and we don't need to recompute
809 // the source live range. The spiller also won't try to hoist this copy.
810 if (SpillMode && !SlotIndex::isSameInstr(A: ParentVNI->def, B: Idx) &&
811 MI->readsVirtualRegister(Reg: Edit->getReg())) {
812 forceRecompute(RegIdx: 0, ParentVNI: *ParentVNI);
813 defFromParent(RegIdx: 0, ParentVNI, UseIdx: Idx, MBB&: *MI->getParent(), I: MI);
814 return Idx;
815 }
816
817 VNInfo *VNI = defFromParent(RegIdx: 0, ParentVNI, UseIdx: Boundary, MBB&: *MI->getParent(),
818 I: std::next(x: MachineBasicBlock::iterator(MI)));
819 return VNI->def;
820}
821
822SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
823 assert(OpenIdx && "openIntv not called before leaveIntvBefore");
824 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx);
825
826 // The interval must be live into the instruction at Idx.
827 Idx = Idx.getBaseIndex();
828 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
829 if (!ParentVNI) {
830 LLVM_DEBUG(dbgs() << ": not live\n");
831 return Idx.getNextSlot();
832 }
833 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
834
835 MachineInstr *MI = LIS.getInstructionFromIndex(index: Idx);
836 assert(MI && "No instruction at index");
837 VNInfo *VNI = defFromParent(RegIdx: 0, ParentVNI, UseIdx: Idx, MBB&: *MI->getParent(), I: MI);
838 return VNI->def;
839}
840
841SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
842 assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
843 SlotIndex Start = LIS.getMBBStartIdx(mbb: &MBB);
844 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB) << ", "
845 << Start);
846
847 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: Start);
848 if (!ParentVNI) {
849 LLVM_DEBUG(dbgs() << ": not live\n");
850 return Start;
851 }
852
853 unsigned RegIdx = 0;
854 Register Reg = LIS.getInterval(Reg: Edit->get(idx: RegIdx)).reg();
855 VNInfo *VNI = defFromParent(RegIdx, ParentVNI, UseIdx: Start, MBB,
856 I: MBB.SkipPHIsLabelsAndDebug(I: MBB.begin(), Reg));
857 RegAssign.insert(a: Start, b: VNI->def, y: OpenIdx);
858 LLVM_DEBUG(dump());
859 return VNI->def;
860}
861
862static bool hasTiedUseOf(MachineInstr &MI, Register Reg) {
863 return any_of(Range: MI.defs(), P: [Reg](const MachineOperand &MO) {
864 return MO.isReg() && MO.isTied() && MO.getReg() == Reg;
865 });
866}
867
868void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
869 assert(OpenIdx && "openIntv not called before overlapIntv");
870 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: Start);
871 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
872 "Parent changes value in extended range");
873 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
874 "Range cannot span basic blocks");
875
876 // The complement interval will be extended as needed by LICalc.extend().
877 if (ParentVNI)
878 forceRecompute(RegIdx: 0, ParentVNI: *ParentVNI);
879
880 // If the last use is tied to a def, we can't mark it as live for the
881 // interval which includes only the use. That would cause the tied pair
882 // to end up in two different intervals.
883 if (auto *MI = LIS.getInstructionFromIndex(index: End))
884 if (hasTiedUseOf(MI&: *MI, Reg: Edit->getReg())) {
885 LLVM_DEBUG(dbgs() << "skip overlap due to tied def at end\n");
886 return;
887 }
888
889 LLVM_DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
890 RegAssign.insert(a: Start, b: End, y: OpenIdx);
891 LLVM_DEBUG(dump());
892}
893
894//===----------------------------------------------------------------------===//
895// Spill modes
896//===----------------------------------------------------------------------===//
897
898void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
899 LiveInterval *LI = &LIS.getInterval(Reg: Edit->get(idx: 0));
900 LLVM_DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
901 RegAssignMap::iterator AssignI;
902 AssignI.setMap(RegAssign);
903
904 for (const VNInfo *C : Copies) {
905 SlotIndex Def = C->def;
906 MachineInstr *MI = LIS.getInstructionFromIndex(index: Def);
907 assert(MI && "No instruction for back-copy");
908
909 MachineBasicBlock *MBB = MI->getParent();
910 MachineBasicBlock::iterator MBBI(MI);
911 bool AtBegin;
912 do AtBegin = MBBI == MBB->begin();
913 while (!AtBegin && (--MBBI)->isDebugOrPseudoInstr());
914
915 LLVM_DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
916 LIS.removeVRegDefAt(LI&: *LI, Pos: Def);
917 LIS.RemoveMachineInstrFromMaps(MI&: *MI);
918 MI->eraseFromParent();
919
920 // Adjust RegAssign if a register assignment is killed at Def. We want to
921 // avoid calculating the live range of the source register if possible.
922 AssignI.find(x: Def.getPrevSlot());
923 if (!AssignI.valid() || AssignI.start() >= Def)
924 continue;
925 // If MI doesn't kill the assigned register, just leave it.
926 if (AssignI.stop() != Def)
927 continue;
928 unsigned RegIdx = AssignI.value();
929 // We could hoist back-copy right after another back-copy. As a result
930 // MMBI points to copy instruction which is actually dead now.
931 // We cannot set its stop to MBBI which will be the same as start and
932 // interval does not support that.
933 SlotIndex Kill =
934 AtBegin ? SlotIndex() : LIS.getInstructionIndex(Instr: *MBBI).getRegSlot();
935 if (AtBegin || !MBBI->readsVirtualRegister(Reg: Edit->getReg()) ||
936 Kill <= AssignI.start()) {
937 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx
938 << '\n');
939 forceRecompute(RegIdx, ParentVNI: *Edit->getParent().getVNInfoAt(Idx: Def));
940 } else {
941 LLVM_DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI);
942 AssignI.setStop(Kill);
943 }
944 }
945}
946
947MachineBasicBlock*
948SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
949 MachineBasicBlock *DefMBB) {
950 if (MBB == DefMBB)
951 return MBB;
952 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
953
954 const MachineLoopInfo &Loops = SA.Loops;
955 const MachineLoop *DefLoop = Loops.getLoopFor(BB: DefMBB);
956 MachineDomTreeNode *DefDomNode = MDT[DefMBB];
957
958 // Best candidate so far.
959 MachineBasicBlock *BestMBB = MBB;
960 unsigned BestDepth = std::numeric_limits<unsigned>::max();
961
962 while (true) {
963 const MachineLoop *Loop = Loops.getLoopFor(BB: MBB);
964
965 // MBB isn't in a loop, it doesn't get any better. All dominators have a
966 // higher frequency by definition.
967 if (!Loop) {
968 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB)
969 << " dominates " << printMBBReference(*MBB)
970 << " at depth 0\n");
971 return MBB;
972 }
973
974 // We'll never be able to exit the DefLoop.
975 if (Loop == DefLoop) {
976 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB)
977 << " dominates " << printMBBReference(*MBB)
978 << " in the same loop\n");
979 return MBB;
980 }
981
982 // Least busy dominator seen so far.
983 unsigned Depth = Loop->getLoopDepth();
984 if (Depth < BestDepth) {
985 BestMBB = MBB;
986 BestDepth = Depth;
987 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB)
988 << " dominates " << printMBBReference(*MBB)
989 << " at depth " << Depth << '\n');
990 }
991
992 // Leave loop by going to the immediate dominator of the loop header.
993 // This is a bigger stride than simply walking up the dominator tree.
994 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
995
996 // Too far up the dominator tree?
997 if (!IDom || !MDT.dominates(A: DefDomNode, B: IDom))
998 return BestMBB;
999
1000 MBB = IDom->getBlock();
1001 }
1002}
1003
1004void SplitEditor::computeRedundantBackCopies(
1005 DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) {
1006 LiveInterval *LI = &LIS.getInterval(Reg: Edit->get(idx: 0));
1007 const LiveInterval *Parent = &Edit->getParent();
1008 SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums());
1009 SmallPtrSet<VNInfo *, 8> DominatedVNIs;
1010
1011 // Aggregate VNIs having the same value as ParentVNI.
1012 for (VNInfo *VNI : LI->valnos) {
1013 if (VNI->isUnused())
1014 continue;
1015 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: VNI->def);
1016 EqualVNs[ParentVNI->id].insert(Ptr: VNI);
1017 }
1018
1019 // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
1020 // redundant VNIs to BackCopies.
1021 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
1022 const VNInfo *ParentVNI = Parent->getValNumInfo(ValNo: i);
1023 if (!NotToHoistSet.count(V: ParentVNI->id))
1024 continue;
1025 SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin();
1026 SmallPtrSetIterator<VNInfo *> It2 = It1;
1027 for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) {
1028 It2 = It1;
1029 for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) {
1030 if (DominatedVNIs.count(Ptr: *It1) || DominatedVNIs.count(Ptr: *It2))
1031 continue;
1032
1033 MachineBasicBlock *MBB1 = LIS.getMBBFromIndex(index: (*It1)->def);
1034 MachineBasicBlock *MBB2 = LIS.getMBBFromIndex(index: (*It2)->def);
1035 if (MBB1 == MBB2) {
1036 DominatedVNIs.insert(Ptr: (*It1)->def < (*It2)->def ? (*It2) : (*It1));
1037 } else if (MDT.dominates(A: MBB1, B: MBB2)) {
1038 DominatedVNIs.insert(Ptr: *It2);
1039 } else if (MDT.dominates(A: MBB2, B: MBB1)) {
1040 DominatedVNIs.insert(Ptr: *It1);
1041 }
1042 }
1043 }
1044 if (!DominatedVNIs.empty()) {
1045 forceRecompute(RegIdx: 0, ParentVNI: *ParentVNI);
1046 append_range(C&: BackCopies, R&: DominatedVNIs);
1047 DominatedVNIs.clear();
1048 }
1049 }
1050}
1051
1052/// For SM_Size mode, find a common dominator for all the back-copies for
1053/// the same ParentVNI and hoist the backcopies to the dominator BB.
1054/// For SM_Speed mode, if the common dominator is hot and it is not beneficial
1055/// to do the hoisting, simply remove the dominated backcopies for the same
1056/// ParentVNI.
1057void SplitEditor::hoistCopies() {
1058 // Get the complement interval, always RegIdx 0.
1059 LiveInterval *LI = &LIS.getInterval(Reg: Edit->get(idx: 0));
1060 const LiveInterval *Parent = &Edit->getParent();
1061
1062 // Track the nearest common dominator for all back-copies for each ParentVNI,
1063 // indexed by ParentVNI->id.
1064 using DomPair = std::pair<MachineBasicBlock *, SlotIndex>;
1065 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
1066 // The total cost of all the back-copies for each ParentVNI.
1067 SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums());
1068 // The ParentVNI->id set for which hoisting back-copies are not beneficial
1069 // for Speed.
1070 DenseSet<unsigned> NotToHoistSet;
1071
1072 // Find the nearest common dominator for parent values with multiple
1073 // back-copies. If a single back-copy dominates, put it in DomPair.second.
1074 for (VNInfo *VNI : LI->valnos) {
1075 if (VNI->isUnused())
1076 continue;
1077 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: VNI->def);
1078 assert(ParentVNI && "Parent not live at complement def");
1079
1080 // Don't hoist remats. The complement is probably going to disappear
1081 // completely anyway.
1082 if (Edit->didRematerialize(ParentVNI))
1083 continue;
1084
1085 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(index: VNI->def);
1086
1087 DomPair &Dom = NearestDom[ParentVNI->id];
1088
1089 // Keep directly defined parent values. This is either a PHI or an
1090 // instruction in the complement range. All other copies of ParentVNI
1091 // should be eliminated.
1092 if (VNI->def == ParentVNI->def) {
1093 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
1094 Dom = DomPair(ValMBB, VNI->def);
1095 continue;
1096 }
1097 // Skip the singly mapped values. There is nothing to gain from hoisting a
1098 // single back-copy.
1099 if (Values.lookup(Val: std::make_pair(x: 0, y&: ParentVNI->id)).getPointer()) {
1100 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
1101 continue;
1102 }
1103
1104 if (!Dom.first) {
1105 // First time we see ParentVNI. VNI dominates itself.
1106 Dom = DomPair(ValMBB, VNI->def);
1107 } else if (Dom.first == ValMBB) {
1108 // Two defs in the same block. Pick the earlier def.
1109 if (!Dom.second.isValid() || VNI->def < Dom.second)
1110 Dom.second = VNI->def;
1111 } else {
1112 // Different basic blocks. Check if one dominates.
1113 MachineBasicBlock *Near =
1114 MDT.findNearestCommonDominator(A: Dom.first, B: ValMBB);
1115 if (Near == ValMBB)
1116 // Def ValMBB dominates.
1117 Dom = DomPair(ValMBB, VNI->def);
1118 else if (Near != Dom.first)
1119 // None dominate. Hoist to common dominator, need new def.
1120 Dom = DomPair(Near, SlotIndex());
1121 Costs[ParentVNI->id] += MBFI.getBlockFreq(MBB: ValMBB);
1122 }
1123
1124 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@'
1125 << VNI->def << " for parent " << ParentVNI->id << '@'
1126 << ParentVNI->def << " hoist to "
1127 << printMBBReference(*Dom.first) << ' ' << Dom.second
1128 << '\n');
1129 }
1130
1131 // Insert the hoisted copies.
1132 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
1133 DomPair &Dom = NearestDom[i];
1134 if (!Dom.first || Dom.second.isValid())
1135 continue;
1136 // This value needs a hoisted copy inserted at the end of Dom.first.
1137 const VNInfo *ParentVNI = Parent->getValNumInfo(ValNo: i);
1138 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(index: ParentVNI->def);
1139 // Get a less loopy dominator than Dom.first.
1140 Dom.first = findShallowDominator(MBB: Dom.first, DefMBB);
1141 if (SpillMode == SM_Speed &&
1142 MBFI.getBlockFreq(MBB: Dom.first) > Costs[ParentVNI->id]) {
1143 NotToHoistSet.insert(V: ParentVNI->id);
1144 continue;
1145 }
1146 SlotIndex LSP = SA.getLastSplitPoint(BB: Dom.first);
1147 if (LSP <= ParentVNI->def) {
1148 NotToHoistSet.insert(V: ParentVNI->id);
1149 continue;
1150 }
1151 Dom.second = defFromParent(RegIdx: 0, ParentVNI, UseIdx: LSP, MBB&: *Dom.first,
1152 I: SA.getLastSplitPointIter(BB: Dom.first))->def;
1153 }
1154
1155 // Remove redundant back-copies that are now known to be dominated by another
1156 // def with the same value.
1157 SmallVector<VNInfo*, 8> BackCopies;
1158 for (VNInfo *VNI : LI->valnos) {
1159 if (VNI->isUnused())
1160 continue;
1161 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx: VNI->def);
1162 const DomPair &Dom = NearestDom[ParentVNI->id];
1163 if (!Dom.first || Dom.second == VNI->def ||
1164 NotToHoistSet.count(V: ParentVNI->id))
1165 continue;
1166 BackCopies.push_back(Elt: VNI);
1167 forceRecompute(RegIdx: 0, ParentVNI: *ParentVNI);
1168 }
1169
1170 // If it is not beneficial to hoist all the BackCopies, simply remove
1171 // redundant BackCopies in speed mode.
1172 if (SpillMode == SM_Speed && !NotToHoistSet.empty())
1173 computeRedundantBackCopies(NotToHoistSet, BackCopies);
1174
1175 removeBackCopies(Copies&: BackCopies);
1176}
1177
1178/// transferValues - Transfer all possible values to the new live ranges.
1179/// Values that were rematerialized are left alone, they need LICalc.extend().
1180bool SplitEditor::transferValues() {
1181 bool Skipped = false;
1182 RegAssignMap::const_iterator AssignI = RegAssign.begin();
1183 for (const LiveRange::Segment &S : Edit->getParent()) {
1184 LLVM_DEBUG(dbgs() << " blit " << S << ':');
1185 VNInfo *ParentVNI = S.valno;
1186 // RegAssign has holes where RegIdx 0 should be used.
1187 SlotIndex Start = S.start;
1188 AssignI.advanceTo(x: Start);
1189 do {
1190 unsigned RegIdx;
1191 SlotIndex End = S.end;
1192 if (!AssignI.valid()) {
1193 RegIdx = 0;
1194 } else if (AssignI.start() <= Start) {
1195 RegIdx = AssignI.value();
1196 if (AssignI.stop() < End) {
1197 End = AssignI.stop();
1198 ++AssignI;
1199 }
1200 } else {
1201 RegIdx = 0;
1202 End = std::min(a: End, b: AssignI.start());
1203 }
1204
1205 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
1206 LLVM_DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx << '('
1207 << printReg(Edit->get(RegIdx)) << ')');
1208 LiveInterval &LI = LIS.getInterval(Reg: Edit->get(idx: RegIdx));
1209
1210 // Check for a simply defined value that can be blitted directly.
1211 ValueForcePair VFP = Values.lookup(Val: std::make_pair(x&: RegIdx, y&: ParentVNI->id));
1212 if (VNInfo *VNI = VFP.getPointer()) {
1213 LLVM_DEBUG(dbgs() << ':' << VNI->id);
1214 LI.addSegment(S: LiveInterval::Segment(Start, End, VNI));
1215 Start = End;
1216 continue;
1217 }
1218
1219 // Skip values with forced recomputation.
1220 if (VFP.getInt()) {
1221 LLVM_DEBUG(dbgs() << "(recalc)");
1222 Skipped = true;
1223 Start = End;
1224 continue;
1225 }
1226
1227 LiveIntervalCalc &LIC = getLICalc(RegIdx);
1228
1229 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
1230 // so the live range is accurate. Add live-in blocks in [Start;End) to the
1231 // LiveInBlocks.
1232 MachineFunction::iterator MBB = LIS.getMBBFromIndex(index: Start)->getIterator();
1233 SlotIndex BlockStart, BlockEnd;
1234 std::tie(args&: BlockStart, args&: BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB: &*MBB);
1235
1236 // The first block may be live-in, or it may have its own def.
1237 if (Start != BlockStart) {
1238 VNInfo *VNI = LI.extendInBlock(StartIdx: BlockStart, Kill: std::min(a: BlockEnd, b: End));
1239 assert(VNI && "Missing def for complex mapped value");
1240 LLVM_DEBUG(dbgs() << ':' << VNI->id << "*" << printMBBReference(*MBB));
1241 // MBB has its own def. Is it also live-out?
1242 if (BlockEnd <= End)
1243 LIC.setLiveOutValue(MBB: &*MBB, VNI);
1244
1245 // Skip to the next block for live-in.
1246 ++MBB;
1247 BlockStart = BlockEnd;
1248 }
1249
1250 // Handle the live-in blocks covered by [Start;End).
1251 assert(Start <= BlockStart && "Expected live-in block");
1252 while (BlockStart < End) {
1253 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB));
1254 BlockEnd = LIS.getMBBEndIdx(mbb: &*MBB);
1255 if (BlockStart == ParentVNI->def) {
1256 // This block has the def of a parent PHI, so it isn't live-in.
1257 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
1258 VNInfo *VNI = LI.extendInBlock(StartIdx: BlockStart, Kill: std::min(a: BlockEnd, b: End));
1259 assert(VNI && "Missing def for complex mapped parent PHI");
1260 if (End >= BlockEnd)
1261 LIC.setLiveOutValue(MBB: &*MBB, VNI); // Live-out as well.
1262 } else {
1263 // This block needs a live-in value. The last block covered may not
1264 // be live-out.
1265 if (End < BlockEnd)
1266 LIC.addLiveInBlock(LR&: LI, DomNode: MDT[&*MBB], Kill: End);
1267 else {
1268 // Live-through, and we don't know the value.
1269 LIC.addLiveInBlock(LR&: LI, DomNode: MDT[&*MBB]);
1270 LIC.setLiveOutValue(MBB: &*MBB, VNI: nullptr);
1271 }
1272 }
1273 BlockStart = BlockEnd;
1274 ++MBB;
1275 }
1276 Start = End;
1277 } while (Start != S.end);
1278 LLVM_DEBUG(dbgs() << '\n');
1279 }
1280
1281 LICalc[0].calculateValues();
1282 if (SpillMode)
1283 LICalc[1].calculateValues();
1284
1285 return Skipped;
1286}
1287
1288static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) {
1289 const LiveRange::Segment *Seg = LR.getSegmentContaining(Idx: Def);
1290 if (Seg == nullptr)
1291 return true;
1292 if (Seg->end != Def.getDeadSlot())
1293 return false;
1294 // This is a dead PHI. Remove it.
1295 LR.removeSegment(S: *Seg, RemoveDeadValNo: true);
1296 return true;
1297}
1298
1299void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveIntervalCalc &LIC,
1300 LiveRange &LR, LaneBitmask LM,
1301 ArrayRef<SlotIndex> Undefs) {
1302 for (MachineBasicBlock *P : B.predecessors()) {
1303 SlotIndex End = LIS.getMBBEndIdx(mbb: P);
1304 SlotIndex LastUse = End.getPrevSlot();
1305 // The predecessor may not have a live-out value. That is OK, like an
1306 // undef PHI operand.
1307 const LiveInterval &PLI = Edit->getParent();
1308 // Need the cast because the inputs to ?: would otherwise be deemed
1309 // "incompatible": SubRange vs LiveInterval.
1310 const LiveRange &PSR = !LM.all() ? getSubRangeForMaskExact(LM, LI: PLI)
1311 : static_cast<const LiveRange &>(PLI);
1312 if (PSR.liveAt(index: LastUse))
1313 LIC.extend(LR, Use: End, /*PhysReg=*/0, Undefs);
1314 }
1315}
1316
1317void SplitEditor::extendPHIKillRanges() {
1318 // Extend live ranges to be live-out for successor PHI values.
1319
1320 // Visit each PHI def slot in the parent live interval. If the def is dead,
1321 // remove it. Otherwise, extend the live interval to reach the end indexes
1322 // of all predecessor blocks.
1323
1324 const LiveInterval &ParentLI = Edit->getParent();
1325 for (const VNInfo *V : ParentLI.valnos) {
1326 if (V->isUnused() || !V->isPHIDef())
1327 continue;
1328
1329 unsigned RegIdx = RegAssign.lookup(x: V->def);
1330 LiveInterval &LI = LIS.getInterval(Reg: Edit->get(idx: RegIdx));
1331 LiveIntervalCalc &LIC = getLICalc(RegIdx);
1332 MachineBasicBlock &B = *LIS.getMBBFromIndex(index: V->def);
1333 if (!removeDeadSegment(Def: V->def, LR&: LI))
1334 extendPHIRange(B, LIC, LR&: LI, LM: LaneBitmask::getAll(), /*Undefs=*/{});
1335 }
1336
1337 SmallVector<SlotIndex, 4> Undefs;
1338 LiveIntervalCalc SubLIC;
1339
1340 for (const LiveInterval::SubRange &PS : ParentLI.subranges()) {
1341 for (const VNInfo *V : PS.valnos) {
1342 if (V->isUnused() || !V->isPHIDef())
1343 continue;
1344 unsigned RegIdx = RegAssign.lookup(x: V->def);
1345 LiveInterval &LI = LIS.getInterval(Reg: Edit->get(idx: RegIdx));
1346 LiveInterval::SubRange &S = getSubRangeForMaskExact(LM: PS.LaneMask, LI);
1347 if (removeDeadSegment(Def: V->def, LR&: S))
1348 continue;
1349
1350 MachineBasicBlock &B = *LIS.getMBBFromIndex(index: V->def);
1351 SubLIC.reset(mf: &VRM.getMachineFunction(), SI: LIS.getSlotIndexes(), MDT: &MDT,
1352 VNIA: &LIS.getVNInfoAllocator());
1353 Undefs.clear();
1354 LI.computeSubRangeUndefs(Undefs, LaneMask: PS.LaneMask, MRI, Indexes: *LIS.getSlotIndexes());
1355 extendPHIRange(B, LIC&: SubLIC, LR&: S, LM: PS.LaneMask, Undefs);
1356 }
1357 }
1358}
1359
1360/// rewriteAssigned - Rewrite all uses of Edit->getReg().
1361void SplitEditor::rewriteAssigned(bool ExtendRanges) {
1362 struct ExtPoint {
1363 ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N)
1364 : MO(O), RegIdx(R), Next(N) {}
1365
1366 MachineOperand MO;
1367 unsigned RegIdx;
1368 SlotIndex Next;
1369 };
1370
1371 SmallVector<ExtPoint,4> ExtPoints;
1372
1373 for (MachineOperand &MO :
1374 llvm::make_early_inc_range(Range: MRI.reg_operands(Reg: Edit->getReg()))) {
1375 MachineInstr *MI = MO.getParent();
1376 // LiveDebugVariables should have handled all DBG_VALUE instructions.
1377 if (MI->isDebugValue()) {
1378 LLVM_DEBUG(dbgs() << "Zapping " << *MI);
1379 MO.setReg(0);
1380 continue;
1381 }
1382
1383 // <undef> operands don't really read the register, so it doesn't matter
1384 // which register we choose. When the use operand is tied to a def, we must
1385 // use the same register as the def, so just do that always.
1386 SlotIndex Idx = LIS.getInstructionIndex(Instr: *MI);
1387 if (MO.isDef() || MO.isUndef())
1388 Idx = Idx.getRegSlot(EC: MO.isEarlyClobber());
1389
1390 // Rewrite to the mapped register at Idx.
1391 unsigned RegIdx = RegAssign.lookup(x: Idx);
1392 LiveInterval &LI = LIS.getInterval(Reg: Edit->get(idx: RegIdx));
1393 MO.setReg(LI.reg());
1394 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI->getParent())
1395 << '\t' << Idx << ':' << RegIdx << '\t' << *MI);
1396
1397 // Extend liveness to Idx if the instruction reads reg.
1398 if (!ExtendRanges || MO.isUndef())
1399 continue;
1400
1401 // Skip instructions that don't read Reg.
1402 if (MO.isDef()) {
1403 if (!MO.getSubReg() && !MO.isEarlyClobber())
1404 continue;
1405 // We may want to extend a live range for a partial redef, or for a use
1406 // tied to an early clobber.
1407 if (!Edit->getParent().liveAt(index: Idx.getPrevSlot()))
1408 continue;
1409 } else {
1410 assert(MO.isUse());
1411 bool IsEarlyClobber = false;
1412 if (MO.isTied()) {
1413 // We want to extend a live range into `e` slot rather than `r` slot if
1414 // tied-def is early clobber, because the `e` slot already contained
1415 // in the live range of early-clobber tied-def operand, give an example
1416 // here:
1417 // 0 %0 = ...
1418 // 16 early-clobber %0 = Op %0 (tied-def 0), ...
1419 // 32 ... = Op %0
1420 // Before extend:
1421 // %0 = [0r, 0d) [16e, 32d)
1422 // The point we want to extend is 0d to 16e not 16r in this case, but if
1423 // we use 16r here we will extend nothing because that already contained
1424 // in [16e, 32d).
1425 unsigned OpIdx = MO.getOperandNo();
1426 unsigned DefOpIdx = MI->findTiedOperandIdx(OpIdx);
1427 const MachineOperand &DefOp = MI->getOperand(i: DefOpIdx);
1428 IsEarlyClobber = DefOp.isEarlyClobber();
1429 }
1430
1431 Idx = Idx.getRegSlot(EC: IsEarlyClobber);
1432 }
1433
1434 SlotIndex Next = Idx;
1435 if (LI.hasSubRanges()) {
1436 // We have to delay extending subranges until we have seen all operands
1437 // defining the register. This is because a <def,read-undef> operand
1438 // will create an "undef" point, and we cannot extend any subranges
1439 // until all of them have been accounted for.
1440 if (MO.isUse())
1441 ExtPoints.push_back(Elt: ExtPoint(MO, RegIdx, Next));
1442 } else {
1443 LiveIntervalCalc &LIC = getLICalc(RegIdx);
1444 LIC.extend(LR&: LI, Use: Next, PhysReg: 0, Undefs: ArrayRef<SlotIndex>());
1445 }
1446 }
1447
1448 for (ExtPoint &EP : ExtPoints) {
1449 LiveInterval &LI = LIS.getInterval(Reg: Edit->get(idx: EP.RegIdx));
1450 assert(LI.hasSubRanges());
1451
1452 LiveIntervalCalc SubLIC;
1453 Register Reg = EP.MO.getReg();
1454 unsigned Sub = EP.MO.getSubReg();
1455 LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(SubIdx: Sub)
1456 : MRI.getMaxLaneMaskForVReg(Reg);
1457 for (LiveInterval::SubRange &S : LI.subranges()) {
1458 if ((S.LaneMask & LM).none())
1459 continue;
1460 // The problem here can be that the new register may have been created
1461 // for a partially defined original register. For example:
1462 // %0:subreg_hireg<def,read-undef> = ...
1463 // ...
1464 // %1 = COPY %0
1465 if (S.empty())
1466 continue;
1467 SubLIC.reset(mf: &VRM.getMachineFunction(), SI: LIS.getSlotIndexes(), MDT: &MDT,
1468 VNIA: &LIS.getVNInfoAllocator());
1469 SmallVector<SlotIndex, 4> Undefs;
1470 LI.computeSubRangeUndefs(Undefs, LaneMask: S.LaneMask, MRI, Indexes: *LIS.getSlotIndexes());
1471 SubLIC.extend(LR&: S, Use: EP.Next, PhysReg: 0, Undefs);
1472 }
1473 }
1474
1475 for (Register R : *Edit) {
1476 LiveInterval &LI = LIS.getInterval(Reg: R);
1477 if (!LI.hasSubRanges())
1478 continue;
1479 LI.clear();
1480 LIS.constructMainRangeFromSubranges(LI);
1481 }
1482}
1483
1484void SplitEditor::deleteRematVictims() {
1485 SmallVector<MachineInstr*, 8> Dead;
1486 for (const Register &R : *Edit) {
1487 LiveInterval *LI = &LIS.getInterval(Reg: R);
1488 for (const LiveRange::Segment &S : LI->segments) {
1489 // Dead defs end at the dead slot.
1490 if (S.end != S.valno->def.getDeadSlot())
1491 continue;
1492 if (S.valno->isPHIDef())
1493 continue;
1494 MachineInstr *MI = LIS.getInstructionFromIndex(index: S.valno->def);
1495 assert(MI && "Missing instruction for dead def");
1496 MI->addRegisterDead(Reg: LI->reg(), RegInfo: &TRI);
1497
1498 if (!MI->allDefsAreDead())
1499 continue;
1500
1501 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
1502 Dead.push_back(Elt: MI);
1503 }
1504 }
1505
1506 if (Dead.empty())
1507 return;
1508
1509 Edit->eliminateDeadDefs(Dead, RegsBeingSpilled: {});
1510}
1511
1512void SplitEditor::forceRecomputeVNI(const VNInfo &ParentVNI) {
1513 // Fast-path for common case.
1514 if (!ParentVNI.isPHIDef()) {
1515 for (unsigned I = 0, E = Edit->size(); I != E; ++I)
1516 forceRecompute(RegIdx: I, ParentVNI);
1517 return;
1518 }
1519
1520 // Trace value through phis.
1521 ///< whether VNI was/is in worklist.
1522 SmallPtrSet<const VNInfo *, 8> Visited = {&ParentVNI};
1523 SmallVector<const VNInfo *, 4> WorkList = {&ParentVNI};
1524
1525 const LiveInterval &ParentLI = Edit->getParent();
1526 const SlotIndexes &Indexes = *LIS.getSlotIndexes();
1527 do {
1528 const VNInfo &VNI = *WorkList.pop_back_val();
1529 for (unsigned I = 0, E = Edit->size(); I != E; ++I)
1530 forceRecompute(RegIdx: I, ParentVNI: VNI);
1531 if (!VNI.isPHIDef())
1532 continue;
1533
1534 MachineBasicBlock &MBB = *Indexes.getMBBFromIndex(index: VNI.def);
1535 for (const MachineBasicBlock *Pred : MBB.predecessors()) {
1536 SlotIndex PredEnd = Indexes.getMBBEndIdx(mbb: Pred);
1537 VNInfo *PredVNI = ParentLI.getVNInfoBefore(Idx: PredEnd);
1538 assert(PredVNI && "Value available in PhiVNI predecessor");
1539 if (Visited.insert(Ptr: PredVNI).second)
1540 WorkList.push_back(Elt: PredVNI);
1541 }
1542 } while(!WorkList.empty());
1543}
1544
1545void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
1546 ++NumFinished;
1547
1548 // At this point, the live intervals in Edit contain VNInfos corresponding to
1549 // the inserted copies.
1550
1551 // Add the original defs from the parent interval.
1552 for (const VNInfo *ParentVNI : Edit->getParent().valnos) {
1553 if (ParentVNI->isUnused())
1554 continue;
1555 unsigned RegIdx = RegAssign.lookup(x: ParentVNI->def);
1556 defValue(RegIdx, ParentVNI, Idx: ParentVNI->def, Original: true);
1557
1558 // Force rematted values to be recomputed everywhere.
1559 // The new live ranges may be truncated.
1560 if (Edit->didRematerialize(ParentVNI))
1561 forceRecomputeVNI(ParentVNI: *ParentVNI);
1562 }
1563
1564 // Hoist back-copies to the complement interval when in spill mode.
1565 switch (SpillMode) {
1566 case SM_Partition:
1567 // Leave all back-copies as is.
1568 break;
1569 case SM_Size:
1570 case SM_Speed:
1571 // hoistCopies will behave differently between size and speed.
1572 hoistCopies();
1573 }
1574
1575 // Transfer the simply mapped values, check if any are skipped.
1576 bool Skipped = transferValues();
1577
1578 // Rewrite virtual registers, possibly extending ranges.
1579 rewriteAssigned(ExtendRanges: Skipped);
1580
1581 if (Skipped)
1582 extendPHIKillRanges();
1583 else
1584 ++NumSimple;
1585
1586 // Delete defs that were rematted everywhere.
1587 if (Skipped)
1588 deleteRematVictims();
1589
1590 // Get rid of unused values and set phi-kill flags.
1591 for (Register Reg : *Edit) {
1592 LiveInterval &LI = LIS.getInterval(Reg);
1593 LI.removeEmptySubRanges();
1594 LI.RenumberValues();
1595 }
1596
1597 // Provide a reverse mapping from original indices to Edit ranges.
1598 if (LRMap) {
1599 auto Seq = llvm::seq<unsigned>(Begin: 0, End: Edit->size());
1600 LRMap->assign(in_start: Seq.begin(), in_end: Seq.end());
1601 }
1602
1603 // Now check if any registers were separated into multiple components.
1604 ConnectedVNInfoEqClasses ConEQ(LIS);
1605 for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
1606 // Don't use iterators, they are invalidated by create() below.
1607 Register VReg = Edit->get(idx: i);
1608 LiveInterval &LI = LIS.getInterval(Reg: VReg);
1609 SmallVector<LiveInterval*, 8> SplitLIs;
1610 LIS.splitSeparateComponents(LI, SplitLIs);
1611 Register Original = VRM.getOriginal(VirtReg: VReg);
1612 for (LiveInterval *SplitLI : SplitLIs)
1613 VRM.setIsSplitFromReg(virtReg: SplitLI->reg(), SReg: Original);
1614
1615 // The new intervals all map back to i.
1616 if (LRMap)
1617 LRMap->resize(N: Edit->size(), NV: i);
1618 }
1619
1620 // Calculate spill weight and allocation hints for new intervals.
1621 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), VRAI);
1622
1623 assert(!LRMap || LRMap->size() == Edit->size());
1624}
1625
1626//===----------------------------------------------------------------------===//
1627// Single Block Splitting
1628//===----------------------------------------------------------------------===//
1629
1630bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
1631 bool SingleInstrs) const {
1632 // Always split for multiple instructions.
1633 if (!BI.isOneInstr())
1634 return true;
1635 // Don't split for single instructions unless explicitly requested.
1636 if (!SingleInstrs)
1637 return false;
1638 // Splitting a live-through range always makes progress.
1639 if (BI.LiveIn && BI.LiveOut)
1640 return true;
1641 // No point in isolating a copy. It has no register class constraints.
1642 MachineInstr *MI = LIS.getInstructionFromIndex(index: BI.FirstInstr);
1643 bool copyLike = TII.isCopyInstr(MI: *MI) || MI->isSubregToReg();
1644 if (copyLike)
1645 return false;
1646 // Finally, don't isolate an end point that was created by earlier splits.
1647 return isOriginalEndpoint(Idx: BI.FirstInstr);
1648}
1649
1650void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
1651 openIntv();
1652 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BB: BI.MBB);
1653 SlotIndex SegStart = enterIntvBefore(Idx: std::min(a: BI.FirstInstr,
1654 b: LastSplitPoint));
1655 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
1656 useIntv(Start: SegStart, End: leaveIntvAfter(Idx: BI.LastInstr));
1657 } else {
1658 // The last use is after the last valid split point.
1659 SlotIndex SegStop = leaveIntvBefore(Idx: LastSplitPoint);
1660 useIntv(Start: SegStart, End: SegStop);
1661 overlapIntv(Start: SegStop, End: BI.LastInstr);
1662 }
1663}
1664
1665//===----------------------------------------------------------------------===//
1666// Global Live Range Splitting Support
1667//===----------------------------------------------------------------------===//
1668
1669// These methods support a method of global live range splitting that uses a
1670// global algorithm to decide intervals for CFG edges. They will insert split
1671// points and color intervals in basic blocks while avoiding interference.
1672//
1673// Note that splitSingleBlock is also useful for blocks where both CFG edges
1674// are on the stack.
1675
1676void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
1677 unsigned IntvIn, SlotIndex LeaveBefore,
1678 unsigned IntvOut, SlotIndex EnterAfter){
1679 SlotIndex Start, Stop;
1680 std::tie(args&: Start, args&: Stop) = LIS.getSlotIndexes()->getMBBRange(Num: MBBNum);
1681
1682 LLVM_DEBUG(dbgs() << "%bb." << MBBNum << " [" << Start << ';' << Stop
1683 << ") intf " << LeaveBefore << '-' << EnterAfter
1684 << ", live-through " << IntvIn << " -> " << IntvOut);
1685
1686 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
1687
1688 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
1689 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
1690 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
1691
1692 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(N: MBBNum);
1693
1694 if (!IntvOut) {
1695 LLVM_DEBUG(dbgs() << ", spill on entry.\n");
1696 //
1697 // <<<<<<<<< Possible LeaveBefore interference.
1698 // |-----------| Live through.
1699 // -____________ Spill on entry.
1700 //
1701 selectIntv(Idx: IntvIn);
1702 SlotIndex Idx = leaveIntvAtTop(MBB&: *MBB);
1703 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1704 (void)Idx;
1705 return;
1706 }
1707
1708 if (!IntvIn) {
1709 LLVM_DEBUG(dbgs() << ", reload on exit.\n");
1710 //
1711 // >>>>>>> Possible EnterAfter interference.
1712 // |-----------| Live through.
1713 // ___________-- Reload on exit.
1714 //
1715 selectIntv(Idx: IntvOut);
1716 SlotIndex Idx = enterIntvAtEnd(MBB&: *MBB);
1717 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1718 (void)Idx;
1719 return;
1720 }
1721
1722 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
1723 LLVM_DEBUG(dbgs() << ", straight through.\n");
1724 //
1725 // |-----------| Live through.
1726 // ------------- Straight through, same intv, no interference.
1727 //
1728 selectIntv(Idx: IntvOut);
1729 useIntv(Start, End: Stop);
1730 return;
1731 }
1732
1733 // We cannot legally insert splits after LSP.
1734 SlotIndex LSP = SA.getLastSplitPoint(Num: MBBNum);
1735 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
1736
1737 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
1738 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
1739 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n");
1740 //
1741 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1742 // |-----------| Live through.
1743 // ------======= Switch intervals between interference.
1744 //
1745 selectIntv(Idx: IntvOut);
1746 SlotIndex Idx;
1747 if (LeaveBefore && LeaveBefore < LSP) {
1748 Idx = enterIntvBefore(Idx: LeaveBefore);
1749 useIntv(Start: Idx, End: Stop);
1750 } else {
1751 Idx = enterIntvAtEnd(MBB&: *MBB);
1752 }
1753 selectIntv(Idx: IntvIn);
1754 useIntv(Start, End: Idx);
1755 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1756 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1757 return;
1758 }
1759
1760 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n");
1761 //
1762 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1763 // |-----------| Live through.
1764 // ==---------== Switch intervals before/after interference.
1765 //
1766 assert(LeaveBefore <= EnterAfter && "Missed case");
1767
1768 selectIntv(Idx: IntvOut);
1769 SlotIndex Idx = enterIntvAfter(Idx: EnterAfter);
1770 useIntv(Start: Idx, End: Stop);
1771 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1772
1773 selectIntv(Idx: IntvIn);
1774 Idx = leaveIntvBefore(Idx: LeaveBefore);
1775 useIntv(Start, End: Idx);
1776 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1777}
1778
1779void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
1780 unsigned IntvIn, SlotIndex LeaveBefore) {
1781 SlotIndex Start, Stop;
1782 std::tie(args&: Start, args&: Stop) = LIS.getSlotIndexes()->getMBBRange(MBB: BI.MBB);
1783
1784 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';'
1785 << Stop << "), uses " << BI.FirstInstr << '-'
1786 << BI.LastInstr << ", reg-in " << IntvIn
1787 << ", leave before " << LeaveBefore
1788 << (BI.LiveOut ? ", stack-out" : ", killed in block"));
1789
1790 assert(IntvIn && "Must have register in");
1791 assert(BI.LiveIn && "Must be live-in");
1792 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
1793
1794 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
1795 LLVM_DEBUG(dbgs() << " before interference.\n");
1796 //
1797 // <<< Interference after kill.
1798 // |---o---x | Killed in block.
1799 // ========= Use IntvIn everywhere.
1800 //
1801 selectIntv(Idx: IntvIn);
1802 useIntv(Start, End: BI.LastInstr);
1803 return;
1804 }
1805
1806 SlotIndex LSP = SA.getLastSplitPoint(BB: BI.MBB);
1807
1808 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
1809 //
1810 // <<< Possible interference after last use.
1811 // |---o---o---| Live-out on stack.
1812 // =========____ Leave IntvIn after last use.
1813 //
1814 // < Interference after last use.
1815 // |---o---o--o| Live-out on stack, late last use.
1816 // ============ Copy to stack after LSP, overlap IntvIn.
1817 // \_____ Stack interval is live-out.
1818 //
1819 if (BI.LastInstr < LSP) {
1820 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n");
1821 selectIntv(Idx: IntvIn);
1822 SlotIndex Idx = leaveIntvAfter(Idx: BI.LastInstr);
1823 useIntv(Start, End: Idx);
1824 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1825 } else {
1826 LLVM_DEBUG(dbgs() << ", spill before last split point.\n");
1827 selectIntv(Idx: IntvIn);
1828 SlotIndex Idx = leaveIntvBefore(Idx: LSP);
1829 overlapIntv(Start: Idx, End: BI.LastInstr);
1830 useIntv(Start, End: Idx);
1831 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1832 }
1833 return;
1834 }
1835
1836 // The interference is overlapping somewhere we wanted to use IntvIn. That
1837 // means we need to create a local interval that can be allocated a
1838 // different register.
1839 unsigned LocalIntv = openIntv();
1840 (void)LocalIntv;
1841 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
1842
1843 if (!BI.LiveOut || BI.LastInstr < LSP) {
1844 //
1845 // <<<<<<< Interference overlapping uses.
1846 // |---o---o---| Live-out on stack.
1847 // =====----____ Leave IntvIn before interference, then spill.
1848 //
1849 SlotIndex To = leaveIntvAfter(Idx: BI.LastInstr);
1850 SlotIndex From = enterIntvBefore(Idx: LeaveBefore);
1851 useIntv(Start: From, End: To);
1852 selectIntv(Idx: IntvIn);
1853 useIntv(Start, End: From);
1854 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1855 return;
1856 }
1857
1858 // <<<<<<< Interference overlapping uses.
1859 // |---o---o--o| Live-out on stack, late last use.
1860 // =====------- Copy to stack before LSP, overlap LocalIntv.
1861 // \_____ Stack interval is live-out.
1862 //
1863 SlotIndex To = leaveIntvBefore(Idx: LSP);
1864 overlapIntv(Start: To, End: BI.LastInstr);
1865 SlotIndex From = enterIntvBefore(Idx: std::min(a: To, b: LeaveBefore));
1866 useIntv(Start: From, End: To);
1867 selectIntv(Idx: IntvIn);
1868 useIntv(Start, End: From);
1869 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1870}
1871
1872void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
1873 unsigned IntvOut, SlotIndex EnterAfter) {
1874 SlotIndex Start, Stop;
1875 std::tie(args&: Start, args&: Stop) = LIS.getSlotIndexes()->getMBBRange(MBB: BI.MBB);
1876
1877 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';'
1878 << Stop << "), uses " << BI.FirstInstr << '-'
1879 << BI.LastInstr << ", reg-out " << IntvOut
1880 << ", enter after " << EnterAfter
1881 << (BI.LiveIn ? ", stack-in" : ", defined in block"));
1882
1883 SlotIndex LSP = SA.getLastSplitPoint(BB: BI.MBB);
1884
1885 assert(IntvOut && "Must have register out");
1886 assert(BI.LiveOut && "Must be live-out");
1887 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
1888
1889 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
1890 LLVM_DEBUG(dbgs() << " after interference.\n");
1891 //
1892 // >>>> Interference before def.
1893 // | o---o---| Defined in block.
1894 // ========= Use IntvOut everywhere.
1895 //
1896 selectIntv(Idx: IntvOut);
1897 useIntv(Start: BI.FirstInstr, End: Stop);
1898 return;
1899 }
1900
1901 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
1902 LLVM_DEBUG(dbgs() << ", reload after interference.\n");
1903 //
1904 // >>>> Interference before def.
1905 // |---o---o---| Live-through, stack-in.
1906 // ____========= Enter IntvOut before first use.
1907 //
1908 selectIntv(Idx: IntvOut);
1909 SlotIndex Idx = enterIntvBefore(Idx: std::min(a: LSP, b: BI.FirstInstr));
1910 useIntv(Start: Idx, End: Stop);
1911 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1912 return;
1913 }
1914
1915 // The interference is overlapping somewhere we wanted to use IntvOut. That
1916 // means we need to create a local interval that can be allocated a
1917 // different register.
1918 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n");
1919 //
1920 // >>>>>>> Interference overlapping uses.
1921 // |---o---o---| Live-through, stack-in.
1922 // ____---====== Create local interval for interference range.
1923 //
1924 selectIntv(Idx: IntvOut);
1925 SlotIndex Idx = enterIntvAfter(Idx: EnterAfter);
1926 useIntv(Start: Idx, End: Stop);
1927 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1928
1929 openIntv();
1930 SlotIndex From = enterIntvBefore(Idx: std::min(a: Idx, b: BI.FirstInstr));
1931 useIntv(Start: From, End: Idx);
1932}
1933
1934void SplitAnalysis::BlockInfo::print(raw_ostream &OS) const {
1935 OS << "{" << printMBBReference(MBB: *MBB) << ", "
1936 << "uses " << FirstInstr << " to " << LastInstr << ", "
1937 << "1st def " << FirstDef << ", "
1938 << (LiveIn ? "live in" : "dead in") << ", "
1939 << (LiveOut ? "live out" : "dead out") << "}";
1940}
1941
1942void SplitAnalysis::BlockInfo::dump() const {
1943 print(OS&: dbgs());
1944 dbgs() << "\n";
1945}
1946