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