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