LLVM API Documentation

SSAUpdater.cpp
Go to the documentation of this file.
00001 //===- SSAUpdater.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 SSAUpdater class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "ssaupdater"
00015 #include "llvm/Transforms/Utils/SSAUpdater.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/TinyPtrVector.h"
00018 #include "llvm/Analysis/InstructionSimplify.h"
00019 #include "llvm/IR/CFG.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/IntrinsicInst.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/raw_ostream.h"
00025 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00026 #include "llvm/Transforms/Utils/Local.h"
00027 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
00028 
00029 using namespace llvm;
00030 
00031 typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
00032 static AvailableValsTy &getAvailableVals(void *AV) {
00033   return *static_cast<AvailableValsTy*>(AV);
00034 }
00035 
00036 SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
00037   : AV(0), ProtoType(0), ProtoName(), InsertedPHIs(NewPHI) {}
00038 
00039 SSAUpdater::~SSAUpdater() {
00040   delete static_cast<AvailableValsTy*>(AV);
00041 }
00042 
00043 void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
00044   if (AV == 0)
00045     AV = new AvailableValsTy();
00046   else
00047     getAvailableVals(AV).clear();
00048   ProtoType = Ty;
00049   ProtoName = Name;
00050 }
00051 
00052 bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
00053   return getAvailableVals(AV).count(BB);
00054 }
00055 
00056 void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
00057   assert(ProtoType != 0 && "Need to initialize SSAUpdater");
00058   assert(ProtoType == V->getType() &&
00059          "All rewritten values must have the same type");
00060   getAvailableVals(AV)[BB] = V;
00061 }
00062 
00063 static bool IsEquivalentPHI(PHINode *PHI,
00064                           SmallDenseMap<BasicBlock*, Value*, 8> &ValueMapping) {
00065   unsigned PHINumValues = PHI->getNumIncomingValues();
00066   if (PHINumValues != ValueMapping.size())
00067     return false;
00068 
00069   // Scan the phi to see if it matches.
00070   for (unsigned i = 0, e = PHINumValues; i != e; ++i)
00071     if (ValueMapping[PHI->getIncomingBlock(i)] !=
00072         PHI->getIncomingValue(i)) {
00073       return false;
00074     }
00075 
00076   return true;
00077 }
00078 
00079 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
00080   Value *Res = GetValueAtEndOfBlockInternal(BB);
00081   return Res;
00082 }
00083 
00084 Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
00085   // If there is no definition of the renamed variable in this block, just use
00086   // GetValueAtEndOfBlock to do our work.
00087   if (!HasValueForBlock(BB))
00088     return GetValueAtEndOfBlock(BB);
00089 
00090   // Otherwise, we have the hard case.  Get the live-in values for each
00091   // predecessor.
00092   SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
00093   Value *SingularValue = 0;
00094 
00095   // We can get our predecessor info by walking the pred_iterator list, but it
00096   // is relatively slow.  If we already have PHI nodes in this block, walk one
00097   // of them to get the predecessor list instead.
00098   if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
00099     for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
00100       BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
00101       Value *PredVal = GetValueAtEndOfBlock(PredBB);
00102       PredValues.push_back(std::make_pair(PredBB, PredVal));
00103 
00104       // Compute SingularValue.
00105       if (i == 0)
00106         SingularValue = PredVal;
00107       else if (PredVal != SingularValue)
00108         SingularValue = 0;
00109     }
00110   } else {
00111     bool isFirstPred = true;
00112     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00113       BasicBlock *PredBB = *PI;
00114       Value *PredVal = GetValueAtEndOfBlock(PredBB);
00115       PredValues.push_back(std::make_pair(PredBB, PredVal));
00116 
00117       // Compute SingularValue.
00118       if (isFirstPred) {
00119         SingularValue = PredVal;
00120         isFirstPred = false;
00121       } else if (PredVal != SingularValue)
00122         SingularValue = 0;
00123     }
00124   }
00125 
00126   // If there are no predecessors, just return undef.
00127   if (PredValues.empty())
00128     return UndefValue::get(ProtoType);
00129 
00130   // Otherwise, if all the merged values are the same, just use it.
00131   if (SingularValue != 0)
00132     return SingularValue;
00133 
00134   // Otherwise, we do need a PHI: check to see if we already have one available
00135   // in this block that produces the right value.
00136   if (isa<PHINode>(BB->begin())) {
00137     SmallDenseMap<BasicBlock*, Value*, 8> ValueMapping(PredValues.begin(),
00138                                                        PredValues.end());
00139     PHINode *SomePHI;
00140     for (BasicBlock::iterator It = BB->begin();
00141          (SomePHI = dyn_cast<PHINode>(It)); ++It) {
00142       if (IsEquivalentPHI(SomePHI, ValueMapping))
00143         return SomePHI;
00144     }
00145   }
00146 
00147   // Ok, we have no way out, insert a new one now.
00148   PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
00149                                          ProtoName, &BB->front());
00150 
00151   // Fill in all the predecessors of the PHI.
00152   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
00153     InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
00154 
00155   // See if the PHI node can be merged to a single value.  This can happen in
00156   // loop cases when we get a PHI of itself and one other value.
00157   if (Value *V = SimplifyInstruction(InsertedPHI)) {
00158     InsertedPHI->eraseFromParent();
00159     return V;
00160   }
00161 
00162   // Set the DebugLoc of the inserted PHI, if available.
00163   DebugLoc DL;
00164   if (const Instruction *I = BB->getFirstNonPHI())
00165       DL = I->getDebugLoc();
00166   InsertedPHI->setDebugLoc(DL);
00167 
00168   // If the client wants to know about all new instructions, tell it.
00169   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
00170 
00171   DEBUG(dbgs() << "  Inserted PHI: " << *InsertedPHI << "\n");
00172   return InsertedPHI;
00173 }
00174 
00175 void SSAUpdater::RewriteUse(Use &U) {
00176   Instruction *User = cast<Instruction>(U.getUser());
00177 
00178   Value *V;
00179   if (PHINode *UserPN = dyn_cast<PHINode>(User))
00180     V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
00181   else
00182     V = GetValueInMiddleOfBlock(User->getParent());
00183 
00184   // Notify that users of the existing value that it is being replaced.
00185   Value *OldVal = U.get();
00186   if (OldVal != V && OldVal->hasValueHandle())
00187     ValueHandleBase::ValueIsRAUWd(OldVal, V);
00188 
00189   U.set(V);
00190 }
00191 
00192 void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
00193   Instruction *User = cast<Instruction>(U.getUser());
00194   
00195   Value *V;
00196   if (PHINode *UserPN = dyn_cast<PHINode>(User))
00197     V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
00198   else
00199     V = GetValueAtEndOfBlock(User->getParent());
00200   
00201   U.set(V);
00202 }
00203 
00204 namespace llvm {
00205 template<>
00206 class SSAUpdaterTraits<SSAUpdater> {
00207 public:
00208   typedef BasicBlock BlkT;
00209   typedef Value *ValT;
00210   typedef PHINode PhiT;
00211 
00212   typedef succ_iterator BlkSucc_iterator;
00213   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
00214   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
00215 
00216   class PHI_iterator {
00217   private:
00218     PHINode *PHI;
00219     unsigned idx;
00220 
00221   public:
00222     explicit PHI_iterator(PHINode *P) // begin iterator
00223       : PHI(P), idx(0) {}
00224     PHI_iterator(PHINode *P, bool) // end iterator
00225       : PHI(P), idx(PHI->getNumIncomingValues()) {}
00226 
00227     PHI_iterator &operator++() { ++idx; return *this; } 
00228     bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
00229     bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
00230     Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
00231     BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
00232   };
00233 
00234   static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
00235   static PHI_iterator PHI_end(PhiT *PHI) {
00236     return PHI_iterator(PHI, true);
00237   }
00238 
00239   /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
00240   /// vector, set Info->NumPreds, and allocate space in Info->Preds.
00241   static void FindPredecessorBlocks(BasicBlock *BB,
00242                                     SmallVectorImpl<BasicBlock*> *Preds) {
00243     // We can get our predecessor info by walking the pred_iterator list,
00244     // but it is relatively slow.  If we already have PHI nodes in this
00245     // block, walk one of them to get the predecessor list instead.
00246     if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
00247       for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI)
00248         Preds->push_back(SomePhi->getIncomingBlock(PI));
00249     } else {
00250       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00251         Preds->push_back(*PI);
00252     }
00253   }
00254 
00255   /// GetUndefVal - Get an undefined value of the same type as the value
00256   /// being handled.
00257   static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
00258     return UndefValue::get(Updater->ProtoType);
00259   }
00260 
00261   /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
00262   /// Reserve space for the operands but do not fill them in yet.
00263   static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
00264                                SSAUpdater *Updater) {
00265     PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
00266                                    Updater->ProtoName, &BB->front());
00267     return PHI;
00268   }
00269 
00270   /// AddPHIOperand - Add the specified value as an operand of the PHI for
00271   /// the specified predecessor block.
00272   static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
00273     PHI->addIncoming(Val, Pred);
00274   }
00275 
00276   /// InstrIsPHI - Check if an instruction is a PHI.
00277   ///
00278   static PHINode *InstrIsPHI(Instruction *I) {
00279     return dyn_cast<PHINode>(I);
00280   }
00281 
00282   /// ValueIsPHI - Check if a value is a PHI.
00283   ///
00284   static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
00285     return dyn_cast<PHINode>(Val);
00286   }
00287 
00288   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
00289   /// operands, i.e., it was just added.
00290   static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
00291     PHINode *PHI = ValueIsPHI(Val, Updater);
00292     if (PHI && PHI->getNumIncomingValues() == 0)
00293       return PHI;
00294     return 0;
00295   }
00296 
00297   /// GetPHIValue - For the specified PHI instruction, return the value
00298   /// that it defines.
00299   static Value *GetPHIValue(PHINode *PHI) {
00300     return PHI;
00301   }
00302 };
00303 
00304 } // End llvm namespace
00305 
00306 /// Check to see if AvailableVals has an entry for the specified BB and if so,
00307 /// return it.  If not, construct SSA form by first calculating the required
00308 /// placement of PHIs and then inserting new PHIs where needed.
00309 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
00310   AvailableValsTy &AvailableVals = getAvailableVals(AV);
00311   if (Value *V = AvailableVals[BB])
00312     return V;
00313 
00314   SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
00315   return Impl.GetValue(BB);
00316 }
00317 
00318 //===----------------------------------------------------------------------===//
00319 // LoadAndStorePromoter Implementation
00320 //===----------------------------------------------------------------------===//
00321 
00322 LoadAndStorePromoter::
00323 LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts,
00324                      SSAUpdater &S, StringRef BaseName) : SSA(S) {
00325   if (Insts.empty()) return;
00326   
00327   Value *SomeVal;
00328   if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
00329     SomeVal = LI;
00330   else
00331     SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
00332 
00333   if (BaseName.empty())
00334     BaseName = SomeVal->getName();
00335   SSA.Initialize(SomeVal->getType(), BaseName);
00336 }
00337 
00338 
00339 void LoadAndStorePromoter::
00340 run(const SmallVectorImpl<Instruction*> &Insts) const {
00341   
00342   // First step: bucket up uses of the alloca by the block they occur in.
00343   // This is important because we have to handle multiple defs/uses in a block
00344   // ourselves: SSAUpdater is purely for cross-block references.
00345   DenseMap<BasicBlock*, TinyPtrVector<Instruction*> > UsesByBlock;
00346   
00347   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
00348     Instruction *User = Insts[i];
00349     UsesByBlock[User->getParent()].push_back(User);
00350   }
00351   
00352   // Okay, now we can iterate over all the blocks in the function with uses,
00353   // processing them.  Keep track of which loads are loading a live-in value.
00354   // Walk the uses in the use-list order to be determinstic.
00355   SmallVector<LoadInst*, 32> LiveInLoads;
00356   DenseMap<Value*, Value*> ReplacedLoads;
00357   
00358   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
00359     Instruction *User = Insts[i];
00360     BasicBlock *BB = User->getParent();
00361     TinyPtrVector<Instruction*> &BlockUses = UsesByBlock[BB];
00362     
00363     // If this block has already been processed, ignore this repeat use.
00364     if (BlockUses.empty()) continue;
00365     
00366     // Okay, this is the first use in the block.  If this block just has a
00367     // single user in it, we can rewrite it trivially.
00368     if (BlockUses.size() == 1) {
00369       // If it is a store, it is a trivial def of the value in the block.
00370       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00371         updateDebugInfo(SI);
00372         SSA.AddAvailableValue(BB, SI->getOperand(0));
00373       } else 
00374         // Otherwise it is a load, queue it to rewrite as a live-in load.
00375         LiveInLoads.push_back(cast<LoadInst>(User));
00376       BlockUses.clear();
00377       continue;
00378     }
00379     
00380     // Otherwise, check to see if this block is all loads.
00381     bool HasStore = false;
00382     for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
00383       if (isa<StoreInst>(BlockUses[i])) {
00384         HasStore = true;
00385         break;
00386       }
00387     }
00388     
00389     // If so, we can queue them all as live in loads.  We don't have an
00390     // efficient way to tell which on is first in the block and don't want to
00391     // scan large blocks, so just add all loads as live ins.
00392     if (!HasStore) {
00393       for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
00394         LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
00395       BlockUses.clear();
00396       continue;
00397     }
00398     
00399     // Otherwise, we have mixed loads and stores (or just a bunch of stores).
00400     // Since SSAUpdater is purely for cross-block values, we need to determine
00401     // the order of these instructions in the block.  If the first use in the
00402     // block is a load, then it uses the live in value.  The last store defines
00403     // the live out value.  We handle this by doing a linear scan of the block.
00404     Value *StoredValue = 0;
00405     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
00406       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
00407         // If this is a load from an unrelated pointer, ignore it.
00408         if (!isInstInList(L, Insts)) continue;
00409         
00410         // If we haven't seen a store yet, this is a live in use, otherwise
00411         // use the stored value.
00412         if (StoredValue) {
00413           replaceLoadWithValue(L, StoredValue);
00414           L->replaceAllUsesWith(StoredValue);
00415           ReplacedLoads[L] = StoredValue;
00416         } else {
00417           LiveInLoads.push_back(L);
00418         }
00419         continue;
00420       }
00421       
00422       if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
00423         // If this is a store to an unrelated pointer, ignore it.
00424         if (!isInstInList(SI, Insts)) continue;
00425         updateDebugInfo(SI);
00426 
00427         // Remember that this is the active value in the block.
00428         StoredValue = SI->getOperand(0);
00429       }
00430     }
00431     
00432     // The last stored value that happened is the live-out for the block.
00433     assert(StoredValue && "Already checked that there is a store in block");
00434     SSA.AddAvailableValue(BB, StoredValue);
00435     BlockUses.clear();
00436   }
00437   
00438   // Okay, now we rewrite all loads that use live-in values in the loop,
00439   // inserting PHI nodes as necessary.
00440   for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
00441     LoadInst *ALoad = LiveInLoads[i];
00442     Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
00443     replaceLoadWithValue(ALoad, NewVal);
00444 
00445     // Avoid assertions in unreachable code.
00446     if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
00447     ALoad->replaceAllUsesWith(NewVal);
00448     ReplacedLoads[ALoad] = NewVal;
00449   }
00450   
00451   // Allow the client to do stuff before we start nuking things.
00452   doExtraRewritesBeforeFinalDeletion();
00453   
00454   // Now that everything is rewritten, delete the old instructions from the
00455   // function.  They should all be dead now.
00456   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
00457     Instruction *User = Insts[i];
00458     
00459     // If this is a load that still has uses, then the load must have been added
00460     // as a live value in the SSAUpdate data structure for a block (e.g. because
00461     // the loaded value was stored later).  In this case, we need to recursively
00462     // propagate the updates until we get to the real value.
00463     if (!User->use_empty()) {
00464       Value *NewVal = ReplacedLoads[User];
00465       assert(NewVal && "not a replaced load?");
00466       
00467       // Propagate down to the ultimate replacee.  The intermediately loads
00468       // could theoretically already have been deleted, so we don't want to
00469       // dereference the Value*'s.
00470       DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
00471       while (RLI != ReplacedLoads.end()) {
00472         NewVal = RLI->second;
00473         RLI = ReplacedLoads.find(NewVal);
00474       }
00475       
00476       replaceLoadWithValue(cast<LoadInst>(User), NewVal);
00477       User->replaceAllUsesWith(NewVal);
00478     }
00479     
00480     instructionDeleted(User);
00481     User->eraseFromParent();
00482   }
00483 }
00484 
00485 bool
00486 LoadAndStorePromoter::isInstInList(Instruction *I,
00487                                    const SmallVectorImpl<Instruction*> &Insts)
00488                                    const {
00489   return std::find(Insts.begin(), Insts.end(), I) != Insts.end();
00490 }