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;
42 // Don't break self-loops.
43 if (PredBB == BB) return false;
44 // Don't break invokes.
45 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
47 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
48 BasicBlock* OnlySucc = BB;
49 for (; SI != SE; ++SI)
50 if (*SI != OnlySucc) {
51 OnlySucc = 0; // There are multiple distinct successors!
55 // Can't merge if there are multiple successors.
56 if (!OnlySucc) return false;
58 // Can't merge if there is PHI loop.
59 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
60 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
61 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
62 if (PN->getIncomingValue(i) == PN)
68 // Begin by getting rid of unneeded PHIs.
69 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
70 PN->replaceAllUsesWith(PN->getIncomingValue(0));
71 BB->getInstList().pop_front(); // Delete the phi node...
74 // Delete the unconditional branch from the predecessor...
75 PredBB->getInstList().pop_back();
77 // Move all definitions in the successor to the predecessor...
78 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
80 // Make all PHI nodes that referred to BB now refer to Pred as their
82 BB->replaceAllUsesWith(PredBB);
84 // Inherit predecessors name if it exists.
85 if (!PredBB->hasName())
88 // Finally, erase the old block and update dominator info.
90 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
91 DomTreeNode* DTN = DT->getNode(BB);
92 DomTreeNode* PredDTN = DT->getNode(PredBB);
95 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
96 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
97 DE = Children.end(); DI != DE; ++DI)
98 DT->changeImmediateDominator(*DI, PredDTN);
105 BB->eraseFromParent();
111 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
112 /// with a value, then remove and delete the original instruction.
114 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
115 BasicBlock::iterator &BI, Value *V) {
116 Instruction &I = *BI;
117 // Replaces all of the uses of the instruction with uses of the value
118 I.replaceAllUsesWith(V);
120 // Make sure to propagate a name if there is one already.
121 if (I.hasName() && !V->hasName())
124 // Delete the unnecessary instruction now...
129 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
130 /// instruction specified by I. The original instruction is deleted and BI is
131 /// updated to point to the new instruction.
133 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
134 BasicBlock::iterator &BI, Instruction *I) {
135 assert(I->getParent() == 0 &&
136 "ReplaceInstWithInst: Instruction already inserted into basic block!");
138 // Insert the new instruction into the basic block...
139 BasicBlock::iterator New = BIL.insert(BI, I);
141 // Replace all uses of the old instruction, and delete it.
142 ReplaceInstWithValue(BIL, BI, I);
144 // Move BI back to point to the newly inserted instruction
148 /// ReplaceInstWithInst - Replace the instruction specified by From with the
149 /// instruction specified by To.
151 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
152 BasicBlock::iterator BI(From);
153 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
156 /// RemoveSuccessor - Change the specified terminator instruction such that its
157 /// successor SuccNum no longer exists. Because this reduces the outgoing
158 /// degree of the current basic block, the actual terminator instruction itself
159 /// may have to be changed. In the case where the last successor of the block
160 /// is deleted, a return instruction is inserted in its place which can cause a
161 /// surprising change in program behavior if it is not expected.
163 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
164 assert(SuccNum < TI->getNumSuccessors() &&
165 "Trying to remove a nonexistant successor!");
167 // If our old successor block contains any PHI nodes, remove the entry in the
168 // PHI nodes that comes from this branch...
170 BasicBlock *BB = TI->getParent();
171 TI->getSuccessor(SuccNum)->removePredecessor(BB);
173 TerminatorInst *NewTI = 0;
174 switch (TI->getOpcode()) {
175 case Instruction::Br:
176 // If this is a conditional branch... convert to unconditional branch.
177 if (TI->getNumSuccessors() == 2) {
178 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
179 } else { // Otherwise convert to a return instruction...
182 // Create a value to return... if the function doesn't return null...
183 if (BB->getParent()->getReturnType() != Type::VoidTy)
184 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
186 // Create the return...
187 NewTI = ReturnInst::Create(RetVal);
191 case Instruction::Invoke: // Should convert to call
192 case Instruction::Switch: // Should remove entry
194 case Instruction::Ret: // Cannot happen, has no successors!
195 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
199 if (NewTI) // If it's a different instruction, replace.
200 ReplaceInstWithInst(TI, NewTI);
203 /// SplitEdge - Split the edge connecting specified block. Pass P must
205 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
206 TerminatorInst *LatchTerm = BB->getTerminator();
207 unsigned SuccNum = 0;
208 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
209 assert(i != e && "Didn't find edge?");
210 if (LatchTerm->getSuccessor(i) == Succ) {
216 // If this is a critical edge, let SplitCriticalEdge do it.
217 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
218 return LatchTerm->getSuccessor(SuccNum);
220 // If the edge isn't critical, then BB has a single successor or Succ has a
221 // single pred. Split the block.
222 BasicBlock::iterator SplitPoint;
223 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
224 // If the successor only has a single pred, split the top of the successor
226 assert(SP == BB && "CFG broken");
227 return SplitBlock(Succ, Succ->begin(), P);
229 // Otherwise, if BB has a single successor, split it at the bottom of the
231 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
232 "Should have a single succ!");
233 return SplitBlock(BB, BB->getTerminator(), P);
237 /// SplitBlock - Split the specified block at the specified instruction - every
238 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
239 /// to a new block. The two blocks are joined by an unconditional branch and
240 /// the loop info is updated.
242 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
243 BasicBlock::iterator SplitIt = SplitPt;
244 while (isa<PHINode>(SplitIt))
246 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
248 // The new block lives in whichever loop the old one did.
249 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
250 if (Loop *L = LI->getLoopFor(Old))
251 L->addBasicBlockToLoop(New, LI->getBase());
253 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
255 // Old dominates New. New node domiantes all other nodes dominated by Old.
256 DomTreeNode *OldNode = DT->getNode(Old);
257 std::vector<DomTreeNode *> Children;
258 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
260 Children.push_back(*I);
262 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
264 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
265 E = Children.end(); I != E; ++I)
266 DT->changeImmediateDominator(*I, NewNode);
269 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
276 /// SplitBlockPredecessors - This method transforms BB by introducing a new
277 /// basic block into the function, and moving some of the predecessors of BB to
278 /// be predecessors of the new block. The new predecessors are indicated by the
279 /// Preds array, which has NumPreds elements in it. The new block is given a
280 /// suffix of 'Suffix'.
282 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
283 /// DominanceFrontier, but no other analyses.
284 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
285 BasicBlock *const *Preds,
286 unsigned NumPreds, const char *Suffix,
288 // Create new basic block, insert right before the original block.
290 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
292 // The new block unconditionally branches to the old block.
293 BranchInst *BI = BranchInst::Create(BB, NewBB);
295 // Move the edges from Preds to point to NewBB instead of BB.
296 for (unsigned i = 0; i != NumPreds; ++i)
297 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
299 // Update dominator tree and dominator frontier if available.
300 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
302 DT->splitBlock(NewBB);
303 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
304 DF->splitBlock(NewBB);
305 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
308 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
309 // node becomes an incoming value for BB's phi node. However, if the Preds
310 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
311 // account for the newly created predecessor.
313 // Insert dummy values as the incoming value.
314 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
315 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
319 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
320 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
321 PHINode *PN = cast<PHINode>(I++);
323 // Check to see if all of the values coming in are the same. If so, we
324 // don't need to create a new PHI node.
325 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
326 for (unsigned i = 1; i != NumPreds; ++i)
327 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
333 // If all incoming values for the new PHI would be the same, just don't
334 // make a new PHI. Instead, just remove the incoming values from the old
336 for (unsigned i = 0; i != NumPreds; ++i)
337 PN->removeIncomingValue(Preds[i], false);
339 // If the values coming into the block are not the same, we need a PHI.
340 // Create the new PHI node, insert it into NewBB at the end of the block
342 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
343 if (AA) AA->copyValue(PN, NewPHI);
345 // Move all of the PHI values for 'Preds' to the new PHI.
346 for (unsigned i = 0; i != NumPreds; ++i) {
347 Value *V = PN->removeIncomingValue(Preds[i], false);
348 NewPHI->addIncoming(V, Preds[i]);
353 // Add an incoming value to the PHI node in the loop for the preheader
355 PN->addIncoming(InVal, NewBB);
357 // Check to see if we can eliminate this phi node.
358 if (Value *V = PN->hasConstantValue(DT != 0)) {
359 Instruction *I = dyn_cast<Instruction>(V);
360 if (!I || DT == 0 || DT->dominates(I, PN)) {
361 PN->replaceAllUsesWith(V);
362 if (AA) AA->deleteValue(PN);
363 PN->eraseFromParent();