blob: d6bedb844bdeae9b878dd943654a9cfef09e6e8d [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
Chris Lattnerf10a56a2006-11-18 21:56:39 +000019#define DEBUG_TYPE "branchfolding"
Chris Lattner21ab22e2004-07-31 10:01:27 +000020#include "llvm/CodeGen/Passes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000024#include "llvm/Target/TargetInstrInfo.h"
25#include "llvm/Target/TargetMachine.h"
Chris Lattner12143052006-10-21 00:47:49 +000026#include "llvm/Support/CommandLine.h"
Chris Lattnerf10a56a2006-11-18 21:56:39 +000027#include "llvm/Support/Debug.h"
Chris Lattner12143052006-10-21 00:47:49 +000028#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000030#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000031using namespace llvm;
32
Chris Lattnercd3245a2006-12-19 22:41:21 +000033STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
34STATISTIC(NumBranchOpts, "Number of branches optimized");
35STATISTIC(NumTailMerge , "Number of block tails merged");
Chris Lattnerd8ccff02006-11-01 00:38:31 +000036static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
Chris Lattner12143052006-10-21 00:47:49 +000037
Chris Lattner21ab22e2004-07-31 10:01:27 +000038namespace {
39 struct BranchFolder : public MachineFunctionPass {
40 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000041 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
42 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000043 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000044 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000045 private:
Chris Lattner12143052006-10-21 00:47:49 +000046 // Tail Merging.
47 bool TailMergeBlocks(MachineFunction &MF);
48 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
49 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000050 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
51 MachineBasicBlock::iterator BBI1);
52
Chris Lattner12143052006-10-21 00:47:49 +000053 // Branch optzn.
54 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000055 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000056 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000057
58 bool CanFallThrough(MachineBasicBlock *CurBB);
59 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
60 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
61 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000062 };
63}
64
65FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
66
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000067/// RemoveDeadBlock - Remove the specified dead machine basic block from the
68/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000069void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000070 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +000071 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +000072
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000073 MachineFunction *MF = MBB->getParent();
74 // drop all successors.
75 while (!MBB->succ_empty())
76 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000077
Jim Laskey1ee29252007-01-26 14:34:52 +000078 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +000079 // records in the basic block. If so, unregister them from MachineModuleInfo.
80 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000081 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
82 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +000083 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +000084 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000085 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000086 }
87 }
88 }
89
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000090 // Remove the block.
91 MF->getBasicBlockList().erase(MBB);
92}
93
Chris Lattner21ab22e2004-07-31 10:01:27 +000094bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +000095 TII = MF.getTarget().getInstrInfo();
96 if (!TII) return false;
97
Jim Laskey44c3b9f2007-01-26 21:22:28 +000098 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +000099
Chris Lattner21ab22e2004-07-31 10:01:27 +0000100 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000101 bool MadeChangeThisIteration = true;
102 while (MadeChangeThisIteration) {
103 MadeChangeThisIteration = false;
104 MadeChangeThisIteration |= TailMergeBlocks(MF);
105 MadeChangeThisIteration |= OptimizeBranches(MF);
106 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000107 }
108
Chris Lattner6acfe122006-10-28 18:34:47 +0000109 // See if any jump tables have become mergable or dead as the code generator
110 // did its thing.
111 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
112 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
113 if (!JTs.empty()) {
114 // Figure out how these jump tables should be merged.
115 std::vector<unsigned> JTMapping;
116 JTMapping.reserve(JTs.size());
117
118 // We always keep the 0th jump table.
119 JTMapping.push_back(0);
120
121 // Scan the jump tables, seeing if there are any duplicates. Note that this
122 // is N^2, which should be fixed someday.
123 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
124 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
125
126 // If a jump table was merge with another one, walk the function rewriting
127 // references to jump tables to reference the new JT ID's. Keep track of
128 // whether we see a jump table idx, if not, we can delete the JT.
129 std::vector<bool> JTIsLive;
130 JTIsLive.resize(JTs.size());
131 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
132 BB != E; ++BB) {
133 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
134 I != E; ++I)
135 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
136 MachineOperand &Op = I->getOperand(op);
137 if (!Op.isJumpTableIndex()) continue;
138 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
139 Op.setJumpTableIndex(NewIdx);
140
141 // Remember that this JT is live.
142 JTIsLive[NewIdx] = true;
143 }
144 }
145
146 // Finally, remove dead jump tables. This happens either because the
147 // indirect jump was unreachable (and thus deleted) or because the jump
148 // table was merged with some other one.
149 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
150 if (!JTIsLive[i]) {
151 JTI->RemoveJumpTable(i);
152 EverMadeChange = true;
153 }
154 }
155
Chris Lattner21ab22e2004-07-31 10:01:27 +0000156 return EverMadeChange;
157}
158
Chris Lattner12143052006-10-21 00:47:49 +0000159//===----------------------------------------------------------------------===//
160// Tail Merging of Blocks
161//===----------------------------------------------------------------------===//
162
163/// HashMachineInstr - Compute a hash value for MI and its operands.
164static unsigned HashMachineInstr(const MachineInstr *MI) {
165 unsigned Hash = MI->getOpcode();
166 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
167 const MachineOperand &Op = MI->getOperand(i);
168
169 // Merge in bits from the operand if easy.
170 unsigned OperandHash = 0;
171 switch (Op.getType()) {
172 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
173 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
174 case MachineOperand::MO_MachineBasicBlock:
175 OperandHash = Op.getMachineBasicBlock()->getNumber();
176 break;
177 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
178 case MachineOperand::MO_ConstantPoolIndex:
179 OperandHash = Op.getConstantPoolIndex();
180 break;
181 case MachineOperand::MO_JumpTableIndex:
182 OperandHash = Op.getJumpTableIndex();
183 break;
184 case MachineOperand::MO_GlobalAddress:
185 case MachineOperand::MO_ExternalSymbol:
186 // Global address / external symbol are too hard, don't bother, but do
187 // pull in the offset.
188 OperandHash = Op.getOffset();
189 break;
190 default: break;
191 }
192
193 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
194 }
195 return Hash;
196}
197
198/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
199/// instructions, because cross-jumping only saves code when at least two
200/// instructions are removed (since a branch must be inserted).
201static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
202 MachineBasicBlock::const_iterator I = MBB->end();
203 if (I == MBB->begin())
204 return 0; // Empty MBB.
205
206 --I;
207 unsigned Hash = HashMachineInstr(I);
208
209 if (I == MBB->begin())
210 return Hash; // Single instr MBB.
211
212 --I;
213 // Hash in the second-to-last instruction.
214 Hash ^= HashMachineInstr(I) << 2;
215 return Hash;
216}
217
218/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
219/// of instructions they actually have in common together at their end. Return
220/// iterators for the first shared instruction in each block.
221static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
222 MachineBasicBlock *MBB2,
223 MachineBasicBlock::iterator &I1,
224 MachineBasicBlock::iterator &I2) {
225 I1 = MBB1->end();
226 I2 = MBB2->end();
227
228 unsigned TailLen = 0;
229 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
230 --I1; --I2;
231 if (!I1->isIdenticalTo(I2)) {
232 ++I1; ++I2;
233 break;
234 }
235 ++TailLen;
236 }
237 return TailLen;
238}
239
240/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000241/// after it, replacing it with an unconditional branch to NewDest. This
242/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000243void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
244 MachineBasicBlock *NewDest) {
245 MachineBasicBlock *OldBB = OldInst->getParent();
246
247 // Remove all the old successors of OldBB from the CFG.
248 while (!OldBB->succ_empty())
249 OldBB->removeSuccessor(OldBB->succ_begin());
250
251 // Remove all the dead instructions from the end of OldBB.
252 OldBB->erase(OldInst, OldBB->end());
253
Chris Lattner386e2902006-10-21 05:08:28 +0000254 // If OldBB isn't immediately before OldBB, insert a branch to it.
255 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
256 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000257 OldBB->addSuccessor(NewDest);
258 ++NumTailMerge;
259}
260
Chris Lattner1d08d832006-11-01 01:16:12 +0000261/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
262/// MBB so that the part before the iterator falls into the part starting at the
263/// iterator. This returns the new MBB.
264MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
265 MachineBasicBlock::iterator BBI1) {
266 // Create the fall-through block.
267 MachineFunction::iterator MBBI = &CurMBB;
268 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
269 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
270
271 // Move all the successors of this block to the specified block.
272 while (!CurMBB.succ_empty()) {
273 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
274 NewMBB->addSuccessor(S);
275 CurMBB.removeSuccessor(S);
276 }
277
278 // Add an edge from CurMBB to NewMBB for the fall-through.
279 CurMBB.addSuccessor(NewMBB);
280
281 // Splice the code over.
282 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
283 return NewMBB;
284}
285
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000286/// EstimateRuntime - Make a rough estimate for how long it will take to run
287/// the specified code.
288static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
289 MachineBasicBlock::iterator E,
290 const TargetInstrInfo *TII) {
291 unsigned Time = 0;
292 for (; I != E; ++I) {
293 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
294 if (TID.Flags & M_CALL_FLAG)
295 Time += 10;
296 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
297 Time += 2;
298 else
299 ++Time;
300 }
301 return Time;
302}
303
304/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
305/// MBB2I and then insert an unconditional branch in the other block. Determine
306/// which is the best to split
307static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
308 MachineBasicBlock::iterator MBB1I,
309 MachineBasicBlock *MBB2,
310 MachineBasicBlock::iterator MBB2I,
311 const TargetInstrInfo *TII) {
312 // TODO: if we had some notion of which block was hotter, we could split
313 // the hot block, so it is the fall-through. Since we don't have profile info
314 // make a decision based on which will hurt most to split.
315 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
316 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
317
318 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
319 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
320 // have a lower overall impact on the program execution.
321 return MBB1Time < MBB2Time;
322}
323
Chris Lattner12143052006-10-21 00:47:49 +0000324bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
325 MadeChange = false;
326
Chris Lattnerd8ccff02006-11-01 00:38:31 +0000327 if (!EnableTailMerge) return false;
Chris Lattner323ece62006-10-25 18:08:50 +0000328
Chris Lattner12143052006-10-21 00:47:49 +0000329 // Find blocks with no successors.
330 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
331 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
332 if (I->succ_empty())
333 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
334 }
335
336 // Sort by hash value so that blocks with identical end sequences sort
337 // together.
338 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
339
340 // Walk through equivalence sets looking for actual exact matches.
341 while (MergePotentials.size() > 1) {
342 unsigned CurHash = (MergePotentials.end()-1)->first;
343 unsigned PrevHash = (MergePotentials.end()-2)->first;
344 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
345
346 // If there is nothing that matches the hash of the current basic block,
347 // give up.
348 if (CurHash != PrevHash) {
349 MergePotentials.pop_back();
350 continue;
351 }
352
353 // Determine the actual length of the shared tail between these two basic
354 // blocks. Because the hash can have collisions, it's possible that this is
355 // less than 2.
356 MachineBasicBlock::iterator BBI1, BBI2;
357 unsigned CommonTailLen =
358 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
359 BBI1, BBI2);
360
361 // If the tails don't have at least two instructions in common, see if there
362 // is anything else in the equivalence class that does match.
363 if (CommonTailLen < 2) {
364 unsigned FoundMatch = ~0U;
365 for (int i = MergePotentials.size()-2;
366 i != -1 && MergePotentials[i].first == CurHash; --i) {
367 CommonTailLen = ComputeCommonTailLength(CurMBB,
368 MergePotentials[i].second,
369 BBI1, BBI2);
370 if (CommonTailLen >= 2) {
371 FoundMatch = i;
372 break;
373 }
374 }
375
376 // If we didn't find anything that has at least two instructions matching
377 // this one, bail out.
378 if (FoundMatch == ~0U) {
379 MergePotentials.pop_back();
380 continue;
381 }
382
383 // Otherwise, move the matching block to the right position.
384 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
385 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000386
Chris Lattner12143052006-10-21 00:47:49 +0000387 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000388
389 // If neither block is the entire common tail, split the tail of one block
390 // to make it redundant with the other tail.
391 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
392 if (0) { // Enable this to disable partial tail merges.
393 MergePotentials.pop_back();
394 continue;
395 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000396
397 // Decide whether we want to split CurMBB or MBB2.
398 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
399 CurMBB = SplitMBBAt(*CurMBB, BBI1);
400 BBI1 = CurMBB->begin();
401 MergePotentials.back().second = CurMBB;
402 } else {
403 MBB2 = SplitMBBAt(*MBB2, BBI2);
404 BBI2 = MBB2->begin();
405 (MergePotentials.end()-2)->second = MBB2;
406 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000407 }
408
409 if (MBB2->begin() == BBI2) {
Chris Lattner12143052006-10-21 00:47:49 +0000410 // Hack the end off CurMBB, making it jump to MBBI@ instead.
411 ReplaceTailWithBranchTo(BBI1, MBB2);
412 // This modifies CurMBB, so remove it from the worklist.
413 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000414 } else {
415 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
416 // Hack the end off MBB2, making it jump to CurMBB instead.
417 ReplaceTailWithBranchTo(BBI2, CurMBB);
418 // This modifies MBB2, so remove it from the worklist.
419 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000420 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000421 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000422 }
423
424 return MadeChange;
425}
426
427
428//===----------------------------------------------------------------------===//
429// Branch Optimization
430//===----------------------------------------------------------------------===//
431
432bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
433 MadeChange = false;
434
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000435 // Make sure blocks are numbered in order
436 MF.RenumberBlocks();
437
Chris Lattner12143052006-10-21 00:47:49 +0000438 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
439 MachineBasicBlock *MBB = I++;
440 OptimizeBlock(MBB);
441
442 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000443 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000444 RemoveDeadBlock(MBB);
445 MadeChange = true;
446 ++NumDeadBlocks;
447 }
448 }
449 return MadeChange;
450}
451
452
Chris Lattner386e2902006-10-21 05:08:28 +0000453/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
454/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
455/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
456/// be null.
457static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
458 MachineBasicBlock *DestA,
459 MachineBasicBlock *DestB,
460 bool isCond,
461 MachineFunction::iterator FallThru) {
462 bool MadeChange = false;
463 bool AddedFallThrough = false;
464
465 // If this block ends with a conditional branch that falls through to its
466 // successor, set DestB as the successor.
467 if (isCond) {
468 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
469 DestB = FallThru;
470 AddedFallThrough = true;
471 }
472 } else {
473 // If this is an unconditional branch with no explicit dest, it must just be
474 // a fallthrough into DestB.
475 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
476 DestA = FallThru;
477 AddedFallThrough = true;
478 }
479 }
480
481 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
482 while (SI != MBB.succ_end()) {
483 if (*SI == DestA) {
484 DestA = 0;
485 ++SI;
486 } else if (*SI == DestB) {
487 DestB = 0;
488 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000489 } else if ((*SI)->isLandingPad()) {
490 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000491 } else {
492 // Otherwise, this is a superfluous edge, remove it.
493 MBB.removeSuccessor(SI);
494 MadeChange = true;
495 }
496 }
497 if (!AddedFallThrough) {
498 assert(DestA == 0 && DestB == 0 &&
499 "MachineCFG is missing edges!");
500 } else if (isCond) {
501 assert(DestA == 0 && "MachineCFG is missing edges!");
502 }
503 return MadeChange;
504}
505
506
Chris Lattner21ab22e2004-07-31 10:01:27 +0000507/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
508/// 'Old', change the code and CFG so that it branches to 'New' instead.
509static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
510 MachineBasicBlock *Old,
511 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000512 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000513 assert(Old != New && "Cannot replace self with self!");
514
515 MachineBasicBlock::iterator I = BB->end();
516 while (I != BB->begin()) {
517 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000518 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000519
520 // Scan the operands of this machine instruction, replacing any uses of Old
521 // with New.
522 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
523 if (I->getOperand(i).isMachineBasicBlock() &&
524 I->getOperand(i).getMachineBasicBlock() == Old)
525 I->getOperand(i).setMachineBasicBlock(New);
526 }
527
Chris Lattnereb15eee2006-10-13 20:43:10 +0000528 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000529 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
530 for (int i = Succs.size()-1; i >= 0; --i)
531 if (Succs[i] == Old) {
532 BB->removeSuccessor(Old);
533 BB->addSuccessor(New);
534 }
535}
536
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000537/// CanFallThrough - Return true if the specified block (with the specified
538/// branch condition) can implicitly transfer control to the block after it by
539/// falling off the end of it. This should return false if it can reach the
540/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
541///
542/// True is a conservative answer.
543///
544bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
545 bool BranchUnAnalyzable,
546 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
547 const std::vector<MachineOperand> &Cond) {
548 MachineFunction::iterator Fallthrough = CurBB;
549 ++Fallthrough;
550 // If FallthroughBlock is off the end of the function, it can't fall through.
551 if (Fallthrough == CurBB->getParent()->end())
552 return false;
553
554 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
555 if (!CurBB->isSuccessor(Fallthrough))
556 return false;
557
558 // If we couldn't analyze the branch, assume it could fall through.
559 if (BranchUnAnalyzable) return true;
560
Chris Lattner7d097842006-10-24 01:12:32 +0000561 // If there is no branch, control always falls through.
562 if (TBB == 0) return true;
563
564 // If there is some explicit branch to the fallthrough block, it can obviously
565 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000566 if (MachineFunction::iterator(TBB) == Fallthrough ||
567 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000568 return true;
569
570 // If it's an unconditional branch to some block not the fall through, it
571 // doesn't fall through.
572 if (Cond.empty()) return false;
573
574 // Otherwise, if it is conditional and has no explicit false block, it falls
575 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000576 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000577}
578
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000579/// CanFallThrough - Return true if the specified can implicitly transfer
580/// control to the block after it by falling off the end of it. This should
581/// return false if it can reach the block after it, but it uses an explicit
582/// branch to do so (e.g. a table jump).
583///
584/// True is a conservative answer.
585///
586bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
587 MachineBasicBlock *TBB = 0, *FBB = 0;
588 std::vector<MachineOperand> Cond;
589 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
590 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
591}
592
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000593/// IsBetterFallthrough - Return true if it would be clearly better to
594/// fall-through to MBB1 than to fall through into MBB2. This has to return
595/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
596/// result in infinite loops.
597static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
598 MachineBasicBlock *MBB2,
599 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000600 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
601 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000602 // optimize branches that branch to either a return block or an assert block
603 // into a fallthrough to the return.
604 if (MBB1->empty() || MBB2->empty()) return false;
605
606 MachineInstr *MBB1I = --MBB1->end();
607 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000608 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000609}
610
Chris Lattner7821a8a2006-10-14 00:21:48 +0000611/// OptimizeBlock - Analyze and optimize control flow related to the specified
612/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000613void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
614 MachineFunction::iterator FallThrough = MBB;
615 ++FallThrough;
616
Chris Lattnereb15eee2006-10-13 20:43:10 +0000617 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000618 // explicitly.
619 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000620 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000621 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000622
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000623 if (FallThrough == MBB->getParent()->end()) {
624 // TODO: Simplify preds to not branch here if possible!
625 } else {
626 // Rewrite all predecessors of the old block to go to the fallthrough
627 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000628 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000629 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
630 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
631 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000632
633 // If MBB was the target of a jump table, update jump tables to go to the
634 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000635 MBB->getParent()->getJumpTableInfo()->
636 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000637 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000638 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000639 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000640 }
641
Chris Lattner7821a8a2006-10-14 00:21:48 +0000642 // Check to see if we can simplify the terminator of the block before this
643 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000644 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000645
Chris Lattner7821a8a2006-10-14 00:21:48 +0000646 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
647 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000648 bool PriorUnAnalyzable =
649 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000650 if (!PriorUnAnalyzable) {
651 // If the CFG for the prior block has extra edges, remove them.
652 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
653 !PriorCond.empty(), MBB);
654
Chris Lattner7821a8a2006-10-14 00:21:48 +0000655 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000656 // destination, remove the branch, replacing it with an unconditional one or
657 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000658 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000659 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000660 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000661 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000662 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000663 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000664 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000665 return OptimizeBlock(MBB);
666 }
667
668 // If the previous branch *only* branches to *this* block (conditional or
669 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000670 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000671 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000672 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000673 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000674 return OptimizeBlock(MBB);
675 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000676
677 // If the prior block branches somewhere else on the condition and here if
678 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000679 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000680 TII->RemoveBranch(PrevBB);
681 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
682 MadeChange = true;
683 ++NumBranchOpts;
684 return OptimizeBlock(MBB);
685 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000686
687 // If the prior block branches here on true and somewhere else on false, and
688 // if the branch condition is reversible, reverse the branch to create a
689 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000690 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000691 std::vector<MachineOperand> NewPriorCond(PriorCond);
692 if (!TII->ReverseBranchCondition(NewPriorCond)) {
693 TII->RemoveBranch(PrevBB);
694 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
695 MadeChange = true;
696 ++NumBranchOpts;
697 return OptimizeBlock(MBB);
698 }
699 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000700
Chris Lattner154e1042006-11-18 21:30:35 +0000701 // If this block doesn't fall through (e.g. it ends with an uncond branch or
702 // has no successors) and if the pred falls through into this block, and if
703 // it would otherwise fall through into the block after this, move this
704 // block to the end of the function.
705 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000706 // We consider it more likely that execution will stay in the function (e.g.
707 // due to loops) than it is to exit it. This asserts in loops etc, moving
708 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000709 if (!PriorCond.empty() && PriorFBB == 0 &&
710 MachineFunction::iterator(PriorTBB) == FallThrough &&
711 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000712 bool DoTransform = true;
713
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000714 // We have to be careful that the succs of PredBB aren't both no-successor
715 // blocks. If neither have successors and if PredBB is the second from
716 // last block in the function, we'd just keep swapping the two blocks for
717 // last. Only do the swap if one is clearly better to fall through than
718 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000719 if (FallThrough == --MBB->getParent()->end() &&
720 !IsBetterFallthrough(PriorTBB, MBB, *TII))
721 DoTransform = false;
722
723 // We don't want to do this transformation if we have control flow like:
724 // br cond BB2
725 // BB1:
726 // ..
727 // jmp BBX
728 // BB2:
729 // ..
730 // ret
731 //
732 // In this case, we could actually be moving the return block *into* a
733 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000734 if (DoTransform && !MBB->succ_empty() &&
735 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000736 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000737
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000738
739 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000740 // Reverse the branch so we will fall through on the previous true cond.
741 std::vector<MachineOperand> NewPriorCond(PriorCond);
742 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000743 DOUT << "\nMoving MBB: " << *MBB;
744 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
745
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000746 TII->RemoveBranch(PrevBB);
747 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
748
749 // Move this block to the end of the function.
750 MBB->moveAfter(--MBB->getParent()->end());
751 MadeChange = true;
752 ++NumBranchOpts;
753 return;
754 }
755 }
756 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000757 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000758
Chris Lattner386e2902006-10-21 05:08:28 +0000759 // Analyze the branch in the current block.
760 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
761 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000762 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
763 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000764 // If the CFG for the prior block has extra edges, remove them.
765 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000766 !CurCond.empty(),
767 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000768
Chris Lattner5d056952006-11-08 01:03:21 +0000769 // If this is a two-way branch, and the FBB branches to this block, reverse
770 // the condition so the single-basic-block loop is faster. Instead of:
771 // Loop: xxx; jcc Out; jmp Loop
772 // we want:
773 // Loop: xxx; jncc Loop; jmp Out
774 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
775 std::vector<MachineOperand> NewCond(CurCond);
776 if (!TII->ReverseBranchCondition(NewCond)) {
777 TII->RemoveBranch(*MBB);
778 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
779 MadeChange = true;
780 ++NumBranchOpts;
781 return OptimizeBlock(MBB);
782 }
783 }
784
785
Chris Lattner386e2902006-10-21 05:08:28 +0000786 // If this branch is the only thing in its block, see if we can forward
787 // other blocks across it.
788 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000789 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000790 // This block may contain just an unconditional branch. Because there can
791 // be 'non-branch terminators' in the block, try removing the branch and
792 // then seeing if the block is empty.
793 TII->RemoveBranch(*MBB);
794
795 // If this block is just an unconditional branch to CurTBB, we can
796 // usually completely eliminate the block. The only case we cannot
797 // completely eliminate the block is when the block before this one
798 // falls through into MBB and we can't understand the prior block's branch
799 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000800 if (MBB->empty()) {
801 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
802 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
803 !PrevBB.isSuccessor(MBB)) {
804 // If the prior block falls through into us, turn it into an
805 // explicit branch to us to make updates simpler.
806 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
807 PriorTBB != MBB && PriorFBB != MBB) {
808 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000809 assert(PriorCond.empty() && PriorFBB == 0 &&
810 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000811 PriorTBB = MBB;
812 } else {
813 assert(PriorFBB == 0 && "Machine CFG out of date!");
814 PriorFBB = MBB;
815 }
816 TII->RemoveBranch(PrevBB);
817 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000818 }
Chris Lattner386e2902006-10-21 05:08:28 +0000819
Chris Lattnercf420cc2006-10-28 17:32:47 +0000820 // Iterate through all the predecessors, revectoring each in-turn.
821 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
822 bool DidChange = false;
823 bool HasBranchToSelf = false;
824 while (PI != MBB->pred_end()) {
825 if (*PI == MBB) {
826 // If this block has an uncond branch to itself, leave it.
827 ++PI;
828 HasBranchToSelf = true;
829 } else {
830 DidChange = true;
831 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
832 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000833 }
Chris Lattner386e2902006-10-21 05:08:28 +0000834
Chris Lattnercf420cc2006-10-28 17:32:47 +0000835 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000836 MBB->getParent()->getJumpTableInfo()->
837 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +0000838 if (DidChange) {
839 ++NumBranchOpts;
840 MadeChange = true;
841 if (!HasBranchToSelf) return;
842 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000843 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000844 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000845
Chris Lattner386e2902006-10-21 05:08:28 +0000846 // Add the branch back if the block is more than just an uncond branch.
847 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000848 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000849 }
850
851 // If the prior block doesn't fall through into this block, and if this
852 // block doesn't fall through into some other block, see if we can find a
853 // place to move this block where a fall-through will happen.
854 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
855 PriorTBB, PriorFBB, PriorCond)) {
856 // Now we know that there was no fall-through into this block, check to
857 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000858 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
859 CurCond);
860
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000861 if (!MBB->isLandingPad()) {
862 // Check all the predecessors of this block. If one of them has no fall
863 // throughs, move this block right after it.
864 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
865 E = MBB->pred_end(); PI != E; ++PI) {
866 // Analyze the branch at the end of the pred.
867 MachineBasicBlock *PredBB = *PI;
868 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
869 if (PredBB != MBB && !CanFallThrough(PredBB)
870 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
871 // If the current block doesn't fall through, just move it.
872 // If the current block can fall through and does not end with a
873 // conditional branch, we need to append an unconditional jump to
874 // the (current) next block. To avoid a possible compile-time
875 // infinite loop, move blocks only backward in this case.
876 if (CurFallsThru) {
877 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
878 CurCond.clear();
879 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
880 }
881 MBB->moveAfter(PredBB);
882 MadeChange = true;
883 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000884 }
885 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000886 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000887
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000888 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000889 // Check all successors to see if we can move this block before it.
890 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
891 E = MBB->succ_end(); SI != E; ++SI) {
892 // Analyze the branch at the end of the block before the succ.
893 MachineBasicBlock *SuccBB = *SI;
894 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000895 std::vector<MachineOperand> SuccPrevCond;
896 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
897 MBB->moveBefore(SuccBB);
898 MadeChange = true;
899 return OptimizeBlock(MBB);
900 }
901 }
902
903 // Okay, there is no really great place to put this block. If, however,
904 // the block before this one would be a fall-through if this block were
905 // removed, move this block to the end of the function.
906 if (FallThrough != MBB->getParent()->end() &&
907 PrevBB.isSuccessor(FallThrough)) {
908 MBB->moveAfter(--MBB->getParent()->end());
909 MadeChange = true;
910 return;
911 }
Chris Lattner7d097842006-10-24 01:12:32 +0000912 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000913 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000914}