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 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/AliasSetTracker.h"
36 #include "llvm/Analysis/InstructionSimplify.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DIBuilder.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Dominators.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/Transforms/Utils/Local.h"
53 #define DEBUG_TYPE "mem2reg"
55 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
56 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
57 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
58 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
60 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
61 // FIXME: If the memory unit is of pointer or integer type, we can permit
62 // assignments to subsections of the memory unit.
63 unsigned AS = AI->getType()->getAddressSpace();
65 // Only allow direct and non-volatile loads and stores...
66 for (const User *U : AI->users()) {
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(), AS))
86 if (!onlyUsedByLifetimeMarkers(BCI))
88 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
89 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
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 = nullptr;
123 DbgDeclare = nullptr;
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 (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
135 Instruction *User = cast<Instruction>(*UI++);
137 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
138 // Remember the basic blocks which define new values for the alloca
139 DefiningBlocks.push_back(SI->getParent());
140 AllocaPointerVal = SI->getOperand(0);
143 LoadInst *LI = cast<LoadInst>(User);
144 // Otherwise it must be a load instruction, keep track of variable
146 UsingBlocks.push_back(LI->getParent());
147 AllocaPointerVal = LI;
150 if (OnlyUsedInOneBlock) {
152 OnlyBlock = User->getParent();
153 else if (OnlyBlock != User->getParent())
154 OnlyUsedInOneBlock = false;
158 DbgDeclare = FindAllocaDbgDeclare(AI);
162 // Data package used by RenamePass()
163 class RenamePassData {
165 typedef std::vector<Value *> ValVector;
167 RenamePassData() : BB(nullptr), Pred(nullptr), Values() {}
168 RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
169 : BB(B), Pred(P), Values(V) {}
174 void swap(RenamePassData &RHS) {
175 std::swap(BB, RHS.BB);
176 std::swap(Pred, RHS.Pred);
177 Values.swap(RHS.Values);
181 /// \brief This assigns and keeps a per-bb relative ordering of load/store
182 /// instructions in the block that directly load or store an alloca.
184 /// This functionality is important because it avoids scanning large basic
185 /// blocks multiple times when promoting many allocas in the same block.
186 class LargeBlockInfo {
187 /// \brief For each instruction that we track, keep the index of the
190 /// The index starts out as the number of the instruction from the start of
192 DenseMap<const Instruction *, unsigned> InstNumbers;
196 /// This code only looks at accesses to allocas.
197 static bool isInterestingInstruction(const Instruction *I) {
198 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
199 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
202 /// Get or calculate the index of the specified instruction.
203 unsigned getInstructionIndex(const Instruction *I) {
204 assert(isInterestingInstruction(I) &&
205 "Not a load/store to/from an alloca?");
207 // If we already have this instruction number, return it.
208 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
209 if (It != InstNumbers.end())
212 // Scan the whole block to get the instruction. This accumulates
213 // information for every interesting instruction in the block, in order to
214 // avoid gratuitus rescans.
215 const BasicBlock *BB = I->getParent();
217 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
219 if (isInterestingInstruction(BBI))
220 InstNumbers[BBI] = InstNo++;
221 It = InstNumbers.find(I);
223 assert(It != InstNumbers.end() && "Didn't insert instruction?");
227 void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
229 void clear() { InstNumbers.clear(); }
232 struct PromoteMem2Reg {
233 /// The alloca instructions being promoted.
234 std::vector<AllocaInst *> Allocas;
238 /// An AliasSetTracker object to update. If null, don't update it.
239 AliasSetTracker *AST;
241 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
244 /// Reverse mapping of Allocas.
245 DenseMap<AllocaInst *, unsigned> AllocaLookup;
247 /// \brief The PhiNodes we're adding.
249 /// That map is used to simplify some Phi nodes as we iterate over it, so
250 /// it should have deterministic iterators. We could use a MapVector, but
251 /// since we already maintain a map from BasicBlock* to a stable numbering
252 /// (BBNumbers), the DenseMap is more efficient (also supports removal).
253 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
255 /// For each PHI node, keep track of which entry in Allocas it corresponds
257 DenseMap<PHINode *, unsigned> PhiToAllocaMap;
259 /// If we are updating an AliasSetTracker, then for each alloca that is of
260 /// pointer type, we keep track of what to copyValue to the inserted PHI
262 std::vector<Value *> PointerAllocaValues;
264 /// For each alloca, we keep track of the dbg.declare intrinsic that
265 /// describes it, if any, so that we can convert it to a dbg.value
266 /// intrinsic if the alloca gets promoted.
267 SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
269 /// The set of basic blocks the renamer has already visited.
271 SmallPtrSet<BasicBlock *, 16> Visited;
273 /// Contains a stable numbering of basic blocks to avoid non-determinstic
275 DenseMap<BasicBlock *, unsigned> BBNumbers;
277 /// Maps DomTreeNodes to their level in the dominator tree.
278 DenseMap<DomTreeNode *, unsigned> DomLevels;
280 /// Lazily compute the number of predecessors a block has.
281 DenseMap<const BasicBlock *, unsigned> BBNumPreds;
284 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
285 AliasSetTracker *AST, AssumptionCache *AC)
286 : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
287 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
293 void RemoveFromAllocasList(unsigned &AllocaIdx) {
294 Allocas[AllocaIdx] = Allocas.back();
299 unsigned getNumPreds(const BasicBlock *BB) {
300 unsigned &NP = BBNumPreds[BB];
302 NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
306 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
308 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
309 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
310 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
311 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
312 RenamePassData::ValVector &IncVals,
313 std::vector<RenamePassData> &Worklist);
314 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
317 } // end of anonymous namespace
319 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
320 // Knowing that this alloca is promotable, we know that it's safe to kill all
321 // instructions except for load and store.
323 for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
324 Instruction *I = cast<Instruction>(*UI);
326 if (isa<LoadInst>(I) || isa<StoreInst>(I))
329 if (!I->getType()->isVoidTy()) {
330 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
331 // Follow the use/def chain to erase them now instead of leaving it for
332 // dead code elimination later.
333 for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
334 Instruction *Inst = cast<Instruction>(*UUI);
336 Inst->eraseFromParent();
339 I->eraseFromParent();
343 /// \brief Rewrite as many loads as possible given a single store.
345 /// When there is only a single store, we can use the domtree to trivially
346 /// replace all of the dominated loads with the stored value. Do so, and return
347 /// true if this has successfully promoted the alloca entirely. If this returns
348 /// false there were some loads which were not dominated by the single store
349 /// and thus must be phi-ed with undef. We fall back to the standard alloca
350 /// promotion algorithm in that case.
351 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
354 AliasSetTracker *AST) {
355 StoreInst *OnlyStore = Info.OnlyStore;
356 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
357 BasicBlock *StoreBB = OnlyStore->getParent();
360 // Clear out UsingBlocks. We will reconstruct it here if needed.
361 Info.UsingBlocks.clear();
363 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
364 Instruction *UserInst = cast<Instruction>(*UI++);
365 if (!isa<LoadInst>(UserInst)) {
366 assert(UserInst == OnlyStore && "Should only have load/stores");
369 LoadInst *LI = cast<LoadInst>(UserInst);
371 // Okay, if we have a load from the alloca, we want to replace it with the
372 // only value stored to the alloca. We can do this if the value is
373 // dominated by the store. If not, we use the rest of the mem2reg machinery
374 // to insert the phi nodes as needed.
375 if (!StoringGlobalVal) { // Non-instructions are always dominated.
376 if (LI->getParent() == StoreBB) {
377 // If we have a use that is in the same block as the store, compare the
378 // indices of the two instructions to see which one came first. If the
379 // load came before the store, we can't handle it.
380 if (StoreIndex == -1)
381 StoreIndex = LBI.getInstructionIndex(OnlyStore);
383 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
384 // Can't handle this load, bail out.
385 Info.UsingBlocks.push_back(StoreBB);
389 } else if (LI->getParent() != StoreBB &&
390 !DT.dominates(StoreBB, LI->getParent())) {
391 // If the load and store are in different blocks, use BB dominance to
392 // check their relationships. If the store doesn't dom the use, bail
394 Info.UsingBlocks.push_back(LI->getParent());
399 // Otherwise, we *can* safely rewrite this load.
400 Value *ReplVal = OnlyStore->getOperand(0);
401 // If the replacement value is the load, this must occur in unreachable
404 ReplVal = UndefValue::get(LI->getType());
405 LI->replaceAllUsesWith(ReplVal);
406 if (AST && LI->getType()->isPointerTy())
407 AST->deleteValue(LI);
408 LI->eraseFromParent();
412 // Finally, after the scan, check to see if the store is all that is left.
413 if (!Info.UsingBlocks.empty())
414 return false; // If not, we'll have to fall back for the remainder.
416 // Record debuginfo for the store and remove the declaration's
418 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
419 DIBuilder DIB(*AI->getParent()->getParent()->getParent(),
420 /*AllowUnresolved*/ false);
421 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
422 DDI->eraseFromParent();
423 LBI.deleteValue(DDI);
425 // Remove the (now dead) store and alloca.
426 Info.OnlyStore->eraseFromParent();
427 LBI.deleteValue(Info.OnlyStore);
430 AST->deleteValue(AI);
431 AI->eraseFromParent();
436 /// Many allocas are only used within a single basic block. If this is the
437 /// case, avoid traversing the CFG and inserting a lot of potentially useless
438 /// PHI nodes by just performing a single linear pass over the basic block
439 /// using the Alloca.
441 /// If we cannot promote this alloca (because it is read before it is written),
442 /// return true. This is necessary in cases where, due to control flow, the
443 /// alloca is potentially undefined on some control flow paths. e.g. code like
444 /// this is potentially correct:
446 /// for (...) { if (c) { A = undef; undef = B; } }
448 /// ... so long as A is not used before undef is set.
449 static void promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
451 AliasSetTracker *AST) {
452 // The trickiest case to handle is when we have large blocks. Because of this,
453 // this code is optimized assuming that large blocks happen. This does not
454 // significantly pessimize the small block case. This uses LargeBlockInfo to
455 // make it efficient to get the index of various operations in the block.
457 // Walk the use-def list of the alloca, getting the locations of all stores.
458 typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
459 StoresByIndexTy StoresByIndex;
461 for (User *U : AI->users())
462 if (StoreInst *SI = dyn_cast<StoreInst>(U))
463 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
465 // Sort the stores by their index, making it efficient to do a lookup with a
467 std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
469 // Walk all of the loads from this alloca, replacing them with the nearest
470 // store above them, if any.
471 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
472 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
476 unsigned LoadIdx = LBI.getInstructionIndex(LI);
478 // Find the nearest store that has a lower index than this load.
479 StoresByIndexTy::iterator I =
480 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
481 std::make_pair(LoadIdx,
482 static_cast<StoreInst *>(nullptr)),
485 if (I == StoresByIndex.begin())
486 // If there is no store before this load, the load takes the undef value.
487 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
489 // Otherwise, there was a store before this load, the load takes its value.
490 LI->replaceAllUsesWith(std::prev(I)->second->getOperand(0));
492 if (AST && LI->getType()->isPointerTy())
493 AST->deleteValue(LI);
494 LI->eraseFromParent();
498 // Remove the (now dead) stores and alloca.
499 while (!AI->use_empty()) {
500 StoreInst *SI = cast<StoreInst>(AI->user_back());
501 // Record debuginfo for the store before removing it.
502 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
503 DIBuilder DIB(*AI->getParent()->getParent()->getParent(),
504 /*AllowUnresolved*/ false);
505 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
507 SI->eraseFromParent();
512 AST->deleteValue(AI);
513 AI->eraseFromParent();
516 // The alloca's debuginfo can be removed as well.
517 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
518 DDI->eraseFromParent();
519 LBI.deleteValue(DDI);
525 void PromoteMem2Reg::run() {
526 Function &F = *DT.getRoot()->getParent();
529 PointerAllocaValues.resize(Allocas.size());
530 AllocaDbgDeclares.resize(Allocas.size());
535 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
536 AllocaInst *AI = Allocas[AllocaNum];
538 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
539 assert(AI->getParent()->getParent() == &F &&
540 "All allocas should be in the same function, which is same as DF!");
542 removeLifetimeIntrinsicUsers(AI);
544 if (AI->use_empty()) {
545 // If there are no uses of the alloca, just delete it now.
547 AST->deleteValue(AI);
548 AI->eraseFromParent();
550 // Remove the alloca from the Allocas list, since it has been processed
551 RemoveFromAllocasList(AllocaNum);
556 // Calculate the set of read and write-locations for each alloca. This is
557 // analogous to finding the 'uses' and 'definitions' of each variable.
558 Info.AnalyzeAlloca(AI);
560 // If there is only a single store to this value, replace any loads of
561 // it that are directly dominated by the definition with the value stored.
562 if (Info.DefiningBlocks.size() == 1) {
563 if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
564 // The alloca has been processed, move on.
565 RemoveFromAllocasList(AllocaNum);
571 // If the alloca is only read and written in one basic block, just perform a
572 // linear sweep over the block to eliminate it.
573 if (Info.OnlyUsedInOneBlock) {
574 promoteSingleBlockAlloca(AI, Info, LBI, AST);
576 // The alloca has been processed, move on.
577 RemoveFromAllocasList(AllocaNum);
581 // If we haven't computed dominator tree levels, do so now.
582 if (DomLevels.empty()) {
583 SmallVector<DomTreeNode *, 32> Worklist;
585 DomTreeNode *Root = DT.getRootNode();
587 Worklist.push_back(Root);
589 while (!Worklist.empty()) {
590 DomTreeNode *Node = Worklist.pop_back_val();
591 unsigned ChildLevel = DomLevels[Node] + 1;
592 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
594 DomLevels[*CI] = ChildLevel;
595 Worklist.push_back(*CI);
600 // If we haven't computed a numbering for the BB's in the function, do so
602 if (BBNumbers.empty()) {
604 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
608 // If we have an AST to keep updated, remember some pointer value that is
609 // stored into the alloca.
611 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
613 // Remember the dbg.declare intrinsic describing this alloca, if any.
615 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
617 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
618 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
620 // At this point, we're committed to promoting the alloca using IDF's, and
621 // the standard SSA construction algorithm. Determine which blocks need PHI
622 // nodes and see if we can optimize out some work by avoiding insertion of
624 DetermineInsertionPoint(AI, AllocaNum, Info);
628 return; // All of the allocas must have been trivial!
632 // Set the incoming values for the basic block to be null values for all of
633 // the alloca's. We do this in case there is a load of a value that has not
634 // been stored yet. In this case, it will get this null value.
636 RenamePassData::ValVector Values(Allocas.size());
637 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
638 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
640 // Walks all basic blocks in the function performing the SSA rename algorithm
641 // and inserting the phi nodes we marked as necessary
643 std::vector<RenamePassData> RenamePassWorkList;
644 RenamePassWorkList.push_back(RenamePassData(F.begin(), nullptr, Values));
647 RPD.swap(RenamePassWorkList.back());
648 RenamePassWorkList.pop_back();
649 // RenamePass may add new worklist entries.
650 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
651 } while (!RenamePassWorkList.empty());
653 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
656 // Remove the allocas themselves from the function.
657 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
658 Instruction *A = Allocas[i];
660 // If there are any uses of the alloca instructions left, they must be in
661 // unreachable basic blocks that were not processed by walking the dominator
662 // tree. Just delete the users now.
664 A->replaceAllUsesWith(UndefValue::get(A->getType()));
667 A->eraseFromParent();
670 // Remove alloca's dbg.declare instrinsics from the function.
671 for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
672 if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
673 DDI->eraseFromParent();
675 // Loop over all of the PHI nodes and see if there are any that we can get
676 // rid of because they merge all of the same incoming values. This can
677 // happen due to undef values coming into the PHI nodes. This process is
678 // iterative, because eliminating one PHI node can cause others to be removed.
679 bool EliminatedAPHI = true;
680 while (EliminatedAPHI) {
681 EliminatedAPHI = false;
683 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
684 // simplify and RAUW them as we go. If it was not, we could add uses to
685 // the values we replace with in a non-deterministic order, thus creating
686 // non-deterministic def->use chains.
687 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
688 I = NewPhiNodes.begin(),
689 E = NewPhiNodes.end();
691 PHINode *PN = I->second;
693 // If this PHI node merges one value and/or undefs, get the value.
694 if (Value *V = SimplifyInstruction(PN, nullptr, nullptr, &DT, AC)) {
695 if (AST && PN->getType()->isPointerTy())
696 AST->deleteValue(PN);
697 PN->replaceAllUsesWith(V);
698 PN->eraseFromParent();
699 NewPhiNodes.erase(I++);
700 EliminatedAPHI = true;
707 // At this point, the renamer has added entries to PHI nodes for all reachable
708 // code. Unfortunately, there may be unreachable blocks which the renamer
709 // hasn't traversed. If this is the case, the PHI nodes may not
710 // have incoming values for all predecessors. Loop over all PHI nodes we have
711 // created, inserting undef values if they are missing any incoming values.
713 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
714 I = NewPhiNodes.begin(),
715 E = NewPhiNodes.end();
717 // We want to do this once per basic block. As such, only process a block
718 // when we find the PHI that is the first entry in the block.
719 PHINode *SomePHI = I->second;
720 BasicBlock *BB = SomePHI->getParent();
721 if (&BB->front() != SomePHI)
724 // Only do work here if there the PHI nodes are missing incoming values. We
725 // know that all PHI nodes that were inserted in a block will have the same
726 // number of incoming values, so we can just check any of them.
727 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
730 // Get the preds for BB.
731 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
733 // Ok, now we know that all of the PHI nodes are missing entries for some
734 // basic blocks. Start by sorting the incoming predecessors for efficient
736 std::sort(Preds.begin(), Preds.end());
738 // Now we loop through all BB's which have entries in SomePHI and remove
739 // them from the Preds list.
740 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
741 // Do a log(n) search of the Preds list for the entry we want.
742 SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
743 Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
744 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
745 "PHI node has entry for a block which is not a predecessor!");
751 // At this point, the blocks left in the preds list must have dummy
752 // entries inserted into every PHI nodes for the block. Update all the phi
753 // nodes in this block that we are inserting (there could be phis before
755 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
756 BasicBlock::iterator BBI = BB->begin();
757 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
758 SomePHI->getNumIncomingValues() == NumBadPreds) {
759 Value *UndefVal = UndefValue::get(SomePHI->getType());
760 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
761 SomePHI->addIncoming(UndefVal, Preds[pred]);
768 /// \brief Determine which blocks the value is live in.
770 /// These are blocks which lead to uses. Knowing this allows us to avoid
771 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
772 /// inserted phi nodes would be dead).
773 void PromoteMem2Reg::ComputeLiveInBlocks(
774 AllocaInst *AI, AllocaInfo &Info,
775 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
776 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
778 // To determine liveness, we must iterate through the predecessors of blocks
779 // where the def is live. Blocks are added to the worklist if we need to
780 // check their predecessors. Start with all the using blocks.
781 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
782 Info.UsingBlocks.end());
784 // If any of the using blocks is also a definition block, check to see if the
785 // definition occurs before or after the use. If it happens before the use,
786 // the value isn't really live-in.
787 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
788 BasicBlock *BB = LiveInBlockWorklist[i];
789 if (!DefBlocks.count(BB))
792 // Okay, this is a block that both uses and defines the value. If the first
793 // reference to the alloca is a def (store), then we know it isn't live-in.
794 for (BasicBlock::iterator I = BB->begin();; ++I) {
795 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
796 if (SI->getOperand(1) != AI)
799 // We found a store to the alloca before a load. The alloca is not
800 // actually live-in here.
801 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
802 LiveInBlockWorklist.pop_back();
807 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
808 if (LI->getOperand(0) != AI)
811 // Okay, we found a load before a store to the alloca. It is actually
812 // live into this block.
818 // Now that we have a set of blocks where the phi is live-in, recursively add
819 // their predecessors until we find the full region the value is live.
820 while (!LiveInBlockWorklist.empty()) {
821 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
823 // The block really is live in here, insert it into the set. If already in
824 // the set, then it has already been processed.
825 if (!LiveInBlocks.insert(BB).second)
828 // Since the value is live into BB, it is either defined in a predecessor or
829 // live into it to. Add the preds to the worklist unless they are a
831 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
834 // The value is not live into a predecessor if it defines the value.
835 if (DefBlocks.count(P))
838 // Otherwise it is, add to the worklist.
839 LiveInBlockWorklist.push_back(P);
844 /// At this point, we're committed to promoting the alloca using IDF's, and the
845 /// standard SSA construction algorithm. Determine which blocks need phi nodes
846 /// and see if we can optimize out some work by avoiding insertion of dead phi
848 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
850 // Unique the set of defining blocks for efficient lookup.
851 SmallPtrSet<BasicBlock *, 32> DefBlocks;
852 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
854 // Determine which blocks the value is live in. These are blocks which lead
856 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
857 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
859 // Use a priority queue keyed on dominator tree level so that inserted nodes
860 // are handled from the bottom of the dominator tree upwards.
861 typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
862 typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
863 less_second> IDFPriorityQueue;
866 for (BasicBlock *BB : DefBlocks) {
867 if (DomTreeNode *Node = DT.getNode(BB))
868 PQ.push(std::make_pair(Node, DomLevels[Node]));
871 SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
872 SmallPtrSet<DomTreeNode *, 32> Visited;
873 SmallVector<DomTreeNode *, 32> Worklist;
874 while (!PQ.empty()) {
875 DomTreeNodePair RootPair = PQ.top();
877 DomTreeNode *Root = RootPair.first;
878 unsigned RootLevel = RootPair.second;
880 // Walk all dominator tree children of Root, inspecting their CFG edges with
881 // targets elsewhere on the dominator tree. Only targets whose level is at
882 // most Root's level are added to the iterated dominance frontier of the
886 Worklist.push_back(Root);
888 while (!Worklist.empty()) {
889 DomTreeNode *Node = Worklist.pop_back_val();
890 BasicBlock *BB = Node->getBlock();
892 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
894 DomTreeNode *SuccNode = DT.getNode(*SI);
896 // Quickly skip all CFG edges that are also dominator tree edges instead
897 // of catching them below.
898 if (SuccNode->getIDom() == Node)
901 unsigned SuccLevel = DomLevels[SuccNode];
902 if (SuccLevel > RootLevel)
905 if (!Visited.insert(SuccNode).second)
908 BasicBlock *SuccBB = SuccNode->getBlock();
909 if (!LiveInBlocks.count(SuccBB))
912 DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
913 if (!DefBlocks.count(SuccBB))
914 PQ.push(std::make_pair(SuccNode, SuccLevel));
917 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
919 if (!Visited.count(*CI))
920 Worklist.push_back(*CI);
925 if (DFBlocks.size() > 1)
926 std::sort(DFBlocks.begin(), DFBlocks.end());
928 unsigned CurrentVersion = 0;
929 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
930 QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
933 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
935 /// Returns true if there wasn't already a phi-node for that variable
936 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
938 // Look up the basic-block in question.
939 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
941 // If the BB already has a phi node added for the i'th alloca then we're done!
945 // Create a PhiNode using the dereferenced type... and add the phi-node to the
947 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
948 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
951 PhiToAllocaMap[PN] = AllocaNo;
953 if (AST && PN->getType()->isPointerTy())
954 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
959 /// \brief Recursively traverse the CFG of the function, renaming loads and
960 /// stores to the allocas which we are promoting.
962 /// IncomingVals indicates what value each Alloca contains on exit from the
963 /// predecessor block Pred.
964 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
965 RenamePassData::ValVector &IncomingVals,
966 std::vector<RenamePassData> &Worklist) {
968 // If we are inserting any phi nodes into this BB, they will already be in the
970 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
971 // If we have PHI nodes to update, compute the number of edges from Pred to
973 if (PhiToAllocaMap.count(APN)) {
974 // We want to be able to distinguish between PHI nodes being inserted by
975 // this invocation of mem2reg from those phi nodes that already existed in
976 // the IR before mem2reg was run. We determine that APN is being inserted
977 // because it is missing incoming edges. All other PHI nodes being
978 // inserted by this pass of mem2reg will have the same number of incoming
979 // operands so far. Remember this count.
980 unsigned NewPHINumOperands = APN->getNumOperands();
982 unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
983 assert(NumEdges && "Must be at least one edge from Pred to BB!");
985 // Add entries for all the phis.
986 BasicBlock::iterator PNI = BB->begin();
988 unsigned AllocaNo = PhiToAllocaMap[APN];
990 // Add N incoming values to the PHI node.
991 for (unsigned i = 0; i != NumEdges; ++i)
992 APN->addIncoming(IncomingVals[AllocaNo], Pred);
994 // The currently active variable for this block is now the PHI.
995 IncomingVals[AllocaNo] = APN;
997 // Get the next phi node.
999 APN = dyn_cast<PHINode>(PNI);
1003 // Verify that it is missing entries. If not, it is not being inserted
1004 // by this mem2reg invocation so we want to ignore it.
1005 } while (APN->getNumOperands() == NewPHINumOperands);
1009 // Don't revisit blocks.
1010 if (!Visited.insert(BB).second)
1013 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
1014 Instruction *I = II++; // get the instruction, increment iterator
1016 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1017 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1021 DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1022 if (AI == AllocaLookup.end())
1025 Value *V = IncomingVals[AI->second];
1027 // Anything using the load now uses the current value.
1028 LI->replaceAllUsesWith(V);
1029 if (AST && LI->getType()->isPointerTy())
1030 AST->deleteValue(LI);
1031 BB->getInstList().erase(LI);
1032 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1033 // Delete this instruction and mark the name as the current holder of the
1035 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1039 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1040 if (ai == AllocaLookup.end())
1043 // what value were we writing?
1044 IncomingVals[ai->second] = SI->getOperand(0);
1045 // Record debuginfo for the store before removing it.
1046 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
1047 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1048 BB->getInstList().erase(SI);
1052 // 'Recurse' to our successors.
1053 succ_iterator I = succ_begin(BB), E = succ_end(BB);
1057 // Keep track of the successors so we don't visit the same successor twice
1058 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1060 // Handle the first successor without using the worklist.
1061 VisitedSuccs.insert(*I);
1067 if (VisitedSuccs.insert(*I).second)
1068 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1073 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1074 AliasSetTracker *AST, AssumptionCache *AC) {
1075 // If there is nothing to do, bail out...
1076 if (Allocas.empty())
1079 PromoteMem2Reg(Allocas, DT, AST, AC).run();