1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
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 family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/Constant.h"
20 #include "llvm/Type.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Target/TargetData.h"
28 /// DeleteDeadBlock - Delete the specified block, which must have no
30 void llvm::DeleteDeadBlock(BasicBlock
*BB
) {
31 assert((pred_begin(BB
) == pred_end(BB
) ||
32 // Can delete self loop.
33 BB
->getSinglePredecessor() == BB
) && "Block is not dead!");
34 TerminatorInst
*BBTerm
= BB
->getTerminator();
36 // Loop through all of our successors and make sure they know that one
37 // of their predecessors is going away.
38 for (unsigned i
= 0, e
= BBTerm
->getNumSuccessors(); i
!= e
; ++i
)
39 BBTerm
->getSuccessor(i
)->removePredecessor(BB
);
41 // Zap all the instructions in the block.
42 while (!BB
->empty()) {
43 Instruction
&I
= BB
->back();
44 // If this instruction is used, replace uses with an arbitrary value.
45 // Because control flow can't get here, we don't care what we replace the
46 // value with. Note that since this block is unreachable, and all values
47 // contained within it must dominate their uses, that all uses will
48 // eventually be removed (they are themselves dead).
50 I
.replaceAllUsesWith(UndefValue::get(I
.getType()));
51 BB
->getInstList().pop_back();
55 BB
->eraseFromParent();
58 /// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
59 /// any single-entry PHI nodes in it, fold them away. This handles the case
60 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
61 /// when the block has exactly one predecessor.
62 void llvm::FoldSingleEntryPHINodes(BasicBlock
*BB
) {
63 if (!isa
<PHINode
>(BB
->begin()))
66 while (PHINode
*PN
= dyn_cast
<PHINode
>(BB
->begin())) {
67 if (PN
->getIncomingValue(0) != PN
)
68 PN
->replaceAllUsesWith(PN
->getIncomingValue(0));
70 PN
->replaceAllUsesWith(UndefValue::get(PN
->getType()));
71 PN
->eraseFromParent();
76 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
77 /// if possible. The return value indicates success or failure.
78 bool llvm::MergeBlockIntoPredecessor(BasicBlock
* BB
, Pass
* P
) {
79 pred_iterator
PI(pred_begin(BB
)), PE(pred_end(BB
));
80 // Can't merge the entry block.
81 if (pred_begin(BB
) == pred_end(BB
)) return false;
83 BasicBlock
*PredBB
= *PI
++;
84 for (; PI
!= PE
; ++PI
) // Search all predecessors, see if they are all same
86 PredBB
= 0; // There are multiple different predecessors...
90 // Can't merge if there are multiple predecessors.
91 if (!PredBB
) return false;
92 // Don't break self-loops.
93 if (PredBB
== BB
) return false;
94 // Don't break invokes.
95 if (isa
<InvokeInst
>(PredBB
->getTerminator())) return false;
97 succ_iterator
SI(succ_begin(PredBB
)), SE(succ_end(PredBB
));
98 BasicBlock
* OnlySucc
= BB
;
99 for (; SI
!= SE
; ++SI
)
100 if (*SI
!= OnlySucc
) {
101 OnlySucc
= 0; // There are multiple distinct successors!
105 // Can't merge if there are multiple successors.
106 if (!OnlySucc
) return false;
108 // Can't merge if there is PHI loop.
109 for (BasicBlock::iterator BI
= BB
->begin(), BE
= BB
->end(); BI
!= BE
; ++BI
) {
110 if (PHINode
*PN
= dyn_cast
<PHINode
>(BI
)) {
111 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
112 if (PN
->getIncomingValue(i
) == PN
)
118 // Begin by getting rid of unneeded PHIs.
119 while (PHINode
*PN
= dyn_cast
<PHINode
>(&BB
->front())) {
120 PN
->replaceAllUsesWith(PN
->getIncomingValue(0));
121 BB
->getInstList().pop_front(); // Delete the phi node...
124 // Delete the unconditional branch from the predecessor...
125 PredBB
->getInstList().pop_back();
127 // Move all definitions in the successor to the predecessor...
128 PredBB
->getInstList().splice(PredBB
->end(), BB
->getInstList());
130 // Make all PHI nodes that referred to BB now refer to Pred as their
132 BB
->replaceAllUsesWith(PredBB
);
134 // Inherit predecessors name if it exists.
135 if (!PredBB
->hasName())
136 PredBB
->takeName(BB
);
138 // Finally, erase the old block and update dominator info.
140 if (DominatorTree
* DT
= P
->getAnalysisIfAvailable
<DominatorTree
>()) {
141 DomTreeNode
* DTN
= DT
->getNode(BB
);
142 DomTreeNode
* PredDTN
= DT
->getNode(PredBB
);
145 SmallPtrSet
<DomTreeNode
*, 8> Children(DTN
->begin(), DTN
->end());
146 for (SmallPtrSet
<DomTreeNode
*, 8>::iterator DI
= Children
.begin(),
147 DE
= Children
.end(); DI
!= DE
; ++DI
)
148 DT
->changeImmediateDominator(*DI
, PredDTN
);
155 BB
->eraseFromParent();
161 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
162 /// with a value, then remove and delete the original instruction.
164 void llvm::ReplaceInstWithValue(BasicBlock::InstListType
&BIL
,
165 BasicBlock::iterator
&BI
, Value
*V
) {
166 Instruction
&I
= *BI
;
167 // Replaces all of the uses of the instruction with uses of the value
168 I
.replaceAllUsesWith(V
);
170 // Make sure to propagate a name if there is one already.
171 if (I
.hasName() && !V
->hasName())
174 // Delete the unnecessary instruction now...
179 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
180 /// instruction specified by I. The original instruction is deleted and BI is
181 /// updated to point to the new instruction.
183 void llvm::ReplaceInstWithInst(BasicBlock::InstListType
&BIL
,
184 BasicBlock::iterator
&BI
, Instruction
*I
) {
185 assert(I
->getParent() == 0 &&
186 "ReplaceInstWithInst: Instruction already inserted into basic block!");
188 // Insert the new instruction into the basic block...
189 BasicBlock::iterator New
= BIL
.insert(BI
, I
);
191 // Replace all uses of the old instruction, and delete it.
192 ReplaceInstWithValue(BIL
, BI
, I
);
194 // Move BI back to point to the newly inserted instruction
198 /// ReplaceInstWithInst - Replace the instruction specified by From with the
199 /// instruction specified by To.
201 void llvm::ReplaceInstWithInst(Instruction
*From
, Instruction
*To
) {
202 BasicBlock::iterator
BI(From
);
203 ReplaceInstWithInst(From
->getParent()->getInstList(), BI
, To
);
206 /// RemoveSuccessor - Change the specified terminator instruction such that its
207 /// successor SuccNum no longer exists. Because this reduces the outgoing
208 /// degree of the current basic block, the actual terminator instruction itself
209 /// may have to be changed. In the case where the last successor of the block
210 /// is deleted, a return instruction is inserted in its place which can cause a
211 /// surprising change in program behavior if it is not expected.
213 void llvm::RemoveSuccessor(TerminatorInst
*TI
, unsigned SuccNum
) {
214 assert(SuccNum
< TI
->getNumSuccessors() &&
215 "Trying to remove a nonexistant successor!");
217 // If our old successor block contains any PHI nodes, remove the entry in the
218 // PHI nodes that comes from this branch...
220 BasicBlock
*BB
= TI
->getParent();
221 TI
->getSuccessor(SuccNum
)->removePredecessor(BB
);
223 TerminatorInst
*NewTI
= 0;
224 switch (TI
->getOpcode()) {
225 case Instruction::Br
:
226 // If this is a conditional branch... convert to unconditional branch.
227 if (TI
->getNumSuccessors() == 2) {
228 cast
<BranchInst
>(TI
)->setUnconditionalDest(TI
->getSuccessor(1-SuccNum
));
229 } else { // Otherwise convert to a return instruction...
232 // Create a value to return... if the function doesn't return null...
233 if (BB
->getParent()->getReturnType() != Type::VoidTy
)
234 RetVal
= Constant::getNullValue(BB
->getParent()->getReturnType());
236 // Create the return...
237 NewTI
= ReturnInst::Create(RetVal
);
241 case Instruction::Invoke
: // Should convert to call
242 case Instruction::Switch
: // Should remove entry
244 case Instruction::Ret
: // Cannot happen, has no successors!
245 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
249 if (NewTI
) // If it's a different instruction, replace.
250 ReplaceInstWithInst(TI
, NewTI
);
253 /// SplitEdge - Split the edge connecting specified block. Pass P must
255 BasicBlock
*llvm::SplitEdge(BasicBlock
*BB
, BasicBlock
*Succ
, Pass
*P
) {
256 TerminatorInst
*LatchTerm
= BB
->getTerminator();
257 unsigned SuccNum
= 0;
259 unsigned e
= LatchTerm
->getNumSuccessors();
261 for (unsigned i
= 0; ; ++i
) {
262 assert(i
!= e
&& "Didn't find edge?");
263 if (LatchTerm
->getSuccessor(i
) == Succ
) {
269 // If this is a critical edge, let SplitCriticalEdge do it.
270 if (SplitCriticalEdge(BB
->getTerminator(), SuccNum
, P
))
271 return LatchTerm
->getSuccessor(SuccNum
);
273 // If the edge isn't critical, then BB has a single successor or Succ has a
274 // single pred. Split the block.
275 BasicBlock::iterator SplitPoint
;
276 if (BasicBlock
*SP
= Succ
->getSinglePredecessor()) {
277 // If the successor only has a single pred, split the top of the successor
279 assert(SP
== BB
&& "CFG broken");
281 return SplitBlock(Succ
, Succ
->begin(), P
);
283 // Otherwise, if BB has a single successor, split it at the bottom of the
285 assert(BB
->getTerminator()->getNumSuccessors() == 1 &&
286 "Should have a single succ!");
287 return SplitBlock(BB
, BB
->getTerminator(), P
);
291 /// SplitBlock - Split the specified block at the specified instruction - every
292 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
293 /// to a new block. The two blocks are joined by an unconditional branch and
294 /// the loop info is updated.
296 BasicBlock
*llvm::SplitBlock(BasicBlock
*Old
, Instruction
*SplitPt
, Pass
*P
) {
297 BasicBlock::iterator SplitIt
= SplitPt
;
298 while (isa
<PHINode
>(SplitIt
))
300 BasicBlock
*New
= Old
->splitBasicBlock(SplitIt
, Old
->getName()+".split");
302 // The new block lives in whichever loop the old one did.
303 if (LoopInfo
* LI
= P
->getAnalysisIfAvailable
<LoopInfo
>())
304 if (Loop
*L
= LI
->getLoopFor(Old
))
305 L
->addBasicBlockToLoop(New
, LI
->getBase());
307 if (DominatorTree
*DT
= P
->getAnalysisIfAvailable
<DominatorTree
>())
309 // Old dominates New. New node domiantes all other nodes dominated by Old.
310 DomTreeNode
*OldNode
= DT
->getNode(Old
);
311 std::vector
<DomTreeNode
*> Children
;
312 for (DomTreeNode::iterator I
= OldNode
->begin(), E
= OldNode
->end();
314 Children
.push_back(*I
);
316 DomTreeNode
*NewNode
= DT
->addNewBlock(New
,Old
);
318 for (std::vector
<DomTreeNode
*>::iterator I
= Children
.begin(),
319 E
= Children
.end(); I
!= E
; ++I
)
320 DT
->changeImmediateDominator(*I
, NewNode
);
323 if (DominanceFrontier
*DF
= P
->getAnalysisIfAvailable
<DominanceFrontier
>())
330 /// SplitBlockPredecessors - This method transforms BB by introducing a new
331 /// basic block into the function, and moving some of the predecessors of BB to
332 /// be predecessors of the new block. The new predecessors are indicated by the
333 /// Preds array, which has NumPreds elements in it. The new block is given a
334 /// suffix of 'Suffix'.
336 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
337 /// DominanceFrontier, but no other analyses.
338 BasicBlock
*llvm::SplitBlockPredecessors(BasicBlock
*BB
,
339 BasicBlock
*const *Preds
,
340 unsigned NumPreds
, const char *Suffix
,
342 // Create new basic block, insert right before the original block.
344 BasicBlock::Create(BB
->getName()+Suffix
, BB
->getParent(), BB
);
346 // The new block unconditionally branches to the old block.
347 BranchInst
*BI
= BranchInst::Create(BB
, NewBB
);
349 // Move the edges from Preds to point to NewBB instead of BB.
350 for (unsigned i
= 0; i
!= NumPreds
; ++i
)
351 Preds
[i
]->getTerminator()->replaceUsesOfWith(BB
, NewBB
);
353 // Update dominator tree and dominator frontier if available.
354 DominatorTree
*DT
= P
? P
->getAnalysisIfAvailable
<DominatorTree
>() : 0;
356 DT
->splitBlock(NewBB
);
357 if (DominanceFrontier
*DF
= P
? P
->getAnalysisIfAvailable
<DominanceFrontier
>():0)
358 DF
->splitBlock(NewBB
);
359 AliasAnalysis
*AA
= P
? P
->getAnalysisIfAvailable
<AliasAnalysis
>() : 0;
362 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
363 // node becomes an incoming value for BB's phi node. However, if the Preds
364 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
365 // account for the newly created predecessor.
367 // Insert dummy values as the incoming value.
368 for (BasicBlock::iterator I
= BB
->begin(); isa
<PHINode
>(I
); ++I
)
369 cast
<PHINode
>(I
)->addIncoming(UndefValue::get(I
->getType()), NewBB
);
373 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
374 for (BasicBlock::iterator I
= BB
->begin(); isa
<PHINode
>(I
); ) {
375 PHINode
*PN
= cast
<PHINode
>(I
++);
377 // Check to see if all of the values coming in are the same. If so, we
378 // don't need to create a new PHI node.
379 Value
*InVal
= PN
->getIncomingValueForBlock(Preds
[0]);
380 for (unsigned i
= 1; i
!= NumPreds
; ++i
)
381 if (InVal
!= PN
->getIncomingValueForBlock(Preds
[i
])) {
387 // If all incoming values for the new PHI would be the same, just don't
388 // make a new PHI. Instead, just remove the incoming values from the old
390 for (unsigned i
= 0; i
!= NumPreds
; ++i
)
391 PN
->removeIncomingValue(Preds
[i
], false);
393 // If the values coming into the block are not the same, we need a PHI.
394 // Create the new PHI node, insert it into NewBB at the end of the block
396 PHINode::Create(PN
->getType(), PN
->getName()+".ph", BI
);
397 if (AA
) AA
->copyValue(PN
, NewPHI
);
399 // Move all of the PHI values for 'Preds' to the new PHI.
400 for (unsigned i
= 0; i
!= NumPreds
; ++i
) {
401 Value
*V
= PN
->removeIncomingValue(Preds
[i
], false);
402 NewPHI
->addIncoming(V
, Preds
[i
]);
407 // Add an incoming value to the PHI node in the loop for the preheader
409 PN
->addIncoming(InVal
, NewBB
);
411 // Check to see if we can eliminate this phi node.
412 if (Value
*V
= PN
->hasConstantValue(DT
!= 0)) {
413 Instruction
*I
= dyn_cast
<Instruction
>(V
);
414 if (!I
|| DT
== 0 || DT
->dominates(I
, PN
)) {
415 PN
->replaceAllUsesWith(V
);
416 if (AA
) AA
->deleteValue(PN
);
417 PN
->eraseFromParent();
425 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
426 /// value. This includes recognizing that %t0 and %t1 will have the same
427 /// value in code like this:
428 /// %t0 = getelementptr \@a, 0, 3
429 /// store i32 0, i32* %t0
430 /// %t1 = getelementptr \@a, 0, 3
431 /// %t2 = load i32* %t1
433 static bool AreEquivalentAddressValues(const Value
*A
, const Value
*B
) {
434 // Test if the values are trivially equivalent.
435 if (A
== B
) return true;
437 // Test if the values come form identical arithmetic instructions.
438 if (isa
<BinaryOperator
>(A
) || isa
<CastInst
>(A
) ||
439 isa
<PHINode
>(A
) || isa
<GetElementPtrInst
>(A
))
440 if (const Instruction
*BI
= dyn_cast
<Instruction
>(B
))
441 if (cast
<Instruction
>(A
)->isIdenticalTo(BI
))
444 // Otherwise they may not be equivalent.
448 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
449 /// instruction before ScanFrom) checking to see if we have the value at the
450 /// memory address *Ptr locally available within a small number of instructions.
451 /// If the value is available, return it.
453 /// If not, return the iterator for the last validated instruction that the
454 /// value would be live through. If we scanned the entire block and didn't find
455 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
456 /// begin() and this returns null. ScanFrom could also be left
458 /// MaxInstsToScan specifies the maximum instructions to scan in the block. If
459 /// it is set to 0, it will scan the whole block. You can also optionally
460 /// specify an alias analysis implementation, which makes this more precise.
461 Value
*llvm::FindAvailableLoadedValue(Value
*Ptr
, BasicBlock
*ScanBB
,
462 BasicBlock::iterator
&ScanFrom
,
463 unsigned MaxInstsToScan
,
465 if (MaxInstsToScan
== 0) MaxInstsToScan
= ~0U;
467 // If we're using alias analysis to disambiguate get the size of *Ptr.
468 unsigned AccessSize
= 0;
470 const Type
*AccessTy
= cast
<PointerType
>(Ptr
->getType())->getElementType();
471 AccessSize
= AA
->getTargetData().getTypeStoreSizeInBits(AccessTy
);
474 while (ScanFrom
!= ScanBB
->begin()) {
475 // We must ignore debug info directives when counting (otherwise they
476 // would affect codegen).
477 Instruction
*Inst
= --ScanFrom
;
478 if (isa
<DbgInfoIntrinsic
>(Inst
))
480 // We skip pointer-to-pointer bitcasts, which are NOPs.
481 // It is necessary for correctness to skip those that feed into a
482 // llvm.dbg.declare, as these are not present when debugging is off.
483 if (isa
<BitCastInst
>(Inst
) && isa
<PointerType
>(Inst
->getType()))
486 // Restore ScanFrom to expected value in case next test succeeds
489 // Don't scan huge blocks.
490 if (MaxInstsToScan
-- == 0) return 0;
493 // If this is a load of Ptr, the loaded value is available.
494 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(Inst
))
495 if (AreEquivalentAddressValues(LI
->getOperand(0), Ptr
))
498 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(Inst
)) {
499 // If this is a store through Ptr, the value is available!
500 if (AreEquivalentAddressValues(SI
->getOperand(1), Ptr
))
501 return SI
->getOperand(0);
503 // If Ptr is an alloca and this is a store to a different alloca, ignore
504 // the store. This is a trivial form of alias analysis that is important
505 // for reg2mem'd code.
506 if ((isa
<AllocaInst
>(Ptr
) || isa
<GlobalVariable
>(Ptr
)) &&
507 (isa
<AllocaInst
>(SI
->getOperand(1)) ||
508 isa
<GlobalVariable
>(SI
->getOperand(1))))
511 // If we have alias analysis and it says the store won't modify the loaded
512 // value, ignore the store.
514 (AA
->getModRefInfo(SI
, Ptr
, AccessSize
) & AliasAnalysis::Mod
) == 0)
517 // Otherwise the store that may or may not alias the pointer, bail out.
522 // If this is some other instruction that may clobber Ptr, bail out.
523 if (Inst
->mayWriteToMemory()) {
524 // If alias analysis claims that it really won't modify the load,
527 (AA
->getModRefInfo(Inst
, Ptr
, AccessSize
) & AliasAnalysis::Mod
) == 0)
530 // May modify the pointer, bail out.
536 // Got to the start of the block, we didn't find it, but are done for this
541 /// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
542 /// make a copy of the stoppoint before InsertPos (presumably before copying
544 void llvm::CopyPrecedingStopPoint(Instruction
*I
,
545 BasicBlock::iterator InsertPos
) {
546 if (I
!= I
->getParent()->begin()) {
547 BasicBlock::iterator BBI
= I
; --BBI
;
548 if (DbgStopPointInst
*DSPI
= dyn_cast
<DbgStopPointInst
>(BBI
)) {
549 CallInst
*newDSPI
= DSPI
->clone();
550 newDSPI
->insertBefore(InsertPos
);