1 //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SSAUpdater class.
12 //===----------------------------------------------------------------------===//
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"
23 typedef DenseMap<BasicBlock*, TrackingVH<Value> > AvailableValsTy;
24 typedef std::vector<std::pair<BasicBlock*, TrackingVH<Value> > >
27 static AvailableValsTy &getAvailableVals(void *AV) {
28 return *static_cast<AvailableValsTy*>(AV);
31 static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
32 return *static_cast<IncomingPredInfoTy*>(IPI);
36 SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
37 : AV(0), PrototypeValue(0), IPI(0), InsertedPHIs(NewPHI) {}
39 SSAUpdater::~SSAUpdater() {
40 delete &getAvailableVals(AV);
41 delete &getIncomingPredInfo(IPI);
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.
46 void SSAUpdater::Initialize(Value *ProtoValue) {
48 AV = new AvailableValsTy();
50 getAvailableVals(AV).clear();
53 IPI = new IncomingPredInfoTy();
55 getIncomingPredInfo(IPI).clear();
56 PrototypeValue = ProtoValue;
59 /// HasValueForBlock - Return true if the SSAUpdater already has a value for
60 /// the specified block.
61 bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
62 return getAvailableVals(AV).count(BB);
65 /// AddAvailableValue - Indicate that a rewritten value is available in the
66 /// specified block with the specified value.
67 void 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;
74 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
75 /// live at the end of the specified block.
76 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
77 assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
78 Value *Res = GetValueAtEndOfBlockInternal(BB);
79 assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
83 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
84 /// is live in the middle of the specified block.
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:
94 /// br Cond, SomeBB, OutBB
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.
102 Value *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);
108 // Otherwise, we have the hard case. Get the live-in values for each
110 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
111 Value *SingularValue = 0;
113 // 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));
122 // Compute SingularValue.
124 SingularValue = PredVal;
125 else if (PredVal != SingularValue)
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));
135 // Compute SingularValue.
137 SingularValue = PredVal;
139 } else if (PredVal != SingularValue)
144 // If there are no predecessors, just return undef.
145 if (PredValues.empty())
146 return UndefValue::get(PrototypeValue->getType());
148 // Otherwise, if all the merged values are the same, just use it.
149 if (SingularValue != 0)
150 return SingularValue;
152 // Otherwise, we do need a PHI: check to see if we already have one available
153 // in this block that produces the right value.
154 if (isa<PHINode>(BB->begin())) {
155 DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(),
158 for (BasicBlock::iterator It = BB->begin();
159 (SomePHI = dyn_cast<PHINode>(It)); ++It) {
160 // Scan this phi to see if it is what we need.
162 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i)
163 if (ValueMapping[SomePHI->getIncomingBlock(i)] !=
164 SomePHI->getIncomingValue(i)) {
174 // Ok, we have no way out, insert a new one now.
175 PHINode *InsertedPHI = PHINode::Create(PrototypeValue->getType(),
176 PrototypeValue->getName(),
178 InsertedPHI->reserveOperandSpace(PredValues.size());
180 // Fill in all the predecessors of the PHI.
181 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
182 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
184 // See if the PHI node can be merged to a single value. This can happen in
185 // loop cases when we get a PHI of itself and one other value.
186 if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
187 InsertedPHI->eraseFromParent();
191 // If the client wants to know about all new instructions, tell it.
192 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
194 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
198 /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
199 /// which use their value in the corresponding predecessor.
200 void SSAUpdater::RewriteUse(Use &U) {
201 Instruction *User = cast<Instruction>(U.getUser());
204 if (PHINode *UserPN = dyn_cast<PHINode>(User))
205 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
207 V = GetValueInMiddleOfBlock(User->getParent());
213 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
214 /// for the specified BB and if so, return it. If not, construct SSA form by
215 /// walking predecessors inserting PHI nodes as needed until we get to a block
216 /// where the value is available.
218 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
219 AvailableValsTy &AvailableVals = getAvailableVals(AV);
221 // Query AvailableVals by doing an insertion of null.
222 std::pair<AvailableValsTy::iterator, bool> InsertRes =
223 AvailableVals.insert(std::make_pair(BB, TrackingVH<Value>()));
225 // Handle the case when the insertion fails because we have already seen BB.
226 if (!InsertRes.second) {
227 // If the insertion failed, there are two cases. The first case is that the
228 // value is already available for the specified block. If we get this, just
230 if (InsertRes.first->second != 0)
231 return InsertRes.first->second;
233 // Otherwise, if the value we find is null, then this is the value is not
234 // known but it is being computed elsewhere in our recursion. This means
235 // that we have a cycle. Handle this by inserting a PHI node and returning
236 // it. When we get back to the first instance of the recursion we will fill
238 return InsertRes.first->second =
239 PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(),
243 // Okay, the value isn't in the map and we just inserted a null in the entry
244 // to indicate that we're processing the block. Since we have no idea what
245 // value is in this block, we have to recurse through our predecessors.
247 // While we're walking our predecessors, we keep track of them in a vector,
248 // then insert a PHI node in the end if we actually need one. We could use a
249 // smallvector here, but that would take a lot of stack space for every level
250 // of the recursion, just use IncomingPredInfo as an explicit stack.
251 IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
252 unsigned FirstPredInfoEntry = IncomingPredInfo.size();
254 // As we're walking the predecessors, keep track of whether they are all
255 // producing the same value. If so, this value will capture it, if not, it
256 // will get reset to null. We distinguish the no-predecessor case explicitly
258 TrackingVH<Value> SingularValue;
260 // We can get our predecessor info by walking the pred_iterator list, but it
261 // is relatively slow. If we already have PHI nodes in this block, walk one
262 // of them to get the predecessor list instead.
263 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
264 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
265 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
266 Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
267 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
269 // Compute SingularValue.
271 SingularValue = PredVal;
272 else if (PredVal != SingularValue)
276 bool isFirstPred = true;
277 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
278 BasicBlock *PredBB = *PI;
279 Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
280 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
282 // Compute SingularValue.
284 SingularValue = PredVal;
286 } else if (PredVal != SingularValue)
291 // If there are no predecessors, then we must have found an unreachable block
292 // just return 'undef'. Since there are no predecessors, InsertRes must not
294 if (IncomingPredInfo.size() == FirstPredInfoEntry)
295 return InsertRes.first->second = UndefValue::get(PrototypeValue->getType());
297 /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If
298 /// this block is involved in a loop, a no-entry PHI node will have been
299 /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted
301 TrackingVH<Value> &InsertedVal = AvailableVals[BB];
303 // If all the predecessor values are the same then we don't need to insert a
304 // PHI. This is the simple and common case.
306 // If a PHI node got inserted, replace it with the singlar value and delete
309 PHINode *OldVal = cast<PHINode>(InsertedVal);
310 // Be careful about dead loops. These RAUW's also update InsertedVal.
311 if (InsertedVal != SingularValue)
312 OldVal->replaceAllUsesWith(SingularValue);
314 OldVal->replaceAllUsesWith(UndefValue::get(InsertedVal->getType()));
315 OldVal->eraseFromParent();
317 InsertedVal = SingularValue;
320 // Either path through the 'if' should have set insertedVal -> SingularVal.
321 assert((InsertedVal == SingularValue || isa<UndefValue>(InsertedVal)) &&
322 "RAUW didn't change InsertedVal to be SingularVal");
324 // Drop the entries we added in IncomingPredInfo to restore the stack.
325 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
326 IncomingPredInfo.end());
327 return SingularValue;
330 // Otherwise, we do need a PHI: insert one now if we don't already have one.
331 if (InsertedVal == 0)
332 InsertedVal = PHINode::Create(PrototypeValue->getType(),
333 PrototypeValue->getName(), &BB->front());
335 PHINode *InsertedPHI = cast<PHINode>(InsertedVal);
336 InsertedPHI->reserveOperandSpace(IncomingPredInfo.size()-FirstPredInfoEntry);
338 // Fill in all the predecessors of the PHI.
339 for (IncomingPredInfoTy::iterator I =
340 IncomingPredInfo.begin()+FirstPredInfoEntry,
341 E = IncomingPredInfo.end(); I != E; ++I)
342 InsertedPHI->addIncoming(I->second, I->first);
344 // Drop the entries we added in IncomingPredInfo to restore the stack.
345 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
346 IncomingPredInfo.end());
348 // See if the PHI node can be merged to a single value. This can happen in
349 // loop cases when we get a PHI of itself and one other value.
350 if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
351 InsertedPHI->replaceAllUsesWith(ConstVal);
352 InsertedPHI->eraseFromParent();
353 InsertedVal = ConstVal;
355 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
357 // If the client wants to know about all new instructions, tell it.
358 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);