blob: ed9c0ee6c70091cc4da366205e93f5467cb740db [file] [log] [blame]
Chris Lattner93f3bcf2009-10-10 09:04:27 +00001//===- SSAUpdater.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 SSAUpdater class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/SSAUpdater.h"
15#include "llvm/Instructions.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/Support/CFG.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/ValueHandle.h"
20#include "llvm/Support/raw_ostream.h"
21using namespace llvm;
22
23typedef DenseMap<BasicBlock*, TrackingVH<Value> > AvailableValsTy;
24typedef std::vector<std::pair<BasicBlock*, TrackingVH<Value> > >
25 IncomingPredInfoTy;
26
27static AvailableValsTy &getAvailableVals(void *AV) {
28 return *static_cast<AvailableValsTy*>(AV);
29}
30
31static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
32 return *static_cast<IncomingPredInfoTy*>(IPI);
33}
34
35
Chris Lattnerf5a1fb62009-10-10 23:15:24 +000036SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
37 : AV(0), PrototypeValue(0), IPI(0), InsertedPHIs(NewPHI) {}
Chris Lattner93f3bcf2009-10-10 09:04:27 +000038
39SSAUpdater::~SSAUpdater() {
40 delete &getAvailableVals(AV);
41 delete &getIncomingPredInfo(IPI);
42}
43
44/// Initialize - Reset this object to get ready for a new set of SSA
45/// updates. ProtoValue is the value used to name PHI nodes.
46void SSAUpdater::Initialize(Value *ProtoValue) {
47 if (AV == 0)
48 AV = new AvailableValsTy();
49 else
50 getAvailableVals(AV).clear();
Duncan Sandsed903422009-10-16 15:20:13 +000051
Chris Lattner93f3bcf2009-10-10 09:04:27 +000052 if (IPI == 0)
53 IPI = new IncomingPredInfoTy();
54 else
55 getIncomingPredInfo(IPI).clear();
56 PrototypeValue = ProtoValue;
57}
58
Chris Lattner0bef5622009-10-10 23:41:48 +000059/// HasValueForBlock - Return true if the SSAUpdater already has a value for
60/// the specified block.
61bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
62 return getAvailableVals(AV).count(BB);
63}
64
Chris Lattner93f3bcf2009-10-10 09:04:27 +000065/// AddAvailableValue - Indicate that a rewritten value is available in the
66/// specified block with the specified value.
67void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
68 assert(PrototypeValue != 0 && "Need to initialize SSAUpdater");
69 assert(PrototypeValue->getType() == V->getType() &&
70 "All rewritten values must have the same type");
71 getAvailableVals(AV)[BB] = V;
72}
73
Chris Lattner1a8d4de2009-10-10 23:00:11 +000074/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
75/// live at the end of the specified block.
Chris Lattner5fb10722009-10-10 22:41:58 +000076Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +000077 assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
Chris Lattner5fb10722009-10-10 22:41:58 +000078 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000079 assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
80 return Res;
81}
82
Chris Lattner1a8d4de2009-10-10 23:00:11 +000083/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
84/// is live in the middle of the specified block.
85///
86/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
87/// important case: if there is a definition of the rewritten value after the
88/// 'use' in BB. Consider code like this:
89///
90/// X1 = ...
91/// SomeBB:
92/// use(X)
93/// X2 = ...
94/// br Cond, SomeBB, OutBB
95///
96/// In this case, there are two values (X1 and X2) added to the AvailableVals
97/// set by the client of the rewriter, and those values are both live out of
98/// their respective blocks. However, the use of X happens in the *middle* of
99/// a block. Because of this, we need to insert a new PHI node in SomeBB to
100/// merge the appropriate values, and this value isn't live out of the block.
101///
102Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
103 // If there is no definition of the renamed variable in this block, just use
104 // GetValueAtEndOfBlock to do our work.
105 if (!getAvailableVals(AV).count(BB))
106 return GetValueAtEndOfBlock(BB);
Duncan Sandsed903422009-10-16 15:20:13 +0000107
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000108 // Otherwise, we have the hard case. Get the live-in values for each
109 // predecessor.
110 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
111 Value *SingularValue = 0;
Duncan Sandsed903422009-10-16 15:20:13 +0000112
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000113 // We can get our predecessor info by walking the pred_iterator list, but it
114 // is relatively slow. If we already have PHI nodes in this block, walk one
115 // of them to get the predecessor list instead.
116 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
117 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
118 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
119 Value *PredVal = GetValueAtEndOfBlock(PredBB);
120 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000121
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000122 // Compute SingularValue.
123 if (i == 0)
124 SingularValue = PredVal;
125 else if (PredVal != SingularValue)
126 SingularValue = 0;
127 }
128 } else {
129 bool isFirstPred = true;
130 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
131 BasicBlock *PredBB = *PI;
132 Value *PredVal = GetValueAtEndOfBlock(PredBB);
133 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000134
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000135 // Compute SingularValue.
136 if (isFirstPred) {
137 SingularValue = PredVal;
138 isFirstPred = false;
139 } else if (PredVal != SingularValue)
140 SingularValue = 0;
141 }
142 }
Duncan Sandsed903422009-10-16 15:20:13 +0000143
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000144 // If there are no predecessors, just return undef.
145 if (PredValues.empty())
146 return UndefValue::get(PrototypeValue->getType());
Duncan Sandsed903422009-10-16 15:20:13 +0000147
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000148 // Otherwise, if all the merged values are the same, just use it.
149 if (SingularValue != 0)
150 return SingularValue;
Duncan Sandsed903422009-10-16 15:20:13 +0000151
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000152 // Otherwise, we do need a PHI: insert one now.
153 PHINode *InsertedPHI = PHINode::Create(PrototypeValue->getType(),
154 PrototypeValue->getName(),
155 &BB->front());
156 InsertedPHI->reserveOperandSpace(PredValues.size());
Duncan Sandsed903422009-10-16 15:20:13 +0000157
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000158 // Fill in all the predecessors of the PHI.
159 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
160 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
Duncan Sandsed903422009-10-16 15:20:13 +0000161
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000162 // See if the PHI node can be merged to a single value. This can happen in
163 // loop cases when we get a PHI of itself and one other value.
164 if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
165 InsertedPHI->eraseFromParent();
166 return ConstVal;
167 }
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000168
169 // If the client wants to know about all new instructions, tell it.
170 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sandsed903422009-10-16 15:20:13 +0000171
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000172 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
173 return InsertedPHI;
174}
175
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000176/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
177/// which use their value in the corresponding predecessor.
178void SSAUpdater::RewriteUse(Use &U) {
179 Instruction *User = cast<Instruction>(U.getUser());
180 BasicBlock *UseBB = User->getParent();
Torok Edwinf9933272009-10-20 15:42:00 +0000181 PHINode *UserPN = dyn_cast<PHINode>(User);
182 if (UserPN)
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000183 UseBB = UserPN->getIncomingBlock(U);
Duncan Sandsed903422009-10-16 15:20:13 +0000184
Torok Edwinf9933272009-10-20 15:42:00 +0000185 Value *V = GetValueInMiddleOfBlock(UseBB);
186 U.set(V);
187 if (UserPN) {
188 // Incoming value from the same BB must be consistent
189 for (unsigned i=0;i<UserPN->getNumIncomingValues();i++)
190 if (UserPN->getIncomingBlock(i) == UseBB)
191 UserPN->setIncomingValue(i, V);
192 }
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000193}
194
195
Chris Lattner5fb10722009-10-10 22:41:58 +0000196/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
197/// for the specified BB and if so, return it. If not, construct SSA form by
198/// walking predecessors inserting PHI nodes as needed until we get to a block
199/// where the value is available.
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000200///
Chris Lattner5fb10722009-10-10 22:41:58 +0000201Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000202 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Duncan Sandsed903422009-10-16 15:20:13 +0000203
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000204 // Query AvailableVals by doing an insertion of null.
205 std::pair<AvailableValsTy::iterator, bool> InsertRes =
206 AvailableVals.insert(std::make_pair(BB, WeakVH()));
Duncan Sandsed903422009-10-16 15:20:13 +0000207
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000208 // Handle the case when the insertion fails because we have already seen BB.
209 if (!InsertRes.second) {
210 // If the insertion failed, there are two cases. The first case is that the
211 // value is already available for the specified block. If we get this, just
212 // return the value.
213 if (InsertRes.first->second != 0)
214 return InsertRes.first->second;
Duncan Sandsed903422009-10-16 15:20:13 +0000215
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000216 // Otherwise, if the value we find is null, then this is the value is not
217 // known but it is being computed elsewhere in our recursion. This means
218 // that we have a cycle. Handle this by inserting a PHI node and returning
219 // it. When we get back to the first instance of the recursion we will fill
220 // in the PHI node.
221 return InsertRes.first->second =
222 PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(),
223 &BB->front());
224 }
Duncan Sandsed903422009-10-16 15:20:13 +0000225
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000226 // Okay, the value isn't in the map and we just inserted a null in the entry
227 // to indicate that we're processing the block. Since we have no idea what
228 // value is in this block, we have to recurse through our predecessors.
229 //
230 // While we're walking our predecessors, we keep track of them in a vector,
231 // then insert a PHI node in the end if we actually need one. We could use a
232 // smallvector here, but that would take a lot of stack space for every level
233 // of the recursion, just use IncomingPredInfo as an explicit stack.
234 IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
235 unsigned FirstPredInfoEntry = IncomingPredInfo.size();
Duncan Sandsed903422009-10-16 15:20:13 +0000236
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000237 // As we're walking the predecessors, keep track of whether they are all
238 // producing the same value. If so, this value will capture it, if not, it
239 // will get reset to null. We distinguish the no-predecessor case explicitly
240 // below.
241 TrackingVH<Value> SingularValue;
Duncan Sandsed903422009-10-16 15:20:13 +0000242
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000243 // We can get our predecessor info by walking the pred_iterator list, but it
244 // is relatively slow. If we already have PHI nodes in this block, walk one
245 // of them to get the predecessor list instead.
246 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
247 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
248 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
Chris Lattner5fb10722009-10-10 22:41:58 +0000249 Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000250 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000251
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000252 // Compute SingularValue.
253 if (i == 0)
254 SingularValue = PredVal;
255 else if (PredVal != SingularValue)
256 SingularValue = 0;
257 }
258 } else {
259 bool isFirstPred = true;
260 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
261 BasicBlock *PredBB = *PI;
Chris Lattner5fb10722009-10-10 22:41:58 +0000262 Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000263 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000264
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000265 // Compute SingularValue.
266 if (isFirstPred) {
267 SingularValue = PredVal;
268 isFirstPred = false;
269 } else if (PredVal != SingularValue)
270 SingularValue = 0;
271 }
272 }
Duncan Sandsed903422009-10-16 15:20:13 +0000273
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000274 // If there are no predecessors, then we must have found an unreachable block
275 // just return 'undef'. Since there are no predecessors, InsertRes must not
276 // be invalidated.
277 if (IncomingPredInfo.size() == FirstPredInfoEntry)
278 return InsertRes.first->second = UndefValue::get(PrototypeValue->getType());
Duncan Sandsed903422009-10-16 15:20:13 +0000279
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000280 /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If
281 /// this block is involved in a loop, a no-entry PHI node will have been
282 /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted
283 /// above.
284 TrackingVH<Value> &InsertedVal = AvailableVals[BB];
Duncan Sandsed903422009-10-16 15:20:13 +0000285
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000286 // If all the predecessor values are the same then we don't need to insert a
287 // PHI. This is the simple and common case.
288 if (SingularValue) {
289 // If a PHI node got inserted, replace it with the singlar value and delete
290 // it.
291 if (InsertedVal) {
292 PHINode *OldVal = cast<PHINode>(InsertedVal);
293 // Be careful about dead loops. These RAUW's also update InsertedVal.
294 if (InsertedVal != SingularValue)
295 OldVal->replaceAllUsesWith(SingularValue);
296 else
297 OldVal->replaceAllUsesWith(UndefValue::get(InsertedVal->getType()));
298 OldVal->eraseFromParent();
299 } else {
300 InsertedVal = SingularValue;
301 }
Duncan Sandsed903422009-10-16 15:20:13 +0000302
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000303 // Drop the entries we added in IncomingPredInfo to restore the stack.
304 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
305 IncomingPredInfo.end());
306 return InsertedVal;
307 }
Duncan Sandsed903422009-10-16 15:20:13 +0000308
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000309 // Otherwise, we do need a PHI: insert one now if we don't already have one.
310 if (InsertedVal == 0)
311 InsertedVal = PHINode::Create(PrototypeValue->getType(),
312 PrototypeValue->getName(), &BB->front());
Duncan Sandsed903422009-10-16 15:20:13 +0000313
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000314 PHINode *InsertedPHI = cast<PHINode>(InsertedVal);
315 InsertedPHI->reserveOperandSpace(IncomingPredInfo.size()-FirstPredInfoEntry);
Duncan Sandsed903422009-10-16 15:20:13 +0000316
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000317 // Fill in all the predecessors of the PHI.
Chris Lattnerf9920fa2009-10-10 09:09:20 +0000318 for (IncomingPredInfoTy::iterator I =
319 IncomingPredInfo.begin()+FirstPredInfoEntry,
320 E = IncomingPredInfo.end(); I != E; ++I)
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000321 InsertedPHI->addIncoming(I->second, I->first);
Duncan Sandsed903422009-10-16 15:20:13 +0000322
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000323 // Drop the entries we added in IncomingPredInfo to restore the stack.
324 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
325 IncomingPredInfo.end());
Duncan Sandsed903422009-10-16 15:20:13 +0000326
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000327 // See if the PHI node can be merged to a single value. This can happen in
328 // loop cases when we get a PHI of itself and one other value.
329 if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
330 InsertedPHI->replaceAllUsesWith(ConstVal);
331 InsertedPHI->eraseFromParent();
332 InsertedVal = ConstVal;
333 } else {
334 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
Duncan Sandsed903422009-10-16 15:20:13 +0000335
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000336 // If the client wants to know about all new instructions, tell it.
337 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000338 }
Duncan Sandsed903422009-10-16 15:20:13 +0000339
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000340 return InsertedVal;
341}