1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
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 promotes 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/IntrinsicInst.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/Analysis/AliasSetTracker.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Compiler.h"
39 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
40 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
41 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
42 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
46 struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
47 typedef std::pair<BasicBlock*, unsigned> EltTy;
48 static inline EltTy getEmptyKey() {
49 return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
51 static inline EltTy getTombstoneKey() {
52 return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
54 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
55 return DenseMapInfo<void*>::getHashValue(Val.first) + Val.second*2;
57 static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
60 static bool isPod() { return true; }
64 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
65 /// This is true if there are only loads and stores to the alloca.
67 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
68 // FIXME: If the memory unit is of pointer or integer type, we can permit
69 // assignments to subsections of the memory unit.
71 // Only allow direct and non-volatile loads and stores...
72 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
73 UI != UE; ++UI) // Loop over all of the uses of the alloca
74 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
77 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
78 if (SI->getOperand(0) == AI)
79 return false; // Don't allow a store OF the AI, only INTO the AI.
82 } else if (const BitCastInst *BC = dyn_cast<BitCastInst>(*UI)) {
83 // A bitcast that does not feed into debug info inhibits promotion.
84 if (!BC->hasOneUse() || !isa<DbgInfoIntrinsic>(*BC->use_begin()))
86 // If the only use is by debug info, this alloca will not exist in
87 // non-debug code, so don't try to promote; this ensures the same
88 // codegen with debug info. Otherwise, debug info should not
89 // inhibit promotion (but we must examine other uses).
102 // Data package used by RenamePass()
103 class VISIBILITY_HIDDEN RenamePassData {
105 typedef std::vector<Value *> ValVector;
108 RenamePassData(BasicBlock *B, BasicBlock *P,
109 const ValVector &V) : BB(B), Pred(P), Values(V) {}
114 void swap(RenamePassData &RHS) {
115 std::swap(BB, RHS.BB);
116 std::swap(Pred, RHS.Pred);
117 Values.swap(RHS.Values);
121 /// LargeBlockInfo - This assigns and keeps a per-bb relative ordering of
122 /// load/store instructions in the block that directly load or store an alloca.
124 /// This functionality is important because it avoids scanning large basic
125 /// blocks multiple times when promoting many allocas in the same block.
126 class VISIBILITY_HIDDEN LargeBlockInfo {
127 /// InstNumbers - For each instruction that we track, keep the index of the
128 /// instruction. The index starts out as the number of the instruction from
129 /// the start of the block.
130 DenseMap<const Instruction *, unsigned> InstNumbers;
133 /// isInterestingInstruction - This code only looks at accesses to allocas.
134 static bool isInterestingInstruction(const Instruction *I) {
135 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
136 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
139 /// getInstructionIndex - Get or calculate the index of the specified
141 unsigned getInstructionIndex(const Instruction *I) {
142 assert(isInterestingInstruction(I) &&
143 "Not a load/store to/from an alloca?");
145 // If we already have this instruction number, return it.
146 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
147 if (It != InstNumbers.end()) return It->second;
149 // Scan the whole block to get the instruction. This accumulates
150 // information for every interesting instruction in the block, in order to
151 // avoid gratuitus rescans.
152 const BasicBlock *BB = I->getParent();
154 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end();
156 if (isInterestingInstruction(BBI))
157 InstNumbers[BBI] = InstNo++;
158 It = InstNumbers.find(I);
160 assert(It != InstNumbers.end() && "Didn't insert instruction?");
164 void deleteValue(const Instruction *I) {
165 InstNumbers.erase(I);
173 struct VISIBILITY_HIDDEN PromoteMem2Reg {
174 /// Allocas - The alloca instructions being promoted.
176 std::vector<AllocaInst*> Allocas;
178 DominanceFrontier &DF;
180 /// AST - An AliasSetTracker object to update. If null, don't update it.
182 AliasSetTracker *AST;
184 LLVMContext &Context;
186 /// AllocaLookup - Reverse mapping of Allocas.
188 std::map<AllocaInst*, unsigned> AllocaLookup;
190 /// NewPhiNodes - The PhiNodes we're adding.
192 DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
194 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
195 /// it corresponds to.
196 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
198 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
199 /// each alloca that is of pointer type, we keep track of what to copyValue
200 /// to the inserted PHI nodes here.
202 std::vector<Value*> PointerAllocaValues;
204 /// Visited - The set of basic blocks the renamer has already visited.
206 SmallPtrSet<BasicBlock*, 16> Visited;
208 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
209 /// non-determinstic behavior.
210 DenseMap<BasicBlock*, unsigned> BBNumbers;
212 /// BBNumPreds - Lazily compute the number of predecessors a block has.
213 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
215 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
216 DominanceFrontier &df, AliasSetTracker *ast,
218 : Allocas(A), DT(dt), DF(df), AST(ast), Context(C) {}
222 /// properlyDominates - Return true if I1 properly dominates I2.
224 bool properlyDominates(Instruction *I1, Instruction *I2) const {
225 if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
226 I1 = II->getNormalDest()->begin();
227 return DT.properlyDominates(I1->getParent(), I2->getParent());
230 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
232 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
233 return DT.dominates(BB1, BB2);
237 void RemoveFromAllocasList(unsigned &AllocaIdx) {
238 Allocas[AllocaIdx] = Allocas.back();
243 unsigned getNumPreds(const BasicBlock *BB) {
244 unsigned &NP = BBNumPreds[BB];
246 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
250 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
252 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
253 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
254 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
256 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
257 LargeBlockInfo &LBI);
258 void PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
259 LargeBlockInfo &LBI);
262 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
263 RenamePassData::ValVector &IncVals,
264 std::vector<RenamePassData> &Worklist);
265 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
266 SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
270 std::vector<BasicBlock*> DefiningBlocks;
271 std::vector<BasicBlock*> UsingBlocks;
273 StoreInst *OnlyStore;
274 BasicBlock *OnlyBlock;
275 bool OnlyUsedInOneBlock;
277 Value *AllocaPointerVal;
280 DefiningBlocks.clear();
284 OnlyUsedInOneBlock = true;
285 AllocaPointerVal = 0;
288 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
290 void AnalyzeAlloca(AllocaInst *AI) {
293 // As we scan the uses of the alloca instruction, keep track of stores,
294 // and decide whether all of the loads and stores to the alloca are within
295 // the same basic block.
296 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
298 Instruction *User = cast<Instruction>(*UI++);
299 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
300 // Remove any uses of this alloca in DbgInfoInstrinsics.
301 assert(BC->hasOneUse() && "Unexpected alloca uses!");
302 DbgInfoIntrinsic *DI = cast<DbgInfoIntrinsic>(*BC->use_begin());
303 DI->eraseFromParent();
304 BC->eraseFromParent();
308 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
309 // Remember the basic blocks which define new values for the alloca
310 DefiningBlocks.push_back(SI->getParent());
311 AllocaPointerVal = SI->getOperand(0);
314 LoadInst *LI = cast<LoadInst>(User);
315 // Otherwise it must be a load instruction, keep track of variable
317 UsingBlocks.push_back(LI->getParent());
318 AllocaPointerVal = LI;
321 if (OnlyUsedInOneBlock) {
323 OnlyBlock = User->getParent();
324 else if (OnlyBlock != User->getParent())
325 OnlyUsedInOneBlock = false;
330 } // end of anonymous namespace
333 void PromoteMem2Reg::run() {
334 Function &F = *DF.getRoot()->getParent();
336 if (AST) PointerAllocaValues.resize(Allocas.size());
341 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
342 AllocaInst *AI = Allocas[AllocaNum];
344 assert(isAllocaPromotable(AI) &&
345 "Cannot promote non-promotable alloca!");
346 assert(AI->getParent()->getParent() == &F &&
347 "All allocas should be in the same function, which is same as DF!");
349 if (AI->use_empty()) {
350 // If there are no uses of the alloca, just delete it now.
351 if (AST) AST->deleteValue(AI);
352 AI->eraseFromParent();
354 // Remove the alloca from the Allocas list, since it has been processed
355 RemoveFromAllocasList(AllocaNum);
360 // Calculate the set of read and write-locations for each alloca. This is
361 // analogous to finding the 'uses' and 'definitions' of each variable.
362 Info.AnalyzeAlloca(AI);
364 // If there is only a single store to this value, replace any loads of
365 // it that are directly dominated by the definition with the value stored.
366 if (Info.DefiningBlocks.size() == 1) {
367 RewriteSingleStoreAlloca(AI, Info, LBI);
369 // Finally, after the scan, check to see if the store is all that is left.
370 if (Info.UsingBlocks.empty()) {
371 // Remove the (now dead) store and alloca.
372 Info.OnlyStore->eraseFromParent();
373 LBI.deleteValue(Info.OnlyStore);
375 if (AST) AST->deleteValue(AI);
376 AI->eraseFromParent();
379 // The alloca has been processed, move on.
380 RemoveFromAllocasList(AllocaNum);
387 // If the alloca is only read and written in one basic block, just perform a
388 // linear sweep over the block to eliminate it.
389 if (Info.OnlyUsedInOneBlock) {
390 PromoteSingleBlockAlloca(AI, Info, LBI);
392 // Finally, after the scan, check to see if the stores are all that is
394 if (Info.UsingBlocks.empty()) {
396 // Remove the (now dead) stores and alloca.
397 while (!AI->use_empty()) {
398 StoreInst *SI = cast<StoreInst>(AI->use_back());
399 SI->eraseFromParent();
403 if (AST) AST->deleteValue(AI);
404 AI->eraseFromParent();
407 // The alloca has been processed, move on.
408 RemoveFromAllocasList(AllocaNum);
415 // If we haven't computed a numbering for the BB's in the function, do so
417 if (BBNumbers.empty()) {
419 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
423 // If we have an AST to keep updated, remember some pointer value that is
424 // stored into the alloca.
426 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
428 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
429 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
431 // At this point, we're committed to promoting the alloca using IDF's, and
432 // the standard SSA construction algorithm. Determine which blocks need PHI
433 // nodes and see if we can optimize out some work by avoiding insertion of
435 DetermineInsertionPoint(AI, AllocaNum, Info);
439 return; // All of the allocas must have been trivial!
444 // Set the incoming values for the basic block to be null values for all of
445 // the alloca's. We do this in case there is a load of a value that has not
446 // been stored yet. In this case, it will get this null value.
448 RenamePassData::ValVector Values(Allocas.size());
449 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
450 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
452 // Walks all basic blocks in the function performing the SSA rename algorithm
453 // and inserting the phi nodes we marked as necessary
455 std::vector<RenamePassData> RenamePassWorkList;
456 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
457 while (!RenamePassWorkList.empty()) {
459 RPD.swap(RenamePassWorkList.back());
460 RenamePassWorkList.pop_back();
461 // RenamePass may add new worklist entries.
462 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
465 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
468 // Remove the allocas themselves from the function.
469 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
470 Instruction *A = Allocas[i];
472 // If there are any uses of the alloca instructions left, they must be in
473 // sections of dead code that were not processed on the dominance frontier.
474 // Just delete the users now.
477 A->replaceAllUsesWith(UndefValue::get(A->getType()));
478 if (AST) AST->deleteValue(A);
479 A->eraseFromParent();
483 // Loop over all of the PHI nodes and see if there are any that we can get
484 // rid of because they merge all of the same incoming values. This can
485 // happen due to undef values coming into the PHI nodes. This process is
486 // iterative, because eliminating one PHI node can cause others to be removed.
487 bool EliminatedAPHI = true;
488 while (EliminatedAPHI) {
489 EliminatedAPHI = false;
491 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
492 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
493 PHINode *PN = I->second;
495 // If this PHI node merges one value and/or undefs, get the value.
496 if (Value *V = PN->hasConstantValue(&DT)) {
497 if (AST && isa<PointerType>(PN->getType()))
498 AST->deleteValue(PN);
499 PN->replaceAllUsesWith(V);
500 PN->eraseFromParent();
501 NewPhiNodes.erase(I++);
502 EliminatedAPHI = true;
509 // At this point, the renamer has added entries to PHI nodes for all reachable
510 // code. Unfortunately, there may be unreachable blocks which the renamer
511 // hasn't traversed. If this is the case, the PHI nodes may not
512 // have incoming values for all predecessors. Loop over all PHI nodes we have
513 // created, inserting undef values if they are missing any incoming values.
515 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
516 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
517 // We want to do this once per basic block. As such, only process a block
518 // when we find the PHI that is the first entry in the block.
519 PHINode *SomePHI = I->second;
520 BasicBlock *BB = SomePHI->getParent();
521 if (&BB->front() != SomePHI)
524 // Only do work here if there the PHI nodes are missing incoming values. We
525 // know that all PHI nodes that were inserted in a block will have the same
526 // number of incoming values, so we can just check any of them.
527 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
530 // Get the preds for BB.
531 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
533 // Ok, now we know that all of the PHI nodes are missing entries for some
534 // basic blocks. Start by sorting the incoming predecessors for efficient
536 std::sort(Preds.begin(), Preds.end());
538 // Now we loop through all BB's which have entries in SomePHI and remove
539 // them from the Preds list.
540 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
541 // Do a log(n) search of the Preds list for the entry we want.
542 SmallVector<BasicBlock*, 16>::iterator EntIt =
543 std::lower_bound(Preds.begin(), Preds.end(),
544 SomePHI->getIncomingBlock(i));
545 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
546 "PHI node has entry for a block which is not a predecessor!");
552 // At this point, the blocks left in the preds list must have dummy
553 // entries inserted into every PHI nodes for the block. Update all the phi
554 // nodes in this block that we are inserting (there could be phis before
556 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
557 BasicBlock::iterator BBI = BB->begin();
558 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
559 SomePHI->getNumIncomingValues() == NumBadPreds) {
560 Value *UndefVal = UndefValue::get(SomePHI->getType());
561 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
562 SomePHI->addIncoming(UndefVal, Preds[pred]);
570 /// ComputeLiveInBlocks - Determine which blocks the value is live in. These
571 /// are blocks which lead to uses. Knowing this allows us to avoid inserting
572 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
574 void PromoteMem2Reg::
575 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
576 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
577 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
579 // To determine liveness, we must iterate through the predecessors of blocks
580 // where the def is live. Blocks are added to the worklist if we need to
581 // check their predecessors. Start with all the using blocks.
582 SmallVector<BasicBlock*, 64> LiveInBlockWorklist;
583 LiveInBlockWorklist.insert(LiveInBlockWorklist.end(),
584 Info.UsingBlocks.begin(), Info.UsingBlocks.end());
586 // If any of the using blocks is also a definition block, check to see if the
587 // definition occurs before or after the use. If it happens before the use,
588 // the value isn't really live-in.
589 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
590 BasicBlock *BB = LiveInBlockWorklist[i];
591 if (!DefBlocks.count(BB)) continue;
593 // Okay, this is a block that both uses and defines the value. If the first
594 // reference to the alloca is a def (store), then we know it isn't live-in.
595 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
596 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
597 if (SI->getOperand(1) != AI) continue;
599 // We found a store to the alloca before a load. The alloca is not
600 // actually live-in here.
601 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
602 LiveInBlockWorklist.pop_back();
607 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
608 if (LI->getOperand(0) != AI) continue;
610 // Okay, we found a load before a store to the alloca. It is actually
611 // live into this block.
617 // Now that we have a set of blocks where the phi is live-in, recursively add
618 // their predecessors until we find the full region the value is live.
619 while (!LiveInBlockWorklist.empty()) {
620 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
622 // The block really is live in here, insert it into the set. If already in
623 // the set, then it has already been processed.
624 if (!LiveInBlocks.insert(BB))
627 // Since the value is live into BB, it is either defined in a predecessor or
628 // live into it to. Add the preds to the worklist unless they are a
630 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
633 // The value is not live into a predecessor if it defines the value.
634 if (DefBlocks.count(P))
637 // Otherwise it is, add to the worklist.
638 LiveInBlockWorklist.push_back(P);
643 /// DetermineInsertionPoint - At this point, we're committed to promoting the
644 /// alloca using IDF's, and the standard SSA construction algorithm. Determine
645 /// which blocks need phi nodes and see if we can optimize out some work by
646 /// avoiding insertion of dead phi nodes.
647 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
650 // Unique the set of defining blocks for efficient lookup.
651 SmallPtrSet<BasicBlock*, 32> DefBlocks;
652 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
654 // Determine which blocks the value is live in. These are blocks which lead
656 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
657 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
659 // Compute the locations where PhiNodes need to be inserted. Look at the
660 // dominance frontier of EACH basic-block we have a write in.
661 unsigned CurrentVersion = 0;
662 SmallPtrSet<PHINode*, 16> InsertedPHINodes;
663 std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
664 while (!Info.DefiningBlocks.empty()) {
665 BasicBlock *BB = Info.DefiningBlocks.back();
666 Info.DefiningBlocks.pop_back();
668 // Look up the DF for this write, add it to defining blocks.
669 DominanceFrontier::const_iterator it = DF.find(BB);
670 if (it == DF.end()) continue;
672 const DominanceFrontier::DomSetType &S = it->second;
674 // In theory we don't need the indirection through the DFBlocks vector.
675 // In practice, the order of calling QueuePhiNode would depend on the
676 // (unspecified) ordering of basic blocks in the dominance frontier,
677 // which would give PHI nodes non-determinstic subscripts. Fix this by
678 // processing blocks in order of the occurance in the function.
679 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
680 PE = S.end(); P != PE; ++P) {
681 // If the frontier block is not in the live-in set for the alloca, don't
682 // bother processing it.
683 if (!LiveInBlocks.count(*P))
686 DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
689 // Sort by which the block ordering in the function.
690 if (DFBlocks.size() > 1)
691 std::sort(DFBlocks.begin(), DFBlocks.end());
693 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
694 BasicBlock *BB = DFBlocks[i].second;
695 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
696 Info.DefiningBlocks.push_back(BB);
702 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
703 /// replace any loads of it that are directly dominated by the definition with
704 /// the value stored.
705 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
707 LargeBlockInfo &LBI) {
708 StoreInst *OnlyStore = Info.OnlyStore;
709 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
710 BasicBlock *StoreBB = OnlyStore->getParent();
713 // Clear out UsingBlocks. We will reconstruct it here if needed.
714 Info.UsingBlocks.clear();
716 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
717 Instruction *UserInst = cast<Instruction>(*UI++);
718 if (!isa<LoadInst>(UserInst)) {
719 assert(UserInst == OnlyStore && "Should only have load/stores");
722 LoadInst *LI = cast<LoadInst>(UserInst);
724 // Okay, if we have a load from the alloca, we want to replace it with the
725 // only value stored to the alloca. We can do this if the value is
726 // dominated by the store. If not, we use the rest of the mem2reg machinery
727 // to insert the phi nodes as needed.
728 if (!StoringGlobalVal) { // Non-instructions are always dominated.
729 if (LI->getParent() == StoreBB) {
730 // If we have a use that is in the same block as the store, compare the
731 // indices of the two instructions to see which one came first. If the
732 // load came before the store, we can't handle it.
733 if (StoreIndex == -1)
734 StoreIndex = LBI.getInstructionIndex(OnlyStore);
736 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
737 // Can't handle this load, bail out.
738 Info.UsingBlocks.push_back(StoreBB);
742 } else if (LI->getParent() != StoreBB &&
743 !dominates(StoreBB, LI->getParent())) {
744 // If the load and store are in different blocks, use BB dominance to
745 // check their relationships. If the store doesn't dom the use, bail
747 Info.UsingBlocks.push_back(LI->getParent());
752 // Otherwise, we *can* safely rewrite this load.
753 LI->replaceAllUsesWith(OnlyStore->getOperand(0));
754 if (AST && isa<PointerType>(LI->getType()))
755 AST->deleteValue(LI);
756 LI->eraseFromParent();
763 /// StoreIndexSearchPredicate - This is a helper predicate used to search by the
764 /// first element of a pair.
765 struct StoreIndexSearchPredicate {
766 bool operator()(const std::pair<unsigned, StoreInst*> &LHS,
767 const std::pair<unsigned, StoreInst*> &RHS) {
768 return LHS.first < RHS.first;
774 /// PromoteSingleBlockAlloca - Many allocas are only used within a single basic
775 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
776 /// potentially useless PHI nodes by just performing a single linear pass over
777 /// the basic block using the Alloca.
779 /// If we cannot promote this alloca (because it is read before it is written),
780 /// return true. This is necessary in cases where, due to control flow, the
781 /// alloca is potentially undefined on some control flow paths. e.g. code like
782 /// this is potentially correct:
784 /// for (...) { if (c) { A = undef; undef = B; } }
786 /// ... so long as A is not used before undef is set.
788 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
789 LargeBlockInfo &LBI) {
790 // The trickiest case to handle is when we have large blocks. Because of this,
791 // this code is optimized assuming that large blocks happen. This does not
792 // significantly pessimize the small block case. This uses LargeBlockInfo to
793 // make it efficient to get the index of various operations in the block.
795 // Clear out UsingBlocks. We will reconstruct it here if needed.
796 Info.UsingBlocks.clear();
798 // Walk the use-def list of the alloca, getting the locations of all stores.
799 typedef SmallVector<std::pair<unsigned, StoreInst*>, 64> StoresByIndexTy;
800 StoresByIndexTy StoresByIndex;
802 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
804 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
805 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
807 // If there are no stores to the alloca, just replace any loads with undef.
808 if (StoresByIndex.empty()) {
809 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
810 if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
811 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
812 if (AST && isa<PointerType>(LI->getType()))
813 AST->deleteValue(LI);
815 LI->eraseFromParent();
820 // Sort the stores by their index, making it efficient to do a lookup with a
822 std::sort(StoresByIndex.begin(), StoresByIndex.end());
824 // Walk all of the loads from this alloca, replacing them with the nearest
825 // store above them, if any.
826 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
827 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
830 unsigned LoadIdx = LBI.getInstructionIndex(LI);
832 // Find the nearest store that has a lower than this load.
833 StoresByIndexTy::iterator I =
834 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
835 std::pair<unsigned, StoreInst*>(LoadIdx, 0),
836 StoreIndexSearchPredicate());
838 // If there is no store before this load, then we can't promote this load.
839 if (I == StoresByIndex.begin()) {
840 // Can't handle this load, bail out.
841 Info.UsingBlocks.push_back(LI->getParent());
845 // Otherwise, there was a store before this load, the load takes its value.
847 LI->replaceAllUsesWith(I->second->getOperand(0));
848 if (AST && isa<PointerType>(LI->getType()))
849 AST->deleteValue(LI);
850 LI->eraseFromParent();
856 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
857 // Alloca returns true if there wasn't already a phi-node for that variable
859 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
861 SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
862 // Look up the basic-block in question.
863 PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
865 // If the BB already has a phi node added for the i'th alloca then we're done!
866 if (PN) return false;
868 // Create a PhiNode using the dereferenced type... and add the phi-node to the
870 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(),
871 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
874 PhiToAllocaMap[PN] = AllocaNo;
875 PN->reserveOperandSpace(getNumPreds(BB));
877 InsertedPHINodes.insert(PN);
879 if (AST && isa<PointerType>(PN->getType()))
880 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
885 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
886 // stores to the allocas which we are promoting. IncomingVals indicates what
887 // value each Alloca contains on exit from the predecessor block Pred.
889 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
890 RenamePassData::ValVector &IncomingVals,
891 std::vector<RenamePassData> &Worklist) {
893 // If we are inserting any phi nodes into this BB, they will already be in the
895 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
896 // If we have PHI nodes to update, compute the number of edges from Pred to
898 if (PhiToAllocaMap.count(APN)) {
899 // We want to be able to distinguish between PHI nodes being inserted by
900 // this invocation of mem2reg from those phi nodes that already existed in
901 // the IR before mem2reg was run. We determine that APN is being inserted
902 // because it is missing incoming edges. All other PHI nodes being
903 // inserted by this pass of mem2reg will have the same number of incoming
904 // operands so far. Remember this count.
905 unsigned NewPHINumOperands = APN->getNumOperands();
907 unsigned NumEdges = 0;
908 for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
911 assert(NumEdges && "Must be at least one edge from Pred to BB!");
913 // Add entries for all the phis.
914 BasicBlock::iterator PNI = BB->begin();
916 unsigned AllocaNo = PhiToAllocaMap[APN];
918 // Add N incoming values to the PHI node.
919 for (unsigned i = 0; i != NumEdges; ++i)
920 APN->addIncoming(IncomingVals[AllocaNo], Pred);
922 // The currently active variable for this block is now the PHI.
923 IncomingVals[AllocaNo] = APN;
925 // Get the next phi node.
927 APN = dyn_cast<PHINode>(PNI);
930 // Verify that it is missing entries. If not, it is not being inserted
931 // by this mem2reg invocation so we want to ignore it.
932 } while (APN->getNumOperands() == NewPHINumOperands);
936 // Don't revisit blocks.
937 if (!Visited.insert(BB)) return;
939 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
940 Instruction *I = II++; // get the instruction, increment iterator
942 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
943 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
946 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
947 if (AI == AllocaLookup.end()) continue;
949 Value *V = IncomingVals[AI->second];
951 // Anything using the load now uses the current value.
952 LI->replaceAllUsesWith(V);
953 if (AST && isa<PointerType>(LI->getType()))
954 AST->deleteValue(LI);
955 BB->getInstList().erase(LI);
956 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
957 // Delete this instruction and mark the name as the current holder of the
959 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
962 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
963 if (ai == AllocaLookup.end())
966 // what value were we writing?
967 IncomingVals[ai->second] = SI->getOperand(0);
968 BB->getInstList().erase(SI);
972 // 'Recurse' to our successors.
973 succ_iterator I = succ_begin(BB), E = succ_end(BB);
976 // Keep track of the successors so we don't visit the same successor twice
977 SmallPtrSet<BasicBlock*, 8> VisitedSuccs;
979 // Handle the first successor without using the worklist.
980 VisitedSuccs.insert(*I);
986 if (VisitedSuccs.insert(*I))
987 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
992 /// PromoteMemToReg - Promote the specified list of alloca instructions into
993 /// scalar registers, inserting PHI nodes as appropriate. This function makes
994 /// use of DominanceFrontier information. This function does not modify the CFG
995 /// of the function at all. All allocas must be from the same function.
997 /// If AST is specified, the specified tracker is updated to reflect changes
1000 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
1001 DominatorTree &DT, DominanceFrontier &DF,
1002 LLVMContext &Context, AliasSetTracker *AST) {
1003 // If there is nothing to do, bail out...
1004 if (Allocas.empty()) return;
1006 PromoteMem2Reg(Allocas, DT, DF, AST, Context).run();