1 //===- SSAUpdaterBulk.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 SSAUpdaterBulk class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
15 #include "llvm/Analysis/IteratedDominanceFrontier.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Use.h"
21 #include "llvm/IR/Value.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "ssaupdaterbulk"
26 
27 /// Helper function for finding a block which should have a value for the given
28 /// user. For PHI-nodes this block is the corresponding predecessor, for other
29 /// instructions it's their parent block.
30 static BasicBlock *getUserBB(Use *U) {
31   auto *User = cast<Instruction>(U->getUser());
32 
33   if (auto *UserPN = dyn_cast<PHINode>(User))
34     return UserPN->getIncomingBlock(*U);
35   else
36     return User->getParent();
37 }
38 
39 /// Add a new variable to the SSA rewriter. This needs to be called before
40 /// AddAvailableValue or AddUse calls.
41 unsigned SSAUpdaterBulk::AddVariable(StringRef Name, Type *Ty) {
42   unsigned Var = Rewrites.size();
43   DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": initialized with Ty = " << *Ty
44                << ", Name = " << Name << "\n");
45   RewriteInfo RI(Name, Ty);
46   Rewrites.push_back(RI);
47   return Var;
48 }
49 
50 /// Indicate that a rewritten value is available in the specified block with the
51 /// specified value.
52 void SSAUpdaterBulk::AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V) {
53   assert(Var < Rewrites.size() && "Variable not found!");
54   DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": added new available value"
55                << *V << " in " << BB->getName() << "\n");
56   Rewrites[Var].Defines[BB] = V;
57 }
58 
59 /// Record a use of the symbolic value. This use will be updated with a
60 /// rewritten value when RewriteAllUses is called.
61 void SSAUpdaterBulk::AddUse(unsigned Var, Use *U) {
62   assert(Var < Rewrites.size() && "Variable not found!");
63   DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": added a use" << *U->get()
64                << " in " << getUserBB(U)->getName() << "\n");
65   Rewrites[Var].Uses.push_back(U);
66 }
67 
68 /// Return true if the SSAUpdater already has a value for the specified variable
69 /// in the specified block.
70 bool SSAUpdaterBulk::HasValueForBlock(unsigned Var, BasicBlock *BB) {
71   return (Var < Rewrites.size()) ? Rewrites[Var].Defines.count(BB) : false;
72 }
73 
74 // Compute value at the given block BB. We either should already know it, or we
75 // should be able to recursively reach it going up dominator tree.
76 Value *SSAUpdaterBulk::computeValueAt(BasicBlock *BB, RewriteInfo &R,
77                                       DominatorTree *DT) {
78   if (!R.Defines.count(BB)) {
79     if (DT->isReachableFromEntry(BB) && PredCache.get(BB).size()) {
80       BasicBlock *IDom = DT->getNode(BB)->getIDom()->getBlock();
81       Value *V = computeValueAt(IDom, R, DT);
82       R.Defines[BB] = V;
83     } else
84       R.Defines[BB] = UndefValue::get(R.Ty);
85   }
86   return R.Defines[BB];
87 }
88 
89 /// Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
90 /// This is basically a subgraph limited by DefBlocks and UsingBlocks.
91 static void
92 ComputeLiveInBlocks(const SmallPtrSetImpl<BasicBlock *> &UsingBlocks,
93                     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
94                     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks,
95                     PredIteratorCache &PredCache) {
96   // To determine liveness, we must iterate through the predecessors of blocks
97   // where the def is live.  Blocks are added to the worklist if we need to
98   // check their predecessors.  Start with all the using blocks.
99   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(UsingBlocks.begin(),
100                                                     UsingBlocks.end());
101 
102   // Now that we have a set of blocks where the phi is live-in, recursively add
103   // their predecessors until we find the full region the value is live.
104   while (!LiveInBlockWorklist.empty()) {
105     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
106 
107     // The block really is live in here, insert it into the set.  If already in
108     // the set, then it has already been processed.
109     if (!LiveInBlocks.insert(BB).second)
110       continue;
111 
112     // Since the value is live into BB, it is either defined in a predecessor or
113     // live into it to.  Add the preds to the worklist unless they are a
114     // defining block.
115     for (BasicBlock *P : PredCache.get(BB)) {
116       // The value is not live into a predecessor if it defines the value.
117       if (DefBlocks.count(P))
118         continue;
119 
120       // Otherwise it is, add to the worklist.
121       LiveInBlockWorklist.push_back(P);
122     }
123   }
124 }
125 
126 /// Perform all the necessary updates, including new PHI-nodes insertion and the
127 /// requested uses update.
128 void SSAUpdaterBulk::RewriteAllUses(DominatorTree *DT,
129                                     SmallVectorImpl<PHINode *> *InsertedPHIs) {
130   for (auto &R : Rewrites) {
131     // Compute locations for new phi-nodes.
132     // For that we need to initialize DefBlocks from definitions in R.Defines,
133     // UsingBlocks from uses in R.Uses, then compute LiveInBlocks, and then use
134     // this set for computing iterated dominance frontier (IDF).
135     // The IDF blocks are the blocks where we need to insert new phi-nodes.
136     ForwardIDFCalculator IDF(*DT);
137     DEBUG(dbgs() << "SSAUpdater: rewriting " << R.Uses.size() << " use(s)\n");
138 
139     SmallPtrSet<BasicBlock *, 2> DefBlocks;
140     for (auto &Def : R.Defines)
141       DefBlocks.insert(Def.first);
142     IDF.setDefiningBlocks(DefBlocks);
143 
144     SmallPtrSet<BasicBlock *, 2> UsingBlocks;
145     for (Use *U : R.Uses)
146       UsingBlocks.insert(getUserBB(U));
147 
148     SmallVector<BasicBlock *, 32> IDFBlocks;
149     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
150     ComputeLiveInBlocks(UsingBlocks, DefBlocks, LiveInBlocks, PredCache);
151     IDF.resetLiveInBlocks();
152     IDF.setLiveInBlocks(LiveInBlocks);
153     IDF.calculate(IDFBlocks);
154 
155     // We've computed IDF, now insert new phi-nodes there.
156     SmallVector<PHINode *, 4> InsertedPHIsForVar;
157     for (auto *FrontierBB : IDFBlocks) {
158       IRBuilder<> B(FrontierBB, FrontierBB->begin());
159       PHINode *PN = B.CreatePHI(R.Ty, 0, R.Name);
160       R.Defines[FrontierBB] = PN;
161       InsertedPHIsForVar.push_back(PN);
162       if (InsertedPHIs)
163         InsertedPHIs->push_back(PN);
164     }
165 
166     // Fill in arguments of the inserted PHIs.
167     for (auto *PN : InsertedPHIsForVar) {
168       BasicBlock *PBB = PN->getParent();
169       for (BasicBlock *Pred : PredCache.get(PBB))
170         PN->addIncoming(computeValueAt(Pred, R, DT), Pred);
171     }
172 
173     // Rewrite actual uses with the inserted definitions.
174     SmallPtrSet<Use *, 4> ProcessedUses;
175     for (Use *U : R.Uses) {
176       if (!ProcessedUses.insert(U).second)
177         continue;
178       Value *V = computeValueAt(getUserBB(U), R, DT);
179       Value *OldVal = U->get();
180       assert(OldVal && "Invalid use!");
181       // Notify that users of the existing value that it is being replaced.
182       if (OldVal != V && OldVal->hasValueHandle())
183         ValueHandleBase::ValueIsRAUWd(OldVal, V);
184       DEBUG(dbgs() << "SSAUpdater: replacing " << *OldVal << " with " << *V
185                    << "\n");
186       U->set(V);
187     }
188   }
189 }
190