BranchFolding.cpp revision a52dd151378eeaad1369829b1dc3164874774e04
1//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block.  This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
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"
32#include <algorithm>
33using namespace llvm;
34
35STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36STATISTIC(NumBranchOpts, "Number of branches optimized");
37STATISTIC(NumTailMerge , "Number of block tails merged");
38static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
39                              cl::init(cl::BOU_UNSET), cl::Hidden);
40namespace {
41  struct BranchFolder : public MachineFunctionPass {
42    static char ID;
43    BranchFolder(bool defaultEnableTailMerge) :
44        MachineFunctionPass((intptr_t)&ID) {
45          switch (FlagEnableTailMerge) {
46          case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
47          case cl::BOU_TRUE: EnableTailMerge = true; break;
48          case cl::BOU_FALSE: EnableTailMerge = false; break;
49          }
50    }
51
52    virtual bool runOnMachineFunction(MachineFunction &MF);
53    virtual const char *getPassName() const { return "Control Flow Optimizer"; }
54    const TargetInstrInfo *TII;
55    MachineModuleInfo *MMI;
56    bool MadeChange;
57  private:
58    // Tail Merging.
59    bool EnableTailMerge;
60    bool TailMergeBlocks(MachineFunction &MF);
61    bool TryMergeBlocks(MachineBasicBlock* SuccBB,
62                        MachineBasicBlock* PredBB);
63    void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
64                                 MachineBasicBlock *NewDest);
65    MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
66                                  MachineBasicBlock::iterator BBI1);
67
68    std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
69    const MRegisterInfo *RegInfo;
70    RegScavenger *RS;
71    // Branch optzn.
72    bool OptimizeBranches(MachineFunction &MF);
73    void OptimizeBlock(MachineBasicBlock *MBB);
74    void RemoveDeadBlock(MachineBasicBlock *MBB);
75
76    bool CanFallThrough(MachineBasicBlock *CurBB);
77    bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
78                        MachineBasicBlock *TBB, MachineBasicBlock *FBB,
79                        const std::vector<MachineOperand> &Cond);
80  };
81  char BranchFolder::ID = 0;
82}
83
84static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
85                                 MachineBasicBlock *DestA,
86                                 MachineBasicBlock *DestB,
87                                 bool isCond,
88                                 MachineFunction::iterator FallThru);
89
90FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
91      return new BranchFolder(DefaultEnableTailMerge); }
92
93/// RemoveDeadBlock - Remove the specified dead machine basic block from the
94/// function, updating the CFG.
95void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
96  assert(MBB->pred_empty() && "MBB must be dead!");
97  DOUT << "\nRemoving MBB: " << *MBB;
98
99  MachineFunction *MF = MBB->getParent();
100  // drop all successors.
101  while (!MBB->succ_empty())
102    MBB->removeSuccessor(MBB->succ_end()-1);
103
104  // If there is DWARF info to active, check to see if there are any LABEL
105  // records in the basic block.  If so, unregister them from MachineModuleInfo.
106  if (MMI && !MBB->empty()) {
107    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
108         I != E; ++I) {
109      if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
110        // The label ID # is always operand #0, an immediate.
111        MMI->InvalidateLabel(I->getOperand(0).getImm());
112      }
113    }
114  }
115
116  // Remove the block.
117  MF->getBasicBlockList().erase(MBB);
118}
119
120bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
121  TII = MF.getTarget().getInstrInfo();
122  if (!TII) return false;
123
124  // Fix CFG.  The later algorithms expect it to be right.
125  bool EverMadeChange = false;
126  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
127    MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
128    std::vector<MachineOperand> Cond;
129    if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
130      EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB,
131                        !Cond.empty(), next(I));
132  }
133
134  RegInfo = MF.getTarget().getRegisterInfo();
135  RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
136
137  MMI = getAnalysisToUpdate<MachineModuleInfo>();
138
139  bool MadeChangeThisIteration = true;
140  while (MadeChangeThisIteration) {
141    MadeChangeThisIteration = false;
142    MadeChangeThisIteration |= TailMergeBlocks(MF);
143    MadeChangeThisIteration |= OptimizeBranches(MF);
144    EverMadeChange |= MadeChangeThisIteration;
145  }
146
147  // See if any jump tables have become mergable or dead as the code generator
148  // did its thing.
149  MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
150  const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
151  if (!JTs.empty()) {
152    // Figure out how these jump tables should be merged.
153    std::vector<unsigned> JTMapping;
154    JTMapping.reserve(JTs.size());
155
156    // We always keep the 0th jump table.
157    JTMapping.push_back(0);
158
159    // Scan the jump tables, seeing if there are any duplicates.  Note that this
160    // is N^2, which should be fixed someday.
161    for (unsigned i = 1, e = JTs.size(); i != e; ++i)
162      JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
163
164    // If a jump table was merge with another one, walk the function rewriting
165    // references to jump tables to reference the new JT ID's.  Keep track of
166    // whether we see a jump table idx, if not, we can delete the JT.
167    std::vector<bool> JTIsLive;
168    JTIsLive.resize(JTs.size());
169    for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
170         BB != E; ++BB) {
171      for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
172           I != E; ++I)
173        for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
174          MachineOperand &Op = I->getOperand(op);
175          if (!Op.isJumpTableIndex()) continue;
176          unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
177          Op.setJumpTableIndex(NewIdx);
178
179          // Remember that this JT is live.
180          JTIsLive[NewIdx] = true;
181        }
182    }
183
184    // Finally, remove dead jump tables.  This happens either because the
185    // indirect jump was unreachable (and thus deleted) or because the jump
186    // table was merged with some other one.
187    for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
188      if (!JTIsLive[i]) {
189        JTI->RemoveJumpTable(i);
190        EverMadeChange = true;
191      }
192  }
193
194  delete RS;
195  return EverMadeChange;
196}
197
198//===----------------------------------------------------------------------===//
199//  Tail Merging of Blocks
200//===----------------------------------------------------------------------===//
201
202/// HashMachineInstr - Compute a hash value for MI and its operands.
203static unsigned HashMachineInstr(const MachineInstr *MI) {
204  unsigned Hash = MI->getOpcode();
205  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
206    const MachineOperand &Op = MI->getOperand(i);
207
208    // Merge in bits from the operand if easy.
209    unsigned OperandHash = 0;
210    switch (Op.getType()) {
211    case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
212    case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
213    case MachineOperand::MO_MachineBasicBlock:
214      OperandHash = Op.getMachineBasicBlock()->getNumber();
215      break;
216    case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
217    case MachineOperand::MO_ConstantPoolIndex:
218      OperandHash = Op.getConstantPoolIndex();
219      break;
220    case MachineOperand::MO_JumpTableIndex:
221      OperandHash = Op.getJumpTableIndex();
222      break;
223    case MachineOperand::MO_GlobalAddress:
224    case MachineOperand::MO_ExternalSymbol:
225      // Global address / external symbol are too hard, don't bother, but do
226      // pull in the offset.
227      OperandHash = Op.getOffset();
228      break;
229    default: break;
230    }
231
232    Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
233  }
234  return Hash;
235}
236
237/// HashEndOfMBB - Hash the last few instructions in the MBB.  For blocks
238/// with no successors, we hash two instructions, because cross-jumping
239/// only saves code when at least two instructions are removed (since a
240/// branch must be inserted).  For blocks with a successor, one of the
241/// two blocks to be tail-merged will end with a branch already, so
242/// it gains to cross-jump even for one instruction.
243
244static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
245                             unsigned minCommonTailLength) {
246  MachineBasicBlock::const_iterator I = MBB->end();
247  if (I == MBB->begin())
248    return 0;   // Empty MBB.
249
250  --I;
251  unsigned Hash = HashMachineInstr(I);
252
253  if (I == MBB->begin() || minCommonTailLength == 1)
254    return Hash;   // Single instr MBB.
255
256  --I;
257  // Hash in the second-to-last instruction.
258  Hash ^= HashMachineInstr(I) << 2;
259  return Hash;
260}
261
262/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
263/// of instructions they actually have in common together at their end.  Return
264/// iterators for the first shared instruction in each block.
265static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
266                                        MachineBasicBlock *MBB2,
267                                        MachineBasicBlock::iterator &I1,
268                                        MachineBasicBlock::iterator &I2) {
269  I1 = MBB1->end();
270  I2 = MBB2->end();
271
272  unsigned TailLen = 0;
273  while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
274    --I1; --I2;
275    if (!I1->isIdenticalTo(I2)) {
276      ++I1; ++I2;
277      break;
278    }
279    ++TailLen;
280  }
281  return TailLen;
282}
283
284/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
285/// after it, replacing it with an unconditional branch to NewDest.  This
286/// returns true if OldInst's block is modified, false if NewDest is modified.
287void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
288                                           MachineBasicBlock *NewDest) {
289  MachineBasicBlock *OldBB = OldInst->getParent();
290
291  // Remove all the old successors of OldBB from the CFG.
292  while (!OldBB->succ_empty())
293    OldBB->removeSuccessor(OldBB->succ_begin());
294
295  // Remove all the dead instructions from the end of OldBB.
296  OldBB->erase(OldInst, OldBB->end());
297
298  // If OldBB isn't immediately before OldBB, insert a branch to it.
299  if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
300    TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
301  OldBB->addSuccessor(NewDest);
302  ++NumTailMerge;
303}
304
305/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
306/// MBB so that the part before the iterator falls into the part starting at the
307/// iterator.  This returns the new MBB.
308MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
309                                            MachineBasicBlock::iterator BBI1) {
310  // Create the fall-through block.
311  MachineFunction::iterator MBBI = &CurMBB;
312  MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
313  CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
314
315  // Move all the successors of this block to the specified block.
316  while (!CurMBB.succ_empty()) {
317    MachineBasicBlock *S = *(CurMBB.succ_end()-1);
318    NewMBB->addSuccessor(S);
319    CurMBB.removeSuccessor(S);
320  }
321
322  // Add an edge from CurMBB to NewMBB for the fall-through.
323  CurMBB.addSuccessor(NewMBB);
324
325  // Splice the code over.
326  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
327
328  // For targets that use the register scavenger, we must maintain LiveIns.
329  if (RS) {
330    RS->enterBasicBlock(&CurMBB);
331    if (!CurMBB.empty())
332      RS->forward(prior(CurMBB.end()));
333    BitVector RegsLiveAtExit(RegInfo->getNumRegs());
334    RS->getRegsUsed(RegsLiveAtExit, false);
335    for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
336      if (RegsLiveAtExit[i])
337        NewMBB->addLiveIn(i);
338  }
339
340  return NewMBB;
341}
342
343/// EstimateRuntime - Make a rough estimate for how long it will take to run
344/// the specified code.
345static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
346                                MachineBasicBlock::iterator E,
347                                const TargetInstrInfo *TII) {
348  unsigned Time = 0;
349  for (; I != E; ++I) {
350    const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
351    if (TID.Flags & M_CALL_FLAG)
352      Time += 10;
353    else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
354      Time += 2;
355    else
356      ++Time;
357  }
358  return Time;
359}
360
361/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
362/// MBB2I and then insert an unconditional branch in the other block.  Determine
363/// which is the best to split
364static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
365                                  MachineBasicBlock::iterator MBB1I,
366                                  MachineBasicBlock *MBB2,
367                                  MachineBasicBlock::iterator MBB2I,
368                                  const TargetInstrInfo *TII,
369                                  MachineBasicBlock *PredBB) {
370  // If one block is the entry block, split the other one; we can't generate
371  // a branch to the entry block, as its label is not emitted.
372  MachineBasicBlock *Entry = MBB1->getParent()->begin();
373  if (MBB1 == Entry)
374    return false;
375  if (MBB2 == Entry)
376    return true;
377
378  // If one block falls through into the common successor, choose that
379  // one to split; it is one instruction less to do that.
380  if (PredBB) {
381    if (MBB1 == PredBB)
382      return true;
383    else if (MBB2 == PredBB)
384      return false;
385  }
386  // TODO: if we had some notion of which block was hotter, we could split
387  // the hot block, so it is the fall-through.  Since we don't have profile info
388  // make a decision based on which will hurt most to split.
389  unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
390  unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
391
392  // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
393  // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
394  // have a lower overall impact on the program execution.
395  return MBB1Time < MBB2Time;
396}
397
398// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
399// branches temporarily for tail merging).  In the case where CurMBB ends
400// with a conditional branch to the next block, optimize by reversing the
401// test and conditionally branching to SuccMBB instead.
402
403static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
404                    const TargetInstrInfo *TII) {
405  MachineFunction *MF = CurMBB->getParent();
406  MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
407  MachineBasicBlock *TBB = 0, *FBB = 0;
408  std::vector<MachineOperand> Cond;
409  if (I != MF->end() &&
410      !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
411    MachineBasicBlock *NextBB = I;
412    if (TBB == NextBB && Cond.size() && !FBB) {
413      if (!TII->ReverseBranchCondition(Cond)) {
414        TII->RemoveBranch(*CurMBB);
415        TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
416        return;
417      }
418    }
419  }
420  TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
421}
422
423static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
424                         const std::pair<unsigned,MachineBasicBlock*> &q) {
425    if (p.first < q.first)
426      return true;
427     else if (p.first > q.first)
428      return false;
429    else if (p.second->getNumber() < q.second->getNumber())
430      return true;
431    else if (p.second->getNumber() > q.second->getNumber())
432      return false;
433    else
434      assert(0 && "Predecessor appears twice");
435}
436
437// See if any of the blocks in MergePotentials (which all have a common single
438// successor, or all have no successor) can be tail-merged.  If there is a
439// successor, any blocks in MergePotentials that are not tail-merged and
440// are not immediately before Succ must have an unconditional branch to
441// Succ added (but the predecessor/successor lists need no adjustment).
442// The lone predecessor of Succ that falls through into Succ,
443// if any, is given in PredBB.
444
445bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
446                                  MachineBasicBlock* PredBB) {
447  unsigned minCommonTailLength = (SuccBB ? 1 : 2);
448  MadeChange = false;
449
450  // Sort by hash value so that blocks with identical end sequences sort
451  // together.
452  std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
453
454  // Walk through equivalence sets looking for actual exact matches.
455  while (MergePotentials.size() > 1) {
456    unsigned CurHash  = (MergePotentials.end()-1)->first;
457    unsigned PrevHash = (MergePotentials.end()-2)->first;
458    MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
459
460    // If there is nothing that matches the hash of the current basic block,
461    // give up.
462    if (CurHash != PrevHash) {
463      if (SuccBB && CurMBB != PredBB)
464        FixTail(CurMBB, SuccBB, TII);
465      MergePotentials.pop_back();
466      continue;
467    }
468
469    // Look through all the blocks that have the same hash as this one, and
470    // find the one that has the largest number of instructions in common.
471    // Since instructions may get combined later (e.g. single stores into
472    // store multiple) this measure is not particularly accurate.
473    MachineBasicBlock::iterator BBI1, BBI2;
474
475    unsigned FoundMatch = ~0U;
476    unsigned maxCommonTailLength = 0U;
477    for (int i = MergePotentials.size()-2;
478         i != -1 && MergePotentials[i].first == CurHash; --i) {
479      MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
480      unsigned CommonTailLen = ComputeCommonTailLength(CurMBB,
481                                              MergePotentials[i].second,
482                                              TrialBBI1, TrialBBI2);
483      if (CommonTailLen >= minCommonTailLength &&
484          CommonTailLen >= maxCommonTailLength) {
485        FoundMatch = i;
486        maxCommonTailLength = CommonTailLen;
487        BBI1 = TrialBBI1;
488        BBI2 = TrialBBI2;
489      }
490    }
491
492    // If we didn't find anything that has at least minCommonTailLength
493    // instructions matching this one, bail out.
494    if (FoundMatch == ~0U) {
495      // Put the unconditional branch back, if we need one.
496      if (SuccBB && CurMBB != PredBB)
497        FixTail(CurMBB, SuccBB, TII);
498      MergePotentials.pop_back();
499      continue;
500    }
501
502    // Otherwise, move the matching block to the right position.
503    if (FoundMatch != MergePotentials.size()-2)
504      std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
505
506    MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
507
508    // If neither block is the entire common tail, split the tail of one block
509    // to make it redundant with the other tail.  Also, we cannot jump to the
510    // entry block, so if one block is the entry block, split the other one.
511    MachineBasicBlock *Entry = CurMBB->getParent()->begin();
512    if (CurMBB->begin() == BBI1 && CurMBB != Entry)
513      ;   // CurMBB is common tail
514    else if (MBB2->begin() == BBI2 && MBB2 != Entry)
515      ;   // MBB2 is common tail
516    else {
517      if (0) { // Enable this to disable partial tail merges.
518        MergePotentials.pop_back();
519        continue;
520      }
521
522      // Decide whether we want to split CurMBB or MBB2.
523      if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
524        CurMBB = SplitMBBAt(*CurMBB, BBI1);
525        BBI1 = CurMBB->begin();
526        MergePotentials.back().second = CurMBB;
527      } else {
528        MBB2 = SplitMBBAt(*MBB2, BBI2);
529        BBI2 = MBB2->begin();
530        (MergePotentials.end()-2)->second = MBB2;
531      }
532    }
533
534    if (MBB2->begin() == BBI2 && MBB2 != Entry) {
535      // Hack the end off CurMBB, making it jump to MBBI@ instead.
536      ReplaceTailWithBranchTo(BBI1, MBB2);
537      // This modifies CurMBB, so remove it from the worklist.
538      MergePotentials.pop_back();
539    } else {
540      assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
541             "Didn't split block correctly?");
542      // Hack the end off MBB2, making it jump to CurMBB instead.
543      ReplaceTailWithBranchTo(BBI2, CurMBB);
544      // This modifies MBB2, so remove it from the worklist.
545      MergePotentials.erase(MergePotentials.end()-2);
546    }
547    MadeChange = true;
548  }
549  return MadeChange;
550}
551
552bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
553
554  if (!EnableTailMerge) return false;
555
556  MadeChange = false;
557
558  // First find blocks with no successors.
559  MergePotentials.clear();
560  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
561    if (I->succ_empty())
562      MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
563  }
564  // See if we can do any tail merging on those.
565  MadeChange |= TryMergeBlocks(NULL, NULL);
566
567  // Look at blocks (IBB) with multiple predecessors (PBB).
568  // We change each predecessor to a canonical form, by
569  // (1) temporarily removing any unconditional branch from the predecessor
570  // to IBB, and
571  // (2) alter conditional branches so they branch to the other block
572  // not IBB; this may require adding back an unconditional branch to IBB
573  // later, where there wasn't one coming in.  E.g.
574  //   Bcc IBB
575  //   fallthrough to QBB
576  // here becomes
577  //   Bncc QBB
578  // with a conceptual B to IBB after that, which never actually exists.
579  // With those changes, we see whether the predecessors' tails match,
580  // and merge them if so.  We change things out of canonical form and
581  // back to the way they were later in the process.  (OptimizeBranches
582  // would undo some of this, but we can't use it, because we'd get into
583  // a compile-time infinite loop repeatedly doing and undoing the same
584  // transformations.)
585
586  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
587    if (!I->succ_empty() && I->pred_size() >= 2) {
588      MachineBasicBlock *IBB = I;
589      MachineBasicBlock *PredBB = prior(I);
590      MergePotentials.clear();
591      for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
592           P != E2; ++P) {
593        MachineBasicBlock* PBB = *P;
594        // Skip blocks that loop to themselves, can't tail merge these.
595        if (PBB==IBB)
596          continue;
597        MachineBasicBlock *TBB = 0, *FBB = 0;
598        std::vector<MachineOperand> Cond;
599        if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
600          // Failing case:  IBB is the target of a cbr, and
601          // we cannot reverse the branch.
602          std::vector<MachineOperand> NewCond(Cond);
603          if (Cond.size() && TBB==IBB) {
604            if (TII->ReverseBranchCondition(NewCond))
605              continue;
606            // This is the QBB case described above
607            if (!FBB)
608              FBB = next(MachineFunction::iterator(PBB));
609          }
610          // Remove the unconditional branch at the end, if any.
611          if (TBB && (Cond.size()==0 || FBB)) {
612            TII->RemoveBranch(*PBB);
613            if (Cond.size())
614              // reinsert conditional branch only, for now
615              TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
616          }
617          MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
618        }
619      }
620    if (MergePotentials.size() >= 2)
621      MadeChange |= TryMergeBlocks(I, PredBB);
622    // Reinsert an unconditional branch if needed.
623    // The 1 below can be either an original single predecessor, or a result
624    // of removing blocks in TryMergeBlocks.
625    PredBB = prior(I);      // this may have been changed in TryMergeBlocks
626    if (MergePotentials.size()==1 &&
627        (MergePotentials.begin())->second != PredBB)
628      FixTail((MergePotentials.begin())->second, I, TII);
629    }
630  }
631  return MadeChange;
632}
633
634//===----------------------------------------------------------------------===//
635//  Branch Optimization
636//===----------------------------------------------------------------------===//
637
638bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
639  MadeChange = false;
640
641  // Make sure blocks are numbered in order
642  MF.RenumberBlocks();
643
644  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
645    MachineBasicBlock *MBB = I++;
646    OptimizeBlock(MBB);
647
648    // If it is dead, remove it.
649    if (MBB->pred_empty()) {
650      RemoveDeadBlock(MBB);
651      MadeChange = true;
652      ++NumDeadBlocks;
653    }
654  }
655  return MadeChange;
656}
657
658
659/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
660/// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
661/// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
662/// be null.
663static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
664                                 MachineBasicBlock *DestA,
665                                 MachineBasicBlock *DestB,
666                                 bool isCond,
667                                 MachineFunction::iterator FallThru) {
668  bool MadeChange = false;
669  bool AddedFallThrough = false;
670
671  // If this block ends with a conditional branch that falls through to its
672  // successor, set DestB as the successor.
673  if (isCond) {
674    if (DestB == 0 && FallThru != MBB.getParent()->end()) {
675      DestB = FallThru;
676      AddedFallThrough = true;
677    }
678  } else {
679    // If this is an unconditional branch with no explicit dest, it must just be
680    // a fallthrough into DestB.
681    if (DestA == 0 && FallThru != MBB.getParent()->end()) {
682      DestA = FallThru;
683      AddedFallThrough = true;
684    }
685  }
686
687  MachineBasicBlock::succ_iterator SI = MBB.succ_begin();
688  bool foundPad = false;
689  while (SI != MBB.succ_end()) {
690    if (*SI == DestA && DestA == DestB) {
691      DestA = DestB = 0;
692      if ((*SI)->isLandingPad())
693        foundPad = true;
694      ++SI;
695    } else if (*SI == DestA) {
696      DestA = 0;
697      if ((*SI)->isLandingPad())
698        foundPad = true;
699      ++SI;
700    } else if (*SI == DestB) {
701      DestB = 0;
702      if ((*SI)->isLandingPad())
703        foundPad = true;
704      ++SI;
705    } else if ((*SI)->isLandingPad() && !foundPad) {
706      foundPad = true;
707      ++SI;
708    } else {
709      // Otherwise, this is a superfluous edge, remove it.
710      MBB.removeSuccessor(SI);
711      MadeChange = true;
712    }
713  }
714  if (!AddedFallThrough) {
715    assert(DestA == 0 && DestB == 0 &&
716           "MachineCFG is missing edges!");
717  } else if (isCond) {
718    assert(DestA == 0 && "MachineCFG is missing edges!");
719  }
720  return MadeChange;
721}
722
723
724/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
725/// 'Old', change the code and CFG so that it branches to 'New' instead.
726static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
727                                   MachineBasicBlock *Old,
728                                   MachineBasicBlock *New,
729                                   const TargetInstrInfo *TII) {
730  assert(Old != New && "Cannot replace self with self!");
731
732  MachineBasicBlock::iterator I = BB->end();
733  while (I != BB->begin()) {
734    --I;
735    if (!TII->isTerminatorInstr(I->getOpcode())) break;
736
737    // Scan the operands of this machine instruction, replacing any uses of Old
738    // with New.
739    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
740      if (I->getOperand(i).isMachineBasicBlock() &&
741          I->getOperand(i).getMachineBasicBlock() == Old)
742        I->getOperand(i).setMachineBasicBlock(New);
743  }
744
745  // Update the successor information.  If New was already a successor, just
746  // remove the link to Old instead of creating another one.  PR 1444.
747  bool HadSuccessorNew = false;
748  std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
749  for (int i = Succs.size()-1; i >= 0; --i)
750    if (Succs[i] == New) {
751      HadSuccessorNew = true;
752      break;
753    }
754  for (int i = Succs.size()-1; i >= 0; --i)
755    if (Succs[i] == Old) {
756      BB->removeSuccessor(Old);
757      if (!HadSuccessorNew)
758        BB->addSuccessor(New);
759    }
760}
761
762/// CanFallThrough - Return true if the specified block (with the specified
763/// branch condition) can implicitly transfer control to the block after it by
764/// falling off the end of it.  This should return false if it can reach the
765/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
766///
767/// True is a conservative answer.
768///
769bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
770                                  bool BranchUnAnalyzable,
771                                  MachineBasicBlock *TBB, MachineBasicBlock *FBB,
772                                  const std::vector<MachineOperand> &Cond) {
773  MachineFunction::iterator Fallthrough = CurBB;
774  ++Fallthrough;
775  // If FallthroughBlock is off the end of the function, it can't fall through.
776  if (Fallthrough == CurBB->getParent()->end())
777    return false;
778
779  // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
780  if (!CurBB->isSuccessor(Fallthrough))
781    return false;
782
783  // If we couldn't analyze the branch, assume it could fall through.
784  if (BranchUnAnalyzable) return true;
785
786  // If there is no branch, control always falls through.
787  if (TBB == 0) return true;
788
789  // If there is some explicit branch to the fallthrough block, it can obviously
790  // reach, even though the branch should get folded to fall through implicitly.
791  if (MachineFunction::iterator(TBB) == Fallthrough ||
792      MachineFunction::iterator(FBB) == Fallthrough)
793    return true;
794
795  // If it's an unconditional branch to some block not the fall through, it
796  // doesn't fall through.
797  if (Cond.empty()) return false;
798
799  // Otherwise, if it is conditional and has no explicit false block, it falls
800  // through.
801  return FBB == 0;
802}
803
804/// CanFallThrough - Return true if the specified can implicitly transfer
805/// control to the block after it by falling off the end of it.  This should
806/// return false if it can reach the block after it, but it uses an explicit
807/// branch to do so (e.g. a table jump).
808///
809/// True is a conservative answer.
810///
811bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
812  MachineBasicBlock *TBB = 0, *FBB = 0;
813  std::vector<MachineOperand> Cond;
814  bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
815  return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
816}
817
818/// IsBetterFallthrough - Return true if it would be clearly better to
819/// fall-through to MBB1 than to fall through into MBB2.  This has to return
820/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
821/// result in infinite loops.
822static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
823                                MachineBasicBlock *MBB2,
824                                const TargetInstrInfo &TII) {
825  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
826  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
827  // optimize branches that branch to either a return block or an assert block
828  // into a fallthrough to the return.
829  if (MBB1->empty() || MBB2->empty()) return false;
830
831  MachineInstr *MBB1I = --MBB1->end();
832  MachineInstr *MBB2I = --MBB2->end();
833  return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
834}
835
836/// OptimizeBlock - Analyze and optimize control flow related to the specified
837/// block.  This is never called on the entry block.
838void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
839  MachineFunction::iterator FallThrough = MBB;
840  ++FallThrough;
841
842  // If this block is empty, make everyone use its fall-through, not the block
843  // explicitly.  Landing pads should not do this since the landing-pad table
844  // points to this block.
845  if (MBB->empty() && !MBB->isLandingPad()) {
846    // Dead block?  Leave for cleanup later.
847    if (MBB->pred_empty()) return;
848
849    if (FallThrough == MBB->getParent()->end()) {
850      // TODO: Simplify preds to not branch here if possible!
851    } else {
852      // Rewrite all predecessors of the old block to go to the fallthrough
853      // instead.
854      while (!MBB->pred_empty()) {
855        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
856        ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
857      }
858
859      // If MBB was the target of a jump table, update jump tables to go to the
860      // fallthrough instead.
861      MBB->getParent()->getJumpTableInfo()->
862        ReplaceMBBInJumpTables(MBB, FallThrough);
863      MadeChange = true;
864    }
865    return;
866  }
867
868  // Check to see if we can simplify the terminator of the block before this
869  // one.
870  MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
871
872  MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
873  std::vector<MachineOperand> PriorCond;
874  bool PriorUnAnalyzable =
875    TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
876  if (!PriorUnAnalyzable) {
877    // If the CFG for the prior block has extra edges, remove them.
878    MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
879                                       !PriorCond.empty(), MBB);
880
881    // If the previous branch is conditional and both conditions go to the same
882    // destination, remove the branch, replacing it with an unconditional one or
883    // a fall-through.
884    if (PriorTBB && PriorTBB == PriorFBB) {
885      TII->RemoveBranch(PrevBB);
886      PriorCond.clear();
887      if (PriorTBB != MBB)
888        TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
889      MadeChange = true;
890      ++NumBranchOpts;
891      return OptimizeBlock(MBB);
892    }
893
894    // If the previous branch *only* branches to *this* block (conditional or
895    // not) remove the branch.
896    if (PriorTBB == MBB && PriorFBB == 0) {
897      TII->RemoveBranch(PrevBB);
898      MadeChange = true;
899      ++NumBranchOpts;
900      return OptimizeBlock(MBB);
901    }
902
903    // If the prior block branches somewhere else on the condition and here if
904    // the condition is false, remove the uncond second branch.
905    if (PriorFBB == MBB) {
906      TII->RemoveBranch(PrevBB);
907      TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
908      MadeChange = true;
909      ++NumBranchOpts;
910      return OptimizeBlock(MBB);
911    }
912
913    // If the prior block branches here on true and somewhere else on false, and
914    // if the branch condition is reversible, reverse the branch to create a
915    // fall-through.
916    if (PriorTBB == MBB) {
917      std::vector<MachineOperand> NewPriorCond(PriorCond);
918      if (!TII->ReverseBranchCondition(NewPriorCond)) {
919        TII->RemoveBranch(PrevBB);
920        TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
921        MadeChange = true;
922        ++NumBranchOpts;
923        return OptimizeBlock(MBB);
924      }
925    }
926
927    // If this block doesn't fall through (e.g. it ends with an uncond branch or
928    // has no successors) and if the pred falls through into this block, and if
929    // it would otherwise fall through into the block after this, move this
930    // block to the end of the function.
931    //
932    // We consider it more likely that execution will stay in the function (e.g.
933    // due to loops) than it is to exit it.  This asserts in loops etc, moving
934    // the assert condition out of the loop body.
935    if (!PriorCond.empty() && PriorFBB == 0 &&
936        MachineFunction::iterator(PriorTBB) == FallThrough &&
937        !CanFallThrough(MBB)) {
938      bool DoTransform = true;
939
940      // We have to be careful that the succs of PredBB aren't both no-successor
941      // blocks.  If neither have successors and if PredBB is the second from
942      // last block in the function, we'd just keep swapping the two blocks for
943      // last.  Only do the swap if one is clearly better to fall through than
944      // the other.
945      if (FallThrough == --MBB->getParent()->end() &&
946          !IsBetterFallthrough(PriorTBB, MBB, *TII))
947        DoTransform = false;
948
949      // We don't want to do this transformation if we have control flow like:
950      //   br cond BB2
951      // BB1:
952      //   ..
953      //   jmp BBX
954      // BB2:
955      //   ..
956      //   ret
957      //
958      // In this case, we could actually be moving the return block *into* a
959      // loop!
960      if (DoTransform && !MBB->succ_empty() &&
961          (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
962        DoTransform = false;
963
964
965      if (DoTransform) {
966        // Reverse the branch so we will fall through on the previous true cond.
967        std::vector<MachineOperand> NewPriorCond(PriorCond);
968        if (!TII->ReverseBranchCondition(NewPriorCond)) {
969          DOUT << "\nMoving MBB: " << *MBB;
970          DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
971
972          TII->RemoveBranch(PrevBB);
973          TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
974
975          // Move this block to the end of the function.
976          MBB->moveAfter(--MBB->getParent()->end());
977          MadeChange = true;
978          ++NumBranchOpts;
979          return;
980        }
981      }
982    }
983  }
984
985  // Analyze the branch in the current block.
986  MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
987  std::vector<MachineOperand> CurCond;
988  bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
989  if (!CurUnAnalyzable) {
990    // If the CFG for the prior block has extra edges, remove them.
991    MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
992                                       !CurCond.empty(),
993                                       ++MachineFunction::iterator(MBB));
994
995    // If this is a two-way branch, and the FBB branches to this block, reverse
996    // the condition so the single-basic-block loop is faster.  Instead of:
997    //    Loop: xxx; jcc Out; jmp Loop
998    // we want:
999    //    Loop: xxx; jncc Loop; jmp Out
1000    if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1001      std::vector<MachineOperand> NewCond(CurCond);
1002      if (!TII->ReverseBranchCondition(NewCond)) {
1003        TII->RemoveBranch(*MBB);
1004        TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1005        MadeChange = true;
1006        ++NumBranchOpts;
1007        return OptimizeBlock(MBB);
1008      }
1009    }
1010
1011
1012    // If this branch is the only thing in its block, see if we can forward
1013    // other blocks across it.
1014    if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1015        TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
1016      // This block may contain just an unconditional branch.  Because there can
1017      // be 'non-branch terminators' in the block, try removing the branch and
1018      // then seeing if the block is empty.
1019      TII->RemoveBranch(*MBB);
1020
1021      // If this block is just an unconditional branch to CurTBB, we can
1022      // usually completely eliminate the block.  The only case we cannot
1023      // completely eliminate the block is when the block before this one
1024      // falls through into MBB and we can't understand the prior block's branch
1025      // condition.
1026      if (MBB->empty()) {
1027        bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1028        if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1029            !PrevBB.isSuccessor(MBB)) {
1030          // If the prior block falls through into us, turn it into an
1031          // explicit branch to us to make updates simpler.
1032          if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1033              PriorTBB != MBB && PriorFBB != MBB) {
1034            if (PriorTBB == 0) {
1035              assert(PriorCond.empty() && PriorFBB == 0 &&
1036                     "Bad branch analysis");
1037              PriorTBB = MBB;
1038            } else {
1039              assert(PriorFBB == 0 && "Machine CFG out of date!");
1040              PriorFBB = MBB;
1041            }
1042            TII->RemoveBranch(PrevBB);
1043            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1044          }
1045
1046          // Iterate through all the predecessors, revectoring each in-turn.
1047          MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1048          bool DidChange = false;
1049          bool HasBranchToSelf = false;
1050          while (PI != MBB->pred_end()) {
1051            if (*PI == MBB) {
1052              // If this block has an uncond branch to itself, leave it.
1053              ++PI;
1054              HasBranchToSelf = true;
1055            } else {
1056              DidChange = true;
1057              ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1058            }
1059          }
1060
1061          // Change any jumptables to go to the new MBB.
1062          MBB->getParent()->getJumpTableInfo()->
1063            ReplaceMBBInJumpTables(MBB, CurTBB);
1064          if (DidChange) {
1065            ++NumBranchOpts;
1066            MadeChange = true;
1067            if (!HasBranchToSelf) return;
1068          }
1069        }
1070      }
1071
1072      // Add the branch back if the block is more than just an uncond branch.
1073      TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1074    }
1075  }
1076
1077  // If the prior block doesn't fall through into this block, and if this
1078  // block doesn't fall through into some other block, see if we can find a
1079  // place to move this block where a fall-through will happen.
1080  if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1081                      PriorTBB, PriorFBB, PriorCond)) {
1082    // Now we know that there was no fall-through into this block, check to
1083    // see if it has a fall-through into its successor.
1084    bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1085                                       CurCond);
1086
1087    if (!MBB->isLandingPad()) {
1088      // Check all the predecessors of this block.  If one of them has no fall
1089      // throughs, move this block right after it.
1090      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1091           E = MBB->pred_end(); PI != E; ++PI) {
1092        // Analyze the branch at the end of the pred.
1093        MachineBasicBlock *PredBB = *PI;
1094        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1095        if (PredBB != MBB && !CanFallThrough(PredBB)
1096            && (!CurFallsThru || !CurTBB || !CurFBB)
1097            && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1098          // If the current block doesn't fall through, just move it.
1099          // If the current block can fall through and does not end with a
1100          // conditional branch, we need to append an unconditional jump to
1101          // the (current) next block.  To avoid a possible compile-time
1102          // infinite loop, move blocks only backward in this case.
1103          // Also, if there are already 2 branches here, we cannot add a third;
1104          // this means we have the case
1105          // Bcc next
1106          // B elsewhere
1107          // next:
1108          if (CurFallsThru) {
1109            MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1110            CurCond.clear();
1111            TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1112          }
1113          MBB->moveAfter(PredBB);
1114          MadeChange = true;
1115          return OptimizeBlock(MBB);
1116        }
1117      }
1118    }
1119
1120    if (!CurFallsThru) {
1121      // Check all successors to see if we can move this block before it.
1122      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1123           E = MBB->succ_end(); SI != E; ++SI) {
1124        // Analyze the branch at the end of the block before the succ.
1125        MachineBasicBlock *SuccBB = *SI;
1126        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1127        std::vector<MachineOperand> SuccPrevCond;
1128
1129        // If this block doesn't already fall-through to that successor, and if
1130        // the succ doesn't already have a block that can fall through into it,
1131        // and if the successor isn't an EH destination, we can arrange for the
1132        // fallthrough to happen.
1133        if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1134            !SuccBB->isLandingPad()) {
1135          MBB->moveBefore(SuccBB);
1136          MadeChange = true;
1137          return OptimizeBlock(MBB);
1138        }
1139      }
1140
1141      // Okay, there is no really great place to put this block.  If, however,
1142      // the block before this one would be a fall-through if this block were
1143      // removed, move this block to the end of the function.
1144      if (FallThrough != MBB->getParent()->end() &&
1145          PrevBB.isSuccessor(FallThrough)) {
1146        MBB->moveAfter(--MBB->getParent()->end());
1147        MadeChange = true;
1148        return;
1149      }
1150    }
1151  }
1152}
1153