LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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 #include "llvm/CodeGen/Passes.h"
00017 #include "llvm/CodeGen/MachineFunctionPass.h"
00018 #include "llvm/CodeGen/MachineInstr.h"
00019 #include "llvm/CodeGen/SSARegMap.h"
00020 #include "llvm/CodeGen/LiveVariables.h"
00021 #include "llvm/Target/TargetInstrInfo.h"
00022 #include "llvm/Target/TargetMachine.h"
00023 #include "llvm/ADT/DenseMap.h"
00024 #include "llvm/ADT/STLExtras.h"
00025 using namespace llvm;
00026 
00027 namespace {
00028   struct PNE : public MachineFunctionPass {
00029     bool runOnMachineFunction(MachineFunction &Fn) {
00030       bool Changed = false;
00031 
00032       // Eliminate PHI instructions by inserting copies into predecessor blocks.
00033       //
00034       for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
00035   Changed |= EliminatePHINodes(Fn, *I);
00036 
00037       //std::cerr << "AFTER PHI NODE ELIM:\n";
00038       //Fn.dump();
00039       return Changed;
00040     }
00041 
00042     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00043       AU.addPreserved<LiveVariables>();
00044       MachineFunctionPass::getAnalysisUsage(AU);
00045     }
00046 
00047   private:
00048     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
00049     /// in predecessor basic blocks.
00050     ///
00051     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
00052   };
00053 
00054   RegisterPass<PNE> X("phi-node-elimination",
00055           "Eliminate PHI nodes for register allocation");
00056 }
00057 
00058 
00059 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
00060 
00061 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
00062 /// predecessor basic blocks.
00063 ///
00064 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
00065   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
00066     return false;   // Quick exit for normal case...
00067 
00068   LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
00069   const TargetInstrInfo &MII = *MF.getTarget().getInstrInfo();
00070   const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
00071 
00072   // VRegPHIUseCount - Keep track of the number of times each virtual register
00073   // is used by PHI nodes in successors of this block.
00074   DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
00075   VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
00076 
00077   unsigned BBIsSuccOfPreds = 0;  // Number of times MBB is a succ of preds
00078   for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
00079          E = MBB.pred_end(); PI != E; ++PI)
00080     for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
00081            E = (*PI)->succ_end(); SI != E; ++SI) {
00082     BBIsSuccOfPreds += *SI == &MBB;
00083     for (MachineBasicBlock::iterator BBI = (*SI)->begin(); BBI !=(*SI)->end() &&
00084            BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
00085       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
00086         VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
00087   }
00088 
00089   // Get an iterator to the first instruction after the last PHI node (this may
00090   // also be the end of the basic block).  While we are scanning the PHIs,
00091   // populate the VRegPHIUseCount map.
00092   MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
00093   while (AfterPHIsIt != MBB.end() &&
00094          AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
00095     ++AfterPHIsIt;    // Skip over all of the PHI nodes...
00096 
00097   while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
00098     // Unlink the PHI node from the basic block, but don't delete the PHI yet.
00099     MachineInstr *MPhi = MBB.remove(MBB.begin());
00100     
00101     assert(MRegisterInfo::isVirtualRegister(MPhi->getOperand(0).getReg()) &&
00102            "PHI node doesn't write virt reg?");
00103 
00104     unsigned DestReg = MPhi->getOperand(0).getReg();
00105     
00106     // Create a new register for the incoming PHI arguments
00107     const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
00108     unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
00109 
00110     // Insert a register to register copy in the top of the current block (but
00111     // after any remaining phi nodes) which copies the new incoming register
00112     // into the phi node destination.
00113     //
00114     RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
00115     
00116     // Update live variable information if there is any...
00117     if (LV) {
00118       MachineInstr *PHICopy = prior(AfterPHIsIt);
00119 
00120       // Add information to LiveVariables to know that the incoming value is
00121       // killed.  Note that because the value is defined in several places (once
00122       // each for each incoming block), the "def" block and instruction fields
00123       // for the VarInfo is not filled in.
00124       //
00125       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
00126 
00127       // Since we are going to be deleting the PHI node, if it is the last use
00128       // of any registers, or if the value itself is dead, we need to move this
00129       // information over to the new copy we just inserted.
00130       //
00131       std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator> 
00132         RKs = LV->killed_range(MPhi);
00133       std::vector<std::pair<MachineInstr*, unsigned> > Range;
00134       if (RKs.first != RKs.second) // Delete the range.
00135         LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
00136 
00137       RKs = LV->dead_range(MPhi);
00138       if (RKs.first != RKs.second) {
00139         // Works as above...
00140         Range.assign(RKs.first, RKs.second);
00141         LV->removeVirtualRegistersDead(RKs.first, RKs.second);
00142         for (unsigned i = 0, e = Range.size(); i != e; ++i)
00143           LV->addVirtualRegisterDead(Range[i].second, PHICopy);
00144       }
00145     }
00146 
00147     // Adjust the VRegPHIUseCount map to account for the removal of this PHI
00148     // node.
00149     for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
00150       VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= BBIsSuccOfPreds;
00151 
00152     // Now loop over all of the incoming arguments, changing them to copy into
00153     // the IncomingReg register in the corresponding predecessor basic block.
00154     //
00155     for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
00156       MachineOperand &opVal = MPhi->getOperand(i-1);
00157       
00158       // Get the MachineBasicBlock equivalent of the BasicBlock that is the
00159       // source path the PHI.
00160       MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
00161 
00162       MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
00163       
00164       // Check to make sure we haven't already emitted the copy for this block.
00165       // This can happen because PHI nodes may have multiple entries for the
00166       // same basic block.  It doesn't matter which entry we use though, because
00167       // all incoming values are guaranteed to be the same for a particular bb.
00168       //
00169       // If we emitted a copy for this basic block already, it will be right
00170       // where we want to insert one now.  Just check for a definition of the
00171       // register we are interested in!
00172       //
00173       bool HaveNotEmitted = true;
00174       
00175       if (I != opBlock.begin()) {
00176         MachineBasicBlock::iterator PrevInst = prior(I);
00177         for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
00178           MachineOperand &MO = PrevInst->getOperand(i);
00179           if (MO.isRegister() && MO.getReg() == IncomingReg)
00180             if (MO.isDef()) {
00181               HaveNotEmitted = false;
00182               break;
00183             }             
00184         }
00185       }
00186 
00187       if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
00188         assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) &&
00189                "Machine PHI Operands must all be virtual registers!");
00190         unsigned SrcReg = opVal.getReg();
00191         RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
00192 
00193         // Now update live variable information if we have it.
00194         if (LV) {
00195           // We want to be able to insert a kill of the register if this PHI
00196           // (aka, the copy we just inserted) is the last use of the source
00197           // value.  Live variable analysis conservatively handles this by
00198           // saying that the value is live until the end of the block the PHI
00199           // entry lives in.  If the value really is dead at the PHI copy, there
00200           // will be no successor blocks which have the value live-in.
00201           //
00202           // Check to see if the copy is the last use, and if so, update the
00203           // live variables information so that it knows the copy source
00204           // instruction kills the incoming value.
00205           //
00206           LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
00207 
00208           // Loop over all of the successors of the basic block, checking to see
00209           // if the value is either live in the block, or if it is killed in the
00210           // block.  Also check to see if this register is in use by another PHI
00211           // node which has not yet been eliminated.  If so, it will be killed
00212           // at an appropriate point later.
00213           //
00214           bool ValueIsLive = false;
00215           for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
00216                  E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
00217             MachineBasicBlock *SuccMBB = *SI;
00218             
00219             // Is it alive in this successor?
00220             unsigned SuccIdx = SuccMBB->getNumber();
00221             if (SuccIdx < InRegVI.AliveBlocks.size() &&
00222                 InRegVI.AliveBlocks[SuccIdx]) {
00223               ValueIsLive = true;
00224               break;
00225             }
00226             
00227             // Is it killed in this successor?
00228             for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
00229               if (InRegVI.Kills[i]->getParent() == SuccMBB) {
00230                 ValueIsLive = true;
00231                 break;
00232               }
00233 
00234             // Is it used by any PHI instructions in this block?
00235             if (!ValueIsLive)
00236               ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
00237           }
00238           
00239           // Okay, if we now know that the value is not live out of the block,
00240           // we can add a kill marker to the copy we inserted saying that it
00241           // kills the incoming value!
00242           //
00243           if (!ValueIsLive) {
00244             MachineBasicBlock::iterator Prev = prior(I);
00245             LV->addVirtualRegisterKilled(SrcReg, Prev);
00246 
00247             // This vreg no longer lives all of the way through opBlock.
00248             unsigned opBlockNum = opBlock.getNumber();
00249             if (opBlockNum < InRegVI.AliveBlocks.size())
00250               InRegVI.AliveBlocks[opBlockNum] = false;
00251           }
00252         }
00253       }
00254     }
00255     
00256     // Really delete the PHI instruction now!
00257     delete MPhi;
00258   }
00259   return true;
00260 }