LLVM API Documentation

MachineCopyPropagation.cpp
Go to the documentation of this file.
00001 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
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 is an extremely simple MachineInstr-level copy propagation pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "codegen-cp"
00015 #include "llvm/CodeGen/Passes.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineFunctionPass.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/Pass.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 #include "llvm/Support/raw_ostream.h"
00027 #include "llvm/Target/TargetInstrInfo.h"
00028 #include "llvm/Target/TargetRegisterInfo.h"
00029 using namespace llvm;
00030 
00031 STATISTIC(NumDeletes, "Number of dead copies deleted");
00032 
00033 namespace {
00034   class MachineCopyPropagation : public MachineFunctionPass {
00035     const TargetRegisterInfo *TRI;
00036     const TargetInstrInfo *TII;
00037     MachineRegisterInfo *MRI;
00038 
00039   public:
00040     static char ID; // Pass identification, replacement for typeid
00041     MachineCopyPropagation() : MachineFunctionPass(ID) {
00042      initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
00043     }
00044 
00045     virtual bool runOnMachineFunction(MachineFunction &MF);
00046 
00047   private:
00048     typedef SmallVector<unsigned, 4> DestList;
00049     typedef DenseMap<unsigned, DestList> SourceMap;
00050 
00051     void SourceNoLongerAvailable(unsigned Reg,
00052                                  SourceMap &SrcMap,
00053                                  DenseMap<unsigned, MachineInstr*> &AvailCopyMap);
00054     bool CopyPropagateBlock(MachineBasicBlock &MBB);
00055     void removeCopy(MachineInstr *MI);
00056   };
00057 }
00058 char MachineCopyPropagation::ID = 0;
00059 char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
00060 
00061 INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
00062                 "Machine Copy Propagation Pass", false, false)
00063 
00064 void
00065 MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg,
00066                               SourceMap &SrcMap,
00067                               DenseMap<unsigned, MachineInstr*> &AvailCopyMap) {
00068   for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00069     SourceMap::iterator SI = SrcMap.find(*AI);
00070     if (SI != SrcMap.end()) {
00071       const DestList& Defs = SI->second;
00072       for (DestList::const_iterator I = Defs.begin(), E = Defs.end();
00073            I != E; ++I) {
00074         unsigned MappedDef = *I;
00075         // Source of copy is no longer available for propagation.
00076         if (AvailCopyMap.erase(MappedDef)) {
00077           for (MCSubRegIterator SR(MappedDef, TRI); SR.isValid(); ++SR)
00078             AvailCopyMap.erase(*SR);
00079         }
00080       }
00081     }
00082   }
00083 }
00084 
00085 static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
00086                                     const MachineInstr *MI) {
00087   const MachineBasicBlock *MBB = CopyMI->getParent();
00088   if (MI->getParent() != MBB)
00089     return false;
00090   MachineBasicBlock::const_iterator I = CopyMI;
00091   MachineBasicBlock::const_iterator E = MBB->end();
00092   MachineBasicBlock::const_iterator E2 = MI;
00093 
00094   ++I;
00095   while (I != E && I != E2) {
00096     if (I->hasUnmodeledSideEffects() || I->isCall() ||
00097         I->isTerminator())
00098       return false;
00099     ++I;
00100   }
00101   return true;
00102 }
00103 
00104 /// isNopCopy - Return true if the specified copy is really a nop. That is
00105 /// if the source of the copy is the same of the definition of the copy that
00106 /// supplied the source. If the source of the copy is a sub-register than it
00107 /// must check the sub-indices match. e.g.
00108 /// ecx = mov eax
00109 /// al  = mov cl
00110 /// But not
00111 /// ecx = mov eax
00112 /// al  = mov ch
00113 static bool isNopCopy(MachineInstr *CopyMI, unsigned Def, unsigned Src,
00114                       const TargetRegisterInfo *TRI) {
00115   unsigned SrcSrc = CopyMI->getOperand(1).getReg();
00116   if (Def == SrcSrc)
00117     return true;
00118   if (TRI->isSubRegister(SrcSrc, Def)) {
00119     unsigned SrcDef = CopyMI->getOperand(0).getReg();
00120     unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
00121     if (!SubIdx)
00122       return false;
00123     return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
00124   }
00125 
00126   return false;
00127 }
00128 
00129 // Remove MI from the function because it has been determined it is dead.
00130 // Turn it into a noop KILL instruction if it has super-register liveness
00131 // adjustments.
00132 void MachineCopyPropagation::removeCopy(MachineInstr *MI) {
00133   if (MI->getNumOperands() == 2)
00134     MI->eraseFromParent();
00135   else
00136     MI->setDesc(TII->get(TargetOpcode::KILL));
00137 }
00138 
00139 bool MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
00140   SmallSetVector<MachineInstr*, 8> MaybeDeadCopies;  // Candidates for deletion
00141   DenseMap<unsigned, MachineInstr*> AvailCopyMap;    // Def -> available copies map
00142   DenseMap<unsigned, MachineInstr*> CopyMap;         // Def -> copies map
00143   SourceMap SrcMap; // Src -> Def map
00144 
00145   bool Changed = false;
00146   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
00147     MachineInstr *MI = &*I;
00148     ++I;
00149 
00150     if (MI->isCopy()) {
00151       unsigned Def = MI->getOperand(0).getReg();
00152       unsigned Src = MI->getOperand(1).getReg();
00153 
00154       if (TargetRegisterInfo::isVirtualRegister(Def) ||
00155           TargetRegisterInfo::isVirtualRegister(Src))
00156         report_fatal_error("MachineCopyPropagation should be run after"
00157                            " register allocation!");
00158 
00159       DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
00160       if (CI != AvailCopyMap.end()) {
00161         MachineInstr *CopyMI = CI->second;
00162         if (!MRI->isReserved(Def) &&
00163             (!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
00164             isNopCopy(CopyMI, Def, Src, TRI)) {
00165           // The two copies cancel out and the source of the first copy
00166           // hasn't been overridden, eliminate the second one. e.g.
00167           //  %ECX<def> = COPY %EAX<kill>
00168           //  ... nothing clobbered EAX.
00169           //  %EAX<def> = COPY %ECX
00170           // =>
00171           //  %ECX<def> = COPY %EAX
00172           //
00173           // Also avoid eliminating a copy from reserved registers unless the
00174           // definition is proven not clobbered. e.g.
00175           // %RSP<def> = COPY %RAX
00176           // CALL
00177           // %RAX<def> = COPY %RSP
00178 
00179           // Clear any kills of Def between CopyMI and MI. This extends the
00180           // live range.
00181           for (MachineBasicBlock::iterator I = CopyMI, E = MI; I != E; ++I)
00182             I->clearRegisterKills(Def, TRI);
00183 
00184           removeCopy(MI);
00185           Changed = true;
00186           ++NumDeletes;
00187           continue;
00188         }
00189       }
00190 
00191       // If Src is defined by a previous copy, it cannot be eliminated.
00192       for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
00193         CI = CopyMap.find(*AI);
00194         if (CI != CopyMap.end())
00195           MaybeDeadCopies.remove(CI->second);
00196       }
00197 
00198       // Copy is now a candidate for deletion.
00199       MaybeDeadCopies.insert(MI);
00200 
00201       // If 'Src' is previously source of another copy, then this earlier copy's
00202       // source is no longer available. e.g.
00203       // %xmm9<def> = copy %xmm2
00204       // ...
00205       // %xmm2<def> = copy %xmm0
00206       // ...
00207       // %xmm2<def> = copy %xmm9
00208       SourceNoLongerAvailable(Def, SrcMap, AvailCopyMap);
00209 
00210       // Remember Def is defined by the copy.
00211       // ... Make sure to clear the def maps of aliases first.
00212       for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
00213         CopyMap.erase(*AI);
00214         AvailCopyMap.erase(*AI);
00215       }
00216       CopyMap[Def] = MI;
00217       AvailCopyMap[Def] = MI;
00218       for (MCSubRegIterator SR(Def, TRI); SR.isValid(); ++SR) {
00219         CopyMap[*SR] = MI;
00220         AvailCopyMap[*SR] = MI;
00221       }
00222 
00223       // Remember source that's copied to Def. Once it's clobbered, then
00224       // it's no longer available for copy propagation.
00225       if (std::find(SrcMap[Src].begin(), SrcMap[Src].end(), Def) ==
00226           SrcMap[Src].end()) {
00227         SrcMap[Src].push_back(Def);
00228       }
00229 
00230       continue;
00231     }
00232 
00233     // Not a copy.
00234     SmallVector<unsigned, 2> Defs;
00235     int RegMaskOpNum = -1;
00236     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00237       MachineOperand &MO = MI->getOperand(i);
00238       if (MO.isRegMask())
00239         RegMaskOpNum = i;
00240       if (!MO.isReg())
00241         continue;
00242       unsigned Reg = MO.getReg();
00243       if (!Reg)
00244         continue;
00245 
00246       if (TargetRegisterInfo::isVirtualRegister(Reg))
00247         report_fatal_error("MachineCopyPropagation should be run after"
00248                            " register allocation!");
00249 
00250       if (MO.isDef()) {
00251         Defs.push_back(Reg);
00252         continue;
00253       }
00254 
00255       // If 'Reg' is defined by a copy, the copy is no longer a candidate
00256       // for elimination.
00257       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00258         DenseMap<unsigned, MachineInstr*>::iterator CI = CopyMap.find(*AI);
00259         if (CI != CopyMap.end())
00260           MaybeDeadCopies.remove(CI->second);
00261       }
00262     }
00263 
00264     // The instruction has a register mask operand which means that it clobbers
00265     // a large set of registers.  It is possible to use the register mask to
00266     // prune the available copies, but treat it like a basic block boundary for
00267     // now.
00268     if (RegMaskOpNum >= 0) {
00269       // Erase any MaybeDeadCopies whose destination register is clobbered.
00270       const MachineOperand &MaskMO = MI->getOperand(RegMaskOpNum);
00271       for (SmallSetVector<MachineInstr*, 8>::iterator
00272            DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
00273            DI != DE; ++DI) {
00274         unsigned Reg = (*DI)->getOperand(0).getReg();
00275         if (MRI->isReserved(Reg) || !MaskMO.clobbersPhysReg(Reg))
00276           continue;
00277         removeCopy(*DI);
00278         Changed = true;
00279         ++NumDeletes;
00280       }
00281 
00282       // Clear all data structures as if we were beginning a new basic block.
00283       MaybeDeadCopies.clear();
00284       AvailCopyMap.clear();
00285       CopyMap.clear();
00286       SrcMap.clear();
00287       continue;
00288     }
00289 
00290     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
00291       unsigned Reg = Defs[i];
00292 
00293       // No longer defined by a copy.
00294       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00295         CopyMap.erase(*AI);
00296         AvailCopyMap.erase(*AI);
00297       }
00298 
00299       // If 'Reg' is previously source of a copy, it is no longer available for
00300       // copy propagation.
00301       SourceNoLongerAvailable(Reg, SrcMap, AvailCopyMap);
00302     }
00303   }
00304 
00305   // If MBB doesn't have successors, delete the copies whose defs are not used.
00306   // If MBB does have successors, then conservative assume the defs are live-out
00307   // since we don't want to trust live-in lists.
00308   if (MBB.succ_empty()) {
00309     for (SmallSetVector<MachineInstr*, 8>::iterator
00310            DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
00311          DI != DE; ++DI) {
00312       if (!MRI->isReserved((*DI)->getOperand(0).getReg())) {
00313         removeCopy(*DI);
00314         Changed = true;
00315         ++NumDeletes;
00316       }
00317     }
00318   }
00319 
00320   return Changed;
00321 }
00322 
00323 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
00324   bool Changed = false;
00325 
00326   TRI = MF.getTarget().getRegisterInfo();
00327   TII = MF.getTarget().getInstrInfo();
00328   MRI = &MF.getRegInfo();
00329 
00330   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
00331     Changed |= CopyPropagateBlock(*I);
00332 
00333   return Changed;
00334 }