blob: 93a8c8e593433809738bbc8b6e737b228ce87a71 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
16#include "llvm/Function.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000018#include "llvm/Constant.h"
19#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000020#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/Dominators.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000023#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Chris Lattner0f67dd62005-04-21 16:04:49 +000026/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
27/// with a value, then remove and delete the original instruction.
28///
Chris Lattnerf7703df2004-01-09 06:12:26 +000029void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
30 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +000031 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000032 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +000033 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000034
Chris Lattner86cc4232007-02-11 01:37:51 +000035 // Make sure to propagate a name if there is one already.
36 if (I.hasName() && !V->hasName())
37 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +000038
Misha Brukman5560c9d2003-08-18 14:43:39 +000039 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +000040 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000041}
42
43
Chris Lattner0f67dd62005-04-21 16:04:49 +000044/// ReplaceInstWithInst - Replace the instruction specified by BI with the
45/// instruction specified by I. The original instruction is deleted and BI is
46/// updated to point to the new instruction.
47///
Chris Lattnerf7703df2004-01-09 06:12:26 +000048void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
49 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000050 assert(I->getParent() == 0 &&
51 "ReplaceInstWithInst: Instruction already inserted into basic block!");
52
53 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000054 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000055
56 // Replace all uses of the old instruction, and delete it.
57 ReplaceInstWithValue(BIL, BI, I);
58
59 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +000060 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000061}
62
Chris Lattner0f67dd62005-04-21 16:04:49 +000063/// ReplaceInstWithInst - Replace the instruction specified by From with the
64/// instruction specified by To.
65///
Chris Lattnerf7703df2004-01-09 06:12:26 +000066void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +000067 BasicBlock::iterator BI(From);
68 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000069}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000070
Chris Lattner0f67dd62005-04-21 16:04:49 +000071/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +000072/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +000073/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +000074/// may have to be changed. In the case where the last successor of the block
75/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +000076/// surprising change in program behavior if it is not expected.
77///
Chris Lattnerf7703df2004-01-09 06:12:26 +000078void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000079 assert(SuccNum < TI->getNumSuccessors() &&
80 "Trying to remove a nonexistant successor!");
81
82 // If our old successor block contains any PHI nodes, remove the entry in the
83 // PHI nodes that comes from this branch...
84 //
85 BasicBlock *BB = TI->getParent();
86 TI->getSuccessor(SuccNum)->removePredecessor(BB);
87
88 TerminatorInst *NewTI = 0;
89 switch (TI->getOpcode()) {
90 case Instruction::Br:
91 // If this is a conditional branch... convert to unconditional branch.
92 if (TI->getNumSuccessors() == 2) {
93 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
94 } else { // Otherwise convert to a return instruction...
95 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +000096
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000097 // Create a value to return... if the function doesn't return null...
98 if (BB->getParent()->getReturnType() != Type::VoidTy)
99 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
100
101 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000102 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000103 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000104 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000105
106 case Instruction::Invoke: // Should convert to call
107 case Instruction::Switch: // Should remove entry
108 default:
109 case Instruction::Ret: // Cannot happen, has no successors!
110 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
111 abort();
112 }
113
114 if (NewTI) // If it's a different instruction, replace.
115 ReplaceInstWithInst(TI, NewTI);
116}
Brian Gaeked0fde302003-11-11 22:41:34 +0000117
Devang Patel80198932007-07-06 21:39:20 +0000118/// SplitEdge - Split the edge connecting specified block. Pass P must
119/// not be NULL.
120BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
121 TerminatorInst *LatchTerm = BB->getTerminator();
122 unsigned SuccNum = 0;
123 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
124 assert(i != e && "Didn't find edge?");
125 if (LatchTerm->getSuccessor(i) == Succ) {
126 SuccNum = i;
127 break;
128 }
129 }
130
131 // If this is a critical edge, let SplitCriticalEdge do it.
132 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
133 return LatchTerm->getSuccessor(SuccNum);
134
135 // If the edge isn't critical, then BB has a single successor or Succ has a
136 // single pred. Split the block.
137 BasicBlock::iterator SplitPoint;
138 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
139 // If the successor only has a single pred, split the top of the successor
140 // block.
141 assert(SP == BB && "CFG broken");
142 return SplitBlock(Succ, Succ->begin(), P);
143 } else {
144 // Otherwise, if BB has a single successor, split it at the bottom of the
145 // block.
146 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
147 "Should have a single succ!");
148 return SplitBlock(BB, BB->getTerminator(), P);
149 }
150}
151
152/// SplitBlock - Split the specified block at the specified instruction - every
153/// thing before SplitPt stays in Old and everything starting with SplitPt moves
154/// to a new block. The two blocks are joined by an unconditional branch and
155/// the loop info is updated.
156///
157BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
158
159 LoopInfo &LI = P->getAnalysis<LoopInfo>();
160 BasicBlock::iterator SplitIt = SplitPt;
161 while (isa<PHINode>(SplitIt))
162 ++SplitIt;
163 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
164
165 // The new block lives in whichever loop the old one did.
166 if (Loop *L = LI.getLoopFor(Old))
Owen Andersond735ee82007-11-27 03:43:35 +0000167 L->addBasicBlockToLoop(New, LI.getBase());
Devang Patel80198932007-07-06 21:39:20 +0000168
Devang Patela8a8a362007-07-19 02:29:24 +0000169 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
170 {
171 // Old dominates New. New node domiantes all other nodes dominated by Old.
172 DomTreeNode *OldNode = DT->getNode(Old);
173 std::vector<DomTreeNode *> Children;
174 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
175 I != E; ++I)
176 Children.push_back(*I);
177
178 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
179
180 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
181 E = Children.end(); I != E; ++I)
182 DT->changeImmediateDominator(*I, NewNode);
183 }
Devang Patel80198932007-07-06 21:39:20 +0000184
185 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
186 DF->splitBlock(Old);
187
188 return New;
189}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000190
191
192/// SplitBlockPredecessors - This method transforms BB by introducing a new
193/// basic block into the function, and moving some of the predecessors of BB to
194/// be predecessors of the new block. The new predecessors are indicated by the
195/// Preds array, which has NumPreds elements in it. The new block is given a
196/// suffix of 'Suffix'.
197///
198/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
199/// DominanceFrontier, but no other analyses.
200BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
201 BasicBlock *const *Preds,
202 unsigned NumPreds, const char *Suffix,
203 Pass *P) {
204 // Create new basic block, insert right before the original block.
205 BasicBlock *NewBB =
206 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
207
208 // The new block unconditionally branches to the old block.
209 BranchInst *BI = BranchInst::Create(BB, NewBB);
210
211 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000212 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000213 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000214
215 // Update dominator tree and dominator frontier if available.
216 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
217 if (DT)
218 DT->splitBlock(NewBB);
219 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
220 DF->splitBlock(NewBB);
221 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
222
223
224 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
225 // node becomes an incoming value for BB's phi node. However, if the Preds
226 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
227 // account for the newly created predecessor.
228 if (NumPreds == 0) {
229 // Insert dummy values as the incoming value.
230 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
231 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
232 return NewBB;
233 }
234
235 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
236 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
237 PHINode *PN = cast<PHINode>(I++);
238
239 // Check to see if all of the values coming in are the same. If so, we
240 // don't need to create a new PHI node.
241 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
242 for (unsigned i = 1; i != NumPreds; ++i)
243 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
244 InVal = 0;
245 break;
246 }
247
248 if (InVal) {
249 // If all incoming values for the new PHI would be the same, just don't
250 // make a new PHI. Instead, just remove the incoming values from the old
251 // PHI.
252 for (unsigned i = 0; i != NumPreds; ++i)
253 PN->removeIncomingValue(Preds[i], false);
254 } else {
255 // If the values coming into the block are not the same, we need a PHI.
256 // Create the new PHI node, insert it into NewBB at the end of the block
257 PHINode *NewPHI =
258 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
259 if (AA) AA->copyValue(PN, NewPHI);
260
261 // Move all of the PHI values for 'Preds' to the new PHI.
262 for (unsigned i = 0; i != NumPreds; ++i) {
263 Value *V = PN->removeIncomingValue(Preds[i], false);
264 NewPHI->addIncoming(V, Preds[i]);
265 }
266 InVal = NewPHI;
267 }
268
269 // Add an incoming value to the PHI node in the loop for the preheader
270 // edge.
271 PN->addIncoming(InVal, NewBB);
272
273 // Check to see if we can eliminate this phi node.
274 if (Value *V = PN->hasConstantValue(DT != 0)) {
275 Instruction *I = dyn_cast<Instruction>(V);
276 if (!I || DT == 0 || DT->dominates(I, PN)) {
277 PN->replaceAllUsesWith(V);
278 if (AA) AA->deleteValue(PN);
279 PN->eraseFromParent();
280 }
281 }
282 }
283
284 return NewBB;
285}