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/Constant.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/Dominators.h"
26 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
27 /// if possible. The return value indicates success or failure.
28 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
29 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
30 // Can't merge the entry block.
31 if (pred_begin(BB) == pred_end(BB)) return false;
33 BasicBlock *PredBB = *PI++;
34 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
36 PredBB = 0; // There are multiple different predecessors...
40 // Can't merge if there are multiple predecessors.
41 if (!PredBB) return false;
43 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
44 BasicBlock* OnlySucc = BB;
45 for (; SI != SE; ++SI)
46 if (*SI != OnlySucc) {
47 OnlySucc = 0; // There are multiple distinct successors!
51 // Can't merge if there are multiple successors.
52 if (!OnlySucc) return false;
54 // Begin by getting rid of unneeded PHIs.
55 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
56 PN->replaceAllUsesWith(PN->getIncomingValue(0));
57 BB->getInstList().pop_front(); // Delete the phi node...
60 // Delete the unconditional branch from the predecessor...
61 PredBB->getInstList().pop_back();
63 // Move all definitions in the successor to the predecessor...
64 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
66 // Make all PHI nodes that referred to BB now refer to Pred as their
68 BB->replaceAllUsesWith(PredBB);
70 // Inherit predecessors name if it exists.
71 if (!PredBB->hasName())
74 // Finally, erase the old block and update dominator info.
76 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
77 DomTreeNode* DTN = DT->getNode(BB);
78 DomTreeNode* PredDTN = DT->getNode(PredBB);
81 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
82 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
83 DE = Children.end(); DI != DE; ++DI)
84 DT->changeImmediateDominator(*DI, PredDTN);
91 BB->eraseFromParent();
97 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
98 /// with a value, then remove and delete the original instruction.
100 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
101 BasicBlock::iterator &BI, Value *V) {
102 Instruction &I = *BI;
103 // Replaces all of the uses of the instruction with uses of the value
104 I.replaceAllUsesWith(V);
106 // Make sure to propagate a name if there is one already.
107 if (I.hasName() && !V->hasName())
110 // Delete the unnecessary instruction now...
115 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
116 /// instruction specified by I. The original instruction is deleted and BI is
117 /// updated to point to the new instruction.
119 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
120 BasicBlock::iterator &BI, Instruction *I) {
121 assert(I->getParent() == 0 &&
122 "ReplaceInstWithInst: Instruction already inserted into basic block!");
124 // Insert the new instruction into the basic block...
125 BasicBlock::iterator New = BIL.insert(BI, I);
127 // Replace all uses of the old instruction, and delete it.
128 ReplaceInstWithValue(BIL, BI, I);
130 // Move BI back to point to the newly inserted instruction
134 /// ReplaceInstWithInst - Replace the instruction specified by From with the
135 /// instruction specified by To.
137 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
138 BasicBlock::iterator BI(From);
139 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
142 /// RemoveSuccessor - Change the specified terminator instruction such that its
143 /// successor SuccNum no longer exists. Because this reduces the outgoing
144 /// degree of the current basic block, the actual terminator instruction itself
145 /// may have to be changed. In the case where the last successor of the block
146 /// is deleted, a return instruction is inserted in its place which can cause a
147 /// surprising change in program behavior if it is not expected.
149 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
150 assert(SuccNum < TI->getNumSuccessors() &&
151 "Trying to remove a nonexistant successor!");
153 // If our old successor block contains any PHI nodes, remove the entry in the
154 // PHI nodes that comes from this branch...
156 BasicBlock *BB = TI->getParent();
157 TI->getSuccessor(SuccNum)->removePredecessor(BB);
159 TerminatorInst *NewTI = 0;
160 switch (TI->getOpcode()) {
161 case Instruction::Br:
162 // If this is a conditional branch... convert to unconditional branch.
163 if (TI->getNumSuccessors() == 2) {
164 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
165 } else { // Otherwise convert to a return instruction...
168 // Create a value to return... if the function doesn't return null...
169 if (BB->getParent()->getReturnType() != Type::VoidTy)
170 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
172 // Create the return...
173 NewTI = ReturnInst::Create(RetVal);
177 case Instruction::Invoke: // Should convert to call
178 case Instruction::Switch: // Should remove entry
180 case Instruction::Ret: // Cannot happen, has no successors!
181 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
185 if (NewTI) // If it's a different instruction, replace.
186 ReplaceInstWithInst(TI, NewTI);
189 /// SplitEdge - Split the edge connecting specified block. Pass P must
191 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
192 TerminatorInst *LatchTerm = BB->getTerminator();
193 unsigned SuccNum = 0;
194 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
195 assert(i != e && "Didn't find edge?");
196 if (LatchTerm->getSuccessor(i) == Succ) {
202 // If this is a critical edge, let SplitCriticalEdge do it.
203 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
204 return LatchTerm->getSuccessor(SuccNum);
206 // If the edge isn't critical, then BB has a single successor or Succ has a
207 // single pred. Split the block.
208 BasicBlock::iterator SplitPoint;
209 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
210 // If the successor only has a single pred, split the top of the successor
212 assert(SP == BB && "CFG broken");
213 return SplitBlock(Succ, Succ->begin(), P);
215 // Otherwise, if BB has a single successor, split it at the bottom of the
217 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
218 "Should have a single succ!");
219 return SplitBlock(BB, BB->getTerminator(), P);
223 /// SplitBlock - Split the specified block at the specified instruction - every
224 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
225 /// to a new block. The two blocks are joined by an unconditional branch and
226 /// the loop info is updated.
228 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
230 LoopInfo &LI = P->getAnalysis<LoopInfo>();
231 BasicBlock::iterator SplitIt = SplitPt;
232 while (isa<PHINode>(SplitIt))
234 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
236 // The new block lives in whichever loop the old one did.
237 if (Loop *L = LI.getLoopFor(Old))
238 L->addBasicBlockToLoop(New, LI.getBase());
240 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
242 // Old dominates New. New node domiantes all other nodes dominated by Old.
243 DomTreeNode *OldNode = DT->getNode(Old);
244 std::vector<DomTreeNode *> Children;
245 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
247 Children.push_back(*I);
249 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
251 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
252 E = Children.end(); I != E; ++I)
253 DT->changeImmediateDominator(*I, NewNode);
256 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
263 /// SplitBlockPredecessors - This method transforms BB by introducing a new
264 /// basic block into the function, and moving some of the predecessors of BB to
265 /// be predecessors of the new block. The new predecessors are indicated by the
266 /// Preds array, which has NumPreds elements in it. The new block is given a
267 /// suffix of 'Suffix'.
269 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
270 /// DominanceFrontier, but no other analyses.
271 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
272 BasicBlock *const *Preds,
273 unsigned NumPreds, const char *Suffix,
275 // Create new basic block, insert right before the original block.
277 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
279 // The new block unconditionally branches to the old block.
280 BranchInst *BI = BranchInst::Create(BB, NewBB);
282 // Move the edges from Preds to point to NewBB instead of BB.
283 for (unsigned i = 0; i != NumPreds; ++i)
284 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
286 // Update dominator tree and dominator frontier if available.
287 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
289 DT->splitBlock(NewBB);
290 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
291 DF->splitBlock(NewBB);
292 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
295 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
296 // node becomes an incoming value for BB's phi node. However, if the Preds
297 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
298 // account for the newly created predecessor.
300 // Insert dummy values as the incoming value.
301 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
302 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
306 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
307 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
308 PHINode *PN = cast<PHINode>(I++);
310 // Check to see if all of the values coming in are the same. If so, we
311 // don't need to create a new PHI node.
312 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
313 for (unsigned i = 1; i != NumPreds; ++i)
314 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
320 // If all incoming values for the new PHI would be the same, just don't
321 // make a new PHI. Instead, just remove the incoming values from the old
323 for (unsigned i = 0; i != NumPreds; ++i)
324 PN->removeIncomingValue(Preds[i], false);
326 // If the values coming into the block are not the same, we need a PHI.
327 // Create the new PHI node, insert it into NewBB at the end of the block
329 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
330 if (AA) AA->copyValue(PN, NewPHI);
332 // Move all of the PHI values for 'Preds' to the new PHI.
333 for (unsigned i = 0; i != NumPreds; ++i) {
334 Value *V = PN->removeIncomingValue(Preds[i], false);
335 NewPHI->addIncoming(V, Preds[i]);
340 // Add an incoming value to the PHI node in the loop for the preheader
342 PN->addIncoming(InVal, NewBB);
344 // Check to see if we can eliminate this phi node.
345 if (Value *V = PN->hasConstantValue(DT != 0)) {
346 Instruction *I = dyn_cast<Instruction>(V);
347 if (!I || DT == 0 || DT->dominates(I, PN)) {
348 PN->replaceAllUsesWith(V);
349 if (AA) AA->deleteValue(PN);
350 PN->eraseFromParent();