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