1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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
14 // Note that this pass must be run after register allocation, it cannot handle
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "branchfolding"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineDebugInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
33 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
34 STATISTIC(NumBranchOpts, "Number of branches optimized");
35 STATISTIC(NumTailMerge , "Number of block tails merged");
36 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
39 struct BranchFolder : public MachineFunctionPass {
40 virtual bool runOnMachineFunction(MachineFunction &MF);
41 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
42 const TargetInstrInfo *TII;
43 MachineDebugInfo *MDI;
47 bool TailMergeBlocks(MachineFunction &MF);
48 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
49 MachineBasicBlock *NewDest);
50 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
51 MachineBasicBlock::iterator BBI1);
54 bool OptimizeBranches(MachineFunction &MF);
55 void OptimizeBlock(MachineBasicBlock *MBB);
56 void RemoveDeadBlock(MachineBasicBlock *MBB);
58 bool CanFallThrough(MachineBasicBlock *CurBB);
59 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
60 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
61 const std::vector<MachineOperand> &Cond);
65 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
67 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
68 /// function, updating the CFG.
69 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
70 assert(MBB->pred_empty() && "MBB must be dead!");
72 MachineFunction *MF = MBB->getParent();
73 // drop all successors.
74 while (!MBB->succ_empty())
75 MBB->removeSuccessor(MBB->succ_end()-1);
77 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
78 // records in the basic block. If so, unregister them from MachineDebugInfo.
79 if (MDI && !MBB->empty()) {
80 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
81 assert(DWARF_LABELOpc &&
82 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
84 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
86 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
87 // The label ID # is always operand #0, an immediate.
88 MDI->InvalidateLabel(I->getOperand(0).getImm());
94 MF->getBasicBlockList().erase(MBB);
97 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
98 TII = MF.getTarget().getInstrInfo();
99 if (!TII) return false;
101 MDI = getAnalysisToUpdate<MachineDebugInfo>();
103 bool EverMadeChange = false;
104 bool MadeChangeThisIteration = true;
105 while (MadeChangeThisIteration) {
106 MadeChangeThisIteration = false;
107 MadeChangeThisIteration |= TailMergeBlocks(MF);
108 MadeChangeThisIteration |= OptimizeBranches(MF);
109 EverMadeChange |= MadeChangeThisIteration;
112 // See if any jump tables have become mergable or dead as the code generator
114 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
115 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
117 // Figure out how these jump tables should be merged.
118 std::vector<unsigned> JTMapping;
119 JTMapping.reserve(JTs.size());
121 // We always keep the 0th jump table.
122 JTMapping.push_back(0);
124 // Scan the jump tables, seeing if there are any duplicates. Note that this
125 // is N^2, which should be fixed someday.
126 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
127 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
129 // If a jump table was merge with another one, walk the function rewriting
130 // references to jump tables to reference the new JT ID's. Keep track of
131 // whether we see a jump table idx, if not, we can delete the JT.
132 std::vector<bool> JTIsLive;
133 JTIsLive.resize(JTs.size());
134 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
136 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
138 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
139 MachineOperand &Op = I->getOperand(op);
140 if (!Op.isJumpTableIndex()) continue;
141 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
142 Op.setJumpTableIndex(NewIdx);
144 // Remember that this JT is live.
145 JTIsLive[NewIdx] = true;
149 // Finally, remove dead jump tables. This happens either because the
150 // indirect jump was unreachable (and thus deleted) or because the jump
151 // table was merged with some other one.
152 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
154 JTI->RemoveJumpTable(i);
155 EverMadeChange = true;
159 return EverMadeChange;
162 //===----------------------------------------------------------------------===//
163 // Tail Merging of Blocks
164 //===----------------------------------------------------------------------===//
166 /// HashMachineInstr - Compute a hash value for MI and its operands.
167 static unsigned HashMachineInstr(const MachineInstr *MI) {
168 unsigned Hash = MI->getOpcode();
169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170 const MachineOperand &Op = MI->getOperand(i);
172 // Merge in bits from the operand if easy.
173 unsigned OperandHash = 0;
174 switch (Op.getType()) {
175 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
176 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
177 case MachineOperand::MO_MachineBasicBlock:
178 OperandHash = Op.getMachineBasicBlock()->getNumber();
180 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
181 case MachineOperand::MO_ConstantPoolIndex:
182 OperandHash = Op.getConstantPoolIndex();
184 case MachineOperand::MO_JumpTableIndex:
185 OperandHash = Op.getJumpTableIndex();
187 case MachineOperand::MO_GlobalAddress:
188 case MachineOperand::MO_ExternalSymbol:
189 // Global address / external symbol are too hard, don't bother, but do
190 // pull in the offset.
191 OperandHash = Op.getOffset();
196 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
201 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
202 /// instructions, because cross-jumping only saves code when at least two
203 /// instructions are removed (since a branch must be inserted).
204 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
205 MachineBasicBlock::const_iterator I = MBB->end();
206 if (I == MBB->begin())
207 return 0; // Empty MBB.
210 unsigned Hash = HashMachineInstr(I);
212 if (I == MBB->begin())
213 return Hash; // Single instr MBB.
216 // Hash in the second-to-last instruction.
217 Hash ^= HashMachineInstr(I) << 2;
221 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
222 /// of instructions they actually have in common together at their end. Return
223 /// iterators for the first shared instruction in each block.
224 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
225 MachineBasicBlock *MBB2,
226 MachineBasicBlock::iterator &I1,
227 MachineBasicBlock::iterator &I2) {
231 unsigned TailLen = 0;
232 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
234 if (!I1->isIdenticalTo(I2)) {
243 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
244 /// after it, replacing it with an unconditional branch to NewDest. This
245 /// returns true if OldInst's block is modified, false if NewDest is modified.
246 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
247 MachineBasicBlock *NewDest) {
248 MachineBasicBlock *OldBB = OldInst->getParent();
250 // Remove all the old successors of OldBB from the CFG.
251 while (!OldBB->succ_empty())
252 OldBB->removeSuccessor(OldBB->succ_begin());
254 // Remove all the dead instructions from the end of OldBB.
255 OldBB->erase(OldInst, OldBB->end());
257 // If OldBB isn't immediately before OldBB, insert a branch to it.
258 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
259 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
260 OldBB->addSuccessor(NewDest);
264 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
265 /// MBB so that the part before the iterator falls into the part starting at the
266 /// iterator. This returns the new MBB.
267 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
268 MachineBasicBlock::iterator BBI1) {
269 // Create the fall-through block.
270 MachineFunction::iterator MBBI = &CurMBB;
271 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
272 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
274 // Move all the successors of this block to the specified block.
275 while (!CurMBB.succ_empty()) {
276 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
277 NewMBB->addSuccessor(S);
278 CurMBB.removeSuccessor(S);
281 // Add an edge from CurMBB to NewMBB for the fall-through.
282 CurMBB.addSuccessor(NewMBB);
284 // Splice the code over.
285 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
289 /// EstimateRuntime - Make a rough estimate for how long it will take to run
290 /// the specified code.
291 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
292 MachineBasicBlock::iterator E,
293 const TargetInstrInfo *TII) {
295 for (; I != E; ++I) {
296 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
297 if (TID.Flags & M_CALL_FLAG)
299 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
307 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
308 /// MBB2I and then insert an unconditional branch in the other block. Determine
309 /// which is the best to split
310 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
311 MachineBasicBlock::iterator MBB1I,
312 MachineBasicBlock *MBB2,
313 MachineBasicBlock::iterator MBB2I,
314 const TargetInstrInfo *TII) {
315 // TODO: if we had some notion of which block was hotter, we could split
316 // the hot block, so it is the fall-through. Since we don't have profile info
317 // make a decision based on which will hurt most to split.
318 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
319 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
321 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
322 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
323 // have a lower overall impact on the program execution.
324 return MBB1Time < MBB2Time;
327 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
330 if (!EnableTailMerge) return false;
332 // Find blocks with no successors.
333 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
334 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
336 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
339 // Sort by hash value so that blocks with identical end sequences sort
341 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
343 // Walk through equivalence sets looking for actual exact matches.
344 while (MergePotentials.size() > 1) {
345 unsigned CurHash = (MergePotentials.end()-1)->first;
346 unsigned PrevHash = (MergePotentials.end()-2)->first;
347 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
349 // If there is nothing that matches the hash of the current basic block,
351 if (CurHash != PrevHash) {
352 MergePotentials.pop_back();
356 // Determine the actual length of the shared tail between these two basic
357 // blocks. Because the hash can have collisions, it's possible that this is
359 MachineBasicBlock::iterator BBI1, BBI2;
360 unsigned CommonTailLen =
361 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
364 // If the tails don't have at least two instructions in common, see if there
365 // is anything else in the equivalence class that does match.
366 if (CommonTailLen < 2) {
367 unsigned FoundMatch = ~0U;
368 for (int i = MergePotentials.size()-2;
369 i != -1 && MergePotentials[i].first == CurHash; --i) {
370 CommonTailLen = ComputeCommonTailLength(CurMBB,
371 MergePotentials[i].second,
373 if (CommonTailLen >= 2) {
379 // If we didn't find anything that has at least two instructions matching
380 // this one, bail out.
381 if (FoundMatch == ~0U) {
382 MergePotentials.pop_back();
386 // Otherwise, move the matching block to the right position.
387 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
390 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
392 // If neither block is the entire common tail, split the tail of one block
393 // to make it redundant with the other tail.
394 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
395 if (0) { // Enable this to disable partial tail merges.
396 MergePotentials.pop_back();
400 // Decide whether we want to split CurMBB or MBB2.
401 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
402 CurMBB = SplitMBBAt(*CurMBB, BBI1);
403 BBI1 = CurMBB->begin();
404 MergePotentials.back().second = CurMBB;
406 MBB2 = SplitMBBAt(*MBB2, BBI2);
407 BBI2 = MBB2->begin();
408 (MergePotentials.end()-2)->second = MBB2;
412 if (MBB2->begin() == BBI2) {
413 // Hack the end off CurMBB, making it jump to MBBI@ instead.
414 ReplaceTailWithBranchTo(BBI1, MBB2);
415 // This modifies CurMBB, so remove it from the worklist.
416 MergePotentials.pop_back();
418 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
419 // Hack the end off MBB2, making it jump to CurMBB instead.
420 ReplaceTailWithBranchTo(BBI2, CurMBB);
421 // This modifies MBB2, so remove it from the worklist.
422 MergePotentials.erase(MergePotentials.end()-2);
431 //===----------------------------------------------------------------------===//
432 // Branch Optimization
433 //===----------------------------------------------------------------------===//
435 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
438 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
439 MachineBasicBlock *MBB = I++;
442 // If it is dead, remove it.
443 if (MBB->pred_empty()) {
444 RemoveDeadBlock(MBB);
453 /// 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
457 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
458 MachineBasicBlock *DestA,
459 MachineBasicBlock *DestB,
461 MachineFunction::iterator FallThru) {
462 bool MadeChange = false;
463 bool AddedFallThrough = false;
465 // If this block ends with a conditional branch that falls through to its
466 // successor, set DestB as the successor.
468 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
470 AddedFallThrough = true;
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()) {
477 AddedFallThrough = true;
481 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
482 while (SI != MBB.succ_end()) {
486 } else if (*SI == DestB) {
490 // Otherwise, this is a superfluous edge, remove it.
491 MBB.removeSuccessor(SI);
495 if (!AddedFallThrough) {
496 assert(DestA == 0 && DestB == 0 &&
497 "MachineCFG is missing edges!");
499 assert(DestA == 0 && "MachineCFG is missing edges!");
505 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
506 /// 'Old', change the code and CFG so that it branches to 'New' instead.
507 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
508 MachineBasicBlock *Old,
509 MachineBasicBlock *New,
510 const TargetInstrInfo *TII) {
511 assert(Old != New && "Cannot replace self with self!");
513 MachineBasicBlock::iterator I = BB->end();
514 while (I != BB->begin()) {
516 if (!TII->isTerminatorInstr(I->getOpcode())) break;
518 // Scan the operands of this machine instruction, replacing any uses of Old
520 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
521 if (I->getOperand(i).isMachineBasicBlock() &&
522 I->getOperand(i).getMachineBasicBlock() == Old)
523 I->getOperand(i).setMachineBasicBlock(New);
526 // Update the successor information.
527 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
528 for (int i = Succs.size()-1; i >= 0; --i)
529 if (Succs[i] == Old) {
530 BB->removeSuccessor(Old);
531 BB->addSuccessor(New);
535 /// CanFallThrough - Return true if the specified block (with the specified
536 /// branch condition) can implicitly transfer control to the block after it by
537 /// falling off the end of it. This should return false if it can reach the
538 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
540 /// True is a conservative answer.
542 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
543 bool BranchUnAnalyzable,
544 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
545 const std::vector<MachineOperand> &Cond) {
546 MachineFunction::iterator Fallthrough = CurBB;
548 // If FallthroughBlock is off the end of the function, it can't fall through.
549 if (Fallthrough == CurBB->getParent()->end())
552 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
553 if (!CurBB->isSuccessor(Fallthrough))
556 // If we couldn't analyze the branch, assume it could fall through.
557 if (BranchUnAnalyzable) return true;
559 // If there is no branch, control always falls through.
560 if (TBB == 0) return true;
562 // If there is some explicit branch to the fallthrough block, it can obviously
563 // reach, even though the branch should get folded to fall through implicitly.
564 if (MachineFunction::iterator(TBB) == Fallthrough ||
565 MachineFunction::iterator(FBB) == Fallthrough)
568 // If it's an unconditional branch to some block not the fall through, it
569 // doesn't fall through.
570 if (Cond.empty()) return false;
572 // Otherwise, if it is conditional and has no explicit false block, it falls
577 /// CanFallThrough - Return true if the specified can implicitly transfer
578 /// control to the block after it by falling off the end of it. This should
579 /// return false if it can reach the block after it, but it uses an explicit
580 /// branch to do so (e.g. a table jump).
582 /// True is a conservative answer.
584 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
585 MachineBasicBlock *TBB = 0, *FBB = 0;
586 std::vector<MachineOperand> Cond;
587 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
588 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
591 /// IsBetterFallthrough - Return true if it would be clearly better to
592 /// fall-through to MBB1 than to fall through into MBB2. This has to return
593 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
594 /// result in infinite loops.
595 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
596 MachineBasicBlock *MBB2,
597 const TargetInstrInfo &TII) {
598 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
599 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
600 // optimize branches that branch to either a return block or an assert block
601 // into a fallthrough to the return.
602 if (MBB1->empty() || MBB2->empty()) return false;
604 MachineInstr *MBB1I = --MBB1->end();
605 MachineInstr *MBB2I = --MBB2->end();
606 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
609 /// OptimizeBlock - Analyze and optimize control flow related to the specified
610 /// block. This is never called on the entry block.
611 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
612 MachineFunction::iterator FallThrough = MBB;
615 // If this block is empty, make everyone use its fall-through, not the block
618 // Dead block? Leave for cleanup later.
619 if (MBB->pred_empty()) return;
621 if (FallThrough == MBB->getParent()->end()) {
622 // TODO: Simplify preds to not branch here if possible!
624 // Rewrite all predecessors of the old block to go to the fallthrough
626 while (!MBB->pred_empty()) {
627 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
628 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
631 // If MBB was the target of a jump table, update jump tables to go to the
632 // fallthrough instead.
633 MBB->getParent()->getJumpTableInfo()->
634 ReplaceMBBInJumpTables(MBB, FallThrough);
640 // Check to see if we can simplify the terminator of the block before this
642 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
644 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
645 std::vector<MachineOperand> PriorCond;
646 bool PriorUnAnalyzable =
647 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
648 if (!PriorUnAnalyzable) {
649 // If the CFG for the prior block has extra edges, remove them.
650 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
651 !PriorCond.empty(), MBB);
653 // If the previous branch is conditional and both conditions go to the same
654 // destination, remove the branch, replacing it with an unconditional one or
656 if (PriorTBB && PriorTBB == PriorFBB) {
657 TII->RemoveBranch(PrevBB);
660 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
663 return OptimizeBlock(MBB);
666 // If the previous branch *only* branches to *this* block (conditional or
667 // not) remove the branch.
668 if (PriorTBB == MBB && PriorFBB == 0) {
669 TII->RemoveBranch(PrevBB);
672 return OptimizeBlock(MBB);
675 // If the prior block branches somewhere else on the condition and here if
676 // the condition is false, remove the uncond second branch.
677 if (PriorFBB == MBB) {
678 TII->RemoveBranch(PrevBB);
679 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
682 return OptimizeBlock(MBB);
685 // If the prior block branches here on true and somewhere else on false, and
686 // if the branch condition is reversible, reverse the branch to create a
688 if (PriorTBB == MBB) {
689 std::vector<MachineOperand> NewPriorCond(PriorCond);
690 if (!TII->ReverseBranchCondition(NewPriorCond)) {
691 TII->RemoveBranch(PrevBB);
692 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
695 return OptimizeBlock(MBB);
699 // If this block doesn't fall through (e.g. it ends with an uncond branch or
700 // has no successors) and if the pred falls through into this block, and if
701 // it would otherwise fall through into the block after this, move this
702 // block to the end of the function.
704 // We consider it more likely that execution will stay in the function (e.g.
705 // due to loops) than it is to exit it. This asserts in loops etc, moving
706 // the assert condition out of the loop body.
707 if (!PriorCond.empty() && PriorFBB == 0 &&
708 MachineFunction::iterator(PriorTBB) == FallThrough &&
709 !CanFallThrough(MBB)) {
710 bool DoTransform = true;
712 // We have to be careful that the succs of PredBB aren't both no-successor
713 // blocks. If neither have successors and if PredBB is the second from
714 // last block in the function, we'd just keep swapping the two blocks for
715 // last. Only do the swap if one is clearly better to fall through than
717 if (FallThrough == --MBB->getParent()->end() &&
718 !IsBetterFallthrough(PriorTBB, MBB, *TII))
721 // We don't want to do this transformation if we have control flow like:
730 // In this case, we could actually be moving the return block *into* a
732 if (DoTransform && !MBB->succ_empty() &&
733 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
738 // Reverse the branch so we will fall through on the previous true cond.
739 std::vector<MachineOperand> NewPriorCond(PriorCond);
740 if (!TII->ReverseBranchCondition(NewPriorCond)) {
741 DOUT << "\nMoving MBB: " << *MBB;
742 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
744 TII->RemoveBranch(PrevBB);
745 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
747 // Move this block to the end of the function.
748 MBB->moveAfter(--MBB->getParent()->end());
757 // Analyze the branch in the current block.
758 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
759 std::vector<MachineOperand> CurCond;
760 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
761 if (!CurUnAnalyzable) {
762 // If the CFG for the prior block has extra edges, remove them.
763 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
765 ++MachineFunction::iterator(MBB));
767 // If this is a two-way branch, and the FBB branches to this block, reverse
768 // the condition so the single-basic-block loop is faster. Instead of:
769 // Loop: xxx; jcc Out; jmp Loop
771 // Loop: xxx; jncc Loop; jmp Out
772 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
773 std::vector<MachineOperand> NewCond(CurCond);
774 if (!TII->ReverseBranchCondition(NewCond)) {
775 TII->RemoveBranch(*MBB);
776 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
779 return OptimizeBlock(MBB);
784 // If this branch is the only thing in its block, see if we can forward
785 // other blocks across it.
786 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
787 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
788 // This block may contain just an unconditional branch. Because there can
789 // be 'non-branch terminators' in the block, try removing the branch and
790 // then seeing if the block is empty.
791 TII->RemoveBranch(*MBB);
793 // If this block is just an unconditional branch to CurTBB, we can
794 // usually completely eliminate the block. The only case we cannot
795 // completely eliminate the block is when the block before this one
796 // falls through into MBB and we can't understand the prior block's branch
799 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
800 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
801 !PrevBB.isSuccessor(MBB)) {
802 // If the prior block falls through into us, turn it into an
803 // explicit branch to us to make updates simpler.
804 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
805 PriorTBB != MBB && PriorFBB != MBB) {
807 assert(PriorCond.empty() && PriorFBB == 0 &&
808 "Bad branch analysis");
811 assert(PriorFBB == 0 && "Machine CFG out of date!");
814 TII->RemoveBranch(PrevBB);
815 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
818 // Iterate through all the predecessors, revectoring each in-turn.
819 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
820 bool DidChange = false;
821 bool HasBranchToSelf = false;
822 while (PI != MBB->pred_end()) {
824 // If this block has an uncond branch to itself, leave it.
826 HasBranchToSelf = true;
829 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
833 // Change any jumptables to go to the new MBB.
834 MBB->getParent()->getJumpTableInfo()->
835 ReplaceMBBInJumpTables(MBB, CurTBB);
839 if (!HasBranchToSelf) return;
844 // Add the branch back if the block is more than just an uncond branch.
845 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
849 // If the prior block doesn't fall through into this block, and if this
850 // block doesn't fall through into some other block, see if we can find a
851 // place to move this block where a fall-through will happen.
852 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
853 PriorTBB, PriorFBB, PriorCond)) {
854 // Now we know that there was no fall-through into this block, check to
855 // see if it has a fall-through into its successor.
856 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
857 // Check all the predecessors of this block. If one of them has no fall
858 // throughs, move this block right after it.
859 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
860 E = MBB->pred_end(); PI != E; ++PI) {
861 // Analyze the branch at the end of the pred.
862 MachineBasicBlock *PredBB = *PI;
863 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
864 std::vector<MachineOperand> PredCond;
865 if (PredBB != MBB && !CanFallThrough(PredBB)) {
866 MBB->moveAfter(PredBB);
868 return OptimizeBlock(MBB);
872 // Check all successors to see if we can move this block before it.
873 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
874 E = MBB->succ_end(); SI != E; ++SI) {
875 // Analyze the branch at the end of the block before the succ.
876 MachineBasicBlock *SuccBB = *SI;
877 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
878 std::vector<MachineOperand> SuccPrevCond;
879 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
880 MBB->moveBefore(SuccBB);
882 return OptimizeBlock(MBB);
886 // Okay, there is no really great place to put this block. If, however,
887 // the block before this one would be a fall-through if this block were
888 // removed, move this block to the end of the function.
889 if (FallThrough != MBB->getParent()->end() &&
890 PrevBB.isSuccessor(FallThrough)) {
891 MBB->moveAfter(--MBB->getParent()->end());