LLVM API Documentation

LiveRangeEdit.cpp
Go to the documentation of this file.
00001 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // The LiveRangeEdit class represents changes done to a virtual register when it
00011 // is spilled or split.
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/LiveRangeEdit.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/CodeGen/CalcSpillWeights.h"
00017 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00018 #include "llvm/CodeGen/MachineRegisterInfo.h"
00019 #include "llvm/CodeGen/VirtRegMap.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Support/raw_ostream.h"
00022 #include "llvm/Target/TargetInstrInfo.h"
00023 
00024 using namespace llvm;
00025 
00026 #define DEBUG_TYPE "regalloc"
00027 
00028 STATISTIC(NumDCEDeleted,     "Number of instructions deleted by DCE");
00029 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
00030 STATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
00031 
00032 void LiveRangeEdit::Delegate::anchor() { }
00033 
00034 LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(unsigned OldReg) {
00035   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
00036   if (VRM) {
00037     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
00038   }
00039   LiveInterval &LI = LIS.createEmptyInterval(VReg);
00040   return LI;
00041 }
00042 
00043 unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
00044   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
00045   if (VRM) {
00046     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
00047   }
00048   return VReg;
00049 }
00050 
00051 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
00052                                           const MachineInstr *DefMI,
00053                                           AliasAnalysis *aa) {
00054   assert(DefMI && "Missing instruction");
00055   ScannedRemattable = true;
00056   if (!TII.isTriviallyReMaterializable(DefMI, aa))
00057     return false;
00058   Remattable.insert(VNI);
00059   return true;
00060 }
00061 
00062 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
00063   for (LiveInterval::vni_iterator I = getParent().vni_begin(),
00064        E = getParent().vni_end(); I != E; ++I) {
00065     VNInfo *VNI = *I;
00066     if (VNI->isUnused())
00067       continue;
00068     MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
00069     if (!DefMI)
00070       continue;
00071     checkRematerializable(VNI, DefMI, aa);
00072   }
00073   ScannedRemattable = true;
00074 }
00075 
00076 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
00077   if (!ScannedRemattable)
00078     scanRemattable(aa);
00079   return !Remattable.empty();
00080 }
00081 
00082 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
00083 /// OrigIdx are also available with the same value at UseIdx.
00084 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
00085                                        SlotIndex OrigIdx,
00086                                        SlotIndex UseIdx) const {
00087   OrigIdx = OrigIdx.getRegSlot(true);
00088   UseIdx = UseIdx.getRegSlot(true);
00089   for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
00090     const MachineOperand &MO = OrigMI->getOperand(i);
00091     if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
00092       continue;
00093 
00094     // We can't remat physreg uses, unless it is a constant.
00095     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
00096       if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
00097         continue;
00098       return false;
00099     }
00100 
00101     LiveInterval &li = LIS.getInterval(MO.getReg());
00102     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
00103     if (!OVNI)
00104       continue;
00105 
00106     // Don't allow rematerialization immediately after the original def.
00107     // It would be incorrect if OrigMI redefines the register.
00108     // See PR14098.
00109     if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
00110       return false;
00111 
00112     if (OVNI != li.getVNInfoAt(UseIdx))
00113       return false;
00114   }
00115   return true;
00116 }
00117 
00118 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
00119                                        SlotIndex UseIdx,
00120                                        bool cheapAsAMove) {
00121   assert(ScannedRemattable && "Call anyRematerializable first");
00122 
00123   // Use scanRemattable info.
00124   if (!Remattable.count(RM.ParentVNI))
00125     return false;
00126 
00127   // No defining instruction provided.
00128   SlotIndex DefIdx;
00129   if (RM.OrigMI)
00130     DefIdx = LIS.getInstructionIndex(RM.OrigMI);
00131   else {
00132     DefIdx = RM.ParentVNI->def;
00133     RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
00134     assert(RM.OrigMI && "No defining instruction for remattable value");
00135   }
00136 
00137   // If only cheap remats were requested, bail out early.
00138   if (cheapAsAMove && !TII.isAsCheapAsAMove(RM.OrigMI))
00139     return false;
00140 
00141   // Verify that all used registers are available with the same values.
00142   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
00143     return false;
00144 
00145   return true;
00146 }
00147 
00148 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
00149                                          MachineBasicBlock::iterator MI,
00150                                          unsigned DestReg,
00151                                          const Remat &RM,
00152                                          const TargetRegisterInfo &tri,
00153                                          bool Late) {
00154   assert(RM.OrigMI && "Invalid remat");
00155   TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
00156   Rematted.insert(RM.ParentVNI);
00157   return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
00158            .getRegSlot();
00159 }
00160 
00161 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
00162   if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
00163     LIS.removeInterval(Reg);
00164 }
00165 
00166 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
00167                                SmallVectorImpl<MachineInstr*> &Dead) {
00168   MachineInstr *DefMI = nullptr, *UseMI = nullptr;
00169 
00170   // Check that there is a single def and a single use.
00171   for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
00172     MachineInstr *MI = MO.getParent();
00173     if (MO.isDef()) {
00174       if (DefMI && DefMI != MI)
00175         return false;
00176       if (!MI->canFoldAsLoad())
00177         return false;
00178       DefMI = MI;
00179     } else if (!MO.isUndef()) {
00180       if (UseMI && UseMI != MI)
00181         return false;
00182       // FIXME: Targets don't know how to fold subreg uses.
00183       if (MO.getSubReg())
00184         return false;
00185       UseMI = MI;
00186     }
00187   }
00188   if (!DefMI || !UseMI)
00189     return false;
00190 
00191   // Since we're moving the DefMI load, make sure we're not extending any live
00192   // ranges.
00193   if (!allUsesAvailableAt(DefMI,
00194                           LIS.getInstructionIndex(DefMI),
00195                           LIS.getInstructionIndex(UseMI)))
00196     return false;
00197 
00198   // We also need to make sure it is safe to move the load.
00199   // Assume there are stores between DefMI and UseMI.
00200   bool SawStore = true;
00201   if (!DefMI->isSafeToMove(&TII, nullptr, SawStore))
00202     return false;
00203 
00204   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
00205                << "       into single use: " << *UseMI);
00206 
00207   SmallVector<unsigned, 8> Ops;
00208   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
00209     return false;
00210 
00211   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
00212   if (!FoldMI)
00213     return false;
00214   DEBUG(dbgs() << "                folded: " << *FoldMI);
00215   LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
00216   UseMI->eraseFromParent();
00217   DefMI->addRegisterDead(LI->reg, nullptr);
00218   Dead.push_back(DefMI);
00219   ++NumDCEFoldedLoads;
00220   return true;
00221 }
00222 
00223 /// Find all live intervals that need to shrink, then remove the instruction.
00224 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
00225   assert(MI->allDefsAreDead() && "Def isn't really dead");
00226   SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
00227 
00228   // Never delete a bundled instruction.
00229   if (MI->isBundled()) {
00230     return;
00231   }
00232   // Never delete inline asm.
00233   if (MI->isInlineAsm()) {
00234     DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
00235     return;
00236   }
00237 
00238   // Use the same criteria as DeadMachineInstructionElim.
00239   bool SawStore = false;
00240   if (!MI->isSafeToMove(&TII, nullptr, SawStore)) {
00241     DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
00242     return;
00243   }
00244 
00245   DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
00246 
00247   // Collect virtual registers to be erased after MI is gone.
00248   SmallVector<unsigned, 8> RegsToErase;
00249   bool ReadsPhysRegs = false;
00250 
00251   // Check for live intervals that may shrink
00252   for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
00253          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
00254     if (!MOI->isReg())
00255       continue;
00256     unsigned Reg = MOI->getReg();
00257     if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
00258       // Check if MI reads any unreserved physregs.
00259       if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
00260         ReadsPhysRegs = true;
00261       else if (MOI->isDef()) {
00262         for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo());
00263              Units.isValid(); ++Units) {
00264           if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
00265             if (VNInfo *VNI = LR->getVNInfoAt(Idx))
00266               LR->removeValNo(VNI);
00267           }
00268         }
00269       }
00270       continue;
00271     }
00272     LiveInterval &LI = LIS.getInterval(Reg);
00273 
00274     // Shrink read registers, unless it is likely to be expensive and
00275     // unlikely to change anything. We typically don't want to shrink the
00276     // PIC base register that has lots of uses everywhere.
00277     // Always shrink COPY uses that probably come from live range splitting.
00278     if (MI->readsVirtualRegister(Reg) &&
00279         (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
00280          LI.Query(Idx).isKill()))
00281       ToShrink.insert(&LI);
00282 
00283     // Remove defined value.
00284     if (MOI->isDef()) {
00285       if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
00286         if (TheDelegate)
00287           TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
00288         LI.removeValNo(VNI);
00289         if (LI.empty())
00290           RegsToErase.push_back(Reg);
00291       }
00292     }
00293   }
00294 
00295   // Currently, we don't support DCE of physreg live ranges. If MI reads
00296   // any unreserved physregs, don't erase the instruction, but turn it into
00297   // a KILL instead. This way, the physreg live ranges don't end up
00298   // dangling.
00299   // FIXME: It would be better to have something like shrinkToUses() for
00300   // physregs. That could potentially enable more DCE and it would free up
00301   // the physreg. It would not happen often, though.
00302   if (ReadsPhysRegs) {
00303     MI->setDesc(TII.get(TargetOpcode::KILL));
00304     // Remove all operands that aren't physregs.
00305     for (unsigned i = MI->getNumOperands(); i; --i) {
00306       const MachineOperand &MO = MI->getOperand(i-1);
00307       if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
00308         continue;
00309       MI->RemoveOperand(i-1);
00310     }
00311     DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
00312   } else {
00313     if (TheDelegate)
00314       TheDelegate->LRE_WillEraseInstruction(MI);
00315     LIS.RemoveMachineInstrFromMaps(MI);
00316     MI->eraseFromParent();
00317     ++NumDCEDeleted;
00318   }
00319 
00320   // Erase any virtregs that are now empty and unused. There may be <undef>
00321   // uses around. Keep the empty live range in that case.
00322   for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
00323     unsigned Reg = RegsToErase[i];
00324     if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
00325       ToShrink.remove(&LIS.getInterval(Reg));
00326       eraseVirtReg(Reg);
00327     }
00328   }
00329 }
00330 
00331 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
00332                                       ArrayRef<unsigned> RegsBeingSpilled) {
00333   ToShrinkSet ToShrink;
00334 
00335   for (;;) {
00336     // Erase all dead defs.
00337     while (!Dead.empty())
00338       eliminateDeadDef(Dead.pop_back_val(), ToShrink);
00339 
00340     if (ToShrink.empty())
00341       break;
00342 
00343     // Shrink just one live interval. Then delete new dead defs.
00344     LiveInterval *LI = ToShrink.back();
00345     ToShrink.pop_back();
00346     if (foldAsLoad(LI, Dead))
00347       continue;
00348     if (TheDelegate)
00349       TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
00350     if (!LIS.shrinkToUses(LI, &Dead))
00351       continue;
00352 
00353     // Don't create new intervals for a register being spilled.
00354     // The new intervals would have to be spilled anyway so its not worth it.
00355     // Also they currently aren't spilled so creating them and not spilling
00356     // them results in incorrect code.
00357     bool BeingSpilled = false;
00358     for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
00359       if (LI->reg == RegsBeingSpilled[i]) {
00360         BeingSpilled = true;
00361         break;
00362       }
00363     }
00364 
00365     if (BeingSpilled) continue;
00366 
00367     // LI may have been separated, create new intervals.
00368     LI->RenumberValues();
00369     ConnectedVNInfoEqClasses ConEQ(LIS);
00370     unsigned NumComp = ConEQ.Classify(LI);
00371     if (NumComp <= 1)
00372       continue;
00373     ++NumFracRanges;
00374     bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
00375     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
00376     SmallVector<LiveInterval*, 8> Dups(1, LI);
00377     for (unsigned i = 1; i != NumComp; ++i) {
00378       Dups.push_back(&createEmptyIntervalFrom(LI->reg));
00379       // If LI is an original interval that hasn't been split yet, make the new
00380       // intervals their own originals instead of referring to LI. The original
00381       // interval must contain all the split products, and LI doesn't.
00382       if (IsOriginal)
00383         VRM->setIsSplitFromReg(Dups.back()->reg, 0);
00384       if (TheDelegate)
00385         TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
00386     }
00387     ConEQ.Distribute(&Dups[0], MRI);
00388     DEBUG({
00389       for (unsigned i = 0; i != NumComp; ++i)
00390         dbgs() << '\t' << *Dups[i] << '\n';
00391     });
00392   }
00393 }
00394 
00395 // Keep track of new virtual registers created via
00396 // MachineRegisterInfo::createVirtualRegister.
00397 void
00398 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
00399 {
00400   if (VRM)
00401     VRM->grow();
00402 
00403   NewRegs.push_back(VReg);
00404 }
00405 
00406 void
00407 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
00408                                         const MachineLoopInfo &Loops,
00409                                         const MachineBlockFrequencyInfo &MBFI) {
00410   VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
00411   for (unsigned I = 0, Size = size(); I < Size; ++I) {
00412     LiveInterval &LI = LIS.getInterval(get(I));
00413     if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
00414       DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
00415                    << MRI.getRegClass(LI.reg)->getName() << '\n');
00416     VRAI.calculateSpillWeightAndHint(LI);
00417   }
00418 }