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