1 //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the SSAUpdater class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Transforms/Utils/SSAUpdater.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/TinyPtrVector.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugLoc.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Use.h"
27 #include "llvm/IR/Value.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
37 #define DEBUG_TYPE "ssaupdater"
39 using AvailableValsTy
= DenseMap
<BasicBlock
*, Value
*>;
41 static AvailableValsTy
&getAvailableVals(void *AV
) {
42 return *static_cast<AvailableValsTy
*>(AV
);
45 SSAUpdater::SSAUpdater(SmallVectorImpl
<PHINode
*> *NewPHI
)
46 : InsertedPHIs(NewPHI
) {}
48 SSAUpdater::~SSAUpdater() {
49 delete static_cast<AvailableValsTy
*>(AV
);
52 void SSAUpdater::Initialize(Type
*Ty
, StringRef Name
) {
54 AV
= new AvailableValsTy();
56 getAvailableVals(AV
).clear();
58 ProtoName
= std::string(Name
);
61 bool SSAUpdater::HasValueForBlock(BasicBlock
*BB
) const {
62 return getAvailableVals(AV
).count(BB
);
65 Value
*SSAUpdater::FindValueForBlock(BasicBlock
*BB
) const {
66 return getAvailableVals(AV
).lookup(BB
);
69 void SSAUpdater::AddAvailableValue(BasicBlock
*BB
, Value
*V
) {
70 assert(ProtoType
&& "Need to initialize SSAUpdater");
71 assert(ProtoType
== V
->getType() &&
72 "All rewritten values must have the same type");
73 getAvailableVals(AV
)[BB
] = V
;
76 static bool IsEquivalentPHI(PHINode
*PHI
,
77 SmallDenseMap
<BasicBlock
*, Value
*, 8> &ValueMapping
) {
78 unsigned PHINumValues
= PHI
->getNumIncomingValues();
79 if (PHINumValues
!= ValueMapping
.size())
82 // Scan the phi to see if it matches.
83 for (unsigned i
= 0, e
= PHINumValues
; i
!= e
; ++i
)
84 if (ValueMapping
[PHI
->getIncomingBlock(i
)] !=
85 PHI
->getIncomingValue(i
)) {
92 Value
*SSAUpdater::GetValueAtEndOfBlock(BasicBlock
*BB
) {
93 Value
*Res
= GetValueAtEndOfBlockInternal(BB
);
97 Value
*SSAUpdater::GetValueInMiddleOfBlock(BasicBlock
*BB
) {
98 // If there is no definition of the renamed variable in this block, just use
99 // GetValueAtEndOfBlock to do our work.
100 if (!HasValueForBlock(BB
))
101 return GetValueAtEndOfBlock(BB
);
103 // Otherwise, we have the hard case. Get the live-in values for each
105 SmallVector
<std::pair
<BasicBlock
*, Value
*>, 8> PredValues
;
106 Value
*SingularValue
= nullptr;
108 // We can get our predecessor info by walking the pred_iterator list, but it
109 // is relatively slow. If we already have PHI nodes in this block, walk one
110 // of them to get the predecessor list instead.
111 if (PHINode
*SomePhi
= dyn_cast
<PHINode
>(BB
->begin())) {
112 for (unsigned i
= 0, e
= SomePhi
->getNumIncomingValues(); i
!= e
; ++i
) {
113 BasicBlock
*PredBB
= SomePhi
->getIncomingBlock(i
);
114 Value
*PredVal
= GetValueAtEndOfBlock(PredBB
);
115 PredValues
.push_back(std::make_pair(PredBB
, PredVal
));
117 // Compute SingularValue.
119 SingularValue
= PredVal
;
120 else if (PredVal
!= SingularValue
)
121 SingularValue
= nullptr;
124 bool isFirstPred
= true;
125 for (BasicBlock
*PredBB
: predecessors(BB
)) {
126 Value
*PredVal
= GetValueAtEndOfBlock(PredBB
);
127 PredValues
.push_back(std::make_pair(PredBB
, PredVal
));
129 // Compute SingularValue.
131 SingularValue
= PredVal
;
133 } else if (PredVal
!= SingularValue
)
134 SingularValue
= nullptr;
138 // If there are no predecessors, just return undef.
139 if (PredValues
.empty())
140 return UndefValue::get(ProtoType
);
142 // Otherwise, if all the merged values are the same, just use it.
144 return SingularValue
;
146 // Otherwise, we do need a PHI: check to see if we already have one available
147 // in this block that produces the right value.
148 if (isa
<PHINode
>(BB
->begin())) {
149 SmallDenseMap
<BasicBlock
*, Value
*, 8> ValueMapping(PredValues
.begin(),
151 for (PHINode
&SomePHI
: BB
->phis()) {
152 if (IsEquivalentPHI(&SomePHI
, ValueMapping
))
157 // Ok, we have no way out, insert a new one now.
158 PHINode
*InsertedPHI
= PHINode::Create(ProtoType
, PredValues
.size(),
159 ProtoName
, &BB
->front());
161 // Fill in all the predecessors of the PHI.
162 for (const auto &PredValue
: PredValues
)
163 InsertedPHI
->addIncoming(PredValue
.second
, PredValue
.first
);
165 // See if the PHI node can be merged to a single value. This can happen in
166 // loop cases when we get a PHI of itself and one other value.
168 simplifyInstruction(InsertedPHI
, BB
->getModule()->getDataLayout())) {
169 InsertedPHI
->eraseFromParent();
173 // Set the DebugLoc of the inserted PHI, if available.
175 if (const Instruction
*I
= BB
->getFirstNonPHI())
176 DL
= I
->getDebugLoc();
177 InsertedPHI
->setDebugLoc(DL
);
179 // If the client wants to know about all new instructions, tell it.
180 if (InsertedPHIs
) InsertedPHIs
->push_back(InsertedPHI
);
182 LLVM_DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI
<< "\n");
186 void SSAUpdater::RewriteUse(Use
&U
) {
187 Instruction
*User
= cast
<Instruction
>(U
.getUser());
190 if (PHINode
*UserPN
= dyn_cast
<PHINode
>(User
))
191 V
= GetValueAtEndOfBlock(UserPN
->getIncomingBlock(U
));
193 V
= GetValueInMiddleOfBlock(User
->getParent());
198 void SSAUpdater::RewriteUseAfterInsertions(Use
&U
) {
199 Instruction
*User
= cast
<Instruction
>(U
.getUser());
202 if (PHINode
*UserPN
= dyn_cast
<PHINode
>(User
))
203 V
= GetValueAtEndOfBlock(UserPN
->getIncomingBlock(U
));
205 V
= GetValueAtEndOfBlock(User
->getParent());
213 class SSAUpdaterTraits
<SSAUpdater
> {
215 using BlkT
= BasicBlock
;
216 using ValT
= Value
*;
217 using PhiT
= PHINode
;
218 using BlkSucc_iterator
= succ_iterator
;
220 static BlkSucc_iterator
BlkSucc_begin(BlkT
*BB
) { return succ_begin(BB
); }
221 static BlkSucc_iterator
BlkSucc_end(BlkT
*BB
) { return succ_end(BB
); }
229 explicit PHI_iterator(PHINode
*P
) // begin iterator
231 PHI_iterator(PHINode
*P
, bool) // end iterator
232 : PHI(P
), idx(PHI
->getNumIncomingValues()) {}
234 PHI_iterator
&operator++() { ++idx
; return *this; }
235 bool operator==(const PHI_iterator
& x
) const { return idx
== x
.idx
; }
236 bool operator!=(const PHI_iterator
& x
) const { return !operator==(x
); }
238 Value
*getIncomingValue() { return PHI
->getIncomingValue(idx
); }
239 BasicBlock
*getIncomingBlock() { return PHI
->getIncomingBlock(idx
); }
242 static PHI_iterator
PHI_begin(PhiT
*PHI
) { return PHI_iterator(PHI
); }
243 static PHI_iterator
PHI_end(PhiT
*PHI
) {
244 return PHI_iterator(PHI
, true);
247 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
248 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
249 static void FindPredecessorBlocks(BasicBlock
*BB
,
250 SmallVectorImpl
<BasicBlock
*> *Preds
) {
251 // We can get our predecessor info by walking the pred_iterator list,
252 // but it is relatively slow. If we already have PHI nodes in this
253 // block, walk one of them to get the predecessor list instead.
254 if (PHINode
*SomePhi
= dyn_cast
<PHINode
>(BB
->begin()))
255 append_range(*Preds
, SomePhi
->blocks());
257 append_range(*Preds
, predecessors(BB
));
260 /// GetUndefVal - Get an undefined value of the same type as the value
262 static Value
*GetUndefVal(BasicBlock
*BB
, SSAUpdater
*Updater
) {
263 return UndefValue::get(Updater
->ProtoType
);
266 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
267 /// Reserve space for the operands but do not fill them in yet.
268 static Value
*CreateEmptyPHI(BasicBlock
*BB
, unsigned NumPreds
,
269 SSAUpdater
*Updater
) {
270 PHINode
*PHI
= PHINode::Create(Updater
->ProtoType
, NumPreds
,
271 Updater
->ProtoName
, &BB
->front());
275 /// AddPHIOperand - Add the specified value as an operand of the PHI for
276 /// the specified predecessor block.
277 static void AddPHIOperand(PHINode
*PHI
, Value
*Val
, BasicBlock
*Pred
) {
278 PHI
->addIncoming(Val
, Pred
);
281 /// ValueIsPHI - Check if a value is a PHI.
282 static PHINode
*ValueIsPHI(Value
*Val
, SSAUpdater
*Updater
) {
283 return dyn_cast
<PHINode
>(Val
);
286 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
287 /// operands, i.e., it was just added.
288 static PHINode
*ValueIsNewPHI(Value
*Val
, SSAUpdater
*Updater
) {
289 PHINode
*PHI
= ValueIsPHI(Val
, Updater
);
290 if (PHI
&& PHI
->getNumIncomingValues() == 0)
295 /// GetPHIValue - For the specified PHI instruction, return the value
297 static Value
*GetPHIValue(PHINode
*PHI
) {
302 } // end namespace llvm
304 /// Check to see if AvailableVals has an entry for the specified BB and if so,
305 /// return it. If not, construct SSA form by first calculating the required
306 /// placement of PHIs and then inserting new PHIs where needed.
307 Value
*SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock
*BB
) {
308 AvailableValsTy
&AvailableVals
= getAvailableVals(AV
);
309 if (Value
*V
= AvailableVals
[BB
])
312 SSAUpdaterImpl
<SSAUpdater
> Impl(this, &AvailableVals
, InsertedPHIs
);
313 return Impl
.GetValue(BB
);
316 //===----------------------------------------------------------------------===//
317 // LoadAndStorePromoter Implementation
318 //===----------------------------------------------------------------------===//
320 LoadAndStorePromoter::
321 LoadAndStorePromoter(ArrayRef
<const Instruction
*> Insts
,
322 SSAUpdater
&S
, StringRef BaseName
) : SSA(S
) {
323 if (Insts
.empty()) return;
325 const Value
*SomeVal
;
326 if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(Insts
[0]))
329 SomeVal
= cast
<StoreInst
>(Insts
[0])->getOperand(0);
331 if (BaseName
.empty())
332 BaseName
= SomeVal
->getName();
333 SSA
.Initialize(SomeVal
->getType(), BaseName
);
336 void LoadAndStorePromoter::run(const SmallVectorImpl
<Instruction
*> &Insts
) {
337 // First step: bucket up uses of the alloca by the block they occur in.
338 // This is important because we have to handle multiple defs/uses in a block
339 // ourselves: SSAUpdater is purely for cross-block references.
340 DenseMap
<BasicBlock
*, TinyPtrVector
<Instruction
*>> UsesByBlock
;
342 for (Instruction
*User
: Insts
)
343 UsesByBlock
[User
->getParent()].push_back(User
);
345 // Okay, now we can iterate over all the blocks in the function with uses,
346 // processing them. Keep track of which loads are loading a live-in value.
347 // Walk the uses in the use-list order to be determinstic.
348 SmallVector
<LoadInst
*, 32> LiveInLoads
;
349 DenseMap
<Value
*, Value
*> ReplacedLoads
;
351 for (Instruction
*User
: Insts
) {
352 BasicBlock
*BB
= User
->getParent();
353 TinyPtrVector
<Instruction
*> &BlockUses
= UsesByBlock
[BB
];
355 // If this block has already been processed, ignore this repeat use.
356 if (BlockUses
.empty()) continue;
358 // Okay, this is the first use in the block. If this block just has a
359 // single user in it, we can rewrite it trivially.
360 if (BlockUses
.size() == 1) {
361 // If it is a store, it is a trivial def of the value in the block.
362 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(User
)) {
364 SSA
.AddAvailableValue(BB
, SI
->getOperand(0));
366 // Otherwise it is a load, queue it to rewrite as a live-in load.
367 LiveInLoads
.push_back(cast
<LoadInst
>(User
));
372 // Otherwise, check to see if this block is all loads.
373 bool HasStore
= false;
374 for (Instruction
*I
: BlockUses
) {
375 if (isa
<StoreInst
>(I
)) {
381 // If so, we can queue them all as live in loads. We don't have an
382 // efficient way to tell which on is first in the block and don't want to
383 // scan large blocks, so just add all loads as live ins.
385 for (Instruction
*I
: BlockUses
)
386 LiveInLoads
.push_back(cast
<LoadInst
>(I
));
391 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
392 // Since SSAUpdater is purely for cross-block values, we need to determine
393 // the order of these instructions in the block. If the first use in the
394 // block is a load, then it uses the live in value. The last store defines
395 // the live out value. We handle this by doing a linear scan of the block.
396 Value
*StoredValue
= nullptr;
397 for (Instruction
&I
: *BB
) {
398 if (LoadInst
*L
= dyn_cast
<LoadInst
>(&I
)) {
399 // If this is a load from an unrelated pointer, ignore it.
400 if (!isInstInList(L
, Insts
)) continue;
402 // If we haven't seen a store yet, this is a live in use, otherwise
403 // use the stored value.
405 replaceLoadWithValue(L
, StoredValue
);
406 L
->replaceAllUsesWith(StoredValue
);
407 ReplacedLoads
[L
] = StoredValue
;
409 LiveInLoads
.push_back(L
);
414 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(&I
)) {
415 // If this is a store to an unrelated pointer, ignore it.
416 if (!isInstInList(SI
, Insts
)) continue;
419 // Remember that this is the active value in the block.
420 StoredValue
= SI
->getOperand(0);
424 // The last stored value that happened is the live-out for the block.
425 assert(StoredValue
&& "Already checked that there is a store in block");
426 SSA
.AddAvailableValue(BB
, StoredValue
);
430 // Okay, now we rewrite all loads that use live-in values in the loop,
431 // inserting PHI nodes as necessary.
432 for (LoadInst
*ALoad
: LiveInLoads
) {
433 Value
*NewVal
= SSA
.GetValueInMiddleOfBlock(ALoad
->getParent());
434 replaceLoadWithValue(ALoad
, NewVal
);
436 // Avoid assertions in unreachable code.
437 if (NewVal
== ALoad
) NewVal
= PoisonValue::get(NewVal
->getType());
438 ALoad
->replaceAllUsesWith(NewVal
);
439 ReplacedLoads
[ALoad
] = NewVal
;
442 // Allow the client to do stuff before we start nuking things.
443 doExtraRewritesBeforeFinalDeletion();
445 // Now that everything is rewritten, delete the old instructions from the
446 // function. They should all be dead now.
447 for (Instruction
*User
: Insts
) {
448 if (!shouldDelete(User
))
451 // If this is a load that still has uses, then the load must have been added
452 // as a live value in the SSAUpdate data structure for a block (e.g. because
453 // the loaded value was stored later). In this case, we need to recursively
454 // propagate the updates until we get to the real value.
455 if (!User
->use_empty()) {
456 Value
*NewVal
= ReplacedLoads
[User
];
457 assert(NewVal
&& "not a replaced load?");
459 // Propagate down to the ultimate replacee. The intermediately loads
460 // could theoretically already have been deleted, so we don't want to
461 // dereference the Value*'s.
462 DenseMap
<Value
*, Value
*>::iterator RLI
= ReplacedLoads
.find(NewVal
);
463 while (RLI
!= ReplacedLoads
.end()) {
464 NewVal
= RLI
->second
;
465 RLI
= ReplacedLoads
.find(NewVal
);
468 replaceLoadWithValue(cast
<LoadInst
>(User
), NewVal
);
469 User
->replaceAllUsesWith(NewVal
);
472 instructionDeleted(User
);
473 User
->eraseFromParent();
478 LoadAndStorePromoter::isInstInList(Instruction
*I
,
479 const SmallVectorImpl
<Instruction
*> &Insts
)
481 return is_contained(Insts
, I
);