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 LABEL
78 // records in the basic block. If so, unregister them from MachineDebugInfo.
79 if (MDI && !MBB->empty()) {
80 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
82 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
83 // The label ID # is always operand #0, an immediate.
84 MDI->InvalidateLabel(I->getOperand(0).getImm());
90 MF->getBasicBlockList().erase(MBB);
93 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
94 TII = MF.getTarget().getInstrInfo();
95 if (!TII) return false;
97 MDI = getAnalysisToUpdate<MachineDebugInfo>();
99 bool EverMadeChange = false;
100 bool MadeChangeThisIteration = true;
101 while (MadeChangeThisIteration) {
102 MadeChangeThisIteration = false;
103 MadeChangeThisIteration |= TailMergeBlocks(MF);
104 MadeChangeThisIteration |= OptimizeBranches(MF);
105 EverMadeChange |= MadeChangeThisIteration;
108 // See if any jump tables have become mergable or dead as the code generator
110 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
111 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
113 // Figure out how these jump tables should be merged.
114 std::vector<unsigned> JTMapping;
115 JTMapping.reserve(JTs.size());
117 // We always keep the 0th jump table.
118 JTMapping.push_back(0);
120 // Scan the jump tables, seeing if there are any duplicates. Note that this
121 // is N^2, which should be fixed someday.
122 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
123 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
125 // If a jump table was merge with another one, walk the function rewriting
126 // references to jump tables to reference the new JT ID's. Keep track of
127 // whether we see a jump table idx, if not, we can delete the JT.
128 std::vector<bool> JTIsLive;
129 JTIsLive.resize(JTs.size());
130 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
132 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
134 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
135 MachineOperand &Op = I->getOperand(op);
136 if (!Op.isJumpTableIndex()) continue;
137 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
138 Op.setJumpTableIndex(NewIdx);
140 // Remember that this JT is live.
141 JTIsLive[NewIdx] = true;
145 // Finally, remove dead jump tables. This happens either because the
146 // indirect jump was unreachable (and thus deleted) or because the jump
147 // table was merged with some other one.
148 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
150 JTI->RemoveJumpTable(i);
151 EverMadeChange = true;
155 return EverMadeChange;
158 //===----------------------------------------------------------------------===//
159 // Tail Merging of Blocks
160 //===----------------------------------------------------------------------===//
162 /// HashMachineInstr - Compute a hash value for MI and its operands.
163 static unsigned HashMachineInstr(const MachineInstr *MI) {
164 unsigned Hash = MI->getOpcode();
165 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
166 const MachineOperand &Op = MI->getOperand(i);
168 // Merge in bits from the operand if easy.
169 unsigned OperandHash = 0;
170 switch (Op.getType()) {
171 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
172 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
173 case MachineOperand::MO_MachineBasicBlock:
174 OperandHash = Op.getMachineBasicBlock()->getNumber();
176 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
177 case MachineOperand::MO_ConstantPoolIndex:
178 OperandHash = Op.getConstantPoolIndex();
180 case MachineOperand::MO_JumpTableIndex:
181 OperandHash = Op.getJumpTableIndex();
183 case MachineOperand::MO_GlobalAddress:
184 case MachineOperand::MO_ExternalSymbol:
185 // Global address / external symbol are too hard, don't bother, but do
186 // pull in the offset.
187 OperandHash = Op.getOffset();
192 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
197 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
198 /// instructions, because cross-jumping only saves code when at least two
199 /// instructions are removed (since a branch must be inserted).
200 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
201 MachineBasicBlock::const_iterator I = MBB->end();
202 if (I == MBB->begin())
203 return 0; // Empty MBB.
206 unsigned Hash = HashMachineInstr(I);
208 if (I == MBB->begin())
209 return Hash; // Single instr MBB.
212 // Hash in the second-to-last instruction.
213 Hash ^= HashMachineInstr(I) << 2;
217 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
218 /// of instructions they actually have in common together at their end. Return
219 /// iterators for the first shared instruction in each block.
220 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
221 MachineBasicBlock *MBB2,
222 MachineBasicBlock::iterator &I1,
223 MachineBasicBlock::iterator &I2) {
227 unsigned TailLen = 0;
228 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
230 if (!I1->isIdenticalTo(I2)) {
239 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
240 /// after it, replacing it with an unconditional branch to NewDest. This
241 /// returns true if OldInst's block is modified, false if NewDest is modified.
242 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
243 MachineBasicBlock *NewDest) {
244 MachineBasicBlock *OldBB = OldInst->getParent();
246 // Remove all the old successors of OldBB from the CFG.
247 while (!OldBB->succ_empty())
248 OldBB->removeSuccessor(OldBB->succ_begin());
250 // Remove all the dead instructions from the end of OldBB.
251 OldBB->erase(OldInst, OldBB->end());
253 // If OldBB isn't immediately before OldBB, insert a branch to it.
254 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
255 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
256 OldBB->addSuccessor(NewDest);
260 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
261 /// MBB so that the part before the iterator falls into the part starting at the
262 /// iterator. This returns the new MBB.
263 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
264 MachineBasicBlock::iterator BBI1) {
265 // Create the fall-through block.
266 MachineFunction::iterator MBBI = &CurMBB;
267 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
268 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
270 // Move all the successors of this block to the specified block.
271 while (!CurMBB.succ_empty()) {
272 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
273 NewMBB->addSuccessor(S);
274 CurMBB.removeSuccessor(S);
277 // Add an edge from CurMBB to NewMBB for the fall-through.
278 CurMBB.addSuccessor(NewMBB);
280 // Splice the code over.
281 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
285 /// EstimateRuntime - Make a rough estimate for how long it will take to run
286 /// the specified code.
287 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
288 MachineBasicBlock::iterator E,
289 const TargetInstrInfo *TII) {
291 for (; I != E; ++I) {
292 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
293 if (TID.Flags & M_CALL_FLAG)
295 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
303 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
304 /// MBB2I and then insert an unconditional branch in the other block. Determine
305 /// which is the best to split
306 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
307 MachineBasicBlock::iterator MBB1I,
308 MachineBasicBlock *MBB2,
309 MachineBasicBlock::iterator MBB2I,
310 const TargetInstrInfo *TII) {
311 // TODO: if we had some notion of which block was hotter, we could split
312 // the hot block, so it is the fall-through. Since we don't have profile info
313 // make a decision based on which will hurt most to split.
314 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
315 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
317 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
318 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
319 // have a lower overall impact on the program execution.
320 return MBB1Time < MBB2Time;
323 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
326 if (!EnableTailMerge) return false;
328 // Find blocks with no successors.
329 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
330 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
332 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
335 // Sort by hash value so that blocks with identical end sequences sort
337 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
339 // Walk through equivalence sets looking for actual exact matches.
340 while (MergePotentials.size() > 1) {
341 unsigned CurHash = (MergePotentials.end()-1)->first;
342 unsigned PrevHash = (MergePotentials.end()-2)->first;
343 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
345 // If there is nothing that matches the hash of the current basic block,
347 if (CurHash != PrevHash) {
348 MergePotentials.pop_back();
352 // Determine the actual length of the shared tail between these two basic
353 // blocks. Because the hash can have collisions, it's possible that this is
355 MachineBasicBlock::iterator BBI1, BBI2;
356 unsigned CommonTailLen =
357 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
360 // If the tails don't have at least two instructions in common, see if there
361 // is anything else in the equivalence class that does match.
362 if (CommonTailLen < 2) {
363 unsigned FoundMatch = ~0U;
364 for (int i = MergePotentials.size()-2;
365 i != -1 && MergePotentials[i].first == CurHash; --i) {
366 CommonTailLen = ComputeCommonTailLength(CurMBB,
367 MergePotentials[i].second,
369 if (CommonTailLen >= 2) {
375 // If we didn't find anything that has at least two instructions matching
376 // this one, bail out.
377 if (FoundMatch == ~0U) {
378 MergePotentials.pop_back();
382 // Otherwise, move the matching block to the right position.
383 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
386 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
388 // If neither block is the entire common tail, split the tail of one block
389 // to make it redundant with the other tail.
390 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
391 if (0) { // Enable this to disable partial tail merges.
392 MergePotentials.pop_back();
396 // Decide whether we want to split CurMBB or MBB2.
397 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
398 CurMBB = SplitMBBAt(*CurMBB, BBI1);
399 BBI1 = CurMBB->begin();
400 MergePotentials.back().second = CurMBB;
402 MBB2 = SplitMBBAt(*MBB2, BBI2);
403 BBI2 = MBB2->begin();
404 (MergePotentials.end()-2)->second = MBB2;
408 if (MBB2->begin() == BBI2) {
409 // Hack the end off CurMBB, making it jump to MBBI@ instead.
410 ReplaceTailWithBranchTo(BBI1, MBB2);
411 // This modifies CurMBB, so remove it from the worklist.
412 MergePotentials.pop_back();
414 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
415 // Hack the end off MBB2, making it jump to CurMBB instead.
416 ReplaceTailWithBranchTo(BBI2, CurMBB);
417 // This modifies MBB2, so remove it from the worklist.
418 MergePotentials.erase(MergePotentials.end()-2);
427 //===----------------------------------------------------------------------===//
428 // Branch Optimization
429 //===----------------------------------------------------------------------===//
431 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
434 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
435 MachineBasicBlock *MBB = I++;
438 // If it is dead, remove it.
439 if (MBB->pred_empty()) {
440 RemoveDeadBlock(MBB);
449 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
450 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
451 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
453 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
454 MachineBasicBlock *DestA,
455 MachineBasicBlock *DestB,
457 MachineFunction::iterator FallThru) {
458 bool MadeChange = false;
459 bool AddedFallThrough = false;
461 // If this block ends with a conditional branch that falls through to its
462 // successor, set DestB as the successor.
464 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
466 AddedFallThrough = true;
469 // If this is an unconditional branch with no explicit dest, it must just be
470 // a fallthrough into DestB.
471 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
473 AddedFallThrough = true;
477 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
478 while (SI != MBB.succ_end()) {
482 } else if (*SI == DestB) {
486 // Otherwise, this is a superfluous edge, remove it.
487 MBB.removeSuccessor(SI);
491 if (!AddedFallThrough) {
492 assert(DestA == 0 && DestB == 0 &&
493 "MachineCFG is missing edges!");
495 assert(DestA == 0 && "MachineCFG is missing edges!");
501 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
502 /// 'Old', change the code and CFG so that it branches to 'New' instead.
503 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
504 MachineBasicBlock *Old,
505 MachineBasicBlock *New,
506 const TargetInstrInfo *TII) {
507 assert(Old != New && "Cannot replace self with self!");
509 MachineBasicBlock::iterator I = BB->end();
510 while (I != BB->begin()) {
512 if (!TII->isTerminatorInstr(I->getOpcode())) break;
514 // Scan the operands of this machine instruction, replacing any uses of Old
516 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
517 if (I->getOperand(i).isMachineBasicBlock() &&
518 I->getOperand(i).getMachineBasicBlock() == Old)
519 I->getOperand(i).setMachineBasicBlock(New);
522 // Update the successor information.
523 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
524 for (int i = Succs.size()-1; i >= 0; --i)
525 if (Succs[i] == Old) {
526 BB->removeSuccessor(Old);
527 BB->addSuccessor(New);
531 /// CanFallThrough - Return true if the specified block (with the specified
532 /// branch condition) can implicitly transfer control to the block after it by
533 /// falling off the end of it. This should return false if it can reach the
534 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
536 /// True is a conservative answer.
538 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
539 bool BranchUnAnalyzable,
540 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
541 const std::vector<MachineOperand> &Cond) {
542 MachineFunction::iterator Fallthrough = CurBB;
544 // If FallthroughBlock is off the end of the function, it can't fall through.
545 if (Fallthrough == CurBB->getParent()->end())
548 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
549 if (!CurBB->isSuccessor(Fallthrough))
552 // If we couldn't analyze the branch, assume it could fall through.
553 if (BranchUnAnalyzable) return true;
555 // If there is no branch, control always falls through.
556 if (TBB == 0) return true;
558 // If there is some explicit branch to the fallthrough block, it can obviously
559 // reach, even though the branch should get folded to fall through implicitly.
560 if (MachineFunction::iterator(TBB) == Fallthrough ||
561 MachineFunction::iterator(FBB) == Fallthrough)
564 // If it's an unconditional branch to some block not the fall through, it
565 // doesn't fall through.
566 if (Cond.empty()) return false;
568 // Otherwise, if it is conditional and has no explicit false block, it falls
573 /// CanFallThrough - Return true if the specified can implicitly transfer
574 /// control to the block after it by falling off the end of it. This should
575 /// return false if it can reach the block after it, but it uses an explicit
576 /// branch to do so (e.g. a table jump).
578 /// True is a conservative answer.
580 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
581 MachineBasicBlock *TBB = 0, *FBB = 0;
582 std::vector<MachineOperand> Cond;
583 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
584 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
587 /// IsBetterFallthrough - Return true if it would be clearly better to
588 /// fall-through to MBB1 than to fall through into MBB2. This has to return
589 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
590 /// result in infinite loops.
591 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
592 MachineBasicBlock *MBB2,
593 const TargetInstrInfo &TII) {
594 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
595 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
596 // optimize branches that branch to either a return block or an assert block
597 // into a fallthrough to the return.
598 if (MBB1->empty() || MBB2->empty()) return false;
600 MachineInstr *MBB1I = --MBB1->end();
601 MachineInstr *MBB2I = --MBB2->end();
602 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
605 /// OptimizeBlock - Analyze and optimize control flow related to the specified
606 /// block. This is never called on the entry block.
607 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
608 MachineFunction::iterator FallThrough = MBB;
611 // If this block is empty, make everyone use its fall-through, not the block
614 // Dead block? Leave for cleanup later.
615 if (MBB->pred_empty()) return;
617 if (FallThrough == MBB->getParent()->end()) {
618 // TODO: Simplify preds to not branch here if possible!
620 // Rewrite all predecessors of the old block to go to the fallthrough
622 while (!MBB->pred_empty()) {
623 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
624 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
627 // If MBB was the target of a jump table, update jump tables to go to the
628 // fallthrough instead.
629 MBB->getParent()->getJumpTableInfo()->
630 ReplaceMBBInJumpTables(MBB, FallThrough);
636 // Check to see if we can simplify the terminator of the block before this
638 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
640 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
641 std::vector<MachineOperand> PriorCond;
642 bool PriorUnAnalyzable =
643 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
644 if (!PriorUnAnalyzable) {
645 // If the CFG for the prior block has extra edges, remove them.
646 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
647 !PriorCond.empty(), MBB);
649 // If the previous branch is conditional and both conditions go to the same
650 // destination, remove the branch, replacing it with an unconditional one or
652 if (PriorTBB && PriorTBB == PriorFBB) {
653 TII->RemoveBranch(PrevBB);
656 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
659 return OptimizeBlock(MBB);
662 // If the previous branch *only* branches to *this* block (conditional or
663 // not) remove the branch.
664 if (PriorTBB == MBB && PriorFBB == 0) {
665 TII->RemoveBranch(PrevBB);
668 return OptimizeBlock(MBB);
671 // If the prior block branches somewhere else on the condition and here if
672 // the condition is false, remove the uncond second branch.
673 if (PriorFBB == MBB) {
674 TII->RemoveBranch(PrevBB);
675 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
678 return OptimizeBlock(MBB);
681 // If the prior block branches here on true and somewhere else on false, and
682 // if the branch condition is reversible, reverse the branch to create a
684 if (PriorTBB == MBB) {
685 std::vector<MachineOperand> NewPriorCond(PriorCond);
686 if (!TII->ReverseBranchCondition(NewPriorCond)) {
687 TII->RemoveBranch(PrevBB);
688 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
691 return OptimizeBlock(MBB);
695 // If this block doesn't fall through (e.g. it ends with an uncond branch or
696 // has no successors) and if the pred falls through into this block, and if
697 // it would otherwise fall through into the block after this, move this
698 // block to the end of the function.
700 // We consider it more likely that execution will stay in the function (e.g.
701 // due to loops) than it is to exit it. This asserts in loops etc, moving
702 // the assert condition out of the loop body.
703 if (!PriorCond.empty() && PriorFBB == 0 &&
704 MachineFunction::iterator(PriorTBB) == FallThrough &&
705 !CanFallThrough(MBB)) {
706 bool DoTransform = true;
708 // We have to be careful that the succs of PredBB aren't both no-successor
709 // blocks. If neither have successors and if PredBB is the second from
710 // last block in the function, we'd just keep swapping the two blocks for
711 // last. Only do the swap if one is clearly better to fall through than
713 if (FallThrough == --MBB->getParent()->end() &&
714 !IsBetterFallthrough(PriorTBB, MBB, *TII))
717 // We don't want to do this transformation if we have control flow like:
726 // In this case, we could actually be moving the return block *into* a
728 if (DoTransform && !MBB->succ_empty() &&
729 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
734 // Reverse the branch so we will fall through on the previous true cond.
735 std::vector<MachineOperand> NewPriorCond(PriorCond);
736 if (!TII->ReverseBranchCondition(NewPriorCond)) {
737 DOUT << "\nMoving MBB: " << *MBB;
738 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
740 TII->RemoveBranch(PrevBB);
741 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
743 // Move this block to the end of the function.
744 MBB->moveAfter(--MBB->getParent()->end());
753 // Analyze the branch in the current block.
754 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
755 std::vector<MachineOperand> CurCond;
756 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
757 if (!CurUnAnalyzable) {
758 // If the CFG for the prior block has extra edges, remove them.
759 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
761 ++MachineFunction::iterator(MBB));
763 // If this is a two-way branch, and the FBB branches to this block, reverse
764 // the condition so the single-basic-block loop is faster. Instead of:
765 // Loop: xxx; jcc Out; jmp Loop
767 // Loop: xxx; jncc Loop; jmp Out
768 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
769 std::vector<MachineOperand> NewCond(CurCond);
770 if (!TII->ReverseBranchCondition(NewCond)) {
771 TII->RemoveBranch(*MBB);
772 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
775 return OptimizeBlock(MBB);
780 // If this branch is the only thing in its block, see if we can forward
781 // other blocks across it.
782 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
783 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
784 // This block may contain just an unconditional branch. Because there can
785 // be 'non-branch terminators' in the block, try removing the branch and
786 // then seeing if the block is empty.
787 TII->RemoveBranch(*MBB);
789 // If this block is just an unconditional branch to CurTBB, we can
790 // usually completely eliminate the block. The only case we cannot
791 // completely eliminate the block is when the block before this one
792 // falls through into MBB and we can't understand the prior block's branch
795 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
796 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
797 !PrevBB.isSuccessor(MBB)) {
798 // If the prior block falls through into us, turn it into an
799 // explicit branch to us to make updates simpler.
800 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
801 PriorTBB != MBB && PriorFBB != MBB) {
803 assert(PriorCond.empty() && PriorFBB == 0 &&
804 "Bad branch analysis");
807 assert(PriorFBB == 0 && "Machine CFG out of date!");
810 TII->RemoveBranch(PrevBB);
811 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
814 // Iterate through all the predecessors, revectoring each in-turn.
815 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
816 bool DidChange = false;
817 bool HasBranchToSelf = false;
818 while (PI != MBB->pred_end()) {
820 // If this block has an uncond branch to itself, leave it.
822 HasBranchToSelf = true;
825 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
829 // Change any jumptables to go to the new MBB.
830 MBB->getParent()->getJumpTableInfo()->
831 ReplaceMBBInJumpTables(MBB, CurTBB);
835 if (!HasBranchToSelf) return;
840 // Add the branch back if the block is more than just an uncond branch.
841 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
845 // If the prior block doesn't fall through into this block, and if this
846 // block doesn't fall through into some other block, see if we can find a
847 // place to move this block where a fall-through will happen.
848 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
849 PriorTBB, PriorFBB, PriorCond)) {
850 // Now we know that there was no fall-through into this block, check to
851 // see if it has a fall-through into its successor.
852 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
853 // Check all the predecessors of this block. If one of them has no fall
854 // throughs, move this block right after it.
855 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
856 E = MBB->pred_end(); PI != E; ++PI) {
857 // Analyze the branch at the end of the pred.
858 MachineBasicBlock *PredBB = *PI;
859 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
860 std::vector<MachineOperand> PredCond;
861 if (PredBB != MBB && !CanFallThrough(PredBB)) {
862 MBB->moveAfter(PredBB);
864 return OptimizeBlock(MBB);
868 // Check all successors to see if we can move this block before it.
869 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
870 E = MBB->succ_end(); SI != E; ++SI) {
871 // Analyze the branch at the end of the block before the succ.
872 MachineBasicBlock *SuccBB = *SI;
873 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
874 std::vector<MachineOperand> SuccPrevCond;
875 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
876 MBB->moveBefore(SuccBB);
878 return OptimizeBlock(MBB);
882 // Okay, there is no really great place to put this block. If, however,
883 // the block before this one would be a fall-through if this block were
884 // removed, move this block to the end of the function.
885 if (FallThrough != MBB->getParent()->end() &&
886 PrevBB.isSuccessor(FallThrough)) {
887 MBB->moveAfter(--MBB->getParent()->end());