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