1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file promote memory references to be register references. It promotes
11 // alloca instructions which only have loads and stores as uses. An alloca is
12 // transformed by using dominator frontiers to place PHI nodes, then traversing
13 // the function in depth-first order to rewrite loads and stores as appropriate.
14 // This is just the standard SSA construction algorithm to construct "pruned"
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Compiler.h"
35 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
36 /// This is true if there are only loads and stores to the alloca.
38 bool llvm::isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
39 // FIXME: If the memory unit is of pointer or integer type, we can permit
40 // assignments to subsections of the memory unit.
42 // Only allow direct loads and stores...
43 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
44 UI != UE; ++UI) // Loop over all of the uses of the alloca
45 if (isa<LoadInst>(*UI)) {
47 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
48 if (SI->getOperand(0) == AI)
49 return false; // Don't allow a store OF the AI, only INTO the AI.
51 return false; // Not a load or store.
58 struct VISIBILITY_HIDDEN PromoteMem2Reg {
59 /// Allocas - The alloca instructions being promoted.
61 std::vector<AllocaInst*> Allocas;
62 SmallVector<AllocaInst*, 16> &RetryList;
64 DominanceFrontier &DF;
67 /// AST - An AliasSetTracker object to update. If null, don't update it.
71 /// AllocaLookup - Reverse mapping of Allocas.
73 std::map<AllocaInst*, unsigned> AllocaLookup;
75 /// NewPhiNodes - The PhiNodes we're adding.
77 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
79 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
80 /// each alloca that is of pointer type, we keep track of what to copyValue
81 /// to the inserted PHI nodes here.
83 std::vector<Value*> PointerAllocaValues;
85 /// Visited - The set of basic blocks the renamer has already visited.
87 SmallPtrSet<BasicBlock*, 16> Visited;
89 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
90 /// non-determinstic behavior.
91 DenseMap<BasicBlock*, unsigned> BBNumbers;
94 PromoteMem2Reg(const std::vector<AllocaInst*> &A,
95 SmallVector<AllocaInst*, 16> &Retry, DominatorTree &dt,
96 DominanceFrontier &df, const TargetData &td,
98 : Allocas(A), RetryList(Retry), DT(dt), DF(df), TD(td), AST(ast) {}
102 /// properlyDominates - Return true if I1 properly dominates I2.
104 bool properlyDominates(Instruction *I1, Instruction *I2) const {
105 if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
106 I1 = II->getNormalDest()->begin();
107 return DT[I1->getParent()]->properlyDominates(DT[I2->getParent()]);
110 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
112 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
113 return DT[BB1]->dominates(DT[BB2]);
117 void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
118 SmallPtrSet<PHINode*, 16> &DeadPHINodes);
119 bool PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
120 void PromoteLocallyUsedAllocas(BasicBlock *BB,
121 const std::vector<AllocaInst*> &AIs);
123 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
124 std::vector<Value*> &IncVals);
125 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
126 SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
128 } // end of anonymous namespace
130 void PromoteMem2Reg::run() {
131 Function &F = *DF.getRoot()->getParent();
133 // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
134 // only used in a single basic block. These instructions can be efficiently
135 // promoted by performing a single linear scan over that one block. Since
136 // individual basic blocks are sometimes large, we group together all allocas
137 // that are live in a single basic block by the basic block they are live in.
138 std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
140 if (AST) PointerAllocaValues.resize(Allocas.size());
142 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
143 AllocaInst *AI = Allocas[AllocaNum];
145 assert(isAllocaPromotable(AI, TD) &&
146 "Cannot promote non-promotable alloca!");
147 assert(AI->getParent()->getParent() == &F &&
148 "All allocas should be in the same function, which is same as DF!");
150 if (AI->use_empty()) {
151 // If there are no uses of the alloca, just delete it now.
152 if (AST) AST->deleteValue(AI);
153 AI->eraseFromParent();
155 // Remove the alloca from the Allocas list, since it has been processed
156 Allocas[AllocaNum] = Allocas.back();
162 // Calculate the set of read and write-locations for each alloca. This is
163 // analogous to finding the 'uses' and 'definitions' of each variable.
164 std::vector<BasicBlock*> DefiningBlocks;
165 std::vector<BasicBlock*> UsingBlocks;
167 StoreInst *OnlyStore = 0;
168 BasicBlock *OnlyBlock = 0;
169 bool OnlyUsedInOneBlock = true;
171 // As we scan the uses of the alloca instruction, keep track of stores, and
172 // decide whether all of the loads and stores to the alloca are within the
174 Value *AllocaPointerVal = 0;
175 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
176 Instruction *User = cast<Instruction>(*U);
177 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
178 // Remember the basic blocks which define new values for the alloca
179 DefiningBlocks.push_back(SI->getParent());
180 AllocaPointerVal = SI->getOperand(0);
183 LoadInst *LI = cast<LoadInst>(User);
184 // Otherwise it must be a load instruction, keep track of variable reads
185 UsingBlocks.push_back(LI->getParent());
186 AllocaPointerVal = LI;
189 if (OnlyUsedInOneBlock) {
191 OnlyBlock = User->getParent();
192 else if (OnlyBlock != User->getParent())
193 OnlyUsedInOneBlock = false;
197 // If the alloca is only read and written in one basic block, just perform a
198 // linear sweep over the block to eliminate it.
199 if (OnlyUsedInOneBlock) {
200 LocallyUsedAllocas[OnlyBlock].push_back(AI);
202 // Remove the alloca from the Allocas list, since it will be processed.
203 Allocas[AllocaNum] = Allocas.back();
209 // If there is only a single store to this value, replace any loads of
210 // it that are directly dominated by the definition with the value stored.
211 if (DefiningBlocks.size() == 1) {
212 // Be aware of loads before the store.
213 std::set<BasicBlock*> ProcessedBlocks;
214 for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
215 // If the store dominates the block and if we haven't processed it yet,
217 if (dominates(OnlyStore->getParent(), UsingBlocks[i]))
218 if (ProcessedBlocks.insert(UsingBlocks[i]).second) {
219 BasicBlock *UseBlock = UsingBlocks[i];
221 // If the use and store are in the same block, do a quick scan to
222 // verify that there are no uses before the store.
223 if (UseBlock == OnlyStore->getParent()) {
224 BasicBlock::iterator I = UseBlock->begin();
225 for (; &*I != OnlyStore; ++I) { // scan block for store.
226 if (isa<LoadInst>(I) && I->getOperand(0) == AI)
229 if (&*I != OnlyStore) break; // Do not handle this case.
232 // Otherwise, if this is a different block or if all uses happen
233 // after the store, do a simple linear scan to replace loads with
235 for (BasicBlock::iterator I = UseBlock->begin(),E = UseBlock->end();
237 if (LoadInst *LI = dyn_cast<LoadInst>(I++)) {
238 if (LI->getOperand(0) == AI) {
239 LI->replaceAllUsesWith(OnlyStore->getOperand(0));
240 if (AST && isa<PointerType>(LI->getType()))
241 AST->deleteValue(LI);
242 LI->eraseFromParent();
247 // Finally, remove this block from the UsingBlock set.
248 UsingBlocks[i] = UsingBlocks.back();
252 // Finally, after the scan, check to see if the store is all that is left.
253 if (UsingBlocks.empty()) {
254 // The alloca has been processed, move on.
255 Allocas[AllocaNum] = Allocas.back();
264 PointerAllocaValues[AllocaNum] = AllocaPointerVal;
266 // If we haven't computed a numbering for the BB's in the function, do so
268 if (BBNumbers.empty()) {
270 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
274 // Compute the locations where PhiNodes need to be inserted. Look at the
275 // dominance frontier of EACH basic-block we have a write in.
277 unsigned CurrentVersion = 0;
278 SmallPtrSet<PHINode*, 16> InsertedPHINodes;
279 std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
280 while (!DefiningBlocks.empty()) {
281 BasicBlock *BB = DefiningBlocks.back();
282 DefiningBlocks.pop_back();
284 // Look up the DF for this write, add it to PhiNodes
285 DominanceFrontier::const_iterator it = DF.find(BB);
286 if (it != DF.end()) {
287 const DominanceFrontier::DomSetType &S = it->second;
289 // In theory we don't need the indirection through the DFBlocks vector.
290 // In practice, the order of calling QueuePhiNode would depend on the
291 // (unspecified) ordering of basic blocks in the dominance frontier,
292 // which would give PHI nodes non-determinstic subscripts. Fix this by
293 // processing blocks in order of the occurance in the function.
294 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
295 PE = S.end(); P != PE; ++P)
296 DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
298 // Sort by which the block ordering in the function.
299 std::sort(DFBlocks.begin(), DFBlocks.end());
301 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
302 BasicBlock *BB = DFBlocks[i].second;
303 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
304 DefiningBlocks.push_back(BB);
310 // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
311 // of the writes to the variable, scan through the reads of the variable,
312 // marking PHI nodes which are actually necessary as alive (by removing them
313 // from the InsertedPHINodes set). This is not perfect: there may PHI
314 // marked alive because of loads which are dominated by stores, but there
315 // will be no unmarked PHI nodes which are actually used.
317 for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
318 MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
321 // If there are any PHI nodes which are now known to be dead, remove them!
322 for (SmallPtrSet<PHINode*, 16>::iterator I = InsertedPHINodes.begin(),
323 E = InsertedPHINodes.end(); I != E; ++I) {
325 std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
326 BBPNs[AllocaNum] = 0;
328 // Check to see if we just removed the last inserted PHI node from this
329 // basic block. If so, remove the entry for the basic block.
330 bool HasOtherPHIs = false;
331 for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
337 NewPhiNodes.erase(PN->getParent());
339 if (AST && isa<PointerType>(PN->getType()))
340 AST->deleteValue(PN);
341 PN->eraseFromParent();
344 // Keep the reverse mapping of the 'Allocas' array.
345 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
348 // Process all allocas which are only used in a single basic block.
349 for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
350 LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
351 const std::vector<AllocaInst*> &LocAllocas = I->second;
352 assert(!LocAllocas.empty() && "empty alloca list??");
354 // It's common for there to only be one alloca in the list. Handle it
356 if (LocAllocas.size() == 1) {
357 // If we can do the quick promotion pass, do so now.
358 if (PromoteLocallyUsedAlloca(I->first, LocAllocas[0]))
359 RetryList.push_back(LocAllocas[0]); // Failed, retry later.
361 // Locally promote anything possible. Note that if this is unable to
362 // promote a particular alloca, it puts the alloca onto the Allocas vector
363 // for global processing.
364 PromoteLocallyUsedAllocas(I->first, LocAllocas);
369 return; // All of the allocas must have been trivial!
371 // Set the incoming values for the basic block to be null values for all of
372 // the alloca's. We do this in case there is a load of a value that has not
373 // been stored yet. In this case, it will get this null value.
375 std::vector<Value *> Values(Allocas.size());
376 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
377 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
379 // Walks all basic blocks in the function performing the SSA rename algorithm
380 // and inserting the phi nodes we marked as necessary
382 RenamePass(F.begin(), 0, Values);
384 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
387 // Remove the allocas themselves from the function.
388 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
389 Instruction *A = Allocas[i];
391 // If there are any uses of the alloca instructions left, they must be in
392 // sections of dead code that were not processed on the dominance frontier.
393 // Just delete the users now.
396 A->replaceAllUsesWith(UndefValue::get(A->getType()));
397 if (AST) AST->deleteValue(A);
398 A->eraseFromParent();
402 // Loop over all of the PHI nodes and see if there are any that we can get
403 // rid of because they merge all of the same incoming values. This can
404 // happen due to undef values coming into the PHI nodes. This process is
405 // iterative, because eliminating one PHI node can cause others to be removed.
406 bool EliminatedAPHI = true;
407 while (EliminatedAPHI) {
408 EliminatedAPHI = false;
410 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
411 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
412 std::vector<PHINode*> &PNs = I->second;
413 for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
414 if (!PNs[i]) continue;
416 // If this PHI node merges one value and/or undefs, get the value.
417 if (Value *V = PNs[i]->hasConstantValue(true)) {
418 if (!isa<Instruction>(V) ||
419 properlyDominates(cast<Instruction>(V), PNs[i])) {
420 if (AST && isa<PointerType>(PNs[i]->getType()))
421 AST->deleteValue(PNs[i]);
422 PNs[i]->replaceAllUsesWith(V);
423 PNs[i]->eraseFromParent();
425 EliminatedAPHI = true;
433 // At this point, the renamer has added entries to PHI nodes for all reachable
434 // code. Unfortunately, there may be unreachable blocks which the renamer
435 // hasn't traversed. If this is the case, the PHI nodes may not
436 // have incoming values for all predecessors. Loop over all PHI nodes we have
437 // created, inserting undef values if they are missing any incoming values.
439 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
440 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
442 std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
443 std::vector<PHINode*> &PNs = I->second;
444 assert(!PNs.empty() && "Empty PHI node list??");
445 PHINode *SomePHI = 0;
446 for (unsigned i = 0, e = PNs.size(); i != e; ++i)
452 // Only do work here if there the PHI nodes are missing incoming values. We
453 // know that all PHI nodes that were inserted in a block will have the same
454 // number of incoming values, so we can just check any PHI node.
455 if (SomePHI && Preds.size() != SomePHI->getNumIncomingValues()) {
456 // Ok, now we know that all of the PHI nodes are missing entries for some
457 // basic blocks. Start by sorting the incoming predecessors for efficient
459 std::sort(Preds.begin(), Preds.end());
461 // Now we loop through all BB's which have entries in SomePHI and remove
462 // them from the Preds list.
463 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
464 // Do a log(n) search of the Preds list for the entry we want.
465 std::vector<BasicBlock*>::iterator EntIt =
466 std::lower_bound(Preds.begin(), Preds.end(),
467 SomePHI->getIncomingBlock(i));
468 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
469 "PHI node has entry for a block which is not a predecessor!");
475 // At this point, the blocks left in the preds list must have dummy
476 // entries inserted into every PHI nodes for the block.
477 for (unsigned i = 0, e = PNs.size(); i != e; ++i)
478 if (PHINode *PN = PNs[i]) {
479 Value *UndefVal = UndefValue::get(PN->getType());
480 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
481 PN->addIncoming(UndefVal, Preds[pred]);
487 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
488 // "minimal" SSA form. To do this, it inserts all of the PHI nodes on the IDF
489 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
490 // each read of the variable. For each block that reads the variable, this
491 // function is called, which removes used PHI nodes from the DeadPHINodes set.
492 // After all of the reads have been processed, any PHI nodes left in the
493 // DeadPHINodes set are removed.
495 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
496 SmallPtrSet<PHINode*, 16> &DeadPHINodes) {
497 // Scan the immediate dominators of this block looking for a block which has a
498 // PHI node for Alloca num. If we find it, mark the PHI node as being alive!
499 for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
500 BasicBlock *DomBB = N->getBlock();
501 std::map<BasicBlock*, std::vector<PHINode*> >::iterator
502 I = NewPhiNodes.find(DomBB);
503 if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
504 // Ok, we found an inserted PHI node which dominates this value.
505 PHINode *DominatingPHI = I->second[AllocaNum];
507 // Find out if we previously thought it was dead. If so, mark it as being
508 // live by removing it from the DeadPHINodes set.
509 if (DeadPHINodes.erase(DominatingPHI)) {
510 // Now that we have marked the PHI node alive, also mark any PHI nodes
511 // which it might use as being alive as well.
512 for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
514 MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
520 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
521 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
522 /// potentially useless PHI nodes by just performing a single linear pass over
523 /// the basic block using the Alloca.
525 /// If we cannot promote this alloca (because it is read before it is written),
526 /// return true. This is necessary in cases where, due to control flow, the
527 /// alloca is potentially undefined on some control flow paths. e.g. code like
528 /// this is potentially correct:
530 /// for (...) { if (c) { A = undef; undef = B; } }
532 /// ... so long as A is not used before undef is set.
534 bool PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
535 assert(!AI->use_empty() && "There are no uses of the alloca!");
537 // Handle degenerate cases quickly.
538 if (AI->hasOneUse()) {
539 Instruction *U = cast<Instruction>(AI->use_back());
540 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
541 // Must be a load of uninitialized value.
542 LI->replaceAllUsesWith(UndefValue::get(AI->getAllocatedType()));
543 if (AST && isa<PointerType>(LI->getType()))
544 AST->deleteValue(LI);
546 // Otherwise it must be a store which is never read.
547 assert(isa<StoreInst>(U));
549 BB->getInstList().erase(U);
551 // Uses of the uninitialized memory location shall get undef.
554 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
555 Instruction *Inst = I++;
556 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
557 if (LI->getOperand(0) == AI) {
558 if (!CurVal) return true; // Could not locally promote!
560 // Loads just returns the "current value"...
561 LI->replaceAllUsesWith(CurVal);
562 if (AST && isa<PointerType>(LI->getType()))
563 AST->deleteValue(LI);
564 BB->getInstList().erase(LI);
566 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
567 if (SI->getOperand(1) == AI) {
568 // Store updates the "current value"...
569 CurVal = SI->getOperand(0);
570 BB->getInstList().erase(SI);
576 // After traversing the basic block, there should be no more uses of the
577 // alloca, remove it now.
578 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
579 if (AST) AST->deleteValue(AI);
580 AI->getParent()->getInstList().erase(AI);
584 /// PromoteLocallyUsedAllocas - This method is just like
585 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
586 /// instructions in parallel. This is important in cases where we have large
587 /// basic blocks, as we don't want to rescan the entire basic block for each
588 /// alloca which is locally used in it (which might be a lot).
589 void PromoteMem2Reg::
590 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
591 std::map<AllocaInst*, Value*> CurValues;
592 for (unsigned i = 0, e = AIs.size(); i != e; ++i)
593 CurValues[AIs[i]] = 0; // Insert with null value
595 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
596 Instruction *Inst = I++;
597 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
598 // Is this a load of an alloca we are tracking?
599 if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
600 std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
601 if (AIt != CurValues.end()) {
602 // If loading an uninitialized value, allow the inter-block case to
603 // handle it. Due to control flow, this might actually be ok.
604 if (AIt->second == 0) { // Use of locally uninitialized value??
605 RetryList.push_back(AI); // Retry elsewhere.
606 CurValues.erase(AIt); // Stop tracking this here.
607 if (CurValues.empty()) return;
609 // Loads just returns the "current value"...
610 LI->replaceAllUsesWith(AIt->second);
611 if (AST && isa<PointerType>(LI->getType()))
612 AST->deleteValue(LI);
613 BB->getInstList().erase(LI);
617 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
618 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
619 std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
620 if (AIt != CurValues.end()) {
621 // Store updates the "current value"...
622 AIt->second = SI->getOperand(0);
623 BB->getInstList().erase(SI);
632 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
633 // Alloca returns true if there wasn't already a phi-node for that variable
635 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
637 SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
638 // Look up the basic-block in question.
639 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
640 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
642 // If the BB already has a phi node added for the i'th alloca then we're done!
643 if (BBPNs[AllocaNo]) return false;
645 // Create a PhiNode using the dereferenced type... and add the phi-node to the
647 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
648 Allocas[AllocaNo]->getName() + "." +
649 utostr(Version++), BB->begin());
650 BBPNs[AllocaNo] = PN;
651 InsertedPHINodes.insert(PN);
653 if (AST && isa<PointerType>(PN->getType()))
654 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
660 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
661 // stores to the allocas which we are promoting. IncomingVals indicates what
662 // value each Alloca contains on exit from the predecessor block Pred.
664 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
665 std::vector<Value*> &IncomingVals) {
667 // If this BB needs a PHI node, update the PHI node for each variable we need
669 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
670 BBPNI = NewPhiNodes.find(BB);
671 if (BBPNI != NewPhiNodes.end()) {
672 std::vector<PHINode *> &BBPNs = BBPNI->second;
673 for (unsigned k = 0; k != BBPNs.size(); ++k)
674 if (PHINode *PN = BBPNs[k]) {
675 // Add this incoming value to the PHI node.
676 PN->addIncoming(IncomingVals[k], Pred);
678 // The currently active variable for this block is now the PHI.
679 IncomingVals[k] = PN;
683 // don't revisit nodes
684 if (Visited.count(BB)) return;
689 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
690 Instruction *I = II++; // get the instruction, increment iterator
692 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
693 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
694 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
695 if (AI != AllocaLookup.end()) {
696 Value *V = IncomingVals[AI->second];
698 // walk the use list of this load and replace all uses with r
699 LI->replaceAllUsesWith(V);
700 if (AST && isa<PointerType>(LI->getType()))
701 AST->deleteValue(LI);
702 BB->getInstList().erase(LI);
705 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
706 // Delete this instruction and mark the name as the current holder of the
708 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
709 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
710 if (ai != AllocaLookup.end()) {
711 // what value were we writing?
712 IncomingVals[ai->second] = SI->getOperand(0);
713 BB->getInstList().erase(SI);
719 // Recurse to our successors.
720 TerminatorInst *TI = BB->getTerminator();
721 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
722 std::vector<Value*> OutgoingVals(IncomingVals);
723 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
727 /// PromoteMemToReg - Promote the specified list of alloca instructions into
728 /// scalar registers, inserting PHI nodes as appropriate. This function makes
729 /// use of DominanceFrontier information. This function does not modify the CFG
730 /// of the function at all. All allocas must be from the same function.
732 /// If AST is specified, the specified tracker is updated to reflect changes
735 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
736 DominatorTree &DT, DominanceFrontier &DF,
737 const TargetData &TD, AliasSetTracker *AST) {
738 // If there is nothing to do, bail out...
739 if (Allocas.empty()) return;
741 SmallVector<AllocaInst*, 16> RetryList;
742 PromoteMem2Reg(Allocas, RetryList, DT, DF, TD, AST).run();
744 // PromoteMem2Reg may not have been able to promote all of the allocas in one
745 // pass, run it again if needed.
746 std::vector<AllocaInst*> NewAllocas;
747 while (!RetryList.empty()) {
748 // If we need to retry some allocas, this is due to there being no store
749 // before a read in a local block. To counteract this, insert a store of
750 // undef into the alloca right after the alloca itself.
751 for (unsigned i = 0, e = RetryList.size(); i != e; ++i) {
752 BasicBlock::iterator BBI = RetryList[i];
754 new StoreInst(UndefValue::get(RetryList[i]->getAllocatedType()),
755 RetryList[i], ++BBI);
758 NewAllocas.assign(RetryList.begin(), RetryList.end());
760 PromoteMem2Reg(NewAllocas, RetryList, DT, DF, TD, AST).run();