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