blob: b0fc6bca742beb464609c9e6555822dab1398c97 [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chris Lattner18d1f192004-02-11 03:36:04 +000015#include "llvm/Constants.h"
16#include "llvm/Instructions.h"
Chris Lattner466a0492002-05-21 20:50:24 +000017#include "llvm/Support/CFG.h"
18#include <algorithm>
19#include <functional>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000020using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000021
Misha Brukman632df282002-10-29 23:06:16 +000022// PropagatePredecessors - This gets "Succ" ready to have the predecessors from
Chris Lattner466a0492002-05-21 20:50:24 +000023// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
24// have extra slots added to them to hold the merge edges from BB's
Chris Lattner31116ba2003-03-05 21:01:52 +000025// predecessors, and BB itself might have had PHI nodes in it. This function
26// returns true (failure) if the Succ BB already has a predecessor that is a
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000027// predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner466a0492002-05-21 20:50:24 +000028//
29// Assumption: Succ is the single successor for BB.
30//
Misha Brukman632df282002-10-29 23:06:16 +000031static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000032 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000033
34 if (!isa<PHINode>(Succ->front()))
35 return false; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000036
37 // If there is more than one predecessor, and there are PHI nodes in
38 // the successor, then we need to add incoming edges for the PHI nodes
39 //
40 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
41
42 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000043 // Succ. If so, we cannot do the transformation if there are any PHI nodes
44 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000045 //
Chris Lattner31116ba2003-03-05 21:01:52 +000046 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
47 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
48 // Loop over all of the PHI nodes checking to see if there are
49 // incompatible values coming in.
Chris Lattnere54d2142003-03-05 21:36:33 +000050 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000051 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner31116ba2003-03-05 21:01:52 +000052 // Loop up the entries in the PHI node for BB and for *PI if the values
53 // coming in are non-equal, we cannot merge these two blocks (instead we
54 // should insert a conditional move or something, then merge the
55 // blocks).
56 int Idx1 = PN->getBasicBlockIndex(BB);
57 int Idx2 = PN->getBasicBlockIndex(*PI);
58 assert(Idx1 != -1 && Idx2 != -1 &&
59 "Didn't have entries for my predecessors??");
60 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
61 return true; // Values are not equal...
62 }
63 }
Chris Lattner466a0492002-05-21 20:50:24 +000064
65 // Loop over all of the PHI nodes in the successor BB
66 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000067 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnera704ac82002-10-08 21:36:33 +000068 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner466a0492002-05-21 20:50:24 +000069 assert(OldVal && "No entry in PHI for Pred BB!");
70
Chris Lattnere54d2142003-03-05 21:36:33 +000071 // If this incoming value is one of the PHI nodes in BB...
72 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
73 PHINode *OldValPN = cast<PHINode>(OldVal);
74 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
75 End = BBPreds.end(); PredI != End; ++PredI) {
76 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
77 }
78 } else {
79 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
80 End = BBPreds.end(); PredI != End; ++PredI) {
81 // Add an incoming value for each of the new incoming values...
82 PN->addIncoming(OldVal, *PredI);
83 }
Chris Lattner466a0492002-05-21 20:50:24 +000084 }
85 }
86 return false;
87}
88
Chris Lattner18d1f192004-02-11 03:36:04 +000089/// GetIfCondition - Given a basic block (BB) with two predecessors (and
90/// presumably PHI nodes in it), check to see if the merge at this block is due
91/// to an "if condition". If so, return the boolean condition that determines
92/// which entry into BB will be taken. Also, return by references the block
93/// that will be entered from if the condition is true, and the block that will
94/// be entered if the condition is false.
95///
96///
97static Value *GetIfCondition(BasicBlock *BB,
98 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
99 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
100 "Function can only handle blocks with 2 predecessors!");
101 BasicBlock *Pred1 = *pred_begin(BB);
102 BasicBlock *Pred2 = *++pred_begin(BB);
103
104 // We can only handle branches. Other control flow will be lowered to
105 // branches if possible anyway.
106 if (!isa<BranchInst>(Pred1->getTerminator()) ||
107 !isa<BranchInst>(Pred2->getTerminator()))
108 return 0;
109 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
110 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
111
112 // Eliminate code duplication by ensuring that Pred1Br is conditional if
113 // either are.
114 if (Pred2Br->isConditional()) {
115 // If both branches are conditional, we don't have an "if statement". In
116 // reality, we could transform this case, but since the condition will be
117 // required anyway, we stand no chance of eliminating it, so the xform is
118 // probably not profitable.
119 if (Pred1Br->isConditional())
120 return 0;
121
122 std::swap(Pred1, Pred2);
123 std::swap(Pred1Br, Pred2Br);
124 }
125
126 if (Pred1Br->isConditional()) {
127 // If we found a conditional branch predecessor, make sure that it branches
128 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
129 if (Pred1Br->getSuccessor(0) == BB &&
130 Pred1Br->getSuccessor(1) == Pred2) {
131 IfTrue = Pred1;
132 IfFalse = Pred2;
133 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
134 Pred1Br->getSuccessor(1) == BB) {
135 IfTrue = Pred2;
136 IfFalse = Pred1;
137 } else {
138 // We know that one arm of the conditional goes to BB, so the other must
139 // go somewhere unrelated, and this must not be an "if statement".
140 return 0;
141 }
142
143 // The only thing we have to watch out for here is to make sure that Pred2
144 // doesn't have incoming edges from other blocks. If it does, the condition
145 // doesn't dominate BB.
146 if (++pred_begin(Pred2) != pred_end(Pred2))
147 return 0;
148
149 return Pred1Br->getCondition();
150 }
151
152 // Ok, if we got here, both predecessors end with an unconditional branch to
153 // BB. Don't panic! If both blocks only have a single (identical)
154 // predecessor, and THAT is a conditional branch, then we're all ok!
155 if (pred_begin(Pred1) == pred_end(Pred1) ||
156 ++pred_begin(Pred1) != pred_end(Pred1) ||
157 pred_begin(Pred2) == pred_end(Pred2) ||
158 ++pred_begin(Pred2) != pred_end(Pred2) ||
159 *pred_begin(Pred1) != *pred_begin(Pred2))
160 return 0;
161
162 // Otherwise, if this is a conditional branch, then we can use it!
163 BasicBlock *CommonPred = *pred_begin(Pred1);
164 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
165 assert(BI->isConditional() && "Two successors but not conditional?");
166 if (BI->getSuccessor(0) == Pred1) {
167 IfTrue = Pred1;
168 IfFalse = Pred2;
169 } else {
170 IfTrue = Pred2;
171 IfFalse = Pred1;
172 }
173 return BI->getCondition();
174 }
175 return 0;
176}
177
178
179// If we have a merge point of an "if condition" as accepted above, return true
180// if the specified value dominates the block. We don't handle the true
181// generality of domination here, just a special case which works well enough
182// for us.
183static bool DominatesMergePoint(Value *V, BasicBlock *BB) {
184 if (Instruction *I = dyn_cast<Instruction>(V)) {
185 BasicBlock *PBB = I->getParent();
186 // If this instruction is defined in a block that contains an unconditional
187 // branch to BB, then it must be in the 'conditional' part of the "if
188 // statement".
189 if (isa<BranchInst>(PBB->getTerminator()) &&
190 cast<BranchInst>(PBB->getTerminator())->isUnconditional() &&
191 cast<BranchInst>(PBB->getTerminator())->getSuccessor(0) == BB)
192 return false;
193
194 // We also don't want to allow wierd loops that might have the "if
195 // condition" in the bottom of this block.
196 if (PBB == BB) return false;
197 }
198
199 // Non-instructions all dominate instructions.
200 return true;
201}
Chris Lattner466a0492002-05-21 20:50:24 +0000202
203// SimplifyCFG - This function is used to do simplification of a CFG. For
204// example, it adjusts branches to branches to eliminate the extra hop, it
205// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +0000206// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +0000207//
208// WARNING: The entry node of a function may not be simplified.
209//
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000210bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +0000211 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +0000212 Function *M = BB->getParent();
213
214 assert(BB && BB->getParent() && "Block not embedded in function!");
215 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +0000216 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +0000217
Chris Lattner838b8452004-02-11 01:17:07 +0000218 // Check to see if the first instruction in this block is just an unwind. If
219 // so, replace any invoke instructions which use this as an exception
220 // destination with call instructions.
Chris Lattner3f5823f2003-08-24 18:36:16 +0000221 //
Chris Lattner04ecefe2003-09-08 19:44:26 +0000222 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator()))
223 if (BB->begin() == BasicBlock::iterator(UI)) { // Empty block?
224 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
225 while (!Preds.empty()) {
226 BasicBlock *Pred = Preds.back();
227 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000228 if (II->getUnwindDest() == BB) {
Chris Lattner04ecefe2003-09-08 19:44:26 +0000229 // Insert a new branch instruction before the invoke, because this
230 // is now a fall through...
231 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
232 Pred->getInstList().remove(II); // Take out of symbol table
233
234 // Insert the call now...
235 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
236 CallInst *CI = new CallInst(II->getCalledValue(), Args,
237 II->getName(), BI);
238 // If the invoke produced a value, the Call now does instead
239 II->replaceAllUsesWith(CI);
240 delete II;
241 Changed = true;
242 }
243
244 Preds.pop_back();
Chris Lattner3f5823f2003-08-24 18:36:16 +0000245 }
Chris Lattner04ecefe2003-09-08 19:44:26 +0000246 }
Chris Lattner3f5823f2003-08-24 18:36:16 +0000247
Chris Lattner466a0492002-05-21 20:50:24 +0000248 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattner838b8452004-02-11 01:17:07 +0000249 if (pred_begin(BB) == pred_end(BB)) {
Chris Lattner466a0492002-05-21 20:50:24 +0000250 //cerr << "Removing BB: \n" << BB;
251
252 // Loop through all of our successors and make sure they know that one
253 // of their predecessors is going away.
254 for_each(succ_begin(BB), succ_end(BB),
255 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
256
257 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000258 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +0000259 // If this instruction is used, replace uses with an arbitrary
260 // constant value. Because control flow can't get here, we don't care
261 // what we replace the value with. Note that since this block is
262 // unreachable, and all values contained within it must dominate their
263 // uses, that all uses will eventually be removed.
Chris Lattnerfda72b12002-06-25 16:12:52 +0000264 if (!I.use_empty())
Chris Lattner466a0492002-05-21 20:50:24 +0000265 // Make all users of this instruction reference the constant instead
Chris Lattnerfda72b12002-06-25 16:12:52 +0000266 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner466a0492002-05-21 20:50:24 +0000267
268 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +0000269 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000270 }
Chris Lattnerfda72b12002-06-25 16:12:52 +0000271 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000272 return true;
273 }
274
Chris Lattner031340a2003-08-17 19:41:53 +0000275 // Check to see if we can constant propagate this terminator instruction
276 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +0000277 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +0000278
Chris Lattnere54d2142003-03-05 21:36:33 +0000279 // Check to see if this block has no non-phi instructions and only a single
280 // successor. If so, replace references to this basic block with references
281 // to the successor.
Chris Lattner466a0492002-05-21 20:50:24 +0000282 succ_iterator SI(succ_begin(BB));
283 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattnere54d2142003-03-05 21:36:33 +0000284
285 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
286 while (isa<PHINode>(*BBI)) ++BBI;
287
288 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner466a0492002-05-21 20:50:24 +0000289 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
290
291 if (Succ != BB) { // Arg, don't hurt infinite loops!
292 // If our successor has PHI nodes, then we need to update them to
293 // include entries for BB's predecessors, not for BB itself.
294 // Be careful though, if this transformation fails (returns true) then
295 // we cannot do this transformation!
296 //
Misha Brukman632df282002-10-29 23:06:16 +0000297 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner466a0492002-05-21 20:50:24 +0000298 //cerr << "Killing Trivial BB: \n" << BB;
Chris Lattnerfda72b12002-06-25 16:12:52 +0000299 std::string OldName = BB->getName();
300
Chris Lattner569a57f2003-03-07 18:13:41 +0000301 std::vector<BasicBlock*>
302 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
303
Chris Lattnere54d2142003-03-05 21:36:33 +0000304 // Move all PHI nodes in BB to Succ if they are alive, otherwise
305 // delete them.
306 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
307 if (PN->use_empty())
308 BB->getInstList().erase(BB->begin()); // Nuke instruction...
309 else {
310 // The instruction is alive, so this means that Succ must have
311 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner569a57f2003-03-07 18:13:41 +0000312 // now. Simply move it into Succ, because we know that BB
313 // strictly dominated Succ.
Chris Lattnere54d2142003-03-05 21:36:33 +0000314 BB->getInstList().remove(BB->begin());
315 Succ->getInstList().push_front(PN);
Chris Lattner569a57f2003-03-07 18:13:41 +0000316
317 // We need to add new entries for the PHI node to account for
318 // predecessors of Succ that the PHI node does not take into
319 // account. At this point, since we know that BB dominated succ,
320 // this means that we should any newly added incoming edges should
321 // use the PHI node as the value for these edges, because they are
322 // loop back edges.
323
324 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
325 if (OldSuccPreds[i] != BB)
326 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattnere54d2142003-03-05 21:36:33 +0000327 }
328
Chris Lattner569a57f2003-03-07 18:13:41 +0000329 // Everything that jumped to BB now goes to Succ...
330 BB->replaceAllUsesWith(Succ);
331
Chris Lattnerfda72b12002-06-25 16:12:52 +0000332 // Delete the old basic block...
333 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000334
Chris Lattnerfda72b12002-06-25 16:12:52 +0000335 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
336 Succ->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000337
338 //cerr << "Function after removal: \n" << M;
339 return true;
340 }
341 }
342 }
343 }
344
Chris Lattnere42732e2004-02-16 06:35:48 +0000345 // If this is a returning block with only PHI nodes in it, fold the return
346 // instruction into any unconditional branch predecessors.
347 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
348 BasicBlock::iterator BBI = BB->getTerminator();
349 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
350 // Find predecessors that end with unconditional branches.
351 std::vector<BasicBlock*> UncondBranchPreds;
352 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
353 TerminatorInst *PTI = (*PI)->getTerminator();
354 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
355 if (BI->isUnconditional())
356 UncondBranchPreds.push_back(*PI);
357 }
358
359 // If we found some, do the transformation!
360 if (!UncondBranchPreds.empty()) {
361 while (!UncondBranchPreds.empty()) {
362 BasicBlock *Pred = UncondBranchPreds.back();
363 UncondBranchPreds.pop_back();
364 Instruction *UncondBranch = Pred->getTerminator();
365 // Clone the return and add it to the end of the predecessor.
366 Instruction *NewRet = RI->clone();
367 Pred->getInstList().push_back(NewRet);
368
369 // If the return instruction returns a value, and if the value was a
370 // PHI node in "BB", propagate the right value into the return.
371 if (NewRet->getNumOperands() == 1)
372 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
373 if (PN->getParent() == BB)
374 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
375 // Update any PHI nodes in the returning block to realize that we no
376 // longer branch to them.
377 BB->removePredecessor(Pred);
378 Pred->getInstList().erase(UncondBranch);
379 }
380
381 // If we eliminated all predecessors of the block, delete the block now.
382 if (pred_begin(BB) == pred_end(BB))
383 // We know there are no successors, so just nuke the block.
384 M->getBasicBlockList().erase(BB);
385
386
387 return true;
388 }
389 }
390 }
391
392
Chris Lattner466a0492002-05-21 20:50:24 +0000393 // Merge basic blocks into their predecessor if there is only one distinct
394 // pred, and if there is only one distinct successor of the predecessor, and
395 // if there are no PHI nodes.
396 //
Chris Lattner838b8452004-02-11 01:17:07 +0000397 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
398 BasicBlock *OnlyPred = *PI++;
399 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
400 if (*PI != OnlyPred) {
401 OnlyPred = 0; // There are multiple different predecessors...
402 break;
403 }
404
405 BasicBlock *OnlySucc = 0;
406 if (OnlyPred && OnlyPred != BB && // Don't break self loops
407 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
408 // Check to see if there is only one distinct successor...
409 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
410 OnlySucc = BB;
411 for (; SI != SE; ++SI)
412 if (*SI != OnlySucc) {
413 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner466a0492002-05-21 20:50:24 +0000414 break;
415 }
Chris Lattner838b8452004-02-11 01:17:07 +0000416 }
417
418 if (OnlySucc) {
419 //cerr << "Merging: " << BB << "into: " << OnlyPred;
420 TerminatorInst *Term = OnlyPred->getTerminator();
421
422 // Resolve any PHI nodes at the start of the block. They are all
423 // guaranteed to have exactly one entry if they exist, unless there are
424 // multiple duplicate (but guaranteed to be equal) entries for the
425 // incoming edges. This occurs when there are multiple edges from
426 // OnlyPred to OnlySucc.
427 //
428 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
429 PN->replaceAllUsesWith(PN->getIncomingValue(0));
430 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner466a0492002-05-21 20:50:24 +0000431 }
432
Chris Lattner838b8452004-02-11 01:17:07 +0000433 // Delete the unconditional branch from the predecessor...
434 OnlyPred->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000435
Chris Lattner838b8452004-02-11 01:17:07 +0000436 // Move all definitions in the successor to the predecessor...
437 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Chris Lattnerfda72b12002-06-25 16:12:52 +0000438
Chris Lattner838b8452004-02-11 01:17:07 +0000439 // Make all PHI nodes that referred to BB now refer to Pred as their
440 // source...
441 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000442
Chris Lattner838b8452004-02-11 01:17:07 +0000443 std::string OldName = BB->getName();
Chris Lattnerfda72b12002-06-25 16:12:52 +0000444
Chris Lattner838b8452004-02-11 01:17:07 +0000445 // Erase basic block from the function...
446 M->getBasicBlockList().erase(BB);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000447
Chris Lattner838b8452004-02-11 01:17:07 +0000448 // Inherit predecessors name if it exists...
449 if (!OldName.empty() && !OnlyPred->hasName())
450 OnlyPred->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000451
Chris Lattner838b8452004-02-11 01:17:07 +0000452 return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000453 }
Chris Lattner18d1f192004-02-11 03:36:04 +0000454
455 // If there is a trivial two-entry PHI node in this basic block, and we can
456 // eliminate it, do so now.
457 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
458 if (PN->getNumIncomingValues() == 2) {
459 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
460 // statement", which has a very simple dominance structure. Basically, we
461 // are trying to find the condition that is being branched on, which
462 // subsequently causes this merge to happen. We really want control
463 // dependence information for this check, but simplifycfg can't keep it up
464 // to date, and this catches most of the cases we care about anyway.
465 //
466 BasicBlock *IfTrue, *IfFalse;
467 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
468 //std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
469 // << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
470
471 // Figure out where to insert instructions as necessary.
472 BasicBlock::iterator AfterPHIIt = BB->begin();
473 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
474
475 BasicBlock::iterator I = BB->begin();
476 while (PHINode *PN = dyn_cast<PHINode>(I)) {
477 ++I;
478
479 // If we can eliminate this PHI by directly computing it based on the
480 // condition, do so now. We can't eliminate PHI nodes where the
481 // incoming values are defined in the conditional parts of the branch,
482 // so check for this.
483 //
484 if (DominatesMergePoint(PN->getIncomingValue(0), BB) &&
485 DominatesMergePoint(PN->getIncomingValue(1), BB)) {
486 Value *TrueVal =
487 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
488 Value *FalseVal =
489 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
490
491 // FIXME: when we have a 'select' statement, we can be completely
492 // generic and clean here and let the instcombine pass clean up
493 // after us, by folding the select instructions away when possible.
494 //
495 if (TrueVal == FalseVal) {
496 // Degenerate case...
497 PN->replaceAllUsesWith(TrueVal);
498 BB->getInstList().erase(PN);
499 Changed = true;
500 } else if (isa<ConstantBool>(TrueVal) &&
501 isa<ConstantBool>(FalseVal)) {
502 if (TrueVal == ConstantBool::True) {
503 // The PHI node produces the same thing as the condition.
504 PN->replaceAllUsesWith(IfCond);
505 } else {
506 // The PHI node produces the inverse of the condition. Insert a
507 // "NOT" instruction, which is really a XOR.
508 Value *InverseCond =
509 BinaryOperator::createNot(IfCond, IfCond->getName()+".inv",
510 AfterPHIIt);
511 PN->replaceAllUsesWith(InverseCond);
512 }
513 BB->getInstList().erase(PN);
514 Changed = true;
515 } else if (isa<ConstantInt>(TrueVal) && isa<ConstantInt>(FalseVal)){
516 // If this is a PHI of two constant integers, we insert a cast of
517 // the boolean to the integer type in question, giving us 0 or 1.
518 // Then we multiply this by the difference of the two constants,
519 // giving us 0 if false, and the difference if true. We add this
520 // result to the base constant, giving us our final value. We
521 // rely on the instruction combiner to eliminate many special
522 // cases, like turning multiplies into shifts when possible.
523 std::string Name = PN->getName(); PN->setName("");
524 Value *TheCast = new CastInst(IfCond, TrueVal->getType(),
525 Name, AfterPHIIt);
526 Constant *TheDiff = ConstantExpr::get(Instruction::Sub,
527 cast<Constant>(TrueVal),
528 cast<Constant>(FalseVal));
529 Value *V = TheCast;
530 if (TheDiff != ConstantInt::get(TrueVal->getType(), 1))
531 V = BinaryOperator::create(Instruction::Mul, TheCast,
532 TheDiff, TheCast->getName()+".scale",
533 AfterPHIIt);
534 if (!cast<Constant>(FalseVal)->isNullValue())
535 V = BinaryOperator::create(Instruction::Add, V, FalseVal,
536 V->getName()+".offs", AfterPHIIt);
537 PN->replaceAllUsesWith(V);
538 BB->getInstList().erase(PN);
539 Changed = true;
540 } else if (isa<ConstantInt>(FalseVal) &&
541 cast<Constant>(FalseVal)->isNullValue()) {
542 // If the false condition is an integral zero value, we can
543 // compute the PHI by multiplying the condition by the other
544 // value.
545 std::string Name = PN->getName(); PN->setName("");
546 Value *TheCast = new CastInst(IfCond, TrueVal->getType(),
547 Name+".c", AfterPHIIt);
548 Value *V = BinaryOperator::create(Instruction::Mul, TrueVal,
549 TheCast, Name, AfterPHIIt);
550 PN->replaceAllUsesWith(V);
551 BB->getInstList().erase(PN);
552 Changed = true;
553 } else if (isa<ConstantInt>(TrueVal) &&
554 cast<Constant>(TrueVal)->isNullValue()) {
555 // If the true condition is an integral zero value, we can compute
556 // the PHI by multiplying the inverse condition by the other
557 // value.
558 std::string Name = PN->getName(); PN->setName("");
559 Value *NotCond = BinaryOperator::createNot(IfCond, Name+".inv",
560 AfterPHIIt);
561 Value *TheCast = new CastInst(NotCond, TrueVal->getType(),
562 Name+".inv", AfterPHIIt);
563 Value *V = BinaryOperator::create(Instruction::Mul, FalseVal,
564 TheCast, Name, AfterPHIIt);
565 PN->replaceAllUsesWith(V);
566 BB->getInstList().erase(PN);
567 Changed = true;
568 }
569 }
570 }
571 }
572 }
Chris Lattner466a0492002-05-21 20:50:24 +0000573
Chris Lattner031340a2003-08-17 19:41:53 +0000574 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +0000575}