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