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/Constants.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/IntrinsicInst.h"
35 #include "llvm/Metadata.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Analysis/DebugInfo.h"
38 #include "llvm/Analysis/DIBuilder.h"
39 #include "llvm/Analysis/Dominators.h"
40 #include "llvm/Analysis/InstructionSimplify.h"
41 #include "llvm/Analysis/ValueTracking.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/STLExtras.h"
48 #include "llvm/Support/CFG.h"
53 STATISTIC(NumLocalPromoted
, "Number of alloca's promoted within one block");
54 STATISTIC(NumSingleStore
, "Number of alloca's promoted with a single store");
55 STATISTIC(NumDeadAlloca
, "Number of dead alloca's removed");
56 STATISTIC(NumPHIInsert
, "Number of PHI nodes inserted");
60 struct DenseMapInfo
<std::pair
<BasicBlock
*, unsigned> > {
61 typedef std::pair
<BasicBlock
*, unsigned> EltTy
;
62 static inline EltTy
getEmptyKey() {
63 return EltTy(reinterpret_cast<BasicBlock
*>(-1), ~0U);
65 static inline EltTy
getTombstoneKey() {
66 return EltTy(reinterpret_cast<BasicBlock
*>(-2), 0U);
68 static unsigned getHashValue(const std::pair
<BasicBlock
*, unsigned> &Val
) {
69 return DenseMapInfo
<void*>::getHashValue(Val
.first
) + Val
.second
*2;
71 static bool isEqual(const EltTy
&LHS
, const EltTy
&RHS
) {
77 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
78 /// This is true if there are only loads and stores to the alloca.
80 bool llvm::isAllocaPromotable(const AllocaInst
*AI
) {
81 // FIXME: If the memory unit is of pointer or integer type, we can permit
82 // assignments to subsections of the memory unit.
84 // Only allow direct and non-volatile loads and stores...
85 for (Value::const_use_iterator UI
= AI
->use_begin(), UE
= AI
->use_end();
86 UI
!= UE
; ++UI
) { // Loop over all of the uses of the alloca
88 if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(U
)) {
91 } else if (const StoreInst
*SI
= dyn_cast
<StoreInst
>(U
)) {
92 if (SI
->getOperand(0) == AI
)
93 return false; // Don't allow a store OF the AI, only INTO the AI.
96 } else if (const IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(U
)) {
97 if (II
->getIntrinsicID() != Intrinsic::lifetime_start
&&
98 II
->getIntrinsicID() != Intrinsic::lifetime_end
)
100 } else if (const BitCastInst
*BCI
= dyn_cast
<BitCastInst
>(U
)) {
101 if (BCI
->getType() != Type::getInt8PtrTy(U
->getContext()))
103 if (!onlyUsedByLifetimeMarkers(BCI
))
105 } else if (const GetElementPtrInst
*GEPI
= dyn_cast
<GetElementPtrInst
>(U
)) {
106 if (GEPI
->getType() != Type::getInt8PtrTy(U
->getContext()))
108 if (!GEPI
->hasAllZeroIndices())
110 if (!onlyUsedByLifetimeMarkers(GEPI
))
123 // Data package used by RenamePass()
124 class RenamePassData
{
126 typedef std::vector
<Value
*> ValVector
;
128 RenamePassData() : BB(NULL
), Pred(NULL
), Values() {}
129 RenamePassData(BasicBlock
*B
, BasicBlock
*P
,
130 const ValVector
&V
) : BB(B
), Pred(P
), Values(V
) {}
135 void swap(RenamePassData
&RHS
) {
136 std::swap(BB
, RHS
.BB
);
137 std::swap(Pred
, RHS
.Pred
);
138 Values
.swap(RHS
.Values
);
142 /// LargeBlockInfo - This assigns and keeps a per-bb relative ordering of
143 /// load/store instructions in the block that directly load or store an alloca.
145 /// This functionality is important because it avoids scanning large basic
146 /// blocks multiple times when promoting many allocas in the same block.
147 class LargeBlockInfo
{
148 /// InstNumbers - For each instruction that we track, keep the index of the
149 /// instruction. The index starts out as the number of the instruction from
150 /// the start of the block.
151 DenseMap
<const Instruction
*, unsigned> InstNumbers
;
154 /// isInterestingInstruction - This code only looks at accesses to allocas.
155 static bool isInterestingInstruction(const Instruction
*I
) {
156 return (isa
<LoadInst
>(I
) && isa
<AllocaInst
>(I
->getOperand(0))) ||
157 (isa
<StoreInst
>(I
) && isa
<AllocaInst
>(I
->getOperand(1)));
160 /// getInstructionIndex - Get or calculate the index of the specified
162 unsigned getInstructionIndex(const Instruction
*I
) {
163 assert(isInterestingInstruction(I
) &&
164 "Not a load/store to/from an alloca?");
166 // If we already have this instruction number, return it.
167 DenseMap
<const Instruction
*, unsigned>::iterator It
= InstNumbers
.find(I
);
168 if (It
!= InstNumbers
.end()) return It
->second
;
170 // Scan the whole block to get the instruction. This accumulates
171 // information for every interesting instruction in the block, in order to
172 // avoid gratuitus rescans.
173 const BasicBlock
*BB
= I
->getParent();
175 for (BasicBlock::const_iterator BBI
= BB
->begin(), E
= BB
->end();
177 if (isInterestingInstruction(BBI
))
178 InstNumbers
[BBI
] = InstNo
++;
179 It
= InstNumbers
.find(I
);
181 assert(It
!= InstNumbers
.end() && "Didn't insert instruction?");
185 void deleteValue(const Instruction
*I
) {
186 InstNumbers
.erase(I
);
194 struct PromoteMem2Reg
{
195 /// Allocas - The alloca instructions being promoted.
197 std::vector
<AllocaInst
*> Allocas
;
201 /// AST - An AliasSetTracker object to update. If null, don't update it.
203 AliasSetTracker
*AST
;
205 /// AllocaLookup - Reverse mapping of Allocas.
207 DenseMap
<AllocaInst
*, unsigned> AllocaLookup
;
209 /// NewPhiNodes - The PhiNodes we're adding.
211 DenseMap
<std::pair
<BasicBlock
*, unsigned>, PHINode
*> NewPhiNodes
;
213 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
214 /// it corresponds to.
215 DenseMap
<PHINode
*, unsigned> PhiToAllocaMap
;
217 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
218 /// each alloca that is of pointer type, we keep track of what to copyValue
219 /// to the inserted PHI nodes here.
221 std::vector
<Value
*> PointerAllocaValues
;
223 /// AllocaDbgDeclares - For each alloca, we keep track of the dbg.declare
224 /// intrinsic that describes it, if any, so that we can convert it to a
225 /// dbg.value intrinsic if the alloca gets promoted.
226 SmallVector
<DbgDeclareInst
*, 8> AllocaDbgDeclares
;
228 /// Visited - The set of basic blocks the renamer has already visited.
230 SmallPtrSet
<BasicBlock
*, 16> Visited
;
232 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
233 /// non-determinstic behavior.
234 DenseMap
<BasicBlock
*, unsigned> BBNumbers
;
236 /// DomLevels - Maps DomTreeNodes to their level in the dominator tree.
237 DenseMap
<DomTreeNode
*, unsigned> DomLevels
;
239 /// BBNumPreds - Lazily compute the number of predecessors a block has.
240 DenseMap
<const BasicBlock
*, unsigned> BBNumPreds
;
242 PromoteMem2Reg(const std::vector
<AllocaInst
*> &A
, DominatorTree
&dt
,
243 AliasSetTracker
*ast
)
244 : Allocas(A
), DT(dt
), DIB(0), AST(ast
) {}
251 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
253 bool dominates(BasicBlock
*BB1
, BasicBlock
*BB2
) const {
254 return DT
.dominates(BB1
, BB2
);
258 void RemoveFromAllocasList(unsigned &AllocaIdx
) {
259 Allocas
[AllocaIdx
] = Allocas
.back();
264 unsigned getNumPreds(const BasicBlock
*BB
) {
265 unsigned &NP
= BBNumPreds
[BB
];
267 NP
= std::distance(pred_begin(BB
), pred_end(BB
))+1;
271 void DetermineInsertionPoint(AllocaInst
*AI
, unsigned AllocaNum
,
273 void ComputeLiveInBlocks(AllocaInst
*AI
, AllocaInfo
&Info
,
274 const SmallPtrSet
<BasicBlock
*, 32> &DefBlocks
,
275 SmallPtrSet
<BasicBlock
*, 32> &LiveInBlocks
);
277 void RewriteSingleStoreAlloca(AllocaInst
*AI
, AllocaInfo
&Info
,
278 LargeBlockInfo
&LBI
);
279 void PromoteSingleBlockAlloca(AllocaInst
*AI
, AllocaInfo
&Info
,
280 LargeBlockInfo
&LBI
);
282 void RenamePass(BasicBlock
*BB
, BasicBlock
*Pred
,
283 RenamePassData::ValVector
&IncVals
,
284 std::vector
<RenamePassData
> &Worklist
);
285 bool QueuePhiNode(BasicBlock
*BB
, unsigned AllocaIdx
, unsigned &Version
);
289 SmallVector
<BasicBlock
*, 32> DefiningBlocks
;
290 SmallVector
<BasicBlock
*, 32> UsingBlocks
;
292 StoreInst
*OnlyStore
;
293 BasicBlock
*OnlyBlock
;
294 bool OnlyUsedInOneBlock
;
296 Value
*AllocaPointerVal
;
297 DbgDeclareInst
*DbgDeclare
;
300 DefiningBlocks
.clear();
304 OnlyUsedInOneBlock
= true;
305 AllocaPointerVal
= 0;
309 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
311 void AnalyzeAlloca(AllocaInst
*AI
) {
314 // As we scan the uses of the alloca instruction, keep track of stores,
315 // and decide whether all of the loads and stores to the alloca are within
316 // the same basic block.
317 for (Value::use_iterator UI
= AI
->use_begin(), E
= AI
->use_end();
319 Instruction
*User
= cast
<Instruction
>(*UI
++);
321 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(User
)) {
322 // Remember the basic blocks which define new values for the alloca
323 DefiningBlocks
.push_back(SI
->getParent());
324 AllocaPointerVal
= SI
->getOperand(0);
327 LoadInst
*LI
= cast
<LoadInst
>(User
);
328 // Otherwise it must be a load instruction, keep track of variable
330 UsingBlocks
.push_back(LI
->getParent());
331 AllocaPointerVal
= LI
;
334 if (OnlyUsedInOneBlock
) {
336 OnlyBlock
= User
->getParent();
337 else if (OnlyBlock
!= User
->getParent())
338 OnlyUsedInOneBlock
= false;
342 DbgDeclare
= FindAllocaDbgDeclare(AI
);
346 typedef std::pair
<DomTreeNode
*, unsigned> DomTreeNodePair
;
348 struct DomTreeNodeCompare
{
349 bool operator()(const DomTreeNodePair
&LHS
, const DomTreeNodePair
&RHS
) {
350 return LHS
.second
< RHS
.second
;
353 } // end of anonymous namespace
355 static void removeLifetimeIntrinsicUsers(AllocaInst
*AI
) {
356 // Knowing that this alloca is promotable, we know that it's safe to kill all
357 // instructions except for load and store.
359 for (Value::use_iterator UI
= AI
->use_begin(), UE
= AI
->use_end();
361 Instruction
*I
= cast
<Instruction
>(*UI
);
363 if (isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
))
366 if (!I
->getType()->isVoidTy()) {
367 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
368 // Follow the use/def chain to erase them now instead of leaving it for
369 // dead code elimination later.
370 for (Value::use_iterator UI
= I
->use_begin(), UE
= I
->use_end();
372 Instruction
*Inst
= cast
<Instruction
>(*UI
);
374 Inst
->eraseFromParent();
377 I
->eraseFromParent();
381 void PromoteMem2Reg::run() {
382 Function
&F
= *DT
.getRoot()->getParent();
384 if (AST
) PointerAllocaValues
.resize(Allocas
.size());
385 AllocaDbgDeclares
.resize(Allocas
.size());
390 for (unsigned AllocaNum
= 0; AllocaNum
!= Allocas
.size(); ++AllocaNum
) {
391 AllocaInst
*AI
= Allocas
[AllocaNum
];
393 assert(isAllocaPromotable(AI
) &&
394 "Cannot promote non-promotable alloca!");
395 assert(AI
->getParent()->getParent() == &F
&&
396 "All allocas should be in the same function, which is same as DF!");
398 removeLifetimeIntrinsicUsers(AI
);
400 if (AI
->use_empty()) {
401 // If there are no uses of the alloca, just delete it now.
402 if (AST
) AST
->deleteValue(AI
);
403 AI
->eraseFromParent();
405 // Remove the alloca from the Allocas list, since it has been processed
406 RemoveFromAllocasList(AllocaNum
);
411 // Calculate the set of read and write-locations for each alloca. This is
412 // analogous to finding the 'uses' and 'definitions' of each variable.
413 Info
.AnalyzeAlloca(AI
);
415 // If there is only a single store to this value, replace any loads of
416 // it that are directly dominated by the definition with the value stored.
417 if (Info
.DefiningBlocks
.size() == 1) {
418 RewriteSingleStoreAlloca(AI
, Info
, LBI
);
420 // Finally, after the scan, check to see if the store is all that is left.
421 if (Info
.UsingBlocks
.empty()) {
422 // Record debuginfo for the store and remove the declaration's debuginfo.
423 if (DbgDeclareInst
*DDI
= Info
.DbgDeclare
) {
425 DIB
= new DIBuilder(*DDI
->getParent()->getParent()->getParent());
426 ConvertDebugDeclareToDebugValue(DDI
, Info
.OnlyStore
, *DIB
);
427 DDI
->eraseFromParent();
429 // Remove the (now dead) store and alloca.
430 Info
.OnlyStore
->eraseFromParent();
431 LBI
.deleteValue(Info
.OnlyStore
);
433 if (AST
) AST
->deleteValue(AI
);
434 AI
->eraseFromParent();
437 // The alloca has been processed, move on.
438 RemoveFromAllocasList(AllocaNum
);
445 // If the alloca is only read and written in one basic block, just perform a
446 // linear sweep over the block to eliminate it.
447 if (Info
.OnlyUsedInOneBlock
) {
448 PromoteSingleBlockAlloca(AI
, Info
, LBI
);
450 // Finally, after the scan, check to see if the stores are all that is
452 if (Info
.UsingBlocks
.empty()) {
454 // Remove the (now dead) stores and alloca.
455 while (!AI
->use_empty()) {
456 StoreInst
*SI
= cast
<StoreInst
>(AI
->use_back());
457 // Record debuginfo for the store before removing it.
458 if (DbgDeclareInst
*DDI
= Info
.DbgDeclare
) {
460 DIB
= new DIBuilder(*SI
->getParent()->getParent()->getParent());
461 ConvertDebugDeclareToDebugValue(DDI
, SI
, *DIB
);
463 SI
->eraseFromParent();
467 if (AST
) AST
->deleteValue(AI
);
468 AI
->eraseFromParent();
471 // The alloca has been processed, move on.
472 RemoveFromAllocasList(AllocaNum
);
474 // The alloca's debuginfo can be removed as well.
475 if (DbgDeclareInst
*DDI
= Info
.DbgDeclare
)
476 DDI
->eraseFromParent();
483 // If we haven't computed dominator tree levels, do so now.
484 if (DomLevels
.empty()) {
485 SmallVector
<DomTreeNode
*, 32> Worklist
;
487 DomTreeNode
*Root
= DT
.getRootNode();
489 Worklist
.push_back(Root
);
491 while (!Worklist
.empty()) {
492 DomTreeNode
*Node
= Worklist
.pop_back_val();
493 unsigned ChildLevel
= DomLevels
[Node
] + 1;
494 for (DomTreeNode::iterator CI
= Node
->begin(), CE
= Node
->end();
496 DomLevels
[*CI
] = ChildLevel
;
497 Worklist
.push_back(*CI
);
502 // If we haven't computed a numbering for the BB's in the function, do so
504 if (BBNumbers
.empty()) {
506 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
)
510 // If we have an AST to keep updated, remember some pointer value that is
511 // stored into the alloca.
513 PointerAllocaValues
[AllocaNum
] = Info
.AllocaPointerVal
;
515 // Remember the dbg.declare intrinsic describing this alloca, if any.
516 if (Info
.DbgDeclare
) AllocaDbgDeclares
[AllocaNum
] = Info
.DbgDeclare
;
518 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
519 AllocaLookup
[Allocas
[AllocaNum
]] = AllocaNum
;
521 // At this point, we're committed to promoting the alloca using IDF's, and
522 // the standard SSA construction algorithm. Determine which blocks need PHI
523 // nodes and see if we can optimize out some work by avoiding insertion of
525 DetermineInsertionPoint(AI
, AllocaNum
, Info
);
529 return; // All of the allocas must have been trivial!
534 // Set the incoming values for the basic block to be null values for all of
535 // the alloca's. We do this in case there is a load of a value that has not
536 // been stored yet. In this case, it will get this null value.
538 RenamePassData::ValVector
Values(Allocas
.size());
539 for (unsigned i
= 0, e
= Allocas
.size(); i
!= e
; ++i
)
540 Values
[i
] = UndefValue::get(Allocas
[i
]->getAllocatedType());
542 // Walks all basic blocks in the function performing the SSA rename algorithm
543 // and inserting the phi nodes we marked as necessary
545 std::vector
<RenamePassData
> RenamePassWorkList
;
546 RenamePassWorkList
.push_back(RenamePassData(F
.begin(), 0, Values
));
549 RPD
.swap(RenamePassWorkList
.back());
550 RenamePassWorkList
.pop_back();
551 // RenamePass may add new worklist entries.
552 RenamePass(RPD
.BB
, RPD
.Pred
, RPD
.Values
, RenamePassWorkList
);
553 } while (!RenamePassWorkList
.empty());
555 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
558 // Remove the allocas themselves from the function.
559 for (unsigned i
= 0, e
= Allocas
.size(); i
!= e
; ++i
) {
560 Instruction
*A
= Allocas
[i
];
562 // If there are any uses of the alloca instructions left, they must be in
563 // unreachable basic blocks that were not processed by walking the dominator
564 // tree. Just delete the users now.
566 A
->replaceAllUsesWith(UndefValue::get(A
->getType()));
567 if (AST
) AST
->deleteValue(A
);
568 A
->eraseFromParent();
571 // Remove alloca's dbg.declare instrinsics from the function.
572 for (unsigned i
= 0, e
= AllocaDbgDeclares
.size(); i
!= e
; ++i
)
573 if (DbgDeclareInst
*DDI
= AllocaDbgDeclares
[i
])
574 DDI
->eraseFromParent();
576 // Loop over all of the PHI nodes and see if there are any that we can get
577 // rid of because they merge all of the same incoming values. This can
578 // happen due to undef values coming into the PHI nodes. This process is
579 // iterative, because eliminating one PHI node can cause others to be removed.
580 bool EliminatedAPHI
= true;
581 while (EliminatedAPHI
) {
582 EliminatedAPHI
= false;
584 for (DenseMap
<std::pair
<BasicBlock
*, unsigned>, PHINode
*>::iterator I
=
585 NewPhiNodes
.begin(), E
= NewPhiNodes
.end(); I
!= E
;) {
586 PHINode
*PN
= I
->second
;
588 // If this PHI node merges one value and/or undefs, get the value.
589 if (Value
*V
= SimplifyInstruction(PN
, 0, &DT
)) {
590 if (AST
&& PN
->getType()->isPointerTy())
591 AST
->deleteValue(PN
);
592 PN
->replaceAllUsesWith(V
);
593 PN
->eraseFromParent();
594 NewPhiNodes
.erase(I
++);
595 EliminatedAPHI
= true;
602 // At this point, the renamer has added entries to PHI nodes for all reachable
603 // code. Unfortunately, there may be unreachable blocks which the renamer
604 // hasn't traversed. If this is the case, the PHI nodes may not
605 // have incoming values for all predecessors. Loop over all PHI nodes we have
606 // created, inserting undef values if they are missing any incoming values.
608 for (DenseMap
<std::pair
<BasicBlock
*, unsigned>, PHINode
*>::iterator I
=
609 NewPhiNodes
.begin(), E
= NewPhiNodes
.end(); I
!= E
; ++I
) {
610 // We want to do this once per basic block. As such, only process a block
611 // when we find the PHI that is the first entry in the block.
612 PHINode
*SomePHI
= I
->second
;
613 BasicBlock
*BB
= SomePHI
->getParent();
614 if (&BB
->front() != SomePHI
)
617 // Only do work here if there the PHI nodes are missing incoming values. We
618 // know that all PHI nodes that were inserted in a block will have the same
619 // number of incoming values, so we can just check any of them.
620 if (SomePHI
->getNumIncomingValues() == getNumPreds(BB
))
623 // Get the preds for BB.
624 SmallVector
<BasicBlock
*, 16> Preds(pred_begin(BB
), pred_end(BB
));
626 // Ok, now we know that all of the PHI nodes are missing entries for some
627 // basic blocks. Start by sorting the incoming predecessors for efficient
629 std::sort(Preds
.begin(), Preds
.end());
631 // Now we loop through all BB's which have entries in SomePHI and remove
632 // them from the Preds list.
633 for (unsigned i
= 0, e
= SomePHI
->getNumIncomingValues(); i
!= e
; ++i
) {
634 // Do a log(n) search of the Preds list for the entry we want.
635 SmallVector
<BasicBlock
*, 16>::iterator EntIt
=
636 std::lower_bound(Preds
.begin(), Preds
.end(),
637 SomePHI
->getIncomingBlock(i
));
638 assert(EntIt
!= Preds
.end() && *EntIt
== SomePHI
->getIncomingBlock(i
)&&
639 "PHI node has entry for a block which is not a predecessor!");
645 // At this point, the blocks left in the preds list must have dummy
646 // entries inserted into every PHI nodes for the block. Update all the phi
647 // nodes in this block that we are inserting (there could be phis before
649 unsigned NumBadPreds
= SomePHI
->getNumIncomingValues();
650 BasicBlock::iterator BBI
= BB
->begin();
651 while ((SomePHI
= dyn_cast
<PHINode
>(BBI
++)) &&
652 SomePHI
->getNumIncomingValues() == NumBadPreds
) {
653 Value
*UndefVal
= UndefValue::get(SomePHI
->getType());
654 for (unsigned pred
= 0, e
= Preds
.size(); pred
!= e
; ++pred
)
655 SomePHI
->addIncoming(UndefVal
, Preds
[pred
]);
663 /// ComputeLiveInBlocks - Determine which blocks the value is live in. These
664 /// are blocks which lead to uses. Knowing this allows us to avoid inserting
665 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
667 void PromoteMem2Reg::
668 ComputeLiveInBlocks(AllocaInst
*AI
, AllocaInfo
&Info
,
669 const SmallPtrSet
<BasicBlock
*, 32> &DefBlocks
,
670 SmallPtrSet
<BasicBlock
*, 32> &LiveInBlocks
) {
672 // To determine liveness, we must iterate through the predecessors of blocks
673 // where the def is live. Blocks are added to the worklist if we need to
674 // check their predecessors. Start with all the using blocks.
675 SmallVector
<BasicBlock
*, 64> LiveInBlockWorklist(Info
.UsingBlocks
.begin(),
676 Info
.UsingBlocks
.end());
678 // If any of the using blocks is also a definition block, check to see if the
679 // definition occurs before or after the use. If it happens before the use,
680 // the value isn't really live-in.
681 for (unsigned i
= 0, e
= LiveInBlockWorklist
.size(); i
!= e
; ++i
) {
682 BasicBlock
*BB
= LiveInBlockWorklist
[i
];
683 if (!DefBlocks
.count(BB
)) continue;
685 // Okay, this is a block that both uses and defines the value. If the first
686 // reference to the alloca is a def (store), then we know it isn't live-in.
687 for (BasicBlock::iterator I
= BB
->begin(); ; ++I
) {
688 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
)) {
689 if (SI
->getOperand(1) != AI
) continue;
691 // We found a store to the alloca before a load. The alloca is not
692 // actually live-in here.
693 LiveInBlockWorklist
[i
] = LiveInBlockWorklist
.back();
694 LiveInBlockWorklist
.pop_back();
699 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
700 if (LI
->getOperand(0) != AI
) continue;
702 // Okay, we found a load before a store to the alloca. It is actually
703 // live into this block.
709 // Now that we have a set of blocks where the phi is live-in, recursively add
710 // their predecessors until we find the full region the value is live.
711 while (!LiveInBlockWorklist
.empty()) {
712 BasicBlock
*BB
= LiveInBlockWorklist
.pop_back_val();
714 // The block really is live in here, insert it into the set. If already in
715 // the set, then it has already been processed.
716 if (!LiveInBlocks
.insert(BB
))
719 // Since the value is live into BB, it is either defined in a predecessor or
720 // live into it to. Add the preds to the worklist unless they are a
722 for (pred_iterator PI
= pred_begin(BB
), E
= pred_end(BB
); PI
!= E
; ++PI
) {
725 // The value is not live into a predecessor if it defines the value.
726 if (DefBlocks
.count(P
))
729 // Otherwise it is, add to the worklist.
730 LiveInBlockWorklist
.push_back(P
);
735 /// DetermineInsertionPoint - At this point, we're committed to promoting the
736 /// alloca using IDF's, and the standard SSA construction algorithm. Determine
737 /// which blocks need phi nodes and see if we can optimize out some work by
738 /// avoiding insertion of dead phi nodes.
739 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst
*AI
, unsigned AllocaNum
,
741 // Unique the set of defining blocks for efficient lookup.
742 SmallPtrSet
<BasicBlock
*, 32> DefBlocks
;
743 DefBlocks
.insert(Info
.DefiningBlocks
.begin(), Info
.DefiningBlocks
.end());
745 // Determine which blocks the value is live in. These are blocks which lead
747 SmallPtrSet
<BasicBlock
*, 32> LiveInBlocks
;
748 ComputeLiveInBlocks(AI
, Info
, DefBlocks
, LiveInBlocks
);
750 // Use a priority queue keyed on dominator tree level so that inserted nodes
751 // are handled from the bottom of the dominator tree upwards.
752 typedef std::priority_queue
<DomTreeNodePair
, SmallVector
<DomTreeNodePair
, 32>,
753 DomTreeNodeCompare
> IDFPriorityQueue
;
756 for (SmallPtrSet
<BasicBlock
*, 32>::const_iterator I
= DefBlocks
.begin(),
757 E
= DefBlocks
.end(); I
!= E
; ++I
) {
758 if (DomTreeNode
*Node
= DT
.getNode(*I
))
759 PQ
.push(std::make_pair(Node
, DomLevels
[Node
]));
762 SmallVector
<std::pair
<unsigned, BasicBlock
*>, 32> DFBlocks
;
763 SmallPtrSet
<DomTreeNode
*, 32> Visited
;
764 SmallVector
<DomTreeNode
*, 32> Worklist
;
765 while (!PQ
.empty()) {
766 DomTreeNodePair RootPair
= PQ
.top();
768 DomTreeNode
*Root
= RootPair
.first
;
769 unsigned RootLevel
= RootPair
.second
;
771 // Walk all dominator tree children of Root, inspecting their CFG edges with
772 // targets elsewhere on the dominator tree. Only targets whose level is at
773 // most Root's level are added to the iterated dominance frontier of the
777 Worklist
.push_back(Root
);
779 while (!Worklist
.empty()) {
780 DomTreeNode
*Node
= Worklist
.pop_back_val();
781 BasicBlock
*BB
= Node
->getBlock();
783 for (succ_iterator SI
= succ_begin(BB
), SE
= succ_end(BB
); SI
!= SE
;
785 DomTreeNode
*SuccNode
= DT
.getNode(*SI
);
787 // Quickly skip all CFG edges that are also dominator tree edges instead
788 // of catching them below.
789 if (SuccNode
->getIDom() == Node
)
792 unsigned SuccLevel
= DomLevels
[SuccNode
];
793 if (SuccLevel
> RootLevel
)
796 if (!Visited
.insert(SuccNode
))
799 BasicBlock
*SuccBB
= SuccNode
->getBlock();
800 if (!LiveInBlocks
.count(SuccBB
))
803 DFBlocks
.push_back(std::make_pair(BBNumbers
[SuccBB
], SuccBB
));
804 if (!DefBlocks
.count(SuccBB
))
805 PQ
.push(std::make_pair(SuccNode
, SuccLevel
));
808 for (DomTreeNode::iterator CI
= Node
->begin(), CE
= Node
->end(); CI
!= CE
;
810 if (!Visited
.count(*CI
))
811 Worklist
.push_back(*CI
);
816 if (DFBlocks
.size() > 1)
817 std::sort(DFBlocks
.begin(), DFBlocks
.end());
819 unsigned CurrentVersion
= 0;
820 for (unsigned i
= 0, e
= DFBlocks
.size(); i
!= e
; ++i
)
821 QueuePhiNode(DFBlocks
[i
].second
, AllocaNum
, CurrentVersion
);
824 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
825 /// replace any loads of it that are directly dominated by the definition with
826 /// the value stored.
827 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst
*AI
,
829 LargeBlockInfo
&LBI
) {
830 StoreInst
*OnlyStore
= Info
.OnlyStore
;
831 bool StoringGlobalVal
= !isa
<Instruction
>(OnlyStore
->getOperand(0));
832 BasicBlock
*StoreBB
= OnlyStore
->getParent();
835 // Clear out UsingBlocks. We will reconstruct it here if needed.
836 Info
.UsingBlocks
.clear();
838 for (Value::use_iterator UI
= AI
->use_begin(), E
= AI
->use_end(); UI
!= E
; ) {
839 Instruction
*UserInst
= cast
<Instruction
>(*UI
++);
840 if (!isa
<LoadInst
>(UserInst
)) {
841 assert(UserInst
== OnlyStore
&& "Should only have load/stores");
844 LoadInst
*LI
= cast
<LoadInst
>(UserInst
);
846 // Okay, if we have a load from the alloca, we want to replace it with the
847 // only value stored to the alloca. We can do this if the value is
848 // dominated by the store. If not, we use the rest of the mem2reg machinery
849 // to insert the phi nodes as needed.
850 if (!StoringGlobalVal
) { // Non-instructions are always dominated.
851 if (LI
->getParent() == StoreBB
) {
852 // If we have a use that is in the same block as the store, compare the
853 // indices of the two instructions to see which one came first. If the
854 // load came before the store, we can't handle it.
855 if (StoreIndex
== -1)
856 StoreIndex
= LBI
.getInstructionIndex(OnlyStore
);
858 if (unsigned(StoreIndex
) > LBI
.getInstructionIndex(LI
)) {
859 // Can't handle this load, bail out.
860 Info
.UsingBlocks
.push_back(StoreBB
);
864 } else if (LI
->getParent() != StoreBB
&&
865 !dominates(StoreBB
, LI
->getParent())) {
866 // If the load and store are in different blocks, use BB dominance to
867 // check their relationships. If the store doesn't dom the use, bail
869 Info
.UsingBlocks
.push_back(LI
->getParent());
874 // Otherwise, we *can* safely rewrite this load.
875 Value
*ReplVal
= OnlyStore
->getOperand(0);
876 // If the replacement value is the load, this must occur in unreachable
879 ReplVal
= UndefValue::get(LI
->getType());
880 LI
->replaceAllUsesWith(ReplVal
);
881 if (AST
&& LI
->getType()->isPointerTy())
882 AST
->deleteValue(LI
);
883 LI
->eraseFromParent();
890 /// StoreIndexSearchPredicate - This is a helper predicate used to search by the
891 /// first element of a pair.
892 struct StoreIndexSearchPredicate
{
893 bool operator()(const std::pair
<unsigned, StoreInst
*> &LHS
,
894 const std::pair
<unsigned, StoreInst
*> &RHS
) {
895 return LHS
.first
< RHS
.first
;
901 /// PromoteSingleBlockAlloca - Many allocas are only used within a single basic
902 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
903 /// potentially useless PHI nodes by just performing a single linear pass over
904 /// the basic block using the Alloca.
906 /// If we cannot promote this alloca (because it is read before it is written),
907 /// return true. This is necessary in cases where, due to control flow, the
908 /// alloca is potentially undefined on some control flow paths. e.g. code like
909 /// this is potentially correct:
911 /// for (...) { if (c) { A = undef; undef = B; } }
913 /// ... so long as A is not used before undef is set.
915 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst
*AI
, AllocaInfo
&Info
,
916 LargeBlockInfo
&LBI
) {
917 // The trickiest case to handle is when we have large blocks. Because of this,
918 // this code is optimized assuming that large blocks happen. This does not
919 // significantly pessimize the small block case. This uses LargeBlockInfo to
920 // make it efficient to get the index of various operations in the block.
922 // Clear out UsingBlocks. We will reconstruct it here if needed.
923 Info
.UsingBlocks
.clear();
925 // Walk the use-def list of the alloca, getting the locations of all stores.
926 typedef SmallVector
<std::pair
<unsigned, StoreInst
*>, 64> StoresByIndexTy
;
927 StoresByIndexTy StoresByIndex
;
929 for (Value::use_iterator UI
= AI
->use_begin(), E
= AI
->use_end();
931 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(*UI
))
932 StoresByIndex
.push_back(std::make_pair(LBI
.getInstructionIndex(SI
), SI
));
934 // If there are no stores to the alloca, just replace any loads with undef.
935 if (StoresByIndex
.empty()) {
936 for (Value::use_iterator UI
= AI
->use_begin(), E
= AI
->use_end(); UI
!= E
;)
937 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(*UI
++)) {
938 LI
->replaceAllUsesWith(UndefValue::get(LI
->getType()));
939 if (AST
&& LI
->getType()->isPointerTy())
940 AST
->deleteValue(LI
);
942 LI
->eraseFromParent();
947 // Sort the stores by their index, making it efficient to do a lookup with a
949 std::sort(StoresByIndex
.begin(), StoresByIndex
.end());
951 // Walk all of the loads from this alloca, replacing them with the nearest
952 // store above them, if any.
953 for (Value::use_iterator UI
= AI
->use_begin(), E
= AI
->use_end(); UI
!= E
;) {
954 LoadInst
*LI
= dyn_cast
<LoadInst
>(*UI
++);
957 unsigned LoadIdx
= LBI
.getInstructionIndex(LI
);
959 // Find the nearest store that has a lower than this load.
960 StoresByIndexTy::iterator I
=
961 std::lower_bound(StoresByIndex
.begin(), StoresByIndex
.end(),
962 std::pair
<unsigned, StoreInst
*>(LoadIdx
, static_cast<StoreInst
*>(0)),
963 StoreIndexSearchPredicate());
965 // If there is no store before this load, then we can't promote this load.
966 if (I
== StoresByIndex
.begin()) {
967 // Can't handle this load, bail out.
968 Info
.UsingBlocks
.push_back(LI
->getParent());
972 // Otherwise, there was a store before this load, the load takes its value.
974 LI
->replaceAllUsesWith(I
->second
->getOperand(0));
975 if (AST
&& LI
->getType()->isPointerTy())
976 AST
->deleteValue(LI
);
977 LI
->eraseFromParent();
982 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
983 // Alloca returns true if there wasn't already a phi-node for that variable
985 bool PromoteMem2Reg::QueuePhiNode(BasicBlock
*BB
, unsigned AllocaNo
,
987 // Look up the basic-block in question.
988 PHINode
*&PN
= NewPhiNodes
[std::make_pair(BB
, AllocaNo
)];
990 // If the BB already has a phi node added for the i'th alloca then we're done!
991 if (PN
) return false;
993 // Create a PhiNode using the dereferenced type... and add the phi-node to the
995 PN
= PHINode::Create(Allocas
[AllocaNo
]->getAllocatedType(), getNumPreds(BB
),
996 Allocas
[AllocaNo
]->getName() + "." + Twine(Version
++),
999 PhiToAllocaMap
[PN
] = AllocaNo
;
1001 if (AST
&& PN
->getType()->isPointerTy())
1002 AST
->copyValue(PointerAllocaValues
[AllocaNo
], PN
);
1007 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
1008 // stores to the allocas which we are promoting. IncomingVals indicates what
1009 // value each Alloca contains on exit from the predecessor block Pred.
1011 void PromoteMem2Reg::RenamePass(BasicBlock
*BB
, BasicBlock
*Pred
,
1012 RenamePassData::ValVector
&IncomingVals
,
1013 std::vector
<RenamePassData
> &Worklist
) {
1015 // If we are inserting any phi nodes into this BB, they will already be in the
1017 if (PHINode
*APN
= dyn_cast
<PHINode
>(BB
->begin())) {
1018 // If we have PHI nodes to update, compute the number of edges from Pred to
1020 if (PhiToAllocaMap
.count(APN
)) {
1021 // We want to be able to distinguish between PHI nodes being inserted by
1022 // this invocation of mem2reg from those phi nodes that already existed in
1023 // the IR before mem2reg was run. We determine that APN is being inserted
1024 // because it is missing incoming edges. All other PHI nodes being
1025 // inserted by this pass of mem2reg will have the same number of incoming
1026 // operands so far. Remember this count.
1027 unsigned NewPHINumOperands
= APN
->getNumOperands();
1029 unsigned NumEdges
= 0;
1030 for (succ_iterator I
= succ_begin(Pred
), E
= succ_end(Pred
); I
!= E
; ++I
)
1033 assert(NumEdges
&& "Must be at least one edge from Pred to BB!");
1035 // Add entries for all the phis.
1036 BasicBlock::iterator PNI
= BB
->begin();
1038 unsigned AllocaNo
= PhiToAllocaMap
[APN
];
1040 // Add N incoming values to the PHI node.
1041 for (unsigned i
= 0; i
!= NumEdges
; ++i
)
1042 APN
->addIncoming(IncomingVals
[AllocaNo
], Pred
);
1044 // The currently active variable for this block is now the PHI.
1045 IncomingVals
[AllocaNo
] = APN
;
1047 // Get the next phi node.
1049 APN
= dyn_cast
<PHINode
>(PNI
);
1050 if (APN
== 0) break;
1052 // Verify that it is missing entries. If not, it is not being inserted
1053 // by this mem2reg invocation so we want to ignore it.
1054 } while (APN
->getNumOperands() == NewPHINumOperands
);
1058 // Don't revisit blocks.
1059 if (!Visited
.insert(BB
)) return;
1061 for (BasicBlock::iterator II
= BB
->begin(); !isa
<TerminatorInst
>(II
); ) {
1062 Instruction
*I
= II
++; // get the instruction, increment iterator
1064 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
1065 AllocaInst
*Src
= dyn_cast
<AllocaInst
>(LI
->getPointerOperand());
1068 DenseMap
<AllocaInst
*, unsigned>::iterator AI
= AllocaLookup
.find(Src
);
1069 if (AI
== AllocaLookup
.end()) continue;
1071 Value
*V
= IncomingVals
[AI
->second
];
1073 // Anything using the load now uses the current value.
1074 LI
->replaceAllUsesWith(V
);
1075 if (AST
&& LI
->getType()->isPointerTy())
1076 AST
->deleteValue(LI
);
1077 BB
->getInstList().erase(LI
);
1078 } else if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
)) {
1079 // Delete this instruction and mark the name as the current holder of the
1081 AllocaInst
*Dest
= dyn_cast
<AllocaInst
>(SI
->getPointerOperand());
1082 if (!Dest
) continue;
1084 DenseMap
<AllocaInst
*, unsigned>::iterator ai
= AllocaLookup
.find(Dest
);
1085 if (ai
== AllocaLookup
.end())
1088 // what value were we writing?
1089 IncomingVals
[ai
->second
] = SI
->getOperand(0);
1090 // Record debuginfo for the store before removing it.
1091 if (DbgDeclareInst
*DDI
= AllocaDbgDeclares
[ai
->second
]) {
1093 DIB
= new DIBuilder(*SI
->getParent()->getParent()->getParent());
1094 ConvertDebugDeclareToDebugValue(DDI
, SI
, *DIB
);
1096 BB
->getInstList().erase(SI
);
1100 // 'Recurse' to our successors.
1101 succ_iterator I
= succ_begin(BB
), E
= succ_end(BB
);
1104 // Keep track of the successors so we don't visit the same successor twice
1105 SmallPtrSet
<BasicBlock
*, 8> VisitedSuccs
;
1107 // Handle the first successor without using the worklist.
1108 VisitedSuccs
.insert(*I
);
1114 if (VisitedSuccs
.insert(*I
))
1115 Worklist
.push_back(RenamePassData(*I
, Pred
, IncomingVals
));
1120 /// PromoteMemToReg - Promote the specified list of alloca instructions into
1121 /// scalar registers, inserting PHI nodes as appropriate. This function does
1122 /// not modify the CFG of the function at all. All allocas must be from the
1125 /// If AST is specified, the specified tracker is updated to reflect changes
1128 void llvm::PromoteMemToReg(const std::vector
<AllocaInst
*> &Allocas
,
1129 DominatorTree
&DT
, AliasSetTracker
*AST
) {
1130 // If there is nothing to do, bail out...
1131 if (Allocas
.empty()) return;
1133 PromoteMem2Reg(Allocas
, DT
, AST
).run();