Do not duplicate method name in comment, remove duplicate comment
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "LiveRangeCalc.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/BlockFrequency.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 #include <cmath>
42 #include <limits>
43 using namespace llvm;
44
45 #define DEBUG_TYPE "regalloc"
46
47 char LiveIntervals::ID = 0;
48 char &llvm::LiveIntervalsID = LiveIntervals::ID;
49 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
50                 "Live Interval Analysis", false, false)
51 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
52 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
53 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
54 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
55 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
56                 "Live Interval Analysis", false, false)
57
58 #ifndef NDEBUG
59 static cl::opt<bool> EnablePrecomputePhysRegs(
60   "precompute-phys-liveness", cl::Hidden,
61   cl::desc("Eagerly compute live intervals for all physreg units."));
62 #else
63 static bool EnablePrecomputePhysRegs = false;
64 #endif // NDEBUG
65
66 static cl::opt<bool> EnableSubRegLiveness(
67   "enable-subreg-liveness", cl::Hidden, cl::init(true),
68   cl::desc("Enable subregister liveness tracking."));
69
70 namespace llvm {
71 cl::opt<bool> UseSegmentSetForPhysRegs(
72     "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
73     cl::desc(
74         "Use segment set for the computation of the live ranges of physregs."));
75 }
76
77 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
78   AU.setPreservesCFG();
79   AU.addRequired<AliasAnalysis>();
80   AU.addPreserved<AliasAnalysis>();
81   // LiveVariables isn't really required by this analysis, it is only required
82   // here to make sure it is live during TwoAddressInstructionPass and
83   // PHIElimination. This is temporary.
84   AU.addRequired<LiveVariables>();
85   AU.addPreserved<LiveVariables>();
86   AU.addPreservedID(MachineLoopInfoID);
87   AU.addRequiredTransitiveID(MachineDominatorsID);
88   AU.addPreservedID(MachineDominatorsID);
89   AU.addPreserved<SlotIndexes>();
90   AU.addRequiredTransitive<SlotIndexes>();
91   MachineFunctionPass::getAnalysisUsage(AU);
92 }
93
94 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
95   DomTree(nullptr), LRCalc(nullptr) {
96   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
97 }
98
99 LiveIntervals::~LiveIntervals() {
100   delete LRCalc;
101 }
102
103 void LiveIntervals::releaseMemory() {
104   // Free the live intervals themselves.
105   for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
106     delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
107   VirtRegIntervals.clear();
108   RegMaskSlots.clear();
109   RegMaskBits.clear();
110   RegMaskBlocks.clear();
111
112   for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
113     delete RegUnitRanges[i];
114   RegUnitRanges.clear();
115
116   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
117   VNInfoAllocator.Reset();
118 }
119
120 /// runOnMachineFunction - calculates LiveIntervals
121 ///
122 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
123   MF = &fn;
124   MRI = &MF->getRegInfo();
125   TRI = MF->getSubtarget().getRegisterInfo();
126   TII = MF->getSubtarget().getInstrInfo();
127   AA = &getAnalysis<AliasAnalysis>();
128   Indexes = &getAnalysis<SlotIndexes>();
129   DomTree = &getAnalysis<MachineDominatorTree>();
130
131   if (EnableSubRegLiveness && MF->getSubtarget().enableSubRegLiveness())
132     MRI->enableSubRegLiveness(true);
133
134   if (!LRCalc)
135     LRCalc = new LiveRangeCalc();
136
137   // Allocate space for all virtual registers.
138   VirtRegIntervals.resize(MRI->getNumVirtRegs());
139
140   computeVirtRegs();
141   computeRegMasks();
142   computeLiveInRegUnits();
143
144   if (EnablePrecomputePhysRegs) {
145     // For stress testing, precompute live ranges of all physical register
146     // units, including reserved registers.
147     for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
148       getRegUnit(i);
149   }
150   DEBUG(dump());
151   return true;
152 }
153
154 /// print - Implement the dump method.
155 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
156   OS << "********** INTERVALS **********\n";
157
158   // Dump the regunits.
159   for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
160     if (LiveRange *LR = RegUnitRanges[i])
161       OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
162
163   // Dump the virtregs.
164   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
165     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
166     if (hasInterval(Reg))
167       OS << getInterval(Reg) << '\n';
168   }
169
170   OS << "RegMasks:";
171   for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
172     OS << ' ' << RegMaskSlots[i];
173   OS << '\n';
174
175   printInstrs(OS);
176 }
177
178 void LiveIntervals::printInstrs(raw_ostream &OS) const {
179   OS << "********** MACHINEINSTRS **********\n";
180   MF->print(OS, Indexes);
181 }
182
183 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
184 void LiveIntervals::dumpInstrs() const {
185   printInstrs(dbgs());
186 }
187 #endif
188
189 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
190   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
191                   llvm::huge_valf : 0.0F;
192   return new LiveInterval(reg, Weight);
193 }
194
195
196 /// computeVirtRegInterval - Compute the live interval of a virtual register,
197 /// based on defs and uses.
198 void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
199   assert(LRCalc && "LRCalc not initialized.");
200   assert(LI.empty() && "Should only compute empty intervals.");
201   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
202   LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
203   computeDeadValues(LI, nullptr);
204 }
205
206 void LiveIntervals::computeVirtRegs() {
207   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
208     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
209     if (MRI->reg_nodbg_empty(Reg))
210       continue;
211     createAndComputeVirtRegInterval(Reg);
212   }
213 }
214
215 void LiveIntervals::computeRegMasks() {
216   RegMaskBlocks.resize(MF->getNumBlockIDs());
217
218   // Find all instructions with regmask operands.
219   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
220        MBBI != E; ++MBBI) {
221     MachineBasicBlock *MBB = MBBI;
222     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
223     RMB.first = RegMaskSlots.size();
224     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
225          MI != ME; ++MI)
226       for (const MachineOperand &MO : MI->operands()) {
227         if (!MO.isRegMask())
228           continue;
229           RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
230           RegMaskBits.push_back(MO.getRegMask());
231       }
232     // Compute the number of register mask instructions in this block.
233     RMB.second = RegMaskSlots.size() - RMB.first;
234   }
235 }
236
237 //===----------------------------------------------------------------------===//
238 //                           Register Unit Liveness
239 //===----------------------------------------------------------------------===//
240 //
241 // Fixed interference typically comes from ABI boundaries: Function arguments
242 // and return values are passed in fixed registers, and so are exception
243 // pointers entering landing pads. Certain instructions require values to be
244 // present in specific registers. That is also represented through fixed
245 // interference.
246 //
247
248 /// computeRegUnitInterval - Compute the live range of a register unit, based
249 /// on the uses and defs of aliasing registers.  The range should be empty,
250 /// or contain only dead phi-defs from ABI blocks.
251 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
252   assert(LRCalc && "LRCalc not initialized.");
253   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
254
255   // The physregs aliasing Unit are the roots and their super-registers.
256   // Create all values as dead defs before extending to uses. Note that roots
257   // may share super-registers. That's OK because createDeadDefs() is
258   // idempotent. It is very rare for a register unit to have multiple roots, so
259   // uniquing super-registers is probably not worthwhile.
260   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
261     for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
262          Supers.isValid(); ++Supers) {
263       if (!MRI->reg_empty(*Supers))
264         LRCalc->createDeadDefs(LR, *Supers);
265     }
266   }
267
268   // Now extend LR to reach all uses.
269   // Ignore uses of reserved registers. We only track defs of those.
270   for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
271     for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
272          Supers.isValid(); ++Supers) {
273       unsigned Reg = *Supers;
274       if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
275         LRCalc->extendToUses(LR, Reg);
276     }
277   }
278
279   // Flush the segment set to the segment vector.
280   if (UseSegmentSetForPhysRegs)
281     LR.flushSegmentSet();
282 }
283
284
285 /// computeLiveInRegUnits - Precompute the live ranges of any register units
286 /// that are live-in to an ABI block somewhere. Register values can appear
287 /// without a corresponding def when entering the entry block or a landing pad.
288 ///
289 void LiveIntervals::computeLiveInRegUnits() {
290   RegUnitRanges.resize(TRI->getNumRegUnits());
291   DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
292
293   // Keep track of the live range sets allocated.
294   SmallVector<unsigned, 8> NewRanges;
295
296   // Check all basic blocks for live-ins.
297   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
298        MFI != MFE; ++MFI) {
299     const MachineBasicBlock *MBB = MFI;
300
301     // We only care about ABI blocks: Entry + landing pads.
302     if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
303       continue;
304
305     // Create phi-defs at Begin for all live-in registers.
306     SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
307     DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
308     for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
309          LIE = MBB->livein_end(); LII != LIE; ++LII) {
310       for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
311         unsigned Unit = *Units;
312         LiveRange *LR = RegUnitRanges[Unit];
313         if (!LR) {
314           // Use segment set to speed-up initial computation of the live range.
315           LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
316           NewRanges.push_back(Unit);
317         }
318         VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
319         (void)VNI;
320         DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
321       }
322     }
323     DEBUG(dbgs() << '\n');
324   }
325   DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
326
327   // Compute the 'normal' part of the ranges.
328   for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
329     unsigned Unit = NewRanges[i];
330     computeRegUnitRange(*RegUnitRanges[Unit], Unit);
331   }
332 }
333
334
335 static void createSegmentsForValues(LiveRange &LR,
336       iterator_range<LiveInterval::vni_iterator> VNIs) {
337   for (auto VNI : VNIs) {
338     if (VNI->isUnused())
339       continue;
340     SlotIndex Def = VNI->def;
341     LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
342   }
343 }
344
345 typedef SmallVector<std::pair<SlotIndex, VNInfo*>, 16> ShrinkToUsesWorkList;
346
347 static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
348                                  ShrinkToUsesWorkList &WorkList,
349                                  const LiveRange &OldRange) {
350   // Keep track of the PHIs that are in use.
351   SmallPtrSet<VNInfo*, 8> UsedPHIs;
352   // Blocks that have already been added to WorkList as live-out.
353   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
354
355   // Extend intervals to reach all uses in WorkList.
356   while (!WorkList.empty()) {
357     SlotIndex Idx = WorkList.back().first;
358     VNInfo *VNI = WorkList.back().second;
359     WorkList.pop_back();
360     const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
361     SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
362
363     // Extend the live range for VNI to be live at Idx.
364     if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
365       assert(ExtVNI == VNI && "Unexpected existing value number");
366       (void)ExtVNI;
367       // Is this a PHIDef we haven't seen before?
368       if (!VNI->isPHIDef() || VNI->def != BlockStart ||
369           !UsedPHIs.insert(VNI).second)
370         continue;
371       // The PHI is live, make sure the predecessors are live-out.
372       for (auto &Pred : MBB->predecessors()) {
373         if (!LiveOut.insert(Pred).second)
374           continue;
375         SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
376         // A predecessor is not required to have a live-out value for a PHI.
377         if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
378           WorkList.push_back(std::make_pair(Stop, PVNI));
379       }
380       continue;
381     }
382
383     // VNI is live-in to MBB.
384     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
385     LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
386
387     // Make sure VNI is live-out from the predecessors.
388     for (auto &Pred : MBB->predecessors()) {
389       if (!LiveOut.insert(Pred).second)
390         continue;
391       SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
392       assert(OldRange.getVNInfoBefore(Stop) == VNI &&
393              "Wrong value out of predecessor");
394       WorkList.push_back(std::make_pair(Stop, VNI));
395     }
396   }
397 }
398
399 bool LiveIntervals::shrinkToUses(LiveInterval *li,
400                                  SmallVectorImpl<MachineInstr*> *dead) {
401   DEBUG(dbgs() << "Shrink: " << *li << '\n');
402   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
403          && "Can only shrink virtual registers");
404
405   // Shrink subregister live ranges.
406   for (LiveInterval::SubRange &S : li->subranges()) {
407     shrinkToUses(S, li->reg);
408   }
409
410   // Find all the values used, including PHI kills.
411   ShrinkToUsesWorkList WorkList;
412
413   // Visit all instructions reading li->reg.
414   for (MachineRegisterInfo::reg_instr_iterator
415        I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
416        I != E; ) {
417     MachineInstr *UseMI = &*(I++);
418     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
419       continue;
420     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
421     LiveQueryResult LRQ = li->Query(Idx);
422     VNInfo *VNI = LRQ.valueIn();
423     if (!VNI) {
424       // This shouldn't happen: readsVirtualRegister returns true, but there is
425       // no live value. It is likely caused by a target getting <undef> flags
426       // wrong.
427       DEBUG(dbgs() << Idx << '\t' << *UseMI
428                    << "Warning: Instr claims to read non-existent value in "
429                     << *li << '\n');
430       continue;
431     }
432     // Special case: An early-clobber tied operand reads and writes the
433     // register one slot early.
434     if (VNInfo *DefVNI = LRQ.valueDefined())
435       Idx = DefVNI->def;
436
437     WorkList.push_back(std::make_pair(Idx, VNI));
438   }
439
440   // Create new live ranges with only minimal live segments per def.
441   LiveRange NewLR;
442   createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
443   extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
444
445   // Move the trimmed segments back.
446   li->segments.swap(NewLR.segments);
447
448   // Handle dead values.
449   bool CanSeparate = computeDeadValues(*li, dead);
450   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
451   return CanSeparate;
452 }
453
454 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
455                                       SmallVectorImpl<MachineInstr*> *dead) {
456   bool PHIRemoved = false;
457   for (auto VNI : LI.valnos) {
458     if (VNI->isUnused())
459       continue;
460     SlotIndex Def = VNI->def;
461     LiveRange::iterator I = LI.FindSegmentContaining(Def);
462     assert(I != LI.end() && "Missing segment for VNI");
463
464     // Is the register live before? Otherwise we may have to add a read-undef
465     // flag for subregister defs.
466     if (MRI->shouldTrackSubRegLiveness(LI.reg)) {
467       if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
468         MachineInstr *MI = getInstructionFromIndex(Def);
469         MI->addRegisterDefReadUndef(LI.reg);
470       }
471     }
472
473     if (I->end != Def.getDeadSlot())
474       continue;
475     if (VNI->isPHIDef()) {
476       // This is a dead PHI. Remove it.
477       VNI->markUnused();
478       LI.removeSegment(I);
479       DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
480       PHIRemoved = true;
481     } else {
482       // This is a dead def. Make sure the instruction knows.
483       MachineInstr *MI = getInstructionFromIndex(Def);
484       assert(MI && "No instruction defining live value");
485       MI->addRegisterDead(LI.reg, TRI);
486       if (dead && MI->allDefsAreDead()) {
487         DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
488         dead->push_back(MI);
489       }
490     }
491   }
492   return PHIRemoved;
493 }
494
495 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg)
496 {
497   DEBUG(dbgs() << "Shrink: " << SR << '\n');
498   assert(TargetRegisterInfo::isVirtualRegister(Reg)
499          && "Can only shrink virtual registers");
500   // Find all the values used, including PHI kills.
501   ShrinkToUsesWorkList WorkList;
502
503   // Visit all instructions reading Reg.
504   SlotIndex LastIdx;
505   for (MachineOperand &MO : MRI->reg_operands(Reg)) {
506     MachineInstr *UseMI = MO.getParent();
507     if (UseMI->isDebugValue())
508       continue;
509     // Maybe the operand is for a subregister we don't care about.
510     unsigned SubReg = MO.getSubReg();
511     if (SubReg != 0) {
512       unsigned SubRegMask = TRI->getSubRegIndexLaneMask(SubReg);
513       if ((SubRegMask & SR.LaneMask) == 0)
514         continue;
515     }
516     // We only need to visit each instruction once.
517     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
518     if (Idx == LastIdx)
519       continue;
520     LastIdx = Idx;
521
522     LiveQueryResult LRQ = SR.Query(Idx);
523     VNInfo *VNI = LRQ.valueIn();
524     // For Subranges it is possible that only undef values are left in that
525     // part of the subregister, so there is no real liverange at the use
526     if (!VNI)
527       continue;
528
529     // Special case: An early-clobber tied operand reads and writes the
530     // register one slot early.
531     if (VNInfo *DefVNI = LRQ.valueDefined())
532       Idx = DefVNI->def;
533
534     WorkList.push_back(std::make_pair(Idx, VNI));
535   }
536
537   // Create a new live ranges with only minimal live segments per def.
538   LiveRange NewLR;
539   createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
540   extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
541
542   // Move the trimmed ranges back.
543   SR.segments.swap(NewLR.segments);
544
545   // Remove dead PHI value numbers
546   for (auto VNI : SR.valnos) {
547     if (VNI->isUnused())
548       continue;
549     const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
550     assert(Segment != nullptr && "Missing segment for VNI");
551     if (Segment->end != VNI->def.getDeadSlot())
552       continue;
553     if (VNI->isPHIDef()) {
554       // This is a dead PHI. Remove it.
555       VNI->markUnused();
556       SR.removeSegment(*Segment);
557       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
558     }
559   }
560
561   DEBUG(dbgs() << "Shrunk: " << SR << '\n');
562 }
563
564 void LiveIntervals::extendToIndices(LiveRange &LR,
565                                     ArrayRef<SlotIndex> Indices) {
566   assert(LRCalc && "LRCalc not initialized.");
567   LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
568   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
569     LRCalc->extend(LR, Indices[i]);
570 }
571
572 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
573                                SmallVectorImpl<SlotIndex> *EndPoints) {
574   LiveQueryResult LRQ = LR.Query(Kill);
575   VNInfo *VNI = LRQ.valueOutOrDead();
576   if (!VNI)
577     return;
578
579   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
580   SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
581
582   // If VNI isn't live out from KillMBB, the value is trivially pruned.
583   if (LRQ.endPoint() < MBBEnd) {
584     LR.removeSegment(Kill, LRQ.endPoint());
585     if (EndPoints) EndPoints->push_back(LRQ.endPoint());
586     return;
587   }
588
589   // VNI is live out of KillMBB.
590   LR.removeSegment(Kill, MBBEnd);
591   if (EndPoints) EndPoints->push_back(MBBEnd);
592
593   // Find all blocks that are reachable from KillMBB without leaving VNI's live
594   // range. It is possible that KillMBB itself is reachable, so start a DFS
595   // from each successor.
596   typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
597   VisitedTy Visited;
598   for (MachineBasicBlock::succ_iterator
599        SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
600        SuccI != SuccE; ++SuccI) {
601     for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
602          I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
603          I != E;) {
604       MachineBasicBlock *MBB = *I;
605
606       // Check if VNI is live in to MBB.
607       SlotIndex MBBStart, MBBEnd;
608       std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
609       LiveQueryResult LRQ = LR.Query(MBBStart);
610       if (LRQ.valueIn() != VNI) {
611         // This block isn't part of the VNI segment. Prune the search.
612         I.skipChildren();
613         continue;
614       }
615
616       // Prune the search if VNI is killed in MBB.
617       if (LRQ.endPoint() < MBBEnd) {
618         LR.removeSegment(MBBStart, LRQ.endPoint());
619         if (EndPoints) EndPoints->push_back(LRQ.endPoint());
620         I.skipChildren();
621         continue;
622       }
623
624       // VNI is live through MBB.
625       LR.removeSegment(MBBStart, MBBEnd);
626       if (EndPoints) EndPoints->push_back(MBBEnd);
627       ++I;
628     }
629   }
630 }
631
632 //===----------------------------------------------------------------------===//
633 // Register allocator hooks.
634 //
635
636 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
637   // Keep track of regunit ranges.
638   SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
639   // Keep track of subregister ranges.
640   SmallVector<std::pair<const LiveInterval::SubRange*,
641                         LiveRange::const_iterator>, 4> SRs;
642
643   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
644     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
645     if (MRI->reg_nodbg_empty(Reg))
646       continue;
647     const LiveInterval &LI = getInterval(Reg);
648     if (LI.empty())
649       continue;
650
651     // Find the regunit intervals for the assigned register. They may overlap
652     // the virtual register live range, cancelling any kills.
653     RU.clear();
654     for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
655          ++Units) {
656       const LiveRange &RURange = getRegUnit(*Units);
657       if (RURange.empty())
658         continue;
659       RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
660     }
661
662     if (MRI->subRegLivenessEnabled()) {
663       SRs.clear();
664       for (const LiveInterval::SubRange &SR : LI.subranges()) {
665         SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
666       }
667     }
668
669     // Every instruction that kills Reg corresponds to a segment range end
670     // point.
671     for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
672          ++RI) {
673       // A block index indicates an MBB edge.
674       if (RI->end.isBlock())
675         continue;
676       MachineInstr *MI = getInstructionFromIndex(RI->end);
677       if (!MI)
678         continue;
679
680       // Check if any of the regunits are live beyond the end of RI. That could
681       // happen when a physreg is defined as a copy of a virtreg:
682       //
683       //   %EAX = COPY %vreg5
684       //   FOO %vreg5         <--- MI, cancel kill because %EAX is live.
685       //   BAR %EAX<kill>
686       //
687       // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
688       for (auto &RUP : RU) {
689         const LiveRange &RURange = *RUP.first;
690         LiveRange::const_iterator &I = RUP.second;
691         if (I == RURange.end())
692           continue;
693         I = RURange.advanceTo(I, RI->end);
694         if (I == RURange.end() || I->start >= RI->end)
695           continue;
696         // I is overlapping RI.
697         goto CancelKill;
698       }
699
700       if (MRI->subRegLivenessEnabled()) {
701         // When reading a partial undefined value we must not add a kill flag.
702         // The regalloc might have used the undef lane for something else.
703         // Example:
704         //     %vreg1 = ...              ; R32: %vreg1
705         //     %vreg2:high16 = ...       ; R64: %vreg2
706         //        = read %vreg2<kill>    ; R64: %vreg2
707         //        = read %vreg1          ; R32: %vreg1
708         // The <kill> flag is correct for %vreg2, but the register allocator may
709         // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
710         // are actually never written by %vreg2. After assignment the <kill>
711         // flag at the read instruction is invalid.
712         unsigned DefinedLanesMask;
713         if (!SRs.empty()) {
714           // Compute a mask of lanes that are defined.
715           DefinedLanesMask = 0;
716           for (auto &SRP : SRs) {
717             const LiveInterval::SubRange &SR = *SRP.first;
718             LiveRange::const_iterator &I = SRP.second;
719             if (I == SR.end())
720               continue;
721             I = SR.advanceTo(I, RI->end);
722             if (I == SR.end() || I->start >= RI->end)
723               continue;
724             // I is overlapping RI
725             DefinedLanesMask |= SR.LaneMask;
726           }
727         } else
728           DefinedLanesMask = ~0u;
729
730         bool IsFullWrite = false;
731         for (const MachineOperand &MO : MI->operands()) {
732           if (!MO.isReg() || MO.getReg() != Reg)
733             continue;
734           if (MO.isUse()) {
735             // Reading any undefined lanes?
736             unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
737             if ((UseMask & ~DefinedLanesMask) != 0)
738               goto CancelKill;
739           } else if (MO.getSubReg() == 0) {
740             // Writing to the full register?
741             assert(MO.isDef());
742             IsFullWrite = true;
743           }
744         }
745
746         // If an instruction writes to a subregister, a new segment starts in
747         // the LiveInterval. But as this is only overriding part of the register
748         // adding kill-flags is not correct here after registers have been
749         // assigned.
750         if (!IsFullWrite) {
751           // Next segment has to be adjacent in the subregister write case.
752           LiveRange::const_iterator N = std::next(RI);
753           if (N != LI.end() && N->start == RI->end)
754             goto CancelKill;
755         }
756       }
757
758       MI->addRegisterKilled(Reg, nullptr);
759       continue;
760 CancelKill:
761       MI->clearRegisterKills(Reg, nullptr);
762     }
763   }
764 }
765
766 MachineBasicBlock*
767 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
768   // A local live range must be fully contained inside the block, meaning it is
769   // defined and killed at instructions, not at block boundaries. It is not
770   // live in or or out of any block.
771   //
772   // It is technically possible to have a PHI-defined live range identical to a
773   // single block, but we are going to return false in that case.
774
775   SlotIndex Start = LI.beginIndex();
776   if (Start.isBlock())
777     return nullptr;
778
779   SlotIndex Stop = LI.endIndex();
780   if (Stop.isBlock())
781     return nullptr;
782
783   // getMBBFromIndex doesn't need to search the MBB table when both indexes
784   // belong to proper instructions.
785   MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
786   MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
787   return MBB1 == MBB2 ? MBB1 : nullptr;
788 }
789
790 bool
791 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
792   for (const VNInfo *PHI : LI.valnos) {
793     if (PHI->isUnused() || !PHI->isPHIDef())
794       continue;
795     const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
796     // Conservatively return true instead of scanning huge predecessor lists.
797     if (PHIMBB->pred_size() > 100)
798       return true;
799     for (MachineBasicBlock::const_pred_iterator
800          PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
801       if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
802         return true;
803   }
804   return false;
805 }
806
807 float
808 LiveIntervals::getSpillWeight(bool isDef, bool isUse,
809                               const MachineBlockFrequencyInfo *MBFI,
810                               const MachineInstr *MI) {
811   BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
812   const float Scale = 1.0f / MBFI->getEntryFreq();
813   return (isDef + isUse) * (Freq.getFrequency() * Scale);
814 }
815
816 LiveRange::Segment
817 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
818   LiveInterval& Interval = createEmptyInterval(reg);
819   VNInfo* VN = Interval.getNextValue(
820     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
821     getVNInfoAllocator());
822   LiveRange::Segment S(
823      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
824      getMBBEndIdx(startInst->getParent()), VN);
825   Interval.addSegment(S);
826
827   return S;
828 }
829
830
831 //===----------------------------------------------------------------------===//
832 //                          Register mask functions
833 //===----------------------------------------------------------------------===//
834
835 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
836                                              BitVector &UsableRegs) {
837   if (LI.empty())
838     return false;
839   LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
840
841   // Use a smaller arrays for local live ranges.
842   ArrayRef<SlotIndex> Slots;
843   ArrayRef<const uint32_t*> Bits;
844   if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
845     Slots = getRegMaskSlotsInBlock(MBB->getNumber());
846     Bits = getRegMaskBitsInBlock(MBB->getNumber());
847   } else {
848     Slots = getRegMaskSlots();
849     Bits = getRegMaskBits();
850   }
851
852   // We are going to enumerate all the register mask slots contained in LI.
853   // Start with a binary search of RegMaskSlots to find a starting point.
854   ArrayRef<SlotIndex>::iterator SlotI =
855     std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
856   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
857
858   // No slots in range, LI begins after the last call.
859   if (SlotI == SlotE)
860     return false;
861
862   bool Found = false;
863   for (;;) {
864     assert(*SlotI >= LiveI->start);
865     // Loop over all slots overlapping this segment.
866     while (*SlotI < LiveI->end) {
867       // *SlotI overlaps LI. Collect mask bits.
868       if (!Found) {
869         // This is the first overlap. Initialize UsableRegs to all ones.
870         UsableRegs.clear();
871         UsableRegs.resize(TRI->getNumRegs(), true);
872         Found = true;
873       }
874       // Remove usable registers clobbered by this mask.
875       UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
876       if (++SlotI == SlotE)
877         return Found;
878     }
879     // *SlotI is beyond the current LI segment.
880     LiveI = LI.advanceTo(LiveI, *SlotI);
881     if (LiveI == LiveE)
882       return Found;
883     // Advance SlotI until it overlaps.
884     while (*SlotI < LiveI->start)
885       if (++SlotI == SlotE)
886         return Found;
887   }
888 }
889
890 //===----------------------------------------------------------------------===//
891 //                         IntervalUpdate class.
892 //===----------------------------------------------------------------------===//
893
894 // HMEditor is a toolkit used by handleMove to trim or extend live intervals.
895 class LiveIntervals::HMEditor {
896 private:
897   LiveIntervals& LIS;
898   const MachineRegisterInfo& MRI;
899   const TargetRegisterInfo& TRI;
900   SlotIndex OldIdx;
901   SlotIndex NewIdx;
902   SmallPtrSet<LiveRange*, 8> Updated;
903   bool UpdateFlags;
904
905 public:
906   HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
907            const TargetRegisterInfo& TRI,
908            SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
909     : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
910       UpdateFlags(UpdateFlags) {}
911
912   // FIXME: UpdateFlags is a workaround that creates live intervals for all
913   // physregs, even those that aren't needed for regalloc, in order to update
914   // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
915   // flags, and postRA passes will use a live register utility instead.
916   LiveRange *getRegUnitLI(unsigned Unit) {
917     if (UpdateFlags)
918       return &LIS.getRegUnit(Unit);
919     return LIS.getCachedRegUnit(Unit);
920   }
921
922   /// Update all live ranges touched by MI, assuming a move from OldIdx to
923   /// NewIdx.
924   void updateAllRanges(MachineInstr *MI) {
925     DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
926     bool hasRegMask = false;
927     for (MachineOperand &MO : MI->operands()) {
928       if (MO.isRegMask())
929         hasRegMask = true;
930       if (!MO.isReg())
931         continue;
932       // Aggressively clear all kill flags.
933       // They are reinserted by VirtRegRewriter.
934       if (MO.isUse())
935         MO.setIsKill(false);
936
937       unsigned Reg = MO.getReg();
938       if (!Reg)
939         continue;
940       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
941         LiveInterval &LI = LIS.getInterval(Reg);
942         if (LI.hasSubRanges()) {
943           unsigned SubReg = MO.getSubReg();
944           unsigned LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
945           for (LiveInterval::SubRange &S : LI.subranges()) {
946             if ((S.LaneMask & LaneMask) == 0)
947               continue;
948             updateRange(S, Reg, S.LaneMask);
949           }
950         }
951         updateRange(LI, Reg, 0);
952         continue;
953       }
954
955       // For physregs, only update the regunits that actually have a
956       // precomputed live range.
957       for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
958         if (LiveRange *LR = getRegUnitLI(*Units))
959           updateRange(*LR, *Units, 0);
960     }
961     if (hasRegMask)
962       updateRegMaskSlots();
963   }
964
965 private:
966   /// Update a single live range, assuming an instruction has been moved from
967   /// OldIdx to NewIdx.
968   void updateRange(LiveRange &LR, unsigned Reg, unsigned LaneMask) {
969     if (!Updated.insert(&LR).second)
970       return;
971     DEBUG({
972       dbgs() << "     ";
973       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
974         dbgs() << PrintReg(Reg);
975         if (LaneMask != 0)
976           dbgs() << format(" L%04X", LaneMask);
977       } else {
978         dbgs() << PrintRegUnit(Reg, &TRI);
979       }
980       dbgs() << ":\t" << LR << '\n';
981     });
982     if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
983       handleMoveDown(LR);
984     else
985       handleMoveUp(LR, Reg, LaneMask);
986     DEBUG(dbgs() << "        -->\t" << LR << '\n');
987     LR.verify();
988   }
989
990   /// Update LR to reflect an instruction has been moved downwards from OldIdx
991   /// to NewIdx.
992   ///
993   /// 1. Live def at OldIdx:
994   ///    Move def to NewIdx, assert endpoint after NewIdx.
995   ///
996   /// 2. Live def at OldIdx, killed at NewIdx:
997   ///    Change to dead def at NewIdx.
998   ///    (Happens when bundling def+kill together).
999   ///
1000   /// 3. Dead def at OldIdx:
1001   ///    Move def to NewIdx, possibly across another live value.
1002   ///
1003   /// 4. Def at OldIdx AND at NewIdx:
1004   ///    Remove segment [OldIdx;NewIdx) and value defined at OldIdx.
1005   ///    (Happens when bundling multiple defs together).
1006   ///
1007   /// 5. Value read at OldIdx, killed before NewIdx:
1008   ///    Extend kill to NewIdx.
1009   ///
1010   void handleMoveDown(LiveRange &LR) {
1011     // First look for a kill at OldIdx.
1012     LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
1013     LiveRange::iterator E = LR.end();
1014     // Is LR even live at OldIdx?
1015     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1016       return;
1017
1018     // Handle a live-in value.
1019     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1020       bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
1021       // If the live-in value already extends to NewIdx, there is nothing to do.
1022       if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
1023         return;
1024       // Aggressively remove all kill flags from the old kill point.
1025       // Kill flags shouldn't be used while live intervals exist, they will be
1026       // reinserted by VirtRegRewriter.
1027       if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
1028         for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
1029           if (MO->isReg() && MO->isUse())
1030             MO->setIsKill(false);
1031       // Adjust I->end to reach NewIdx. This may temporarily make LR invalid by
1032       // overlapping ranges. Case 5 above.
1033       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1034       // If this was a kill, there may also be a def. Otherwise we're done.
1035       if (!isKill)
1036         return;
1037       ++I;
1038     }
1039
1040     // Check for a def at OldIdx.
1041     if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
1042       return;
1043     // We have a def at OldIdx.
1044     VNInfo *DefVNI = I->valno;
1045     assert(DefVNI->def == I->start && "Inconsistent def");
1046     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1047     // If the defined value extends beyond NewIdx, just move the def down.
1048     // This is case 1 above.
1049     if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
1050       I->start = DefVNI->def;
1051       return;
1052     }
1053     // The remaining possibilities are now:
1054     // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
1055     // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
1056     // In either case, it is possible that there is an existing def at NewIdx.
1057     assert((I->end == OldIdx.getDeadSlot() ||
1058             SlotIndex::isSameInstr(I->end, NewIdx)) &&
1059             "Cannot move def below kill");
1060     LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
1061     if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1062       // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
1063       // coalesced into that value.
1064       assert(NewI->valno != DefVNI && "Multiple defs of value?");
1065       LR.removeValNo(DefVNI);
1066       return;
1067     }
1068     // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
1069     // If the def at OldIdx was dead, we allow it to be moved across other LR
1070     // values. The new range should be placed immediately before NewI, move any
1071     // intermediate ranges up.
1072     assert(NewI != I && "Inconsistent iterators");
1073     std::copy(std::next(I), NewI, I);
1074     *std::prev(NewI)
1075       = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1076   }
1077
1078   /// Update LR to reflect an instruction has been moved upwards from OldIdx
1079   /// to NewIdx.
1080   ///
1081   /// 1. Live def at OldIdx:
1082   ///    Hoist def to NewIdx.
1083   ///
1084   /// 2. Dead def at OldIdx:
1085   ///    Hoist def+end to NewIdx, possibly move across other values.
1086   ///
1087   /// 3. Dead def at OldIdx AND existing def at NewIdx:
1088   ///    Remove value defined at OldIdx, coalescing it with existing value.
1089   ///
1090   /// 4. Live def at OldIdx AND existing def at NewIdx:
1091   ///    Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
1092   ///    (Happens when bundling multiple defs together).
1093   ///
1094   /// 5. Value killed at OldIdx:
1095   ///    Hoist kill to NewIdx, then scan for last kill between NewIdx and
1096   ///    OldIdx.
1097   ///
1098   void handleMoveUp(LiveRange &LR, unsigned Reg, unsigned LaneMask) {
1099     // First look for a kill at OldIdx.
1100     LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
1101     LiveRange::iterator E = LR.end();
1102     // Is LR even live at OldIdx?
1103     if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1104       return;
1105
1106     // Handle a live-in value.
1107     if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1108       // If the live-in value isn't killed here, there is nothing to do.
1109       if (!SlotIndex::isSameInstr(OldIdx, I->end))
1110         return;
1111       // Adjust I->end to end at NewIdx. If we are hoisting a kill above
1112       // another use, we need to search for that use. Case 5 above.
1113       I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1114       ++I;
1115       // If OldIdx also defines a value, there couldn't have been another use.
1116       if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
1117         // No def, search for the new kill.
1118         // This can never be an early clobber kill since there is no def.
1119         std::prev(I)->end = findLastUseBefore(Reg, LaneMask).getRegSlot();
1120         return;
1121       }
1122     }
1123
1124     // Now deal with the def at OldIdx.
1125     assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
1126     VNInfo *DefVNI = I->valno;
1127     assert(DefVNI->def == I->start && "Inconsistent def");
1128     DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1129
1130     // Check for an existing def at NewIdx.
1131     LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
1132     if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1133       assert(NewI->valno != DefVNI && "Same value defined more than once?");
1134       // There is an existing def at NewIdx.
1135       if (I->end.isDead()) {
1136         // Case 3: Remove the dead def at OldIdx.
1137         LR.removeValNo(DefVNI);
1138         return;
1139       }
1140       // Case 4: Replace def at NewIdx with live def at OldIdx.
1141       I->start = DefVNI->def;
1142       LR.removeValNo(NewI->valno);
1143       return;
1144     }
1145
1146     // There is no existing def at NewIdx. Hoist DefVNI.
1147     if (!I->end.isDead()) {
1148       // Leave the end point of a live def.
1149       I->start = DefVNI->def;
1150       return;
1151     }
1152
1153     // DefVNI is a dead def. It may have been moved across other values in LR,
1154     // so move I up to NewI. Slide [NewI;I) down one position.
1155     std::copy_backward(NewI, I, std::next(I));
1156     *NewI = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1157   }
1158
1159   void updateRegMaskSlots() {
1160     SmallVectorImpl<SlotIndex>::iterator RI =
1161       std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1162                        OldIdx);
1163     assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1164            "No RegMask at OldIdx.");
1165     *RI = NewIdx.getRegSlot();
1166     assert((RI == LIS.RegMaskSlots.begin() ||
1167             SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1168            "Cannot move regmask instruction above another call");
1169     assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1170             SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1171            "Cannot move regmask instruction below another call");
1172   }
1173
1174   // Return the last use of reg between NewIdx and OldIdx.
1175   SlotIndex findLastUseBefore(unsigned Reg, unsigned LaneMask) {
1176
1177     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1178       SlotIndex LastUse = NewIdx;
1179       for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1180         unsigned SubReg = MO.getSubReg();
1181         if (SubReg != 0 && LaneMask != 0
1182             && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask) == 0)
1183           continue;
1184
1185         const MachineInstr *MI = MO.getParent();
1186         SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1187         if (InstSlot > LastUse && InstSlot < OldIdx)
1188           LastUse = InstSlot;
1189       }
1190       return LastUse;
1191     }
1192
1193     // This is a regunit interval, so scanning the use list could be very
1194     // expensive. Scan upwards from OldIdx instead.
1195     assert(NewIdx < OldIdx && "Expected upwards move");
1196     SlotIndexes *Indexes = LIS.getSlotIndexes();
1197     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
1198
1199     // OldIdx may not correspond to an instruction any longer, so set MII to
1200     // point to the next instruction after OldIdx, or MBB->end().
1201     MachineBasicBlock::iterator MII = MBB->end();
1202     if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1203                            Indexes->getNextNonNullIndex(OldIdx)))
1204       if (MI->getParent() == MBB)
1205         MII = MI;
1206
1207     MachineBasicBlock::iterator Begin = MBB->begin();
1208     while (MII != Begin) {
1209       if ((--MII)->isDebugValue())
1210         continue;
1211       SlotIndex Idx = Indexes->getInstructionIndex(MII);
1212
1213       // Stop searching when NewIdx is reached.
1214       if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
1215         return NewIdx;
1216
1217       // Check if MII uses Reg.
1218       for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1219         if (MO->isReg() &&
1220             TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1221             TRI.hasRegUnit(MO->getReg(), Reg))
1222           return Idx;
1223     }
1224     // Didn't reach NewIdx. It must be the first instruction in the block.
1225     return NewIdx;
1226   }
1227 };
1228
1229 void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
1230   assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
1231   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1232   Indexes->removeMachineInstrFromMaps(MI);
1233   SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1234   assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1235          OldIndex < getMBBEndIdx(MI->getParent()) &&
1236          "Cannot handle moves across basic block boundaries.");
1237
1238   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1239   HME.updateAllRanges(MI);
1240 }
1241
1242 void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
1243                                          MachineInstr* BundleStart,
1244                                          bool UpdateFlags) {
1245   SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1246   SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1247   HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1248   HME.updateAllRanges(MI);
1249 }
1250
1251 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1252                                         const MachineBasicBlock::iterator End,
1253                                         const SlotIndex endIdx,
1254                                         LiveRange &LR, const unsigned Reg,
1255                                         const unsigned LaneMask) {
1256   LiveInterval::iterator LII = LR.find(endIdx);
1257   SlotIndex lastUseIdx;
1258   if (LII != LR.end() && LII->start < endIdx)
1259     lastUseIdx = LII->end;
1260   else
1261     --LII;
1262
1263   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1264     --I;
1265     MachineInstr *MI = I;
1266     if (MI->isDebugValue())
1267       continue;
1268
1269     SlotIndex instrIdx = getInstructionIndex(MI);
1270     bool isStartValid = getInstructionFromIndex(LII->start);
1271     bool isEndValid = getInstructionFromIndex(LII->end);
1272
1273     // FIXME: This doesn't currently handle early-clobber or multiple removed
1274     // defs inside of the region to repair.
1275     for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1276          OE = MI->operands_end(); OI != OE; ++OI) {
1277       const MachineOperand &MO = *OI;
1278       if (!MO.isReg() || MO.getReg() != Reg)
1279         continue;
1280
1281       unsigned SubReg = MO.getSubReg();
1282       unsigned Mask = TRI->getSubRegIndexLaneMask(SubReg);
1283       if ((Mask & LaneMask) == 0)
1284         continue;
1285
1286       if (MO.isDef()) {
1287         if (!isStartValid) {
1288           if (LII->end.isDead()) {
1289             SlotIndex prevStart;
1290             if (LII != LR.begin())
1291               prevStart = std::prev(LII)->start;
1292
1293             // FIXME: This could be more efficient if there was a
1294             // removeSegment method that returned an iterator.
1295             LR.removeSegment(*LII, true);
1296             if (prevStart.isValid())
1297               LII = LR.find(prevStart);
1298             else
1299               LII = LR.begin();
1300           } else {
1301             LII->start = instrIdx.getRegSlot();
1302             LII->valno->def = instrIdx.getRegSlot();
1303             if (MO.getSubReg() && !MO.isUndef())
1304               lastUseIdx = instrIdx.getRegSlot();
1305             else
1306               lastUseIdx = SlotIndex();
1307             continue;
1308           }
1309         }
1310
1311         if (!lastUseIdx.isValid()) {
1312           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1313           LiveRange::Segment S(instrIdx.getRegSlot(),
1314                                instrIdx.getDeadSlot(), VNI);
1315           LII = LR.addSegment(S);
1316         } else if (LII->start != instrIdx.getRegSlot()) {
1317           VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1318           LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1319           LII = LR.addSegment(S);
1320         }
1321
1322         if (MO.getSubReg() && !MO.isUndef())
1323           lastUseIdx = instrIdx.getRegSlot();
1324         else
1325           lastUseIdx = SlotIndex();
1326       } else if (MO.isUse()) {
1327         // FIXME: This should probably be handled outside of this branch,
1328         // either as part of the def case (for defs inside of the region) or
1329         // after the loop over the region.
1330         if (!isEndValid && !LII->end.isBlock())
1331           LII->end = instrIdx.getRegSlot();
1332         if (!lastUseIdx.isValid())
1333           lastUseIdx = instrIdx.getRegSlot();
1334       }
1335     }
1336   }
1337 }
1338
1339 void
1340 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
1341                                       MachineBasicBlock::iterator Begin,
1342                                       MachineBasicBlock::iterator End,
1343                                       ArrayRef<unsigned> OrigRegs) {
1344   // Find anchor points, which are at the beginning/end of blocks or at
1345   // instructions that already have indexes.
1346   while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1347     --Begin;
1348   while (End != MBB->end() && !Indexes->hasIndex(End))
1349     ++End;
1350
1351   SlotIndex endIdx;
1352   if (End == MBB->end())
1353     endIdx = getMBBEndIdx(MBB).getPrevSlot();
1354   else
1355     endIdx = getInstructionIndex(End);
1356
1357   Indexes->repairIndexesInRange(MBB, Begin, End);
1358
1359   for (MachineBasicBlock::iterator I = End; I != Begin;) {
1360     --I;
1361     MachineInstr *MI = I;
1362     if (MI->isDebugValue())
1363       continue;
1364     for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1365          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1366       if (MOI->isReg() &&
1367           TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1368           !hasInterval(MOI->getReg())) {
1369         createAndComputeVirtRegInterval(MOI->getReg());
1370       }
1371     }
1372   }
1373
1374   for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1375     unsigned Reg = OrigRegs[i];
1376     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1377       continue;
1378
1379     LiveInterval &LI = getInterval(Reg);
1380     // FIXME: Should we support undefs that gain defs?
1381     if (!LI.hasAtLeastOneValue())
1382       continue;
1383
1384     for (LiveInterval::SubRange &S : LI.subranges()) {
1385       repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1386     }
1387     repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1388   }
1389 }
1390
1391 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1392   for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1393     if (LiveRange *LR = getCachedRegUnit(*Units))
1394       if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1395         LR->removeValNo(VNI);
1396   }
1397 }
1398
1399 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1400   VNInfo *VNI = LI.getVNInfoAt(Pos);
1401   if (VNI == nullptr)
1402     return;
1403   LI.removeValNo(VNI);
1404
1405   // Also remove the value in subranges.
1406   for (LiveInterval::SubRange &S : LI.subranges()) {
1407     if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1408       S.removeValNo(SVNI);
1409   }
1410   LI.removeEmptySubRanges();
1411 }