1 //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
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 /// \file This file implements the LiveInterval analysis pass which is used
10 /// by the Linear Scan Register allocator. This pass linearizes the
11 /// basic blocks of the function in DFS order and computes live intervals for
12 /// each virtual and physical register.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/LiveIntervals.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/LiveInterval.h"
24 #include "llvm/CodeGen/LiveIntervalCalc.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBundle.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/SlotIndexes.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/CodeGen/VirtRegMap.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/MC/LaneBitmask.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/BlockFrequency.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <iterator>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "regalloc"
59 
60 char LiveIntervals::ID = 0;
61 char &llvm::LiveIntervalsID = LiveIntervals::ID;
62 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
63                 "Live Interval Analysis", false, false)
64 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
65 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
66 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
67 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
68                 "Live Interval Analysis", false, false)
69 
70 #ifndef NDEBUG
71 static cl::opt<bool> EnablePrecomputePhysRegs(
72   "precompute-phys-liveness", cl::Hidden,
73   cl::desc("Eagerly compute live intervals for all physreg units."));
74 #else
75 static bool EnablePrecomputePhysRegs = false;
76 #endif // NDEBUG
77 
78 namespace llvm {
79 
80 cl::opt<bool> UseSegmentSetForPhysRegs(
81     "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
82     cl::desc(
83         "Use segment set for the computation of the live ranges of physregs."));
84 
85 } // end namespace llvm
86 
87 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
88   AU.setPreservesCFG();
89   AU.addRequired<AAResultsWrapperPass>();
90   AU.addPreserved<AAResultsWrapperPass>();
91   AU.addPreserved<LiveVariables>();
92   AU.addPreservedID(MachineLoopInfoID);
93   AU.addRequiredTransitiveID(MachineDominatorsID);
94   AU.addPreservedID(MachineDominatorsID);
95   AU.addPreserved<SlotIndexes>();
96   AU.addRequiredTransitive<SlotIndexes>();
97   MachineFunctionPass::getAnalysisUsage(AU);
98 }
99 
100 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID) {
101   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
102 }
103 
104 LiveIntervals::~LiveIntervals() { delete LICalc; }
105 
106 void LiveIntervals::releaseMemory() {
107   // Free the live intervals themselves.
108   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
109     delete VirtRegIntervals[Register::index2VirtReg(i)];
110   VirtRegIntervals.clear();
111   RegMaskSlots.clear();
112   RegMaskBits.clear();
113   RegMaskBlocks.clear();
114 
115   for (LiveRange *LR : RegUnitRanges)
116     delete LR;
117   RegUnitRanges.clear();
118 
119   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
120   VNInfoAllocator.Reset();
121 }
122 
123 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
124   MF = &fn;
125   MRI = &MF->getRegInfo();
126   TRI = MF->getSubtarget().getRegisterInfo();
127   TII = MF->getSubtarget().getInstrInfo();
128   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
129   Indexes = &getAnalysis<SlotIndexes>();
130   DomTree = &getAnalysis<MachineDominatorTree>();
131 
132   if (!LICalc)
133     LICalc = new LiveIntervalCalc();
134 
135   // Allocate space for all virtual registers.
136   VirtRegIntervals.resize(MRI->getNumVirtRegs());
137 
138   computeVirtRegs();
139   computeRegMasks();
140   computeLiveInRegUnits();
141 
142   if (EnablePrecomputePhysRegs) {
143     // For stress testing, precompute live ranges of all physical register
144     // units, including reserved registers.
145     for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
146       getRegUnit(i);
147   }
148   LLVM_DEBUG(dump());
149   return true;
150 }
151 
152 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
153   OS << "********** INTERVALS **********\n";
154 
155   // Dump the regunits.
156   for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
157     if (LiveRange *LR = RegUnitRanges[Unit])
158       OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
159 
160   // Dump the virtregs.
161   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
162     unsigned Reg = Register::index2VirtReg(i);
163     if (hasInterval(Reg))
164       OS << getInterval(Reg) << '\n';
165   }
166 
167   OS << "RegMasks:";
168   for (SlotIndex Idx : RegMaskSlots)
169     OS << ' ' << Idx;
170   OS << '\n';
171 
172   printInstrs(OS);
173 }
174 
175 void LiveIntervals::printInstrs(raw_ostream &OS) const {
176   OS << "********** MACHINEINSTRS **********\n";
177   MF->print(OS, Indexes);
178 }
179 
180 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
181 LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
182   printInstrs(dbgs());
183 }
184 #endif
185 
186 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
187   float Weight = Register::isPhysicalRegister(reg) ? huge_valf : 0.0F;
188   return new LiveInterval(reg, Weight);
189 }
190 
191 /// Compute the live interval of a virtual register, based on defs and uses.
192 bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
193   assert(LICalc && "LICalc not initialized.");
194   assert(LI.empty() && "Should only compute empty intervals.");
195   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
196   LICalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
197   return computeDeadValues(LI, nullptr);
198 }
199 
200 void LiveIntervals::computeVirtRegs() {
201   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
202     unsigned Reg = Register::index2VirtReg(i);
203     if (MRI->reg_nodbg_empty(Reg))
204       continue;
205     LiveInterval &LI = createEmptyInterval(Reg);
206     bool NeedSplit = computeVirtRegInterval(LI);
207     if (NeedSplit) {
208       SmallVector<LiveInterval*, 8> SplitLIs;
209       splitSeparateComponents(LI, SplitLIs);
210     }
211   }
212 }
213 
214 void LiveIntervals::computeRegMasks() {
215   RegMaskBlocks.resize(MF->getNumBlockIDs());
216 
217   // Find all instructions with regmask operands.
218   for (const MachineBasicBlock &MBB : *MF) {
219     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
220     RMB.first = RegMaskSlots.size();
221 
222     // Some block starts, such as EH funclets, create masks.
223     if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
224       RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
225       RegMaskBits.push_back(Mask);
226     }
227 
228     for (const MachineInstr &MI : MBB) {
229       for (const MachineOperand &MO : MI.operands()) {
230         if (!MO.isRegMask())
231           continue;
232         RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
233         RegMaskBits.push_back(MO.getRegMask());
234       }
235     }
236 
237     // Some block ends, such as funclet returns, create masks. Put the mask on
238     // the last instruction of the block, because MBB slot index intervals are
239     // half-open.
240     if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
241       assert(!MBB.empty() && "empty return block?");
242       RegMaskSlots.push_back(
243           Indexes->getInstructionIndex(MBB.back()).getRegSlot());
244       RegMaskBits.push_back(Mask);
245     }
246 
247     // Compute the number of register mask instructions in this block.
248     RMB.second = RegMaskSlots.size() - RMB.first;
249   }
250 }
251 
252 //===----------------------------------------------------------------------===//
253 //                           Register Unit Liveness
254 //===----------------------------------------------------------------------===//
255 //
256 // Fixed interference typically comes from ABI boundaries: Function arguments
257 // and return values are passed in fixed registers, and so are exception
258 // pointers entering landing pads. Certain instructions require values to be
259 // present in specific registers. That is also represented through fixed
260 // interference.
261 //
262 
263 /// Compute the live range of a register unit, based on the uses and defs of
264 /// aliasing registers.  The range should be empty, or contain only dead
265 /// phi-defs from ABI blocks.
266 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
267   assert(LICalc && "LICalc not initialized.");
268   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
269 
270   // The physregs aliasing Unit are the roots and their super-registers.
271   // Create all values as dead defs before extending to uses. Note that roots
272   // may share super-registers. That's OK because createDeadDefs() is
273   // idempotent. It is very rare for a register unit to have multiple roots, so
274   // uniquing super-registers is probably not worthwhile.
275   bool IsReserved = false;
276   for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
277     bool IsRootReserved = true;
278     for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
279          Super.isValid(); ++Super) {
280       unsigned Reg = *Super;
281       if (!MRI->reg_empty(Reg))
282         LICalc->createDeadDefs(LR, Reg);
283       // A register unit is considered reserved if all its roots and all their
284       // super registers are reserved.
285       if (!MRI->isReserved(Reg))
286         IsRootReserved = false;
287     }
288     IsReserved |= IsRootReserved;
289   }
290   assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
291          "reserved computation mismatch");
292 
293   // Now extend LR to reach all uses.
294   // Ignore uses of reserved registers. We only track defs of those.
295   if (!IsReserved) {
296     for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
297       for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
298            Super.isValid(); ++Super) {
299         unsigned Reg = *Super;
300         if (!MRI->reg_empty(Reg))
301           LICalc->extendToUses(LR, Reg);
302       }
303     }
304   }
305 
306   // Flush the segment set to the segment vector.
307   if (UseSegmentSetForPhysRegs)
308     LR.flushSegmentSet();
309 }
310 
311 /// Precompute the live ranges of any register units that are live-in to an ABI
312 /// block somewhere. Register values can appear without a corresponding def when
313 /// entering the entry block or a landing pad.
314 void LiveIntervals::computeLiveInRegUnits() {
315   RegUnitRanges.resize(TRI->getNumRegUnits());
316   LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
317 
318   // Keep track of the live range sets allocated.
319   SmallVector<unsigned, 8> NewRanges;
320 
321   // Check all basic blocks for live-ins.
322   for (const MachineBasicBlock &MBB : *MF) {
323     // We only care about ABI blocks: Entry + landing pads.
324     if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
325       continue;
326 
327     // Create phi-defs at Begin for all live-in registers.
328     SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
329     LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
330     for (const auto &LI : MBB.liveins()) {
331       for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
332         unsigned Unit = *Units;
333         LiveRange *LR = RegUnitRanges[Unit];
334         if (!LR) {
335           // Use segment set to speed-up initial computation of the live range.
336           LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
337           NewRanges.push_back(Unit);
338         }
339         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
340         (void)VNI;
341         LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
342       }
343     }
344     LLVM_DEBUG(dbgs() << '\n');
345   }
346   LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
347 
348   // Compute the 'normal' part of the ranges.
349   for (unsigned Unit : NewRanges)
350     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
351 }
352 
353 static void createSegmentsForValues(LiveRange &LR,
354     iterator_range<LiveInterval::vni_iterator> VNIs) {
355   for (VNInfo *VNI : VNIs) {
356     if (VNI->isUnused())
357       continue;
358     SlotIndex Def = VNI->def;
359     LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
360   }
361 }
362 
363 void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
364                                          ShrinkToUsesWorkList &WorkList,
365                                          unsigned Reg, LaneBitmask LaneMask) {
366   // Keep track of the PHIs that are in use.
367   SmallPtrSet<VNInfo*, 8> UsedPHIs;
368   // Blocks that have already been added to WorkList as live-out.
369   SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
370 
371   auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
372         -> const LiveRange& {
373     if (M.none())
374       return I;
375     for (const LiveInterval::SubRange &SR : I.subranges()) {
376       if ((SR.LaneMask & M).any()) {
377         assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
378         return SR;
379       }
380     }
381     llvm_unreachable("Subrange for mask not found");
382   };
383 
384   const LiveInterval &LI = getInterval(Reg);
385   const LiveRange &OldRange = getSubRange(LI, LaneMask);
386 
387   // Extend intervals to reach all uses in WorkList.
388   while (!WorkList.empty()) {
389     SlotIndex Idx = WorkList.back().first;
390     VNInfo *VNI = WorkList.back().second;
391     WorkList.pop_back();
392     const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
393     SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
394 
395     // Extend the live range for VNI to be live at Idx.
396     if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
397       assert(ExtVNI == VNI && "Unexpected existing value number");
398       (void)ExtVNI;
399       // Is this a PHIDef we haven't seen before?
400       if (!VNI->isPHIDef() || VNI->def != BlockStart ||
401           !UsedPHIs.insert(VNI).second)
402         continue;
403       // The PHI is live, make sure the predecessors are live-out.
404       for (const MachineBasicBlock *Pred : MBB->predecessors()) {
405         if (!LiveOut.insert(Pred).second)
406           continue;
407         SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
408         // A predecessor is not required to have a live-out value for a PHI.
409         if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
410           WorkList.push_back(std::make_pair(Stop, PVNI));
411       }
412       continue;
413     }
414 
415     // VNI is live-in to MBB.
416     LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
417     Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
418 
419     // Make sure VNI is live-out from the predecessors.
420     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
421       if (!LiveOut.insert(Pred).second)
422         continue;
423       SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
424       if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
425         assert(OldVNI == VNI && "Wrong value out of predecessor");
426         (void)OldVNI;
427         WorkList.push_back(std::make_pair(Stop, VNI));
428       } else {
429 #ifndef NDEBUG
430         // There was no old VNI. Verify that Stop is jointly dominated
431         // by <undef>s for this live range.
432         assert(LaneMask.any() &&
433                "Missing value out of predecessor for main range");
434         SmallVector<SlotIndex,8> Undefs;
435         LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
436         assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
437                "Missing value out of predecessor for subrange");
438 #endif
439       }
440     }
441   }
442 }
443 
444 bool LiveIntervals::shrinkToUses(LiveInterval *li,
445                                  SmallVectorImpl<MachineInstr*> *dead) {
446   LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
447   assert(Register::isVirtualRegister(li->reg) &&
448          "Can only shrink virtual registers");
449 
450   // Shrink subregister live ranges.
451   bool NeedsCleanup = false;
452   for (LiveInterval::SubRange &S : li->subranges()) {
453     shrinkToUses(S, li->reg);
454     if (S.empty())
455       NeedsCleanup = true;
456   }
457   if (NeedsCleanup)
458     li->removeEmptySubRanges();
459 
460   // Find all the values used, including PHI kills.
461   ShrinkToUsesWorkList WorkList;
462 
463   // Visit all instructions reading li->reg.
464   unsigned Reg = li->reg;
465   for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
466     if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg))
467       continue;
468     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
469     LiveQueryResult LRQ = li->Query(Idx);
470     VNInfo *VNI = LRQ.valueIn();
471     if (!VNI) {
472       // This shouldn't happen: readsVirtualRegister returns true, but there is
473       // no live value. It is likely caused by a target getting <undef> flags
474       // wrong.
475       LLVM_DEBUG(
476           dbgs() << Idx << '\t' << UseMI
477                  << "Warning: Instr claims to read non-existent value in "
478                  << *li << '\n');
479       continue;
480     }
481     // Special case: An early-clobber tied operand reads and writes the
482     // register one slot early.
483     if (VNInfo *DefVNI = LRQ.valueDefined())
484       Idx = DefVNI->def;
485 
486     WorkList.push_back(std::make_pair(Idx, VNI));
487   }
488 
489   // Create new live ranges with only minimal live segments per def.
490   LiveRange NewLR;
491   createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
492   extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
493 
494   // Move the trimmed segments back.
495   li->segments.swap(NewLR.segments);
496 
497   // Handle dead values.
498   bool CanSeparate = computeDeadValues(*li, dead);
499   LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
500   return CanSeparate;
501 }
502 
503 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
504                                       SmallVectorImpl<MachineInstr*> *dead) {
505   bool MayHaveSplitComponents = false;
506   bool HaveDeadDef = false;
507 
508   for (VNInfo *VNI : LI.valnos) {
509     if (VNI->isUnused())
510       continue;
511     SlotIndex Def = VNI->def;
512     LiveRange::iterator I = LI.FindSegmentContaining(Def);
513     assert(I != LI.end() && "Missing segment for VNI");
514 
515     // Is the register live before? Otherwise we may have to add a read-undef
516     // flag for subregister defs.
517     unsigned VReg = LI.reg;
518     if (MRI->shouldTrackSubRegLiveness(VReg)) {
519       if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
520         MachineInstr *MI = getInstructionFromIndex(Def);
521         MI->setRegisterDefReadUndef(VReg);
522       }
523     }
524 
525     if (I->end != Def.getDeadSlot())
526       continue;
527     if (VNI->isPHIDef()) {
528       // This is a dead PHI. Remove it.
529       VNI->markUnused();
530       LI.removeSegment(I);
531       LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
532       MayHaveSplitComponents = true;
533     } else {
534       // This is a dead def. Make sure the instruction knows.
535       MachineInstr *MI = getInstructionFromIndex(Def);
536       assert(MI && "No instruction defining live value");
537       MI->addRegisterDead(LI.reg, TRI);
538       if (HaveDeadDef)
539         MayHaveSplitComponents = true;
540       HaveDeadDef = true;
541 
542       if (dead && MI->allDefsAreDead()) {
543         LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
544         dead->push_back(MI);
545       }
546     }
547   }
548   return MayHaveSplitComponents;
549 }
550 
551 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg) {
552   LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
553   assert(Register::isVirtualRegister(Reg) &&
554          "Can only shrink virtual registers");
555   // Find all the values used, including PHI kills.
556   ShrinkToUsesWorkList WorkList;
557 
558   // Visit all instructions reading Reg.
559   SlotIndex LastIdx;
560   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
561     // Skip "undef" uses.
562     if (!MO.readsReg())
563       continue;
564     // Maybe the operand is for a subregister we don't care about.
565     unsigned SubReg = MO.getSubReg();
566     if (SubReg != 0) {
567       LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
568       if ((LaneMask & SR.LaneMask).none())
569         continue;
570     }
571     // We only need to visit each instruction once.
572     MachineInstr *UseMI = MO.getParent();
573     SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
574     if (Idx == LastIdx)
575       continue;
576     LastIdx = Idx;
577 
578     LiveQueryResult LRQ = SR.Query(Idx);
579     VNInfo *VNI = LRQ.valueIn();
580     // For Subranges it is possible that only undef values are left in that
581     // part of the subregister, so there is no real liverange at the use
582     if (!VNI)
583       continue;
584 
585     // Special case: An early-clobber tied operand reads and writes the
586     // register one slot early.
587     if (VNInfo *DefVNI = LRQ.valueDefined())
588       Idx = DefVNI->def;
589 
590     WorkList.push_back(std::make_pair(Idx, VNI));
591   }
592 
593   // Create a new live ranges with only minimal live segments per def.
594   LiveRange NewLR;
595   createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
596   extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
597 
598   // Move the trimmed ranges back.
599   SR.segments.swap(NewLR.segments);
600 
601   // Remove dead PHI value numbers
602   for (VNInfo *VNI : SR.valnos) {
603     if (VNI->isUnused())
604       continue;
605     const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
606     assert(Segment != nullptr && "Missing segment for VNI");
607     if (Segment->end != VNI->def.getDeadSlot())
608       continue;
609     if (VNI->isPHIDef()) {
610       // This is a dead PHI. Remove it.
611       LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
612                         << " may separate interval\n");
613       VNI->markUnused();
614       SR.removeSegment(*Segment);
615     }
616   }
617 
618   LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
619 }
620 
621 void LiveIntervals::extendToIndices(LiveRange &LR,
622                                     ArrayRef<SlotIndex> Indices,
623                                     ArrayRef<SlotIndex> Undefs) {
624   assert(LICalc && "LICalc not initialized.");
625   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
626   for (SlotIndex Idx : Indices)
627     LICalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
628 }
629 
630 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
631                                SmallVectorImpl<SlotIndex> *EndPoints) {
632   LiveQueryResult LRQ = LR.Query(Kill);
633   VNInfo *VNI = LRQ.valueOutOrDead();
634   if (!VNI)
635     return;
636 
637   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
638   SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
639 
640   // If VNI isn't live out from KillMBB, the value is trivially pruned.
641   if (LRQ.endPoint() < MBBEnd) {
642     LR.removeSegment(Kill, LRQ.endPoint());
643     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
644     return;
645   }
646 
647   // VNI is live out of KillMBB.
648   LR.removeSegment(Kill, MBBEnd);
649   if (EndPoints) EndPoints->push_back(MBBEnd);
650 
651   // Find all blocks that are reachable from KillMBB without leaving VNI's live
652   // range. It is possible that KillMBB itself is reachable, so start a DFS
653   // from each successor.
654   using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
655   VisitedTy Visited;
656   for (MachineBasicBlock *Succ : KillMBB->successors()) {
657     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
658          I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
659          I != E;) {
660       MachineBasicBlock *MBB = *I;
661 
662       // Check if VNI is live in to MBB.
663       SlotIndex MBBStart, MBBEnd;
664       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
665       LiveQueryResult LRQ = LR.Query(MBBStart);
666       if (LRQ.valueIn() != VNI) {
667         // This block isn't part of the VNI segment. Prune the search.
668         I.skipChildren();
669         continue;
670       }
671 
672       // Prune the search if VNI is killed in MBB.
673       if (LRQ.endPoint() < MBBEnd) {
674         LR.removeSegment(MBBStart, LRQ.endPoint());
675         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
676         I.skipChildren();
677         continue;
678       }
679 
680       // VNI is live through MBB.
681       LR.removeSegment(MBBStart, MBBEnd);
682       if (EndPoints) EndPoints->push_back(MBBEnd);
683       ++I;
684     }
685   }
686 }
687 
688 //===----------------------------------------------------------------------===//
689 // Register allocator hooks.
690 //
691 
692 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
693   // Keep track of regunit ranges.
694   SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
695   // Keep track of subregister ranges.
696   SmallVector<std::pair<const LiveInterval::SubRange*,
697                         LiveRange::const_iterator>, 4> SRs;
698 
699   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
700     unsigned Reg = Register::index2VirtReg(i);
701     if (MRI->reg_nodbg_empty(Reg))
702       continue;
703     const LiveInterval &LI = getInterval(Reg);
704     if (LI.empty())
705       continue;
706 
707     // Find the regunit intervals for the assigned register. They may overlap
708     // the virtual register live range, cancelling any kills.
709     RU.clear();
710     for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid();
711          ++Unit) {
712       const LiveRange &RURange = getRegUnit(*Unit);
713       if (RURange.empty())
714         continue;
715       RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
716     }
717 
718     if (MRI->subRegLivenessEnabled()) {
719       SRs.clear();
720       for (const LiveInterval::SubRange &SR : LI.subranges()) {
721         SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
722       }
723     }
724 
725     // Every instruction that kills Reg corresponds to a segment range end
726     // point.
727     for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
728          ++RI) {
729       // A block index indicates an MBB edge.
730       if (RI->end.isBlock())
731         continue;
732       MachineInstr *MI = getInstructionFromIndex(RI->end);
733       if (!MI)
734         continue;
735 
736       // Check if any of the regunits are live beyond the end of RI. That could
737       // happen when a physreg is defined as a copy of a virtreg:
738       //
739       //   %eax = COPY %5
740       //   FOO %5             <--- MI, cancel kill because %eax is live.
741       //   BAR killed %eax
742       //
743       // There should be no kill flag on FOO when %5 is rewritten as %eax.
744       for (auto &RUP : RU) {
745         const LiveRange &RURange = *RUP.first;
746         LiveRange::const_iterator &I = RUP.second;
747         if (I == RURange.end())
748           continue;
749         I = RURange.advanceTo(I, RI->end);
750         if (I == RURange.end() || I->start >= RI->end)
751           continue;
752         // I is overlapping RI.
753         goto CancelKill;
754       }
755 
756       if (MRI->subRegLivenessEnabled()) {
757         // When reading a partial undefined value we must not add a kill flag.
758         // The regalloc might have used the undef lane for something else.
759         // Example:
760         //     %1 = ...                  ; R32: %1
761         //     %2:high16 = ...           ; R64: %2
762         //        = read killed %2        ; R64: %2
763         //        = read %1              ; R32: %1
764         // The <kill> flag is correct for %2, but the register allocator may
765         // assign R0L to %1, and R0 to %2 because the low 32bits of R0
766         // are actually never written by %2. After assignment the <kill>
767         // flag at the read instruction is invalid.
768         LaneBitmask DefinedLanesMask;
769         if (!SRs.empty()) {
770           // Compute a mask of lanes that are defined.
771           DefinedLanesMask = LaneBitmask::getNone();
772           for (auto &SRP : SRs) {
773             const LiveInterval::SubRange &SR = *SRP.first;
774             LiveRange::const_iterator &I = SRP.second;
775             if (I == SR.end())
776               continue;
777             I = SR.advanceTo(I, RI->end);
778             if (I == SR.end() || I->start >= RI->end)
779               continue;
780             // I is overlapping RI
781             DefinedLanesMask |= SR.LaneMask;
782           }
783         } else
784           DefinedLanesMask = LaneBitmask::getAll();
785 
786         bool IsFullWrite = false;
787         for (const MachineOperand &MO : MI->operands()) {
788           if (!MO.isReg() || MO.getReg() != Reg)
789             continue;
790           if (MO.isUse()) {
791             // Reading any undefined lanes?
792             LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
793             if ((UseMask & ~DefinedLanesMask).any())
794               goto CancelKill;
795           } else if (MO.getSubReg() == 0) {
796             // Writing to the full register?
797             assert(MO.isDef());
798             IsFullWrite = true;
799           }
800         }
801 
802         // If an instruction writes to a subregister, a new segment starts in
803         // the LiveInterval. But as this is only overriding part of the register
804         // adding kill-flags is not correct here after registers have been
805         // assigned.
806         if (!IsFullWrite) {
807           // Next segment has to be adjacent in the subregister write case.
808           LiveRange::const_iterator N = std::next(RI);
809           if (N != LI.end() && N->start == RI->end)
810             goto CancelKill;
811         }
812       }
813 
814       MI->addRegisterKilled(Reg, nullptr);
815       continue;
816 CancelKill:
817       MI->clearRegisterKills(Reg, nullptr);
818     }
819   }
820 }
821 
822 MachineBasicBlock*
823 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
824   // A local live range must be fully contained inside the block, meaning it is
825   // defined and killed at instructions, not at block boundaries. It is not
826   // live in or out of any block.
827   //
828   // It is technically possible to have a PHI-defined live range identical to a
829   // single block, but we are going to return false in that case.
830 
831   SlotIndex Start = LI.beginIndex();
832   if (Start.isBlock())
833     return nullptr;
834 
835   SlotIndex Stop = LI.endIndex();
836   if (Stop.isBlock())
837     return nullptr;
838 
839   // getMBBFromIndex doesn't need to search the MBB table when both indexes
840   // belong to proper instructions.
841   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
842   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
843   return MBB1 == MBB2 ? MBB1 : nullptr;
844 }
845 
846 bool
847 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
848   for (const VNInfo *PHI : LI.valnos) {
849     if (PHI->isUnused() || !PHI->isPHIDef())
850       continue;
851     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
852     // Conservatively return true instead of scanning huge predecessor lists.
853     if (PHIMBB->pred_size() > 100)
854       return true;
855     for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
856       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
857         return true;
858   }
859   return false;
860 }
861 
862 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
863                                     const MachineBlockFrequencyInfo *MBFI,
864                                     const MachineInstr &MI) {
865   return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
866 }
867 
868 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
869                                     const MachineBlockFrequencyInfo *MBFI,
870                                     const MachineBasicBlock *MBB) {
871   BlockFrequency Freq = MBFI->getBlockFreq(MBB);
872   const float Scale = 1.0f / MBFI->getEntryFreq();
873   return (isDef + isUse) * (Freq.getFrequency() * Scale);
874 }
875 
876 LiveRange::Segment
877 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) {
878   LiveInterval& Interval = createEmptyInterval(reg);
879   VNInfo *VN = Interval.getNextValue(
880       SlotIndex(getInstructionIndex(startInst).getRegSlot()),
881       getVNInfoAllocator());
882   LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
883                        getMBBEndIdx(startInst.getParent()), VN);
884   Interval.addSegment(S);
885 
886   return S;
887 }
888 
889 //===----------------------------------------------------------------------===//
890 //                          Register mask functions
891 //===----------------------------------------------------------------------===//
892 
893 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
894                                              BitVector &UsableRegs) {
895   if (LI.empty())
896     return false;
897   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
898 
899   // Use a smaller arrays for local live ranges.
900   ArrayRef<SlotIndex> Slots;
901   ArrayRef<const uint32_t*> Bits;
902   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
903     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
904     Bits = getRegMaskBitsInBlock(MBB->getNumber());
905   } else {
906     Slots = getRegMaskSlots();
907     Bits = getRegMaskBits();
908   }
909 
910   // We are going to enumerate all the register mask slots contained in LI.
911   // Start with a binary search of RegMaskSlots to find a starting point.
912   ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
913   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
914 
915   // No slots in range, LI begins after the last call.
916   if (SlotI == SlotE)
917     return false;
918 
919   bool Found = false;
920   while (true) {
921     assert(*SlotI >= LiveI->start);
922     // Loop over all slots overlapping this segment.
923     while (*SlotI < LiveI->end) {
924       // *SlotI overlaps LI. Collect mask bits.
925       if (!Found) {
926         // This is the first overlap. Initialize UsableRegs to all ones.
927         UsableRegs.clear();
928         UsableRegs.resize(TRI->getNumRegs(), true);
929         Found = true;
930       }
931       // Remove usable registers clobbered by this mask.
932       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
933       if (++SlotI == SlotE)
934         return Found;
935     }
936     // *SlotI is beyond the current LI segment.
937     LiveI = LI.advanceTo(LiveI, *SlotI);
938     if (LiveI == LiveE)
939       return Found;
940     // Advance SlotI until it overlaps.
941     while (*SlotI < LiveI->start)
942       if (++SlotI == SlotE)
943         return Found;
944   }
945 }
946 
947 //===----------------------------------------------------------------------===//
948 //                         IntervalUpdate class.
949 //===----------------------------------------------------------------------===//
950 
951 /// Toolkit used by handleMove to trim or extend live intervals.
952 class LiveIntervals::HMEditor {
953 private:
954   LiveIntervals& LIS;
955   const MachineRegisterInfo& MRI;
956   const TargetRegisterInfo& TRI;
957   SlotIndex OldIdx;
958   SlotIndex NewIdx;
959   SmallPtrSet<LiveRange*, 8> Updated;
960   bool UpdateFlags;
961 
962 public:
963   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
964            const TargetRegisterInfo& TRI,
965            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
966     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
967       UpdateFlags(UpdateFlags) {}
968 
969   // FIXME: UpdateFlags is a workaround that creates live intervals for all
970   // physregs, even those that aren't needed for regalloc, in order to update
971   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
972   // flags, and postRA passes will use a live register utility instead.
973   LiveRange *getRegUnitLI(unsigned Unit) {
974     if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
975       return &LIS.getRegUnit(Unit);
976     return LIS.getCachedRegUnit(Unit);
977   }
978 
979   /// Update all live ranges touched by MI, assuming a move from OldIdx to
980   /// NewIdx.
981   void updateAllRanges(MachineInstr *MI) {
982     LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
983                       << *MI);
984     bool hasRegMask = false;
985     for (MachineOperand &MO : MI->operands()) {
986       if (MO.isRegMask())
987         hasRegMask = true;
988       if (!MO.isReg())
989         continue;
990       if (MO.isUse()) {
991         if (!MO.readsReg())
992           continue;
993         // Aggressively clear all kill flags.
994         // They are reinserted by VirtRegRewriter.
995         MO.setIsKill(false);
996       }
997 
998       Register Reg = MO.getReg();
999       if (!Reg)
1000         continue;
1001       if (Register::isVirtualRegister(Reg)) {
1002         LiveInterval &LI = LIS.getInterval(Reg);
1003         if (LI.hasSubRanges()) {
1004           unsigned SubReg = MO.getSubReg();
1005           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1006                                         : MRI.getMaxLaneMaskForVReg(Reg);
1007           for (LiveInterval::SubRange &S : LI.subranges()) {
1008             if ((S.LaneMask & LaneMask).none())
1009               continue;
1010             updateRange(S, Reg, S.LaneMask);
1011           }
1012         }
1013         updateRange(LI, Reg, LaneBitmask::getNone());
1014         continue;
1015       }
1016 
1017       // For physregs, only update the regunits that actually have a
1018       // precomputed live range.
1019       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
1020         if (LiveRange *LR = getRegUnitLI(*Units))
1021           updateRange(*LR, *Units, LaneBitmask::getNone());
1022     }
1023     if (hasRegMask)
1024       updateRegMaskSlots();
1025   }
1026 
1027 private:
1028   /// Update a single live range, assuming an instruction has been moved from
1029   /// OldIdx to NewIdx.
1030   void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1031     if (!Updated.insert(&LR).second)
1032       return;
1033     LLVM_DEBUG({
1034       dbgs() << "     ";
1035       if (Register::isVirtualRegister(Reg)) {
1036         dbgs() << printReg(Reg);
1037         if (LaneMask.any())
1038           dbgs() << " L" << PrintLaneMask(LaneMask);
1039       } else {
1040         dbgs() << printRegUnit(Reg, &TRI);
1041       }
1042       dbgs() << ":\t" << LR << '\n';
1043     });
1044     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1045       handleMoveDown(LR);
1046     else
1047       handleMoveUp(LR, Reg, LaneMask);
1048     LLVM_DEBUG(dbgs() << "        -->\t" << LR << '\n');
1049     LR.verify();
1050   }
1051 
1052   /// Update LR to reflect an instruction has been moved downwards from OldIdx
1053   /// to NewIdx (OldIdx < NewIdx).
1054   void handleMoveDown(LiveRange &LR) {
1055     LiveRange::iterator E = LR.end();
1056     // Segment going into OldIdx.
1057     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1058 
1059     // No value live before or after OldIdx? Nothing to do.
1060     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1061       return;
1062 
1063     LiveRange::iterator OldIdxOut;
1064     // Do we have a value live-in to OldIdx?
1065     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1066       // If the live-in value already extends to NewIdx, there is nothing to do.
1067       if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1068         return;
1069       // Aggressively remove all kill flags from the old kill point.
1070       // Kill flags shouldn't be used while live intervals exist, they will be
1071       // reinserted by VirtRegRewriter.
1072       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1073         for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1074           if (MOP.isReg() && MOP.isUse())
1075             MOP.setIsKill(false);
1076 
1077       // Is there a def before NewIdx which is not OldIdx?
1078       LiveRange::iterator Next = std::next(OldIdxIn);
1079       if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1080           SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1081         // If we are here then OldIdx was just a use but not a def. We only have
1082         // to ensure liveness extends to NewIdx.
1083         LiveRange::iterator NewIdxIn =
1084           LR.advanceTo(Next, NewIdx.getBaseIndex());
1085         // Extend the segment before NewIdx if necessary.
1086         if (NewIdxIn == E ||
1087             !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1088           LiveRange::iterator Prev = std::prev(NewIdxIn);
1089           Prev->end = NewIdx.getRegSlot();
1090         }
1091         // Extend OldIdxIn.
1092         OldIdxIn->end = Next->start;
1093         return;
1094       }
1095 
1096       // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1097       // invalid by overlapping ranges.
1098       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1099       OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1100       // If this was not a kill, then there was no def and we're done.
1101       if (!isKill)
1102         return;
1103 
1104       // Did we have a Def at OldIdx?
1105       OldIdxOut = Next;
1106       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1107         return;
1108     } else {
1109       OldIdxOut = OldIdxIn;
1110     }
1111 
1112     // If we are here then there is a Definition at OldIdx. OldIdxOut points
1113     // to the segment starting there.
1114     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1115            "No def?");
1116     VNInfo *OldIdxVNI = OldIdxOut->valno;
1117     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1118 
1119     // If the defined value extends beyond NewIdx, just move the beginning
1120     // of the segment to NewIdx.
1121     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1122     if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1123       OldIdxVNI->def = NewIdxDef;
1124       OldIdxOut->start = OldIdxVNI->def;
1125       return;
1126     }
1127 
1128     // If we are here then we have a Definition at OldIdx which ends before
1129     // NewIdx.
1130 
1131     // Is there an existing Def at NewIdx?
1132     LiveRange::iterator AfterNewIdx
1133       = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
1134     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1135     if (!OldIdxDefIsDead &&
1136         SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1137       // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1138       VNInfo *DefVNI;
1139       if (OldIdxOut != LR.begin() &&
1140           !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1141                                      OldIdxOut->start)) {
1142         // There is no gap between OldIdxOut and its predecessor anymore,
1143         // merge them.
1144         LiveRange::iterator IPrev = std::prev(OldIdxOut);
1145         DefVNI = OldIdxVNI;
1146         IPrev->end = OldIdxOut->end;
1147       } else {
1148         // The value is live in to OldIdx
1149         LiveRange::iterator INext = std::next(OldIdxOut);
1150         assert(INext != E && "Must have following segment");
1151         // We merge OldIdxOut and its successor. As we're dealing with subreg
1152         // reordering, there is always a successor to OldIdxOut in the same BB
1153         // We don't need INext->valno anymore and will reuse for the new segment
1154         // we create later.
1155         DefVNI = OldIdxVNI;
1156         INext->start = OldIdxOut->end;
1157         INext->valno->def = INext->start;
1158       }
1159       // If NewIdx is behind the last segment, extend that and append a new one.
1160       if (AfterNewIdx == E) {
1161         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1162         // one position.
1163         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1164         // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1165         std::copy(std::next(OldIdxOut), E, OldIdxOut);
1166         // The last segment is undefined now, reuse it for a dead def.
1167         LiveRange::iterator NewSegment = std::prev(E);
1168         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1169                                          DefVNI);
1170         DefVNI->def = NewIdxDef;
1171 
1172         LiveRange::iterator Prev = std::prev(NewSegment);
1173         Prev->end = NewIdxDef;
1174       } else {
1175         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1176         // one position.
1177         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1178         // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1179         std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1180         LiveRange::iterator Prev = std::prev(AfterNewIdx);
1181         // We have two cases:
1182         if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1183           // Case 1: NewIdx is inside a liverange. Split this liverange at
1184           // NewIdxDef into the segment "Prev" followed by "NewSegment".
1185           LiveRange::iterator NewSegment = AfterNewIdx;
1186           *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1187           Prev->valno->def = NewIdxDef;
1188 
1189           *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1190           DefVNI->def = Prev->start;
1191         } else {
1192           // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1193           // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1194           *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1195           DefVNI->def = NewIdxDef;
1196           assert(DefVNI != AfterNewIdx->valno);
1197         }
1198       }
1199       return;
1200     }
1201 
1202     if (AfterNewIdx != E &&
1203         SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1204       // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1205       // that value.
1206       assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1207       LR.removeValNo(OldIdxVNI);
1208     } else {
1209       // There was no existing def at NewIdx. We need to create a dead def
1210       // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1211       // a new segment at the place where we want to construct the dead def.
1212       //    |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1213       // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1214       assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1215       std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1216       // We can reuse OldIdxVNI now.
1217       LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1218       VNInfo *NewSegmentVNI = OldIdxVNI;
1219       NewSegmentVNI->def = NewIdxDef;
1220       *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1221                                        NewSegmentVNI);
1222     }
1223   }
1224 
1225   /// Update LR to reflect an instruction has been moved upwards from OldIdx
1226   /// to NewIdx (NewIdx < OldIdx).
1227   void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1228     LiveRange::iterator E = LR.end();
1229     // Segment going into OldIdx.
1230     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1231 
1232     // No value live before or after OldIdx? Nothing to do.
1233     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1234       return;
1235 
1236     LiveRange::iterator OldIdxOut;
1237     // Do we have a value live-in to OldIdx?
1238     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1239       // If the live-in value isn't killed here, then we have no Def at
1240       // OldIdx, moreover the value must be live at NewIdx so there is nothing
1241       // to do.
1242       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1243       if (!isKill)
1244         return;
1245 
1246       // At this point we have to move OldIdxIn->end back to the nearest
1247       // previous use or (dead-)def but no further than NewIdx.
1248       SlotIndex DefBeforeOldIdx
1249         = std::max(OldIdxIn->start.getDeadSlot(),
1250                    NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1251       OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
1252 
1253       // Did we have a Def at OldIdx? If not we are done now.
1254       OldIdxOut = std::next(OldIdxIn);
1255       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1256         return;
1257     } else {
1258       OldIdxOut = OldIdxIn;
1259       OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
1260     }
1261 
1262     // If we are here then there is a Definition at OldIdx. OldIdxOut points
1263     // to the segment starting there.
1264     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1265            "No def?");
1266     VNInfo *OldIdxVNI = OldIdxOut->valno;
1267     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1268     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1269 
1270     // Is there an existing def at NewIdx?
1271     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1272     LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1273     if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1274       assert(NewIdxOut->valno != OldIdxVNI &&
1275              "Same value defined more than once?");
1276       // If OldIdx was a dead def remove it.
1277       if (!OldIdxDefIsDead) {
1278         // Remove segment starting at NewIdx and move begin of OldIdxOut to
1279         // NewIdx so it can take its place.
1280         OldIdxVNI->def = NewIdxDef;
1281         OldIdxOut->start = NewIdxDef;
1282         LR.removeValNo(NewIdxOut->valno);
1283       } else {
1284         // Simply remove the dead def at OldIdx.
1285         LR.removeValNo(OldIdxVNI);
1286       }
1287     } else {
1288       // Previously nothing was live after NewIdx, so all we have to do now is
1289       // move the begin of OldIdxOut to NewIdx.
1290       if (!OldIdxDefIsDead) {
1291         // Do we have any intermediate Defs between OldIdx and NewIdx?
1292         if (OldIdxIn != E &&
1293             SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1294           // OldIdx is not a dead def and NewIdx is before predecessor start.
1295           LiveRange::iterator NewIdxIn = NewIdxOut;
1296           assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1297           const SlotIndex SplitPos = NewIdxDef;
1298           OldIdxVNI = OldIdxIn->valno;
1299 
1300           SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
1301           LiveRange::iterator Prev = std::prev(OldIdxIn);
1302           if (OldIdxIn != LR.begin() &&
1303               SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
1304             // If the segment before OldIdx read a value defined earlier than
1305             // NewIdx, the moved instruction also reads and forwards that
1306             // value. Extend the lifetime of the new def point.
1307 
1308             // Extend to where the previous range started, unless there is
1309             // another redef first.
1310             NewDefEndPoint = std::min(OldIdxIn->start,
1311                                       std::next(NewIdxOut)->start);
1312           }
1313 
1314           // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1315           OldIdxOut->valno->def = OldIdxIn->start;
1316           *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1317                                           OldIdxOut->valno);
1318           // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1319           // We Slide [NewIdxIn, OldIdxIn) down one position.
1320           //    |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1321           // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1322           std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1323           // NewIdxIn is now considered undef so we can reuse it for the moved
1324           // value.
1325           LiveRange::iterator NewSegment = NewIdxIn;
1326           LiveRange::iterator Next = std::next(NewSegment);
1327           if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1328             // There is no gap between NewSegment and its predecessor.
1329             *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1330                                              Next->valno);
1331 
1332             *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
1333             Next->valno->def = SplitPos;
1334           } else {
1335             // There is a gap between NewSegment and its predecessor
1336             // Value becomes live in.
1337             *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1338             NewSegment->valno->def = SplitPos;
1339           }
1340         } else {
1341           // Leave the end point of a live def.
1342           OldIdxOut->start = NewIdxDef;
1343           OldIdxVNI->def = NewIdxDef;
1344           if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1345             OldIdxIn->end = NewIdx.getRegSlot();
1346         }
1347       } else if (OldIdxIn != E
1348           && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1349           && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1350         // OldIdxVNI is a dead def that has been moved into the middle of
1351         // another value in LR. That can happen when LR is a whole register,
1352         // but the dead def is a write to a subreg that is dead at NewIdx.
1353         // The dead def may have been moved across other values
1354         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1355         // down one position.
1356         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1357         // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1358         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1359         // Modify the segment at NewIdxOut and the following segment to meet at
1360         // the point of the dead def, with the following segment getting
1361         // OldIdxVNI as its value number.
1362         *NewIdxOut = LiveRange::Segment(
1363             NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1364         *(NewIdxOut + 1) = LiveRange::Segment(
1365             NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1366         OldIdxVNI->def = NewIdxDef;
1367         // Modify subsequent segments to be defined by the moved def OldIdxVNI.
1368         for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
1369           Idx->valno = OldIdxVNI;
1370         // Aggressively remove all dead flags from the former dead definition.
1371         // Kill/dead flags shouldn't be used while live intervals exist; they
1372         // will be reinserted by VirtRegRewriter.
1373         if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1374           for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1375             if (MO->isReg() && !MO->isUse())
1376               MO->setIsDead(false);
1377       } else {
1378         // OldIdxVNI is a dead def. It may have been moved across other values
1379         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1380         // down one position.
1381         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1382         // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1383         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1384         // OldIdxVNI can be reused now to build a new dead def segment.
1385         LiveRange::iterator NewSegment = NewIdxOut;
1386         VNInfo *NewSegmentVNI = OldIdxVNI;
1387         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1388                                          NewSegmentVNI);
1389         NewSegmentVNI->def = NewIdxDef;
1390       }
1391     }
1392   }
1393 
1394   void updateRegMaskSlots() {
1395     SmallVectorImpl<SlotIndex>::iterator RI =
1396         llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
1397     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1398            "No RegMask at OldIdx.");
1399     *RI = NewIdx.getRegSlot();
1400     assert((RI == LIS.RegMaskSlots.begin() ||
1401             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1402            "Cannot move regmask instruction above another call");
1403     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1404             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1405            "Cannot move regmask instruction below another call");
1406   }
1407 
1408   // Return the last use of reg between NewIdx and OldIdx.
1409   SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
1410                               LaneBitmask LaneMask) {
1411     if (Register::isVirtualRegister(Reg)) {
1412       SlotIndex LastUse = Before;
1413       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1414         if (MO.isUndef())
1415           continue;
1416         unsigned SubReg = MO.getSubReg();
1417         if (SubReg != 0 && LaneMask.any()
1418             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
1419           continue;
1420 
1421         const MachineInstr &MI = *MO.getParent();
1422         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1423         if (InstSlot > LastUse && InstSlot < OldIdx)
1424           LastUse = InstSlot.getRegSlot();
1425       }
1426       return LastUse;
1427     }
1428 
1429     // This is a regunit interval, so scanning the use list could be very
1430     // expensive. Scan upwards from OldIdx instead.
1431     assert(Before < OldIdx && "Expected upwards move");
1432     SlotIndexes *Indexes = LIS.getSlotIndexes();
1433     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
1434 
1435     // OldIdx may not correspond to an instruction any longer, so set MII to
1436     // point to the next instruction after OldIdx, or MBB->end().
1437     MachineBasicBlock::iterator MII = MBB->end();
1438     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1439                            Indexes->getNextNonNullIndex(OldIdx)))
1440       if (MI->getParent() == MBB)
1441         MII = MI;
1442 
1443     MachineBasicBlock::iterator Begin = MBB->begin();
1444     while (MII != Begin) {
1445       if ((--MII)->isDebugInstr())
1446         continue;
1447       SlotIndex Idx = Indexes->getInstructionIndex(*MII);
1448 
1449       // Stop searching when Before is reached.
1450       if (!SlotIndex::isEarlierInstr(Before, Idx))
1451         return Before;
1452 
1453       // Check if MII uses Reg.
1454       for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1455         if (MO->isReg() && !MO->isUndef() &&
1456             Register::isPhysicalRegister(MO->getReg()) &&
1457             TRI.hasRegUnit(MO->getReg(), Reg))
1458           return Idx.getRegSlot();
1459     }
1460     // Didn't reach Before. It must be the first instruction in the block.
1461     return Before;
1462   }
1463 };
1464 
1465 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
1466   // It is fine to move a bundle as a whole, but not an individual instruction
1467   // inside it.
1468   assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
1469          "Cannot move instruction in bundle");
1470   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1471   Indexes->removeMachineInstrFromMaps(MI);
1472   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1473   assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1474          OldIndex < getMBBEndIdx(MI.getParent()) &&
1475          "Cannot handle moves across basic block boundaries.");
1476 
1477   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1478   HME.updateAllRanges(&MI);
1479 }
1480 
1481 void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart,
1482                                             bool UpdateFlags) {
1483   assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
1484          "Bundle start is not a bundle");
1485   SmallVector<SlotIndex, 16> ToProcess;
1486   const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart);
1487   auto BundleEnd = getBundleEnd(BundleStart.getIterator());
1488 
1489   auto I = BundleStart.getIterator();
1490   I++;
1491   while (I != BundleEnd) {
1492     if (!Indexes->hasIndex(*I))
1493       continue;
1494     SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true);
1495     ToProcess.push_back(OldIndex);
1496     Indexes->removeMachineInstrFromMaps(*I, true);
1497     I++;
1498   }
1499   for (SlotIndex OldIndex : ToProcess) {
1500     HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1501     HME.updateAllRanges(&BundleStart);
1502   }
1503 
1504   // Fix up dead defs
1505   const SlotIndex Index = getInstructionIndex(BundleStart);
1506   for (unsigned Idx = 0, E = BundleStart.getNumOperands(); Idx != E; ++Idx) {
1507     MachineOperand &MO = BundleStart.getOperand(Idx);
1508     if (!MO.isReg())
1509       continue;
1510     Register Reg = MO.getReg();
1511     if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
1512       LiveInterval &LI = getInterval(Reg);
1513       LiveQueryResult LRQ = LI.Query(Index);
1514       if (LRQ.isDeadDef())
1515         MO.setIsDead();
1516     }
1517   }
1518 }
1519 
1520 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1521                                         const MachineBasicBlock::iterator End,
1522                                         const SlotIndex endIdx,
1523                                         LiveRange &LR, const unsigned Reg,
1524                                         LaneBitmask LaneMask) {
1525   LiveInterval::iterator LII = LR.find(endIdx);
1526   SlotIndex lastUseIdx;
1527   if (LII == LR.begin()) {
1528     // This happens when the function is called for a subregister that only
1529     // occurs _after_ the range that is to be repaired.
1530     return;
1531   }
1532   if (LII != LR.end() && LII->start < endIdx)
1533     lastUseIdx = LII->end;
1534   else
1535     --LII;
1536 
1537   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1538     --I;
1539     MachineInstr &MI = *I;
1540     if (MI.isDebugInstr())
1541       continue;
1542 
1543     SlotIndex instrIdx = getInstructionIndex(MI);
1544     bool isStartValid = getInstructionFromIndex(LII->start);
1545     bool isEndValid = getInstructionFromIndex(LII->end);
1546 
1547     // FIXME: This doesn't currently handle early-clobber or multiple removed
1548     // defs inside of the region to repair.
1549     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
1550                                     OE = MI.operands_end();
1551          OI != OE; ++OI) {
1552       const MachineOperand &MO = *OI;
1553       if (!MO.isReg() || MO.getReg() != Reg)
1554         continue;
1555 
1556       unsigned SubReg = MO.getSubReg();
1557       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1558       if ((Mask & LaneMask).none())
1559         continue;
1560 
1561       if (MO.isDef()) {
1562         if (!isStartValid) {
1563           if (LII->end.isDead()) {
1564             SlotIndex prevStart;
1565             if (LII != LR.begin())
1566               prevStart = std::prev(LII)->start;
1567 
1568             // FIXME: This could be more efficient if there was a
1569             // removeSegment method that returned an iterator.
1570             LR.removeSegment(*LII, true);
1571             if (prevStart.isValid())
1572               LII = LR.find(prevStart);
1573             else
1574               LII = LR.begin();
1575           } else {
1576             LII->start = instrIdx.getRegSlot();
1577             LII->valno->def = instrIdx.getRegSlot();
1578             if (MO.getSubReg() && !MO.isUndef())
1579               lastUseIdx = instrIdx.getRegSlot();
1580             else
1581               lastUseIdx = SlotIndex();
1582             continue;
1583           }
1584         }
1585 
1586         if (!lastUseIdx.isValid()) {
1587           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1588           LiveRange::Segment S(instrIdx.getRegSlot(),
1589                                instrIdx.getDeadSlot(), VNI);
1590           LII = LR.addSegment(S);
1591         } else if (LII->start != instrIdx.getRegSlot()) {
1592           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1593           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1594           LII = LR.addSegment(S);
1595         }
1596 
1597         if (MO.getSubReg() && !MO.isUndef())
1598           lastUseIdx = instrIdx.getRegSlot();
1599         else
1600           lastUseIdx = SlotIndex();
1601       } else if (MO.isUse()) {
1602         // FIXME: This should probably be handled outside of this branch,
1603         // either as part of the def case (for defs inside of the region) or
1604         // after the loop over the region.
1605         if (!isEndValid && !LII->end.isBlock())
1606           LII->end = instrIdx.getRegSlot();
1607         if (!lastUseIdx.isValid())
1608           lastUseIdx = instrIdx.getRegSlot();
1609       }
1610     }
1611   }
1612 }
1613 
1614 void
1615 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1616                                       MachineBasicBlock::iterator Begin,
1617                                       MachineBasicBlock::iterator End,
1618                                       ArrayRef<Register> OrigRegs) {
1619   // Find anchor points, which are at the beginning/end of blocks or at
1620   // instructions that already have indexes.
1621   while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
1622     --Begin;
1623   while (End != MBB->end() && !Indexes->hasIndex(*End))
1624     ++End;
1625 
1626   SlotIndex endIdx;
1627   if (End == MBB->end())
1628     endIdx = getMBBEndIdx(MBB).getPrevSlot();
1629   else
1630     endIdx = getInstructionIndex(*End);
1631 
1632   Indexes->repairIndexesInRange(MBB, Begin, End);
1633 
1634   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1635     --I;
1636     MachineInstr &MI = *I;
1637     if (MI.isDebugInstr())
1638       continue;
1639     for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1640                                           MOE = MI.operands_end();
1641          MOI != MOE; ++MOI) {
1642       if (MOI->isReg() && Register::isVirtualRegister(MOI->getReg()) &&
1643           !hasInterval(MOI->getReg())) {
1644         createAndComputeVirtRegInterval(MOI->getReg());
1645       }
1646     }
1647   }
1648 
1649   for (Register Reg : OrigRegs) {
1650     if (!Reg.isVirtual())
1651       continue;
1652 
1653     LiveInterval &LI = getInterval(Reg);
1654     // FIXME: Should we support undefs that gain defs?
1655     if (!LI.hasAtLeastOneValue())
1656       continue;
1657 
1658     for (LiveInterval::SubRange &S : LI.subranges())
1659       repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1660 
1661     repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1662   }
1663 }
1664 
1665 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1666   for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
1667     if (LiveRange *LR = getCachedRegUnit(*Unit))
1668       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1669         LR->removeValNo(VNI);
1670   }
1671 }
1672 
1673 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1674   // LI may not have the main range computed yet, but its subranges may
1675   // be present.
1676   VNInfo *VNI = LI.getVNInfoAt(Pos);
1677   if (VNI != nullptr) {
1678     assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1679     LI.removeValNo(VNI);
1680   }
1681 
1682   // Also remove the value defined in subranges.
1683   for (LiveInterval::SubRange &S : LI.subranges()) {
1684     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1685       if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1686         S.removeValNo(SVNI);
1687   }
1688   LI.removeEmptySubRanges();
1689 }
1690 
1691 void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1692     SmallVectorImpl<LiveInterval*> &SplitLIs) {
1693   ConnectedVNInfoEqClasses ConEQ(*this);
1694   unsigned NumComp = ConEQ.Classify(LI);
1695   if (NumComp <= 1)
1696     return;
1697   LLVM_DEBUG(dbgs() << "  Split " << NumComp << " components: " << LI << '\n');
1698   unsigned Reg = LI.reg;
1699   const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1700   for (unsigned I = 1; I < NumComp; ++I) {
1701     Register NewVReg = MRI->createVirtualRegister(RegClass);
1702     LiveInterval &NewLI = createEmptyInterval(NewVReg);
1703     SplitLIs.push_back(&NewLI);
1704   }
1705   ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1706 }
1707 
1708 void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
1709   assert(LICalc && "LICalc not initialized.");
1710   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1711   LICalc->constructMainRangeFromSubranges(LI);
1712 }
1713