1 //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SSAUpdater class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/SSAUpdater.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.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/SSAUpdaterImpl.h"
39 #define DEBUG_TYPE "ssaupdater"
41 using AvailableValsTy = DenseMap<BasicBlock *, Value *>;
43 static AvailableValsTy &getAvailableVals(void *AV) {
44 return *static_cast<AvailableValsTy*>(AV);
47 SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode *> *NewPHI)
48 : InsertedPHIs(NewPHI) {}
50 SSAUpdater::~SSAUpdater() {
51 delete static_cast<AvailableValsTy*>(AV);
54 void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
56 AV = new AvailableValsTy();
58 getAvailableVals(AV).clear();
63 bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
64 return getAvailableVals(AV).count(BB);
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;
74 static bool IsEquivalentPHI(PHINode *PHI,
75 SmallDenseMap<BasicBlock *, Value *, 8> &ValueMapping) {
76 unsigned PHINumValues = PHI->getNumIncomingValues();
77 if (PHINumValues != ValueMapping.size())
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)) {
90 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
91 Value *Res = GetValueAtEndOfBlockInternal(BB);
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);
101 // Otherwise, we have the hard case. Get the live-in values for each
103 SmallVector<std::pair<BasicBlock *, Value *>, 8> PredValues;
104 Value *SingularValue = nullptr;
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));
115 // Compute SingularValue.
117 SingularValue = PredVal;
118 else if (PredVal != SingularValue)
119 SingularValue = nullptr;
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));
128 // Compute SingularValue.
130 SingularValue = PredVal;
132 } else if (PredVal != SingularValue)
133 SingularValue = nullptr;
137 // If there are no predecessors, just return undef.
138 if (PredValues.empty())
139 return UndefValue::get(ProtoType);
141 // Otherwise, if all the merged values are the same, just use it.
143 return SingularValue;
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(),
150 for (PHINode &SomePHI : BB->phis()) {
151 if (IsEquivalentPHI(&SomePHI, ValueMapping))
156 // Ok, we have no way out, insert a new one now.
157 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
158 ProtoName, &BB->front());
160 // Fill in all the predecessors of the PHI.
161 for (const auto &PredValue : PredValues)
162 InsertedPHI->addIncoming(PredValue.second, PredValue.first);
164 // See if the PHI node can be merged to a single value. This can happen in
165 // loop cases when we get a PHI of itself and one other value.
167 SimplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) {
168 InsertedPHI->eraseFromParent();
172 // Set the DebugLoc of the inserted PHI, if available.
174 if (const Instruction *I = BB->getFirstNonPHI())
175 DL = I->getDebugLoc();
176 InsertedPHI->setDebugLoc(DL);
178 // If the client wants to know about all new instructions, tell it.
179 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
181 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
185 void SSAUpdater::RewriteUse(Use &U) {
186 Instruction *User = cast<Instruction>(U.getUser());
189 if (PHINode *UserPN = dyn_cast<PHINode>(User))
190 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
192 V = GetValueInMiddleOfBlock(User->getParent());
194 // Notify that users of the existing value that it is being replaced.
195 Value *OldVal = U.get();
196 if (OldVal != V && OldVal->hasValueHandle())
197 ValueHandleBase::ValueIsRAUWd(OldVal, V);
202 void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
203 Instruction *User = cast<Instruction>(U.getUser());
206 if (PHINode *UserPN = dyn_cast<PHINode>(User))
207 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
209 V = GetValueAtEndOfBlock(User->getParent());
217 class SSAUpdaterTraits<SSAUpdater> {
219 using BlkT = BasicBlock;
220 using ValT = Value *;
221 using PhiT = PHINode;
222 using BlkSucc_iterator = succ_iterator;
224 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
225 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
233 explicit PHI_iterator(PHINode *P) // begin iterator
235 PHI_iterator(PHINode *P, bool) // end iterator
236 : PHI(P), idx(PHI->getNumIncomingValues()) {}
238 PHI_iterator &operator++() { ++idx; return *this; }
239 bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
240 bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
242 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
243 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
246 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
247 static PHI_iterator PHI_end(PhiT *PHI) {
248 return PHI_iterator(PHI, true);
251 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
252 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
253 static void FindPredecessorBlocks(BasicBlock *BB,
254 SmallVectorImpl<BasicBlock *> *Preds) {
255 // We can get our predecessor info by walking the pred_iterator list,
256 // but it is relatively slow. If we already have PHI nodes in this
257 // block, walk one of them to get the predecessor list instead.
258 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
259 Preds->append(SomePhi->block_begin(), SomePhi->block_end());
261 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
262 Preds->push_back(*PI);
266 /// GetUndefVal - Get an undefined value of the same type as the value
268 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
269 return UndefValue::get(Updater->ProtoType);
272 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
273 /// Reserve space for the operands but do not fill them in yet.
274 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
275 SSAUpdater *Updater) {
276 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
277 Updater->ProtoName, &BB->front());
281 /// AddPHIOperand - Add the specified value as an operand of the PHI for
282 /// the specified predecessor block.
283 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
284 PHI->addIncoming(Val, Pred);
287 /// InstrIsPHI - Check if an instruction is a PHI.
289 static PHINode *InstrIsPHI(Instruction *I) {
290 return dyn_cast<PHINode>(I);
293 /// ValueIsPHI - Check if a value is a PHI.
294 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
295 return dyn_cast<PHINode>(Val);
298 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
299 /// operands, i.e., it was just added.
300 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
301 PHINode *PHI = ValueIsPHI(Val, Updater);
302 if (PHI && PHI->getNumIncomingValues() == 0)
307 /// GetPHIValue - For the specified PHI instruction, return the value
309 static Value *GetPHIValue(PHINode *PHI) {
314 } // end namespace llvm
316 /// Check to see if AvailableVals has an entry for the specified BB and if so,
317 /// return it. If not, construct SSA form by first calculating the required
318 /// placement of PHIs and then inserting new PHIs where needed.
319 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
320 AvailableValsTy &AvailableVals = getAvailableVals(AV);
321 if (Value *V = AvailableVals[BB])
324 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
325 return Impl.GetValue(BB);
328 //===----------------------------------------------------------------------===//
329 // LoadAndStorePromoter Implementation
330 //===----------------------------------------------------------------------===//
332 LoadAndStorePromoter::
333 LoadAndStorePromoter(ArrayRef<const Instruction *> Insts,
334 SSAUpdater &S, StringRef BaseName) : SSA(S) {
335 if (Insts.empty()) return;
337 const Value *SomeVal;
338 if (const LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
341 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
343 if (BaseName.empty())
344 BaseName = SomeVal->getName();
345 SSA.Initialize(SomeVal->getType(), BaseName);
348 void LoadAndStorePromoter::
349 run(const SmallVectorImpl<Instruction *> &Insts) const {
350 // First step: bucket up uses of the alloca by the block they occur in.
351 // This is important because we have to handle multiple defs/uses in a block
352 // ourselves: SSAUpdater is purely for cross-block references.
353 DenseMap<BasicBlock *, TinyPtrVector<Instruction *>> UsesByBlock;
355 for (Instruction *User : Insts)
356 UsesByBlock[User->getParent()].push_back(User);
358 // Okay, now we can iterate over all the blocks in the function with uses,
359 // processing them. Keep track of which loads are loading a live-in value.
360 // Walk the uses in the use-list order to be determinstic.
361 SmallVector<LoadInst *, 32> LiveInLoads;
362 DenseMap<Value *, Value *> ReplacedLoads;
364 for (Instruction *User : Insts) {
365 BasicBlock *BB = User->getParent();
366 TinyPtrVector<Instruction *> &BlockUses = UsesByBlock[BB];
368 // If this block has already been processed, ignore this repeat use.
369 if (BlockUses.empty()) continue;
371 // Okay, this is the first use in the block. If this block just has a
372 // single user in it, we can rewrite it trivially.
373 if (BlockUses.size() == 1) {
374 // If it is a store, it is a trivial def of the value in the block.
375 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
377 SSA.AddAvailableValue(BB, SI->getOperand(0));
379 // Otherwise it is a load, queue it to rewrite as a live-in load.
380 LiveInLoads.push_back(cast<LoadInst>(User));
385 // Otherwise, check to see if this block is all loads.
386 bool HasStore = false;
387 for (Instruction *I : BlockUses) {
388 if (isa<StoreInst>(I)) {
394 // If so, we can queue them all as live in loads. We don't have an
395 // efficient way to tell which on is first in the block and don't want to
396 // scan large blocks, so just add all loads as live ins.
398 for (Instruction *I : BlockUses)
399 LiveInLoads.push_back(cast<LoadInst>(I));
404 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
405 // Since SSAUpdater is purely for cross-block values, we need to determine
406 // the order of these instructions in the block. If the first use in the
407 // block is a load, then it uses the live in value. The last store defines
408 // the live out value. We handle this by doing a linear scan of the block.
409 Value *StoredValue = nullptr;
410 for (Instruction &I : *BB) {
411 if (LoadInst *L = dyn_cast<LoadInst>(&I)) {
412 // If this is a load from an unrelated pointer, ignore it.
413 if (!isInstInList(L, Insts)) continue;
415 // If we haven't seen a store yet, this is a live in use, otherwise
416 // use the stored value.
418 replaceLoadWithValue(L, StoredValue);
419 L->replaceAllUsesWith(StoredValue);
420 ReplacedLoads[L] = StoredValue;
422 LiveInLoads.push_back(L);
427 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
428 // If this is a store to an unrelated pointer, ignore it.
429 if (!isInstInList(SI, Insts)) continue;
432 // Remember that this is the active value in the block.
433 StoredValue = SI->getOperand(0);
437 // The last stored value that happened is the live-out for the block.
438 assert(StoredValue && "Already checked that there is a store in block");
439 SSA.AddAvailableValue(BB, StoredValue);
443 // Okay, now we rewrite all loads that use live-in values in the loop,
444 // inserting PHI nodes as necessary.
445 for (LoadInst *ALoad : LiveInLoads) {
446 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
447 replaceLoadWithValue(ALoad, NewVal);
449 // Avoid assertions in unreachable code.
450 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
451 ALoad->replaceAllUsesWith(NewVal);
452 ReplacedLoads[ALoad] = NewVal;
455 // Allow the client to do stuff before we start nuking things.
456 doExtraRewritesBeforeFinalDeletion();
458 // Now that everything is rewritten, delete the old instructions from the
459 // function. They should all be dead now.
460 for (Instruction *User : Insts) {
461 // If this is a load that still has uses, then the load must have been added
462 // as a live value in the SSAUpdate data structure for a block (e.g. because
463 // the loaded value was stored later). In this case, we need to recursively
464 // propagate the updates until we get to the real value.
465 if (!User->use_empty()) {
466 Value *NewVal = ReplacedLoads[User];
467 assert(NewVal && "not a replaced load?");
469 // Propagate down to the ultimate replacee. The intermediately loads
470 // could theoretically already have been deleted, so we don't want to
471 // dereference the Value*'s.
472 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
473 while (RLI != ReplacedLoads.end()) {
474 NewVal = RLI->second;
475 RLI = ReplacedLoads.find(NewVal);
478 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
479 User->replaceAllUsesWith(NewVal);
482 instructionDeleted(User);
483 User->eraseFromParent();
488 LoadAndStorePromoter::isInstInList(Instruction *I,
489 const SmallVectorImpl<Instruction *> &Insts)
491 return is_contained(Insts, I);