LLVM API Documentation

MachineSSAUpdater.cpp
Go to the documentation of this file.
00001 //===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
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 MachineSSAUpdater class. It's based on SSAUpdater
00011 // class in lib/Transforms/Utils.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/MachineSSAUpdater.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SmallVector.h"
00018 #include "llvm/CodeGen/MachineInstr.h"
00019 #include "llvm/CodeGen/MachineInstrBuilder.h"
00020 #include "llvm/CodeGen/MachineRegisterInfo.h"
00021 #include "llvm/Support/AlignOf.h"
00022 #include "llvm/Support/Allocator.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Target/TargetRegisterInfo.h"
00029 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
00030 using namespace llvm;
00031 
00032 typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
00033 static AvailableValsTy &getAvailableVals(void *AV) {
00034   return *static_cast<AvailableValsTy*>(AV);
00035 }
00036 
00037 MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
00038                                      SmallVectorImpl<MachineInstr*> *NewPHI)
00039   : AV(0), InsertedPHIs(NewPHI) {
00040   TII = MF.getTarget().getInstrInfo();
00041   MRI = &MF.getRegInfo();
00042 }
00043 
00044 MachineSSAUpdater::~MachineSSAUpdater() {
00045   delete static_cast<AvailableValsTy*>(AV);
00046 }
00047 
00048 /// Initialize - Reset this object to get ready for a new set of SSA
00049 /// updates.  ProtoValue is the value used to name PHI nodes.
00050 void MachineSSAUpdater::Initialize(unsigned V) {
00051   if (AV == 0)
00052     AV = new AvailableValsTy();
00053   else
00054     getAvailableVals(AV).clear();
00055 
00056   VR = V;
00057   VRC = MRI->getRegClass(VR);
00058 }
00059 
00060 /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
00061 /// the specified block.
00062 bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
00063   return getAvailableVals(AV).count(BB);
00064 }
00065 
00066 /// AddAvailableValue - Indicate that a rewritten value is available in the
00067 /// specified block with the specified value.
00068 void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
00069   getAvailableVals(AV)[BB] = V;
00070 }
00071 
00072 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
00073 /// live at the end of the specified block.
00074 unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
00075   return GetValueAtEndOfBlockInternal(BB);
00076 }
00077 
00078 static
00079 unsigned LookForIdenticalPHI(MachineBasicBlock *BB,
00080           SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> &PredValues) {
00081   if (BB->empty())
00082     return 0;
00083 
00084   MachineBasicBlock::iterator I = BB->begin();
00085   if (!I->isPHI())
00086     return 0;
00087 
00088   AvailableValsTy AVals;
00089   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
00090     AVals[PredValues[i].first] = PredValues[i].second;
00091   while (I != BB->end() && I->isPHI()) {
00092     bool Same = true;
00093     for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
00094       unsigned SrcReg = I->getOperand(i).getReg();
00095       MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
00096       if (AVals[SrcBB] != SrcReg) {
00097         Same = false;
00098         break;
00099       }
00100     }
00101     if (Same)
00102       return I->getOperand(0).getReg();
00103     ++I;
00104   }
00105   return 0;
00106 }
00107 
00108 /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
00109 /// a value of the given register class at the start of the specified basic
00110 /// block. It returns the virtual register defined by the instruction.
00111 static
00112 MachineInstrBuilder InsertNewDef(unsigned Opcode,
00113                            MachineBasicBlock *BB, MachineBasicBlock::iterator I,
00114                            const TargetRegisterClass *RC,
00115                            MachineRegisterInfo *MRI,
00116                            const TargetInstrInfo *TII) {
00117   unsigned NewVR = MRI->createVirtualRegister(RC);
00118   return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
00119 }
00120 
00121 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
00122 /// is live in the middle of the specified block.
00123 ///
00124 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
00125 /// important case: if there is a definition of the rewritten value after the
00126 /// 'use' in BB.  Consider code like this:
00127 ///
00128 ///      X1 = ...
00129 ///   SomeBB:
00130 ///      use(X)
00131 ///      X2 = ...
00132 ///      br Cond, SomeBB, OutBB
00133 ///
00134 /// In this case, there are two values (X1 and X2) added to the AvailableVals
00135 /// set by the client of the rewriter, and those values are both live out of
00136 /// their respective blocks.  However, the use of X happens in the *middle* of
00137 /// a block.  Because of this, we need to insert a new PHI node in SomeBB to
00138 /// merge the appropriate values, and this value isn't live out of the block.
00139 ///
00140 unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
00141   // If there is no definition of the renamed variable in this block, just use
00142   // GetValueAtEndOfBlock to do our work.
00143   if (!HasValueForBlock(BB))
00144     return GetValueAtEndOfBlockInternal(BB);
00145 
00146   // If there are no predecessors, just return undef.
00147   if (BB->pred_empty()) {
00148     // Insert an implicit_def to represent an undef value.
00149     MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
00150                                         BB, BB->getFirstTerminator(),
00151                                         VRC, MRI, TII);
00152     return NewDef->getOperand(0).getReg();
00153   }
00154 
00155   // Otherwise, we have the hard case.  Get the live-in values for each
00156   // predecessor.
00157   SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
00158   unsigned SingularValue = 0;
00159 
00160   bool isFirstPred = true;
00161   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
00162          E = BB->pred_end(); PI != E; ++PI) {
00163     MachineBasicBlock *PredBB = *PI;
00164     unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
00165     PredValues.push_back(std::make_pair(PredBB, PredVal));
00166 
00167     // Compute SingularValue.
00168     if (isFirstPred) {
00169       SingularValue = PredVal;
00170       isFirstPred = false;
00171     } else if (PredVal != SingularValue)
00172       SingularValue = 0;
00173   }
00174 
00175   // Otherwise, if all the merged values are the same, just use it.
00176   if (SingularValue != 0)
00177     return SingularValue;
00178 
00179   // If an identical PHI is already in BB, just reuse it.
00180   unsigned DupPHI = LookForIdenticalPHI(BB, PredValues);
00181   if (DupPHI)
00182     return DupPHI;
00183 
00184   // Otherwise, we do need a PHI: insert one now.
00185   MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
00186   MachineInstrBuilder InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
00187                                                  Loc, VRC, MRI, TII);
00188 
00189   // Fill in all the predecessors of the PHI.
00190   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
00191     InsertedPHI.addReg(PredValues[i].second).addMBB(PredValues[i].first);
00192 
00193   // See if the PHI node can be merged to a single value.  This can happen in
00194   // loop cases when we get a PHI of itself and one other value.
00195   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
00196     InsertedPHI->eraseFromParent();
00197     return ConstVal;
00198   }
00199 
00200   // If the client wants to know about all new instructions, tell it.
00201   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
00202 
00203   DEBUG(dbgs() << "  Inserted PHI: " << *InsertedPHI << "\n");
00204   return InsertedPHI->getOperand(0).getReg();
00205 }
00206 
00207 static
00208 MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
00209                                          MachineOperand *U) {
00210   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
00211     if (&MI->getOperand(i) == U)
00212       return MI->getOperand(i+1).getMBB();
00213   }
00214 
00215   llvm_unreachable("MachineOperand::getParent() failure?");
00216 }
00217 
00218 /// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI nodes,
00219 /// which use their value in the corresponding predecessor.
00220 void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
00221   MachineInstr *UseMI = U.getParent();
00222   unsigned NewVR = 0;
00223   if (UseMI->isPHI()) {
00224     MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
00225     NewVR = GetValueAtEndOfBlockInternal(SourceBB);
00226   } else {
00227     NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
00228   }
00229 
00230   U.setReg(NewVR);
00231 }
00232 
00233 void MachineSSAUpdater::ReplaceRegWith(unsigned OldReg, unsigned NewReg) {
00234   MRI->replaceRegWith(OldReg, NewReg);
00235 
00236   AvailableValsTy &AvailableVals = getAvailableVals(AV);
00237   for (DenseMap<MachineBasicBlock*, unsigned>::iterator
00238          I = AvailableVals.begin(), E = AvailableVals.end(); I != E; ++I)
00239     if (I->second == OldReg)
00240       I->second = NewReg;
00241 }
00242 
00243 /// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
00244 /// template, specialized for MachineSSAUpdater.
00245 namespace llvm {
00246 template<>
00247 class SSAUpdaterTraits<MachineSSAUpdater> {
00248 public:
00249   typedef MachineBasicBlock BlkT;
00250   typedef unsigned ValT;
00251   typedef MachineInstr PhiT;
00252 
00253   typedef MachineBasicBlock::succ_iterator BlkSucc_iterator;
00254   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
00255   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
00256 
00257   /// Iterator for PHI operands.
00258   class PHI_iterator {
00259   private:
00260     MachineInstr *PHI;
00261     unsigned idx;
00262  
00263   public:
00264     explicit PHI_iterator(MachineInstr *P) // begin iterator
00265       : PHI(P), idx(1) {}
00266     PHI_iterator(MachineInstr *P, bool) // end iterator
00267       : PHI(P), idx(PHI->getNumOperands()) {}
00268 
00269     PHI_iterator &operator++() { idx += 2; return *this; } 
00270     bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
00271     bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
00272     unsigned getIncomingValue() { return PHI->getOperand(idx).getReg(); }
00273     MachineBasicBlock *getIncomingBlock() {
00274       return PHI->getOperand(idx+1).getMBB();
00275     }
00276   };
00277   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
00278   static inline PHI_iterator PHI_end(PhiT *PHI) {
00279     return PHI_iterator(PHI, true);
00280   }
00281 
00282   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
00283   /// vector.
00284   static void FindPredecessorBlocks(MachineBasicBlock *BB,
00285                                     SmallVectorImpl<MachineBasicBlock*> *Preds){
00286     for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
00287            E = BB->pred_end(); PI != E; ++PI)
00288       Preds->push_back(*PI);
00289   }
00290 
00291   /// GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
00292   /// Add it into the specified block and return the register.
00293   static unsigned GetUndefVal(MachineBasicBlock *BB,
00294                               MachineSSAUpdater *Updater) {
00295     // Insert an implicit_def to represent an undef value.
00296     MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
00297                                         BB, BB->getFirstTerminator(),
00298                                         Updater->VRC, Updater->MRI,
00299                                         Updater->TII);
00300     return NewDef->getOperand(0).getReg();
00301   }
00302 
00303   /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
00304   /// Add it into the specified block and return the register.
00305   static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
00306                                  MachineSSAUpdater *Updater) {
00307     MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
00308     MachineInstr *PHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
00309                                      Updater->VRC, Updater->MRI,
00310                                      Updater->TII);
00311     return PHI->getOperand(0).getReg();
00312   }
00313 
00314   /// AddPHIOperand - Add the specified value as an operand of the PHI for
00315   /// the specified predecessor block.
00316   static void AddPHIOperand(MachineInstr *PHI, unsigned Val,
00317                             MachineBasicBlock *Pred) {
00318     MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
00319   }
00320 
00321   /// InstrIsPHI - Check if an instruction is a PHI.
00322   ///
00323   static MachineInstr *InstrIsPHI(MachineInstr *I) {
00324     if (I && I->isPHI())
00325       return I;
00326     return 0;
00327   }
00328 
00329   /// ValueIsPHI - Check if the instruction that defines the specified register
00330   /// is a PHI instruction.
00331   static MachineInstr *ValueIsPHI(unsigned Val, MachineSSAUpdater *Updater) {
00332     return InstrIsPHI(Updater->MRI->getVRegDef(Val));
00333   }
00334 
00335   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
00336   /// operands, i.e., it was just added.
00337   static MachineInstr *ValueIsNewPHI(unsigned Val, MachineSSAUpdater *Updater) {
00338     MachineInstr *PHI = ValueIsPHI(Val, Updater);
00339     if (PHI && PHI->getNumOperands() <= 1)
00340       return PHI;
00341     return 0;
00342   }
00343 
00344   /// GetPHIValue - For the specified PHI instruction, return the register
00345   /// that it defines.
00346   static unsigned GetPHIValue(MachineInstr *PHI) {
00347     return PHI->getOperand(0).getReg();
00348   }
00349 };
00350 
00351 } // End llvm namespace
00352 
00353 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
00354 /// for the specified BB and if so, return it.  If not, construct SSA form by
00355 /// first calculating the required placement of PHIs and then inserting new
00356 /// PHIs where needed.
00357 unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
00358   AvailableValsTy &AvailableVals = getAvailableVals(AV);
00359   if (unsigned V = AvailableVals[BB])
00360     return V;
00361 
00362   SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
00363   return Impl.GetValue(BB);
00364 }