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() : AV(0), PrototypeValue(0), IPI(0) {}
38 SSAUpdater::~SSAUpdater() {
39 delete &getAvailableVals(AV);
40 delete &getIncomingPredInfo(IPI);
43 /// Initialize - Reset this object to get ready for a new set of SSA
44 /// updates. ProtoValue is the value used to name PHI nodes.
45 void SSAUpdater::Initialize(Value *ProtoValue) {
47 AV = new AvailableValsTy();
49 getAvailableVals(AV).clear();
52 IPI = new IncomingPredInfoTy();
54 getIncomingPredInfo(IPI).clear();
55 PrototypeValue = ProtoValue;
58 /// AddAvailableValue - Indicate that a rewritten value is available in the
59 /// specified block with the specified value.
60 void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
61 assert(PrototypeValue != 0 && "Need to initialize SSAUpdater");
62 assert(PrototypeValue->getType() == V->getType() &&
63 "All rewritten values must have the same type");
64 getAvailableVals(AV)[BB] = V;
67 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
68 /// live at the end of the specified block.
69 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
70 assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
71 Value *Res = GetValueAtEndOfBlockInternal(BB);
72 assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
76 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
77 /// is live in the middle of the specified block.
79 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
80 /// important case: if there is a definition of the rewritten value after the
81 /// 'use' in BB. Consider code like this:
87 /// br Cond, SomeBB, OutBB
89 /// In this case, there are two values (X1 and X2) added to the AvailableVals
90 /// set by the client of the rewriter, and those values are both live out of
91 /// their respective blocks. However, the use of X happens in the *middle* of
92 /// a block. Because of this, we need to insert a new PHI node in SomeBB to
93 /// merge the appropriate values, and this value isn't live out of the block.
95 Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
96 // If there is no definition of the renamed variable in this block, just use
97 // GetValueAtEndOfBlock to do our work.
98 if (!getAvailableVals(AV).count(BB))
99 return GetValueAtEndOfBlock(BB);
101 // Otherwise, we have the hard case. Get the live-in values for each
103 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
104 Value *SingularValue = 0;
106 // We can get our predecessor info by walking the pred_iterator list, but it
107 // is relatively slow. If we already have PHI nodes in this block, walk one
108 // of them to get the predecessor list instead.
109 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
110 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
111 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
112 Value *PredVal = GetValueAtEndOfBlock(PredBB);
113 PredValues.push_back(std::make_pair(PredBB, PredVal));
115 // Compute SingularValue.
117 SingularValue = PredVal;
118 else if (PredVal != SingularValue)
122 bool isFirstPred = true;
123 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
124 BasicBlock *PredBB = *PI;
125 Value *PredVal = GetValueAtEndOfBlock(PredBB);
126 PredValues.push_back(std::make_pair(PredBB, PredVal));
128 // Compute SingularValue.
130 SingularValue = PredVal;
132 } else if (PredVal != SingularValue)
137 // If there are no predecessors, just return undef.
138 if (PredValues.empty())
139 return UndefValue::get(PrototypeValue->getType());
141 // Otherwise, if all the merged values are the same, just use it.
142 if (SingularValue != 0)
143 return SingularValue;
145 // Otherwise, we do need a PHI: insert one now.
146 PHINode *InsertedPHI = PHINode::Create(PrototypeValue->getType(),
147 PrototypeValue->getName(),
149 InsertedPHI->reserveOperandSpace(PredValues.size());
151 // Fill in all the predecessors of the PHI.
152 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
153 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
155 // See if the PHI node can be merged to a single value. This can happen in
156 // loop cases when we get a PHI of itself and one other value.
157 if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
158 InsertedPHI->eraseFromParent();
161 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");
165 /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
166 /// which use their value in the corresponding predecessor.
167 void SSAUpdater::RewriteUse(Use &U) {
168 Instruction *User = cast<Instruction>(U.getUser());
169 BasicBlock *UseBB = User->getParent();
170 if (PHINode *UserPN = dyn_cast<PHINode>(User))
171 UseBB = UserPN->getIncomingBlock(U);
173 U.set(GetValueInMiddleOfBlock(UseBB));
177 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
178 /// for the specified BB and if so, return it. If not, construct SSA form by
179 /// walking predecessors inserting PHI nodes as needed until we get to a block
180 /// where the value is available.
182 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
183 AvailableValsTy &AvailableVals = getAvailableVals(AV);
185 // Query AvailableVals by doing an insertion of null.
186 std::pair<AvailableValsTy::iterator, bool> InsertRes =
187 AvailableVals.insert(std::make_pair(BB, WeakVH()));
189 // Handle the case when the insertion fails because we have already seen BB.
190 if (!InsertRes.second) {
191 // If the insertion failed, there are two cases. The first case is that the
192 // value is already available for the specified block. If we get this, just
194 if (InsertRes.first->second != 0)
195 return InsertRes.first->second;
197 // Otherwise, if the value we find is null, then this is the value is not
198 // known but it is being computed elsewhere in our recursion. This means
199 // that we have a cycle. Handle this by inserting a PHI node and returning
200 // it. When we get back to the first instance of the recursion we will fill
202 return InsertRes.first->second =
203 PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(),
207 // Okay, the value isn't in the map and we just inserted a null in the entry
208 // to indicate that we're processing the block. Since we have no idea what
209 // value is in this block, we have to recurse through our predecessors.
211 // While we're walking our predecessors, we keep track of them in a vector,
212 // then insert a PHI node in the end if we actually need one. We could use a
213 // smallvector here, but that would take a lot of stack space for every level
214 // of the recursion, just use IncomingPredInfo as an explicit stack.
215 IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
216 unsigned FirstPredInfoEntry = IncomingPredInfo.size();
218 // As we're walking the predecessors, keep track of whether they are all
219 // producing the same value. If so, this value will capture it, if not, it
220 // will get reset to null. We distinguish the no-predecessor case explicitly
222 TrackingVH<Value> SingularValue;
224 // We can get our predecessor info by walking the pred_iterator list, but it
225 // is relatively slow. If we already have PHI nodes in this block, walk one
226 // of them to get the predecessor list instead.
227 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
228 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
229 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
230 Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
231 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
233 // Compute SingularValue.
235 SingularValue = PredVal;
236 else if (PredVal != SingularValue)
240 bool isFirstPred = true;
241 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
242 BasicBlock *PredBB = *PI;
243 Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
244 IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
246 // Compute SingularValue.
248 SingularValue = PredVal;
250 } else if (PredVal != SingularValue)
255 // If there are no predecessors, then we must have found an unreachable block
256 // just return 'undef'. Since there are no predecessors, InsertRes must not
258 if (IncomingPredInfo.size() == FirstPredInfoEntry)
259 return InsertRes.first->second = UndefValue::get(PrototypeValue->getType());
261 /// Look up BB's entry in AvailableVals. 'InsertRes' may be invalidated. If
262 /// this block is involved in a loop, a no-entry PHI node will have been
263 /// inserted as InsertedVal. Otherwise, we'll still have the null we inserted
265 TrackingVH<Value> &InsertedVal = AvailableVals[BB];
267 // If all the predecessor values are the same then we don't need to insert a
268 // PHI. This is the simple and common case.
270 // If a PHI node got inserted, replace it with the singlar value and delete
273 PHINode *OldVal = cast<PHINode>(InsertedVal);
274 // Be careful about dead loops. These RAUW's also update InsertedVal.
275 if (InsertedVal != SingularValue)
276 OldVal->replaceAllUsesWith(SingularValue);
278 OldVal->replaceAllUsesWith(UndefValue::get(InsertedVal->getType()));
279 OldVal->eraseFromParent();
281 InsertedVal = SingularValue;
284 // Drop the entries we added in IncomingPredInfo to restore the stack.
285 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
286 IncomingPredInfo.end());
290 // Otherwise, we do need a PHI: insert one now if we don't already have one.
291 if (InsertedVal == 0)
292 InsertedVal = PHINode::Create(PrototypeValue->getType(),
293 PrototypeValue->getName(), &BB->front());
295 PHINode *InsertedPHI = cast<PHINode>(InsertedVal);
296 InsertedPHI->reserveOperandSpace(IncomingPredInfo.size()-FirstPredInfoEntry);
298 // Fill in all the predecessors of the PHI.
299 for (IncomingPredInfoTy::iterator I =
300 IncomingPredInfo.begin()+FirstPredInfoEntry,
301 E = IncomingPredInfo.end(); I != E; ++I)
302 InsertedPHI->addIncoming(I->second, I->first);
304 // Drop the entries we added in IncomingPredInfo to restore the stack.
305 IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
306 IncomingPredInfo.end());
308 // See if the PHI node can be merged to a single value. This can happen in
309 // loop cases when we get a PHI of itself and one other value.
310 if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
311 InsertedPHI->replaceAllUsesWith(ConstVal);
312 InsertedPHI->eraseFromParent();
313 InsertedVal = ConstVal;
315 DEBUG(errs() << " Inserted PHI: " << *InsertedPHI << "\n");