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/MachineModuleInfo.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 MachineModuleInfo *MMI;
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 MachineModuleInfo.
79 if (MMI && !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 MMI->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 MMI = getAnalysisToUpdate<MachineModuleInfo>();
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 // Make sure blocks are numbered in order
437 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
438 MachineBasicBlock *MBB = I++;
441 // If it is dead, remove it.
442 if (MBB->pred_empty()) {
443 RemoveDeadBlock(MBB);
452 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
453 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
454 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
456 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
457 MachineBasicBlock *DestA,
458 MachineBasicBlock *DestB,
460 MachineFunction::iterator FallThru) {
461 bool MadeChange = false;
462 bool AddedFallThrough = false;
464 // If this block ends with a conditional branch that falls through to its
465 // successor, set DestB as the successor.
467 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
469 AddedFallThrough = true;
472 // If this is an unconditional branch with no explicit dest, it must just be
473 // a fallthrough into DestB.
474 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
476 AddedFallThrough = true;
480 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
481 while (SI != MBB.succ_end()) {
485 } else if (*SI == DestB) {
489 // Otherwise, this is a superfluous edge, remove it.
490 MBB.removeSuccessor(SI);
494 if (!AddedFallThrough) {
495 assert(DestA == 0 && DestB == 0 &&
496 "MachineCFG is missing edges!");
498 assert(DestA == 0 && "MachineCFG is missing edges!");
504 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
505 /// 'Old', change the code and CFG so that it branches to 'New' instead.
506 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
507 MachineBasicBlock *Old,
508 MachineBasicBlock *New,
509 const TargetInstrInfo *TII) {
510 assert(Old != New && "Cannot replace self with self!");
512 MachineBasicBlock::iterator I = BB->end();
513 while (I != BB->begin()) {
515 if (!TII->isTerminatorInstr(I->getOpcode())) break;
517 // Scan the operands of this machine instruction, replacing any uses of Old
519 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
520 if (I->getOperand(i).isMachineBasicBlock() &&
521 I->getOperand(i).getMachineBasicBlock() == Old)
522 I->getOperand(i).setMachineBasicBlock(New);
525 // Update the successor information.
526 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
527 for (int i = Succs.size()-1; i >= 0; --i)
528 if (Succs[i] == Old) {
529 BB->removeSuccessor(Old);
530 BB->addSuccessor(New);
534 /// CanFallThrough - Return true if the specified block (with the specified
535 /// branch condition) can implicitly transfer control to the block after it by
536 /// falling off the end of it. This should return false if it can reach the
537 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
539 /// True is a conservative answer.
541 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
542 bool BranchUnAnalyzable,
543 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
544 const std::vector<MachineOperand> &Cond) {
545 MachineFunction::iterator Fallthrough = CurBB;
547 // If FallthroughBlock is off the end of the function, it can't fall through.
548 if (Fallthrough == CurBB->getParent()->end())
551 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
552 if (!CurBB->isSuccessor(Fallthrough))
555 // If we couldn't analyze the branch, assume it could fall through.
556 if (BranchUnAnalyzable) return true;
558 // If there is no branch, control always falls through.
559 if (TBB == 0) return true;
561 // If there is some explicit branch to the fallthrough block, it can obviously
562 // reach, even though the branch should get folded to fall through implicitly.
563 if (MachineFunction::iterator(TBB) == Fallthrough ||
564 MachineFunction::iterator(FBB) == Fallthrough)
567 // If it's an unconditional branch to some block not the fall through, it
568 // doesn't fall through.
569 if (Cond.empty()) return false;
571 // Otherwise, if it is conditional and has no explicit false block, it falls
576 /// CanFallThrough - Return true if the specified can implicitly transfer
577 /// control to the block after it by falling off the end of it. This should
578 /// return false if it can reach the block after it, but it uses an explicit
579 /// branch to do so (e.g. a table jump).
581 /// True is a conservative answer.
583 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
584 MachineBasicBlock *TBB = 0, *FBB = 0;
585 std::vector<MachineOperand> Cond;
586 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
587 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
590 /// IsBetterFallthrough - Return true if it would be clearly better to
591 /// fall-through to MBB1 than to fall through into MBB2. This has to return
592 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
593 /// result in infinite loops.
594 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
595 MachineBasicBlock *MBB2,
596 const TargetInstrInfo &TII) {
597 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
598 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
599 // optimize branches that branch to either a return block or an assert block
600 // into a fallthrough to the return.
601 if (MBB1->empty() || MBB2->empty()) return false;
603 MachineInstr *MBB1I = --MBB1->end();
604 MachineInstr *MBB2I = --MBB2->end();
605 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
608 /// OptimizeBlock - Analyze and optimize control flow related to the specified
609 /// block. This is never called on the entry block.
610 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
611 MachineFunction::iterator FallThrough = MBB;
614 // If this block is empty, make everyone use its fall-through, not the block
617 // Dead block? Leave for cleanup later.
618 if (MBB->pred_empty()) return;
620 if (FallThrough == MBB->getParent()->end()) {
621 // TODO: Simplify preds to not branch here if possible!
623 // Rewrite all predecessors of the old block to go to the fallthrough
625 while (!MBB->pred_empty()) {
626 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
627 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
630 // If MBB was the target of a jump table, update jump tables to go to the
631 // fallthrough instead.
632 MBB->getParent()->getJumpTableInfo()->
633 ReplaceMBBInJumpTables(MBB, FallThrough);
639 // Check to see if we can simplify the terminator of the block before this
641 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
643 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
644 std::vector<MachineOperand> PriorCond;
645 bool PriorUnAnalyzable =
646 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
647 if (!PriorUnAnalyzable) {
648 // If the CFG for the prior block has extra edges, remove them.
649 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
650 !PriorCond.empty(), MBB);
652 // If the previous branch is conditional and both conditions go to the same
653 // destination, remove the branch, replacing it with an unconditional one or
655 if (PriorTBB && PriorTBB == PriorFBB) {
656 TII->RemoveBranch(PrevBB);
659 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
662 return OptimizeBlock(MBB);
665 // If the previous branch *only* branches to *this* block (conditional or
666 // not) remove the branch.
667 if (PriorTBB == MBB && PriorFBB == 0) {
668 TII->RemoveBranch(PrevBB);
671 return OptimizeBlock(MBB);
674 // If the prior block branches somewhere else on the condition and here if
675 // the condition is false, remove the uncond second branch.
676 if (PriorFBB == MBB) {
677 TII->RemoveBranch(PrevBB);
678 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
681 return OptimizeBlock(MBB);
684 // If the prior block branches here on true and somewhere else on false, and
685 // if the branch condition is reversible, reverse the branch to create a
687 if (PriorTBB == MBB) {
688 std::vector<MachineOperand> NewPriorCond(PriorCond);
689 if (!TII->ReverseBranchCondition(NewPriorCond)) {
690 TII->RemoveBranch(PrevBB);
691 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
694 return OptimizeBlock(MBB);
698 // If this block doesn't fall through (e.g. it ends with an uncond branch or
699 // has no successors) and if the pred falls through into this block, and if
700 // it would otherwise fall through into the block after this, move this
701 // block to the end of the function.
703 // We consider it more likely that execution will stay in the function (e.g.
704 // due to loops) than it is to exit it. This asserts in loops etc, moving
705 // the assert condition out of the loop body.
706 if (!PriorCond.empty() && PriorFBB == 0 &&
707 MachineFunction::iterator(PriorTBB) == FallThrough &&
708 !CanFallThrough(MBB)) {
709 bool DoTransform = true;
711 // We have to be careful that the succs of PredBB aren't both no-successor
712 // blocks. If neither have successors and if PredBB is the second from
713 // last block in the function, we'd just keep swapping the two blocks for
714 // last. Only do the swap if one is clearly better to fall through than
716 if (FallThrough == --MBB->getParent()->end() &&
717 !IsBetterFallthrough(PriorTBB, MBB, *TII))
720 // We don't want to do this transformation if we have control flow like:
729 // In this case, we could actually be moving the return block *into* a
731 if (DoTransform && !MBB->succ_empty() &&
732 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
737 // Reverse the branch so we will fall through on the previous true cond.
738 std::vector<MachineOperand> NewPriorCond(PriorCond);
739 if (!TII->ReverseBranchCondition(NewPriorCond)) {
740 DOUT << "\nMoving MBB: " << *MBB;
741 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
743 TII->RemoveBranch(PrevBB);
744 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
746 // Move this block to the end of the function.
747 MBB->moveAfter(--MBB->getParent()->end());
756 // Analyze the branch in the current block.
757 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
758 std::vector<MachineOperand> CurCond;
759 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
760 if (!CurUnAnalyzable) {
761 // If the CFG for the prior block has extra edges, remove them.
762 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
764 ++MachineFunction::iterator(MBB));
766 // If this is a two-way branch, and the FBB branches to this block, reverse
767 // the condition so the single-basic-block loop is faster. Instead of:
768 // Loop: xxx; jcc Out; jmp Loop
770 // Loop: xxx; jncc Loop; jmp Out
771 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
772 std::vector<MachineOperand> NewCond(CurCond);
773 if (!TII->ReverseBranchCondition(NewCond)) {
774 TII->RemoveBranch(*MBB);
775 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
778 return OptimizeBlock(MBB);
783 // If this branch is the only thing in its block, see if we can forward
784 // other blocks across it.
785 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
786 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
787 // This block may contain just an unconditional branch. Because there can
788 // be 'non-branch terminators' in the block, try removing the branch and
789 // then seeing if the block is empty.
790 TII->RemoveBranch(*MBB);
792 // If this block is just an unconditional branch to CurTBB, we can
793 // usually completely eliminate the block. The only case we cannot
794 // completely eliminate the block is when the block before this one
795 // falls through into MBB and we can't understand the prior block's branch
798 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
799 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
800 !PrevBB.isSuccessor(MBB)) {
801 // If the prior block falls through into us, turn it into an
802 // explicit branch to us to make updates simpler.
803 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
804 PriorTBB != MBB && PriorFBB != MBB) {
806 assert(PriorCond.empty() && PriorFBB == 0 &&
807 "Bad branch analysis");
810 assert(PriorFBB == 0 && "Machine CFG out of date!");
813 TII->RemoveBranch(PrevBB);
814 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
817 // Iterate through all the predecessors, revectoring each in-turn.
818 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
819 bool DidChange = false;
820 bool HasBranchToSelf = false;
821 while (PI != MBB->pred_end()) {
823 // If this block has an uncond branch to itself, leave it.
825 HasBranchToSelf = true;
828 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
832 // Change any jumptables to go to the new MBB.
833 MBB->getParent()->getJumpTableInfo()->
834 ReplaceMBBInJumpTables(MBB, CurTBB);
838 if (!HasBranchToSelf) return;
843 // Add the branch back if the block is more than just an uncond branch.
844 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
848 // If the prior block doesn't fall through into this block, and if this
849 // block doesn't fall through into some other block, see if we can find a
850 // place to move this block where a fall-through will happen.
851 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
852 PriorTBB, PriorFBB, PriorCond)) {
853 // Now we know that there was no fall-through into this block, check to
854 // see if it has a fall-through into its successor.
855 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
858 // Check all the predecessors of this block. If one of them has no fall
859 // throughs, move this block right after it.
860 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
861 E = MBB->pred_end(); PI != E; ++PI) {
862 // Analyze the branch at the end of the pred.
863 MachineBasicBlock *PredBB = *PI;
864 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
865 if (PredBB != MBB && !CanFallThrough(PredBB)
866 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
867 // If the current block doesn't fall through, just move it.
868 // If the current block can fall through and does not end with a
869 // conditional branch, we need to append an unconditional jump to
870 // the (current) next block. To avoid a possible compile-time
871 // infinite loop, move blocks only backward in this case.
873 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
875 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
877 MBB->moveAfter(PredBB);
879 return OptimizeBlock(MBB);
884 // Check all successors to see if we can move this block before it.
885 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
886 E = MBB->succ_end(); SI != E; ++SI) {
887 // Analyze the branch at the end of the block before the succ.
888 MachineBasicBlock *SuccBB = *SI;
889 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
890 std::vector<MachineOperand> SuccPrevCond;
891 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
892 MBB->moveBefore(SuccBB);
894 return OptimizeBlock(MBB);
898 // Okay, there is no really great place to put this block. If, however,
899 // the block before this one would be a fall-through if this block were
900 // removed, move this block to the end of the function.
901 if (FallThrough != MBB->getParent()->end() &&
902 PrevBB.isSuccessor(FallThrough)) {
903 MBB->moveAfter(--MBB->getParent()->end());