1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "SplitKit.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveRangeEdit.h"
19 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/VirtRegMap.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "regalloc"
33 
34 STATISTIC(NumFinished, "Number of splits finished");
35 STATISTIC(NumSimple,   "Number of splits that were simple");
36 STATISTIC(NumCopies,   "Number of copies inserted for splitting");
37 STATISTIC(NumRemats,   "Number of rematerialized defs for splitting");
38 STATISTIC(NumRepairs,  "Number of invalid live ranges repaired");
39 
40 //===----------------------------------------------------------------------===//
41 //                     Last Insert Point Analysis
42 //===----------------------------------------------------------------------===//
43 
44 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis,
45                                          unsigned BBNum)
46     : LIS(lis), LastInsertPoint(BBNum) {}
47 
48 SlotIndex
49 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI,
50                                             const MachineBasicBlock &MBB) {
51   unsigned Num = MBB.getNumber();
52   std::pair<SlotIndex, SlotIndex> &LIP = LastInsertPoint[Num];
53   SlotIndex MBBEnd = LIS.getMBBEndIdx(&MBB);
54 
55   SmallVector<const MachineBasicBlock *, 1> EHPadSucessors;
56   for (const MachineBasicBlock *SMBB : MBB.successors())
57     if (SMBB->isEHPad())
58       EHPadSucessors.push_back(SMBB);
59 
60   // Compute insert points on the first call. The pair is independent of the
61   // current live interval.
62   if (!LIP.first.isValid()) {
63     MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator();
64     if (FirstTerm == MBB.end())
65       LIP.first = MBBEnd;
66     else
67       LIP.first = LIS.getInstructionIndex(*FirstTerm);
68 
69     // If there is a landing pad successor, also find the call instruction.
70     if (EHPadSucessors.empty())
71       return LIP.first;
72     // There may not be a call instruction (?) in which case we ignore LPad.
73     LIP.second = LIP.first;
74     for (MachineBasicBlock::const_iterator I = MBB.end(), E = MBB.begin();
75          I != E;) {
76       --I;
77       if (I->isCall()) {
78         LIP.second = LIS.getInstructionIndex(*I);
79         break;
80       }
81     }
82   }
83 
84   // If CurLI is live into a landing pad successor, move the last insert point
85   // back to the call that may throw.
86   if (!LIP.second)
87     return LIP.first;
88 
89   if (none_of(EHPadSucessors, [&](const MachineBasicBlock *EHPad) {
90         return LIS.isLiveInToMBB(CurLI, EHPad);
91       }))
92     return LIP.first;
93 
94   // Find the value leaving MBB.
95   const VNInfo *VNI = CurLI.getVNInfoBefore(MBBEnd);
96   if (!VNI)
97     return LIP.first;
98 
99   // If the value leaving MBB was defined after the call in MBB, it can't
100   // really be live-in to the landing pad.  This can happen if the landing pad
101   // has a PHI, and this register is undef on the exceptional edge.
102   // <rdar://problem/10664933>
103   if (!SlotIndex::isEarlierInstr(VNI->def, LIP.second) && VNI->def < MBBEnd)
104     return LIP.first;
105 
106   // Value is properly live-in to the landing pad.
107   // Only allow inserts before the call.
108   return LIP.second;
109 }
110 
111 MachineBasicBlock::iterator
112 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI,
113                                             MachineBasicBlock &MBB) {
114   SlotIndex LIP = getLastInsertPoint(CurLI, MBB);
115   if (LIP == LIS.getMBBEndIdx(&MBB))
116     return MBB.end();
117   return LIS.getInstructionFromIndex(LIP);
118 }
119 
120 //===----------------------------------------------------------------------===//
121 //                                 Split Analysis
122 //===----------------------------------------------------------------------===//
123 
124 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
125                              const MachineLoopInfo &mli)
126     : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
127       TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr),
128       IPA(lis, MF.getNumBlockIDs()) {}
129 
130 void SplitAnalysis::clear() {
131   UseSlots.clear();
132   UseBlocks.clear();
133   ThroughBlocks.clear();
134   CurLI = nullptr;
135   DidRepairRange = false;
136 }
137 
138 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
139 void SplitAnalysis::analyzeUses() {
140   assert(UseSlots.empty() && "Call clear first");
141 
142   // First get all the defs from the interval values. This provides the correct
143   // slots for early clobbers.
144   for (const VNInfo *VNI : CurLI->valnos)
145     if (!VNI->isPHIDef() && !VNI->isUnused())
146       UseSlots.push_back(VNI->def);
147 
148   // Get use slots form the use-def chain.
149   const MachineRegisterInfo &MRI = MF.getRegInfo();
150   for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg))
151     if (!MO.isUndef())
152       UseSlots.push_back(LIS.getInstructionIndex(*MO.getParent()).getRegSlot());
153 
154   array_pod_sort(UseSlots.begin(), UseSlots.end());
155 
156   // Remove duplicates, keeping the smaller slot for each instruction.
157   // That is what we want for early clobbers.
158   UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
159                              SlotIndex::isSameInstr),
160                  UseSlots.end());
161 
162   // Compute per-live block info.
163   if (!calcLiveBlockInfo()) {
164     // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
165     // I am looking at you, RegisterCoalescer!
166     DidRepairRange = true;
167     ++NumRepairs;
168     DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
169     const_cast<LiveIntervals&>(LIS)
170       .shrinkToUses(const_cast<LiveInterval*>(CurLI));
171     UseBlocks.clear();
172     ThroughBlocks.clear();
173     bool fixed = calcLiveBlockInfo();
174     (void)fixed;
175     assert(fixed && "Couldn't fix broken live interval");
176   }
177 
178   DEBUG(dbgs() << "Analyze counted "
179                << UseSlots.size() << " instrs in "
180                << UseBlocks.size() << " blocks, through "
181                << NumThroughBlocks << " blocks.\n");
182 }
183 
184 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
185 /// where CurLI is live.
186 bool SplitAnalysis::calcLiveBlockInfo() {
187   ThroughBlocks.resize(MF.getNumBlockIDs());
188   NumThroughBlocks = NumGapBlocks = 0;
189   if (CurLI->empty())
190     return true;
191 
192   LiveInterval::const_iterator LVI = CurLI->begin();
193   LiveInterval::const_iterator LVE = CurLI->end();
194 
195   SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
196   UseI = UseSlots.begin();
197   UseE = UseSlots.end();
198 
199   // Loop over basic blocks where CurLI is live.
200   MachineFunction::iterator MFI =
201       LIS.getMBBFromIndex(LVI->start)->getIterator();
202   for (;;) {
203     BlockInfo BI;
204     BI.MBB = &*MFI;
205     SlotIndex Start, Stop;
206     std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
207 
208     // If the block contains no uses, the range must be live through. At one
209     // point, RegisterCoalescer could create dangling ranges that ended
210     // mid-block.
211     if (UseI == UseE || *UseI >= Stop) {
212       ++NumThroughBlocks;
213       ThroughBlocks.set(BI.MBB->getNumber());
214       // The range shouldn't end mid-block if there are no uses. This shouldn't
215       // happen.
216       if (LVI->end < Stop)
217         return false;
218     } else {
219       // This block has uses. Find the first and last uses in the block.
220       BI.FirstInstr = *UseI;
221       assert(BI.FirstInstr >= Start);
222       do ++UseI;
223       while (UseI != UseE && *UseI < Stop);
224       BI.LastInstr = UseI[-1];
225       assert(BI.LastInstr < Stop);
226 
227       // LVI is the first live segment overlapping MBB.
228       BI.LiveIn = LVI->start <= Start;
229 
230       // When not live in, the first use should be a def.
231       if (!BI.LiveIn) {
232         assert(LVI->start == LVI->valno->def && "Dangling Segment start");
233         assert(LVI->start == BI.FirstInstr && "First instr should be a def");
234         BI.FirstDef = BI.FirstInstr;
235       }
236 
237       // Look for gaps in the live range.
238       BI.LiveOut = true;
239       while (LVI->end < Stop) {
240         SlotIndex LastStop = LVI->end;
241         if (++LVI == LVE || LVI->start >= Stop) {
242           BI.LiveOut = false;
243           BI.LastInstr = LastStop;
244           break;
245         }
246 
247         if (LastStop < LVI->start) {
248           // There is a gap in the live range. Create duplicate entries for the
249           // live-in snippet and the live-out snippet.
250           ++NumGapBlocks;
251 
252           // Push the Live-in part.
253           BI.LiveOut = false;
254           UseBlocks.push_back(BI);
255           UseBlocks.back().LastInstr = LastStop;
256 
257           // Set up BI for the live-out part.
258           BI.LiveIn = false;
259           BI.LiveOut = true;
260           BI.FirstInstr = BI.FirstDef = LVI->start;
261         }
262 
263         // A Segment that starts in the middle of the block must be a def.
264         assert(LVI->start == LVI->valno->def && "Dangling Segment start");
265         if (!BI.FirstDef)
266           BI.FirstDef = LVI->start;
267       }
268 
269       UseBlocks.push_back(BI);
270 
271       // LVI is now at LVE or LVI->end >= Stop.
272       if (LVI == LVE)
273         break;
274     }
275 
276     // Live segment ends exactly at Stop. Move to the next segment.
277     if (LVI->end == Stop && ++LVI == LVE)
278       break;
279 
280     // Pick the next basic block.
281     if (LVI->start < Stop)
282       ++MFI;
283     else
284       MFI = LIS.getMBBFromIndex(LVI->start)->getIterator();
285   }
286 
287   assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
288   return true;
289 }
290 
291 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
292   if (cli->empty())
293     return 0;
294   LiveInterval *li = const_cast<LiveInterval*>(cli);
295   LiveInterval::iterator LVI = li->begin();
296   LiveInterval::iterator LVE = li->end();
297   unsigned Count = 0;
298 
299   // Loop over basic blocks where li is live.
300   MachineFunction::const_iterator MFI =
301       LIS.getMBBFromIndex(LVI->start)->getIterator();
302   SlotIndex Stop = LIS.getMBBEndIdx(&*MFI);
303   for (;;) {
304     ++Count;
305     LVI = li->advanceTo(LVI, Stop);
306     if (LVI == LVE)
307       return Count;
308     do {
309       ++MFI;
310       Stop = LIS.getMBBEndIdx(&*MFI);
311     } while (Stop <= LVI->start);
312   }
313 }
314 
315 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
316   unsigned OrigReg = VRM.getOriginal(CurLI->reg);
317   const LiveInterval &Orig = LIS.getInterval(OrigReg);
318   assert(!Orig.empty() && "Splitting empty interval?");
319   LiveInterval::const_iterator I = Orig.find(Idx);
320 
321   // Range containing Idx should begin at Idx.
322   if (I != Orig.end() && I->start <= Idx)
323     return I->start == Idx;
324 
325   // Range does not contain Idx, previous must end at Idx.
326   return I != Orig.begin() && (--I)->end == Idx;
327 }
328 
329 void SplitAnalysis::analyze(const LiveInterval *li) {
330   clear();
331   CurLI = li;
332   analyzeUses();
333 }
334 
335 
336 //===----------------------------------------------------------------------===//
337 //                               Split Editor
338 //===----------------------------------------------------------------------===//
339 
340 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
341 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
342                          MachineDominatorTree &mdt,
343                          MachineBlockFrequencyInfo &mbfi)
344     : SA(sa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()),
345       MDT(mdt), TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()),
346       TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()),
347       MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition),
348       RegAssign(Allocator) {}
349 
350 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
351   Edit = &LRE;
352   SpillMode = SM;
353   OpenIdx = 0;
354   RegAssign.clear();
355   Values.clear();
356 
357   // Reset the LiveRangeCalc instances needed for this spill mode.
358   LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
359                   &LIS.getVNInfoAllocator());
360   if (SpillMode)
361     LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
362                     &LIS.getVNInfoAllocator());
363 
364   // We don't need an AliasAnalysis since we will only be performing
365   // cheap-as-a-copy remats anyway.
366   Edit->anyRematerializable(nullptr);
367 }
368 
369 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
370 LLVM_DUMP_METHOD void SplitEditor::dump() const {
371   if (RegAssign.empty()) {
372     dbgs() << " empty\n";
373     return;
374   }
375 
376   for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
377     dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
378   dbgs() << '\n';
379 }
380 #endif
381 
382 VNInfo *SplitEditor::defValue(unsigned RegIdx,
383                               const VNInfo *ParentVNI,
384                               SlotIndex Idx) {
385   assert(ParentVNI && "Mapping  NULL value");
386   assert(Idx.isValid() && "Invalid SlotIndex");
387   assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
388   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
389 
390   // Create a new value.
391   VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
392 
393   // Use insert for lookup, so we can add missing values with a second lookup.
394   std::pair<ValueMap::iterator, bool> InsP =
395     Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
396                                  ValueForcePair(VNI, false)));
397 
398   // This was the first time (RegIdx, ParentVNI) was mapped.
399   // Keep it as a simple def without any liveness.
400   if (InsP.second)
401     return VNI;
402 
403   // If the previous value was a simple mapping, add liveness for it now.
404   if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
405     SlotIndex Def = OldVNI->def;
406     LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI));
407     // No longer a simple mapping.  Switch to a complex, non-forced mapping.
408     InsP.first->second = ValueForcePair();
409   }
410 
411   // This is a complex mapping, add liveness for VNI
412   SlotIndex Def = VNI->def;
413   LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
414 
415   return VNI;
416 }
417 
418 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
419   assert(ParentVNI && "Mapping  NULL value");
420   ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
421   VNInfo *VNI = VFP.getPointer();
422 
423   // ParentVNI was either unmapped or already complex mapped. Either way, just
424   // set the force bit.
425   if (!VNI) {
426     VFP.setInt(true);
427     return;
428   }
429 
430   // This was previously a single mapping. Make sure the old def is represented
431   // by a trivial live range.
432   SlotIndex Def = VNI->def;
433   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
434   LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
435   // Mark as complex mapped, forced.
436   VFP = ValueForcePair(nullptr, true);
437 }
438 
439 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
440                                    VNInfo *ParentVNI,
441                                    SlotIndex UseIdx,
442                                    MachineBasicBlock &MBB,
443                                    MachineBasicBlock::iterator I) {
444   MachineInstr *CopyMI = nullptr;
445   SlotIndex Def;
446   LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
447 
448   // We may be trying to avoid interference that ends at a deleted instruction,
449   // so always begin RegIdx 0 early and all others late.
450   bool Late = RegIdx != 0;
451 
452   // Attempt cheap-as-a-copy rematerialization.
453   unsigned Original = VRM.getOriginal(Edit->get(RegIdx));
454   LiveInterval &OrigLI = LIS.getInterval(Original);
455   VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
456   LiveRangeEdit::Remat RM(ParentVNI);
457   RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
458 
459   if (Edit->canRematerializeAt(RM, OrigVNI, UseIdx, true)) {
460     Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
461     ++NumRemats;
462   } else {
463     // Can't remat, just insert a copy from parent.
464     CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
465                .addReg(Edit->getReg());
466     Def = LIS.getSlotIndexes()
467               ->insertMachineInstrInMaps(*CopyMI, Late)
468               .getRegSlot();
469     ++NumCopies;
470   }
471 
472   // Define the value in Reg.
473   return defValue(RegIdx, ParentVNI, Def);
474 }
475 
476 /// Create a new virtual register and live interval.
477 unsigned SplitEditor::openIntv() {
478   // Create the complement as index 0.
479   if (Edit->empty())
480     Edit->createEmptyInterval();
481 
482   // Create the open interval.
483   OpenIdx = Edit->size();
484   Edit->createEmptyInterval();
485   return OpenIdx;
486 }
487 
488 void SplitEditor::selectIntv(unsigned Idx) {
489   assert(Idx != 0 && "Cannot select the complement interval");
490   assert(Idx < Edit->size() && "Can only select previously opened interval");
491   DEBUG(dbgs() << "    selectIntv " << OpenIdx << " -> " << Idx << '\n');
492   OpenIdx = Idx;
493 }
494 
495 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
496   assert(OpenIdx && "openIntv not called before enterIntvBefore");
497   DEBUG(dbgs() << "    enterIntvBefore " << Idx);
498   Idx = Idx.getBaseIndex();
499   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
500   if (!ParentVNI) {
501     DEBUG(dbgs() << ": not live\n");
502     return Idx;
503   }
504   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
505   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
506   assert(MI && "enterIntvBefore called with invalid index");
507 
508   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
509   return VNI->def;
510 }
511 
512 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
513   assert(OpenIdx && "openIntv not called before enterIntvAfter");
514   DEBUG(dbgs() << "    enterIntvAfter " << Idx);
515   Idx = Idx.getBoundaryIndex();
516   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
517   if (!ParentVNI) {
518     DEBUG(dbgs() << ": not live\n");
519     return Idx;
520   }
521   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
522   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
523   assert(MI && "enterIntvAfter called with invalid index");
524 
525   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
526                               std::next(MachineBasicBlock::iterator(MI)));
527   return VNI->def;
528 }
529 
530 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
531   assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
532   SlotIndex End = LIS.getMBBEndIdx(&MBB);
533   SlotIndex Last = End.getPrevSlot();
534   DEBUG(dbgs() << "    enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
535   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
536   if (!ParentVNI) {
537     DEBUG(dbgs() << ": not live\n");
538     return End;
539   }
540   DEBUG(dbgs() << ": valno " << ParentVNI->id);
541   VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
542                               SA.getLastSplitPointIter(&MBB));
543   RegAssign.insert(VNI->def, End, OpenIdx);
544   DEBUG(dump());
545   return VNI->def;
546 }
547 
548 /// useIntv - indicate that all instructions in MBB should use OpenLI.
549 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
550   useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
551 }
552 
553 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
554   assert(OpenIdx && "openIntv not called before useIntv");
555   DEBUG(dbgs() << "    useIntv [" << Start << ';' << End << "):");
556   RegAssign.insert(Start, End, OpenIdx);
557   DEBUG(dump());
558 }
559 
560 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
561   assert(OpenIdx && "openIntv not called before leaveIntvAfter");
562   DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
563 
564   // The interval must be live beyond the instruction at Idx.
565   SlotIndex Boundary = Idx.getBoundaryIndex();
566   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
567   if (!ParentVNI) {
568     DEBUG(dbgs() << ": not live\n");
569     return Boundary.getNextSlot();
570   }
571   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
572   MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
573   assert(MI && "No instruction at index");
574 
575   // In spill mode, make live ranges as short as possible by inserting the copy
576   // before MI.  This is only possible if that instruction doesn't redefine the
577   // value.  The inserted COPY is not a kill, and we don't need to recompute
578   // the source live range.  The spiller also won't try to hoist this copy.
579   if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
580       MI->readsVirtualRegister(Edit->getReg())) {
581     forceRecompute(0, ParentVNI);
582     defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
583     return Idx;
584   }
585 
586   VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
587                               std::next(MachineBasicBlock::iterator(MI)));
588   return VNI->def;
589 }
590 
591 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
592   assert(OpenIdx && "openIntv not called before leaveIntvBefore");
593   DEBUG(dbgs() << "    leaveIntvBefore " << Idx);
594 
595   // The interval must be live into the instruction at Idx.
596   Idx = Idx.getBaseIndex();
597   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
598   if (!ParentVNI) {
599     DEBUG(dbgs() << ": not live\n");
600     return Idx.getNextSlot();
601   }
602   DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
603 
604   MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
605   assert(MI && "No instruction at index");
606   VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
607   return VNI->def;
608 }
609 
610 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
611   assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
612   SlotIndex Start = LIS.getMBBStartIdx(&MBB);
613   DEBUG(dbgs() << "    leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
614 
615   VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
616   if (!ParentVNI) {
617     DEBUG(dbgs() << ": not live\n");
618     return Start;
619   }
620 
621   VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
622                               MBB.SkipPHIsAndLabels(MBB.begin()));
623   RegAssign.insert(Start, VNI->def, OpenIdx);
624   DEBUG(dump());
625   return VNI->def;
626 }
627 
628 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
629   assert(OpenIdx && "openIntv not called before overlapIntv");
630   const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
631   assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
632          "Parent changes value in extended range");
633   assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
634          "Range cannot span basic blocks");
635 
636   // The complement interval will be extended as needed by LRCalc.extend().
637   if (ParentVNI)
638     forceRecompute(0, ParentVNI);
639   DEBUG(dbgs() << "    overlapIntv [" << Start << ';' << End << "):");
640   RegAssign.insert(Start, End, OpenIdx);
641   DEBUG(dump());
642 }
643 
644 //===----------------------------------------------------------------------===//
645 //                                  Spill modes
646 //===----------------------------------------------------------------------===//
647 
648 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
649   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
650   DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
651   RegAssignMap::iterator AssignI;
652   AssignI.setMap(RegAssign);
653 
654   for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
655     SlotIndex Def = Copies[i]->def;
656     MachineInstr *MI = LIS.getInstructionFromIndex(Def);
657     assert(MI && "No instruction for back-copy");
658 
659     MachineBasicBlock *MBB = MI->getParent();
660     MachineBasicBlock::iterator MBBI(MI);
661     bool AtBegin;
662     do AtBegin = MBBI == MBB->begin();
663     while (!AtBegin && (--MBBI)->isDebugValue());
664 
665     DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
666     LIS.removeVRegDefAt(*LI, Def);
667     LIS.RemoveMachineInstrFromMaps(*MI);
668     MI->eraseFromParent();
669 
670     // Adjust RegAssign if a register assignment is killed at Def. We want to
671     // avoid calculating the live range of the source register if possible.
672     AssignI.find(Def.getPrevSlot());
673     if (!AssignI.valid() || AssignI.start() >= Def)
674       continue;
675     // If MI doesn't kill the assigned register, just leave it.
676     if (AssignI.stop() != Def)
677       continue;
678     unsigned RegIdx = AssignI.value();
679     if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
680       DEBUG(dbgs() << "  cannot find simple kill of RegIdx " << RegIdx << '\n');
681       forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
682     } else {
683       SlotIndex Kill = LIS.getInstructionIndex(*MBBI).getRegSlot();
684       DEBUG(dbgs() << "  move kill to " << Kill << '\t' << *MBBI);
685       AssignI.setStop(Kill);
686     }
687   }
688 }
689 
690 MachineBasicBlock*
691 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
692                                   MachineBasicBlock *DefMBB) {
693   if (MBB == DefMBB)
694     return MBB;
695   assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
696 
697   const MachineLoopInfo &Loops = SA.Loops;
698   const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
699   MachineDomTreeNode *DefDomNode = MDT[DefMBB];
700 
701   // Best candidate so far.
702   MachineBasicBlock *BestMBB = MBB;
703   unsigned BestDepth = UINT_MAX;
704 
705   for (;;) {
706     const MachineLoop *Loop = Loops.getLoopFor(MBB);
707 
708     // MBB isn't in a loop, it doesn't get any better.  All dominators have a
709     // higher frequency by definition.
710     if (!Loop) {
711       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
712                    << MBB->getNumber() << " at depth 0\n");
713       return MBB;
714     }
715 
716     // We'll never be able to exit the DefLoop.
717     if (Loop == DefLoop) {
718       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
719                    << MBB->getNumber() << " in the same loop\n");
720       return MBB;
721     }
722 
723     // Least busy dominator seen so far.
724     unsigned Depth = Loop->getLoopDepth();
725     if (Depth < BestDepth) {
726       BestMBB = MBB;
727       BestDepth = Depth;
728       DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
729                    << MBB->getNumber() << " at depth " << Depth << '\n');
730     }
731 
732     // Leave loop by going to the immediate dominator of the loop header.
733     // This is a bigger stride than simply walking up the dominator tree.
734     MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
735 
736     // Too far up the dominator tree?
737     if (!IDom || !MDT.dominates(DefDomNode, IDom))
738       return BestMBB;
739 
740     MBB = IDom->getBlock();
741   }
742 }
743 
744 void SplitEditor::computeRedundantBackCopies(
745     DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) {
746   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
747   LiveInterval *Parent = &Edit->getParent();
748   SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums());
749   SmallPtrSet<VNInfo *, 8> DominatedVNIs;
750 
751   // Aggregate VNIs having the same value as ParentVNI.
752   for (VNInfo *VNI : LI->valnos) {
753     if (VNI->isUnused())
754       continue;
755     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
756     EqualVNs[ParentVNI->id].insert(VNI);
757   }
758 
759   // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
760   // redundant VNIs to BackCopies.
761   for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
762     VNInfo *ParentVNI = Parent->getValNumInfo(i);
763     if (!NotToHoistSet.count(ParentVNI->id))
764       continue;
765     SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin();
766     SmallPtrSetIterator<VNInfo *> It2 = It1;
767     for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) {
768       It2 = It1;
769       for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) {
770         if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2))
771           continue;
772 
773         MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def);
774         MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def);
775         if (MBB1 == MBB2) {
776           DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1));
777         } else if (MDT.dominates(MBB1, MBB2)) {
778           DominatedVNIs.insert(*It2);
779         } else if (MDT.dominates(MBB2, MBB1)) {
780           DominatedVNIs.insert(*It1);
781         }
782       }
783     }
784     if (!DominatedVNIs.empty()) {
785       forceRecompute(0, ParentVNI);
786       for (auto VNI : DominatedVNIs) {
787         BackCopies.push_back(VNI);
788       }
789       DominatedVNIs.clear();
790     }
791   }
792 }
793 
794 /// For SM_Size mode, find a common dominator for all the back-copies for
795 /// the same ParentVNI and hoist the backcopies to the dominator BB.
796 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial
797 /// to do the hoisting, simply remove the dominated backcopies for the same
798 /// ParentVNI.
799 void SplitEditor::hoistCopies() {
800   // Get the complement interval, always RegIdx 0.
801   LiveInterval *LI = &LIS.getInterval(Edit->get(0));
802   LiveInterval *Parent = &Edit->getParent();
803 
804   // Track the nearest common dominator for all back-copies for each ParentVNI,
805   // indexed by ParentVNI->id.
806   typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
807   SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
808   // The total cost of all the back-copies for each ParentVNI.
809   SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums());
810   // The ParentVNI->id set for which hoisting back-copies are not beneficial
811   // for Speed.
812   DenseSet<unsigned> NotToHoistSet;
813 
814   // Find the nearest common dominator for parent values with multiple
815   // back-copies.  If a single back-copy dominates, put it in DomPair.second.
816   for (VNInfo *VNI : LI->valnos) {
817     if (VNI->isUnused())
818       continue;
819     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
820     assert(ParentVNI && "Parent not live at complement def");
821 
822     // Don't hoist remats.  The complement is probably going to disappear
823     // completely anyway.
824     if (Edit->didRematerialize(ParentVNI))
825       continue;
826 
827     MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
828 
829     DomPair &Dom = NearestDom[ParentVNI->id];
830 
831     // Keep directly defined parent values.  This is either a PHI or an
832     // instruction in the complement range.  All other copies of ParentVNI
833     // should be eliminated.
834     if (VNI->def == ParentVNI->def) {
835       DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
836       Dom = DomPair(ValMBB, VNI->def);
837       continue;
838     }
839     // Skip the singly mapped values.  There is nothing to gain from hoisting a
840     // single back-copy.
841     if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
842       DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
843       continue;
844     }
845 
846     if (!Dom.first) {
847       // First time we see ParentVNI.  VNI dominates itself.
848       Dom = DomPair(ValMBB, VNI->def);
849     } else if (Dom.first == ValMBB) {
850       // Two defs in the same block.  Pick the earlier def.
851       if (!Dom.second.isValid() || VNI->def < Dom.second)
852         Dom.second = VNI->def;
853     } else {
854       // Different basic blocks. Check if one dominates.
855       MachineBasicBlock *Near =
856         MDT.findNearestCommonDominator(Dom.first, ValMBB);
857       if (Near == ValMBB)
858         // Def ValMBB dominates.
859         Dom = DomPair(ValMBB, VNI->def);
860       else if (Near != Dom.first)
861         // None dominate. Hoist to common dominator, need new def.
862         Dom = DomPair(Near, SlotIndex());
863       Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB);
864     }
865 
866     DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
867                  << " for parent " << ParentVNI->id << '@' << ParentVNI->def
868                  << " hoist to BB#" << Dom.first->getNumber() << ' '
869                  << Dom.second << '\n');
870   }
871 
872   // Insert the hoisted copies.
873   for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
874     DomPair &Dom = NearestDom[i];
875     if (!Dom.first || Dom.second.isValid())
876       continue;
877     // This value needs a hoisted copy inserted at the end of Dom.first.
878     VNInfo *ParentVNI = Parent->getValNumInfo(i);
879     MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
880     // Get a less loopy dominator than Dom.first.
881     Dom.first = findShallowDominator(Dom.first, DefMBB);
882     if (SpillMode == SM_Speed &&
883         MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) {
884       NotToHoistSet.insert(ParentVNI->id);
885       continue;
886     }
887     SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
888     Dom.second =
889       defFromParent(0, ParentVNI, Last, *Dom.first,
890                     SA.getLastSplitPointIter(Dom.first))->def;
891   }
892 
893   // Remove redundant back-copies that are now known to be dominated by another
894   // def with the same value.
895   SmallVector<VNInfo*, 8> BackCopies;
896   for (VNInfo *VNI : LI->valnos) {
897     if (VNI->isUnused())
898       continue;
899     VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
900     const DomPair &Dom = NearestDom[ParentVNI->id];
901     if (!Dom.first || Dom.second == VNI->def ||
902         NotToHoistSet.count(ParentVNI->id))
903       continue;
904     BackCopies.push_back(VNI);
905     forceRecompute(0, ParentVNI);
906   }
907 
908   // If it is not beneficial to hoist all the BackCopies, simply remove
909   // redundant BackCopies in speed mode.
910   if (SpillMode == SM_Speed && !NotToHoistSet.empty())
911     computeRedundantBackCopies(NotToHoistSet, BackCopies);
912 
913   removeBackCopies(BackCopies);
914 }
915 
916 
917 /// transferValues - Transfer all possible values to the new live ranges.
918 /// Values that were rematerialized are left alone, they need LRCalc.extend().
919 bool SplitEditor::transferValues() {
920   bool Skipped = false;
921   RegAssignMap::const_iterator AssignI = RegAssign.begin();
922   for (const LiveRange::Segment &S : Edit->getParent()) {
923     DEBUG(dbgs() << "  blit " << S << ':');
924     VNInfo *ParentVNI = S.valno;
925     // RegAssign has holes where RegIdx 0 should be used.
926     SlotIndex Start = S.start;
927     AssignI.advanceTo(Start);
928     do {
929       unsigned RegIdx;
930       SlotIndex End = S.end;
931       if (!AssignI.valid()) {
932         RegIdx = 0;
933       } else if (AssignI.start() <= Start) {
934         RegIdx = AssignI.value();
935         if (AssignI.stop() < End) {
936           End = AssignI.stop();
937           ++AssignI;
938         }
939       } else {
940         RegIdx = 0;
941         End = std::min(End, AssignI.start());
942       }
943 
944       // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
945       DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
946       LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
947 
948       // Check for a simply defined value that can be blitted directly.
949       ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
950       if (VNInfo *VNI = VFP.getPointer()) {
951         DEBUG(dbgs() << ':' << VNI->id);
952         LR.addSegment(LiveInterval::Segment(Start, End, VNI));
953         Start = End;
954         continue;
955       }
956 
957       // Skip values with forced recomputation.
958       if (VFP.getInt()) {
959         DEBUG(dbgs() << "(recalc)");
960         Skipped = true;
961         Start = End;
962         continue;
963       }
964 
965       LiveRangeCalc &LRC = getLRCalc(RegIdx);
966 
967       // This value has multiple defs in RegIdx, but it wasn't rematerialized,
968       // so the live range is accurate. Add live-in blocks in [Start;End) to the
969       // LiveInBlocks.
970       MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
971       SlotIndex BlockStart, BlockEnd;
972       std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB);
973 
974       // The first block may be live-in, or it may have its own def.
975       if (Start != BlockStart) {
976         VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
977         assert(VNI && "Missing def for complex mapped value");
978         DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
979         // MBB has its own def. Is it also live-out?
980         if (BlockEnd <= End)
981           LRC.setLiveOutValue(&*MBB, VNI);
982 
983         // Skip to the next block for live-in.
984         ++MBB;
985         BlockStart = BlockEnd;
986       }
987 
988       // Handle the live-in blocks covered by [Start;End).
989       assert(Start <= BlockStart && "Expected live-in block");
990       while (BlockStart < End) {
991         DEBUG(dbgs() << ">BB#" << MBB->getNumber());
992         BlockEnd = LIS.getMBBEndIdx(&*MBB);
993         if (BlockStart == ParentVNI->def) {
994           // This block has the def of a parent PHI, so it isn't live-in.
995           assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
996           VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
997           assert(VNI && "Missing def for complex mapped parent PHI");
998           if (End >= BlockEnd)
999             LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well.
1000         } else {
1001           // This block needs a live-in value.  The last block covered may not
1002           // be live-out.
1003           if (End < BlockEnd)
1004             LRC.addLiveInBlock(LR, MDT[&*MBB], End);
1005           else {
1006             // Live-through, and we don't know the value.
1007             LRC.addLiveInBlock(LR, MDT[&*MBB]);
1008             LRC.setLiveOutValue(&*MBB, nullptr);
1009           }
1010         }
1011         BlockStart = BlockEnd;
1012         ++MBB;
1013       }
1014       Start = End;
1015     } while (Start != S.end);
1016     DEBUG(dbgs() << '\n');
1017   }
1018 
1019   LRCalc[0].calculateValues();
1020   if (SpillMode)
1021     LRCalc[1].calculateValues();
1022 
1023   return Skipped;
1024 }
1025 
1026 void SplitEditor::extendPHIKillRanges() {
1027   // Extend live ranges to be live-out for successor PHI values.
1028   for (const VNInfo *PHIVNI : Edit->getParent().valnos) {
1029     if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
1030       continue;
1031     unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
1032     LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
1033 
1034     // Check whether PHI is dead.
1035     const LiveRange::Segment *Segment = LR.getSegmentContaining(PHIVNI->def);
1036     assert(Segment != nullptr && "Missing segment for VNI");
1037     if (Segment->end == PHIVNI->def.getDeadSlot()) {
1038       // This is a dead PHI. Remove it.
1039       LR.removeSegment(*Segment, true);
1040       continue;
1041     }
1042 
1043     LiveRangeCalc &LRC = getLRCalc(RegIdx);
1044     MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
1045     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1046          PE = MBB->pred_end(); PI != PE; ++PI) {
1047       SlotIndex End = LIS.getMBBEndIdx(*PI);
1048       SlotIndex LastUse = End.getPrevSlot();
1049       // The predecessor may not have a live-out value. That is OK, like an
1050       // undef PHI operand.
1051       if (Edit->getParent().liveAt(LastUse)) {
1052         assert(RegAssign.lookup(LastUse) == RegIdx &&
1053                "Different register assignment in phi predecessor");
1054         LRC.extend(LR, End);
1055       }
1056     }
1057   }
1058 }
1059 
1060 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
1061 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
1062   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
1063        RE = MRI.reg_end(); RI != RE;) {
1064     MachineOperand &MO = *RI;
1065     MachineInstr *MI = MO.getParent();
1066     ++RI;
1067     // LiveDebugVariables should have handled all DBG_VALUE instructions.
1068     if (MI->isDebugValue()) {
1069       DEBUG(dbgs() << "Zapping " << *MI);
1070       MO.setReg(0);
1071       continue;
1072     }
1073 
1074     // <undef> operands don't really read the register, so it doesn't matter
1075     // which register we choose.  When the use operand is tied to a def, we must
1076     // use the same register as the def, so just do that always.
1077     SlotIndex Idx = LIS.getInstructionIndex(*MI);
1078     if (MO.isDef() || MO.isUndef())
1079       Idx = Idx.getRegSlot(MO.isEarlyClobber());
1080 
1081     // Rewrite to the mapped register at Idx.
1082     unsigned RegIdx = RegAssign.lookup(Idx);
1083     LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
1084     MO.setReg(LI->reg);
1085     DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
1086                  << Idx << ':' << RegIdx << '\t' << *MI);
1087 
1088     // Extend liveness to Idx if the instruction reads reg.
1089     if (!ExtendRanges || MO.isUndef())
1090       continue;
1091 
1092     // Skip instructions that don't read Reg.
1093     if (MO.isDef()) {
1094       if (!MO.getSubReg() && !MO.isEarlyClobber())
1095         continue;
1096       // We may wan't to extend a live range for a partial redef, or for a use
1097       // tied to an early clobber.
1098       Idx = Idx.getPrevSlot();
1099       if (!Edit->getParent().liveAt(Idx))
1100         continue;
1101     } else
1102       Idx = Idx.getRegSlot(true);
1103 
1104     getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot());
1105   }
1106 }
1107 
1108 void SplitEditor::deleteRematVictims() {
1109   SmallVector<MachineInstr*, 8> Dead;
1110   for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
1111     LiveInterval *LI = &LIS.getInterval(*I);
1112     for (const LiveRange::Segment &S : LI->segments) {
1113       // Dead defs end at the dead slot.
1114       if (S.end != S.valno->def.getDeadSlot())
1115         continue;
1116       if (S.valno->isPHIDef())
1117         continue;
1118       MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def);
1119       assert(MI && "Missing instruction for dead def");
1120       MI->addRegisterDead(LI->reg, &TRI);
1121 
1122       if (!MI->allDefsAreDead())
1123         continue;
1124 
1125       DEBUG(dbgs() << "All defs dead: " << *MI);
1126       Dead.push_back(MI);
1127     }
1128   }
1129 
1130   if (Dead.empty())
1131     return;
1132 
1133   Edit->eliminateDeadDefs(Dead);
1134 }
1135 
1136 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
1137   ++NumFinished;
1138 
1139   // At this point, the live intervals in Edit contain VNInfos corresponding to
1140   // the inserted copies.
1141 
1142   // Add the original defs from the parent interval.
1143   for (const VNInfo *ParentVNI : Edit->getParent().valnos) {
1144     if (ParentVNI->isUnused())
1145       continue;
1146     unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
1147     defValue(RegIdx, ParentVNI, ParentVNI->def);
1148 
1149     // Force rematted values to be recomputed everywhere.
1150     // The new live ranges may be truncated.
1151     if (Edit->didRematerialize(ParentVNI))
1152       for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1153         forceRecompute(i, ParentVNI);
1154   }
1155 
1156   // Hoist back-copies to the complement interval when in spill mode.
1157   switch (SpillMode) {
1158   case SM_Partition:
1159     // Leave all back-copies as is.
1160     break;
1161   case SM_Size:
1162   case SM_Speed:
1163     // hoistCopies will behave differently between size and speed.
1164     hoistCopies();
1165   }
1166 
1167   // Transfer the simply mapped values, check if any are skipped.
1168   bool Skipped = transferValues();
1169 
1170   // Rewrite virtual registers, possibly extending ranges.
1171   rewriteAssigned(Skipped);
1172 
1173   if (Skipped)
1174     extendPHIKillRanges();
1175   else
1176     ++NumSimple;
1177 
1178   // Delete defs that were rematted everywhere.
1179   if (Skipped)
1180     deleteRematVictims();
1181 
1182   // Get rid of unused values and set phi-kill flags.
1183   for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) {
1184     LiveInterval &LI = LIS.getInterval(*I);
1185     LI.RenumberValues();
1186   }
1187 
1188   // Provide a reverse mapping from original indices to Edit ranges.
1189   if (LRMap) {
1190     LRMap->clear();
1191     for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1192       LRMap->push_back(i);
1193   }
1194 
1195   // Now check if any registers were separated into multiple components.
1196   ConnectedVNInfoEqClasses ConEQ(LIS);
1197   for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
1198     // Don't use iterators, they are invalidated by create() below.
1199     unsigned VReg = Edit->get(i);
1200     LiveInterval &LI = LIS.getInterval(VReg);
1201     SmallVector<LiveInterval*, 8> SplitLIs;
1202     LIS.splitSeparateComponents(LI, SplitLIs);
1203     unsigned Original = VRM.getOriginal(VReg);
1204     for (LiveInterval *SplitLI : SplitLIs)
1205       VRM.setIsSplitFromReg(SplitLI->reg, Original);
1206 
1207     // The new intervals all map back to i.
1208     if (LRMap)
1209       LRMap->resize(Edit->size(), i);
1210   }
1211 
1212   // Calculate spill weight and allocation hints for new intervals.
1213   Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI);
1214 
1215   assert(!LRMap || LRMap->size() == Edit->size());
1216 }
1217 
1218 
1219 //===----------------------------------------------------------------------===//
1220 //                            Single Block Splitting
1221 //===----------------------------------------------------------------------===//
1222 
1223 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
1224                                            bool SingleInstrs) const {
1225   // Always split for multiple instructions.
1226   if (!BI.isOneInstr())
1227     return true;
1228   // Don't split for single instructions unless explicitly requested.
1229   if (!SingleInstrs)
1230     return false;
1231   // Splitting a live-through range always makes progress.
1232   if (BI.LiveIn && BI.LiveOut)
1233     return true;
1234   // No point in isolating a copy. It has no register class constraints.
1235   if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
1236     return false;
1237   // Finally, don't isolate an end point that was created by earlier splits.
1238   return isOriginalEndpoint(BI.FirstInstr);
1239 }
1240 
1241 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
1242   openIntv();
1243   SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
1244   SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
1245     LastSplitPoint));
1246   if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
1247     useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
1248   } else {
1249       // The last use is after the last valid split point.
1250     SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
1251     useIntv(SegStart, SegStop);
1252     overlapIntv(SegStop, BI.LastInstr);
1253   }
1254 }
1255 
1256 
1257 //===----------------------------------------------------------------------===//
1258 //                    Global Live Range Splitting Support
1259 //===----------------------------------------------------------------------===//
1260 
1261 // These methods support a method of global live range splitting that uses a
1262 // global algorithm to decide intervals for CFG edges. They will insert split
1263 // points and color intervals in basic blocks while avoiding interference.
1264 //
1265 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1266 // are on the stack.
1267 
1268 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
1269                                         unsigned IntvIn, SlotIndex LeaveBefore,
1270                                         unsigned IntvOut, SlotIndex EnterAfter){
1271   SlotIndex Start, Stop;
1272   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
1273 
1274   DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
1275                << ") intf " << LeaveBefore << '-' << EnterAfter
1276                << ", live-through " << IntvIn << " -> " << IntvOut);
1277 
1278   assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
1279 
1280   assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
1281   assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
1282   assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
1283 
1284   MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
1285 
1286   if (!IntvOut) {
1287     DEBUG(dbgs() << ", spill on entry.\n");
1288     //
1289     //        <<<<<<<<<    Possible LeaveBefore interference.
1290     //    |-----------|    Live through.
1291     //    -____________    Spill on entry.
1292     //
1293     selectIntv(IntvIn);
1294     SlotIndex Idx = leaveIntvAtTop(*MBB);
1295     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1296     (void)Idx;
1297     return;
1298   }
1299 
1300   if (!IntvIn) {
1301     DEBUG(dbgs() << ", reload on exit.\n");
1302     //
1303     //    >>>>>>>          Possible EnterAfter interference.
1304     //    |-----------|    Live through.
1305     //    ___________--    Reload on exit.
1306     //
1307     selectIntv(IntvOut);
1308     SlotIndex Idx = enterIntvAtEnd(*MBB);
1309     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1310     (void)Idx;
1311     return;
1312   }
1313 
1314   if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
1315     DEBUG(dbgs() << ", straight through.\n");
1316     //
1317     //    |-----------|    Live through.
1318     //    -------------    Straight through, same intv, no interference.
1319     //
1320     selectIntv(IntvOut);
1321     useIntv(Start, Stop);
1322     return;
1323   }
1324 
1325   // We cannot legally insert splits after LSP.
1326   SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
1327   assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
1328 
1329   if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
1330                   LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
1331     DEBUG(dbgs() << ", switch avoiding interference.\n");
1332     //
1333     //    >>>>     <<<<    Non-overlapping EnterAfter/LeaveBefore interference.
1334     //    |-----------|    Live through.
1335     //    ------=======    Switch intervals between interference.
1336     //
1337     selectIntv(IntvOut);
1338     SlotIndex Idx;
1339     if (LeaveBefore && LeaveBefore < LSP) {
1340       Idx = enterIntvBefore(LeaveBefore);
1341       useIntv(Idx, Stop);
1342     } else {
1343       Idx = enterIntvAtEnd(*MBB);
1344     }
1345     selectIntv(IntvIn);
1346     useIntv(Start, Idx);
1347     assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1348     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1349     return;
1350   }
1351 
1352   DEBUG(dbgs() << ", create local intv for interference.\n");
1353   //
1354   //    >>><><><><<<<    Overlapping EnterAfter/LeaveBefore interference.
1355   //    |-----------|    Live through.
1356   //    ==---------==    Switch intervals before/after interference.
1357   //
1358   assert(LeaveBefore <= EnterAfter && "Missed case");
1359 
1360   selectIntv(IntvOut);
1361   SlotIndex Idx = enterIntvAfter(EnterAfter);
1362   useIntv(Idx, Stop);
1363   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1364 
1365   selectIntv(IntvIn);
1366   Idx = leaveIntvBefore(LeaveBefore);
1367   useIntv(Start, Idx);
1368   assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1369 }
1370 
1371 
1372 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
1373                                   unsigned IntvIn, SlotIndex LeaveBefore) {
1374   SlotIndex Start, Stop;
1375   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1376 
1377   DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
1378                << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1379                << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
1380                << (BI.LiveOut ? ", stack-out" : ", killed in block"));
1381 
1382   assert(IntvIn && "Must have register in");
1383   assert(BI.LiveIn && "Must be live-in");
1384   assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
1385 
1386   if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
1387     DEBUG(dbgs() << " before interference.\n");
1388     //
1389     //               <<<    Interference after kill.
1390     //     |---o---x   |    Killed in block.
1391     //     =========        Use IntvIn everywhere.
1392     //
1393     selectIntv(IntvIn);
1394     useIntv(Start, BI.LastInstr);
1395     return;
1396   }
1397 
1398   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1399 
1400   if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
1401     //
1402     //               <<<    Possible interference after last use.
1403     //     |---o---o---|    Live-out on stack.
1404     //     =========____    Leave IntvIn after last use.
1405     //
1406     //                 <    Interference after last use.
1407     //     |---o---o--o|    Live-out on stack, late last use.
1408     //     ============     Copy to stack after LSP, overlap IntvIn.
1409     //            \_____    Stack interval is live-out.
1410     //
1411     if (BI.LastInstr < LSP) {
1412       DEBUG(dbgs() << ", spill after last use before interference.\n");
1413       selectIntv(IntvIn);
1414       SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
1415       useIntv(Start, Idx);
1416       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1417     } else {
1418       DEBUG(dbgs() << ", spill before last split point.\n");
1419       selectIntv(IntvIn);
1420       SlotIndex Idx = leaveIntvBefore(LSP);
1421       overlapIntv(Idx, BI.LastInstr);
1422       useIntv(Start, Idx);
1423       assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1424     }
1425     return;
1426   }
1427 
1428   // The interference is overlapping somewhere we wanted to use IntvIn. That
1429   // means we need to create a local interval that can be allocated a
1430   // different register.
1431   unsigned LocalIntv = openIntv();
1432   (void)LocalIntv;
1433   DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
1434 
1435   if (!BI.LiveOut || BI.LastInstr < LSP) {
1436     //
1437     //           <<<<<<<    Interference overlapping uses.
1438     //     |---o---o---|    Live-out on stack.
1439     //     =====----____    Leave IntvIn before interference, then spill.
1440     //
1441     SlotIndex To = leaveIntvAfter(BI.LastInstr);
1442     SlotIndex From = enterIntvBefore(LeaveBefore);
1443     useIntv(From, To);
1444     selectIntv(IntvIn);
1445     useIntv(Start, From);
1446     assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1447     return;
1448   }
1449 
1450   //           <<<<<<<    Interference overlapping uses.
1451   //     |---o---o--o|    Live-out on stack, late last use.
1452   //     =====-------     Copy to stack before LSP, overlap LocalIntv.
1453   //            \_____    Stack interval is live-out.
1454   //
1455   SlotIndex To = leaveIntvBefore(LSP);
1456   overlapIntv(To, BI.LastInstr);
1457   SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
1458   useIntv(From, To);
1459   selectIntv(IntvIn);
1460   useIntv(Start, From);
1461   assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1462 }
1463 
1464 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
1465                                    unsigned IntvOut, SlotIndex EnterAfter) {
1466   SlotIndex Start, Stop;
1467   std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1468 
1469   DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
1470                << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1471                << ", reg-out " << IntvOut << ", enter after " << EnterAfter
1472                << (BI.LiveIn ? ", stack-in" : ", defined in block"));
1473 
1474   SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1475 
1476   assert(IntvOut && "Must have register out");
1477   assert(BI.LiveOut && "Must be live-out");
1478   assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
1479 
1480   if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
1481     DEBUG(dbgs() << " after interference.\n");
1482     //
1483     //    >>>>             Interference before def.
1484     //    |   o---o---|    Defined in block.
1485     //        =========    Use IntvOut everywhere.
1486     //
1487     selectIntv(IntvOut);
1488     useIntv(BI.FirstInstr, Stop);
1489     return;
1490   }
1491 
1492   if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
1493     DEBUG(dbgs() << ", reload after interference.\n");
1494     //
1495     //    >>>>             Interference before def.
1496     //    |---o---o---|    Live-through, stack-in.
1497     //    ____=========    Enter IntvOut before first use.
1498     //
1499     selectIntv(IntvOut);
1500     SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
1501     useIntv(Idx, Stop);
1502     assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1503     return;
1504   }
1505 
1506   // The interference is overlapping somewhere we wanted to use IntvOut. That
1507   // means we need to create a local interval that can be allocated a
1508   // different register.
1509   DEBUG(dbgs() << ", interference overlaps uses.\n");
1510   //
1511   //    >>>>>>>          Interference overlapping uses.
1512   //    |---o---o---|    Live-through, stack-in.
1513   //    ____---======    Create local interval for interference range.
1514   //
1515   selectIntv(IntvOut);
1516   SlotIndex Idx = enterIntvAfter(EnterAfter);
1517   useIntv(Idx, Stop);
1518   assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1519 
1520   openIntv();
1521   SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));
1522   useIntv(From, Idx);
1523 }
1524