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   return (isDef + isUse) * MBFI->getBlockFreqRelativeToEntryBlock(MBB);
872 }
873 
874 LiveRange::Segment
875 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) {
876   LiveInterval& Interval = createEmptyInterval(reg);
877   VNInfo *VN = Interval.getNextValue(
878       SlotIndex(getInstructionIndex(startInst).getRegSlot()),
879       getVNInfoAllocator());
880   LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
881                        getMBBEndIdx(startInst.getParent()), VN);
882   Interval.addSegment(S);
883 
884   return S;
885 }
886 
887 //===----------------------------------------------------------------------===//
888 //                          Register mask functions
889 //===----------------------------------------------------------------------===//
890 
891 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
892                                              BitVector &UsableRegs) {
893   if (LI.empty())
894     return false;
895   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
896 
897   // Use a smaller arrays for local live ranges.
898   ArrayRef<SlotIndex> Slots;
899   ArrayRef<const uint32_t*> Bits;
900   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
901     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
902     Bits = getRegMaskBitsInBlock(MBB->getNumber());
903   } else {
904     Slots = getRegMaskSlots();
905     Bits = getRegMaskBits();
906   }
907 
908   // We are going to enumerate all the register mask slots contained in LI.
909   // Start with a binary search of RegMaskSlots to find a starting point.
910   ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
911   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
912 
913   // No slots in range, LI begins after the last call.
914   if (SlotI == SlotE)
915     return false;
916 
917   bool Found = false;
918   while (true) {
919     assert(*SlotI >= LiveI->start);
920     // Loop over all slots overlapping this segment.
921     while (*SlotI < LiveI->end) {
922       // *SlotI overlaps LI. Collect mask bits.
923       if (!Found) {
924         // This is the first overlap. Initialize UsableRegs to all ones.
925         UsableRegs.clear();
926         UsableRegs.resize(TRI->getNumRegs(), true);
927         Found = true;
928       }
929       // Remove usable registers clobbered by this mask.
930       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
931       if (++SlotI == SlotE)
932         return Found;
933     }
934     // *SlotI is beyond the current LI segment.
935     LiveI = LI.advanceTo(LiveI, *SlotI);
936     if (LiveI == LiveE)
937       return Found;
938     // Advance SlotI until it overlaps.
939     while (*SlotI < LiveI->start)
940       if (++SlotI == SlotE)
941         return Found;
942   }
943 }
944 
945 //===----------------------------------------------------------------------===//
946 //                         IntervalUpdate class.
947 //===----------------------------------------------------------------------===//
948 
949 /// Toolkit used by handleMove to trim or extend live intervals.
950 class LiveIntervals::HMEditor {
951 private:
952   LiveIntervals& LIS;
953   const MachineRegisterInfo& MRI;
954   const TargetRegisterInfo& TRI;
955   SlotIndex OldIdx;
956   SlotIndex NewIdx;
957   SmallPtrSet<LiveRange*, 8> Updated;
958   bool UpdateFlags;
959 
960 public:
961   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
962            const TargetRegisterInfo& TRI,
963            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
964     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
965       UpdateFlags(UpdateFlags) {}
966 
967   // FIXME: UpdateFlags is a workaround that creates live intervals for all
968   // physregs, even those that aren't needed for regalloc, in order to update
969   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
970   // flags, and postRA passes will use a live register utility instead.
971   LiveRange *getRegUnitLI(unsigned Unit) {
972     if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
973       return &LIS.getRegUnit(Unit);
974     return LIS.getCachedRegUnit(Unit);
975   }
976 
977   /// Update all live ranges touched by MI, assuming a move from OldIdx to
978   /// NewIdx.
979   void updateAllRanges(MachineInstr *MI) {
980     LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
981                       << *MI);
982     bool hasRegMask = false;
983     for (MachineOperand &MO : MI->operands()) {
984       if (MO.isRegMask())
985         hasRegMask = true;
986       if (!MO.isReg())
987         continue;
988       if (MO.isUse()) {
989         if (!MO.readsReg())
990           continue;
991         // Aggressively clear all kill flags.
992         // They are reinserted by VirtRegRewriter.
993         MO.setIsKill(false);
994       }
995 
996       Register Reg = MO.getReg();
997       if (!Reg)
998         continue;
999       if (Register::isVirtualRegister(Reg)) {
1000         LiveInterval &LI = LIS.getInterval(Reg);
1001         if (LI.hasSubRanges()) {
1002           unsigned SubReg = MO.getSubReg();
1003           LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1004                                         : MRI.getMaxLaneMaskForVReg(Reg);
1005           for (LiveInterval::SubRange &S : LI.subranges()) {
1006             if ((S.LaneMask & LaneMask).none())
1007               continue;
1008             updateRange(S, Reg, S.LaneMask);
1009           }
1010         }
1011         updateRange(LI, Reg, LaneBitmask::getNone());
1012         // If main range has a hole and we are moving a subrange use across
1013         // the hole updateRange() cannot properly handle it since it only
1014         // gets the LiveRange and not the whole LiveInterval. As a result
1015         // we may end up with a main range not covering all subranges.
1016         // This is extremely rare case, so let's check and reconstruct the
1017         // main range.
1018         for (LiveInterval::SubRange &S : LI.subranges()) {
1019           if (LI.covers(S))
1020             continue;
1021           LI.clear();
1022           LIS.constructMainRangeFromSubranges(LI);
1023           break;
1024         }
1025 
1026         continue;
1027       }
1028 
1029       // For physregs, only update the regunits that actually have a
1030       // precomputed live range.
1031       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
1032         if (LiveRange *LR = getRegUnitLI(*Units))
1033           updateRange(*LR, *Units, LaneBitmask::getNone());
1034     }
1035     if (hasRegMask)
1036       updateRegMaskSlots();
1037   }
1038 
1039 private:
1040   /// Update a single live range, assuming an instruction has been moved from
1041   /// OldIdx to NewIdx.
1042   void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1043     if (!Updated.insert(&LR).second)
1044       return;
1045     LLVM_DEBUG({
1046       dbgs() << "     ";
1047       if (Register::isVirtualRegister(Reg)) {
1048         dbgs() << printReg(Reg);
1049         if (LaneMask.any())
1050           dbgs() << " L" << PrintLaneMask(LaneMask);
1051       } else {
1052         dbgs() << printRegUnit(Reg, &TRI);
1053       }
1054       dbgs() << ":\t" << LR << '\n';
1055     });
1056     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1057       handleMoveDown(LR);
1058     else
1059       handleMoveUp(LR, Reg, LaneMask);
1060     LLVM_DEBUG(dbgs() << "        -->\t" << LR << '\n');
1061     LR.verify();
1062   }
1063 
1064   /// Update LR to reflect an instruction has been moved downwards from OldIdx
1065   /// to NewIdx (OldIdx < NewIdx).
1066   void handleMoveDown(LiveRange &LR) {
1067     LiveRange::iterator E = LR.end();
1068     // Segment going into OldIdx.
1069     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1070 
1071     // No value live before or after OldIdx? Nothing to do.
1072     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1073       return;
1074 
1075     LiveRange::iterator OldIdxOut;
1076     // Do we have a value live-in to OldIdx?
1077     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1078       // If the live-in value already extends to NewIdx, there is nothing to do.
1079       if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1080         return;
1081       // Aggressively remove all kill flags from the old kill point.
1082       // Kill flags shouldn't be used while live intervals exist, they will be
1083       // reinserted by VirtRegRewriter.
1084       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1085         for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1086           if (MOP.isReg() && MOP.isUse())
1087             MOP.setIsKill(false);
1088 
1089       // Is there a def before NewIdx which is not OldIdx?
1090       LiveRange::iterator Next = std::next(OldIdxIn);
1091       if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1092           SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1093         // If we are here then OldIdx was just a use but not a def. We only have
1094         // to ensure liveness extends to NewIdx.
1095         LiveRange::iterator NewIdxIn =
1096           LR.advanceTo(Next, NewIdx.getBaseIndex());
1097         // Extend the segment before NewIdx if necessary.
1098         if (NewIdxIn == E ||
1099             !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1100           LiveRange::iterator Prev = std::prev(NewIdxIn);
1101           Prev->end = NewIdx.getRegSlot();
1102         }
1103         // Extend OldIdxIn.
1104         OldIdxIn->end = Next->start;
1105         return;
1106       }
1107 
1108       // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1109       // invalid by overlapping ranges.
1110       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1111       OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1112       // If this was not a kill, then there was no def and we're done.
1113       if (!isKill)
1114         return;
1115 
1116       // Did we have a Def at OldIdx?
1117       OldIdxOut = Next;
1118       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1119         return;
1120     } else {
1121       OldIdxOut = OldIdxIn;
1122     }
1123 
1124     // If we are here then there is a Definition at OldIdx. OldIdxOut points
1125     // to the segment starting there.
1126     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1127            "No def?");
1128     VNInfo *OldIdxVNI = OldIdxOut->valno;
1129     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1130 
1131     // If the defined value extends beyond NewIdx, just move the beginning
1132     // of the segment to NewIdx.
1133     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1134     if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1135       OldIdxVNI->def = NewIdxDef;
1136       OldIdxOut->start = OldIdxVNI->def;
1137       return;
1138     }
1139 
1140     // If we are here then we have a Definition at OldIdx which ends before
1141     // NewIdx.
1142 
1143     // Is there an existing Def at NewIdx?
1144     LiveRange::iterator AfterNewIdx
1145       = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
1146     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1147     if (!OldIdxDefIsDead &&
1148         SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1149       // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1150       VNInfo *DefVNI;
1151       if (OldIdxOut != LR.begin() &&
1152           !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1153                                      OldIdxOut->start)) {
1154         // There is no gap between OldIdxOut and its predecessor anymore,
1155         // merge them.
1156         LiveRange::iterator IPrev = std::prev(OldIdxOut);
1157         DefVNI = OldIdxVNI;
1158         IPrev->end = OldIdxOut->end;
1159       } else {
1160         // The value is live in to OldIdx
1161         LiveRange::iterator INext = std::next(OldIdxOut);
1162         assert(INext != E && "Must have following segment");
1163         // We merge OldIdxOut and its successor. As we're dealing with subreg
1164         // reordering, there is always a successor to OldIdxOut in the same BB
1165         // We don't need INext->valno anymore and will reuse for the new segment
1166         // we create later.
1167         DefVNI = OldIdxVNI;
1168         INext->start = OldIdxOut->end;
1169         INext->valno->def = INext->start;
1170       }
1171       // If NewIdx is behind the last segment, extend that and append a new one.
1172       if (AfterNewIdx == E) {
1173         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1174         // one position.
1175         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1176         // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1177         std::copy(std::next(OldIdxOut), E, OldIdxOut);
1178         // The last segment is undefined now, reuse it for a dead def.
1179         LiveRange::iterator NewSegment = std::prev(E);
1180         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1181                                          DefVNI);
1182         DefVNI->def = NewIdxDef;
1183 
1184         LiveRange::iterator Prev = std::prev(NewSegment);
1185         Prev->end = NewIdxDef;
1186       } else {
1187         // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1188         // one position.
1189         //    |-  ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1190         // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1191         std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1192         LiveRange::iterator Prev = std::prev(AfterNewIdx);
1193         // We have two cases:
1194         if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1195           // Case 1: NewIdx is inside a liverange. Split this liverange at
1196           // NewIdxDef into the segment "Prev" followed by "NewSegment".
1197           LiveRange::iterator NewSegment = AfterNewIdx;
1198           *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1199           Prev->valno->def = NewIdxDef;
1200 
1201           *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1202           DefVNI->def = Prev->start;
1203         } else {
1204           // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1205           // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1206           *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1207           DefVNI->def = NewIdxDef;
1208           assert(DefVNI != AfterNewIdx->valno);
1209         }
1210       }
1211       return;
1212     }
1213 
1214     if (AfterNewIdx != E &&
1215         SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1216       // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1217       // that value.
1218       assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1219       LR.removeValNo(OldIdxVNI);
1220     } else {
1221       // There was no existing def at NewIdx. We need to create a dead def
1222       // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1223       // a new segment at the place where we want to construct the dead def.
1224       //    |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1225       // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1226       assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1227       std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1228       // We can reuse OldIdxVNI now.
1229       LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1230       VNInfo *NewSegmentVNI = OldIdxVNI;
1231       NewSegmentVNI->def = NewIdxDef;
1232       *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1233                                        NewSegmentVNI);
1234     }
1235   }
1236 
1237   /// Update LR to reflect an instruction has been moved upwards from OldIdx
1238   /// to NewIdx (NewIdx < OldIdx).
1239   void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1240     LiveRange::iterator E = LR.end();
1241     // Segment going into OldIdx.
1242     LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1243 
1244     // No value live before or after OldIdx? Nothing to do.
1245     if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1246       return;
1247 
1248     LiveRange::iterator OldIdxOut;
1249     // Do we have a value live-in to OldIdx?
1250     if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1251       // If the live-in value isn't killed here, then we have no Def at
1252       // OldIdx, moreover the value must be live at NewIdx so there is nothing
1253       // to do.
1254       bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1255       if (!isKill)
1256         return;
1257 
1258       // At this point we have to move OldIdxIn->end back to the nearest
1259       // previous use or (dead-)def but no further than NewIdx.
1260       SlotIndex DefBeforeOldIdx
1261         = std::max(OldIdxIn->start.getDeadSlot(),
1262                    NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1263       OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
1264 
1265       // Did we have a Def at OldIdx? If not we are done now.
1266       OldIdxOut = std::next(OldIdxIn);
1267       if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1268         return;
1269     } else {
1270       OldIdxOut = OldIdxIn;
1271       OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
1272     }
1273 
1274     // If we are here then there is a Definition at OldIdx. OldIdxOut points
1275     // to the segment starting there.
1276     assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1277            "No def?");
1278     VNInfo *OldIdxVNI = OldIdxOut->valno;
1279     assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1280     bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1281 
1282     // Is there an existing def at NewIdx?
1283     SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1284     LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1285     if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1286       assert(NewIdxOut->valno != OldIdxVNI &&
1287              "Same value defined more than once?");
1288       // If OldIdx was a dead def remove it.
1289       if (!OldIdxDefIsDead) {
1290         // Remove segment starting at NewIdx and move begin of OldIdxOut to
1291         // NewIdx so it can take its place.
1292         OldIdxVNI->def = NewIdxDef;
1293         OldIdxOut->start = NewIdxDef;
1294         LR.removeValNo(NewIdxOut->valno);
1295       } else {
1296         // Simply remove the dead def at OldIdx.
1297         LR.removeValNo(OldIdxVNI);
1298       }
1299     } else {
1300       // Previously nothing was live after NewIdx, so all we have to do now is
1301       // move the begin of OldIdxOut to NewIdx.
1302       if (!OldIdxDefIsDead) {
1303         // Do we have any intermediate Defs between OldIdx and NewIdx?
1304         if (OldIdxIn != E &&
1305             SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1306           // OldIdx is not a dead def and NewIdx is before predecessor start.
1307           LiveRange::iterator NewIdxIn = NewIdxOut;
1308           assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1309           const SlotIndex SplitPos = NewIdxDef;
1310           OldIdxVNI = OldIdxIn->valno;
1311 
1312           SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
1313           LiveRange::iterator Prev = std::prev(OldIdxIn);
1314           if (OldIdxIn != LR.begin() &&
1315               SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
1316             // If the segment before OldIdx read a value defined earlier than
1317             // NewIdx, the moved instruction also reads and forwards that
1318             // value. Extend the lifetime of the new def point.
1319 
1320             // Extend to where the previous range started, unless there is
1321             // another redef first.
1322             NewDefEndPoint = std::min(OldIdxIn->start,
1323                                       std::next(NewIdxOut)->start);
1324           }
1325 
1326           // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1327           OldIdxOut->valno->def = OldIdxIn->start;
1328           *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1329                                           OldIdxOut->valno);
1330           // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1331           // We Slide [NewIdxIn, OldIdxIn) down one position.
1332           //    |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1333           // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1334           std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1335           // NewIdxIn is now considered undef so we can reuse it for the moved
1336           // value.
1337           LiveRange::iterator NewSegment = NewIdxIn;
1338           LiveRange::iterator Next = std::next(NewSegment);
1339           if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1340             // There is no gap between NewSegment and its predecessor.
1341             *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1342                                              Next->valno);
1343 
1344             *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
1345             Next->valno->def = SplitPos;
1346           } else {
1347             // There is a gap between NewSegment and its predecessor
1348             // Value becomes live in.
1349             *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1350             NewSegment->valno->def = SplitPos;
1351           }
1352         } else {
1353           // Leave the end point of a live def.
1354           OldIdxOut->start = NewIdxDef;
1355           OldIdxVNI->def = NewIdxDef;
1356           if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1357             OldIdxIn->end = NewIdxDef;
1358         }
1359       } else if (OldIdxIn != E
1360           && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1361           && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1362         // OldIdxVNI is a dead def that has been moved into the middle of
1363         // another value in LR. That can happen when LR is a whole register,
1364         // but the dead def is a write to a subreg that is dead at NewIdx.
1365         // The dead def may have been moved across other values
1366         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1367         // down one position.
1368         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1369         // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1370         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1371         // Modify the segment at NewIdxOut and the following segment to meet at
1372         // the point of the dead def, with the following segment getting
1373         // OldIdxVNI as its value number.
1374         *NewIdxOut = LiveRange::Segment(
1375             NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1376         *(NewIdxOut + 1) = LiveRange::Segment(
1377             NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1378         OldIdxVNI->def = NewIdxDef;
1379         // Modify subsequent segments to be defined by the moved def OldIdxVNI.
1380         for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
1381           Idx->valno = OldIdxVNI;
1382         // Aggressively remove all dead flags from the former dead definition.
1383         // Kill/dead flags shouldn't be used while live intervals exist; they
1384         // will be reinserted by VirtRegRewriter.
1385         if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1386           for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1387             if (MO->isReg() && !MO->isUse())
1388               MO->setIsDead(false);
1389       } else {
1390         // OldIdxVNI is a dead def. It may have been moved across other values
1391         // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1392         // down one position.
1393         //    |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1394         // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1395         std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1396         // OldIdxVNI can be reused now to build a new dead def segment.
1397         LiveRange::iterator NewSegment = NewIdxOut;
1398         VNInfo *NewSegmentVNI = OldIdxVNI;
1399         *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1400                                          NewSegmentVNI);
1401         NewSegmentVNI->def = NewIdxDef;
1402       }
1403     }
1404   }
1405 
1406   void updateRegMaskSlots() {
1407     SmallVectorImpl<SlotIndex>::iterator RI =
1408         llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
1409     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1410            "No RegMask at OldIdx.");
1411     *RI = NewIdx.getRegSlot();
1412     assert((RI == LIS.RegMaskSlots.begin() ||
1413             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1414            "Cannot move regmask instruction above another call");
1415     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1416             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1417            "Cannot move regmask instruction below another call");
1418   }
1419 
1420   // Return the last use of reg between NewIdx and OldIdx.
1421   SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
1422                               LaneBitmask LaneMask) {
1423     if (Register::isVirtualRegister(Reg)) {
1424       SlotIndex LastUse = Before;
1425       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1426         if (MO.isUndef())
1427           continue;
1428         unsigned SubReg = MO.getSubReg();
1429         if (SubReg != 0 && LaneMask.any()
1430             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
1431           continue;
1432 
1433         const MachineInstr &MI = *MO.getParent();
1434         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1435         if (InstSlot > LastUse && InstSlot < OldIdx)
1436           LastUse = InstSlot.getRegSlot();
1437       }
1438       return LastUse;
1439     }
1440 
1441     // This is a regunit interval, so scanning the use list could be very
1442     // expensive. Scan upwards from OldIdx instead.
1443     assert(Before < OldIdx && "Expected upwards move");
1444     SlotIndexes *Indexes = LIS.getSlotIndexes();
1445     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
1446 
1447     // OldIdx may not correspond to an instruction any longer, so set MII to
1448     // point to the next instruction after OldIdx, or MBB->end().
1449     MachineBasicBlock::iterator MII = MBB->end();
1450     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1451                            Indexes->getNextNonNullIndex(OldIdx)))
1452       if (MI->getParent() == MBB)
1453         MII = MI;
1454 
1455     MachineBasicBlock::iterator Begin = MBB->begin();
1456     while (MII != Begin) {
1457       if ((--MII)->isDebugInstr())
1458         continue;
1459       SlotIndex Idx = Indexes->getInstructionIndex(*MII);
1460 
1461       // Stop searching when Before is reached.
1462       if (!SlotIndex::isEarlierInstr(Before, Idx))
1463         return Before;
1464 
1465       // Check if MII uses Reg.
1466       for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1467         if (MO->isReg() && !MO->isUndef() &&
1468             Register::isPhysicalRegister(MO->getReg()) &&
1469             TRI.hasRegUnit(MO->getReg(), Reg))
1470           return Idx.getRegSlot();
1471     }
1472     // Didn't reach Before. It must be the first instruction in the block.
1473     return Before;
1474   }
1475 };
1476 
1477 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
1478   // It is fine to move a bundle as a whole, but not an individual instruction
1479   // inside it.
1480   assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
1481          "Cannot move instruction in bundle");
1482   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1483   Indexes->removeMachineInstrFromMaps(MI);
1484   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1485   assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1486          OldIndex < getMBBEndIdx(MI.getParent()) &&
1487          "Cannot handle moves across basic block boundaries.");
1488 
1489   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1490   HME.updateAllRanges(&MI);
1491 }
1492 
1493 void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart,
1494                                             bool UpdateFlags) {
1495   assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
1496          "Bundle start is not a bundle");
1497   SmallVector<SlotIndex, 16> ToProcess;
1498   const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart);
1499   auto BundleEnd = getBundleEnd(BundleStart.getIterator());
1500 
1501   auto I = BundleStart.getIterator();
1502   I++;
1503   while (I != BundleEnd) {
1504     if (!Indexes->hasIndex(*I))
1505       continue;
1506     SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true);
1507     ToProcess.push_back(OldIndex);
1508     Indexes->removeMachineInstrFromMaps(*I, true);
1509     I++;
1510   }
1511   for (SlotIndex OldIndex : ToProcess) {
1512     HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1513     HME.updateAllRanges(&BundleStart);
1514   }
1515 
1516   // Fix up dead defs
1517   const SlotIndex Index = getInstructionIndex(BundleStart);
1518   for (unsigned Idx = 0, E = BundleStart.getNumOperands(); Idx != E; ++Idx) {
1519     MachineOperand &MO = BundleStart.getOperand(Idx);
1520     if (!MO.isReg())
1521       continue;
1522     Register Reg = MO.getReg();
1523     if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
1524       LiveInterval &LI = getInterval(Reg);
1525       LiveQueryResult LRQ = LI.Query(Index);
1526       if (LRQ.isDeadDef())
1527         MO.setIsDead();
1528     }
1529   }
1530 }
1531 
1532 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1533                                         const MachineBasicBlock::iterator End,
1534                                         const SlotIndex endIdx,
1535                                         LiveRange &LR, const unsigned Reg,
1536                                         LaneBitmask LaneMask) {
1537   LiveInterval::iterator LII = LR.find(endIdx);
1538   SlotIndex lastUseIdx;
1539   if (LII == LR.begin()) {
1540     // This happens when the function is called for a subregister that only
1541     // occurs _after_ the range that is to be repaired.
1542     return;
1543   }
1544   if (LII != LR.end() && LII->start < endIdx)
1545     lastUseIdx = LII->end;
1546   else
1547     --LII;
1548 
1549   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1550     --I;
1551     MachineInstr &MI = *I;
1552     if (MI.isDebugInstr())
1553       continue;
1554 
1555     SlotIndex instrIdx = getInstructionIndex(MI);
1556     bool isStartValid = getInstructionFromIndex(LII->start);
1557     bool isEndValid = getInstructionFromIndex(LII->end);
1558 
1559     // FIXME: This doesn't currently handle early-clobber or multiple removed
1560     // defs inside of the region to repair.
1561     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
1562                                     OE = MI.operands_end();
1563          OI != OE; ++OI) {
1564       const MachineOperand &MO = *OI;
1565       if (!MO.isReg() || MO.getReg() != Reg)
1566         continue;
1567 
1568       unsigned SubReg = MO.getSubReg();
1569       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1570       if ((Mask & LaneMask).none())
1571         continue;
1572 
1573       if (MO.isDef()) {
1574         if (!isStartValid) {
1575           if (LII->end.isDead()) {
1576             SlotIndex prevStart;
1577             if (LII != LR.begin())
1578               prevStart = std::prev(LII)->start;
1579 
1580             // FIXME: This could be more efficient if there was a
1581             // removeSegment method that returned an iterator.
1582             LR.removeSegment(*LII, true);
1583             if (prevStart.isValid())
1584               LII = LR.find(prevStart);
1585             else
1586               LII = LR.begin();
1587           } else {
1588             LII->start = instrIdx.getRegSlot();
1589             LII->valno->def = instrIdx.getRegSlot();
1590             if (MO.getSubReg() && !MO.isUndef())
1591               lastUseIdx = instrIdx.getRegSlot();
1592             else
1593               lastUseIdx = SlotIndex();
1594             continue;
1595           }
1596         }
1597 
1598         if (!lastUseIdx.isValid()) {
1599           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1600           LiveRange::Segment S(instrIdx.getRegSlot(),
1601                                instrIdx.getDeadSlot(), VNI);
1602           LII = LR.addSegment(S);
1603         } else if (LII->start != instrIdx.getRegSlot()) {
1604           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1605           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1606           LII = LR.addSegment(S);
1607         }
1608 
1609         if (MO.getSubReg() && !MO.isUndef())
1610           lastUseIdx = instrIdx.getRegSlot();
1611         else
1612           lastUseIdx = SlotIndex();
1613       } else if (MO.isUse()) {
1614         // FIXME: This should probably be handled outside of this branch,
1615         // either as part of the def case (for defs inside of the region) or
1616         // after the loop over the region.
1617         if (!isEndValid && !LII->end.isBlock())
1618           LII->end = instrIdx.getRegSlot();
1619         if (!lastUseIdx.isValid())
1620           lastUseIdx = instrIdx.getRegSlot();
1621       }
1622     }
1623   }
1624 }
1625 
1626 void
1627 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1628                                       MachineBasicBlock::iterator Begin,
1629                                       MachineBasicBlock::iterator End,
1630                                       ArrayRef<Register> OrigRegs) {
1631   // Find anchor points, which are at the beginning/end of blocks or at
1632   // instructions that already have indexes.
1633   while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
1634     --Begin;
1635   while (End != MBB->end() && !Indexes->hasIndex(*End))
1636     ++End;
1637 
1638   SlotIndex endIdx;
1639   if (End == MBB->end())
1640     endIdx = getMBBEndIdx(MBB).getPrevSlot();
1641   else
1642     endIdx = getInstructionIndex(*End);
1643 
1644   Indexes->repairIndexesInRange(MBB, Begin, End);
1645 
1646   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1647     --I;
1648     MachineInstr &MI = *I;
1649     if (MI.isDebugInstr())
1650       continue;
1651     for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1652                                           MOE = MI.operands_end();
1653          MOI != MOE; ++MOI) {
1654       if (MOI->isReg() && Register::isVirtualRegister(MOI->getReg()) &&
1655           !hasInterval(MOI->getReg())) {
1656         createAndComputeVirtRegInterval(MOI->getReg());
1657       }
1658     }
1659   }
1660 
1661   for (Register Reg : OrigRegs) {
1662     if (!Reg.isVirtual())
1663       continue;
1664 
1665     LiveInterval &LI = getInterval(Reg);
1666     // FIXME: Should we support undefs that gain defs?
1667     if (!LI.hasAtLeastOneValue())
1668       continue;
1669 
1670     for (LiveInterval::SubRange &S : LI.subranges())
1671       repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1672 
1673     repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1674   }
1675 }
1676 
1677 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1678   for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
1679     if (LiveRange *LR = getCachedRegUnit(*Unit))
1680       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1681         LR->removeValNo(VNI);
1682   }
1683 }
1684 
1685 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1686   // LI may not have the main range computed yet, but its subranges may
1687   // be present.
1688   VNInfo *VNI = LI.getVNInfoAt(Pos);
1689   if (VNI != nullptr) {
1690     assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1691     LI.removeValNo(VNI);
1692   }
1693 
1694   // Also remove the value defined in subranges.
1695   for (LiveInterval::SubRange &S : LI.subranges()) {
1696     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1697       if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1698         S.removeValNo(SVNI);
1699   }
1700   LI.removeEmptySubRanges();
1701 }
1702 
1703 void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1704     SmallVectorImpl<LiveInterval*> &SplitLIs) {
1705   ConnectedVNInfoEqClasses ConEQ(*this);
1706   unsigned NumComp = ConEQ.Classify(LI);
1707   if (NumComp <= 1)
1708     return;
1709   LLVM_DEBUG(dbgs() << "  Split " << NumComp << " components: " << LI << '\n');
1710   unsigned Reg = LI.reg;
1711   const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1712   for (unsigned I = 1; I < NumComp; ++I) {
1713     Register NewVReg = MRI->createVirtualRegister(RegClass);
1714     LiveInterval &NewLI = createEmptyInterval(NewVReg);
1715     SplitLIs.push_back(&NewLI);
1716   }
1717   ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1718 }
1719 
1720 void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
1721   assert(LICalc && "LICalc not initialized.");
1722   LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1723   LICalc->constructMainRangeFromSubranges(LI);
1724 }
1725