Skip to content
SplitKit.cpp 48.4 KiB
Newer Older
         "Range cannot span basic blocks");

  // Treat this as useIntv() for now. The complement interval will be extended
  // as needed by mapValue().
  DEBUG(dbgs() << "    overlapIntv [" << Start << ';' << End << "):");
  RegAssign.insert(Start, End, OpenIdx);
  DEBUG(dump());
}

/// closeIntv - Indicate that we are done editing the currently open
void SplitEditor::closeIntv() {
Eric Christopher's avatar
Eric Christopher committed
  assert(OpenIdx && "openIntv not called before closeIntv");
  OpenIdx = 0;
Eric Christopher's avatar
Eric Christopher committed
/// rewriteAssigned - Rewrite all uses of Edit.getReg().
void SplitEditor::rewriteAssigned() {
  for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit.getReg()),
       RE = MRI.reg_end(); RI != RE;) {
    MachineOperand &MO = RI.getOperand();
    MachineInstr *MI = MO.getParent();
    ++RI;
Eric Christopher's avatar
Eric Christopher committed
    // LiveDebugVariables should have handled all DBG_VALUE instructions.
    if (MI->isDebugValue()) {
      DEBUG(dbgs() << "Zapping " << *MI);
      MO.setReg(0);
      continue;
    }

    // <undef> operands don't really read the register, so just assign them to
    // the complement.
    if (MO.isUse() && MO.isUndef()) {
      MO.setReg(Edit.get(0)->reg);
      continue;
    }

    SlotIndex Idx = LIS.getInstructionIndex(MI);
    Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
Eric Christopher's avatar
Eric Christopher committed

    // Rewrite to the mapped register at Idx.
    unsigned RegIdx = RegAssign.lookup(Idx);
    MO.setReg(Edit.get(RegIdx)->reg);
    DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
                 << Idx << ':' << RegIdx << '\t' << *MI);

    // Extend liveness to Idx.
    const VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx);
    LIMappers[RegIdx].mapValue(ParentVNI, Idx);
Eric Christopher's avatar
Eric Christopher committed
/// rewriteSplit - Rewrite uses of Intvs[0] according to the ConEQ mapping.
void SplitEditor::rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs,
                                    const ConnectedVNInfoEqClasses &ConEq) {
  for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Intvs[0]->reg),
       RE = MRI.reg_end(); RI != RE;) {
    MachineOperand &MO = RI.getOperand();
    MachineInstr *MI = MO.getParent();
    ++RI;
    if (MO.isUse() && MO.isUndef())
Eric Christopher's avatar
Eric Christopher committed
    // DBG_VALUE instructions should have been eliminated earlier.
    SlotIndex Idx = LIS.getInstructionIndex(MI);
    Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
    DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
                 << Idx << ':');
    const VNInfo *VNI = Intvs[0]->getVNInfoAt(Idx);
    assert(VNI && "Interval not live at use.");
    MO.setReg(Intvs[ConEq.getEqClass(VNI)]->reg);
    DEBUG(dbgs() << VNI->id << '\t' << *MI);
Eric Christopher's avatar
Eric Christopher committed
void SplitEditor::finish() {
  assert(OpenIdx == 0 && "Previous LI not closed before rewrite");

  // At this point, the live intervals in Edit contain VNInfos corresponding to
  // the inserted copies.

  // Add the original defs from the parent interval.
  for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(),
         E = Edit.getParent().vni_end(); I != E; ++I) {
    const VNInfo *ParentVNI = *I;
    if (ParentVNI->isUnused())
      continue;
Eric Christopher's avatar
Eric Christopher committed
    LiveIntervalMap &LIM = LIMappers[RegAssign.lookup(ParentVNI->def)];
    VNInfo *VNI = LIM.defValue(ParentVNI, ParentVNI->def);
    LIM.getLI()->addRange(LiveRange(ParentVNI->def,
                                    ParentVNI->def.getNextSlot(), VNI));
    // Mark all values as complex to force liveness computation.
    // This should really only be necessary for remat victims, but we are lazy.
    LIM.markComplexMapped(ParentVNI);
Eric Christopher's avatar
Eric Christopher committed
#ifndef NDEBUG
  // Every new interval must have a def by now, otherwise the split is bogus.
  for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I)
    assert((*I)->hasAtLeastOneValue() && "Split interval has no value");
#endif

  // FIXME: Don't recompute the liveness of all values, infer it from the
  // overlaps between the parent live interval and RegAssign.
  // The mapValue algorithm is only necessary when:
  // - The parent value maps to multiple defs, and new phis are needed, or
  // - The value has been rematerialized before some uses, and we want to
  //   minimize the live range so it only reaches the remaining uses.
  // All other values have simple liveness that can be computed from RegAssign
  // and the parent live interval.

  // Extend live ranges to be live-out for successor PHI values.
  for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(),
       E = Edit.getParent().vni_end(); I != E; ++I) {
    const VNInfo *PHIVNI = *I;
    if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
Eric Christopher's avatar
Eric Christopher committed
      continue;
    unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
    LiveIntervalMap &LIM = LIMappers[RegIdx];
Eric Christopher's avatar
Eric Christopher committed
    MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
    DEBUG(dbgs() << "  map phi in BB#" << MBB->getNumber() << '@' << PHIVNI->def
                 << " -> " << RegIdx << '\n');
Eric Christopher's avatar
Eric Christopher committed
    for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
         PE = MBB->pred_end(); PI != PE; ++PI) {
      SlotIndex End = LIS.getMBBEndIdx(*PI).getPrevSlot();
      DEBUG(dbgs() << "    pred BB#" << (*PI)->getNumber() << '@' << End);
Eric Christopher's avatar
Eric Christopher committed
      // The predecessor may not have a live-out value. That is OK, like an
      // undef PHI operand.
      if (VNInfo *VNI = Edit.getParent().getVNInfoAt(End)) {
        DEBUG(dbgs() << " has parent valno #" << VNI->id << " live out\n");
        assert(RegAssign.lookup(End) == RegIdx &&
               "Different register assignment in phi predecessor");
Eric Christopher's avatar
Eric Christopher committed
        LIM.mapValue(VNI, End);
      }
      else
        DEBUG(dbgs() << " is not live-out\n");
    DEBUG(dbgs() << "    " << *LIM.getLI() << '\n');
Eric Christopher's avatar
Eric Christopher committed
  // Rewrite instructions.
  rewriteAssigned();
Eric Christopher's avatar
Eric Christopher committed
  // FIXME: Delete defs that were rematted everywhere.
  // Get rid of unused values and set phi-kill flags.
  for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I)
    (*I)->RenumberValues(LIS);
  // Now check if any registers were separated into multiple components.
  ConnectedVNInfoEqClasses ConEQ(LIS);
  for (unsigned i = 0, e = Edit.size(); i != e; ++i) {
    // Don't use iterators, they are invalidated by create() below.
    LiveInterval *li = Edit.get(i);
    unsigned NumComp = ConEQ.Classify(li);
    if (NumComp <= 1)
      continue;
    DEBUG(dbgs() << "  " << NumComp << " components: " << *li << '\n');
    SmallVector<LiveInterval*, 8> dups;
    dups.push_back(li);
    for (unsigned i = 1; i != NumComp; ++i)
      dups.push_back(&Edit.create(MRI, LIS, VRM));
Eric Christopher's avatar
Eric Christopher committed
    rewriteComponents(dups, ConEQ);
  // Calculate spill weight and allocation hints for new intervals.
  VirtRegAuxInfo vrai(VRM.getMachineFunction(), LIS, sa_.Loops);
  for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I){
    vrai.CalculateRegClass(li.reg);
    DEBUG(dbgs() << "  new interval " << MRI.getRegClass(li.reg)->getName()
                 << ":" << li << '\n');
//===----------------------------------------------------------------------===//
//                               Loop Splitting
//===----------------------------------------------------------------------===//

void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
  SplitAnalysis::LoopBlocks Blocks;
  sa_.getLoopBlocks(Loop, Blocks);

  DEBUG({
Jakob Stoklund Olesen's avatar
Jakob Stoklund Olesen committed
    dbgs() << "  splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
  // Break critical edges as needed.
  SplitAnalysis::BlockPtrSet CriticalExits;
  sa_.getCriticalExits(Blocks, CriticalExits);
  assert(CriticalExits.empty() && "Cannot break critical exits yet");

  // Create new live interval for the loop.
  // Insert copies in the predecessors if live-in to the header.
  if (LIS.isLiveInToMBB(Edit.getParent(), Loop->getHeader())) {
    for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
           E = Blocks.Preds.end(); I != E; ++I) {
      MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
      enterIntvAtEnd(MBB);
    }
  }

  // Switch all loop blocks.
  for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
       E = Blocks.Loop.end(); I != E; ++I)
     useIntv(**I);

  // Insert back copies in the exit blocks.
  for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
       E = Blocks.Exits.end(); I != E; ++I) {
    MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
    leaveIntvAtTop(MBB);
  closeIntv();

//===----------------------------------------------------------------------===//
//                            Single Block Splitting
//===----------------------------------------------------------------------===//

/// getMultiUseBlocks - if CurLI has more than one use in a basic block, it
/// may be an advantage to split CurLI for the duration of the block.
bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
  // If CurLI is local to one block, there is no point to splitting it.
    return false;
  // Add blocks with multiple uses.
  for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
    const BlockInfo &BI = LiveBlocks[i];
    if (!BI.Uses)
    unsigned Instrs = UsingBlocks.lookup(BI.MBB);
    if (Instrs <= 1)
      continue;
    if (Instrs == 2 && BI.LiveIn && BI.LiveOut && !BI.LiveThrough)
      continue;
    Blocks.insert(BI.MBB);
  }
/// splitSingleBlocks - Split CurLI into a separate live interval inside each
/// basic block in Blocks.
void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
  DEBUG(dbgs() << "  splitSingleBlocks for " << Blocks.size() << " blocks.\n");
  for (unsigned i = 0, e = sa_.LiveBlocks.size(); i != e; ++i) {
    const SplitAnalysis::BlockInfo &BI = sa_.LiveBlocks[i];
    if (!BI.Uses || !Blocks.count(BI.MBB))
      continue;
    SlotIndex SegStart = enterIntvBefore(BI.FirstUse);
    if (BI.LastUse < BI.LastSplitPoint) {
      useIntv(SegStart, leaveIntvAfter(BI.LastUse));
    } else {
      // THe last use os after tha last valid split point.
      SlotIndex SegStop = leaveIntvBefore(BI.LastSplitPoint);
      useIntv(SegStart, SegStop);
      overlapIntv(SegStop, BI.LastUse);
    }

//===----------------------------------------------------------------------===//
//                            Sub Block Splitting
//===----------------------------------------------------------------------===//

/// getBlockForInsideSplit - If CurLI is contained inside a single basic block,
/// and it wou pay to subdivide the interval inside that block, return it.
/// Otherwise return NULL. The returned block can be passed to
/// SplitEditor::splitInsideBlock.
const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
  // The interval must be exclusive to one block.
  if (UsingBlocks.size() != 1)
    return 0;
  // Don't to this for less than 4 instructions. We want to be sure that
  // splitting actually reduces the instruction count per interval.
  if (UsingInstrs.size() < 4)
  return UsingBlocks.begin()->first;
/// splitInsideBlock - Split CurLI into multiple intervals inside MBB.
void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
  SmallVector<SlotIndex, 32> Uses;
  Uses.reserve(sa_.UsingInstrs.size());
  for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.UsingInstrs.begin(),
       E = sa_.UsingInstrs.end(); I != E; ++I)
    if ((*I)->getParent() == MBB)
      Uses.push_back(LIS.getInstructionIndex(*I));
  DEBUG(dbgs() << "  splitInsideBlock BB#" << MBB->getNumber() << " for "
               << Uses.size() << " instructions.\n");
  assert(Uses.size() >= 3 && "Need at least 3 instructions");
  array_pod_sort(Uses.begin(), Uses.end());

  // Simple algorithm: Find the largest gap between uses as determined by slot
  // indices. Create new intervals for instructions before the gap and after the
  // gap.
  unsigned bestPos = 0;
  int bestGap = 0;
  DEBUG(dbgs() << "    dist (" << Uses[0]);
  for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
    int g = Uses[i-1].distance(Uses[i]);
    DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
    if (g > bestGap)
      bestPos = i, bestGap = g;
  }
  DEBUG(dbgs() << "), best: -" << bestGap << "-\n");

  // bestPos points to the first use after the best gap.
  assert(bestPos > 0 && "Invalid gap");

  // FIXME: Don't create intervals for low densities.

  // First interval before the gap. Don't create single-instr intervals.
  if (bestPos > 1) {
    openIntv();
    useIntv(enterIntvBefore(Uses.front()), leaveIntvAfter(Uses[bestPos-1]));
    closeIntv();
  }

  // Second interval after the gap.
  if (bestPos < Uses.size()-1) {
    openIntv();
    useIntv(enterIntvBefore(Uses[bestPos]), leaveIntvAfter(Uses.back()));