LLVM API Documentation

VirtRegMap.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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 // This file implements the VirtRegMap class.
00011 //
00012 // It also contains implementations of the Spiller interface, which, given a
00013 // virtual register map and a machine function, eliminates all virtual
00014 // references by replacing them with physical register references - adding spill
00015 // code as necessary.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/CodeGen/VirtRegMap.h"
00020 #include "LiveDebugVariables.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/ADT/SparseSet.h"
00023 #include "llvm/ADT/Statistic.h"
00024 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00025 #include "llvm/CodeGen/LiveStackAnalysis.h"
00026 #include "llvm/CodeGen/MachineFrameInfo.h"
00027 #include "llvm/CodeGen/MachineFunction.h"
00028 #include "llvm/CodeGen/MachineInstrBuilder.h"
00029 #include "llvm/CodeGen/MachineRegisterInfo.h"
00030 #include "llvm/CodeGen/Passes.h"
00031 #include "llvm/IR/Function.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Compiler.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetMachine.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <algorithm>
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "regalloc"
00044 
00045 STATISTIC(NumSpillSlots, "Number of spill slots allocated");
00046 STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
00047 
00048 //===----------------------------------------------------------------------===//
00049 //  VirtRegMap implementation
00050 //===----------------------------------------------------------------------===//
00051 
00052 char VirtRegMap::ID = 0;
00053 
00054 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
00055 
00056 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
00057   MRI = &mf.getRegInfo();
00058   TII = mf.getSubtarget().getInstrInfo();
00059   TRI = mf.getSubtarget().getRegisterInfo();
00060   MF = &mf;
00061 
00062   Virt2PhysMap.clear();
00063   Virt2StackSlotMap.clear();
00064   Virt2SplitMap.clear();
00065 
00066   grow();
00067   return false;
00068 }
00069 
00070 void VirtRegMap::grow() {
00071   unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
00072   Virt2PhysMap.resize(NumRegs);
00073   Virt2StackSlotMap.resize(NumRegs);
00074   Virt2SplitMap.resize(NumRegs);
00075 }
00076 
00077 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
00078   int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
00079                                                       RC->getAlignment());
00080   ++NumSpillSlots;
00081   return SS;
00082 }
00083 
00084 bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
00085   unsigned Hint = MRI->getSimpleHint(VirtReg);
00086   if (!Hint)
00087     return 0;
00088   if (TargetRegisterInfo::isVirtualRegister(Hint))
00089     Hint = getPhys(Hint);
00090   return getPhys(VirtReg) == Hint;
00091 }
00092 
00093 bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
00094   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
00095   if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
00096     return true;
00097   if (TargetRegisterInfo::isVirtualRegister(Hint.second))
00098     return hasPhys(Hint.second);
00099   return false;
00100 }
00101 
00102 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
00103   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
00104   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
00105          "attempt to assign stack slot to already spilled register");
00106   const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
00107   return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
00108 }
00109 
00110 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
00111   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
00112   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
00113          "attempt to assign stack slot to already spilled register");
00114   assert((SS >= 0 ||
00115           (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
00116          "illegal fixed frame index");
00117   Virt2StackSlotMap[virtReg] = SS;
00118 }
00119 
00120 void VirtRegMap::print(raw_ostream &OS, const Module*) const {
00121   OS << "********** REGISTER MAP **********\n";
00122   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00123     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00124     if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
00125       OS << '[' << PrintReg(Reg, TRI) << " -> "
00126          << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
00127          << MRI->getRegClass(Reg)->getName() << "\n";
00128     }
00129   }
00130 
00131   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00132     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00133     if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
00134       OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
00135          << "] " << MRI->getRegClass(Reg)->getName() << "\n";
00136     }
00137   }
00138   OS << '\n';
00139 }
00140 
00141 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00142 void VirtRegMap::dump() const {
00143   print(dbgs());
00144 }
00145 #endif
00146 
00147 //===----------------------------------------------------------------------===//
00148 //                              VirtRegRewriter
00149 //===----------------------------------------------------------------------===//
00150 //
00151 // The VirtRegRewriter is the last of the register allocator passes.
00152 // It rewrites virtual registers to physical registers as specified in the
00153 // VirtRegMap analysis. It also updates live-in information on basic blocks
00154 // according to LiveIntervals.
00155 //
00156 namespace {
00157 class VirtRegRewriter : public MachineFunctionPass {
00158   MachineFunction *MF;
00159   const TargetMachine *TM;
00160   const TargetRegisterInfo *TRI;
00161   const TargetInstrInfo *TII;
00162   MachineRegisterInfo *MRI;
00163   SlotIndexes *Indexes;
00164   LiveIntervals *LIS;
00165   VirtRegMap *VRM;
00166   SparseSet<unsigned> PhysRegs;
00167 
00168   void rewrite();
00169   void addMBBLiveIns();
00170 public:
00171   static char ID;
00172   VirtRegRewriter() : MachineFunctionPass(ID) {}
00173 
00174   void getAnalysisUsage(AnalysisUsage &AU) const override;
00175 
00176   bool runOnMachineFunction(MachineFunction&) override;
00177 };
00178 } // end anonymous namespace
00179 
00180 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
00181 
00182 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
00183                       "Virtual Register Rewriter", false, false)
00184 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
00185 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
00186 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
00187 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
00188 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
00189 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
00190                     "Virtual Register Rewriter", false, false)
00191 
00192 char VirtRegRewriter::ID = 0;
00193 
00194 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
00195   AU.setPreservesCFG();
00196   AU.addRequired<LiveIntervals>();
00197   AU.addRequired<SlotIndexes>();
00198   AU.addPreserved<SlotIndexes>();
00199   AU.addRequired<LiveDebugVariables>();
00200   AU.addRequired<LiveStacks>();
00201   AU.addPreserved<LiveStacks>();
00202   AU.addRequired<VirtRegMap>();
00203   MachineFunctionPass::getAnalysisUsage(AU);
00204 }
00205 
00206 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
00207   MF = &fn;
00208   TM = &MF->getTarget();
00209   TRI = TM->getSubtargetImpl()->getRegisterInfo();
00210   TII = TM->getSubtargetImpl()->getInstrInfo();
00211   MRI = &MF->getRegInfo();
00212   Indexes = &getAnalysis<SlotIndexes>();
00213   LIS = &getAnalysis<LiveIntervals>();
00214   VRM = &getAnalysis<VirtRegMap>();
00215   DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
00216                << "********** Function: "
00217                << MF->getName() << '\n');
00218   DEBUG(VRM->dump());
00219 
00220   // Add kill flags while we still have virtual registers.
00221   LIS->addKillFlags(VRM);
00222 
00223   // Live-in lists on basic blocks are required for physregs.
00224   addMBBLiveIns();
00225 
00226   // Rewrite virtual registers.
00227   rewrite();
00228 
00229   // Write out new DBG_VALUE instructions.
00230   getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
00231 
00232   // All machine operands and other references to virtual registers have been
00233   // replaced. Remove the virtual registers and release all the transient data.
00234   VRM->clearAllVirt();
00235   MRI->clearVirtRegs();
00236   return true;
00237 }
00238 
00239 // Compute MBB live-in lists from virtual register live ranges and their
00240 // assignments.
00241 void VirtRegRewriter::addMBBLiveIns() {
00242   SmallVector<MachineBasicBlock*, 16> LiveIn;
00243   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
00244     unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
00245     if (MRI->reg_nodbg_empty(VirtReg))
00246       continue;
00247     LiveInterval &LI = LIS->getInterval(VirtReg);
00248     if (LI.empty() || LIS->intervalIsInOneMBB(LI))
00249       continue;
00250     // This is a virtual register that is live across basic blocks. Its
00251     // assigned PhysReg must be marked as live-in to those blocks.
00252     unsigned PhysReg = VRM->getPhys(VirtReg);
00253     assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
00254 
00255     // Scan the segments of LI.
00256     for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I != E;
00257          ++I) {
00258       if (!Indexes->findLiveInMBBs(I->start, I->end, LiveIn))
00259         continue;
00260       for (unsigned i = 0, e = LiveIn.size(); i != e; ++i)
00261         if (!LiveIn[i]->isLiveIn(PhysReg))
00262           LiveIn[i]->addLiveIn(PhysReg);
00263       LiveIn.clear();
00264     }
00265   }
00266 }
00267 
00268 void VirtRegRewriter::rewrite() {
00269   SmallVector<unsigned, 8> SuperDeads;
00270   SmallVector<unsigned, 8> SuperDefs;
00271   SmallVector<unsigned, 8> SuperKills;
00272   SmallPtrSet<const MachineInstr *, 4> NoReturnInsts;
00273 
00274   // Here we have a SparseSet to hold which PhysRegs are actually encountered
00275   // in the MF we are about to iterate over so that later when we call
00276   // setPhysRegUsed, we are only doing it for physRegs that were actually found
00277   // in the program and not for all of the possible physRegs for the given
00278   // target architecture. If the target has a lot of physRegs, then for a small
00279   // program there will be a significant compile time reduction here.
00280   PhysRegs.clear();
00281   PhysRegs.setUniverse(TRI->getNumRegs());
00282 
00283   // The function with uwtable should guarantee that the stack unwinder
00284   // can unwind the stack to the previous frame.  Thus, we can't apply the
00285   // noreturn optimization if the caller function has uwtable attribute.
00286   bool HasUWTable = MF->getFunction()->hasFnAttribute(Attribute::UWTable);
00287 
00288   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
00289        MBBI != MBBE; ++MBBI) {
00290     DEBUG(MBBI->print(dbgs(), Indexes));
00291     bool IsExitBB = MBBI->succ_empty();
00292     for (MachineBasicBlock::instr_iterator
00293            MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
00294       MachineInstr *MI = MII;
00295       ++MII;
00296 
00297       // Check if this instruction is a call to a noreturn function.  If this
00298       // is a call to noreturn function and we don't need the stack unwinding
00299       // functionality (i.e. this function does not have uwtable attribute and
00300       // the callee function has the nounwind attribute), then we can ignore
00301       // the definitions set by this instruction.
00302       if (!HasUWTable && IsExitBB && MI->isCall()) {
00303         for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
00304                MOE = MI->operands_end(); MOI != MOE; ++MOI) {
00305           MachineOperand &MO = *MOI;
00306           if (!MO.isGlobal())
00307             continue;
00308           const Function *Func = dyn_cast<Function>(MO.getGlobal());
00309           if (!Func || !Func->hasFnAttribute(Attribute::NoReturn) ||
00310               // We need to keep correct unwind information
00311               // even if the function will not return, since the
00312               // runtime may need it.
00313               !Func->hasFnAttribute(Attribute::NoUnwind))
00314             continue;
00315           NoReturnInsts.insert(MI);
00316           break;
00317         }
00318       }
00319 
00320       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
00321            MOE = MI->operands_end(); MOI != MOE; ++MOI) {
00322         MachineOperand &MO = *MOI;
00323 
00324         // Make sure MRI knows about registers clobbered by regmasks.
00325         if (MO.isRegMask())
00326           MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
00327 
00328         // If we encounter a VirtReg or PhysReg then get at the PhysReg and add
00329         // it to the physreg bitset.  Later we use only the PhysRegs that were
00330         // actually encountered in the MF to populate the MRI's used physregs.
00331         if (MO.isReg() && MO.getReg())
00332           PhysRegs.insert(
00333               TargetRegisterInfo::isVirtualRegister(MO.getReg()) ?
00334               VRM->getPhys(MO.getReg()) :
00335               MO.getReg());
00336 
00337         if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
00338           continue;
00339         unsigned VirtReg = MO.getReg();
00340         unsigned PhysReg = VRM->getPhys(VirtReg);
00341         assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
00342                "Instruction uses unmapped VirtReg");
00343         assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
00344 
00345         // Preserve semantics of sub-register operands.
00346         if (MO.getSubReg()) {
00347           // A virtual register kill refers to the whole register, so we may
00348           // have to add <imp-use,kill> operands for the super-register.  A
00349           // partial redef always kills and redefines the super-register.
00350           if (MO.readsReg() && (MO.isDef() || MO.isKill()))
00351             SuperKills.push_back(PhysReg);
00352 
00353           if (MO.isDef()) {
00354             // The <def,undef> flag only makes sense for sub-register defs, and
00355             // we are substituting a full physreg.  An <imp-use,kill> operand
00356             // from the SuperKills list will represent the partial read of the
00357             // super-register.
00358             MO.setIsUndef(false);
00359 
00360             // Also add implicit defs for the super-register.
00361             if (MO.isDead())
00362               SuperDeads.push_back(PhysReg);
00363             else
00364               SuperDefs.push_back(PhysReg);
00365           }
00366 
00367           // PhysReg operands cannot have subregister indexes.
00368           PhysReg = TRI->getSubReg(PhysReg, MO.getSubReg());
00369           assert(PhysReg && "Invalid SubReg for physical register");
00370           MO.setSubReg(0);
00371         }
00372         // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
00373         // we need the inlining here.
00374         MO.setReg(PhysReg);
00375       }
00376 
00377       // Add any missing super-register kills after rewriting the whole
00378       // instruction.
00379       while (!SuperKills.empty())
00380         MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
00381 
00382       while (!SuperDeads.empty())
00383         MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
00384 
00385       while (!SuperDefs.empty())
00386         MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
00387 
00388       DEBUG(dbgs() << "> " << *MI);
00389 
00390       // Finally, remove any identity copies.
00391       if (MI->isIdentityCopy()) {
00392         ++NumIdCopies;
00393         if (MI->getNumOperands() == 2) {
00394           DEBUG(dbgs() << "Deleting identity copy.\n");
00395           if (Indexes)
00396             Indexes->removeMachineInstrFromMaps(MI);
00397           // It's safe to erase MI because MII has already been incremented.
00398           MI->eraseFromParent();
00399         } else {
00400           // Transform identity copy to a KILL to deal with subregisters.
00401           MI->setDesc(TII->get(TargetOpcode::KILL));
00402           DEBUG(dbgs() << "Identity copy: " << *MI);
00403         }
00404       }
00405     }
00406   }
00407 
00408   // Tell MRI about physical registers in use.
00409   if (NoReturnInsts.empty()) {
00410     for (SparseSet<unsigned>::iterator
00411         RegI = PhysRegs.begin(), E = PhysRegs.end(); RegI != E; ++RegI)
00412       if (!MRI->reg_nodbg_empty(*RegI))
00413         MRI->setPhysRegUsed(*RegI);
00414   } else {
00415     for (SparseSet<unsigned>::iterator
00416         I = PhysRegs.begin(), E = PhysRegs.end(); I != E; ++I) {
00417       unsigned Reg = *I;
00418       if (MRI->reg_nodbg_empty(Reg))
00419         continue;
00420       // Check if this register has a use that will impact the rest of the
00421       // code. Uses in debug and noreturn instructions do not impact the
00422       // generated code.
00423       for (MachineInstr &It : MRI->reg_nodbg_instructions(Reg)) {
00424         if (!NoReturnInsts.count(&It)) {
00425           MRI->setPhysRegUsed(Reg);
00426           break;
00427         }
00428       }
00429     }
00430   }
00431 }
00432