blob: b47a7ccd80ba65da50501a654e6e0a81f6034b27 [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
Bob Wilson84bd6b02010-04-17 03:08:24 +000014#define DEBUG_TYPE "ssaupdater"
Jay Foad562b84b2011-04-11 09:35:34 +000015#include "llvm/Constants.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000016#include "llvm/Instructions.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000017#include "llvm/IntrinsicInst.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000018#include "llvm/ADT/DenseMap.h"
Duncan Sandscdbd9922010-11-16 17:41:24 +000019#include "llvm/Analysis/InstructionSimplify.h"
Bob Wilson84bd6b02010-04-17 03:08:24 +000020#include "llvm/Support/AlignOf.h"
21#include "llvm/Support/Allocator.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000022#include "llvm/Support/CFG.h"
23#include "llvm/Support/Debug.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000024#include "llvm/Support/raw_ostream.h"
Devang Patel40348e82011-04-29 22:28:59 +000025#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000026#include "llvm/Transforms/Utils/Local.h"
Bob Wilson4aad88d2010-05-04 23:18:19 +000027#include "llvm/Transforms/Utils/SSAUpdater.h"
28#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Devang Patel40348e82011-04-29 22:28:59 +000029
Chris Lattner93f3bcf2009-10-10 09:04:27 +000030using namespace llvm;
31
Bob Wilson84bd6b02010-04-17 03:08:24 +000032typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
Chris Lattner93f3bcf2009-10-10 09:04:27 +000033static AvailableValsTy &getAvailableVals(void *AV) {
34 return *static_cast<AvailableValsTy*>(AV);
35}
36
Chris Lattnerf5a1fb62009-10-10 23:15:24 +000037SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000038 : AV(0), ProtoType(0), ProtoName(), InsertedPHIs(NewPHI) {}
Chris Lattner93f3bcf2009-10-10 09:04:27 +000039
40SSAUpdater::~SSAUpdater() {
41 delete &getAvailableVals(AV);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000042}
43
44/// Initialize - Reset this object to get ready for a new set of SSA
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000045/// updates with type 'Ty'. PHI nodes get a name based on 'Name'.
46void SSAUpdater::Initialize(const Type *Ty, StringRef Name) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +000047 if (AV == 0)
48 AV = new AvailableValsTy();
49 else
50 getAvailableVals(AV).clear();
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000051 ProtoType = Ty;
52 ProtoName = Name;
Chris Lattner93f3bcf2009-10-10 09:04:27 +000053}
54
Chris Lattner0bef5622009-10-10 23:41:48 +000055/// HasValueForBlock - Return true if the SSAUpdater already has a value for
56/// the specified block.
57bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
58 return getAvailableVals(AV).count(BB);
59}
60
Chris Lattner93f3bcf2009-10-10 09:04:27 +000061/// AddAvailableValue - Indicate that a rewritten value is available in the
62/// specified block with the specified value.
63void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000064 assert(ProtoType != 0 && "Need to initialize SSAUpdater");
65 assert(ProtoType == V->getType() &&
Chris Lattner93f3bcf2009-10-10 09:04:27 +000066 "All rewritten values must have the same type");
67 getAvailableVals(AV)[BB] = V;
68}
69
Bob Wilsone98585e2010-01-27 22:01:02 +000070/// IsEquivalentPHI - Check if PHI has the same incoming value as specified
71/// in ValueMapping for each predecessor block.
Bob Wilson84bd6b02010-04-17 03:08:24 +000072static bool IsEquivalentPHI(PHINode *PHI,
Bob Wilsone98585e2010-01-27 22:01:02 +000073 DenseMap<BasicBlock*, Value*> &ValueMapping) {
74 unsigned PHINumValues = PHI->getNumIncomingValues();
75 if (PHINumValues != ValueMapping.size())
76 return false;
77
78 // Scan the phi to see if it matches.
79 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
80 if (ValueMapping[PHI->getIncomingBlock(i)] !=
81 PHI->getIncomingValue(i)) {
82 return false;
83 }
84
85 return true;
86}
87
Chris Lattner1a8d4de2009-10-10 23:00:11 +000088/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
89/// live at the end of the specified block.
Chris Lattner5fb10722009-10-10 22:41:58 +000090Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattner5fb10722009-10-10 22:41:58 +000091 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000092 return Res;
93}
94
Chris Lattner1a8d4de2009-10-10 23:00:11 +000095/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
96/// is live in the middle of the specified block.
97///
98/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
99/// important case: if there is a definition of the rewritten value after the
100/// 'use' in BB. Consider code like this:
101///
102/// X1 = ...
103/// SomeBB:
104/// use(X)
105/// X2 = ...
106/// br Cond, SomeBB, OutBB
107///
108/// In this case, there are two values (X1 and X2) added to the AvailableVals
109/// set by the client of the rewriter, and those values are both live out of
110/// their respective blocks. However, the use of X happens in the *middle* of
111/// a block. Because of this, we need to insert a new PHI node in SomeBB to
112/// merge the appropriate values, and this value isn't live out of the block.
113///
114Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
115 // If there is no definition of the renamed variable in this block, just use
116 // GetValueAtEndOfBlock to do our work.
Bob Wilson84bd6b02010-04-17 03:08:24 +0000117 if (!HasValueForBlock(BB))
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000118 return GetValueAtEndOfBlock(BB);
Duncan Sandsed903422009-10-16 15:20:13 +0000119
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000120 // Otherwise, we have the hard case. Get the live-in values for each
121 // predecessor.
122 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
123 Value *SingularValue = 0;
Duncan Sandsed903422009-10-16 15:20:13 +0000124
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000125 // We can get our predecessor info by walking the pred_iterator list, but it
126 // is relatively slow. If we already have PHI nodes in this block, walk one
127 // of them to get the predecessor list instead.
128 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
129 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
130 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
131 Value *PredVal = GetValueAtEndOfBlock(PredBB);
132 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000133
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000134 // Compute SingularValue.
135 if (i == 0)
136 SingularValue = PredVal;
137 else if (PredVal != SingularValue)
138 SingularValue = 0;
139 }
140 } else {
141 bool isFirstPred = true;
142 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
143 BasicBlock *PredBB = *PI;
144 Value *PredVal = GetValueAtEndOfBlock(PredBB);
145 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000146
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000147 // Compute SingularValue.
148 if (isFirstPred) {
149 SingularValue = PredVal;
150 isFirstPred = false;
151 } else if (PredVal != SingularValue)
152 SingularValue = 0;
153 }
154 }
Duncan Sandsed903422009-10-16 15:20:13 +0000155
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000156 // If there are no predecessors, just return undef.
157 if (PredValues.empty())
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000158 return UndefValue::get(ProtoType);
Duncan Sandsed903422009-10-16 15:20:13 +0000159
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000160 // Otherwise, if all the merged values are the same, just use it.
161 if (SingularValue != 0)
162 return SingularValue;
Duncan Sandsed903422009-10-16 15:20:13 +0000163
Bob Wilson84bd6b02010-04-17 03:08:24 +0000164 // Otherwise, we do need a PHI: check to see if we already have one available
165 // in this block that produces the right value.
166 if (isa<PHINode>(BB->begin())) {
167 DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(),
168 PredValues.end());
169 PHINode *SomePHI;
170 for (BasicBlock::iterator It = BB->begin();
171 (SomePHI = dyn_cast<PHINode>(It)); ++It) {
172 if (IsEquivalentPHI(SomePHI, ValueMapping))
173 return SomePHI;
174 }
175 }
Bob Wilsone98585e2010-01-27 22:01:02 +0000176
Chris Lattner4c1e3da2009-12-21 07:16:11 +0000177 // Ok, we have no way out, insert a new one now.
Jay Foad3ecfc862011-03-30 11:28:46 +0000178 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
179 ProtoName, &BB->front());
Duncan Sandsed903422009-10-16 15:20:13 +0000180
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000181 // Fill in all the predecessors of the PHI.
182 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
183 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
Duncan Sandsed903422009-10-16 15:20:13 +0000184
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000185 // See if the PHI node can be merged to a single value. This can happen in
186 // loop cases when we get a PHI of itself and one other value.
Duncan Sandscdbd9922010-11-16 17:41:24 +0000187 if (Value *V = SimplifyInstruction(InsertedPHI)) {
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000188 InsertedPHI->eraseFromParent();
Duncan Sandscdbd9922010-11-16 17:41:24 +0000189 return V;
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000190 }
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000191
Devang Patel40348e82011-04-29 22:28:59 +0000192 // Set DebugLoc.
193 InsertedPHI->setDebugLoc(GetFirstDebugLocInBasicBlock(BB));
194
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000195 // If the client wants to know about all new instructions, tell it.
196 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sandsed903422009-10-16 15:20:13 +0000197
David Greene1af40ca2010-01-05 01:26:49 +0000198 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000199 return InsertedPHI;
200}
201
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000202/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
203/// which use their value in the corresponding predecessor.
204void SSAUpdater::RewriteUse(Use &U) {
205 Instruction *User = cast<Instruction>(U.getUser());
Bob Wilson84bd6b02010-04-17 03:08:24 +0000206
Chris Lattner88a86242009-10-20 20:27:49 +0000207 Value *V;
208 if (PHINode *UserPN = dyn_cast<PHINode>(User))
209 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
210 else
211 V = GetValueInMiddleOfBlock(User->getParent());
Duncan Sandsed903422009-10-16 15:20:13 +0000212
Torok Edwinf9933272009-10-20 15:42:00 +0000213 U.set(V);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000214}
215
Chris Lattnerffd9bee2010-08-29 04:54:06 +0000216/// RewriteUseAfterInsertions - Rewrite a use, just like RewriteUse. However,
217/// this version of the method can rewrite uses in the same block as a
218/// definition, because it assumes that all uses of a value are below any
219/// inserted values.
220void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
221 Instruction *User = cast<Instruction>(U.getUser());
222
223 Value *V;
224 if (PHINode *UserPN = dyn_cast<PHINode>(User))
225 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
226 else
227 V = GetValueAtEndOfBlock(User->getParent());
228
229 U.set(V);
230}
231
Bob Wilson4aad88d2010-05-04 23:18:19 +0000232/// PHIiter - Iterator for PHI operands. This is used for the PHI_iterator
233/// in the SSAUpdaterImpl template.
234namespace {
235 class PHIiter {
236 private:
237 PHINode *PHI;
238 unsigned idx;
239
240 public:
241 explicit PHIiter(PHINode *P) // begin iterator
242 : PHI(P), idx(0) {}
243 PHIiter(PHINode *P, bool) // end iterator
244 : PHI(P), idx(PHI->getNumIncomingValues()) {}
245
246 PHIiter &operator++() { ++idx; return *this; }
247 bool operator==(const PHIiter& x) const { return idx == x.idx; }
248 bool operator!=(const PHIiter& x) const { return !operator==(x); }
249 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
250 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
251 };
252}
253
254/// SSAUpdaterTraits<SSAUpdater> - Traits for the SSAUpdaterImpl template,
255/// specialized for SSAUpdater.
256namespace llvm {
257template<>
258class SSAUpdaterTraits<SSAUpdater> {
259public:
260 typedef BasicBlock BlkT;
261 typedef Value *ValT;
262 typedef PHINode PhiT;
263
264 typedef succ_iterator BlkSucc_iterator;
265 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
266 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
267
268 typedef PHIiter PHI_iterator;
269 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
270 static inline PHI_iterator PHI_end(PhiT *PHI) {
271 return PHI_iterator(PHI, true);
272 }
273
274 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
275 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
276 static void FindPredecessorBlocks(BasicBlock *BB,
277 SmallVectorImpl<BasicBlock*> *Preds) {
278 // We can get our predecessor info by walking the pred_iterator list,
279 // but it is relatively slow. If we already have PHI nodes in this
280 // block, walk one of them to get the predecessor list instead.
281 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
282 for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI)
283 Preds->push_back(SomePhi->getIncomingBlock(PI));
284 } else {
285 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
286 Preds->push_back(*PI);
287 }
288 }
289
290 /// GetUndefVal - Get an undefined value of the same type as the value
291 /// being handled.
292 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000293 return UndefValue::get(Updater->ProtoType);
Bob Wilson4aad88d2010-05-04 23:18:19 +0000294 }
295
296 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
297 /// Reserve space for the operands but do not fill them in yet.
298 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
299 SSAUpdater *Updater) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000300 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
301 Updater->ProtoName, &BB->front());
Bob Wilson4aad88d2010-05-04 23:18:19 +0000302 return PHI;
303 }
304
305 /// AddPHIOperand - Add the specified value as an operand of the PHI for
306 /// the specified predecessor block.
307 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
308 PHI->addIncoming(Val, Pred);
309 }
310
311 /// InstrIsPHI - Check if an instruction is a PHI.
312 ///
313 static PHINode *InstrIsPHI(Instruction *I) {
314 return dyn_cast<PHINode>(I);
315 }
316
317 /// ValueIsPHI - Check if a value is a PHI.
318 ///
319 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
320 return dyn_cast<PHINode>(Val);
321 }
322
323 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
324 /// operands, i.e., it was just added.
325 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
326 PHINode *PHI = ValueIsPHI(Val, Updater);
327 if (PHI && PHI->getNumIncomingValues() == 0)
328 return PHI;
329 return 0;
330 }
331
332 /// GetPHIValue - For the specified PHI instruction, return the value
333 /// that it defines.
334 static Value *GetPHIValue(PHINode *PHI) {
335 return PHI;
336 }
337};
338
339} // End llvm namespace
340
Chris Lattner5fb10722009-10-10 22:41:58 +0000341/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
342/// for the specified BB and if so, return it. If not, construct SSA form by
Bob Wilson84bd6b02010-04-17 03:08:24 +0000343/// first calculating the required placement of PHIs and then inserting new
344/// PHIs where needed.
Chris Lattner5fb10722009-10-10 22:41:58 +0000345Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000346 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilson84bd6b02010-04-17 03:08:24 +0000347 if (Value *V = AvailableVals[BB])
348 return V;
Duncan Sandsed903422009-10-16 15:20:13 +0000349
Bob Wilson4aad88d2010-05-04 23:18:19 +0000350 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
351 return Impl.GetValue(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000352}
Chris Lattnera2d845a2011-01-14 19:36:13 +0000353
354//===----------------------------------------------------------------------===//
355// LoadAndStorePromoter Implementation
356//===----------------------------------------------------------------------===//
357
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000358LoadAndStorePromoter::
359LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts,
Devang Patel231a5ab2011-07-06 21:09:55 +0000360 SSAUpdater &S, StringRef BaseName) : SSA(S) {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000361 if (Insts.empty()) return;
362
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000363 Value *SomeVal;
Chris Lattnera2d845a2011-01-14 19:36:13 +0000364 if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000365 SomeVal = LI;
Chris Lattnera2d845a2011-01-14 19:36:13 +0000366 else
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000367 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
368
369 if (BaseName.empty())
370 BaseName = SomeVal->getName();
371 SSA.Initialize(SomeVal->getType(), BaseName);
372}
373
374
375void LoadAndStorePromoter::
376run(const SmallVectorImpl<Instruction*> &Insts) const {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000377
378 // First step: bucket up uses of the alloca by the block they occur in.
379 // This is important because we have to handle multiple defs/uses in a block
380 // ourselves: SSAUpdater is purely for cross-block references.
381 // FIXME: Want a TinyVector<Instruction*> since there is often 0/1 element.
382 DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
383
384 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
385 Instruction *User = Insts[i];
386 UsesByBlock[User->getParent()].push_back(User);
387 }
388
389 // Okay, now we can iterate over all the blocks in the function with uses,
390 // processing them. Keep track of which loads are loading a live-in value.
391 // Walk the uses in the use-list order to be determinstic.
392 SmallVector<LoadInst*, 32> LiveInLoads;
393 DenseMap<Value*, Value*> ReplacedLoads;
394
395 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
396 Instruction *User = Insts[i];
397 BasicBlock *BB = User->getParent();
398 std::vector<Instruction*> &BlockUses = UsesByBlock[BB];
399
400 // If this block has already been processed, ignore this repeat use.
401 if (BlockUses.empty()) continue;
402
403 // Okay, this is the first use in the block. If this block just has a
404 // single user in it, we can rewrite it trivially.
405 if (BlockUses.size() == 1) {
406 // If it is a store, it is a trivial def of the value in the block.
Cameron Zwarichc8279392011-05-24 03:10:43 +0000407 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Devang Patel231a5ab2011-07-06 21:09:55 +0000408 updateDebugInfo(SI);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000409 SSA.AddAvailableValue(BB, SI->getOperand(0));
Cameron Zwarichc8279392011-05-24 03:10:43 +0000410 } else
Chris Lattnera2d845a2011-01-14 19:36:13 +0000411 // Otherwise it is a load, queue it to rewrite as a live-in load.
412 LiveInLoads.push_back(cast<LoadInst>(User));
413 BlockUses.clear();
414 continue;
415 }
416
417 // Otherwise, check to see if this block is all loads.
418 bool HasStore = false;
419 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
420 if (isa<StoreInst>(BlockUses[i])) {
421 HasStore = true;
422 break;
423 }
424 }
425
426 // If so, we can queue them all as live in loads. We don't have an
427 // efficient way to tell which on is first in the block and don't want to
428 // scan large blocks, so just add all loads as live ins.
429 if (!HasStore) {
430 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
431 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
432 BlockUses.clear();
433 continue;
434 }
435
436 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
437 // Since SSAUpdater is purely for cross-block values, we need to determine
438 // the order of these instructions in the block. If the first use in the
439 // block is a load, then it uses the live in value. The last store defines
440 // the live out value. We handle this by doing a linear scan of the block.
441 Value *StoredValue = 0;
442 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
443 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
444 // If this is a load from an unrelated pointer, ignore it.
445 if (!isInstInList(L, Insts)) continue;
446
447 // If we haven't seen a store yet, this is a live in use, otherwise
448 // use the stored value.
449 if (StoredValue) {
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000450 replaceLoadWithValue(L, StoredValue);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000451 L->replaceAllUsesWith(StoredValue);
452 ReplacedLoads[L] = StoredValue;
453 } else {
454 LiveInLoads.push_back(L);
455 }
456 continue;
457 }
458
Cameron Zwarichc8279392011-05-24 03:10:43 +0000459 if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000460 // If this is a store to an unrelated pointer, ignore it.
Cameron Zwarichc8279392011-05-24 03:10:43 +0000461 if (!isInstInList(SI, Insts)) continue;
Devang Patel231a5ab2011-07-06 21:09:55 +0000462 updateDebugInfo(SI);
Cameron Zwarichc8279392011-05-24 03:10:43 +0000463
Chris Lattnera2d845a2011-01-14 19:36:13 +0000464 // Remember that this is the active value in the block.
Cameron Zwarichc8279392011-05-24 03:10:43 +0000465 StoredValue = SI->getOperand(0);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000466 }
467 }
468
469 // The last stored value that happened is the live-out for the block.
470 assert(StoredValue && "Already checked that there is a store in block");
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000471 SSA.AddAvailableValue(BB, StoredValue);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000472 BlockUses.clear();
473 }
474
475 // Okay, now we rewrite all loads that use live-in values in the loop,
476 // inserting PHI nodes as necessary.
477 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
478 LoadInst *ALoad = LiveInLoads[i];
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000479 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
480 replaceLoadWithValue(ALoad, NewVal);
Chris Lattner867be592011-01-24 03:29:07 +0000481
482 // Avoid assertions in unreachable code.
483 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
Chris Lattnera2d845a2011-01-14 19:36:13 +0000484 ALoad->replaceAllUsesWith(NewVal);
485 ReplacedLoads[ALoad] = NewVal;
486 }
487
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000488 // Allow the client to do stuff before we start nuking things.
489 doExtraRewritesBeforeFinalDeletion();
490
Chris Lattnera2d845a2011-01-14 19:36:13 +0000491 // Now that everything is rewritten, delete the old instructions from the
492 // function. They should all be dead now.
493 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
494 Instruction *User = Insts[i];
495
496 // If this is a load that still has uses, then the load must have been added
497 // as a live value in the SSAUpdate data structure for a block (e.g. because
498 // the loaded value was stored later). In this case, we need to recursively
499 // propagate the updates until we get to the real value.
500 if (!User->use_empty()) {
501 Value *NewVal = ReplacedLoads[User];
502 assert(NewVal && "not a replaced load?");
503
504 // Propagate down to the ultimate replacee. The intermediately loads
505 // could theoretically already have been deleted, so we don't want to
506 // dereference the Value*'s.
507 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
508 while (RLI != ReplacedLoads.end()) {
509 NewVal = RLI->second;
510 RLI = ReplacedLoads.find(NewVal);
511 }
512
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000513 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000514 User->replaceAllUsesWith(NewVal);
515 }
516
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000517 instructionDeleted(User);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000518 User->eraseFromParent();
519 }
520}