blob: 652a64718975fb7fcee6ead7c3c012e2d8fc3b18 [file] [log] [blame]
Chris Lattner21ab22e2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner21ab22e2004-07-31 10:01:27 +00003// 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.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner21ab22e2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/CodeGen/Passes.h"
Chris Lattner683747a2006-10-17 23:17:27 +000020#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000022#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
Chris Lattner12143052006-10-21 00:47:49 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/STLExtras.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000028using namespace llvm;
29
Chris Lattner12143052006-10-21 00:47:49 +000030static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
31static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
32static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
Chris Lattner12143052006-10-21 00:47:49 +000033
Chris Lattner21ab22e2004-07-31 10:01:27 +000034namespace {
35 struct BranchFolder : public MachineFunctionPass {
36 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000037 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
38 const TargetInstrInfo *TII;
Chris Lattner683747a2006-10-17 23:17:27 +000039 MachineDebugInfo *MDI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000040 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000041 private:
Chris Lattner12143052006-10-21 00:47:49 +000042 // Tail Merging.
43 bool TailMergeBlocks(MachineFunction &MF);
44 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
45 MachineBasicBlock *NewDest);
46
47 // Branch optzn.
48 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000049 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000050 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner21ab22e2004-07-31 10:01:27 +000051 };
52}
53
54FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
55
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000056/// RemoveDeadBlock - Remove the specified dead machine basic block from the
57/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000058void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000059 assert(MBB->pred_empty() && "MBB must be dead!");
Chris Lattner683747a2006-10-17 23:17:27 +000060
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000061 MachineFunction *MF = MBB->getParent();
62 // drop all successors.
63 while (!MBB->succ_empty())
64 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000065
66 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
67 // records in the basic block. If so, unregister them from MachineDebugInfo.
68 if (MDI && !MBB->empty()) {
69 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
70 assert(DWARF_LABELOpc &&
71 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
72
73 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
74 I != E; ++I) {
75 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
76 // The label ID # is always operand #0, an immediate.
Jim Laskey66ebf092006-10-23 14:56:37 +000077 MDI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000078 }
79 }
80 }
81
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000082 // Remove the block.
83 MF->getBasicBlockList().erase(MBB);
84}
85
Chris Lattner21ab22e2004-07-31 10:01:27 +000086bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +000087 TII = MF.getTarget().getInstrInfo();
88 if (!TII) return false;
89
Chris Lattner683747a2006-10-17 23:17:27 +000090 MDI = getAnalysisToUpdate<MachineDebugInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +000091
Chris Lattner21ab22e2004-07-31 10:01:27 +000092 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +000093 bool MadeChangeThisIteration = true;
94 while (MadeChangeThisIteration) {
95 MadeChangeThisIteration = false;
96 MadeChangeThisIteration |= TailMergeBlocks(MF);
97 MadeChangeThisIteration |= OptimizeBranches(MF);
98 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +000099 }
100
101 return EverMadeChange;
102}
103
Chris Lattner12143052006-10-21 00:47:49 +0000104//===----------------------------------------------------------------------===//
105// Tail Merging of Blocks
106//===----------------------------------------------------------------------===//
107
108/// HashMachineInstr - Compute a hash value for MI and its operands.
109static unsigned HashMachineInstr(const MachineInstr *MI) {
110 unsigned Hash = MI->getOpcode();
111 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
112 const MachineOperand &Op = MI->getOperand(i);
113
114 // Merge in bits from the operand if easy.
115 unsigned OperandHash = 0;
116 switch (Op.getType()) {
117 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
118 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
119 case MachineOperand::MO_MachineBasicBlock:
120 OperandHash = Op.getMachineBasicBlock()->getNumber();
121 break;
122 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
123 case MachineOperand::MO_ConstantPoolIndex:
124 OperandHash = Op.getConstantPoolIndex();
125 break;
126 case MachineOperand::MO_JumpTableIndex:
127 OperandHash = Op.getJumpTableIndex();
128 break;
129 case MachineOperand::MO_GlobalAddress:
130 case MachineOperand::MO_ExternalSymbol:
131 // Global address / external symbol are too hard, don't bother, but do
132 // pull in the offset.
133 OperandHash = Op.getOffset();
134 break;
135 default: break;
136 }
137
138 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
139 }
140 return Hash;
141}
142
143/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
144/// instructions, because cross-jumping only saves code when at least two
145/// instructions are removed (since a branch must be inserted).
146static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
147 MachineBasicBlock::const_iterator I = MBB->end();
148 if (I == MBB->begin())
149 return 0; // Empty MBB.
150
151 --I;
152 unsigned Hash = HashMachineInstr(I);
153
154 if (I == MBB->begin())
155 return Hash; // Single instr MBB.
156
157 --I;
158 // Hash in the second-to-last instruction.
159 Hash ^= HashMachineInstr(I) << 2;
160 return Hash;
161}
162
163/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
164/// of instructions they actually have in common together at their end. Return
165/// iterators for the first shared instruction in each block.
166static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
167 MachineBasicBlock *MBB2,
168 MachineBasicBlock::iterator &I1,
169 MachineBasicBlock::iterator &I2) {
170 I1 = MBB1->end();
171 I2 = MBB2->end();
172
173 unsigned TailLen = 0;
174 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
175 --I1; --I2;
176 if (!I1->isIdenticalTo(I2)) {
177 ++I1; ++I2;
178 break;
179 }
180 ++TailLen;
181 }
182 return TailLen;
183}
184
185/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000186/// after it, replacing it with an unconditional branch to NewDest. This
187/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000188void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
189 MachineBasicBlock *NewDest) {
190 MachineBasicBlock *OldBB = OldInst->getParent();
191
192 // Remove all the old successors of OldBB from the CFG.
193 while (!OldBB->succ_empty())
194 OldBB->removeSuccessor(OldBB->succ_begin());
195
196 // Remove all the dead instructions from the end of OldBB.
197 OldBB->erase(OldInst, OldBB->end());
198
Chris Lattner386e2902006-10-21 05:08:28 +0000199 // If OldBB isn't immediately before OldBB, insert a branch to it.
200 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
201 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000202 OldBB->addSuccessor(NewDest);
203 ++NumTailMerge;
204}
205
206bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
207 MadeChange = false;
208
Chris Lattner12143052006-10-21 00:47:49 +0000209 // Find blocks with no successors.
210 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
211 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
212 if (I->succ_empty())
213 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
214 }
215
216 // Sort by hash value so that blocks with identical end sequences sort
217 // together.
218 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
219
220 // Walk through equivalence sets looking for actual exact matches.
221 while (MergePotentials.size() > 1) {
222 unsigned CurHash = (MergePotentials.end()-1)->first;
223 unsigned PrevHash = (MergePotentials.end()-2)->first;
224 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
225
226 // If there is nothing that matches the hash of the current basic block,
227 // give up.
228 if (CurHash != PrevHash) {
229 MergePotentials.pop_back();
230 continue;
231 }
232
233 // Determine the actual length of the shared tail between these two basic
234 // blocks. Because the hash can have collisions, it's possible that this is
235 // less than 2.
236 MachineBasicBlock::iterator BBI1, BBI2;
237 unsigned CommonTailLen =
238 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
239 BBI1, BBI2);
240
241 // If the tails don't have at least two instructions in common, see if there
242 // is anything else in the equivalence class that does match.
243 if (CommonTailLen < 2) {
244 unsigned FoundMatch = ~0U;
245 for (int i = MergePotentials.size()-2;
246 i != -1 && MergePotentials[i].first == CurHash; --i) {
247 CommonTailLen = ComputeCommonTailLength(CurMBB,
248 MergePotentials[i].second,
249 BBI1, BBI2);
250 if (CommonTailLen >= 2) {
251 FoundMatch = i;
252 break;
253 }
254 }
255
256 // If we didn't find anything that has at least two instructions matching
257 // this one, bail out.
258 if (FoundMatch == ~0U) {
259 MergePotentials.pop_back();
260 continue;
261 }
262
263 // Otherwise, move the matching block to the right position.
264 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
265 }
266
267 // If either block is the entire common tail, make the longer one branch to
268 // the shorter one.
269 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
270 if (CurMBB->begin() == BBI1) {
271 // Hack the end off MBB2, making it jump to CurMBB instead.
272 ReplaceTailWithBranchTo(BBI2, CurMBB);
273 // This modifies MBB2, so remove it from the worklist.
274 MergePotentials.erase(MergePotentials.end()-2);
275 MadeChange = true;
276 continue;
277 } else if (MBB2->begin() == BBI2) {
278 // Hack the end off CurMBB, making it jump to MBBI@ instead.
279 ReplaceTailWithBranchTo(BBI1, MBB2);
280 // This modifies CurMBB, so remove it from the worklist.
281 MergePotentials.pop_back();
282 MadeChange = true;
283 continue;
284 }
285
286 MergePotentials.pop_back();
287 }
288
289 return MadeChange;
290}
291
292
293//===----------------------------------------------------------------------===//
294// Branch Optimization
295//===----------------------------------------------------------------------===//
296
297bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
298 MadeChange = false;
299
300 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
301 MachineBasicBlock *MBB = I++;
302 OptimizeBlock(MBB);
303
304 // If it is dead, remove it.
305 if (MBB->pred_empty()) {
306 RemoveDeadBlock(MBB);
307 MadeChange = true;
308 ++NumDeadBlocks;
309 }
310 }
311 return MadeChange;
312}
313
314
Chris Lattner386e2902006-10-21 05:08:28 +0000315/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
316/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
317/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
318/// be null.
319static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
320 MachineBasicBlock *DestA,
321 MachineBasicBlock *DestB,
322 bool isCond,
323 MachineFunction::iterator FallThru) {
324 bool MadeChange = false;
325 bool AddedFallThrough = false;
326
327 // If this block ends with a conditional branch that falls through to its
328 // successor, set DestB as the successor.
329 if (isCond) {
330 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
331 DestB = FallThru;
332 AddedFallThrough = true;
333 }
334 } else {
335 // If this is an unconditional branch with no explicit dest, it must just be
336 // a fallthrough into DestB.
337 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
338 DestA = FallThru;
339 AddedFallThrough = true;
340 }
341 }
342
343 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
344 while (SI != MBB.succ_end()) {
345 if (*SI == DestA) {
346 DestA = 0;
347 ++SI;
348 } else if (*SI == DestB) {
349 DestB = 0;
350 ++SI;
351 } else {
352 // Otherwise, this is a superfluous edge, remove it.
353 MBB.removeSuccessor(SI);
354 MadeChange = true;
355 }
356 }
357 if (!AddedFallThrough) {
358 assert(DestA == 0 && DestB == 0 &&
359 "MachineCFG is missing edges!");
360 } else if (isCond) {
361 assert(DestA == 0 && "MachineCFG is missing edges!");
362 }
363 return MadeChange;
364}
365
366
Chris Lattner21ab22e2004-07-31 10:01:27 +0000367/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
368/// 'Old', change the code and CFG so that it branches to 'New' instead.
369static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
370 MachineBasicBlock *Old,
371 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000372 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000373 assert(Old != New && "Cannot replace self with self!");
374
375 MachineBasicBlock::iterator I = BB->end();
376 while (I != BB->begin()) {
377 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000378 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000379
380 // Scan the operands of this machine instruction, replacing any uses of Old
381 // with New.
382 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
383 if (I->getOperand(i).isMachineBasicBlock() &&
384 I->getOperand(i).getMachineBasicBlock() == Old)
385 I->getOperand(i).setMachineBasicBlock(New);
386 }
387
Chris Lattnereb15eee2006-10-13 20:43:10 +0000388 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000389 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
390 for (int i = Succs.size()-1; i >= 0; --i)
391 if (Succs[i] == Old) {
392 BB->removeSuccessor(Old);
393 BB->addSuccessor(New);
394 }
395}
396
Chris Lattner7d097842006-10-24 01:12:32 +0000397/// CanFallThrough - Return true of the specified branch condition can transfer
398/// control to FallthroughBlock, the block immediately after the branch.
399static bool CanFallThrough(MachineBasicBlock *TBB,
400 MachineBasicBlock *FBB,
401 const std::vector<MachineOperand> &Cond,
402 MachineFunction::iterator FallthroughBlock) {
403 // If there is no branch, control always falls through.
404 if (TBB == 0) return true;
405
406 // If there is some explicit branch to the fallthrough block, it can obviously
407 // reach, even though the branch should get folded to fall through implicitly.
408 if (MachineFunction::iterator(TBB) == FallthroughBlock ||
409 MachineFunction::iterator(FBB) == FallthroughBlock)
410 return true;
411
412 // If it's an unconditional branch to some block not the fall through, it
413 // doesn't fall through.
414 if (Cond.empty()) return false;
415
416 // Otherwise, if it is conditional and has no explicit false block, it falls
417 // through.
418 return !Cond.empty() && FBB == 0;
419}
420
Chris Lattner7821a8a2006-10-14 00:21:48 +0000421/// OptimizeBlock - Analyze and optimize control flow related to the specified
422/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000423void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
424 MachineFunction::iterator FallThrough = MBB;
425 ++FallThrough;
426
Chris Lattnereb15eee2006-10-13 20:43:10 +0000427 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000428 // explicitly.
429 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000430 // Dead block? Leave for cleanup later.
431 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000432
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000433 if (FallThrough == MBB->getParent()->end()) {
434 // TODO: Simplify preds to not branch here if possible!
435 } else {
436 // Rewrite all predecessors of the old block to go to the fallthrough
437 // instead.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000438 while (!MBB->pred_empty()) {
439 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
440 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
441 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000442
443 // If MBB was the target of a jump table, update jump tables to go to the
444 // fallthrough instead.
445 MBB->getParent()->getJumpTableInfo()->ReplaceMBBInJumpTables(MBB,
446 FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000447 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000448 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000449 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000450 }
451
Chris Lattner7821a8a2006-10-14 00:21:48 +0000452 // Check to see if we can simplify the terminator of the block before this
453 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000454 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000455
Chris Lattner7821a8a2006-10-14 00:21:48 +0000456 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
457 std::vector<MachineOperand> PriorCond;
Chris Lattner386e2902006-10-21 05:08:28 +0000458 bool PriorUnAnalyzable = false;
459 PriorUnAnalyzable = TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
460 if (!PriorUnAnalyzable) {
461 // If the CFG for the prior block has extra edges, remove them.
462 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
463 !PriorCond.empty(), MBB);
464
Chris Lattner7821a8a2006-10-14 00:21:48 +0000465 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000466 // destination, remove the branch, replacing it with an unconditional one or
467 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000468 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000469 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000470 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000471 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000472 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000473 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000474 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000475 return OptimizeBlock(MBB);
476 }
477
478 // If the previous branch *only* branches to *this* block (conditional or
479 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000480 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000481 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000482 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000483 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000484 return OptimizeBlock(MBB);
485 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000486
487 // If the prior block branches somewhere else on the condition and here if
488 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000489 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000490 TII->RemoveBranch(PrevBB);
491 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
492 MadeChange = true;
493 ++NumBranchOpts;
494 return OptimizeBlock(MBB);
495 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000496
497 // If the prior block branches here on true and somewhere else on false, and
498 // if the branch condition is reversible, reverse the branch to create a
499 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000500 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000501 std::vector<MachineOperand> NewPriorCond(PriorCond);
502 if (!TII->ReverseBranchCondition(NewPriorCond)) {
503 TII->RemoveBranch(PrevBB);
504 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
505 MadeChange = true;
506 ++NumBranchOpts;
507 return OptimizeBlock(MBB);
508 }
509 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000510 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000511
Chris Lattner386e2902006-10-21 05:08:28 +0000512 // Analyze the branch in the current block.
513 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
514 std::vector<MachineOperand> CurCond;
515 if (!TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond)) {
516 // If the CFG for the prior block has extra edges, remove them.
517 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000518 !CurCond.empty(),
519 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000520
Chris Lattner386e2902006-10-21 05:08:28 +0000521 // If this branch is the only thing in its block, see if we can forward
522 // other blocks across it.
523 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000524 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000525 // This block may contain just an unconditional branch. Because there can
526 // be 'non-branch terminators' in the block, try removing the branch and
527 // then seeing if the block is empty.
528 TII->RemoveBranch(*MBB);
529
530 // If this block is just an unconditional branch to CurTBB, we can
531 // usually completely eliminate the block. The only case we cannot
532 // completely eliminate the block is when the block before this one
533 // falls through into MBB and we can't understand the prior block's branch
534 // condition.
535 if (MBB->empty() && (!PriorUnAnalyzable || !PrevBB.isSuccessor(MBB))) {
536 // If the prior block falls through into us, turn it into an
537 // explicit branch to us to make updates simpler.
Chris Lattner7d097842006-10-24 01:12:32 +0000538 if (PrevBB.isSuccessor(MBB) && PriorTBB != MBB && PriorFBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000539 if (PriorTBB == 0) {
540 assert(PriorCond.empty() && PriorFBB == 0 && "Bad branch analysis");
541 PriorTBB = MBB;
542 } else {
543 assert(PriorFBB == 0 && "Machine CFG out of date!");
544 PriorFBB = MBB;
545 }
546 TII->RemoveBranch(PrevBB);
547 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
548 }
549
550 // Iterate through all the predecessors, revectoring each in-turn.
Chris Lattner4bc135e2006-10-21 06:11:43 +0000551 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
552 bool DidChange = false;
553 bool HasBranchToSelf = false;
554 while (PI != MBB->pred_end()) {
Chris Lattner7d097842006-10-24 01:12:32 +0000555 if (*PI == MBB) {
Chris Lattner4bc135e2006-10-21 06:11:43 +0000556 // If this block has an uncond branch to itself, leave it.
557 ++PI;
558 HasBranchToSelf = true;
559 } else {
560 DidChange = true;
561 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
562 }
563 }
Chris Lattner386e2902006-10-21 05:08:28 +0000564
565 // Change any jumptables to go to the new MBB.
566 MBB->getParent()->getJumpTableInfo()->ReplaceMBBInJumpTables(MBB,
567 CurTBB);
Chris Lattner4bc135e2006-10-21 06:11:43 +0000568 if (DidChange) {
569 ++NumBranchOpts;
570 MadeChange = true;
571 if (!HasBranchToSelf) return;
572 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000573 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000574
Chris Lattner386e2902006-10-21 05:08:28 +0000575 // Add the branch back if the block is more than just an uncond branch.
576 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000577 }
Chris Lattner7d097842006-10-24 01:12:32 +0000578
579 // If the prior block doesn't fall through into this block, and if this
580 // block doesn't fall through into some other block, see if we can find a
581 // place to move this block where a fall-through will happen.
582 if (!PriorUnAnalyzable && !CanFallThrough(PriorTBB, PriorFBB,
583 PriorCond, MBB)) {
584 // Now we know that there was no fall-through into this block, check to
585 // see if it has fall-throughs.
586 if (!CanFallThrough(CurTBB, CurFBB, CurCond, FallThrough)) {
587
588 // Check all the predecessors of this block. If one of them has no fall
589 // throughs, move this block right after it.
590 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
591 E = MBB->pred_end(); PI != E; ++PI) {
592 // Analyze the branch at the end of the pred.
593 MachineBasicBlock *PredBB = *PI;
594 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
595 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
596 std::vector<MachineOperand> PredCond;
597 if (PredBB != MBB &&
598 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond) &&
599 !CanFallThrough(PredTBB, PredFBB, PredCond, PredFallthrough)) {
600 MBB->moveAfter(PredBB);
601 MadeChange = true;
602 return OptimizeBlock(MBB);
603 }
604 }
605
606 // Check all successors to see if we can move this block before it.
607 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
608 E = MBB->succ_end(); SI != E; ++SI) {
609 // Analyze the branch at the end of the block before the succ.
610 MachineBasicBlock *SuccBB = *SI;
611 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
612 MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
613 std::vector<MachineOperand> SuccPrevCond;
614 if (SuccBB != MBB &&
615 !TII->AnalyzeBranch(*SuccPrev, SuccPrevTBB, SuccPrevFBB,
616 SuccPrevCond) &&
617 !CanFallThrough(SuccPrevTBB, SuccPrevFBB, SuccPrevCond, SuccBB)) {
618 MBB->moveBefore(SuccBB);
619 MadeChange = true;
620 return OptimizeBlock(MBB);
621 }
622 }
623
624 // Okay, there is no really great place to put this block. If, however,
625 // the block before this one would be a fall-through if this block were
626 // removed, move this block to the end of the function.
627 if (FallThrough != MBB->getParent()->end() &&
628 CanFallThrough(PriorTBB, PriorFBB, PriorCond, FallThrough)) {
629 MBB->moveAfter(--MBB->getParent()->end());
630 MadeChange = true;
631 return;
632 }
633 }
634 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000635 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000636}