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 static_cast<AvailableValsTy*>(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 the DebugLoc of the inserted PHI, if available. 194 DebugLoc DL; 195 if (const Instruction *I = BB->getFirstNonPHI()) 196 DL = I->getDebugLoc(); 197 InsertedPHI->setDebugLoc(DL); 198 199 // If the client wants to know about all new instructions, tell it. 200 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); 201 202 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n"); 203 return InsertedPHI; 204} 205 206/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes, 207/// which use their value in the corresponding predecessor. 208void SSAUpdater::RewriteUse(Use &U) { 209 Instruction *User = cast<Instruction>(U.getUser()); 210 211 Value *V; 212 if (PHINode *UserPN = dyn_cast<PHINode>(User)) 213 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); 214 else 215 V = GetValueInMiddleOfBlock(User->getParent()); 216 217 // Notify that users of the existing value that it is being replaced. 218 Value *OldVal = U.get(); 219 if (OldVal != V && OldVal->hasValueHandle()) 220 ValueHandleBase::ValueIsRAUWd(OldVal, V); 221 222 U.set(V); 223} 224 225/// RewriteUseAfterInsertions - Rewrite a use, just like RewriteUse. However, 226/// this version of the method can rewrite uses in the same block as a 227/// definition, because it assumes that all uses of a value are below any 228/// inserted values. 229void SSAUpdater::RewriteUseAfterInsertions(Use &U) { 230 Instruction *User = cast<Instruction>(U.getUser()); 231 232 Value *V; 233 if (PHINode *UserPN = dyn_cast<PHINode>(User)) 234 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); 235 else 236 V = GetValueAtEndOfBlock(User->getParent()); 237 238 U.set(V); 239} 240 241/// SSAUpdaterTraits<SSAUpdater> - Traits for the SSAUpdaterImpl template, 242/// specialized for SSAUpdater. 243namespace llvm { 244template<> 245class SSAUpdaterTraits<SSAUpdater> { 246public: 247 typedef BasicBlock BlkT; 248 typedef Value *ValT; 249 typedef PHINode PhiT; 250 251 typedef succ_iterator BlkSucc_iterator; 252 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); } 253 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); } 254 255 class PHI_iterator { 256 private: 257 PHINode *PHI; 258 unsigned idx; 259 260 public: 261 explicit PHI_iterator(PHINode *P) // begin iterator 262 : PHI(P), idx(0) {} 263 PHI_iterator(PHINode *P, bool) // end iterator 264 : PHI(P), idx(PHI->getNumIncomingValues()) {} 265 266 PHI_iterator &operator++() { ++idx; return *this; } 267 bool operator==(const PHI_iterator& x) const { return idx == x.idx; } 268 bool operator!=(const PHI_iterator& x) const { return !operator==(x); } 269 Value *getIncomingValue() { return PHI->getIncomingValue(idx); } 270 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); } 271 }; 272 273 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 274 static PHI_iterator PHI_end(PhiT *PHI) { 275 return PHI_iterator(PHI, true); 276 } 277 278 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds 279 /// vector, set Info->NumPreds, and allocate space in Info->Preds. 280 static void FindPredecessorBlocks(BasicBlock *BB, 281 SmallVectorImpl<BasicBlock*> *Preds) { 282 // We can get our predecessor info by walking the pred_iterator list, 283 // but it is relatively slow. If we already have PHI nodes in this 284 // block, walk one of them to get the predecessor list instead. 285 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { 286 for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI) 287 Preds->push_back(SomePhi->getIncomingBlock(PI)); 288 } else { 289 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 290 Preds->push_back(*PI); 291 } 292 } 293 294 /// GetUndefVal - Get an undefined value of the same type as the value 295 /// being handled. 296 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) { 297 return UndefValue::get(Updater->ProtoType); 298 } 299 300 /// CreateEmptyPHI - Create a new PHI instruction in the specified block. 301 /// Reserve space for the operands but do not fill them in yet. 302 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds, 303 SSAUpdater *Updater) { 304 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds, 305 Updater->ProtoName, &BB->front()); 306 return PHI; 307 } 308 309 /// AddPHIOperand - Add the specified value as an operand of the PHI for 310 /// the specified predecessor block. 311 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) { 312 PHI->addIncoming(Val, Pred); 313 } 314 315 /// InstrIsPHI - Check if an instruction is a PHI. 316 /// 317 static PHINode *InstrIsPHI(Instruction *I) { 318 return dyn_cast<PHINode>(I); 319 } 320 321 /// ValueIsPHI - Check if a value is a PHI. 322 /// 323 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) { 324 return dyn_cast<PHINode>(Val); 325 } 326 327 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 328 /// operands, i.e., it was just added. 329 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) { 330 PHINode *PHI = ValueIsPHI(Val, Updater); 331 if (PHI && PHI->getNumIncomingValues() == 0) 332 return PHI; 333 return 0; 334 } 335 336 /// GetPHIValue - For the specified PHI instruction, return the value 337 /// that it defines. 338 static Value *GetPHIValue(PHINode *PHI) { 339 return PHI; 340 } 341}; 342 343} // End llvm namespace 344 345/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry 346/// for the specified BB and if so, return it. If not, construct SSA form by 347/// first calculating the required placement of PHIs and then inserting new 348/// PHIs where needed. 349Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) { 350 AvailableValsTy &AvailableVals = getAvailableVals(AV); 351 if (Value *V = AvailableVals[BB]) 352 return V; 353 354 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs); 355 return Impl.GetValue(BB); 356} 357 358//===----------------------------------------------------------------------===// 359// LoadAndStorePromoter Implementation 360//===----------------------------------------------------------------------===// 361 362LoadAndStorePromoter:: 363LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts, 364 SSAUpdater &S, StringRef BaseName) : SSA(S) { 365 if (Insts.empty()) return; 366 367 Value *SomeVal; 368 if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0])) 369 SomeVal = LI; 370 else 371 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0); 372 373 if (BaseName.empty()) 374 BaseName = SomeVal->getName(); 375 SSA.Initialize(SomeVal->getType(), BaseName); 376} 377 378 379void LoadAndStorePromoter:: 380run(const SmallVectorImpl<Instruction*> &Insts) const { 381 382 // First step: bucket up uses of the alloca by the block they occur in. 383 // This is important because we have to handle multiple defs/uses in a block 384 // ourselves: SSAUpdater is purely for cross-block references. 385 DenseMap<BasicBlock*, TinyPtrVector<Instruction*> > UsesByBlock; 386 387 for (unsigned i = 0, e = Insts.size(); i != e; ++i) { 388 Instruction *User = Insts[i]; 389 UsesByBlock[User->getParent()].push_back(User); 390 } 391 392 // Okay, now we can iterate over all the blocks in the function with uses, 393 // processing them. Keep track of which loads are loading a live-in value. 394 // Walk the uses in the use-list order to be determinstic. 395 SmallVector<LoadInst*, 32> LiveInLoads; 396 DenseMap<Value*, Value*> ReplacedLoads; 397 398 for (unsigned i = 0, e = Insts.size(); i != e; ++i) { 399 Instruction *User = Insts[i]; 400 BasicBlock *BB = User->getParent(); 401 TinyPtrVector<Instruction*> &BlockUses = UsesByBlock[BB]; 402 403 // If this block has already been processed, ignore this repeat use. 404 if (BlockUses.empty()) continue; 405 406 // Okay, this is the first use in the block. If this block just has a 407 // single user in it, we can rewrite it trivially. 408 if (BlockUses.size() == 1) { 409 // If it is a store, it is a trivial def of the value in the block. 410 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 411 updateDebugInfo(SI); 412 SSA.AddAvailableValue(BB, SI->getOperand(0)); 413 } else 414 // Otherwise it is a load, queue it to rewrite as a live-in load. 415 LiveInLoads.push_back(cast<LoadInst>(User)); 416 BlockUses.clear(); 417 continue; 418 } 419 420 // Otherwise, check to see if this block is all loads. 421 bool HasStore = false; 422 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) { 423 if (isa<StoreInst>(BlockUses[i])) { 424 HasStore = true; 425 break; 426 } 427 } 428 429 // If so, we can queue them all as live in loads. We don't have an 430 // efficient way to tell which on is first in the block and don't want to 431 // scan large blocks, so just add all loads as live ins. 432 if (!HasStore) { 433 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) 434 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i])); 435 BlockUses.clear(); 436 continue; 437 } 438 439 // Otherwise, we have mixed loads and stores (or just a bunch of stores). 440 // Since SSAUpdater is purely for cross-block values, we need to determine 441 // the order of these instructions in the block. If the first use in the 442 // block is a load, then it uses the live in value. The last store defines 443 // the live out value. We handle this by doing a linear scan of the block. 444 Value *StoredValue = 0; 445 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) { 446 if (LoadInst *L = dyn_cast<LoadInst>(II)) { 447 // If this is a load from an unrelated pointer, ignore it. 448 if (!isInstInList(L, Insts)) continue; 449 450 // If we haven't seen a store yet, this is a live in use, otherwise 451 // use the stored value. 452 if (StoredValue) { 453 replaceLoadWithValue(L, StoredValue); 454 L->replaceAllUsesWith(StoredValue); 455 ReplacedLoads[L] = StoredValue; 456 } else { 457 LiveInLoads.push_back(L); 458 } 459 continue; 460 } 461 462 if (StoreInst *SI = dyn_cast<StoreInst>(II)) { 463 // If this is a store to an unrelated pointer, ignore it. 464 if (!isInstInList(SI, Insts)) continue; 465 updateDebugInfo(SI); 466 467 // Remember that this is the active value in the block. 468 StoredValue = SI->getOperand(0); 469 } 470 } 471 472 // The last stored value that happened is the live-out for the block. 473 assert(StoredValue && "Already checked that there is a store in block"); 474 SSA.AddAvailableValue(BB, StoredValue); 475 BlockUses.clear(); 476 } 477 478 // Okay, now we rewrite all loads that use live-in values in the loop, 479 // inserting PHI nodes as necessary. 480 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) { 481 LoadInst *ALoad = LiveInLoads[i]; 482 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent()); 483 replaceLoadWithValue(ALoad, NewVal); 484 485 // Avoid assertions in unreachable code. 486 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType()); 487 ALoad->replaceAllUsesWith(NewVal); 488 ReplacedLoads[ALoad] = NewVal; 489 } 490 491 // Allow the client to do stuff before we start nuking things. 492 doExtraRewritesBeforeFinalDeletion(); 493 494 // Now that everything is rewritten, delete the old instructions from the 495 // function. They should all be dead now. 496 for (unsigned i = 0, e = Insts.size(); i != e; ++i) { 497 Instruction *User = Insts[i]; 498 499 // If this is a load that still has uses, then the load must have been added 500 // as a live value in the SSAUpdate data structure for a block (e.g. because 501 // the loaded value was stored later). In this case, we need to recursively 502 // propagate the updates until we get to the real value. 503 if (!User->use_empty()) { 504 Value *NewVal = ReplacedLoads[User]; 505 assert(NewVal && "not a replaced load?"); 506 507 // Propagate down to the ultimate replacee. The intermediately loads 508 // could theoretically already have been deleted, so we don't want to 509 // dereference the Value*'s. 510 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal); 511 while (RLI != ReplacedLoads.end()) { 512 NewVal = RLI->second; 513 RLI = ReplacedLoads.find(NewVal); 514 } 515 516 replaceLoadWithValue(cast<LoadInst>(User), NewVal); 517 User->replaceAllUsesWith(NewVal); 518 } 519 520 instructionDeleted(User); 521 User->eraseFromParent(); 522 } 523} 524 525bool 526LoadAndStorePromoter::isInstInList(Instruction *I, 527 const SmallVectorImpl<Instruction*> &Insts) 528 const { 529 return std::find(Insts.begin(), Insts.end(), I) != Insts.end(); 530} 531