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