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/CodeGen/RegisterScavenging.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
35 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36 STATISTIC(NumBranchOpts, "Number of branches optimized");
37 STATISTIC(NumTailMerge , "Number of block tails merged");
38 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
41 struct BranchFolder : public MachineFunctionPass {
42 virtual bool runOnMachineFunction(MachineFunction &MF);
43 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
44 const TargetInstrInfo *TII;
45 MachineModuleInfo *MMI;
49 bool TailMergeBlocks(MachineFunction &MF);
50 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
51 MachineBasicBlock *NewDest);
52 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
53 MachineBasicBlock::iterator BBI1);
55 const MRegisterInfo *RegInfo;
58 bool OptimizeBranches(MachineFunction &MF);
59 void OptimizeBlock(MachineBasicBlock *MBB);
60 void RemoveDeadBlock(MachineBasicBlock *MBB);
62 bool CanFallThrough(MachineBasicBlock *CurBB);
63 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
64 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
65 const std::vector<MachineOperand> &Cond);
69 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
71 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
72 /// function, updating the CFG.
73 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
74 assert(MBB->pred_empty() && "MBB must be dead!");
75 DOUT << "\nRemoving MBB: " << *MBB;
77 MachineFunction *MF = MBB->getParent();
78 // drop all successors.
79 while (!MBB->succ_empty())
80 MBB->removeSuccessor(MBB->succ_end()-1);
82 // If there is DWARF info to active, check to see if there are any LABEL
83 // records in the basic block. If so, unregister them from MachineModuleInfo.
84 if (MMI && !MBB->empty()) {
85 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
87 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
88 // The label ID # is always operand #0, an immediate.
89 MMI->InvalidateLabel(I->getOperand(0).getImm());
95 MF->getBasicBlockList().erase(MBB);
98 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
99 TII = MF.getTarget().getInstrInfo();
100 if (!TII) return false;
102 RegInfo = MF.getTarget().getRegisterInfo();
103 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
105 MMI = getAnalysisToUpdate<MachineModuleInfo>();
107 bool EverMadeChange = false;
108 bool MadeChangeThisIteration = true;
109 while (MadeChangeThisIteration) {
110 MadeChangeThisIteration = false;
111 MadeChangeThisIteration |= TailMergeBlocks(MF);
112 MadeChangeThisIteration |= OptimizeBranches(MF);
113 EverMadeChange |= MadeChangeThisIteration;
116 // See if any jump tables have become mergable or dead as the code generator
118 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
119 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
121 // Figure out how these jump tables should be merged.
122 std::vector<unsigned> JTMapping;
123 JTMapping.reserve(JTs.size());
125 // We always keep the 0th jump table.
126 JTMapping.push_back(0);
128 // Scan the jump tables, seeing if there are any duplicates. Note that this
129 // is N^2, which should be fixed someday.
130 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
131 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
133 // If a jump table was merge with another one, walk the function rewriting
134 // references to jump tables to reference the new JT ID's. Keep track of
135 // whether we see a jump table idx, if not, we can delete the JT.
136 std::vector<bool> JTIsLive;
137 JTIsLive.resize(JTs.size());
138 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
140 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
142 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
143 MachineOperand &Op = I->getOperand(op);
144 if (!Op.isJumpTableIndex()) continue;
145 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
146 Op.setJumpTableIndex(NewIdx);
148 // Remember that this JT is live.
149 JTIsLive[NewIdx] = true;
153 // Finally, remove dead jump tables. This happens either because the
154 // indirect jump was unreachable (and thus deleted) or because the jump
155 // table was merged with some other one.
156 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
158 JTI->RemoveJumpTable(i);
159 EverMadeChange = true;
164 return EverMadeChange;
167 //===----------------------------------------------------------------------===//
168 // Tail Merging of Blocks
169 //===----------------------------------------------------------------------===//
171 /// HashMachineInstr - Compute a hash value for MI and its operands.
172 static unsigned HashMachineInstr(const MachineInstr *MI) {
173 unsigned Hash = MI->getOpcode();
174 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
175 const MachineOperand &Op = MI->getOperand(i);
177 // Merge in bits from the operand if easy.
178 unsigned OperandHash = 0;
179 switch (Op.getType()) {
180 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
181 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
182 case MachineOperand::MO_MachineBasicBlock:
183 OperandHash = Op.getMachineBasicBlock()->getNumber();
185 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
186 case MachineOperand::MO_ConstantPoolIndex:
187 OperandHash = Op.getConstantPoolIndex();
189 case MachineOperand::MO_JumpTableIndex:
190 OperandHash = Op.getJumpTableIndex();
192 case MachineOperand::MO_GlobalAddress:
193 case MachineOperand::MO_ExternalSymbol:
194 // Global address / external symbol are too hard, don't bother, but do
195 // pull in the offset.
196 OperandHash = Op.getOffset();
201 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
206 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
207 /// instructions, because cross-jumping only saves code when at least two
208 /// instructions are removed (since a branch must be inserted).
209 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
210 MachineBasicBlock::const_iterator I = MBB->end();
211 if (I == MBB->begin())
212 return 0; // Empty MBB.
215 unsigned Hash = HashMachineInstr(I);
217 if (I == MBB->begin())
218 return Hash; // Single instr MBB.
221 // Hash in the second-to-last instruction.
222 Hash ^= HashMachineInstr(I) << 2;
226 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
227 /// of instructions they actually have in common together at their end. Return
228 /// iterators for the first shared instruction in each block.
229 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
230 MachineBasicBlock *MBB2,
231 MachineBasicBlock::iterator &I1,
232 MachineBasicBlock::iterator &I2) {
236 unsigned TailLen = 0;
237 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
239 if (!I1->isIdenticalTo(I2)) {
248 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
249 /// after it, replacing it with an unconditional branch to NewDest. This
250 /// returns true if OldInst's block is modified, false if NewDest is modified.
251 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
252 MachineBasicBlock *NewDest) {
253 MachineBasicBlock *OldBB = OldInst->getParent();
255 // Remove all the old successors of OldBB from the CFG.
256 while (!OldBB->succ_empty())
257 OldBB->removeSuccessor(OldBB->succ_begin());
259 // Remove all the dead instructions from the end of OldBB.
260 OldBB->erase(OldInst, OldBB->end());
262 // If OldBB isn't immediately before OldBB, insert a branch to it.
263 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
264 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
265 OldBB->addSuccessor(NewDest);
269 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
270 /// MBB so that the part before the iterator falls into the part starting at the
271 /// iterator. This returns the new MBB.
272 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
273 MachineBasicBlock::iterator BBI1) {
274 // Create the fall-through block.
275 MachineFunction::iterator MBBI = &CurMBB;
276 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
277 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
279 // Move all the successors of this block to the specified block.
280 while (!CurMBB.succ_empty()) {
281 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
282 NewMBB->addSuccessor(S);
283 CurMBB.removeSuccessor(S);
286 // Add an edge from CurMBB to NewMBB for the fall-through.
287 CurMBB.addSuccessor(NewMBB);
289 // Splice the code over.
290 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
292 // For targets that use the register scavenger, we must maintain LiveIns.
294 RS->enterBasicBlock(&CurMBB);
296 RS->forward(prior(CurMBB.end()));
297 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
298 RS->getRegsUsed(RegsLiveAtExit, false);
299 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
300 if (RegsLiveAtExit[i])
301 NewMBB->addLiveIn(i);
307 /// EstimateRuntime - Make a rough estimate for how long it will take to run
308 /// the specified code.
309 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
310 MachineBasicBlock::iterator E,
311 const TargetInstrInfo *TII) {
313 for (; I != E; ++I) {
314 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
315 if (TID.Flags & M_CALL_FLAG)
317 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
325 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
326 /// MBB2I and then insert an unconditional branch in the other block. Determine
327 /// which is the best to split
328 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
329 MachineBasicBlock::iterator MBB1I,
330 MachineBasicBlock *MBB2,
331 MachineBasicBlock::iterator MBB2I,
332 const TargetInstrInfo *TII) {
333 // TODO: if we had some notion of which block was hotter, we could split
334 // the hot block, so it is the fall-through. Since we don't have profile info
335 // make a decision based on which will hurt most to split.
336 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
337 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
339 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
340 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
341 // have a lower overall impact on the program execution.
342 return MBB1Time < MBB2Time;
345 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
348 if (!EnableTailMerge) return false;
350 // Find blocks with no successors.
351 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
352 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
354 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
357 // Sort by hash value so that blocks with identical end sequences sort
359 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
361 // Walk through equivalence sets looking for actual exact matches.
362 while (MergePotentials.size() > 1) {
363 unsigned CurHash = (MergePotentials.end()-1)->first;
364 unsigned PrevHash = (MergePotentials.end()-2)->first;
365 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
367 // If there is nothing that matches the hash of the current basic block,
369 if (CurHash != PrevHash) {
370 MergePotentials.pop_back();
374 // Determine the actual length of the shared tail between these two basic
375 // blocks. Because the hash can have collisions, it's possible that this is
377 MachineBasicBlock::iterator BBI1, BBI2;
378 unsigned CommonTailLen =
379 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
382 // If the tails don't have at least two instructions in common, see if there
383 // is anything else in the equivalence class that does match.
384 if (CommonTailLen < 2) {
385 unsigned FoundMatch = ~0U;
386 for (int i = MergePotentials.size()-2;
387 i != -1 && MergePotentials[i].first == CurHash; --i) {
388 CommonTailLen = ComputeCommonTailLength(CurMBB,
389 MergePotentials[i].second,
391 if (CommonTailLen >= 2) {
397 // If we didn't find anything that has at least two instructions matching
398 // this one, bail out.
399 if (FoundMatch == ~0U) {
400 MergePotentials.pop_back();
404 // Otherwise, move the matching block to the right position.
405 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
408 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
410 // If neither block is the entire common tail, split the tail of one block
411 // to make it redundant with the other tail.
412 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
413 if (0) { // Enable this to disable partial tail merges.
414 MergePotentials.pop_back();
418 // Decide whether we want to split CurMBB or MBB2.
419 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
420 CurMBB = SplitMBBAt(*CurMBB, BBI1);
421 BBI1 = CurMBB->begin();
422 MergePotentials.back().second = CurMBB;
424 MBB2 = SplitMBBAt(*MBB2, BBI2);
425 BBI2 = MBB2->begin();
426 (MergePotentials.end()-2)->second = MBB2;
430 if (MBB2->begin() == BBI2) {
431 // Hack the end off CurMBB, making it jump to MBBI@ instead.
432 ReplaceTailWithBranchTo(BBI1, MBB2);
433 // This modifies CurMBB, so remove it from the worklist.
434 MergePotentials.pop_back();
436 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
437 // Hack the end off MBB2, making it jump to CurMBB instead.
438 ReplaceTailWithBranchTo(BBI2, CurMBB);
439 // This modifies MBB2, so remove it from the worklist.
440 MergePotentials.erase(MergePotentials.end()-2);
449 //===----------------------------------------------------------------------===//
450 // Branch Optimization
451 //===----------------------------------------------------------------------===//
453 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
456 // Make sure blocks are numbered in order
459 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
460 MachineBasicBlock *MBB = I++;
463 // If it is dead, remove it.
464 if (MBB->pred_empty()) {
465 RemoveDeadBlock(MBB);
474 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
475 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
476 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
478 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
479 MachineBasicBlock *DestA,
480 MachineBasicBlock *DestB,
482 MachineFunction::iterator FallThru) {
483 bool MadeChange = false;
484 bool AddedFallThrough = false;
486 // If this block ends with a conditional branch that falls through to its
487 // successor, set DestB as the successor.
489 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
491 AddedFallThrough = true;
494 // If this is an unconditional branch with no explicit dest, it must just be
495 // a fallthrough into DestB.
496 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
498 AddedFallThrough = true;
502 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
503 while (SI != MBB.succ_end()) {
507 } else if (*SI == DestB) {
510 } else if ((*SI)->isLandingPad()) {
513 // Otherwise, this is a superfluous edge, remove it.
514 MBB.removeSuccessor(SI);
518 if (!AddedFallThrough) {
519 assert(DestA == 0 && DestB == 0 &&
520 "MachineCFG is missing edges!");
522 assert(DestA == 0 && "MachineCFG is missing edges!");
528 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
529 /// 'Old', change the code and CFG so that it branches to 'New' instead.
530 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
531 MachineBasicBlock *Old,
532 MachineBasicBlock *New,
533 const TargetInstrInfo *TII) {
534 assert(Old != New && "Cannot replace self with self!");
536 MachineBasicBlock::iterator I = BB->end();
537 while (I != BB->begin()) {
539 if (!TII->isTerminatorInstr(I->getOpcode())) break;
541 // Scan the operands of this machine instruction, replacing any uses of Old
543 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
544 if (I->getOperand(i).isMachineBasicBlock() &&
545 I->getOperand(i).getMachineBasicBlock() == Old)
546 I->getOperand(i).setMachineBasicBlock(New);
549 // Update the successor information.
550 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
551 for (int i = Succs.size()-1; i >= 0; --i)
552 if (Succs[i] == Old) {
553 BB->removeSuccessor(Old);
554 BB->addSuccessor(New);
558 /// CanFallThrough - Return true if the specified block (with the specified
559 /// branch condition) can implicitly transfer control to the block after it by
560 /// falling off the end of it. This should return false if it can reach the
561 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
563 /// True is a conservative answer.
565 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
566 bool BranchUnAnalyzable,
567 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
568 const std::vector<MachineOperand> &Cond) {
569 MachineFunction::iterator Fallthrough = CurBB;
571 // If FallthroughBlock is off the end of the function, it can't fall through.
572 if (Fallthrough == CurBB->getParent()->end())
575 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
576 if (!CurBB->isSuccessor(Fallthrough))
579 // If we couldn't analyze the branch, assume it could fall through.
580 if (BranchUnAnalyzable) return true;
582 // If there is no branch, control always falls through.
583 if (TBB == 0) return true;
585 // If there is some explicit branch to the fallthrough block, it can obviously
586 // reach, even though the branch should get folded to fall through implicitly.
587 if (MachineFunction::iterator(TBB) == Fallthrough ||
588 MachineFunction::iterator(FBB) == Fallthrough)
591 // If it's an unconditional branch to some block not the fall through, it
592 // doesn't fall through.
593 if (Cond.empty()) return false;
595 // Otherwise, if it is conditional and has no explicit false block, it falls
600 /// CanFallThrough - Return true if the specified can implicitly transfer
601 /// control to the block after it by falling off the end of it. This should
602 /// return false if it can reach the block after it, but it uses an explicit
603 /// branch to do so (e.g. a table jump).
605 /// True is a conservative answer.
607 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
608 MachineBasicBlock *TBB = 0, *FBB = 0;
609 std::vector<MachineOperand> Cond;
610 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
611 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
614 /// IsBetterFallthrough - Return true if it would be clearly better to
615 /// fall-through to MBB1 than to fall through into MBB2. This has to return
616 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
617 /// result in infinite loops.
618 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
619 MachineBasicBlock *MBB2,
620 const TargetInstrInfo &TII) {
621 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
622 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
623 // optimize branches that branch to either a return block or an assert block
624 // into a fallthrough to the return.
625 if (MBB1->empty() || MBB2->empty()) return false;
627 MachineInstr *MBB1I = --MBB1->end();
628 MachineInstr *MBB2I = --MBB2->end();
629 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
632 /// OptimizeBlock - Analyze and optimize control flow related to the specified
633 /// block. This is never called on the entry block.
634 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
635 MachineFunction::iterator FallThrough = MBB;
638 // If this block is empty, make everyone use its fall-through, not the block
641 // Dead block? Leave for cleanup later.
642 if (MBB->pred_empty()) return;
644 if (FallThrough == MBB->getParent()->end()) {
645 // TODO: Simplify preds to not branch here if possible!
647 // Rewrite all predecessors of the old block to go to the fallthrough
649 while (!MBB->pred_empty()) {
650 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
651 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
654 // If MBB was the target of a jump table, update jump tables to go to the
655 // fallthrough instead.
656 MBB->getParent()->getJumpTableInfo()->
657 ReplaceMBBInJumpTables(MBB, FallThrough);
663 // Check to see if we can simplify the terminator of the block before this
665 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
667 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
668 std::vector<MachineOperand> PriorCond;
669 bool PriorUnAnalyzable =
670 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
671 if (!PriorUnAnalyzable) {
672 // If the CFG for the prior block has extra edges, remove them.
673 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
674 !PriorCond.empty(), MBB);
676 // If the previous branch is conditional and both conditions go to the same
677 // destination, remove the branch, replacing it with an unconditional one or
679 if (PriorTBB && PriorTBB == PriorFBB) {
680 TII->RemoveBranch(PrevBB);
683 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
686 return OptimizeBlock(MBB);
689 // If the previous branch *only* branches to *this* block (conditional or
690 // not) remove the branch.
691 if (PriorTBB == MBB && PriorFBB == 0) {
692 TII->RemoveBranch(PrevBB);
695 return OptimizeBlock(MBB);
698 // If the prior block branches somewhere else on the condition and here if
699 // the condition is false, remove the uncond second branch.
700 if (PriorFBB == MBB) {
701 TII->RemoveBranch(PrevBB);
702 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
705 return OptimizeBlock(MBB);
708 // If the prior block branches here on true and somewhere else on false, and
709 // if the branch condition is reversible, reverse the branch to create a
711 if (PriorTBB == MBB) {
712 std::vector<MachineOperand> NewPriorCond(PriorCond);
713 if (!TII->ReverseBranchCondition(NewPriorCond)) {
714 TII->RemoveBranch(PrevBB);
715 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
718 return OptimizeBlock(MBB);
722 // If this block doesn't fall through (e.g. it ends with an uncond branch or
723 // has no successors) and if the pred falls through into this block, and if
724 // it would otherwise fall through into the block after this, move this
725 // block to the end of the function.
727 // We consider it more likely that execution will stay in the function (e.g.
728 // due to loops) than it is to exit it. This asserts in loops etc, moving
729 // the assert condition out of the loop body.
730 if (!PriorCond.empty() && PriorFBB == 0 &&
731 MachineFunction::iterator(PriorTBB) == FallThrough &&
732 !CanFallThrough(MBB)) {
733 bool DoTransform = true;
735 // We have to be careful that the succs of PredBB aren't both no-successor
736 // blocks. If neither have successors and if PredBB is the second from
737 // last block in the function, we'd just keep swapping the two blocks for
738 // last. Only do the swap if one is clearly better to fall through than
740 if (FallThrough == --MBB->getParent()->end() &&
741 !IsBetterFallthrough(PriorTBB, MBB, *TII))
744 // We don't want to do this transformation if we have control flow like:
753 // In this case, we could actually be moving the return block *into* a
755 if (DoTransform && !MBB->succ_empty() &&
756 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
761 // Reverse the branch so we will fall through on the previous true cond.
762 std::vector<MachineOperand> NewPriorCond(PriorCond);
763 if (!TII->ReverseBranchCondition(NewPriorCond)) {
764 DOUT << "\nMoving MBB: " << *MBB;
765 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
767 TII->RemoveBranch(PrevBB);
768 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
770 // Move this block to the end of the function.
771 MBB->moveAfter(--MBB->getParent()->end());
780 // Analyze the branch in the current block.
781 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
782 std::vector<MachineOperand> CurCond;
783 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
784 if (!CurUnAnalyzable) {
785 // If the CFG for the prior block has extra edges, remove them.
786 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
788 ++MachineFunction::iterator(MBB));
790 // If this is a two-way branch, and the FBB branches to this block, reverse
791 // the condition so the single-basic-block loop is faster. Instead of:
792 // Loop: xxx; jcc Out; jmp Loop
794 // Loop: xxx; jncc Loop; jmp Out
795 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
796 std::vector<MachineOperand> NewCond(CurCond);
797 if (!TII->ReverseBranchCondition(NewCond)) {
798 TII->RemoveBranch(*MBB);
799 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
802 return OptimizeBlock(MBB);
807 // If this branch is the only thing in its block, see if we can forward
808 // other blocks across it.
809 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
810 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
811 // This block may contain just an unconditional branch. Because there can
812 // be 'non-branch terminators' in the block, try removing the branch and
813 // then seeing if the block is empty.
814 TII->RemoveBranch(*MBB);
816 // If this block is just an unconditional branch to CurTBB, we can
817 // usually completely eliminate the block. The only case we cannot
818 // completely eliminate the block is when the block before this one
819 // falls through into MBB and we can't understand the prior block's branch
822 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
823 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
824 !PrevBB.isSuccessor(MBB)) {
825 // If the prior block falls through into us, turn it into an
826 // explicit branch to us to make updates simpler.
827 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
828 PriorTBB != MBB && PriorFBB != MBB) {
830 assert(PriorCond.empty() && PriorFBB == 0 &&
831 "Bad branch analysis");
834 assert(PriorFBB == 0 && "Machine CFG out of date!");
837 TII->RemoveBranch(PrevBB);
838 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
841 // Iterate through all the predecessors, revectoring each in-turn.
842 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
843 bool DidChange = false;
844 bool HasBranchToSelf = false;
845 while (PI != MBB->pred_end()) {
847 // If this block has an uncond branch to itself, leave it.
849 HasBranchToSelf = true;
852 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
856 // Change any jumptables to go to the new MBB.
857 MBB->getParent()->getJumpTableInfo()->
858 ReplaceMBBInJumpTables(MBB, CurTBB);
862 if (!HasBranchToSelf) return;
867 // Add the branch back if the block is more than just an uncond branch.
868 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
872 // If the prior block doesn't fall through into this block, and if this
873 // block doesn't fall through into some other block, see if we can find a
874 // place to move this block where a fall-through will happen.
875 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
876 PriorTBB, PriorFBB, PriorCond)) {
877 // Now we know that there was no fall-through into this block, check to
878 // see if it has a fall-through into its successor.
879 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
882 if (!MBB->isLandingPad()) {
883 // Check all the predecessors of this block. If one of them has no fall
884 // throughs, move this block right after it.
885 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
886 E = MBB->pred_end(); PI != E; ++PI) {
887 // Analyze the branch at the end of the pred.
888 MachineBasicBlock *PredBB = *PI;
889 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
890 if (PredBB != MBB && !CanFallThrough(PredBB)
891 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
892 // If the current block doesn't fall through, just move it.
893 // If the current block can fall through and does not end with a
894 // conditional branch, we need to append an unconditional jump to
895 // the (current) next block. To avoid a possible compile-time
896 // infinite loop, move blocks only backward in this case.
898 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
900 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
902 MBB->moveAfter(PredBB);
904 return OptimizeBlock(MBB);
910 // Check all successors to see if we can move this block before it.
911 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
912 E = MBB->succ_end(); SI != E; ++SI) {
913 // Analyze the branch at the end of the block before the succ.
914 MachineBasicBlock *SuccBB = *SI;
915 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
916 std::vector<MachineOperand> SuccPrevCond;
917 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
918 MBB->moveBefore(SuccBB);
920 return OptimizeBlock(MBB);
924 // Okay, there is no really great place to put this block. If, however,
925 // the block before this one would be a fall-through if this block were
926 // removed, move this block to the end of the function.
927 if (FallThrough != MBB->getParent()->end() &&
928 PrevBB.isSuccessor(FallThrough)) {
929 MBB->moveAfter(--MBB->getParent()->end());