LLVM API Documentation

PHIElimination.cpp

Go to the documentation of this file.
00001 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
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 pass eliminates machine instruction PHI nodes by inserting copy
00011 // instructions.  This destroys SSA information, but is the desired input for
00012 // some register allocators.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "phielim"
00017 #include "PHIElimination.h"
00018 #include "llvm/BasicBlock.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/CodeGen/LiveVariables.h"
00021 #include "llvm/CodeGen/Passes.h"
00022 #include "llvm/CodeGen/MachineFunctionPass.h"
00023 #include "llvm/CodeGen/MachineInstr.h"
00024 #include "llvm/CodeGen/MachineInstrBuilder.h"
00025 #include "llvm/CodeGen/MachineRegisterInfo.h"
00026 #include "llvm/Target/TargetMachine.h"
00027 #include "llvm/ADT/SmallPtrSet.h"
00028 #include "llvm/ADT/STLExtras.h"
00029 #include "llvm/ADT/Statistic.h"
00030 #include "llvm/Support/Compiler.h"
00031 #include <algorithm>
00032 #include <map>
00033 using namespace llvm;
00034 
00035 STATISTIC(NumAtomic, "Number of atomic phis lowered");
00036 
00037 char PHIElimination::ID = 0;
00038 static RegisterPass<PHIElimination>
00039 X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
00040 
00041 const PassInfo *const llvm::PHIEliminationID = &X;
00042 
00043 void llvm::PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
00044   AU.setPreservesCFG();
00045   AU.addPreserved<LiveVariables>();
00046   AU.addPreservedID(MachineLoopInfoID);
00047   AU.addPreservedID(MachineDominatorsID);
00048   MachineFunctionPass::getAnalysisUsage(AU);
00049 }
00050 
00051 bool llvm::PHIElimination::runOnMachineFunction(MachineFunction &Fn) {
00052   MRI = &Fn.getRegInfo();
00053 
00054   PHIDefs.clear();
00055   PHIKills.clear();
00056   analyzePHINodes(Fn);
00057 
00058   bool Changed = false;
00059 
00060   // Eliminate PHI instructions by inserting copies into predecessor blocks.
00061   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
00062     Changed |= EliminatePHINodes(Fn, *I);
00063 
00064   // Remove dead IMPLICIT_DEF instructions.
00065   for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
00066          E = ImpDefs.end(); I != E; ++I) {
00067     MachineInstr *DefMI = *I;
00068     unsigned DefReg = DefMI->getOperand(0).getReg();
00069     if (MRI->use_empty(DefReg))
00070       DefMI->eraseFromParent();
00071   }
00072 
00073   ImpDefs.clear();
00074   VRegPHIUseCount.clear();
00075   return Changed;
00076 }
00077 
00078 
00079 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
00080 /// predecessor basic blocks.
00081 ///
00082 bool llvm::PHIElimination::EliminatePHINodes(MachineFunction &MF,
00083                                              MachineBasicBlock &MBB) {
00084   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
00085     return false;   // Quick exit for basic blocks without PHIs.
00086 
00087   // Get an iterator to the first instruction after the last PHI node (this may
00088   // also be the end of the basic block).
00089   MachineBasicBlock::iterator AfterPHIsIt = SkipPHIsAndLabels(MBB, MBB.begin());
00090 
00091   while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
00092     LowerAtomicPHINode(MBB, AfterPHIsIt);
00093 
00094   return true;
00095 }
00096 
00097 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
00098 /// are implicit_def's.
00099 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
00100                                          const MachineRegisterInfo *MRI) {
00101   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
00102     unsigned SrcReg = MPhi->getOperand(i).getReg();
00103     const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
00104     if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
00105       return false;
00106   }
00107   return true;
00108 }
00109 
00110 // FindCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg.
00111 // This needs to be after any def or uses of SrcReg, but before any subsequent
00112 // point where control flow might jump out of the basic block.
00113 MachineBasicBlock::iterator
00114 llvm::PHIElimination::FindCopyInsertPoint(MachineBasicBlock &MBB,
00115                                           unsigned SrcReg) {
00116   // Handle the trivial case trivially.
00117   if (MBB.empty())
00118     return MBB.begin();
00119 
00120   // If this basic block does not contain an invoke, then control flow always
00121   // reaches the end of it, so place the copy there.  The logic below works in
00122   // this case too, but is more expensive.
00123   if (!isa<InvokeInst>(MBB.getBasicBlock()->getTerminator()))
00124     return MBB.getFirstTerminator();
00125 
00126   // Discover any definition/uses in this basic block.
00127   SmallPtrSet<MachineInstr*, 8> DefUsesInMBB;
00128   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
00129        RE = MRI->reg_end(); RI != RE; ++RI) {
00130     MachineInstr *DefUseMI = &*RI;
00131     if (DefUseMI->getParent() == &MBB)
00132       DefUsesInMBB.insert(DefUseMI);
00133   }
00134 
00135   MachineBasicBlock::iterator InsertPoint;
00136   if (DefUsesInMBB.empty()) {
00137     // No def/uses.  Insert the copy at the start of the basic block.
00138     InsertPoint = MBB.begin();
00139   } else if (DefUsesInMBB.size() == 1) {
00140     // Insert the copy immediately after the definition/use.
00141     InsertPoint = *DefUsesInMBB.begin();
00142     ++InsertPoint;
00143   } else {
00144     // Insert the copy immediately after the last definition/use.
00145     InsertPoint = MBB.end();
00146     while (!DefUsesInMBB.count(&*--InsertPoint)) {}
00147     ++InsertPoint;
00148   }
00149 
00150   // Make sure the copy goes after any phi nodes however.
00151   return SkipPHIsAndLabels(MBB, InsertPoint);
00152 }
00153 
00154 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
00155 /// under the assuption that it needs to be lowered in a way that supports
00156 /// atomic execution of PHIs.  This lowering method is always correct all of the
00157 /// time.
00158 ///  
00159 void llvm::PHIElimination::LowerAtomicPHINode(
00160                                       MachineBasicBlock &MBB,
00161                                       MachineBasicBlock::iterator AfterPHIsIt) {
00162   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
00163   MachineInstr *MPhi = MBB.remove(MBB.begin());
00164 
00165   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
00166   unsigned DestReg = MPhi->getOperand(0).getReg();
00167   bool isDead = MPhi->getOperand(0).isDead();
00168 
00169   // Create a new register for the incoming PHI arguments.
00170   MachineFunction &MF = *MBB.getParent();
00171   const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
00172   unsigned IncomingReg = 0;
00173 
00174   // Insert a register to register copy at the top of the current block (but
00175   // after any remaining phi nodes) which copies the new incoming register
00176   // into the phi node destination.
00177   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
00178   if (isSourceDefinedByImplicitDef(MPhi, MRI))
00179     // If all sources of a PHI node are implicit_def, just emit an
00180     // implicit_def instead of a copy.
00181     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
00182             TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
00183   else {
00184     IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
00185     TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
00186   }
00187 
00188   // Record PHI def.
00189   assert(!hasPHIDef(DestReg) && "Vreg has multiple phi-defs?"); 
00190   PHIDefs[DestReg] = &MBB;
00191 
00192   // Update live variable information if there is any.
00193   LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
00194   if (LV) {
00195     MachineInstr *PHICopy = prior(AfterPHIsIt);
00196 
00197     if (IncomingReg) {
00198       // Increment use count of the newly created virtual register.
00199       LV->getVarInfo(IncomingReg).NumUses++;
00200 
00201       // Add information to LiveVariables to know that the incoming value is
00202       // killed.  Note that because the value is defined in several places (once
00203       // each for each incoming block), the "def" block and instruction fields
00204       // for the VarInfo is not filled in.
00205       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
00206     }
00207 
00208     // Since we are going to be deleting the PHI node, if it is the last use of
00209     // any registers, or if the value itself is dead, we need to move this
00210     // information over to the new copy we just inserted.
00211     LV->removeVirtualRegistersKilled(MPhi);
00212 
00213     // If the result is dead, update LV.
00214     if (isDead) {
00215       LV->addVirtualRegisterDead(DestReg, PHICopy);
00216       LV->removeVirtualRegisterDead(DestReg, MPhi);
00217     }
00218   }
00219 
00220   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
00221   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
00222     --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
00223                                  MPhi->getOperand(i).getReg())];
00224 
00225   // Now loop over all of the incoming arguments, changing them to copy into the
00226   // IncomingReg register in the corresponding predecessor basic block.
00227   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
00228   for (int i = NumSrcs - 1; i >= 0; --i) {
00229     unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
00230     assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
00231            "Machine PHI Operands must all be virtual registers!");
00232 
00233     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
00234     // path the PHI.
00235     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
00236 
00237     // Record the kill.
00238     PHIKills[SrcReg].insert(&opBlock);
00239 
00240     // If source is defined by an implicit def, there is no need to insert a
00241     // copy.
00242     MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
00243     if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
00244       ImpDefs.insert(DefMI);
00245       continue;
00246     }
00247 
00248     // Check to make sure we haven't already emitted the copy for this block.
00249     // This can happen because PHI nodes may have multiple entries for the same
00250     // basic block.
00251     if (!MBBsInsertedInto.insert(&opBlock))
00252       continue;  // If the copy has already been emitted, we're done.
00253  
00254     // Find a safe location to insert the copy, this may be the first terminator
00255     // in the block (or end()).
00256     MachineBasicBlock::iterator InsertPos = FindCopyInsertPoint(opBlock, SrcReg);
00257 
00258     // Insert the copy.
00259     TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
00260 
00261     // Now update live variable information if we have it.  Otherwise we're done
00262     if (!LV) continue;
00263     
00264     // We want to be able to insert a kill of the register if this PHI (aka, the
00265     // copy we just inserted) is the last use of the source value.  Live
00266     // variable analysis conservatively handles this by saying that the value is
00267     // live until the end of the block the PHI entry lives in.  If the value
00268     // really is dead at the PHI copy, there will be no successor blocks which
00269     // have the value live-in.
00270     //
00271     // Check to see if the copy is the last use, and if so, update the live
00272     // variables information so that it knows the copy source instruction kills
00273     // the incoming value.
00274     LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
00275 
00276     // Loop over all of the successors of the basic block, checking to see if
00277     // the value is either live in the block, or if it is killed in the block.
00278     // Also check to see if this register is in use by another PHI node which
00279     // has not yet been eliminated.  If so, it will be killed at an appropriate
00280     // point later.
00281 
00282     // Is it used by any PHI instructions in this block?
00283     bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
00284 
00285     std::vector<MachineBasicBlock*> OpSuccBlocks;
00286     
00287     // Otherwise, scan successors, including the BB the PHI node lives in.
00288     for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
00289            E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
00290       MachineBasicBlock *SuccMBB = *SI;
00291 
00292       // Is it alive in this successor?
00293       unsigned SuccIdx = SuccMBB->getNumber();
00294       if (InRegVI.AliveBlocks.test(SuccIdx)) {
00295         ValueIsLive = true;
00296         break;
00297       }
00298 
00299       OpSuccBlocks.push_back(SuccMBB);
00300     }
00301 
00302     // Check to see if this value is live because there is a use in a successor
00303     // that kills it.
00304     if (!ValueIsLive) {
00305       switch (OpSuccBlocks.size()) {
00306       case 1: {
00307         MachineBasicBlock *MBB = OpSuccBlocks[0];
00308         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
00309           if (InRegVI.Kills[i]->getParent() == MBB) {
00310             ValueIsLive = true;
00311             break;
00312           }
00313         break;
00314       }
00315       case 2: {
00316         MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
00317         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
00318           if (InRegVI.Kills[i]->getParent() == MBB1 || 
00319               InRegVI.Kills[i]->getParent() == MBB2) {
00320             ValueIsLive = true;
00321             break;
00322           }
00323         break;        
00324       }
00325       default:
00326         std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
00327         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
00328           if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
00329                                  InRegVI.Kills[i]->getParent())) {
00330             ValueIsLive = true;
00331             break;
00332           }
00333       }
00334     }        
00335 
00336     // Okay, if we now know that the value is not live out of the block, we can
00337     // add a kill marker in this block saying that it kills the incoming value!
00338     if (!ValueIsLive) {
00339       // In our final twist, we have to decide which instruction kills the
00340       // register.  In most cases this is the copy, however, the first
00341       // terminator instruction at the end of the block may also use the value.
00342       // In this case, we should mark *it* as being the killing block, not the
00343       // copy.
00344       MachineBasicBlock::iterator KillInst = prior(InsertPos);
00345       MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
00346       if (Term != opBlock.end()) {
00347         if (Term->readsRegister(SrcReg))
00348           KillInst = Term;
00349       
00350         // Check that no other terminators use values.
00351 #ifndef NDEBUG
00352         for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
00353              ++TI) {
00354           assert(!TI->readsRegister(SrcReg) &&
00355                  "Terminator instructions cannot use virtual registers unless"
00356                  "they are the first terminator in a block!");
00357         }
00358 #endif
00359       }
00360       
00361       // Finally, mark it killed.
00362       LV->addVirtualRegisterKilled(SrcReg, KillInst);
00363 
00364       // This vreg no longer lives all of the way through opBlock.
00365       unsigned opBlockNum = opBlock.getNumber();
00366       InRegVI.AliveBlocks.reset(opBlockNum);
00367     }
00368   }
00369     
00370   // Really delete the PHI instruction now!
00371   MF.DeleteMachineInstr(MPhi);
00372   ++NumAtomic;
00373 }
00374 
00375 /// analyzePHINodes - Gather information about the PHI nodes in here. In
00376 /// particular, we want to map the number of uses of a virtual register which is
00377 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
00378 /// used later to determine when the vreg is killed in the BB.
00379 ///
00380 void llvm::PHIElimination::analyzePHINodes(const MachineFunction& Fn) {
00381   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
00382        I != E; ++I)
00383     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
00384          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
00385       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
00386         ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
00387                                      BBI->getOperand(i).getReg())];
00388 }