Home | History | Annotate | Download | only in CodeGen
      1 //===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
      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 // The LiveRangeEdit class represents changes done to a virtual register when it
     11 // is spilled or split.
     12 //===----------------------------------------------------------------------===//
     13 
     14 #define DEBUG_TYPE "regalloc"
     15 #include "LiveRangeEdit.h"
     16 #include "VirtRegMap.h"
     17 #include "llvm/ADT/SetVector.h"
     18 #include "llvm/ADT/Statistic.h"
     19 #include "llvm/CodeGen/CalcSpillWeights.h"
     20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
     21 #include "llvm/CodeGen/MachineRegisterInfo.h"
     22 #include "llvm/Target/TargetInstrInfo.h"
     23 #include "llvm/Support/Debug.h"
     24 #include "llvm/Support/raw_ostream.h"
     25 
     26 using namespace llvm;
     27 
     28 STATISTIC(NumDCEDeleted,     "Number of instructions deleted by DCE");
     29 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
     30 STATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
     31 
     32 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg,
     33                                         LiveIntervals &LIS,
     34                                         VirtRegMap &VRM) {
     35   MachineRegisterInfo &MRI = VRM.getRegInfo();
     36   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
     37   VRM.grow();
     38   VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
     39   LiveInterval &LI = LIS.getOrCreateInterval(VReg);
     40   newRegs_.push_back(&LI);
     41   return LI;
     42 }
     43 
     44 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
     45                                           const MachineInstr *DefMI,
     46                                           const TargetInstrInfo &tii,
     47                                           AliasAnalysis *aa) {
     48   assert(DefMI && "Missing instruction");
     49   scannedRemattable_ = true;
     50   if (!tii.isTriviallyReMaterializable(DefMI, aa))
     51     return false;
     52   remattable_.insert(VNI);
     53   return true;
     54 }
     55 
     56 void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
     57                                    const TargetInstrInfo &tii,
     58                                    AliasAnalysis *aa) {
     59   for (LiveInterval::vni_iterator I = parent_.vni_begin(),
     60        E = parent_.vni_end(); I != E; ++I) {
     61     VNInfo *VNI = *I;
     62     if (VNI->isUnused())
     63       continue;
     64     MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
     65     if (!DefMI)
     66       continue;
     67     checkRematerializable(VNI, DefMI, tii, aa);
     68   }
     69   scannedRemattable_ = true;
     70 }
     71 
     72 bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
     73                                         const TargetInstrInfo &tii,
     74                                         AliasAnalysis *aa) {
     75   if (!scannedRemattable_)
     76     scanRemattable(lis, tii, aa);
     77   return !remattable_.empty();
     78 }
     79 
     80 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
     81 /// OrigIdx are also available with the same value at UseIdx.
     82 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
     83                                        SlotIndex OrigIdx,
     84                                        SlotIndex UseIdx,
     85                                        LiveIntervals &lis) {
     86   OrigIdx = OrigIdx.getUseIndex();
     87   UseIdx = UseIdx.getUseIndex();
     88   for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
     89     const MachineOperand &MO = OrigMI->getOperand(i);
     90     if (!MO.isReg() || !MO.getReg() || MO.isDef())
     91       continue;
     92     // Reserved registers are OK.
     93     if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
     94       continue;
     95     // We cannot depend on virtual registers in uselessRegs_.
     96     if (uselessRegs_)
     97       for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
     98         if ((*uselessRegs_)[ui]->reg == MO.getReg())
     99           return false;
    100 
    101     LiveInterval &li = lis.getInterval(MO.getReg());
    102     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
    103     if (!OVNI)
    104       continue;
    105     if (OVNI != li.getVNInfoAt(UseIdx))
    106       return false;
    107   }
    108   return true;
    109 }
    110 
    111 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
    112                                        SlotIndex UseIdx,
    113                                        bool cheapAsAMove,
    114                                        LiveIntervals &lis) {
    115   assert(scannedRemattable_ && "Call anyRematerializable first");
    116 
    117   // Use scanRemattable info.
    118   if (!remattable_.count(RM.ParentVNI))
    119     return false;
    120 
    121   // No defining instruction provided.
    122   SlotIndex DefIdx;
    123   if (RM.OrigMI)
    124     DefIdx = lis.getInstructionIndex(RM.OrigMI);
    125   else {
    126     DefIdx = RM.ParentVNI->def;
    127     RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
    128     assert(RM.OrigMI && "No defining instruction for remattable value");
    129   }
    130 
    131   // If only cheap remats were requested, bail out early.
    132   if (cheapAsAMove && !RM.OrigMI->getDesc().isAsCheapAsAMove())
    133     return false;
    134 
    135   // Verify that all used registers are available with the same values.
    136   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
    137     return false;
    138 
    139   return true;
    140 }
    141 
    142 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
    143                                          MachineBasicBlock::iterator MI,
    144                                          unsigned DestReg,
    145                                          const Remat &RM,
    146                                          LiveIntervals &lis,
    147                                          const TargetInstrInfo &tii,
    148                                          const TargetRegisterInfo &tri,
    149                                          bool Late) {
    150   assert(RM.OrigMI && "Invalid remat");
    151   tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
    152   rematted_.insert(RM.ParentVNI);
    153   return lis.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
    154            .getDefIndex();
    155 }
    156 
    157 void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
    158   if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
    159     LIS.removeInterval(Reg);
    160 }
    161 
    162 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
    163                                SmallVectorImpl<MachineInstr*> &Dead,
    164                                MachineRegisterInfo &MRI,
    165                                LiveIntervals &LIS,
    166                                const TargetInstrInfo &TII) {
    167   MachineInstr *DefMI = 0, *UseMI = 0;
    168 
    169   // Check that there is a single def and a single use.
    170   for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
    171        E = MRI.reg_nodbg_end(); I != E; ++I) {
    172     MachineOperand &MO = I.getOperand();
    173     MachineInstr *MI = MO.getParent();
    174     if (MO.isDef()) {
    175       if (DefMI && DefMI != MI)
    176         return false;
    177       if (!MI->getDesc().canFoldAsLoad())
    178         return false;
    179       DefMI = MI;
    180     } else if (!MO.isUndef()) {
    181       if (UseMI && UseMI != MI)
    182         return false;
    183       // FIXME: Targets don't know how to fold subreg uses.
    184       if (MO.getSubReg())
    185         return false;
    186       UseMI = MI;
    187     }
    188   }
    189   if (!DefMI || !UseMI)
    190     return false;
    191 
    192   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
    193                << "       into single use: " << *UseMI);
    194 
    195   SmallVector<unsigned, 8> Ops;
    196   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
    197     return false;
    198 
    199   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
    200   if (!FoldMI)
    201     return false;
    202   DEBUG(dbgs() << "                folded: " << *FoldMI);
    203   LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
    204   UseMI->eraseFromParent();
    205   DefMI->addRegisterDead(LI->reg, 0);
    206   Dead.push_back(DefMI);
    207   ++NumDCEFoldedLoads;
    208   return true;
    209 }
    210 
    211 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
    212                                       LiveIntervals &LIS, VirtRegMap &VRM,
    213                                       const TargetInstrInfo &TII) {
    214   SetVector<LiveInterval*,
    215             SmallVector<LiveInterval*, 8>,
    216             SmallPtrSet<LiveInterval*, 8> > ToShrink;
    217   MachineRegisterInfo &MRI = VRM.getRegInfo();
    218 
    219   for (;;) {
    220     // Erase all dead defs.
    221     while (!Dead.empty()) {
    222       MachineInstr *MI = Dead.pop_back_val();
    223       assert(MI->allDefsAreDead() && "Def isn't really dead");
    224       SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
    225 
    226       // Never delete inline asm.
    227       if (MI->isInlineAsm()) {
    228         DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
    229         continue;
    230       }
    231 
    232       // Use the same criteria as DeadMachineInstructionElim.
    233       bool SawStore = false;
    234       if (!MI->isSafeToMove(&TII, 0, SawStore)) {
    235         DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
    236         continue;
    237       }
    238 
    239       DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
    240 
    241       // Check for live intervals that may shrink
    242       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
    243              MOE = MI->operands_end(); MOI != MOE; ++MOI) {
    244         if (!MOI->isReg())
    245           continue;
    246         unsigned Reg = MOI->getReg();
    247         if (!TargetRegisterInfo::isVirtualRegister(Reg))
    248           continue;
    249         LiveInterval &LI = LIS.getInterval(Reg);
    250 
    251         // Shrink read registers, unless it is likely to be expensive and
    252         // unlikely to change anything. We typically don't want to shrink the
    253         // PIC base register that has lots of uses everywhere.
    254         // Always shrink COPY uses that probably come from live range splitting.
    255         if (MI->readsVirtualRegister(Reg) &&
    256             (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
    257              LI.killedAt(Idx)))
    258           ToShrink.insert(&LI);
    259 
    260         // Remove defined value.
    261         if (MOI->isDef()) {
    262           if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
    263             if (delegate_)
    264               delegate_->LRE_WillShrinkVirtReg(LI.reg);
    265             LI.removeValNo(VNI);
    266             if (LI.empty()) {
    267               ToShrink.remove(&LI);
    268               eraseVirtReg(Reg, LIS);
    269             }
    270           }
    271         }
    272       }
    273 
    274       if (delegate_)
    275         delegate_->LRE_WillEraseInstruction(MI);
    276       LIS.RemoveMachineInstrFromMaps(MI);
    277       MI->eraseFromParent();
    278       ++NumDCEDeleted;
    279     }
    280 
    281     if (ToShrink.empty())
    282       break;
    283 
    284     // Shrink just one live interval. Then delete new dead defs.
    285     LiveInterval *LI = ToShrink.back();
    286     ToShrink.pop_back();
    287     if (foldAsLoad(LI, Dead, MRI, LIS, TII))
    288       continue;
    289     if (delegate_)
    290       delegate_->LRE_WillShrinkVirtReg(LI->reg);
    291     if (!LIS.shrinkToUses(LI, &Dead))
    292       continue;
    293 
    294     // LI may have been separated, create new intervals.
    295     LI->RenumberValues(LIS);
    296     ConnectedVNInfoEqClasses ConEQ(LIS);
    297     unsigned NumComp = ConEQ.Classify(LI);
    298     if (NumComp <= 1)
    299       continue;
    300     ++NumFracRanges;
    301     bool IsOriginal = VRM.getOriginal(LI->reg) == LI->reg;
    302     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
    303     SmallVector<LiveInterval*, 8> Dups(1, LI);
    304     for (unsigned i = 1; i != NumComp; ++i) {
    305       Dups.push_back(&createFrom(LI->reg, LIS, VRM));
    306       // If LI is an original interval that hasn't been split yet, make the new
    307       // intervals their own originals instead of referring to LI. The original
    308       // interval must contain all the split products, and LI doesn't.
    309       if (IsOriginal)
    310         VRM.setIsSplitFromReg(Dups.back()->reg, 0);
    311       if (delegate_)
    312         delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
    313     }
    314     ConEQ.Distribute(&Dups[0], MRI);
    315   }
    316 }
    317 
    318 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
    319                                              LiveIntervals &LIS,
    320                                              const MachineLoopInfo &Loops) {
    321   VirtRegAuxInfo VRAI(MF, LIS, Loops);
    322   MachineRegisterInfo &MRI = MF.getRegInfo();
    323   for (iterator I = begin(), E = end(); I != E; ++I) {
    324     LiveInterval &LI = **I;
    325     if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
    326       DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
    327                    << MRI.getRegClass(LI.reg)->getName() << '\n');
    328     VRAI.CalculateWeightAndHint(LI);
    329   }
    330 }
    331