SSAUpdater.cpp revision fdc2d0faf321224393f1a5dbf05c3e3f88bb6e3e
1//===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the SSAUpdater class. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "ssaupdater" 15#include "llvm/Constants.h" 16#include "llvm/Instructions.h" 17#include "llvm/IntrinsicInst.h" 18#include "llvm/ADT/DenseMap.h" 19#include "llvm/ADT/TinyPtrVector.h" 20#include "llvm/Analysis/InstructionSimplify.h" 21#include "llvm/Support/AlignOf.h" 22#include "llvm/Support/Allocator.h" 23#include "llvm/Support/CFG.h" 24#include "llvm/Support/Debug.h" 25#include "llvm/Support/raw_ostream.h" 26#include "llvm/Transforms/Utils/BasicBlockUtils.h" 27#include "llvm/Transforms/Utils/Local.h" 28#include "llvm/Transforms/Utils/SSAUpdater.h" 29#include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 30 31using namespace llvm; 32 33typedef DenseMap<BasicBlock*, Value*> AvailableValsTy; 34static AvailableValsTy &getAvailableVals(void *AV) { 35 return *static_cast<AvailableValsTy*>(AV); 36} 37 38SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI) 39 : AV(0), ProtoType(0), ProtoName(), InsertedPHIs(NewPHI) {} 40 41SSAUpdater::~SSAUpdater() { 42 delete &getAvailableVals(AV); 43} 44 45/// Initialize - Reset this object to get ready for a new set of SSA 46/// updates with type 'Ty'. PHI nodes get a name based on 'Name'. 47void SSAUpdater::Initialize(Type *Ty, StringRef Name) { 48 if (AV == 0) 49 AV = new AvailableValsTy(); 50 else 51 getAvailableVals(AV).clear(); 52 ProtoType = Ty; 53 ProtoName = Name; 54} 55 56/// HasValueForBlock - Return true if the SSAUpdater already has a value for 57/// the specified block. 58bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const { 59 return getAvailableVals(AV).count(BB); 60} 61 62/// AddAvailableValue - Indicate that a rewritten value is available in the 63/// specified block with the specified value. 64void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) { 65 assert(ProtoType != 0 && "Need to initialize SSAUpdater"); 66 assert(ProtoType == V->getType() && 67 "All rewritten values must have the same type"); 68 getAvailableVals(AV)[BB] = V; 69} 70 71/// IsEquivalentPHI - Check if PHI has the same incoming value as specified 72/// in ValueMapping for each predecessor block. 73static bool IsEquivalentPHI(PHINode *PHI, 74 DenseMap<BasicBlock*, Value*> &ValueMapping) { 75 unsigned PHINumValues = PHI->getNumIncomingValues(); 76 if (PHINumValues != ValueMapping.size()) 77 return false; 78 79 // Scan the phi to see if it matches. 80 for (unsigned i = 0, e = PHINumValues; i != e; ++i) 81 if (ValueMapping[PHI->getIncomingBlock(i)] != 82 PHI->getIncomingValue(i)) { 83 return false; 84 } 85 86 return true; 87} 88 89/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is 90/// live at the end of the specified block. 91Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) { 92 Value *Res = GetValueAtEndOfBlockInternal(BB); 93 return Res; 94} 95 96/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that 97/// is live in the middle of the specified block. 98/// 99/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one 100/// important case: if there is a definition of the rewritten value after the 101/// 'use' in BB. Consider code like this: 102/// 103/// X1 = ... 104/// SomeBB: 105/// use(X) 106/// X2 = ... 107/// br Cond, SomeBB, OutBB 108/// 109/// In this case, there are two values (X1 and X2) added to the AvailableVals 110/// set by the client of the rewriter, and those values are both live out of 111/// their respective blocks. However, the use of X happens in the *middle* of 112/// a block. Because of this, we need to insert a new PHI node in SomeBB to 113/// merge the appropriate values, and this value isn't live out of the block. 114/// 115Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) { 116 // If there is no definition of the renamed variable in this block, just use 117 // GetValueAtEndOfBlock to do our work. 118 if (!HasValueForBlock(BB)) 119 return GetValueAtEndOfBlock(BB); 120 121 // Otherwise, we have the hard case. Get the live-in values for each 122 // predecessor. 123 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues; 124 Value *SingularValue = 0; 125 126 // We can get our predecessor info by walking the pred_iterator list, but it 127 // is relatively slow. If we already have PHI nodes in this block, walk one 128 // of them to get the predecessor list instead. 129 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { 130 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) { 131 BasicBlock *PredBB = SomePhi->getIncomingBlock(i); 132 Value *PredVal = GetValueAtEndOfBlock(PredBB); 133 PredValues.push_back(std::make_pair(PredBB, PredVal)); 134 135 // Compute SingularValue. 136 if (i == 0) 137 SingularValue = PredVal; 138 else if (PredVal != SingularValue) 139 SingularValue = 0; 140 } 141 } else { 142 bool isFirstPred = true; 143 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 144 BasicBlock *PredBB = *PI; 145 Value *PredVal = GetValueAtEndOfBlock(PredBB); 146 PredValues.push_back(std::make_pair(PredBB, PredVal)); 147 148 // Compute SingularValue. 149 if (isFirstPred) { 150 SingularValue = PredVal; 151 isFirstPred = false; 152 } else if (PredVal != SingularValue) 153 SingularValue = 0; 154 } 155 } 156 157 // If there are no predecessors, just return undef. 158 if (PredValues.empty()) 159 return UndefValue::get(ProtoType); 160 161 // Otherwise, if all the merged values are the same, just use it. 162 if (SingularValue != 0) 163 return SingularValue; 164 165 // Otherwise, we do need a PHI: check to see if we already have one available 166 // in this block that produces the right value. 167 if (isa<PHINode>(BB->begin())) { 168 DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(), 169 PredValues.end()); 170 PHINode *SomePHI; 171 for (BasicBlock::iterator It = BB->begin(); 172 (SomePHI = dyn_cast<PHINode>(It)); ++It) { 173 if (IsEquivalentPHI(SomePHI, ValueMapping)) 174 return SomePHI; 175 } 176 } 177 178 // Ok, we have no way out, insert a new one now. 179 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(), 180 ProtoName, &BB->front()); 181 182 // Fill in all the predecessors of the PHI. 183 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) 184 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first); 185 186 // See if the PHI node can be merged to a single value. This can happen in 187 // loop cases when we get a PHI of itself and one other value. 188 if (Value *V = SimplifyInstruction(InsertedPHI)) { 189 InsertedPHI->eraseFromParent(); 190 return V; 191 } 192 193 // Set DebugLoc. 194 InsertedPHI->setDebugLoc(GetFirstDebugLocInBasicBlock(BB)); 195 196 // If the client wants to know about all new instructions, tell it. 197 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); 198 199 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n"); 200 return InsertedPHI; 201} 202 203/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes, 204/// which use their value in the corresponding predecessor. 205void SSAUpdater::RewriteUse(Use &U) { 206 Instruction *User = cast<Instruction>(U.getUser()); 207 208 Value *V; 209 if (PHINode *UserPN = dyn_cast<PHINode>(User)) 210 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); 211 else 212 V = GetValueInMiddleOfBlock(User->getParent()); 213 214 U.set(V); 215} 216 217/// RewriteUseAfterInsertions - Rewrite a use, just like RewriteUse. However, 218/// this version of the method can rewrite uses in the same block as a 219/// definition, because it assumes that all uses of a value are below any 220/// inserted values. 221void SSAUpdater::RewriteUseAfterInsertions(Use &U) { 222 Instruction *User = cast<Instruction>(U.getUser()); 223 224 Value *V; 225 if (PHINode *UserPN = dyn_cast<PHINode>(User)) 226 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); 227 else 228 V = GetValueAtEndOfBlock(User->getParent()); 229 230 U.set(V); 231} 232 233/// SSAUpdaterTraits<SSAUpdater> - Traits for the SSAUpdaterImpl template, 234/// specialized for SSAUpdater. 235namespace llvm { 236template<> 237class SSAUpdaterTraits<SSAUpdater> { 238public: 239 typedef BasicBlock BlkT; 240 typedef Value *ValT; 241 typedef PHINode PhiT; 242 243 typedef succ_iterator BlkSucc_iterator; 244 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); } 245 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); } 246 247 class PHI_iterator { 248 private: 249 PHINode *PHI; 250 unsigned idx; 251 252 public: 253 explicit PHI_iterator(PHINode *P) // begin iterator 254 : PHI(P), idx(0) {} 255 PHI_iterator(PHINode *P, bool) // end iterator 256 : PHI(P), idx(PHI->getNumIncomingValues()) {} 257 258 PHI_iterator &operator++() { ++idx; return *this; } 259 bool operator==(const PHI_iterator& x) const { return idx == x.idx; } 260 bool operator!=(const PHI_iterator& x) const { return !operator==(x); } 261 Value *getIncomingValue() { return PHI->getIncomingValue(idx); } 262 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); } 263 }; 264 265 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 266 static PHI_iterator PHI_end(PhiT *PHI) { 267 return PHI_iterator(PHI, true); 268 } 269 270 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds 271 /// vector, set Info->NumPreds, and allocate space in Info->Preds. 272 static void FindPredecessorBlocks(BasicBlock *BB, 273 SmallVectorImpl<BasicBlock*> *Preds) { 274 // We can get our predecessor info by walking the pred_iterator list, 275 // but it is relatively slow. If we already have PHI nodes in this 276 // block, walk one of them to get the predecessor list instead. 277 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { 278 for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI) 279 Preds->push_back(SomePhi->getIncomingBlock(PI)); 280 } else { 281 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 282 Preds->push_back(*PI); 283 } 284 } 285 286 /// GetUndefVal - Get an undefined value of the same type as the value 287 /// being handled. 288 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) { 289 return UndefValue::get(Updater->ProtoType); 290 } 291 292 /// CreateEmptyPHI - Create a new PHI instruction in the specified block. 293 /// Reserve space for the operands but do not fill them in yet. 294 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds, 295 SSAUpdater *Updater) { 296 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds, 297 Updater->ProtoName, &BB->front()); 298 return PHI; 299 } 300 301 /// AddPHIOperand - Add the specified value as an operand of the PHI for 302 /// the specified predecessor block. 303 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) { 304 PHI->addIncoming(Val, Pred); 305 } 306 307 /// InstrIsPHI - Check if an instruction is a PHI. 308 /// 309 static PHINode *InstrIsPHI(Instruction *I) { 310 return dyn_cast<PHINode>(I); 311 } 312 313 /// ValueIsPHI - Check if a value is a PHI. 314 /// 315 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) { 316 return dyn_cast<PHINode>(Val); 317 } 318 319 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 320 /// operands, i.e., it was just added. 321 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) { 322 PHINode *PHI = ValueIsPHI(Val, Updater); 323 if (PHI && PHI->getNumIncomingValues() == 0) 324 return PHI; 325 return 0; 326 } 327 328 /// GetPHIValue - For the specified PHI instruction, return the value 329 /// that it defines. 330 static Value *GetPHIValue(PHINode *PHI) { 331 return PHI; 332 } 333}; 334 335} // End llvm namespace 336 337/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry 338/// for the specified BB and if so, return it. If not, construct SSA form by 339/// first calculating the required placement of PHIs and then inserting new 340/// PHIs where needed. 341Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) { 342 AvailableValsTy &AvailableVals = getAvailableVals(AV); 343 if (Value *V = AvailableVals[BB]) 344 return V; 345 346 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs); 347 return Impl.GetValue(BB); 348} 349 350//===----------------------------------------------------------------------===// 351// LoadAndStorePromoter Implementation 352//===----------------------------------------------------------------------===// 353 354LoadAndStorePromoter:: 355LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts, 356 SSAUpdater &S, StringRef BaseName) : SSA(S) { 357 if (Insts.empty()) return; 358 359 Value *SomeVal; 360 if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0])) 361 SomeVal = LI; 362 else 363 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0); 364 365 if (BaseName.empty()) 366 BaseName = SomeVal->getName(); 367 SSA.Initialize(SomeVal->getType(), BaseName); 368} 369 370 371void LoadAndStorePromoter:: 372run(const SmallVectorImpl<Instruction*> &Insts) const { 373 374 // First step: bucket up uses of the alloca by the block they occur in. 375 // This is important because we have to handle multiple defs/uses in a block 376 // ourselves: SSAUpdater is purely for cross-block references. 377 DenseMap<BasicBlock*, TinyPtrVector<Instruction*> > UsesByBlock; 378 379 for (unsigned i = 0, e = Insts.size(); i != e; ++i) { 380 Instruction *User = Insts[i]; 381 UsesByBlock[User->getParent()].push_back(User); 382 } 383 384 // Okay, now we can iterate over all the blocks in the function with uses, 385 // processing them. Keep track of which loads are loading a live-in value. 386 // Walk the uses in the use-list order to be determinstic. 387 SmallVector<LoadInst*, 32> LiveInLoads; 388 DenseMap<Value*, Value*> ReplacedLoads; 389 390 for (unsigned i = 0, e = Insts.size(); i != e; ++i) { 391 Instruction *User = Insts[i]; 392 BasicBlock *BB = User->getParent(); 393 TinyPtrVector<Instruction*> &BlockUses = UsesByBlock[BB]; 394 395 // If this block has already been processed, ignore this repeat use. 396 if (BlockUses.empty()) continue; 397 398 // Okay, this is the first use in the block. If this block just has a 399 // single user in it, we can rewrite it trivially. 400 if (BlockUses.size() == 1) { 401 // If it is a store, it is a trivial def of the value in the block. 402 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 403 updateDebugInfo(SI); 404 SSA.AddAvailableValue(BB, SI->getOperand(0)); 405 } else 406 // Otherwise it is a load, queue it to rewrite as a live-in load. 407 LiveInLoads.push_back(cast<LoadInst>(User)); 408 BlockUses.clear(); 409 continue; 410 } 411 412 // Otherwise, check to see if this block is all loads. 413 bool HasStore = false; 414 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) { 415 if (isa<StoreInst>(BlockUses[i])) { 416 HasStore = true; 417 break; 418 } 419 } 420 421 // If so, we can queue them all as live in loads. We don't have an 422 // efficient way to tell which on is first in the block and don't want to 423 // scan large blocks, so just add all loads as live ins. 424 if (!HasStore) { 425 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) 426 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i])); 427 BlockUses.clear(); 428 continue; 429 } 430 431 // Otherwise, we have mixed loads and stores (or just a bunch of stores). 432 // Since SSAUpdater is purely for cross-block values, we need to determine 433 // the order of these instructions in the block. If the first use in the 434 // block is a load, then it uses the live in value. The last store defines 435 // the live out value. We handle this by doing a linear scan of the block. 436 Value *StoredValue = 0; 437 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) { 438 if (LoadInst *L = dyn_cast<LoadInst>(II)) { 439 // If this is a load from an unrelated pointer, ignore it. 440 if (!isInstInList(L, Insts)) continue; 441 442 // If we haven't seen a store yet, this is a live in use, otherwise 443 // use the stored value. 444 if (StoredValue) { 445 replaceLoadWithValue(L, StoredValue); 446 L->replaceAllUsesWith(StoredValue); 447 ReplacedLoads[L] = StoredValue; 448 } else { 449 LiveInLoads.push_back(L); 450 } 451 continue; 452 } 453 454 if (StoreInst *SI = dyn_cast<StoreInst>(II)) { 455 // If this is a store to an unrelated pointer, ignore it. 456 if (!isInstInList(SI, Insts)) continue; 457 updateDebugInfo(SI); 458 459 // Remember that this is the active value in the block. 460 StoredValue = SI->getOperand(0); 461 } 462 } 463 464 // The last stored value that happened is the live-out for the block. 465 assert(StoredValue && "Already checked that there is a store in block"); 466 SSA.AddAvailableValue(BB, StoredValue); 467 BlockUses.clear(); 468 } 469 470 // Okay, now we rewrite all loads that use live-in values in the loop, 471 // inserting PHI nodes as necessary. 472 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) { 473 LoadInst *ALoad = LiveInLoads[i]; 474 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent()); 475 replaceLoadWithValue(ALoad, NewVal); 476 477 // Avoid assertions in unreachable code. 478 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType()); 479 ALoad->replaceAllUsesWith(NewVal); 480 ReplacedLoads[ALoad] = NewVal; 481 } 482 483 // Allow the client to do stuff before we start nuking things. 484 doExtraRewritesBeforeFinalDeletion(); 485 486 // Now that everything is rewritten, delete the old instructions from the 487 // function. They should all be dead now. 488 for (unsigned i = 0, e = Insts.size(); i != e; ++i) { 489 Instruction *User = Insts[i]; 490 491 // If this is a load that still has uses, then the load must have been added 492 // as a live value in the SSAUpdate data structure for a block (e.g. because 493 // the loaded value was stored later). In this case, we need to recursively 494 // propagate the updates until we get to the real value. 495 if (!User->use_empty()) { 496 Value *NewVal = ReplacedLoads[User]; 497 assert(NewVal && "not a replaced load?"); 498 499 // Propagate down to the ultimate replacee. The intermediately loads 500 // could theoretically already have been deleted, so we don't want to 501 // dereference the Value*'s. 502 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal); 503 while (RLI != ReplacedLoads.end()) { 504 NewVal = RLI->second; 505 RLI = ReplacedLoads.find(NewVal); 506 } 507 508 replaceLoadWithValue(cast<LoadInst>(User), NewVal); 509 User->replaceAllUsesWith(NewVal); 510 } 511 512 instructionDeleted(User); 513 User->eraseFromParent(); 514 } 515} 516 517bool 518LoadAndStorePromoter::isInstInList(Instruction *I, 519 const SmallVectorImpl<Instruction*> &Insts) 520 const { 521 return std::find(Insts.begin(), Insts.end(), I) != Insts.end(); 522} 523