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 iterated dominator frontiers to place PHI nodes, then
13 // traversing the function in depth-first order to rewrite loads and stores as
16 // The algorithm used here is based on:
18 // Sreedhar and Gao. A linear time algorithm for placing phi-nodes.
19 // In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of
20 // Programming Languages
21 // POPL '95. ACM, New York, NY, 62-73.
23 // It has been modified to not explicitly use the DJ graph data structure and to
24 // directly compute pruned SSA using per-variable liveness information.
26 //===----------------------------------------------------------------------===//
28 #define DEBUG_TYPE "mem2reg"
29 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/Hashing.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Analysis/Dominators.h"
38 #include "llvm/Analysis/InstructionSimplify.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/DIBuilder.h"
41 #include "llvm/DebugInfo.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Transforms/Utils/Local.h"
54 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
55 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
56 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
57 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
61 struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
62 typedef std::pair<BasicBlock*, unsigned> EltTy;
63 static inline EltTy getEmptyKey() {
64 return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
66 static inline EltTy getTombstoneKey() {
67 return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
69 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
70 using llvm::hash_value;
71 return static_cast<unsigned>(hash_value(Val));
73 static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
79 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
80 // FIXME: If the memory unit is of pointer or integer type, we can permit
81 // assignments to subsections of the memory unit.
83 // Only allow direct and non-volatile loads and stores...
84 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
85 UI != UE; ++UI) { // Loop over all of the uses of the alloca
87 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
88 // Note that atomic loads can be transformed; atomic semantics do
89 // not have any meaning for a local alloca.
92 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
93 if (SI->getOperand(0) == AI)
94 return false; // Don't allow a store OF the AI, only INTO the AI.
95 // Note that atomic stores can be transformed; atomic semantics do
96 // not have any meaning for a local alloca.
99 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
100 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
101 II->getIntrinsicID() != Intrinsic::lifetime_end)
103 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
104 if (BCI->getType() != Type::getInt8PtrTy(U->getContext()))
106 if (!onlyUsedByLifetimeMarkers(BCI))
108 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
109 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext()))
111 if (!GEPI->hasAllZeroIndices())
113 if (!onlyUsedByLifetimeMarkers(GEPI))
126 // Data package used by RenamePass()
127 class RenamePassData {
129 typedef std::vector<Value *> ValVector;
131 RenamePassData() : BB(NULL), Pred(NULL), Values() {}
132 RenamePassData(BasicBlock *B, BasicBlock *P,
133 const ValVector &V) : BB(B), Pred(P), Values(V) {}
138 void swap(RenamePassData &RHS) {
139 std::swap(BB, RHS.BB);
140 std::swap(Pred, RHS.Pred);
141 Values.swap(RHS.Values);
145 /// \brief This assigns and keeps a per-bb relative ordering of load/store
146 /// instructions in the block that directly load or store an alloca.
148 /// This functionality is important because it avoids scanning large basic
149 /// blocks multiple times when promoting many allocas in the same block.
150 class LargeBlockInfo {
151 /// \brief For each instruction that we track, keep the index of the
154 /// The index starts out as the number of the instruction from the start of
156 DenseMap<const Instruction *, unsigned> InstNumbers;
159 /// This code only looks at accesses to allocas.
160 static bool isInterestingInstruction(const Instruction *I) {
161 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
162 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
165 /// Get or calculate the index of the specified instruction.
166 unsigned getInstructionIndex(const Instruction *I) {
167 assert(isInterestingInstruction(I) &&
168 "Not a load/store to/from an alloca?");
170 // If we already have this instruction number, return it.
171 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
172 if (It != InstNumbers.end()) return It->second;
174 // Scan the whole block to get the instruction. This accumulates
175 // information for every interesting instruction in the block, in order to
176 // avoid gratuitus rescans.
177 const BasicBlock *BB = I->getParent();
179 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end();
181 if (isInterestingInstruction(BBI))
182 InstNumbers[BBI] = InstNo++;
183 It = InstNumbers.find(I);
185 assert(It != InstNumbers.end() && "Didn't insert instruction?");
189 void deleteValue(const Instruction *I) {
190 InstNumbers.erase(I);
198 struct PromoteMem2Reg {
199 /// The alloca instructions being promoted.
200 std::vector<AllocaInst*> Allocas;
204 /// An AliasSetTracker object to update. If null, don't update it.
205 AliasSetTracker *AST;
207 /// Reverse mapping of Allocas.
208 DenseMap<AllocaInst*, unsigned> AllocaLookup;
210 /// \brief The PhiNodes we're adding.
212 /// That map is used to simplify some Phi nodes as we iterate over it, so
213 /// it should have deterministic iterators. We could use a MapVector, but
214 /// since we already maintain a map from BasicBlock* to a stable numbering
215 /// (BBNumbers), the DenseMap is more efficient (also supports removal).
216 DenseMap<std::pair<unsigned, unsigned>, PHINode*> NewPhiNodes;
218 /// For each PHI node, keep track of which entry in Allocas it corresponds
220 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
222 /// If we are updating an AliasSetTracker, then for each alloca that is of
223 /// pointer type, we keep track of what to copyValue to the inserted PHI
225 std::vector<Value*> PointerAllocaValues;
227 /// For each alloca, we keep track of the dbg.declare intrinsic that
228 /// describes it, if any, so that we can convert it to a dbg.value
229 /// intrinsic if the alloca gets promoted.
230 SmallVector<DbgDeclareInst*, 8> AllocaDbgDeclares;
232 /// The set of basic blocks the renamer has already visited.
234 SmallPtrSet<BasicBlock*, 16> Visited;
236 /// Contains a stable numbering of basic blocks to avoid non-determinstic
238 DenseMap<BasicBlock*, unsigned> BBNumbers;
240 /// Maps DomTreeNodes to their level in the dominator tree.
241 DenseMap<DomTreeNode*, unsigned> DomLevels;
243 /// Lazily compute the number of predecessors a block has.
244 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
246 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
247 AliasSetTracker *ast)
248 : Allocas(A), DT(dt), DIB(0), AST(ast) {}
255 /// Return true if BB1 dominates BB2 using the DominatorTree.
256 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
257 return DT.dominates(BB1, BB2);
261 void RemoveFromAllocasList(unsigned &AllocaIdx) {
262 Allocas[AllocaIdx] = Allocas.back();
267 unsigned getNumPreds(const BasicBlock *BB) {
268 unsigned &NP = BBNumPreds[BB];
270 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
274 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
276 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
277 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
278 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
280 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
281 LargeBlockInfo &LBI);
282 void PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
283 LargeBlockInfo &LBI);
285 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
286 RenamePassData::ValVector &IncVals,
287 std::vector<RenamePassData> &Worklist);
288 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
292 SmallVector<BasicBlock*, 32> DefiningBlocks;
293 SmallVector<BasicBlock*, 32> UsingBlocks;
295 StoreInst *OnlyStore;
296 BasicBlock *OnlyBlock;
297 bool OnlyUsedInOneBlock;
299 Value *AllocaPointerVal;
300 DbgDeclareInst *DbgDeclare;
303 DefiningBlocks.clear();
307 OnlyUsedInOneBlock = true;
308 AllocaPointerVal = 0;
312 /// Scan the uses of the specified alloca, filling in the AllocaInfo used
313 /// by the rest of the pass to reason about the uses of this alloca.
314 void AnalyzeAlloca(AllocaInst *AI) {
317 // As we scan the uses of the alloca instruction, keep track of stores,
318 // and decide whether all of the loads and stores to the alloca are within
319 // the same basic block.
320 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
322 Instruction *User = cast<Instruction>(*UI++);
324 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
325 // Remember the basic blocks which define new values for the alloca
326 DefiningBlocks.push_back(SI->getParent());
327 AllocaPointerVal = SI->getOperand(0);
330 LoadInst *LI = cast<LoadInst>(User);
331 // Otherwise it must be a load instruction, keep track of variable
333 UsingBlocks.push_back(LI->getParent());
334 AllocaPointerVal = LI;
337 if (OnlyUsedInOneBlock) {
339 OnlyBlock = User->getParent();
340 else if (OnlyBlock != User->getParent())
341 OnlyUsedInOneBlock = false;
345 DbgDeclare = FindAllocaDbgDeclare(AI);
349 typedef std::pair<DomTreeNode*, unsigned> DomTreeNodePair;
351 struct DomTreeNodeCompare {
352 bool operator()(const DomTreeNodePair &LHS, const DomTreeNodePair &RHS) {
353 return LHS.second < RHS.second;
356 } // end of anonymous namespace
358 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
359 // Knowing that this alloca is promotable, we know that it's safe to kill all
360 // instructions except for load and store.
362 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
364 Instruction *I = cast<Instruction>(*UI);
366 if (isa<LoadInst>(I) || isa<StoreInst>(I))
369 if (!I->getType()->isVoidTy()) {
370 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
371 // Follow the use/def chain to erase them now instead of leaving it for
372 // dead code elimination later.
373 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
375 Instruction *Inst = cast<Instruction>(*UI);
377 Inst->eraseFromParent();
380 I->eraseFromParent();
384 void PromoteMem2Reg::run() {
385 Function &F = *DT.getRoot()->getParent();
387 if (AST) PointerAllocaValues.resize(Allocas.size());
388 AllocaDbgDeclares.resize(Allocas.size());
393 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
394 AllocaInst *AI = Allocas[AllocaNum];
396 assert(isAllocaPromotable(AI) &&
397 "Cannot promote non-promotable alloca!");
398 assert(AI->getParent()->getParent() == &F &&
399 "All allocas should be in the same function, which is same as DF!");
401 removeLifetimeIntrinsicUsers(AI);
403 if (AI->use_empty()) {
404 // If there are no uses of the alloca, just delete it now.
405 if (AST) AST->deleteValue(AI);
406 AI->eraseFromParent();
408 // Remove the alloca from the Allocas list, since it has been processed
409 RemoveFromAllocasList(AllocaNum);
414 // Calculate the set of read and write-locations for each alloca. This is
415 // analogous to finding the 'uses' and 'definitions' of each variable.
416 Info.AnalyzeAlloca(AI);
418 // If there is only a single store to this value, replace any loads of
419 // it that are directly dominated by the definition with the value stored.
420 if (Info.DefiningBlocks.size() == 1) {
421 RewriteSingleStoreAlloca(AI, Info, LBI);
423 // Finally, after the scan, check to see if the store is all that is left.
424 if (Info.UsingBlocks.empty()) {
425 // Record debuginfo for the store and remove the declaration's
427 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
429 DIB = new DIBuilder(*DDI->getParent()->getParent()->getParent());
430 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, *DIB);
431 DDI->eraseFromParent();
433 // Remove the (now dead) store and alloca.
434 Info.OnlyStore->eraseFromParent();
435 LBI.deleteValue(Info.OnlyStore);
437 if (AST) AST->deleteValue(AI);
438 AI->eraseFromParent();
441 // The alloca has been processed, move on.
442 RemoveFromAllocasList(AllocaNum);
449 // If the alloca is only read and written in one basic block, just perform a
450 // linear sweep over the block to eliminate it.
451 if (Info.OnlyUsedInOneBlock) {
452 PromoteSingleBlockAlloca(AI, Info, LBI);
454 // Finally, after the scan, check to see if the stores are all that is
456 if (Info.UsingBlocks.empty()) {
458 // Remove the (now dead) stores and alloca.
459 while (!AI->use_empty()) {
460 StoreInst *SI = cast<StoreInst>(AI->use_back());
461 // Record debuginfo for the store before removing it.
462 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
464 DIB = new DIBuilder(*SI->getParent()->getParent()->getParent());
465 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
467 SI->eraseFromParent();
471 if (AST) AST->deleteValue(AI);
472 AI->eraseFromParent();
475 // The alloca has been processed, move on.
476 RemoveFromAllocasList(AllocaNum);
478 // The alloca's debuginfo can be removed as well.
479 if (DbgDeclareInst *DDI = Info.DbgDeclare)
480 DDI->eraseFromParent();
487 // If we haven't computed dominator tree levels, do so now.
488 if (DomLevels.empty()) {
489 SmallVector<DomTreeNode*, 32> Worklist;
491 DomTreeNode *Root = DT.getRootNode();
493 Worklist.push_back(Root);
495 while (!Worklist.empty()) {
496 DomTreeNode *Node = Worklist.pop_back_val();
497 unsigned ChildLevel = DomLevels[Node] + 1;
498 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
500 DomLevels[*CI] = ChildLevel;
501 Worklist.push_back(*CI);
506 // If we haven't computed a numbering for the BB's in the function, do so
508 if (BBNumbers.empty()) {
510 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
514 // If we have an AST to keep updated, remember some pointer value that is
515 // stored into the alloca.
517 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
519 // Remember the dbg.declare intrinsic describing this alloca, if any.
520 if (Info.DbgDeclare) AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
522 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
523 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
525 // At this point, we're committed to promoting the alloca using IDF's, and
526 // the standard SSA construction algorithm. Determine which blocks need PHI
527 // nodes and see if we can optimize out some work by avoiding insertion of
529 DetermineInsertionPoint(AI, AllocaNum, Info);
533 return; // All of the allocas must have been trivial!
538 // Set the incoming values for the basic block to be null values for all of
539 // the alloca's. We do this in case there is a load of a value that has not
540 // been stored yet. In this case, it will get this null value.
542 RenamePassData::ValVector Values(Allocas.size());
543 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
544 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
546 // Walks all basic blocks in the function performing the SSA rename algorithm
547 // and inserting the phi nodes we marked as necessary
549 std::vector<RenamePassData> RenamePassWorkList;
550 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
553 RPD.swap(RenamePassWorkList.back());
554 RenamePassWorkList.pop_back();
555 // RenamePass may add new worklist entries.
556 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
557 } while (!RenamePassWorkList.empty());
559 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
562 // Remove the allocas themselves from the function.
563 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
564 Instruction *A = Allocas[i];
566 // If there are any uses of the alloca instructions left, they must be in
567 // unreachable basic blocks that were not processed by walking the dominator
568 // tree. Just delete the users now.
570 A->replaceAllUsesWith(UndefValue::get(A->getType()));
571 if (AST) AST->deleteValue(A);
572 A->eraseFromParent();
575 // Remove alloca's dbg.declare instrinsics from the function.
576 for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
577 if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
578 DDI->eraseFromParent();
580 // Loop over all of the PHI nodes and see if there are any that we can get
581 // rid of because they merge all of the same incoming values. This can
582 // happen due to undef values coming into the PHI nodes. This process is
583 // iterative, because eliminating one PHI node can cause others to be removed.
584 bool EliminatedAPHI = true;
585 while (EliminatedAPHI) {
586 EliminatedAPHI = false;
588 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
589 // simplify and RAUW them as we go. If it was not, we could add uses to
590 // the values we replace with in a non deterministic order, thus creating
591 // non deterministic def->use chains.
592 for (DenseMap<std::pair<unsigned, unsigned>, PHINode*>::iterator I =
593 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
594 PHINode *PN = I->second;
596 // If this PHI node merges one value and/or undefs, get the value.
597 if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
598 if (AST && PN->getType()->isPointerTy())
599 AST->deleteValue(PN);
600 PN->replaceAllUsesWith(V);
601 PN->eraseFromParent();
602 NewPhiNodes.erase(I++);
603 EliminatedAPHI = true;
610 // At this point, the renamer has added entries to PHI nodes for all reachable
611 // code. Unfortunately, there may be unreachable blocks which the renamer
612 // hasn't traversed. If this is the case, the PHI nodes may not
613 // have incoming values for all predecessors. Loop over all PHI nodes we have
614 // created, inserting undef values if they are missing any incoming values.
616 for (DenseMap<std::pair<unsigned, unsigned>, PHINode*>::iterator I =
617 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
618 // We want to do this once per basic block. As such, only process a block
619 // when we find the PHI that is the first entry in the block.
620 PHINode *SomePHI = I->second;
621 BasicBlock *BB = SomePHI->getParent();
622 if (&BB->front() != SomePHI)
625 // Only do work here if there the PHI nodes are missing incoming values. We
626 // know that all PHI nodes that were inserted in a block will have the same
627 // number of incoming values, so we can just check any of them.
628 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
631 // Get the preds for BB.
632 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
634 // Ok, now we know that all of the PHI nodes are missing entries for some
635 // basic blocks. Start by sorting the incoming predecessors for efficient
637 std::sort(Preds.begin(), Preds.end());
639 // Now we loop through all BB's which have entries in SomePHI and remove
640 // them from the Preds list.
641 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
642 // Do a log(n) search of the Preds list for the entry we want.
643 SmallVectorImpl<BasicBlock *>::iterator EntIt =
644 std::lower_bound(Preds.begin(), Preds.end(),
645 SomePHI->getIncomingBlock(i));
646 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
647 "PHI node has entry for a block which is not a predecessor!");
653 // At this point, the blocks left in the preds list must have dummy
654 // entries inserted into every PHI nodes for the block. Update all the phi
655 // nodes in this block that we are inserting (there could be phis before
657 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
658 BasicBlock::iterator BBI = BB->begin();
659 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
660 SomePHI->getNumIncomingValues() == NumBadPreds) {
661 Value *UndefVal = UndefValue::get(SomePHI->getType());
662 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
663 SomePHI->addIncoming(UndefVal, Preds[pred]);
671 /// \brief Determine which blocks the value is live in.
673 /// These are blocks which lead to uses. Knowing this allows us to avoid
674 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
675 /// inserted phi nodes would be dead).
676 void PromoteMem2Reg::
677 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
678 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
679 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
681 // To determine liveness, we must iterate through the predecessors of blocks
682 // where the def is live. Blocks are added to the worklist if we need to
683 // check their predecessors. Start with all the using blocks.
684 SmallVector<BasicBlock*, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
685 Info.UsingBlocks.end());
687 // If any of the using blocks is also a definition block, check to see if the
688 // definition occurs before or after the use. If it happens before the use,
689 // the value isn't really live-in.
690 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
691 BasicBlock *BB = LiveInBlockWorklist[i];
692 if (!DefBlocks.count(BB)) continue;
694 // Okay, this is a block that both uses and defines the value. If the first
695 // reference to the alloca is a def (store), then we know it isn't live-in.
696 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
697 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
698 if (SI->getOperand(1) != AI) continue;
700 // We found a store to the alloca before a load. The alloca is not
701 // actually live-in here.
702 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
703 LiveInBlockWorklist.pop_back();
708 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
709 if (LI->getOperand(0) != AI) continue;
711 // Okay, we found a load before a store to the alloca. It is actually
712 // live into this block.
718 // Now that we have a set of blocks where the phi is live-in, recursively add
719 // their predecessors until we find the full region the value is live.
720 while (!LiveInBlockWorklist.empty()) {
721 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
723 // The block really is live in here, insert it into the set. If already in
724 // the set, then it has already been processed.
725 if (!LiveInBlocks.insert(BB))
728 // Since the value is live into BB, it is either defined in a predecessor or
729 // live into it to. Add the preds to the worklist unless they are a
731 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
734 // The value is not live into a predecessor if it defines the value.
735 if (DefBlocks.count(P))
738 // Otherwise it is, add to the worklist.
739 LiveInBlockWorklist.push_back(P);
744 /// At this point, we're committed to promoting the alloca using IDF's, and the
745 /// standard SSA construction algorithm. Determine which blocks need phi nodes
746 /// and see if we can optimize out some work by avoiding insertion of dead phi
748 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
750 // Unique the set of defining blocks for efficient lookup.
751 SmallPtrSet<BasicBlock*, 32> DefBlocks;
752 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
754 // Determine which blocks the value is live in. These are blocks which lead
756 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
757 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
759 // Use a priority queue keyed on dominator tree level so that inserted nodes
760 // are handled from the bottom of the dominator tree upwards.
761 typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
762 DomTreeNodeCompare> IDFPriorityQueue;
765 for (SmallPtrSet<BasicBlock*, 32>::const_iterator I = DefBlocks.begin(),
766 E = DefBlocks.end(); I != E; ++I) {
767 if (DomTreeNode *Node = DT.getNode(*I))
768 PQ.push(std::make_pair(Node, DomLevels[Node]));
771 SmallVector<std::pair<unsigned, BasicBlock*>, 32> DFBlocks;
772 SmallPtrSet<DomTreeNode*, 32> Visited;
773 SmallVector<DomTreeNode*, 32> Worklist;
774 while (!PQ.empty()) {
775 DomTreeNodePair RootPair = PQ.top();
777 DomTreeNode *Root = RootPair.first;
778 unsigned RootLevel = RootPair.second;
780 // Walk all dominator tree children of Root, inspecting their CFG edges with
781 // targets elsewhere on the dominator tree. Only targets whose level is at
782 // most Root's level are added to the iterated dominance frontier of the
786 Worklist.push_back(Root);
788 while (!Worklist.empty()) {
789 DomTreeNode *Node = Worklist.pop_back_val();
790 BasicBlock *BB = Node->getBlock();
792 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
794 DomTreeNode *SuccNode = DT.getNode(*SI);
796 // Quickly skip all CFG edges that are also dominator tree edges instead
797 // of catching them below.
798 if (SuccNode->getIDom() == Node)
801 unsigned SuccLevel = DomLevels[SuccNode];
802 if (SuccLevel > RootLevel)
805 if (!Visited.insert(SuccNode))
808 BasicBlock *SuccBB = SuccNode->getBlock();
809 if (!LiveInBlocks.count(SuccBB))
812 DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
813 if (!DefBlocks.count(SuccBB))
814 PQ.push(std::make_pair(SuccNode, SuccLevel));
817 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
819 if (!Visited.count(*CI))
820 Worklist.push_back(*CI);
825 if (DFBlocks.size() > 1)
826 std::sort(DFBlocks.begin(), DFBlocks.end());
828 unsigned CurrentVersion = 0;
829 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
830 QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
833 /// If there is only a single store to this value, replace any loads of it that
834 /// are directly dominated by the definition with the value stored.
835 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
837 LargeBlockInfo &LBI) {
838 StoreInst *OnlyStore = Info.OnlyStore;
839 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
840 BasicBlock *StoreBB = OnlyStore->getParent();
843 // Clear out UsingBlocks. We will reconstruct it here if needed.
844 Info.UsingBlocks.clear();
846 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
847 Instruction *UserInst = cast<Instruction>(*UI++);
848 if (!isa<LoadInst>(UserInst)) {
849 assert(UserInst == OnlyStore && "Should only have load/stores");
852 LoadInst *LI = cast<LoadInst>(UserInst);
854 // Okay, if we have a load from the alloca, we want to replace it with the
855 // only value stored to the alloca. We can do this if the value is
856 // dominated by the store. If not, we use the rest of the mem2reg machinery
857 // to insert the phi nodes as needed.
858 if (!StoringGlobalVal) { // Non-instructions are always dominated.
859 if (LI->getParent() == StoreBB) {
860 // If we have a use that is in the same block as the store, compare the
861 // indices of the two instructions to see which one came first. If the
862 // load came before the store, we can't handle it.
863 if (StoreIndex == -1)
864 StoreIndex = LBI.getInstructionIndex(OnlyStore);
866 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
867 // Can't handle this load, bail out.
868 Info.UsingBlocks.push_back(StoreBB);
872 } else if (LI->getParent() != StoreBB &&
873 !dominates(StoreBB, LI->getParent())) {
874 // If the load and store are in different blocks, use BB dominance to
875 // check their relationships. If the store doesn't dom the use, bail
877 Info.UsingBlocks.push_back(LI->getParent());
882 // Otherwise, we *can* safely rewrite this load.
883 Value *ReplVal = OnlyStore->getOperand(0);
884 // If the replacement value is the load, this must occur in unreachable
887 ReplVal = UndefValue::get(LI->getType());
888 LI->replaceAllUsesWith(ReplVal);
889 if (AST && LI->getType()->isPointerTy())
890 AST->deleteValue(LI);
891 LI->eraseFromParent();
898 /// This is a helper predicate used to search by the first element of a pair.
899 struct StoreIndexSearchPredicate {
900 bool operator()(const std::pair<unsigned, StoreInst*> &LHS,
901 const std::pair<unsigned, StoreInst*> &RHS) {
902 return LHS.first < RHS.first;
908 /// Many allocas are only used within a single basic block. If this is the
909 /// case, avoid traversing the CFG and inserting a lot of potentially useless
910 /// PHI nodes by just performing a single linear pass over the basic block
911 /// using the Alloca.
913 /// If we cannot promote this alloca (because it is read before it is written),
914 /// return true. This is necessary in cases where, due to control flow, the
915 /// alloca is potentially undefined on some control flow paths. e.g. code like
916 /// this is potentially correct:
918 /// for (...) { if (c) { A = undef; undef = B; } }
920 /// ... so long as A is not used before undef is set.
921 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
922 LargeBlockInfo &LBI) {
923 // The trickiest case to handle is when we have large blocks. Because of this,
924 // this code is optimized assuming that large blocks happen. This does not
925 // significantly pessimize the small block case. This uses LargeBlockInfo to
926 // make it efficient to get the index of various operations in the block.
928 // Clear out UsingBlocks. We will reconstruct it here if needed.
929 Info.UsingBlocks.clear();
931 // Walk the use-def list of the alloca, getting the locations of all stores.
932 typedef SmallVector<std::pair<unsigned, StoreInst*>, 64> StoresByIndexTy;
933 StoresByIndexTy StoresByIndex;
935 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
937 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
938 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
940 // If there are no stores to the alloca, just replace any loads with undef.
941 if (StoresByIndex.empty()) {
942 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
943 if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
944 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
945 if (AST && LI->getType()->isPointerTy())
946 AST->deleteValue(LI);
948 LI->eraseFromParent();
953 // Sort the stores by their index, making it efficient to do a lookup with a
955 std::sort(StoresByIndex.begin(), StoresByIndex.end());
957 // Walk all of the loads from this alloca, replacing them with the nearest
958 // store above them, if any.
959 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
960 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
963 unsigned LoadIdx = LBI.getInstructionIndex(LI);
965 // Find the nearest store that has a lower than this load.
966 StoresByIndexTy::iterator I =
967 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
968 std::pair<unsigned, StoreInst*>(LoadIdx, static_cast<StoreInst*>(0)),
969 StoreIndexSearchPredicate());
971 // If there is no store before this load, then we can't promote this load.
972 if (I == StoresByIndex.begin()) {
973 // Can't handle this load, bail out.
974 Info.UsingBlocks.push_back(LI->getParent());
978 // Otherwise, there was a store before this load, the load takes its value.
980 LI->replaceAllUsesWith(I->second->getOperand(0));
981 if (AST && LI->getType()->isPointerTy())
982 AST->deleteValue(LI);
983 LI->eraseFromParent();
988 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
990 /// Returns true if there wasn't already a phi-node for that variable
991 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
993 // Look up the basic-block in question.
994 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
996 // If the BB already has a phi node added for the i'th alloca then we're done!
997 if (PN) return false;
999 // Create a PhiNode using the dereferenced type... and add the phi-node to the
1001 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
1002 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
1005 PhiToAllocaMap[PN] = AllocaNo;
1007 if (AST && PN->getType()->isPointerTy())
1008 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
1013 /// \brief Recursively traverse the CFG of the function, renaming loads and
1014 /// stores to the allocas which we are promoting.
1016 /// IncomingVals indicates what value each Alloca contains on exit from the
1017 /// predecessor block Pred.
1018 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
1019 RenamePassData::ValVector &IncomingVals,
1020 std::vector<RenamePassData> &Worklist) {
1022 // If we are inserting any phi nodes into this BB, they will already be in the
1024 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1025 // If we have PHI nodes to update, compute the number of edges from Pred to
1027 if (PhiToAllocaMap.count(APN)) {
1028 // We want to be able to distinguish between PHI nodes being inserted by
1029 // this invocation of mem2reg from those phi nodes that already existed in
1030 // the IR before mem2reg was run. We determine that APN is being inserted
1031 // because it is missing incoming edges. All other PHI nodes being
1032 // inserted by this pass of mem2reg will have the same number of incoming
1033 // operands so far. Remember this count.
1034 unsigned NewPHINumOperands = APN->getNumOperands();
1036 unsigned NumEdges = 0;
1037 for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
1040 assert(NumEdges && "Must be at least one edge from Pred to BB!");
1042 // Add entries for all the phis.
1043 BasicBlock::iterator PNI = BB->begin();
1045 unsigned AllocaNo = PhiToAllocaMap[APN];
1047 // Add N incoming values to the PHI node.
1048 for (unsigned i = 0; i != NumEdges; ++i)
1049 APN->addIncoming(IncomingVals[AllocaNo], Pred);
1051 // The currently active variable for this block is now the PHI.
1052 IncomingVals[AllocaNo] = APN;
1054 // Get the next phi node.
1056 APN = dyn_cast<PHINode>(PNI);
1057 if (APN == 0) break;
1059 // Verify that it is missing entries. If not, it is not being inserted
1060 // by this mem2reg invocation so we want to ignore it.
1061 } while (APN->getNumOperands() == NewPHINumOperands);
1065 // Don't revisit blocks.
1066 if (!Visited.insert(BB)) return;
1068 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
1069 Instruction *I = II++; // get the instruction, increment iterator
1071 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1072 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1075 DenseMap<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
1076 if (AI == AllocaLookup.end()) continue;
1078 Value *V = IncomingVals[AI->second];
1080 // Anything using the load now uses the current value.
1081 LI->replaceAllUsesWith(V);
1082 if (AST && LI->getType()->isPointerTy())
1083 AST->deleteValue(LI);
1084 BB->getInstList().erase(LI);
1085 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1086 // Delete this instruction and mark the name as the current holder of the
1088 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1089 if (!Dest) continue;
1091 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1092 if (ai == AllocaLookup.end())
1095 // what value were we writing?
1096 IncomingVals[ai->second] = SI->getOperand(0);
1097 // Record debuginfo for the store before removing it.
1098 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second]) {
1100 DIB = new DIBuilder(*SI->getParent()->getParent()->getParent());
1101 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1103 BB->getInstList().erase(SI);
1107 // 'Recurse' to our successors.
1108 succ_iterator I = succ_begin(BB), E = succ_end(BB);
1111 // Keep track of the successors so we don't visit the same successor twice
1112 SmallPtrSet<BasicBlock*, 8> VisitedSuccs;
1114 // Handle the first successor without using the worklist.
1115 VisitedSuccs.insert(*I);
1121 if (VisitedSuccs.insert(*I))
1122 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1127 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
1128 DominatorTree &DT, AliasSetTracker *AST) {
1129 // If there is nothing to do, bail out...
1130 if (Allocas.empty()) return;
1132 PromoteMem2Reg(Allocas, DT, AST).run();