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");
59 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
60 // FIXME: If the memory unit is of pointer or integer type, we can permit
61 // assignments to subsections of the memory unit.
63 // Only allow direct and non-volatile loads and stores...
64 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
65 UI != UE; ++UI) { // Loop over all of the uses of the alloca
67 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
68 // Note that atomic loads can be transformed; atomic semantics do
69 // not have any meaning for a local alloca.
72 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
73 if (SI->getOperand(0) == AI)
74 return false; // Don't allow a store OF the AI, only INTO the AI.
75 // Note that atomic stores can be transformed; atomic semantics do
76 // not have any meaning for a local alloca.
79 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
80 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
81 II->getIntrinsicID() != Intrinsic::lifetime_end)
83 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
84 if (BCI->getType() != Type::getInt8PtrTy(U->getContext()))
86 if (!onlyUsedByLifetimeMarkers(BCI))
88 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
89 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext()))
91 if (!GEPI->hasAllZeroIndices())
93 if (!onlyUsedByLifetimeMarkers(GEPI))
106 SmallVector<BasicBlock *, 32> DefiningBlocks;
107 SmallVector<BasicBlock *, 32> UsingBlocks;
109 StoreInst *OnlyStore;
110 BasicBlock *OnlyBlock;
111 bool OnlyUsedInOneBlock;
113 Value *AllocaPointerVal;
114 DbgDeclareInst *DbgDeclare;
117 DefiningBlocks.clear();
121 OnlyUsedInOneBlock = true;
122 AllocaPointerVal = 0;
126 /// Scan the uses of the specified alloca, filling in the AllocaInfo used
127 /// by the rest of the pass to reason about the uses of this alloca.
128 void AnalyzeAlloca(AllocaInst *AI) {
131 // As we scan the uses of the alloca instruction, keep track of stores,
132 // and decide whether all of the loads and stores to the alloca are within
133 // the same basic block.
134 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
136 Instruction *User = cast<Instruction>(*UI++);
138 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
139 // Remember the basic blocks which define new values for the alloca
140 DefiningBlocks.push_back(SI->getParent());
141 AllocaPointerVal = SI->getOperand(0);
144 LoadInst *LI = cast<LoadInst>(User);
145 // Otherwise it must be a load instruction, keep track of variable
147 UsingBlocks.push_back(LI->getParent());
148 AllocaPointerVal = LI;
151 if (OnlyUsedInOneBlock) {
153 OnlyBlock = User->getParent();
154 else if (OnlyBlock != User->getParent())
155 OnlyUsedInOneBlock = false;
159 DbgDeclare = FindAllocaDbgDeclare(AI);
163 // Data package used by RenamePass()
164 class RenamePassData {
166 typedef std::vector<Value *> ValVector;
168 RenamePassData() : BB(NULL), Pred(NULL), Values() {}
169 RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
170 : BB(B), Pred(P), Values(V) {}
175 void swap(RenamePassData &RHS) {
176 std::swap(BB, RHS.BB);
177 std::swap(Pred, RHS.Pred);
178 Values.swap(RHS.Values);
182 /// \brief This assigns and keeps a per-bb relative ordering of load/store
183 /// instructions in the block that directly load or store an alloca.
185 /// This functionality is important because it avoids scanning large basic
186 /// blocks multiple times when promoting many allocas in the same block.
187 class LargeBlockInfo {
188 /// \brief For each instruction that we track, keep the index of the
191 /// The index starts out as the number of the instruction from the start of
193 DenseMap<const Instruction *, unsigned> InstNumbers;
197 /// This code only looks at accesses to allocas.
198 static bool isInterestingInstruction(const Instruction *I) {
199 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
200 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
203 /// Get or calculate the index of the specified instruction.
204 unsigned getInstructionIndex(const Instruction *I) {
205 assert(isInterestingInstruction(I) &&
206 "Not a load/store to/from an alloca?");
208 // If we already have this instruction number, return it.
209 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
210 if (It != InstNumbers.end())
213 // Scan the whole block to get the instruction. This accumulates
214 // information for every interesting instruction in the block, in order to
215 // avoid gratuitus rescans.
216 const BasicBlock *BB = I->getParent();
218 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
220 if (isInterestingInstruction(BBI))
221 InstNumbers[BBI] = InstNo++;
222 It = InstNumbers.find(I);
224 assert(It != InstNumbers.end() && "Didn't insert instruction?");
228 void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
230 void clear() { InstNumbers.clear(); }
233 struct PromoteMem2Reg {
234 /// The alloca instructions being promoted.
235 std::vector<AllocaInst *> Allocas;
239 /// An AliasSetTracker object to update. If null, don't update it.
240 AliasSetTracker *AST;
242 /// Reverse mapping of Allocas.
243 DenseMap<AllocaInst *, unsigned> AllocaLookup;
245 /// \brief The PhiNodes we're adding.
247 /// That map is used to simplify some Phi nodes as we iterate over it, so
248 /// it should have deterministic iterators. We could use a MapVector, but
249 /// since we already maintain a map from BasicBlock* to a stable numbering
250 /// (BBNumbers), the DenseMap is more efficient (also supports removal).
251 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
253 /// For each PHI node, keep track of which entry in Allocas it corresponds
255 DenseMap<PHINode *, unsigned> PhiToAllocaMap;
257 /// If we are updating an AliasSetTracker, then for each alloca that is of
258 /// pointer type, we keep track of what to copyValue to the inserted PHI
260 std::vector<Value *> PointerAllocaValues;
262 /// For each alloca, we keep track of the dbg.declare intrinsic that
263 /// describes it, if any, so that we can convert it to a dbg.value
264 /// intrinsic if the alloca gets promoted.
265 SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
267 /// The set of basic blocks the renamer has already visited.
269 SmallPtrSet<BasicBlock *, 16> Visited;
271 /// Contains a stable numbering of basic blocks to avoid non-determinstic
273 DenseMap<BasicBlock *, unsigned> BBNumbers;
275 /// Maps DomTreeNodes to their level in the dominator tree.
276 DenseMap<DomTreeNode *, unsigned> DomLevels;
278 /// Lazily compute the number of predecessors a block has.
279 DenseMap<const BasicBlock *, unsigned> BBNumPreds;
282 PromoteMem2Reg(const std::vector<AllocaInst *> &Allocas, DominatorTree &DT,
283 AliasSetTracker *AST)
284 : Allocas(Allocas), DT(DT), DIB(*DT.getRoot()->getParent()->getParent()),
289 /// Return true if BB1 dominates BB2 using the DominatorTree.
290 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
291 return DT.dominates(BB1, BB2);
295 void RemoveFromAllocasList(unsigned &AllocaIdx) {
296 Allocas[AllocaIdx] = Allocas.back();
301 unsigned getNumPreds(const BasicBlock *BB) {
302 unsigned &NP = BBNumPreds[BB];
304 NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
308 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
310 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
311 const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
312 SmallPtrSet<BasicBlock *, 32> &LiveInBlocks);
313 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
314 RenamePassData::ValVector &IncVals,
315 std::vector<RenamePassData> &Worklist);
316 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
319 } // end of anonymous namespace
321 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
322 // Knowing that this alloca is promotable, we know that it's safe to kill all
323 // instructions except for load and store.
325 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
327 Instruction *I = cast<Instruction>(*UI);
329 if (isa<LoadInst>(I) || isa<StoreInst>(I))
332 if (!I->getType()->isVoidTy()) {
333 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
334 // Follow the use/def chain to erase them now instead of leaving it for
335 // dead code elimination later.
336 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
338 Instruction *Inst = cast<Instruction>(*UI);
340 Inst->eraseFromParent();
343 I->eraseFromParent();
347 /// If there is only a single store to this value, replace any loads of it that
348 /// are directly dominated by the definition with the value stored.
349 static void rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
352 AliasSetTracker *AST) {
353 StoreInst *OnlyStore = Info.OnlyStore;
354 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
355 BasicBlock *StoreBB = OnlyStore->getParent();
358 // Clear out UsingBlocks. We will reconstruct it here if needed.
359 Info.UsingBlocks.clear();
361 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
362 Instruction *UserInst = cast<Instruction>(*UI++);
363 if (!isa<LoadInst>(UserInst)) {
364 assert(UserInst == OnlyStore && "Should only have load/stores");
367 LoadInst *LI = cast<LoadInst>(UserInst);
369 // Okay, if we have a load from the alloca, we want to replace it with the
370 // only value stored to the alloca. We can do this if the value is
371 // dominated by the store. If not, we use the rest of the mem2reg machinery
372 // to insert the phi nodes as needed.
373 if (!StoringGlobalVal) { // Non-instructions are always dominated.
374 if (LI->getParent() == StoreBB) {
375 // If we have a use that is in the same block as the store, compare the
376 // indices of the two instructions to see which one came first. If the
377 // load came before the store, we can't handle it.
378 if (StoreIndex == -1)
379 StoreIndex = LBI.getInstructionIndex(OnlyStore);
381 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
382 // Can't handle this load, bail out.
383 Info.UsingBlocks.push_back(StoreBB);
387 } else if (LI->getParent() != StoreBB &&
388 !DT.dominates(StoreBB, LI->getParent())) {
389 // If the load and store are in different blocks, use BB dominance to
390 // check their relationships. If the store doesn't dom the use, bail
392 Info.UsingBlocks.push_back(LI->getParent());
397 // Otherwise, we *can* safely rewrite this load.
398 Value *ReplVal = OnlyStore->getOperand(0);
399 // If the replacement value is the load, this must occur in unreachable
402 ReplVal = UndefValue::get(LI->getType());
403 LI->replaceAllUsesWith(ReplVal);
404 if (AST && LI->getType()->isPointerTy())
405 AST->deleteValue(LI);
406 LI->eraseFromParent();
412 /// This is a helper predicate used to search by the first element of a pair.
413 struct StoreIndexSearchPredicate {
414 bool operator()(const std::pair<unsigned, StoreInst *> &LHS,
415 const std::pair<unsigned, StoreInst *> &RHS) {
416 return LHS.first < RHS.first;
421 /// Many allocas are only used within a single basic block. If this is the
422 /// case, avoid traversing the CFG and inserting a lot of potentially useless
423 /// PHI nodes by just performing a single linear pass over the basic block
424 /// using the Alloca.
426 /// If we cannot promote this alloca (because it is read before it is written),
427 /// return true. This is necessary in cases where, due to control flow, the
428 /// alloca is potentially undefined on some control flow paths. e.g. code like
429 /// this is potentially correct:
431 /// for (...) { if (c) { A = undef; undef = B; } }
433 /// ... so long as A is not used before undef is set.
434 static void promoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
436 AliasSetTracker *AST) {
437 // The trickiest case to handle is when we have large blocks. Because of this,
438 // this code is optimized assuming that large blocks happen. This does not
439 // significantly pessimize the small block case. This uses LargeBlockInfo to
440 // make it efficient to get the index of various operations in the block.
442 // Clear out UsingBlocks. We will reconstruct it here if needed.
443 Info.UsingBlocks.clear();
445 // Walk the use-def list of the alloca, getting the locations of all stores.
446 typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
447 StoresByIndexTy StoresByIndex;
449 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;
451 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
452 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
454 // If there are no stores to the alloca, just replace any loads with undef.
455 if (StoresByIndex.empty()) {
456 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
457 if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
458 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
459 if (AST && LI->getType()->isPointerTy())
460 AST->deleteValue(LI);
462 LI->eraseFromParent();
467 // Sort the stores by their index, making it efficient to do a lookup with a
469 std::sort(StoresByIndex.begin(), StoresByIndex.end());
471 // Walk all of the loads from this alloca, replacing them with the nearest
472 // store above them, if any.
473 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
474 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
478 unsigned LoadIdx = LBI.getInstructionIndex(LI);
480 // Find the nearest store that has a lower than this load.
481 StoresByIndexTy::iterator I = std::lower_bound(
482 StoresByIndex.begin(), StoresByIndex.end(),
483 std::pair<unsigned, StoreInst *>(LoadIdx, static_cast<StoreInst *>(0)),
484 StoreIndexSearchPredicate());
486 // If there is no store before this load, then we can't promote this load.
487 if (I == StoresByIndex.begin()) {
488 // Can't handle this load, bail out.
489 Info.UsingBlocks.push_back(LI->getParent());
493 // Otherwise, there was a store before this load, the load takes its value.
495 LI->replaceAllUsesWith(I->second->getOperand(0));
496 if (AST && LI->getType()->isPointerTy())
497 AST->deleteValue(LI);
498 LI->eraseFromParent();
503 void PromoteMem2Reg::run() {
504 Function &F = *DT.getRoot()->getParent();
507 PointerAllocaValues.resize(Allocas.size());
508 AllocaDbgDeclares.resize(Allocas.size());
513 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
514 AllocaInst *AI = Allocas[AllocaNum];
516 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
517 assert(AI->getParent()->getParent() == &F &&
518 "All allocas should be in the same function, which is same as DF!");
520 removeLifetimeIntrinsicUsers(AI);
522 if (AI->use_empty()) {
523 // If there are no uses of the alloca, just delete it now.
525 AST->deleteValue(AI);
526 AI->eraseFromParent();
528 // Remove the alloca from the Allocas list, since it has been processed
529 RemoveFromAllocasList(AllocaNum);
534 // Calculate the set of read and write-locations for each alloca. This is
535 // analogous to finding the 'uses' and 'definitions' of each variable.
536 Info.AnalyzeAlloca(AI);
538 // If there is only a single store to this value, replace any loads of
539 // it that are directly dominated by the definition with the value stored.
540 if (Info.DefiningBlocks.size() == 1) {
541 rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST);
543 // Finally, after the scan, check to see if the store is all that is left.
544 if (Info.UsingBlocks.empty()) {
545 // Record debuginfo for the store and remove the declaration's
547 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
548 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
549 DDI->eraseFromParent();
551 // Remove the (now dead) store and alloca.
552 Info.OnlyStore->eraseFromParent();
553 LBI.deleteValue(Info.OnlyStore);
556 AST->deleteValue(AI);
557 AI->eraseFromParent();
560 // The alloca has been processed, move on.
561 RemoveFromAllocasList(AllocaNum);
568 // If the alloca is only read and written in one basic block, just perform a
569 // linear sweep over the block to eliminate it.
570 if (Info.OnlyUsedInOneBlock) {
571 promoteSingleBlockAlloca(AI, Info, LBI, AST);
573 // Finally, after the scan, check to see if the stores are all that is
575 if (Info.UsingBlocks.empty()) {
577 // Remove the (now dead) stores and alloca.
578 while (!AI->use_empty()) {
579 StoreInst *SI = cast<StoreInst>(AI->use_back());
580 // Record debuginfo for the store before removing it.
581 if (DbgDeclareInst *DDI = Info.DbgDeclare)
582 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
583 SI->eraseFromParent();
588 AST->deleteValue(AI);
589 AI->eraseFromParent();
592 // The alloca has been processed, move on.
593 RemoveFromAllocasList(AllocaNum);
595 // The alloca's debuginfo can be removed as well.
596 if (DbgDeclareInst *DDI = Info.DbgDeclare)
597 DDI->eraseFromParent();
604 // If we haven't computed dominator tree levels, do so now.
605 if (DomLevels.empty()) {
606 SmallVector<DomTreeNode *, 32> Worklist;
608 DomTreeNode *Root = DT.getRootNode();
610 Worklist.push_back(Root);
612 while (!Worklist.empty()) {
613 DomTreeNode *Node = Worklist.pop_back_val();
614 unsigned ChildLevel = DomLevels[Node] + 1;
615 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
617 DomLevels[*CI] = ChildLevel;
618 Worklist.push_back(*CI);
623 // If we haven't computed a numbering for the BB's in the function, do so
625 if (BBNumbers.empty()) {
627 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
631 // If we have an AST to keep updated, remember some pointer value that is
632 // stored into the alloca.
634 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
636 // Remember the dbg.declare intrinsic describing this alloca, if any.
638 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
640 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
641 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
643 // At this point, we're committed to promoting the alloca using IDF's, and
644 // the standard SSA construction algorithm. Determine which blocks need PHI
645 // nodes and see if we can optimize out some work by avoiding insertion of
647 DetermineInsertionPoint(AI, AllocaNum, Info);
651 return; // All of the allocas must have been trivial!
655 // Set the incoming values for the basic block to be null values for all of
656 // the alloca's. We do this in case there is a load of a value that has not
657 // been stored yet. In this case, it will get this null value.
659 RenamePassData::ValVector Values(Allocas.size());
660 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
661 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
663 // Walks all basic blocks in the function performing the SSA rename algorithm
664 // and inserting the phi nodes we marked as necessary
666 std::vector<RenamePassData> RenamePassWorkList;
667 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
670 RPD.swap(RenamePassWorkList.back());
671 RenamePassWorkList.pop_back();
672 // RenamePass may add new worklist entries.
673 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
674 } while (!RenamePassWorkList.empty());
676 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
679 // Remove the allocas themselves from the function.
680 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
681 Instruction *A = Allocas[i];
683 // If there are any uses of the alloca instructions left, they must be in
684 // unreachable basic blocks that were not processed by walking the dominator
685 // tree. Just delete the users now.
687 A->replaceAllUsesWith(UndefValue::get(A->getType()));
690 A->eraseFromParent();
693 // Remove alloca's dbg.declare instrinsics from the function.
694 for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
695 if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
696 DDI->eraseFromParent();
698 // Loop over all of the PHI nodes and see if there are any that we can get
699 // rid of because they merge all of the same incoming values. This can
700 // happen due to undef values coming into the PHI nodes. This process is
701 // iterative, because eliminating one PHI node can cause others to be removed.
702 bool EliminatedAPHI = true;
703 while (EliminatedAPHI) {
704 EliminatedAPHI = false;
706 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
707 // simplify and RAUW them as we go. If it was not, we could add uses to
708 // the values we replace with in a non deterministic order, thus creating
709 // non deterministic def->use chains.
710 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
711 I = NewPhiNodes.begin(),
712 E = NewPhiNodes.end();
714 PHINode *PN = I->second;
716 // If this PHI node merges one value and/or undefs, get the value.
717 if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
718 if (AST && PN->getType()->isPointerTy())
719 AST->deleteValue(PN);
720 PN->replaceAllUsesWith(V);
721 PN->eraseFromParent();
722 NewPhiNodes.erase(I++);
723 EliminatedAPHI = true;
730 // At this point, the renamer has added entries to PHI nodes for all reachable
731 // code. Unfortunately, there may be unreachable blocks which the renamer
732 // hasn't traversed. If this is the case, the PHI nodes may not
733 // have incoming values for all predecessors. Loop over all PHI nodes we have
734 // created, inserting undef values if they are missing any incoming values.
736 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
737 I = NewPhiNodes.begin(),
738 E = NewPhiNodes.end();
740 // We want to do this once per basic block. As such, only process a block
741 // when we find the PHI that is the first entry in the block.
742 PHINode *SomePHI = I->second;
743 BasicBlock *BB = SomePHI->getParent();
744 if (&BB->front() != SomePHI)
747 // Only do work here if there the PHI nodes are missing incoming values. We
748 // know that all PHI nodes that were inserted in a block will have the same
749 // number of incoming values, so we can just check any of them.
750 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
753 // Get the preds for BB.
754 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
756 // Ok, now we know that all of the PHI nodes are missing entries for some
757 // basic blocks. Start by sorting the incoming predecessors for efficient
759 std::sort(Preds.begin(), Preds.end());
761 // Now we loop through all BB's which have entries in SomePHI and remove
762 // them from the Preds list.
763 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
764 // Do a log(n) search of the Preds list for the entry we want.
765 SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
766 Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
767 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
768 "PHI node has entry for a block which is not a predecessor!");
774 // At this point, the blocks left in the preds list must have dummy
775 // entries inserted into every PHI nodes for the block. Update all the phi
776 // nodes in this block that we are inserting (there could be phis before
778 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
779 BasicBlock::iterator BBI = BB->begin();
780 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
781 SomePHI->getNumIncomingValues() == NumBadPreds) {
782 Value *UndefVal = UndefValue::get(SomePHI->getType());
783 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
784 SomePHI->addIncoming(UndefVal, Preds[pred]);
791 /// \brief Determine which blocks the value is live in.
793 /// These are blocks which lead to uses. Knowing this allows us to avoid
794 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
795 /// inserted phi nodes would be dead).
796 void PromoteMem2Reg::ComputeLiveInBlocks(
797 AllocaInst *AI, AllocaInfo &Info,
798 const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
799 SmallPtrSet<BasicBlock *, 32> &LiveInBlocks) {
801 // To determine liveness, we must iterate through the predecessors of blocks
802 // where the def is live. Blocks are added to the worklist if we need to
803 // check their predecessors. Start with all the using blocks.
804 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
805 Info.UsingBlocks.end());
807 // If any of the using blocks is also a definition block, check to see if the
808 // definition occurs before or after the use. If it happens before the use,
809 // the value isn't really live-in.
810 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
811 BasicBlock *BB = LiveInBlockWorklist[i];
812 if (!DefBlocks.count(BB))
815 // Okay, this is a block that both uses and defines the value. If the first
816 // reference to the alloca is a def (store), then we know it isn't live-in.
817 for (BasicBlock::iterator I = BB->begin();; ++I) {
818 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
819 if (SI->getOperand(1) != AI)
822 // We found a store to the alloca before a load. The alloca is not
823 // actually live-in here.
824 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
825 LiveInBlockWorklist.pop_back();
830 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
831 if (LI->getOperand(0) != AI)
834 // Okay, we found a load before a store to the alloca. It is actually
835 // live into this block.
841 // Now that we have a set of blocks where the phi is live-in, recursively add
842 // their predecessors until we find the full region the value is live.
843 while (!LiveInBlockWorklist.empty()) {
844 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
846 // The block really is live in here, insert it into the set. If already in
847 // the set, then it has already been processed.
848 if (!LiveInBlocks.insert(BB))
851 // Since the value is live into BB, it is either defined in a predecessor or
852 // live into it to. Add the preds to the worklist unless they are a
854 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
857 // The value is not live into a predecessor if it defines the value.
858 if (DefBlocks.count(P))
861 // Otherwise it is, add to the worklist.
862 LiveInBlockWorklist.push_back(P);
868 typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
870 struct DomTreeNodeCompare {
871 bool operator()(const DomTreeNodePair &LHS, const DomTreeNodePair &RHS) {
872 return LHS.second < RHS.second;
875 } // end anonymous namespace
877 /// At this point, we're committed to promoting the alloca using IDF's, and the
878 /// standard SSA construction algorithm. Determine which blocks need phi nodes
879 /// and see if we can optimize out some work by avoiding insertion of dead phi
881 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
883 // Unique the set of defining blocks for efficient lookup.
884 SmallPtrSet<BasicBlock *, 32> DefBlocks;
885 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
887 // Determine which blocks the value is live in. These are blocks which lead
889 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
890 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
892 // Use a priority queue keyed on dominator tree level so that inserted nodes
893 // are handled from the bottom of the dominator tree upwards.
894 typedef std::priority_queue<DomTreeNodePair,
895 SmallVector<DomTreeNodePair, 32>,
896 DomTreeNodeCompare> IDFPriorityQueue;
899 for (SmallPtrSet<BasicBlock *, 32>::const_iterator I = DefBlocks.begin(),
902 if (DomTreeNode *Node = DT.getNode(*I))
903 PQ.push(std::make_pair(Node, DomLevels[Node]));
906 SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
907 SmallPtrSet<DomTreeNode *, 32> Visited;
908 SmallVector<DomTreeNode *, 32> Worklist;
909 while (!PQ.empty()) {
910 DomTreeNodePair RootPair = PQ.top();
912 DomTreeNode *Root = RootPair.first;
913 unsigned RootLevel = RootPair.second;
915 // Walk all dominator tree children of Root, inspecting their CFG edges with
916 // targets elsewhere on the dominator tree. Only targets whose level is at
917 // most Root's level are added to the iterated dominance frontier of the
921 Worklist.push_back(Root);
923 while (!Worklist.empty()) {
924 DomTreeNode *Node = Worklist.pop_back_val();
925 BasicBlock *BB = Node->getBlock();
927 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
929 DomTreeNode *SuccNode = DT.getNode(*SI);
931 // Quickly skip all CFG edges that are also dominator tree edges instead
932 // of catching them below.
933 if (SuccNode->getIDom() == Node)
936 unsigned SuccLevel = DomLevels[SuccNode];
937 if (SuccLevel > RootLevel)
940 if (!Visited.insert(SuccNode))
943 BasicBlock *SuccBB = SuccNode->getBlock();
944 if (!LiveInBlocks.count(SuccBB))
947 DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
948 if (!DefBlocks.count(SuccBB))
949 PQ.push(std::make_pair(SuccNode, SuccLevel));
952 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
954 if (!Visited.count(*CI))
955 Worklist.push_back(*CI);
960 if (DFBlocks.size() > 1)
961 std::sort(DFBlocks.begin(), DFBlocks.end());
963 unsigned CurrentVersion = 0;
964 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
965 QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
968 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
970 /// Returns true if there wasn't already a phi-node for that variable
971 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
973 // Look up the basic-block in question.
974 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
976 // If the BB already has a phi node added for the i'th alloca then we're done!
980 // Create a PhiNode using the dereferenced type... and add the phi-node to the
982 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
983 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
986 PhiToAllocaMap[PN] = AllocaNo;
988 if (AST && PN->getType()->isPointerTy())
989 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
994 /// \brief Recursively traverse the CFG of the function, renaming loads and
995 /// stores to the allocas which we are promoting.
997 /// IncomingVals indicates what value each Alloca contains on exit from the
998 /// predecessor block Pred.
999 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
1000 RenamePassData::ValVector &IncomingVals,
1001 std::vector<RenamePassData> &Worklist) {
1003 // If we are inserting any phi nodes into this BB, they will already be in the
1005 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1006 // If we have PHI nodes to update, compute the number of edges from Pred to
1008 if (PhiToAllocaMap.count(APN)) {
1009 // We want to be able to distinguish between PHI nodes being inserted by
1010 // this invocation of mem2reg from those phi nodes that already existed in
1011 // the IR before mem2reg was run. We determine that APN is being inserted
1012 // because it is missing incoming edges. All other PHI nodes being
1013 // inserted by this pass of mem2reg will have the same number of incoming
1014 // operands so far. Remember this count.
1015 unsigned NewPHINumOperands = APN->getNumOperands();
1017 unsigned NumEdges = 0;
1018 for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
1021 assert(NumEdges && "Must be at least one edge from Pred to BB!");
1023 // Add entries for all the phis.
1024 BasicBlock::iterator PNI = BB->begin();
1026 unsigned AllocaNo = PhiToAllocaMap[APN];
1028 // Add N incoming values to the PHI node.
1029 for (unsigned i = 0; i != NumEdges; ++i)
1030 APN->addIncoming(IncomingVals[AllocaNo], Pred);
1032 // The currently active variable for this block is now the PHI.
1033 IncomingVals[AllocaNo] = APN;
1035 // Get the next phi node.
1037 APN = dyn_cast<PHINode>(PNI);
1041 // Verify that it is missing entries. If not, it is not being inserted
1042 // by this mem2reg invocation so we want to ignore it.
1043 } while (APN->getNumOperands() == NewPHINumOperands);
1047 // Don't revisit blocks.
1048 if (!Visited.insert(BB))
1051 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
1052 Instruction *I = II++; // get the instruction, increment iterator
1054 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1055 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1059 DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1060 if (AI == AllocaLookup.end())
1063 Value *V = IncomingVals[AI->second];
1065 // Anything using the load now uses the current value.
1066 LI->replaceAllUsesWith(V);
1067 if (AST && LI->getType()->isPointerTy())
1068 AST->deleteValue(LI);
1069 BB->getInstList().erase(LI);
1070 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1071 // Delete this instruction and mark the name as the current holder of the
1073 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1077 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1078 if (ai == AllocaLookup.end())
1081 // what value were we writing?
1082 IncomingVals[ai->second] = SI->getOperand(0);
1083 // Record debuginfo for the store before removing it.
1084 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
1085 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1086 BB->getInstList().erase(SI);
1090 // 'Recurse' to our successors.
1091 succ_iterator I = succ_begin(BB), E = succ_end(BB);
1095 // Keep track of the successors so we don't visit the same successor twice
1096 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1098 // Handle the first successor without using the worklist.
1099 VisitedSuccs.insert(*I);
1105 if (VisitedSuccs.insert(*I))
1106 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1111 void llvm::PromoteMemToReg(const std::vector<AllocaInst *> &Allocas,
1112 DominatorTree &DT, AliasSetTracker *AST) {
1113 // If there is nothing to do, bail out...
1114 if (Allocas.empty())
1117 PromoteMem2Reg(Allocas, DT, AST).run();