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