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 #define DEBUG_TYPE "mem2reg"
20 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/AliasSetTracker.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Compiler.h"
37 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
38 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
39 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
40 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
42 // Provide DenseMapKeyInfo for all pointers.
45 struct DenseMapKeyInfo<std::pair<BasicBlock*, unsigned> > {
46 static inline std::pair<BasicBlock*, unsigned> getEmptyKey() {
47 return std::make_pair((BasicBlock*)-1, ~0U);
49 static inline std::pair<BasicBlock*, unsigned> getTombstoneKey() {
50 return std::make_pair((BasicBlock*)-2, 0U);
52 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
53 return DenseMapKeyInfo<void*>::getHashValue(Val.first) + Val.second*2;
55 static bool isPod() { return true; }
59 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
60 /// This is true if there are only loads and stores to the alloca.
62 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
63 // FIXME: If the memory unit is of pointer or integer type, we can permit
64 // assignments to subsections of the memory unit.
66 // Only allow direct loads and stores...
67 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
68 UI != UE; ++UI) // Loop over all of the uses of the alloca
69 if (isa<LoadInst>(*UI)) {
71 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
72 if (SI->getOperand(0) == AI)
73 return false; // Don't allow a store OF the AI, only INTO the AI.
75 return false; // Not a load or store.
84 // Data package used by RenamePass()
85 class VISIBILITY_HIDDEN RenamePassData {
87 typedef std::vector<Value *> ValVector;
90 RenamePassData(BasicBlock *B, BasicBlock *P,
91 const ValVector &V) : BB(B), Pred(P), Values(V) {}
96 void swap(RenamePassData &RHS) {
97 std::swap(BB, RHS.BB);
98 std::swap(Pred, RHS.Pred);
99 Values.swap(RHS.Values);
103 struct VISIBILITY_HIDDEN PromoteMem2Reg {
104 /// Allocas - The alloca instructions being promoted.
106 std::vector<AllocaInst*> Allocas;
107 SmallVector<AllocaInst*, 16> &RetryList;
109 DominanceFrontier &DF;
111 /// AST - An AliasSetTracker object to update. If null, don't update it.
113 AliasSetTracker *AST;
115 /// AllocaLookup - Reverse mapping of Allocas.
117 std::map<AllocaInst*, unsigned> AllocaLookup;
119 /// NewPhiNodes - The PhiNodes we're adding.
121 DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
123 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
124 /// it corresponds to.
125 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
127 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
128 /// each alloca that is of pointer type, we keep track of what to copyValue
129 /// to the inserted PHI nodes here.
131 std::vector<Value*> PointerAllocaValues;
133 /// Visited - The set of basic blocks the renamer has already visited.
135 SmallPtrSet<BasicBlock*, 16> Visited;
137 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
138 /// non-determinstic behavior.
139 DenseMap<BasicBlock*, unsigned> BBNumbers;
141 /// BBNumPreds - Lazily compute the number of predecessors a block has.
142 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
144 PromoteMem2Reg(const std::vector<AllocaInst*> &A,
145 SmallVector<AllocaInst*, 16> &Retry, DominatorTree &dt,
146 DominanceFrontier &df, AliasSetTracker *ast)
147 : Allocas(A), RetryList(Retry), DT(dt), DF(df), AST(ast) {}
151 /// properlyDominates - Return true if I1 properly dominates I2.
153 bool properlyDominates(Instruction *I1, Instruction *I2) const {
154 if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
155 I1 = II->getNormalDest()->begin();
156 return DT.properlyDominates(I1->getParent(), I2->getParent());
159 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
161 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
162 return DT.dominates(BB1, BB2);
166 void RemoveFromAllocasList(unsigned &AllocaIdx) {
167 Allocas[AllocaIdx] = Allocas.back();
172 unsigned getNumPreds(const BasicBlock *BB) {
173 unsigned &NP = BBNumPreds[BB];
175 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
179 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
181 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
182 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
183 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
185 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info);
187 bool PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
188 void PromoteLocallyUsedAllocas(BasicBlock *BB,
189 const std::vector<AllocaInst*> &AIs);
191 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
192 RenamePassData::ValVector &IncVals,
193 std::vector<RenamePassData> &Worklist);
194 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
195 SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
199 std::vector<BasicBlock*> DefiningBlocks;
200 std::vector<BasicBlock*> UsingBlocks;
202 StoreInst *OnlyStore;
203 BasicBlock *OnlyBlock;
204 bool OnlyUsedInOneBlock;
206 Value *AllocaPointerVal;
209 DefiningBlocks.clear();
213 OnlyUsedInOneBlock = true;
214 AllocaPointerVal = 0;
217 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
219 void AnalyzeAlloca(AllocaInst *AI) {
222 // As we scan the uses of the alloca instruction, keep track of stores,
223 // and decide whether all of the loads and stores to the alloca are within
224 // the same basic block.
225 for (Value::use_iterator U = AI->use_begin(), E = AI->use_end();
227 Instruction *User = cast<Instruction>(*U);
228 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
229 // Remember the basic blocks which define new values for the alloca
230 DefiningBlocks.push_back(SI->getParent());
231 AllocaPointerVal = SI->getOperand(0);
234 LoadInst *LI = cast<LoadInst>(User);
235 // Otherwise it must be a load instruction, keep track of variable
237 UsingBlocks.push_back(LI->getParent());
238 AllocaPointerVal = LI;
241 if (OnlyUsedInOneBlock) {
243 OnlyBlock = User->getParent();
244 else if (OnlyBlock != User->getParent())
245 OnlyUsedInOneBlock = false;
251 } // end of anonymous namespace
254 void PromoteMem2Reg::run() {
255 Function &F = *DF.getRoot()->getParent();
257 // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
258 // only used in a single basic block. These instructions can be efficiently
259 // promoted by performing a single linear scan over that one block. Since
260 // individual basic blocks are sometimes large, we group together all allocas
261 // that are live in a single basic block by the basic block they are live in.
262 std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
264 if (AST) PointerAllocaValues.resize(Allocas.size());
268 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
269 AllocaInst *AI = Allocas[AllocaNum];
271 assert(isAllocaPromotable(AI) &&
272 "Cannot promote non-promotable alloca!");
273 assert(AI->getParent()->getParent() == &F &&
274 "All allocas should be in the same function, which is same as DF!");
276 if (AI->use_empty()) {
277 // If there are no uses of the alloca, just delete it now.
278 if (AST) AST->deleteValue(AI);
279 AI->eraseFromParent();
281 // Remove the alloca from the Allocas list, since it has been processed
282 RemoveFromAllocasList(AllocaNum);
287 // Calculate the set of read and write-locations for each alloca. This is
288 // analogous to finding the 'uses' and 'definitions' of each variable.
289 Info.AnalyzeAlloca(AI);
291 // If there is only a single store to this value, replace any loads of
292 // it that are directly dominated by the definition with the value stored.
293 if (Info.DefiningBlocks.size() == 1) {
294 RewriteSingleStoreAlloca(AI, Info);
296 // Finally, after the scan, check to see if the store is all that is left.
297 if (Info.UsingBlocks.empty()) {
298 // Remove the (now dead) store and alloca.
299 Info.OnlyStore->eraseFromParent();
300 if (AST) AST->deleteValue(AI);
301 AI->eraseFromParent();
303 // The alloca has been processed, move on.
304 RemoveFromAllocasList(AllocaNum);
311 // If the alloca is only read and written in one basic block, just perform a
312 // linear sweep over the block to eliminate it.
313 if (Info.OnlyUsedInOneBlock) {
314 LocallyUsedAllocas[Info.OnlyBlock].push_back(AI);
316 // Remove the alloca from the Allocas list, since it will be processed.
317 RemoveFromAllocasList(AllocaNum);
321 // If we haven't computed a numbering for the BB's in the function, do so
323 if (BBNumbers.empty()) {
325 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
329 // If we have an AST to keep updated, remember some pointer value that is
330 // stored into the alloca.
332 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
334 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
335 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
337 // At this point, we're committed to promoting the alloca using IDF's, and
338 // the standard SSA construction algorithm. Determine which blocks need phi
339 // nodes and see if we can optimize out some work by avoiding insertion of
341 DetermineInsertionPoint(AI, AllocaNum, Info);
344 // Process all allocas which are only used in a single basic block.
345 for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
346 LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
347 const std::vector<AllocaInst*> &LocAllocas = I->second;
348 assert(!LocAllocas.empty() && "empty alloca list??");
350 // It's common for there to only be one alloca in the list. Handle it
352 if (LocAllocas.size() == 1) {
353 // If we can do the quick promotion pass, do so now.
354 if (PromoteLocallyUsedAlloca(I->first, LocAllocas[0]))
355 RetryList.push_back(LocAllocas[0]); // Failed, retry later.
357 // Locally promote anything possible. Note that if this is unable to
358 // promote a particular alloca, it puts the alloca onto the Allocas vector
359 // for global processing.
360 PromoteLocallyUsedAllocas(I->first, LocAllocas);
365 return; // All of the allocas must have been trivial!
367 // Set the incoming values for the basic block to be null values for all of
368 // the alloca's. We do this in case there is a load of a value that has not
369 // been stored yet. In this case, it will get this null value.
371 RenamePassData::ValVector Values(Allocas.size());
372 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
373 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
375 // Walks all basic blocks in the function performing the SSA rename algorithm
376 // and inserting the phi nodes we marked as necessary
378 std::vector<RenamePassData> RenamePassWorkList;
379 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
380 while (!RenamePassWorkList.empty()) {
382 RPD.swap(RenamePassWorkList.back());
383 RenamePassWorkList.pop_back();
384 // RenamePass may add new worklist entries.
385 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
388 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
391 // Remove the allocas themselves from the function.
392 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
393 Instruction *A = Allocas[i];
395 // If there are any uses of the alloca instructions left, they must be in
396 // sections of dead code that were not processed on the dominance frontier.
397 // Just delete the users now.
400 A->replaceAllUsesWith(UndefValue::get(A->getType()));
401 if (AST) AST->deleteValue(A);
402 A->eraseFromParent();
406 // Loop over all of the PHI nodes and see if there are any that we can get
407 // rid of because they merge all of the same incoming values. This can
408 // happen due to undef values coming into the PHI nodes. This process is
409 // iterative, because eliminating one PHI node can cause others to be removed.
410 bool EliminatedAPHI = true;
411 while (EliminatedAPHI) {
412 EliminatedAPHI = false;
414 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
415 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
416 PHINode *PN = I->second;
418 // If this PHI node merges one value and/or undefs, get the value.
419 if (Value *V = PN->hasConstantValue(true)) {
420 if (!isa<Instruction>(V) ||
421 properlyDominates(cast<Instruction>(V), PN)) {
422 if (AST && isa<PointerType>(PN->getType()))
423 AST->deleteValue(PN);
424 PN->replaceAllUsesWith(V);
425 PN->eraseFromParent();
426 NewPhiNodes.erase(I++);
427 EliminatedAPHI = true;
435 // At this point, the renamer has added entries to PHI nodes for all reachable
436 // code. Unfortunately, there may be unreachable blocks which the renamer
437 // hasn't traversed. If this is the case, the PHI nodes may not
438 // have incoming values for all predecessors. Loop over all PHI nodes we have
439 // created, inserting undef values if they are missing any incoming values.
441 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
442 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
443 // We want to do this once per basic block. As such, only process a block
444 // when we find the PHI that is the first entry in the block.
445 PHINode *SomePHI = I->second;
446 BasicBlock *BB = SomePHI->getParent();
447 if (&BB->front() != SomePHI)
450 // Only do work here if there the PHI nodes are missing incoming values. We
451 // know that all PHI nodes that were inserted in a block will have the same
452 // number of incoming values, so we can just check any of them.
453 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
456 // Get the preds for BB.
457 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
459 // Ok, now we know that all of the PHI nodes are missing entries for some
460 // basic blocks. Start by sorting the incoming predecessors for efficient
462 std::sort(Preds.begin(), Preds.end());
464 // Now we loop through all BB's which have entries in SomePHI and remove
465 // them from the Preds list.
466 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
467 // Do a log(n) search of the Preds list for the entry we want.
468 SmallVector<BasicBlock*, 16>::iterator EntIt =
469 std::lower_bound(Preds.begin(), Preds.end(),
470 SomePHI->getIncomingBlock(i));
471 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
472 "PHI node has entry for a block which is not a predecessor!");
478 // At this point, the blocks left in the preds list must have dummy
479 // entries inserted into every PHI nodes for the block. Update all the phi
480 // nodes in this block that we are inserting (there could be phis before
482 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
483 BasicBlock::iterator BBI = BB->begin();
484 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
485 SomePHI->getNumIncomingValues() == NumBadPreds) {
486 Value *UndefVal = UndefValue::get(SomePHI->getType());
487 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
488 SomePHI->addIncoming(UndefVal, Preds[pred]);
496 /// ComputeLiveInBlocks - Determine which blocks the value is live in. These
497 /// are blocks which lead to uses. Knowing this allows us to avoid inserting
498 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
500 void PromoteMem2Reg::
501 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
502 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
503 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
505 // To determine liveness, we must iterate through the predecessors of blocks
506 // where the def is live. Blocks are added to the worklist if we need to
507 // check their predecessors. Start with all the using blocks.
508 SmallVector<BasicBlock*, 64> LiveInBlockWorklist;
509 LiveInBlockWorklist.insert(LiveInBlockWorklist.end(),
510 Info.UsingBlocks.begin(), Info.UsingBlocks.end());
512 // If any of the using blocks is also a definition block, check to see if the
513 // definition occurs before or after the use. If it happens before the use,
514 // the value isn't really live-in.
515 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
516 BasicBlock *BB = LiveInBlockWorklist[i];
517 if (!DefBlocks.count(BB)) continue;
519 // Okay, this is a block that both uses and defines the value. If the first
520 // reference to the alloca is a def (store), then we know it isn't live-in.
521 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
522 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
523 if (SI->getOperand(1) != AI) continue;
525 // We found a store to the alloca before a load. The alloca is not
526 // actually live-in here.
527 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
528 LiveInBlockWorklist.pop_back();
531 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
532 if (LI->getOperand(0) != AI) continue;
534 // Okay, we found a load before a store to the alloca. It is actually
535 // live into this block.
541 // Now that we have a set of blocks where the phi is live-in, recursively add
542 // their predecessors until we find the full region the value is live.
543 while (!LiveInBlockWorklist.empty()) {
544 BasicBlock *BB = LiveInBlockWorklist.back();
545 LiveInBlockWorklist.pop_back();
547 // The block really is live in here, insert it into the set. If already in
548 // the set, then it has already been processed.
549 if (!LiveInBlocks.insert(BB))
552 // Since the value is live into BB, it is either defined in a predecessor or
553 // live into it to. Add the preds to the worklist unless they are a
555 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
558 // The value is not live into a predecessor if it defines the value.
559 if (DefBlocks.count(P))
562 // Otherwise it is, add to the worklist.
563 LiveInBlockWorklist.push_back(P);
568 /// DetermineInsertionPoint - At this point, we're committed to promoting the
569 /// alloca using IDF's, and the standard SSA construction algorithm. Determine
570 /// which blocks need phi nodes and see if we can optimize out some work by
571 /// avoiding insertion of dead phi nodes.
572 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
575 // Unique the set of defining blocks for efficient lookup.
576 SmallPtrSet<BasicBlock*, 32> DefBlocks;
577 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
579 // Determine which blocks the value is live in. These are blocks which lead
581 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
582 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
584 // Compute the locations where PhiNodes need to be inserted. Look at the
585 // dominance frontier of EACH basic-block we have a write in.
586 unsigned CurrentVersion = 0;
587 SmallPtrSet<PHINode*, 16> InsertedPHINodes;
588 std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
589 while (!Info.DefiningBlocks.empty()) {
590 BasicBlock *BB = Info.DefiningBlocks.back();
591 Info.DefiningBlocks.pop_back();
593 // Look up the DF for this write, add it to defining blocks.
594 DominanceFrontier::const_iterator it = DF.find(BB);
595 if (it == DF.end()) continue;
597 const DominanceFrontier::DomSetType &S = it->second;
599 // In theory we don't need the indirection through the DFBlocks vector.
600 // In practice, the order of calling QueuePhiNode would depend on the
601 // (unspecified) ordering of basic blocks in the dominance frontier,
602 // which would give PHI nodes non-determinstic subscripts. Fix this by
603 // processing blocks in order of the occurance in the function.
604 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
605 PE = S.end(); P != PE; ++P) {
606 // If the frontier block is not in the live-in set for the alloca, don't
607 // bother processing it.
608 if (!LiveInBlocks.count(*P))
611 DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
614 // Sort by which the block ordering in the function.
615 if (DFBlocks.size() > 1)
616 std::sort(DFBlocks.begin(), DFBlocks.end());
618 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
619 BasicBlock *BB = DFBlocks[i].second;
620 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
621 Info.DefiningBlocks.push_back(BB);
628 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
629 /// replace any loads of it that are directly dominated by the definition with
630 /// the value stored.
631 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
633 StoreInst *OnlyStore = Info.OnlyStore;
634 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
636 // Be aware of loads before the store.
637 SmallPtrSet<BasicBlock*, 32> ProcessedBlocks;
638 for (unsigned i = 0, e = Info.UsingBlocks.size(); i != e; ++i) {
639 BasicBlock *UseBlock = Info.UsingBlocks[i];
641 // If we already processed this block, don't reprocess it.
642 if (!ProcessedBlocks.insert(UseBlock)) {
643 Info.UsingBlocks[i] = Info.UsingBlocks.back();
644 Info.UsingBlocks.pop_back();
649 // If the store dominates the block and if we haven't processed it yet,
650 // do so now. We can't handle the case where the store doesn't dominate a
651 // block because there may be a path between the store and the use, but we
652 // may need to insert phi nodes to handle dominance properly.
653 if (!StoringGlobalVal && !dominates(OnlyStore->getParent(), UseBlock))
656 // If the use and store are in the same block, do a quick scan to
657 // verify that there are no uses before the store.
658 if (UseBlock == OnlyStore->getParent()) {
659 BasicBlock::iterator I = UseBlock->begin();
660 for (; &*I != OnlyStore; ++I) { // scan block for store.
661 if (isa<LoadInst>(I) && I->getOperand(0) == AI)
664 if (&*I != OnlyStore)
665 continue; // Do not promote the uses of this in this block.
668 // Otherwise, if this is a different block or if all uses happen
669 // after the store, do a simple linear scan to replace loads with
671 for (BasicBlock::iterator I = UseBlock->begin(), E = UseBlock->end();
673 if (LoadInst *LI = dyn_cast<LoadInst>(I++)) {
674 if (LI->getOperand(0) == AI) {
675 LI->replaceAllUsesWith(OnlyStore->getOperand(0));
676 if (AST && isa<PointerType>(LI->getType()))
677 AST->deleteValue(LI);
678 LI->eraseFromParent();
683 // Finally, remove this block from the UsingBlock set.
684 Info.UsingBlocks[i] = Info.UsingBlocks.back();
685 Info.UsingBlocks.pop_back();
691 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
692 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
693 /// potentially useless PHI nodes by just performing a single linear pass over
694 /// the basic block using the Alloca.
696 /// If we cannot promote this alloca (because it is read before it is written),
697 /// return true. This is necessary in cases where, due to control flow, the
698 /// alloca is potentially undefined on some control flow paths. e.g. code like
699 /// this is potentially correct:
701 /// for (...) { if (c) { A = undef; undef = B; } }
703 /// ... so long as A is not used before undef is set.
705 bool PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
706 assert(!AI->use_empty() && "There are no uses of the alloca!");
708 // Handle degenerate cases quickly.
709 if (AI->hasOneUse()) {
710 Instruction *U = cast<Instruction>(AI->use_back());
711 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
712 // Must be a load of uninitialized value.
713 LI->replaceAllUsesWith(UndefValue::get(AI->getAllocatedType()));
714 if (AST && isa<PointerType>(LI->getType()))
715 AST->deleteValue(LI);
717 // Otherwise it must be a store which is never read.
718 assert(isa<StoreInst>(U));
720 BB->getInstList().erase(U);
722 // Uses of the uninitialized memory location shall get undef.
725 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
726 Instruction *Inst = I++;
727 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
728 if (LI->getOperand(0) == AI) {
729 if (!CurVal) return true; // Could not locally promote!
731 // Loads just returns the "current value"...
732 LI->replaceAllUsesWith(CurVal);
733 if (AST && isa<PointerType>(LI->getType()))
734 AST->deleteValue(LI);
735 BB->getInstList().erase(LI);
737 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
738 if (SI->getOperand(1) == AI) {
739 // Store updates the "current value"...
740 CurVal = SI->getOperand(0);
741 BB->getInstList().erase(SI);
747 // After traversing the basic block, there should be no more uses of the
748 // alloca: remove it now.
749 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
750 if (AST) AST->deleteValue(AI);
751 AI->eraseFromParent();
757 /// PromoteLocallyUsedAllocas - This method is just like
758 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
759 /// instructions in parallel. This is important in cases where we have large
760 /// basic blocks, as we don't want to rescan the entire basic block for each
761 /// alloca which is locally used in it (which might be a lot).
762 void PromoteMem2Reg::
763 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
764 DenseMap<AllocaInst*, Value*> CurValues;
765 for (unsigned i = 0, e = AIs.size(); i != e; ++i)
766 CurValues[AIs[i]] = 0; // Insert with null value
768 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
769 Instruction *Inst = I++;
770 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
771 // Is this a load of an alloca we are tracking?
772 if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
773 DenseMap<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
774 if (AIt != CurValues.end()) {
775 // If loading an uninitialized value, allow the inter-block case to
776 // handle it. Due to control flow, this might actually be ok.
777 if (AIt->second == 0) { // Use of locally uninitialized value??
778 RetryList.push_back(AI); // Retry elsewhere.
779 CurValues.erase(AIt); // Stop tracking this here.
780 if (CurValues.empty()) return;
782 // Loads just returns the "current value"...
783 LI->replaceAllUsesWith(AIt->second);
784 if (AST && isa<PointerType>(LI->getType()))
785 AST->deleteValue(LI);
786 BB->getInstList().erase(LI);
790 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
791 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
792 DenseMap<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
793 if (AIt != CurValues.end()) {
794 // Store updates the "current value"...
795 AIt->second = SI->getOperand(0);
796 SI->eraseFromParent();
802 // At the end of the block scan, all allocas in CurValues are dead.
803 for (DenseMap<AllocaInst*, Value*>::iterator I = CurValues.begin(),
804 E = CurValues.end(); I != E; ++I) {
805 AllocaInst *AI = I->first;
806 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
807 if (AST) AST->deleteValue(AI);
808 AI->eraseFromParent();
811 NumLocalPromoted += CurValues.size();
816 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
817 // Alloca returns true if there wasn't already a phi-node for that variable
819 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
821 SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
822 // Look up the basic-block in question.
823 PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
825 // If the BB already has a phi node added for the i'th alloca then we're done!
826 if (PN) return false;
828 // Create a PhiNode using the dereferenced type... and add the phi-node to the
830 PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
831 Allocas[AllocaNo]->getName() + "." +
832 utostr(Version++), BB->begin());
834 PhiToAllocaMap[PN] = AllocaNo;
835 PN->reserveOperandSpace(getNumPreds(BB));
837 InsertedPHINodes.insert(PN);
839 if (AST && isa<PointerType>(PN->getType()))
840 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
846 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
847 // stores to the allocas which we are promoting. IncomingVals indicates what
848 // value each Alloca contains on exit from the predecessor block Pred.
850 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
851 RenamePassData::ValVector &IncomingVals,
852 std::vector<RenamePassData> &Worklist) {
854 // If we are inserting any phi nodes into this BB, they will already be in the
856 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
857 // Pred may have multiple edges to BB. If so, we want to add N incoming
858 // values to each PHI we are inserting on the first time we see the edge.
859 // Check to see if APN already has incoming values from Pred. This also
860 // prevents us from modifying PHI nodes that are not currently being
862 bool HasPredEntries = false;
863 for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
864 if (APN->getIncomingBlock(i) == Pred) {
865 HasPredEntries = true;
870 // If we have PHI nodes to update, compute the number of edges from Pred to
872 if (!HasPredEntries) {
873 TerminatorInst *PredTerm = Pred->getTerminator();
874 unsigned NumEdges = 0;
875 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
876 if (PredTerm->getSuccessor(i) == BB)
879 assert(NumEdges && "Must be at least one edge from Pred to BB!");
881 // Add entries for all the phis.
882 BasicBlock::iterator PNI = BB->begin();
884 unsigned AllocaNo = PhiToAllocaMap[APN];
886 // Add N incoming values to the PHI node.
887 for (unsigned i = 0; i != NumEdges; ++i)
888 APN->addIncoming(IncomingVals[AllocaNo], Pred);
890 // The currently active variable for this block is now the PHI.
891 IncomingVals[AllocaNo] = APN;
893 // Get the next phi node.
895 APN = dyn_cast<PHINode>(PNI);
898 // Verify it doesn't already have entries for Pred. If it does, it is
899 // not being inserted by this mem2reg invocation.
900 HasPredEntries = false;
901 for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
902 if (APN->getIncomingBlock(i) == Pred) {
903 HasPredEntries = true;
907 } while (!HasPredEntries);
911 // Don't revisit blocks.
912 if (!Visited.insert(BB)) return;
914 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
915 Instruction *I = II++; // get the instruction, increment iterator
917 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
918 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
921 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
922 if (AI == AllocaLookup.end()) continue;
924 Value *V = IncomingVals[AI->second];
926 // Anything using the load now uses the current value.
927 LI->replaceAllUsesWith(V);
928 if (AST && isa<PointerType>(LI->getType()))
929 AST->deleteValue(LI);
930 BB->getInstList().erase(LI);
931 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
932 // Delete this instruction and mark the name as the current holder of the
934 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
937 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
938 if (ai == AllocaLookup.end())
941 // what value were we writing?
942 IncomingVals[ai->second] = SI->getOperand(0);
943 BB->getInstList().erase(SI);
947 // 'Recurse' to our successors.
948 TerminatorInst *TI = BB->getTerminator();
949 unsigned NumSuccs = TI->getNumSuccessors();
950 if (NumSuccs == 0) return;
952 // Add all-but-one successor to the worklist.
953 for (unsigned i = 0; i != NumSuccs-1; i++)
954 Worklist.push_back(RenamePassData(TI->getSuccessor(i), BB, IncomingVals));
956 // Handle the last successor without using the worklist. This allows us to
957 // handle unconditional branches directly, for example.
959 BB = TI->getSuccessor(NumSuccs-1);
963 /// PromoteMemToReg - Promote the specified list of alloca instructions into
964 /// scalar registers, inserting PHI nodes as appropriate. This function makes
965 /// use of DominanceFrontier information. This function does not modify the CFG
966 /// of the function at all. All allocas must be from the same function.
968 /// If AST is specified, the specified tracker is updated to reflect changes
971 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
972 DominatorTree &DT, DominanceFrontier &DF,
973 AliasSetTracker *AST) {
974 // If there is nothing to do, bail out...
975 if (Allocas.empty()) return;
977 SmallVector<AllocaInst*, 16> RetryList;
978 PromoteMem2Reg(Allocas, RetryList, DT, DF, AST).run();
980 // PromoteMem2Reg may not have been able to promote all of the allocas in one
981 // pass, run it again if needed.
982 std::vector<AllocaInst*> NewAllocas;
983 while (!RetryList.empty()) {
984 // If we need to retry some allocas, this is due to there being no store
985 // before a read in a local block. To counteract this, insert a store of
986 // undef into the alloca right after the alloca itself.
987 for (unsigned i = 0, e = RetryList.size(); i != e; ++i) {
988 BasicBlock::iterator BBI = RetryList[i];
990 new StoreInst(UndefValue::get(RetryList[i]->getAllocatedType()),
991 RetryList[i], ++BBI);
994 NewAllocas.assign(RetryList.begin(), RetryList.end());
996 PromoteMem2Reg(NewAllocas, RetryList, DT, DF, AST).run();