1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Support/CFG.h"
25 // PropagatePredecessors - This gets "Succ" ready to have the predecessors from
26 // "BB". This is a little tricky because "Succ" has PHI nodes, which need to
27 // have extra slots added to them to hold the merge edges from BB's
28 // predecessors, and BB itself might have had PHI nodes in it. This function
29 // returns true (failure) if the Succ BB already has a predecessor that is a
30 // predecessor of BB and incoming PHI arguments would not be discernible.
32 // Assumption: Succ is the single successor for BB.
34 static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
35 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
37 if (!isa<PHINode>(Succ->front()))
38 return false; // We can make the transformation, no problem.
40 // If there is more than one predecessor, and there are PHI nodes in
41 // the successor, then we need to add incoming edges for the PHI nodes
43 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
45 // Check to see if one of the predecessors of BB is already a predecessor of
46 // Succ. If so, we cannot do the transformation if there are any PHI nodes
47 // with incompatible values coming in from the two edges!
49 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
50 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
51 // Loop over all of the PHI nodes checking to see if there are
52 // incompatible values coming in.
53 for (BasicBlock::iterator I = Succ->begin();
54 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
55 // Loop up the entries in the PHI node for BB and for *PI if the values
56 // coming in are non-equal, we cannot merge these two blocks (instead we
57 // should insert a conditional move or something, then merge the
59 int Idx1 = PN->getBasicBlockIndex(BB);
60 int Idx2 = PN->getBasicBlockIndex(*PI);
61 assert(Idx1 != -1 && Idx2 != -1 &&
62 "Didn't have entries for my predecessors??");
63 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
64 return true; // Values are not equal...
68 // Loop over all of the PHI nodes in the successor BB
69 for (BasicBlock::iterator I = Succ->begin();
70 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
71 Value *OldVal = PN->removeIncomingValue(BB, false);
72 assert(OldVal && "No entry in PHI for Pred BB!");
74 // If this incoming value is one of the PHI nodes in BB...
75 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
76 PHINode *OldValPN = cast<PHINode>(OldVal);
77 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
78 End = BBPreds.end(); PredI != End; ++PredI) {
79 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
82 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
83 End = BBPreds.end(); PredI != End; ++PredI) {
84 // Add an incoming value for each of the new incoming values...
85 PN->addIncoming(OldVal, *PredI);
93 // SimplifyCFG - This function is used to do simplification of a CFG. For
94 // example, it adjusts branches to branches to eliminate the extra hop, it
95 // eliminates unreachable basic blocks, and does other "peephole" optimization
96 // of the CFG. It returns true if a modification was made.
98 // WARNING: The entry node of a function may not be simplified.
100 bool llvm::SimplifyCFG(BasicBlock *BB) {
101 bool Changed = false;
102 Function *M = BB->getParent();
104 assert(BB && BB->getParent() && "Block not embedded in function!");
105 assert(BB->getTerminator() && "Degenerate basic block encountered!");
106 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
108 // Check to see if the first instruction in this block is just an
109 // 'llvm.unwind'. If so, replace any invoke instructions which use this as an
110 // exception destination with call instructions.
112 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator()))
113 if (BB->begin() == BasicBlock::iterator(UI)) { // Empty block?
114 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
115 while (!Preds.empty()) {
116 BasicBlock *Pred = Preds.back();
117 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
118 if (II->getExceptionalDest() == BB) {
119 // Insert a new branch instruction before the invoke, because this
120 // is now a fall through...
121 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
122 Pred->getInstList().remove(II); // Take out of symbol table
124 // Insert the call now...
125 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
126 CallInst *CI = new CallInst(II->getCalledValue(), Args,
128 // If the invoke produced a value, the Call now does instead
129 II->replaceAllUsesWith(CI);
138 // Remove basic blocks that have no predecessors... which are unreachable.
139 if (pred_begin(BB) == pred_end(BB) &&
140 !BB->hasConstantReferences()) {
141 //cerr << "Removing BB: \n" << BB;
143 // Loop through all of our successors and make sure they know that one
144 // of their predecessors is going away.
145 for_each(succ_begin(BB), succ_end(BB),
146 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
148 while (!BB->empty()) {
149 Instruction &I = BB->back();
150 // If this instruction is used, replace uses with an arbitrary
151 // constant value. Because control flow can't get here, we don't care
152 // what we replace the value with. Note that since this block is
153 // unreachable, and all values contained within it must dominate their
154 // uses, that all uses will eventually be removed.
156 // Make all users of this instruction reference the constant instead
157 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
159 // Remove the instruction from the basic block
160 BB->getInstList().pop_back();
162 M->getBasicBlockList().erase(BB);
166 // Check to see if we can constant propagate this terminator instruction
168 Changed |= ConstantFoldTerminator(BB);
170 // Check to see if this block has no non-phi instructions and only a single
171 // successor. If so, replace references to this basic block with references
173 succ_iterator SI(succ_begin(BB));
174 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
176 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
177 while (isa<PHINode>(*BBI)) ++BBI;
179 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
180 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
182 if (Succ != BB) { // Arg, don't hurt infinite loops!
183 // If our successor has PHI nodes, then we need to update them to
184 // include entries for BB's predecessors, not for BB itself.
185 // Be careful though, if this transformation fails (returns true) then
186 // we cannot do this transformation!
188 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
189 //cerr << "Killing Trivial BB: \n" << BB;
190 std::string OldName = BB->getName();
192 std::vector<BasicBlock*>
193 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
195 // Move all PHI nodes in BB to Succ if they are alive, otherwise
197 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
199 BB->getInstList().erase(BB->begin()); // Nuke instruction...
201 // The instruction is alive, so this means that Succ must have
202 // *ONLY* had BB as a predecessor, and the PHI node is still valid
203 // now. Simply move it into Succ, because we know that BB
204 // strictly dominated Succ.
205 BB->getInstList().remove(BB->begin());
206 Succ->getInstList().push_front(PN);
208 // We need to add new entries for the PHI node to account for
209 // predecessors of Succ that the PHI node does not take into
210 // account. At this point, since we know that BB dominated succ,
211 // this means that we should any newly added incoming edges should
212 // use the PHI node as the value for these edges, because they are
215 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
216 if (OldSuccPreds[i] != BB)
217 PN->addIncoming(PN, OldSuccPreds[i]);
220 // Everything that jumped to BB now goes to Succ...
221 BB->replaceAllUsesWith(Succ);
223 // Delete the old basic block...
224 M->getBasicBlockList().erase(BB);
226 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
227 Succ->setName(OldName);
229 //cerr << "Function after removal: \n" << M;
236 // Merge basic blocks into their predecessor if there is only one distinct
237 // pred, and if there is only one distinct successor of the predecessor, and
238 // if there are no PHI nodes.
240 if (!BB->hasConstantReferences()) {
241 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
242 BasicBlock *OnlyPred = *PI++;
243 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
244 if (*PI != OnlyPred) {
245 OnlyPred = 0; // There are multiple different predecessors...
249 BasicBlock *OnlySucc = 0;
250 if (OnlyPred && OnlyPred != BB && // Don't break self loops
251 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
252 // Check to see if there is only one distinct successor...
253 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
255 for (; SI != SE; ++SI)
256 if (*SI != OnlySucc) {
257 OnlySucc = 0; // There are multiple distinct successors!
263 //cerr << "Merging: " << BB << "into: " << OnlyPred;
264 TerminatorInst *Term = OnlyPred->getTerminator();
266 // Resolve any PHI nodes at the start of the block. They are all
267 // guaranteed to have exactly one entry if they exist, unless there are
268 // multiple duplicate (but guaranteed to be equal) entries for the
269 // incoming edges. This occurs when there are multiple edges from
270 // OnlyPred to OnlySucc.
272 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
273 PN->replaceAllUsesWith(PN->getIncomingValue(0));
274 BB->getInstList().pop_front(); // Delete the phi node...
277 // Delete the unconditional branch from the predecessor...
278 OnlyPred->getInstList().pop_back();
280 // Move all definitions in the successor to the predecessor...
281 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
283 // Make all PHI nodes that referred to BB now refer to Pred as their
285 BB->replaceAllUsesWith(OnlyPred);
287 std::string OldName = BB->getName();
289 // Erase basic block from the function...
290 M->getBasicBlockList().erase(BB);
292 // Inherit predecessors name if it exists...
293 if (!OldName.empty() && !OnlyPred->hasName())
294 OnlyPred->setName(OldName);