BranchFolding.cpp revision 8ef7e2159fc1cccf6308d20f5ef7872c344e2253
1//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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 "BranchFolding.h"
21#include "llvm/Function.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
25#include "llvm/CodeGen/MachineJumpTableInfo.h"
26#include "llvm/CodeGen/RegisterScavenging.h"
27#include "llvm/Target/TargetInstrInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetRegisterInfo.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/SetVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
38#include <algorithm>
39using namespace llvm;
40
41STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
42STATISTIC(NumBranchOpts, "Number of branches optimized");
43STATISTIC(NumTailMerge , "Number of block tails merged");
44
45static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
46                              cl::init(cl::BOU_UNSET), cl::Hidden);
47
48// Throttle for huge numbers of predecessors (compile speed problems)
49static cl::opt<unsigned>
50TailMergeThreshold("tail-merge-threshold",
51          cl::desc("Max number of predecessors to consider tail merging"),
52          cl::init(150), cl::Hidden);
53
54// Heuristic for tail merging (and, inversely, tail duplication).
55// TODO: This should be replaced with a target query.
56static cl::opt<unsigned>
57TailMergeSize("tail-merge-size",
58          cl::desc("Min number of instructions to consider tail merging"),
59                              cl::init(3), cl::Hidden);
60
61namespace {
62  /// BranchFolderPass - Wrap branch folder in a machine function pass.
63  class BranchFolderPass : public MachineFunctionPass,
64                           public BranchFolder {
65  public:
66    static char ID;
67    explicit BranchFolderPass(bool defaultEnableTailMerge)
68      : MachineFunctionPass(&ID), BranchFolder(defaultEnableTailMerge) {}
69
70    virtual bool runOnMachineFunction(MachineFunction &MF);
71    virtual const char *getPassName() const { return "Control Flow Optimizer"; }
72  };
73}
74
75char BranchFolderPass::ID = 0;
76
77FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
78  return new BranchFolderPass(DefaultEnableTailMerge);
79}
80
81bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
82  return OptimizeFunction(MF,
83                          MF.getTarget().getInstrInfo(),
84                          MF.getTarget().getRegisterInfo(),
85                          getAnalysisIfAvailable<MachineModuleInfo>());
86}
87
88
89BranchFolder::BranchFolder(bool defaultEnableTailMerge) {
90  switch (FlagEnableTailMerge) {
91  case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
92  case cl::BOU_TRUE: EnableTailMerge = true; break;
93  case cl::BOU_FALSE: EnableTailMerge = false; break;
94  }
95}
96
97/// RemoveDeadBlock - Remove the specified dead machine basic block from the
98/// function, updating the CFG.
99void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
100  assert(MBB->pred_empty() && "MBB must be dead!");
101  DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
102
103  MachineFunction *MF = MBB->getParent();
104  // drop all successors.
105  while (!MBB->succ_empty())
106    MBB->removeSuccessor(MBB->succ_end()-1);
107
108  // Remove the block.
109  MF->erase(MBB);
110}
111
112/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
113/// followed by terminators, and if the implicitly defined registers are not
114/// used by the terminators, remove those implicit_def's. e.g.
115/// BB1:
116///   r0 = implicit_def
117///   r1 = implicit_def
118///   br
119/// This block can be optimized away later if the implicit instructions are
120/// removed.
121bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
122  SmallSet<unsigned, 4> ImpDefRegs;
123  MachineBasicBlock::iterator I = MBB->begin();
124  while (I != MBB->end()) {
125    if (!I->isImplicitDef())
126      break;
127    unsigned Reg = I->getOperand(0).getReg();
128    ImpDefRegs.insert(Reg);
129    for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
130         unsigned SubReg = *SubRegs; ++SubRegs)
131      ImpDefRegs.insert(SubReg);
132    ++I;
133  }
134  if (ImpDefRegs.empty())
135    return false;
136
137  MachineBasicBlock::iterator FirstTerm = I;
138  while (I != MBB->end()) {
139    if (!TII->isUnpredicatedTerminator(I))
140      return false;
141    // See if it uses any of the implicitly defined registers.
142    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
143      MachineOperand &MO = I->getOperand(i);
144      if (!MO.isReg() || !MO.isUse())
145        continue;
146      unsigned Reg = MO.getReg();
147      if (ImpDefRegs.count(Reg))
148        return false;
149    }
150    ++I;
151  }
152
153  I = MBB->begin();
154  while (I != FirstTerm) {
155    MachineInstr *ImpDefMI = &*I;
156    ++I;
157    MBB->erase(ImpDefMI);
158  }
159
160  return true;
161}
162
163/// OptimizeFunction - Perhaps branch folding, tail merging and other
164/// CFG optimizations on the given function.
165bool BranchFolder::OptimizeFunction(MachineFunction &MF,
166                                    const TargetInstrInfo *tii,
167                                    const TargetRegisterInfo *tri,
168                                    MachineModuleInfo *mmi) {
169  if (!tii) return false;
170
171  TII = tii;
172  TRI = tri;
173  MMI = mmi;
174
175  RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
176
177  // Fix CFG.  The later algorithms expect it to be right.
178  bool MadeChange = false;
179  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
180    MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
181    SmallVector<MachineOperand, 4> Cond;
182    if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
183      MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
184    MadeChange |= OptimizeImpDefsBlock(MBB);
185  }
186
187  bool MadeChangeThisIteration = true;
188  while (MadeChangeThisIteration) {
189    MadeChangeThisIteration = false;
190    MadeChangeThisIteration |= TailMergeBlocks(MF);
191    MadeChangeThisIteration |= OptimizeBranches(MF);
192    MadeChange |= MadeChangeThisIteration;
193  }
194
195  // See if any jump tables have become mergable or dead as the code generator
196  // did its thing.
197  MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
198  if (JTI == 0) {
199    delete RS;
200    return MadeChange;
201  }
202
203  const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
204  // Figure out how these jump tables should be merged.
205  std::vector<unsigned> JTMapping;
206  JTMapping.reserve(JTs.size());
207
208  // We always keep the 0th jump table.
209  JTMapping.push_back(0);
210
211  // Scan the jump tables, seeing if there are any duplicates.  Note that this
212  // is N^2, which should be fixed someday.
213  for (unsigned i = 1, e = JTs.size(); i != e; ++i) {
214    if (JTs[i].MBBs.empty())
215      JTMapping.push_back(i);
216    else
217      JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
218  }
219
220  // If a jump table was merge with another one, walk the function rewriting
221  // references to jump tables to reference the new JT ID's.  Keep track of
222  // whether we see a jump table idx, if not, we can delete the JT.
223  BitVector JTIsLive(JTs.size());
224  for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
225       BB != E; ++BB) {
226    for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
227         I != E; ++I)
228      for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
229        MachineOperand &Op = I->getOperand(op);
230        if (!Op.isJTI()) continue;
231        unsigned NewIdx = JTMapping[Op.getIndex()];
232        Op.setIndex(NewIdx);
233
234        // Remember that this JT is live.
235        JTIsLive.set(NewIdx);
236      }
237  }
238
239  // Finally, remove dead jump tables.  This happens either because the
240  // indirect jump was unreachable (and thus deleted) or because the jump
241  // table was merged with some other one.
242  for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
243    if (!JTIsLive.test(i)) {
244      JTI->RemoveJumpTable(i);
245      MadeChange = true;
246    }
247
248  delete RS;
249  return MadeChange;
250}
251
252//===----------------------------------------------------------------------===//
253//  Tail Merging of Blocks
254//===----------------------------------------------------------------------===//
255
256/// HashMachineInstr - Compute a hash value for MI and its operands.
257static unsigned HashMachineInstr(const MachineInstr *MI) {
258  unsigned Hash = MI->getOpcode();
259  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
260    const MachineOperand &Op = MI->getOperand(i);
261
262    // Merge in bits from the operand if easy.
263    unsigned OperandHash = 0;
264    switch (Op.getType()) {
265    case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
266    case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
267    case MachineOperand::MO_MachineBasicBlock:
268      OperandHash = Op.getMBB()->getNumber();
269      break;
270    case MachineOperand::MO_FrameIndex:
271    case MachineOperand::MO_ConstantPoolIndex:
272    case MachineOperand::MO_JumpTableIndex:
273      OperandHash = Op.getIndex();
274      break;
275    case MachineOperand::MO_GlobalAddress:
276    case MachineOperand::MO_ExternalSymbol:
277      // Global address / external symbol are too hard, don't bother, but do
278      // pull in the offset.
279      OperandHash = Op.getOffset();
280      break;
281    default: break;
282    }
283
284    Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
285  }
286  return Hash;
287}
288
289/// HashEndOfMBB - Hash the last few instructions in the MBB.  For blocks
290/// with no successors, we hash two instructions, because cross-jumping
291/// only saves code when at least two instructions are removed (since a
292/// branch must be inserted).  For blocks with a successor, one of the
293/// two blocks to be tail-merged will end with a branch already, so
294/// it gains to cross-jump even for one instruction.
295static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
296                             unsigned minCommonTailLength) {
297  MachineBasicBlock::const_iterator I = MBB->end();
298  if (I == MBB->begin())
299    return 0;   // Empty MBB.
300
301  --I;
302  // Skip debug info so it will not affect codegen.
303  while (I->isDebugValue()) {
304    if (I==MBB->begin())
305      return 0;      // MBB empty except for debug info.
306    --I;
307  }
308  unsigned Hash = HashMachineInstr(I);
309
310  if (I == MBB->begin() || minCommonTailLength == 1)
311    return Hash;   // Single instr MBB.
312
313  --I;
314  while (I->isDebugValue()) {
315    if (I==MBB->begin())
316      return Hash;      // MBB with single non-debug instr.
317    --I;
318  }
319  // Hash in the second-to-last instruction.
320  Hash ^= HashMachineInstr(I) << 2;
321  return Hash;
322}
323
324/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
325/// of instructions they actually have in common together at their end.  Return
326/// iterators for the first shared instruction in each block.
327static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
328                                        MachineBasicBlock *MBB2,
329                                        MachineBasicBlock::iterator &I1,
330                                        MachineBasicBlock::iterator &I2) {
331  I1 = MBB1->end();
332  I2 = MBB2->end();
333
334  unsigned TailLen = 0;
335  while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
336    --I1; --I2;
337    // Skip debugging pseudos; necessary to avoid changing the code.
338    while (I1->isDebugValue()) {
339      if (I1==MBB1->begin()) {
340        while (I2->isDebugValue()) {
341          if (I2==MBB2->begin())
342            // I1==DBG at begin; I2==DBG at begin
343            return TailLen;
344          --I2;
345        }
346        ++I2;
347        // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
348        return TailLen;
349      }
350      --I1;
351    }
352    // I1==first (untested) non-DBG preceding known match
353    while (I2->isDebugValue()) {
354      if (I2==MBB2->begin()) {
355        ++I1;
356        // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
357        return TailLen;
358      }
359      --I2;
360    }
361    // I1, I2==first (untested) non-DBGs preceding known match
362    if (!I1->isIdenticalTo(I2) ||
363        // FIXME: This check is dubious. It's used to get around a problem where
364        // people incorrectly expect inline asm directives to remain in the same
365        // relative order. This is untenable because normal compiler
366        // optimizations (like this one) may reorder and/or merge these
367        // directives.
368        I1->isInlineAsm()) {
369      ++I1; ++I2;
370      break;
371    }
372    ++TailLen;
373  }
374  // Back past possible debugging pseudos at beginning of block.  This matters
375  // when one block differs from the other only by whether debugging pseudos
376  // are present at the beginning.  (This way, the various checks later for
377  // I1==MBB1->begin() work as expected.)
378  if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
379    --I2;
380    while (I2->isDebugValue()) {
381      if (I2 == MBB2->begin()) {
382        return TailLen;
383        }
384      --I2;
385    }
386    ++I2;
387  }
388  if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
389    --I1;
390    while (I1->isDebugValue()) {
391      if (I1 == MBB1->begin())
392        return TailLen;
393      --I1;
394    }
395    ++I1;
396  }
397  return TailLen;
398}
399
400/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
401/// after it, replacing it with an unconditional branch to NewDest.  This
402/// returns true if OldInst's block is modified, false if NewDest is modified.
403void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
404                                           MachineBasicBlock *NewDest) {
405  MachineBasicBlock *OldBB = OldInst->getParent();
406
407  // Remove all the old successors of OldBB from the CFG.
408  while (!OldBB->succ_empty())
409    OldBB->removeSuccessor(OldBB->succ_begin());
410
411  // Remove all the dead instructions from the end of OldBB.
412  OldBB->erase(OldInst, OldBB->end());
413
414  // If OldBB isn't immediately before OldBB, insert a branch to it.
415  if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
416    TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
417  OldBB->addSuccessor(NewDest);
418  ++NumTailMerge;
419}
420
421/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
422/// MBB so that the part before the iterator falls into the part starting at the
423/// iterator.  This returns the new MBB.
424MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
425                                            MachineBasicBlock::iterator BBI1) {
426  MachineFunction &MF = *CurMBB.getParent();
427
428  // Create the fall-through block.
429  MachineFunction::iterator MBBI = &CurMBB;
430  MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
431  CurMBB.getParent()->insert(++MBBI, NewMBB);
432
433  // Move all the successors of this block to the specified block.
434  NewMBB->transferSuccessors(&CurMBB);
435
436  // Add an edge from CurMBB to NewMBB for the fall-through.
437  CurMBB.addSuccessor(NewMBB);
438
439  // Splice the code over.
440  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
441
442  // For targets that use the register scavenger, we must maintain LiveIns.
443  if (RS) {
444    RS->enterBasicBlock(&CurMBB);
445    if (!CurMBB.empty())
446      RS->forward(prior(CurMBB.end()));
447    BitVector RegsLiveAtExit(TRI->getNumRegs());
448    RS->getRegsUsed(RegsLiveAtExit, false);
449    for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++)
450      if (RegsLiveAtExit[i])
451        NewMBB->addLiveIn(i);
452  }
453
454  return NewMBB;
455}
456
457/// EstimateRuntime - Make a rough estimate for how long it will take to run
458/// the specified code.
459static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
460                                MachineBasicBlock::iterator E) {
461  unsigned Time = 0;
462  for (; I != E; ++I) {
463    if (I->isDebugValue())
464      continue;
465    const TargetInstrDesc &TID = I->getDesc();
466    if (TID.isCall())
467      Time += 10;
468    else if (TID.mayLoad() || TID.mayStore())
469      Time += 2;
470    else
471      ++Time;
472  }
473  return Time;
474}
475
476// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
477// branches temporarily for tail merging).  In the case where CurMBB ends
478// with a conditional branch to the next block, optimize by reversing the
479// test and conditionally branching to SuccMBB instead.
480static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
481                    const TargetInstrInfo *TII) {
482  MachineFunction *MF = CurMBB->getParent();
483  MachineFunction::iterator I = llvm::next(MachineFunction::iterator(CurMBB));
484  MachineBasicBlock *TBB = 0, *FBB = 0;
485  SmallVector<MachineOperand, 4> Cond;
486  if (I != MF->end() &&
487      !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
488    MachineBasicBlock *NextBB = I;
489    if (TBB == NextBB && !Cond.empty() && !FBB) {
490      if (!TII->ReverseBranchCondition(Cond)) {
491        TII->RemoveBranch(*CurMBB);
492        TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
493        return;
494      }
495    }
496  }
497  TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
498}
499
500bool
501BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
502  if (getHash() < o.getHash())
503    return true;
504   else if (getHash() > o.getHash())
505    return false;
506  else if (getBlock()->getNumber() < o.getBlock()->getNumber())
507    return true;
508  else if (getBlock()->getNumber() > o.getBlock()->getNumber())
509    return false;
510  else {
511    // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
512    // an object with itself.
513#ifndef _GLIBCXX_DEBUG
514    llvm_unreachable("Predecessor appears twice");
515#endif
516    return false;
517  }
518}
519
520/// CountTerminators - Count the number of terminators in the given
521/// block and set I to the position of the first non-terminator, if there
522/// is one, or MBB->end() otherwise.
523static unsigned CountTerminators(MachineBasicBlock *MBB,
524                                 MachineBasicBlock::iterator &I) {
525  I = MBB->end();
526  unsigned NumTerms = 0;
527  for (;;) {
528    if (I == MBB->begin()) {
529      I = MBB->end();
530      break;
531    }
532    --I;
533    if (!I->getDesc().isTerminator()) break;
534    ++NumTerms;
535  }
536  return NumTerms;
537}
538
539/// ProfitableToMerge - Check if two machine basic blocks have a common tail
540/// and decide if it would be profitable to merge those tails.  Return the
541/// length of the common tail and iterators to the first common instruction
542/// in each block.
543static bool ProfitableToMerge(MachineBasicBlock *MBB1,
544                              MachineBasicBlock *MBB2,
545                              unsigned minCommonTailLength,
546                              unsigned &CommonTailLen,
547                              MachineBasicBlock::iterator &I1,
548                              MachineBasicBlock::iterator &I2,
549                              MachineBasicBlock *SuccBB,
550                              MachineBasicBlock *PredBB) {
551  CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
552  MachineFunction *MF = MBB1->getParent();
553
554  if (CommonTailLen == 0)
555    return false;
556
557  // It's almost always profitable to merge any number of non-terminator
558  // instructions with the block that falls through into the common successor.
559  if (MBB1 == PredBB || MBB2 == PredBB) {
560    MachineBasicBlock::iterator I;
561    unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
562    if (CommonTailLen > NumTerms)
563      return true;
564  }
565
566  // If one of the blocks can be completely merged and happens to be in
567  // a position where the other could fall through into it, merge any number
568  // of instructions, because it can be done without a branch.
569  // TODO: If the blocks are not adjacent, move one of them so that they are?
570  if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
571    return true;
572  if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
573    return true;
574
575  // If both blocks have an unconditional branch temporarily stripped out,
576  // count that as an additional common instruction for the following
577  // heuristics.
578  unsigned EffectiveTailLen = CommonTailLen;
579  if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
580      !MBB1->back().getDesc().isBarrier() &&
581      !MBB2->back().getDesc().isBarrier())
582    ++EffectiveTailLen;
583
584  // Check if the common tail is long enough to be worthwhile.
585  if (EffectiveTailLen >= minCommonTailLength)
586    return true;
587
588  // If we are optimizing for code size, 2 instructions in common is enough if
589  // we don't have to split a block.  At worst we will be introducing 1 new
590  // branch instruction, which is likely to be smaller than the 2
591  // instructions that would be deleted in the merge.
592  if (EffectiveTailLen >= 2 &&
593      MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
594      (I1 == MBB1->begin() || I2 == MBB2->begin()))
595    return true;
596
597  return false;
598}
599
600/// ComputeSameTails - Look through all the blocks in MergePotentials that have
601/// hash CurHash (guaranteed to match the last element).  Build the vector
602/// SameTails of all those that have the (same) largest number of instructions
603/// in common of any pair of these blocks.  SameTails entries contain an
604/// iterator into MergePotentials (from which the MachineBasicBlock can be
605/// found) and a MachineBasicBlock::iterator into that MBB indicating the
606/// instruction where the matching code sequence begins.
607/// Order of elements in SameTails is the reverse of the order in which
608/// those blocks appear in MergePotentials (where they are not necessarily
609/// consecutive).
610unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
611                                        unsigned minCommonTailLength,
612                                        MachineBasicBlock *SuccBB,
613                                        MachineBasicBlock *PredBB) {
614  unsigned maxCommonTailLength = 0U;
615  SameTails.clear();
616  MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
617  MPIterator HighestMPIter = prior(MergePotentials.end());
618  for (MPIterator CurMPIter = prior(MergePotentials.end()),
619                  B = MergePotentials.begin();
620       CurMPIter != B && CurMPIter->getHash() == CurHash;
621       --CurMPIter) {
622    for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
623      unsigned CommonTailLen;
624      if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
625                            minCommonTailLength,
626                            CommonTailLen, TrialBBI1, TrialBBI2,
627                            SuccBB, PredBB)) {
628        if (CommonTailLen > maxCommonTailLength) {
629          SameTails.clear();
630          maxCommonTailLength = CommonTailLen;
631          HighestMPIter = CurMPIter;
632          SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
633        }
634        if (HighestMPIter == CurMPIter &&
635            CommonTailLen == maxCommonTailLength)
636          SameTails.push_back(SameTailElt(I, TrialBBI2));
637      }
638      if (I == B)
639        break;
640    }
641  }
642  return maxCommonTailLength;
643}
644
645/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
646/// MergePotentials, restoring branches at ends of blocks as appropriate.
647void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
648                                        MachineBasicBlock *SuccBB,
649                                        MachineBasicBlock *PredBB) {
650  MPIterator CurMPIter, B;
651  for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
652       CurMPIter->getHash() == CurHash;
653       --CurMPIter) {
654    // Put the unconditional branch back, if we need one.
655    MachineBasicBlock *CurMBB = CurMPIter->getBlock();
656    if (SuccBB && CurMBB != PredBB)
657      FixTail(CurMBB, SuccBB, TII);
658    if (CurMPIter == B)
659      break;
660  }
661  if (CurMPIter->getHash() != CurHash)
662    CurMPIter++;
663  MergePotentials.erase(CurMPIter, MergePotentials.end());
664}
665
666/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
667/// only of the common tail.  Create a block that does by splitting one.
668unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
669                                             unsigned maxCommonTailLength) {
670  unsigned commonTailIndex = 0;
671  unsigned TimeEstimate = ~0U;
672  for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
673    // Use PredBB if possible; that doesn't require a new branch.
674    if (SameTails[i].getBlock() == PredBB) {
675      commonTailIndex = i;
676      break;
677    }
678    // Otherwise, make a (fairly bogus) choice based on estimate of
679    // how long it will take the various blocks to execute.
680    unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
681                                 SameTails[i].getTailStartPos());
682    if (t <= TimeEstimate) {
683      TimeEstimate = t;
684      commonTailIndex = i;
685    }
686  }
687
688  MachineBasicBlock::iterator BBI =
689    SameTails[commonTailIndex].getTailStartPos();
690  MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
691
692  // If the common tail includes any debug info we will take it pretty
693  // randomly from one of the inputs.  Might be better to remove it?
694  DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
695               << maxCommonTailLength);
696
697  MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
698  SameTails[commonTailIndex].setBlock(newMBB);
699  SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
700
701  // If we split PredBB, newMBB is the new predecessor.
702  if (PredBB == MBB)
703    PredBB = newMBB;
704
705  return commonTailIndex;
706}
707
708// See if any of the blocks in MergePotentials (which all have a common single
709// successor, or all have no successor) can be tail-merged.  If there is a
710// successor, any blocks in MergePotentials that are not tail-merged and
711// are not immediately before Succ must have an unconditional branch to
712// Succ added (but the predecessor/successor lists need no adjustment).
713// The lone predecessor of Succ that falls through into Succ,
714// if any, is given in PredBB.
715
716bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
717                                      MachineBasicBlock *PredBB) {
718  bool MadeChange = false;
719
720  // Except for the special cases below, tail-merge if there are at least
721  // this many instructions in common.
722  unsigned minCommonTailLength = TailMergeSize;
723
724  DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
725        for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
726          dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
727                 << (i == e-1 ? "" : ", ");
728        dbgs() << "\n";
729        if (SuccBB) {
730          dbgs() << "  with successor BB#" << SuccBB->getNumber() << '\n';
731          if (PredBB)
732            dbgs() << "  which has fall-through from BB#"
733                   << PredBB->getNumber() << "\n";
734        }
735        dbgs() << "Looking for common tails of at least "
736               << minCommonTailLength << " instruction"
737               << (minCommonTailLength == 1 ? "" : "s") << '\n';
738       );
739
740  // Sort by hash value so that blocks with identical end sequences sort
741  // together.
742  std::stable_sort(MergePotentials.begin(), MergePotentials.end());
743
744  // Walk through equivalence sets looking for actual exact matches.
745  while (MergePotentials.size() > 1) {
746    unsigned CurHash = MergePotentials.back().getHash();
747
748    // Build SameTails, identifying the set of blocks with this hash code
749    // and with the maximum number of instructions in common.
750    unsigned maxCommonTailLength = ComputeSameTails(CurHash,
751                                                    minCommonTailLength,
752                                                    SuccBB, PredBB);
753
754    // If we didn't find any pair that has at least minCommonTailLength
755    // instructions in common, remove all blocks with this hash code and retry.
756    if (SameTails.empty()) {
757      RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
758      continue;
759    }
760
761    // If one of the blocks is the entire common tail (and not the entry
762    // block, which we can't jump to), we can treat all blocks with this same
763    // tail at once.  Use PredBB if that is one of the possibilities, as that
764    // will not introduce any extra branches.
765    MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
766                                 getParent()->begin();
767    unsigned commonTailIndex = SameTails.size();
768    // If there are two blocks, check to see if one can be made to fall through
769    // into the other.
770    if (SameTails.size() == 2 &&
771        SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
772        SameTails[1].tailIsWholeBlock())
773      commonTailIndex = 1;
774    else if (SameTails.size() == 2 &&
775             SameTails[1].getBlock()->isLayoutSuccessor(
776                                                     SameTails[0].getBlock()) &&
777             SameTails[0].tailIsWholeBlock())
778      commonTailIndex = 0;
779    else {
780      // Otherwise just pick one, favoring the fall-through predecessor if
781      // there is one.
782      for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
783        MachineBasicBlock *MBB = SameTails[i].getBlock();
784        if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
785          continue;
786        if (MBB == PredBB) {
787          commonTailIndex = i;
788          break;
789        }
790        if (SameTails[i].tailIsWholeBlock())
791          commonTailIndex = i;
792      }
793    }
794
795    if (commonTailIndex == SameTails.size() ||
796        (SameTails[commonTailIndex].getBlock() == PredBB &&
797         !SameTails[commonTailIndex].tailIsWholeBlock())) {
798      // None of the blocks consist entirely of the common tail.
799      // Split a block so that one does.
800      commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
801    }
802
803    MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
804    // MBB is common tail.  Adjust all other BB's to jump to this one.
805    // Traversal must be forwards so erases work.
806    DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
807                 << " for ");
808    for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
809      if (commonTailIndex == i)
810        continue;
811      DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
812                   << (i == e-1 ? "" : ", "));
813      // Hack the end off BB i, making it jump to BB commonTailIndex instead.
814      ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
815      // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
816      MergePotentials.erase(SameTails[i].getMPIter());
817    }
818    DEBUG(dbgs() << "\n");
819    // We leave commonTailIndex in the worklist in case there are other blocks
820    // that match it with a smaller number of instructions.
821    MadeChange = true;
822  }
823  return MadeChange;
824}
825
826bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
827
828  if (!EnableTailMerge) return false;
829
830  bool MadeChange = false;
831
832  // First find blocks with no successors.
833  MergePotentials.clear();
834  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
835    if (I->succ_empty())
836      MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I, 2U), I));
837  }
838
839  // See if we can do any tail merging on those.
840  if (MergePotentials.size() < TailMergeThreshold &&
841      MergePotentials.size() >= 2)
842    MadeChange |= TryTailMergeBlocks(NULL, NULL);
843
844  // Look at blocks (IBB) with multiple predecessors (PBB).
845  // We change each predecessor to a canonical form, by
846  // (1) temporarily removing any unconditional branch from the predecessor
847  // to IBB, and
848  // (2) alter conditional branches so they branch to the other block
849  // not IBB; this may require adding back an unconditional branch to IBB
850  // later, where there wasn't one coming in.  E.g.
851  //   Bcc IBB
852  //   fallthrough to QBB
853  // here becomes
854  //   Bncc QBB
855  // with a conceptual B to IBB after that, which never actually exists.
856  // With those changes, we see whether the predecessors' tails match,
857  // and merge them if so.  We change things out of canonical form and
858  // back to the way they were later in the process.  (OptimizeBranches
859  // would undo some of this, but we can't use it, because we'd get into
860  // a compile-time infinite loop repeatedly doing and undoing the same
861  // transformations.)
862
863  for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
864       I != E; ++I) {
865    if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
866      SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
867      MachineBasicBlock *IBB = I;
868      MachineBasicBlock *PredBB = prior(I);
869      MergePotentials.clear();
870      for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
871                                            E2 = I->pred_end();
872           P != E2; ++P) {
873        MachineBasicBlock *PBB = *P;
874        // Skip blocks that loop to themselves, can't tail merge these.
875        if (PBB == IBB)
876          continue;
877        // Visit each predecessor only once.
878        if (!UniquePreds.insert(PBB))
879          continue;
880        MachineBasicBlock *TBB = 0, *FBB = 0;
881        SmallVector<MachineOperand, 4> Cond;
882        if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
883          // Failing case:  IBB is the target of a cbr, and
884          // we cannot reverse the branch.
885          SmallVector<MachineOperand, 4> NewCond(Cond);
886          if (!Cond.empty() && TBB == IBB) {
887            if (TII->ReverseBranchCondition(NewCond))
888              continue;
889            // This is the QBB case described above
890            if (!FBB)
891              FBB = llvm::next(MachineFunction::iterator(PBB));
892          }
893          // Failing case:  the only way IBB can be reached from PBB is via
894          // exception handling.  Happens for landing pads.  Would be nice
895          // to have a bit in the edge so we didn't have to do all this.
896          if (IBB->isLandingPad()) {
897            MachineFunction::iterator IP = PBB;  IP++;
898            MachineBasicBlock *PredNextBB = NULL;
899            if (IP != MF.end())
900              PredNextBB = IP;
901            if (TBB == NULL) {
902              if (IBB != PredNextBB)      // fallthrough
903                continue;
904            } else if (FBB) {
905              if (TBB != IBB && FBB != IBB)   // cbr then ubr
906                continue;
907            } else if (Cond.empty()) {
908              if (TBB != IBB)               // ubr
909                continue;
910            } else {
911              if (TBB != IBB && IBB != PredNextBB)  // cbr
912                continue;
913            }
914          }
915          // Remove the unconditional branch at the end, if any.
916          if (TBB && (Cond.empty() || FBB)) {
917            TII->RemoveBranch(*PBB);
918            if (!Cond.empty())
919              // reinsert conditional branch only, for now
920              TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond);
921          }
922          MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB, 1U),
923                                                       *P));
924        }
925      }
926      if (MergePotentials.size() >= 2)
927        MadeChange |= TryTailMergeBlocks(IBB, PredBB);
928      // Reinsert an unconditional branch if needed.
929      // The 1 below can occur as a result of removing blocks in TryTailMergeBlocks.
930      PredBB = prior(I);      // this may have been changed in TryTailMergeBlocks
931      if (MergePotentials.size() == 1 &&
932          MergePotentials.begin()->getBlock() != PredBB)
933        FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
934    }
935  }
936  return MadeChange;
937}
938
939//===----------------------------------------------------------------------===//
940//  Branch Optimization
941//===----------------------------------------------------------------------===//
942
943bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
944  bool MadeChange = false;
945
946  // Make sure blocks are numbered in order
947  MF.RenumberBlocks();
948
949  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
950    MachineBasicBlock *MBB = I++;
951    MadeChange |= OptimizeBlock(MBB);
952
953    // If it is dead, remove it.
954    if (MBB->pred_empty()) {
955      RemoveDeadBlock(MBB);
956      MadeChange = true;
957      ++NumDeadBlocks;
958    }
959  }
960  return MadeChange;
961}
962
963// Blocks should be considered empty if they contain only debug info;
964// else the debug info would affect codegen.
965static bool IsEmptyBlock(MachineBasicBlock *MBB) {
966  if (MBB->empty())
967    return true;
968  for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
969       MBBI!=MBBE; ++MBBI) {
970    if (!MBBI->isDebugValue())
971      return false;
972  }
973  return true;
974}
975
976// Blocks with only debug info and branches should be considered the same
977// as blocks with only branches.
978static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
979  MachineBasicBlock::iterator MBBI, MBBE;
980  for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
981    if (!MBBI->isDebugValue())
982      break;
983  }
984  return (MBBI->getDesc().isBranch());
985}
986
987/// IsBetterFallthrough - Return true if it would be clearly better to
988/// fall-through to MBB1 than to fall through into MBB2.  This has to return
989/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
990/// result in infinite loops.
991static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
992                                MachineBasicBlock *MBB2) {
993  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
994  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
995  // optimize branches that branch to either a return block or an assert block
996  // into a fallthrough to the return.
997  if (MBB1->empty() || MBB2->empty()) return false;
998
999  // If there is a clear successor ordering we make sure that one block
1000  // will fall through to the next
1001  if (MBB1->isSuccessor(MBB2)) return true;
1002  if (MBB2->isSuccessor(MBB1)) return false;
1003
1004  MachineInstr *MBB1I = --MBB1->end();
1005  MachineInstr *MBB2I = --MBB2->end();
1006  return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
1007}
1008
1009/// OptimizeBlock - Analyze and optimize control flow related to the specified
1010/// block.  This is never called on the entry block.
1011bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1012  bool MadeChange = false;
1013  MachineFunction &MF = *MBB->getParent();
1014ReoptimizeBlock:
1015
1016  MachineFunction::iterator FallThrough = MBB;
1017  ++FallThrough;
1018
1019  // If this block is empty, make everyone use its fall-through, not the block
1020  // explicitly.  Landing pads should not do this since the landing-pad table
1021  // points to this block.  Blocks with their addresses taken shouldn't be
1022  // optimized away.
1023  if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
1024    // Dead block?  Leave for cleanup later.
1025    if (MBB->pred_empty()) return MadeChange;
1026
1027    if (FallThrough == MF.end()) {
1028      // TODO: Simplify preds to not branch here if possible!
1029    } else {
1030      // Rewrite all predecessors of the old block to go to the fallthrough
1031      // instead.
1032      while (!MBB->pred_empty()) {
1033        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1034        Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
1035      }
1036      // If MBB was the target of a jump table, update jump tables to go to the
1037      // fallthrough instead.
1038      if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1039        MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
1040      MadeChange = true;
1041    }
1042    return MadeChange;
1043  }
1044
1045  // Check to see if we can simplify the terminator of the block before this
1046  // one.
1047  MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
1048
1049  MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
1050  SmallVector<MachineOperand, 4> PriorCond;
1051  bool PriorUnAnalyzable =
1052    TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1053  if (!PriorUnAnalyzable) {
1054    // If the CFG for the prior block has extra edges, remove them.
1055    MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1056                                              !PriorCond.empty());
1057
1058    // If the previous branch is conditional and both conditions go to the same
1059    // destination, remove the branch, replacing it with an unconditional one or
1060    // a fall-through.
1061    if (PriorTBB && PriorTBB == PriorFBB) {
1062      TII->RemoveBranch(PrevBB);
1063      PriorCond.clear();
1064      if (PriorTBB != MBB)
1065        TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
1066      MadeChange = true;
1067      ++NumBranchOpts;
1068      goto ReoptimizeBlock;
1069    }
1070
1071    // If the previous block unconditionally falls through to this block and
1072    // this block has no other predecessors, move the contents of this block
1073    // into the prior block. This doesn't usually happen when SimplifyCFG
1074    // has been used, but it can happen if tail merging splits a fall-through
1075    // predecessor of a block.
1076    // This has to check PrevBB->succ_size() because EH edges are ignored by
1077    // AnalyzeBranch.
1078    if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1079        PrevBB.succ_size() == 1 &&
1080        !MBB->hasAddressTaken()) {
1081      DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1082                   << "From MBB: " << *MBB);
1083      PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1084      PrevBB.removeSuccessor(PrevBB.succ_begin());;
1085      assert(PrevBB.succ_empty());
1086      PrevBB.transferSuccessors(MBB);
1087      MadeChange = true;
1088      return MadeChange;
1089    }
1090
1091    // If the previous branch *only* branches to *this* block (conditional or
1092    // not) remove the branch.
1093    if (PriorTBB == MBB && PriorFBB == 0) {
1094      TII->RemoveBranch(PrevBB);
1095      MadeChange = true;
1096      ++NumBranchOpts;
1097      goto ReoptimizeBlock;
1098    }
1099
1100    // If the prior block branches somewhere else on the condition and here if
1101    // the condition is false, remove the uncond second branch.
1102    if (PriorFBB == MBB) {
1103      TII->RemoveBranch(PrevBB);
1104      TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
1105      MadeChange = true;
1106      ++NumBranchOpts;
1107      goto ReoptimizeBlock;
1108    }
1109
1110    // If the prior block branches here on true and somewhere else on false, and
1111    // if the branch condition is reversible, reverse the branch to create a
1112    // fall-through.
1113    if (PriorTBB == MBB) {
1114      SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1115      if (!TII->ReverseBranchCondition(NewPriorCond)) {
1116        TII->RemoveBranch(PrevBB);
1117        TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
1118        MadeChange = true;
1119        ++NumBranchOpts;
1120        goto ReoptimizeBlock;
1121      }
1122    }
1123
1124    // If this block has no successors (e.g. it is a return block or ends with
1125    // a call to a no-return function like abort or __cxa_throw) and if the pred
1126    // falls through into this block, and if it would otherwise fall through
1127    // into the block after this, move this block to the end of the function.
1128    //
1129    // We consider it more likely that execution will stay in the function (e.g.
1130    // due to loops) than it is to exit it.  This asserts in loops etc, moving
1131    // the assert condition out of the loop body.
1132    if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
1133        MachineFunction::iterator(PriorTBB) == FallThrough &&
1134        !MBB->canFallThrough()) {
1135      bool DoTransform = true;
1136
1137      // We have to be careful that the succs of PredBB aren't both no-successor
1138      // blocks.  If neither have successors and if PredBB is the second from
1139      // last block in the function, we'd just keep swapping the two blocks for
1140      // last.  Only do the swap if one is clearly better to fall through than
1141      // the other.
1142      if (FallThrough == --MF.end() &&
1143          !IsBetterFallthrough(PriorTBB, MBB))
1144        DoTransform = false;
1145
1146      if (DoTransform) {
1147        // Reverse the branch so we will fall through on the previous true cond.
1148        SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1149        if (!TII->ReverseBranchCondition(NewPriorCond)) {
1150          DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1151                       << "To make fallthrough to: " << *PriorTBB << "\n");
1152
1153          TII->RemoveBranch(PrevBB);
1154          TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1155
1156          // Move this block to the end of the function.
1157          MBB->moveAfter(--MF.end());
1158          MadeChange = true;
1159          ++NumBranchOpts;
1160          return MadeChange;
1161        }
1162      }
1163    }
1164  }
1165
1166  // Analyze the branch in the current block.
1167  MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1168  SmallVector<MachineOperand, 4> CurCond;
1169  bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1170  if (!CurUnAnalyzable) {
1171    // If the CFG for the prior block has extra edges, remove them.
1172    MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1173
1174    // If this is a two-way branch, and the FBB branches to this block, reverse
1175    // the condition so the single-basic-block loop is faster.  Instead of:
1176    //    Loop: xxx; jcc Out; jmp Loop
1177    // we want:
1178    //    Loop: xxx; jncc Loop; jmp Out
1179    if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1180      SmallVector<MachineOperand, 4> NewCond(CurCond);
1181      if (!TII->ReverseBranchCondition(NewCond)) {
1182        TII->RemoveBranch(*MBB);
1183        TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1184        MadeChange = true;
1185        ++NumBranchOpts;
1186        goto ReoptimizeBlock;
1187      }
1188    }
1189
1190    // If this branch is the only thing in its block, see if we can forward
1191    // other blocks across it.
1192    if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1193        IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1194        !MBB->hasAddressTaken()) {
1195      // This block may contain just an unconditional branch.  Because there can
1196      // be 'non-branch terminators' in the block, try removing the branch and
1197      // then seeing if the block is empty.
1198      TII->RemoveBranch(*MBB);
1199      // If the only things remaining in the block are debug info, remove these
1200      // as well, so this will behave the same as an empty block in non-debug
1201      // mode.
1202      if (!MBB->empty()) {
1203        bool NonDebugInfoFound = false;
1204        for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1205             I != E; ++I) {
1206          if (!I->isDebugValue()) {
1207            NonDebugInfoFound = true;
1208            break;
1209          }
1210        }
1211        if (!NonDebugInfoFound)
1212          // Make the block empty, losing the debug info (we could probably
1213          // improve this in some cases.)
1214          MBB->erase(MBB->begin(), MBB->end());
1215      }
1216      // If this block is just an unconditional branch to CurTBB, we can
1217      // usually completely eliminate the block.  The only case we cannot
1218      // completely eliminate the block is when the block before this one
1219      // falls through into MBB and we can't understand the prior block's branch
1220      // condition.
1221      if (MBB->empty()) {
1222        bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1223        if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1224            !PrevBB.isSuccessor(MBB)) {
1225          // If the prior block falls through into us, turn it into an
1226          // explicit branch to us to make updates simpler.
1227          if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1228              PriorTBB != MBB && PriorFBB != MBB) {
1229            if (PriorTBB == 0) {
1230              assert(PriorCond.empty() && PriorFBB == 0 &&
1231                     "Bad branch analysis");
1232              PriorTBB = MBB;
1233            } else {
1234              assert(PriorFBB == 0 && "Machine CFG out of date!");
1235              PriorFBB = MBB;
1236            }
1237            TII->RemoveBranch(PrevBB);
1238            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1239          }
1240
1241          // Iterate through all the predecessors, revectoring each in-turn.
1242          size_t PI = 0;
1243          bool DidChange = false;
1244          bool HasBranchToSelf = false;
1245          while(PI != MBB->pred_size()) {
1246            MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1247            if (PMBB == MBB) {
1248              // If this block has an uncond branch to itself, leave it.
1249              ++PI;
1250              HasBranchToSelf = true;
1251            } else {
1252              DidChange = true;
1253              PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1254              // If this change resulted in PMBB ending in a conditional
1255              // branch where both conditions go to the same destination,
1256              // change this to an unconditional branch (and fix the CFG).
1257              MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1258              SmallVector<MachineOperand, 4> NewCurCond;
1259              bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1260                      NewCurFBB, NewCurCond, true);
1261              if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1262                TII->RemoveBranch(*PMBB);
1263                NewCurCond.clear();
1264                TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1265                MadeChange = true;
1266                ++NumBranchOpts;
1267                PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
1268              }
1269            }
1270          }
1271
1272          // Change any jumptables to go to the new MBB.
1273          if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1274            MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1275          if (DidChange) {
1276            ++NumBranchOpts;
1277            MadeChange = true;
1278            if (!HasBranchToSelf) return MadeChange;
1279          }
1280        }
1281      }
1282
1283      // Add the branch back if the block is more than just an uncond branch.
1284      TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1285    }
1286  }
1287
1288  // If the prior block doesn't fall through into this block, and if this
1289  // block doesn't fall through into some other block, see if we can find a
1290  // place to move this block where a fall-through will happen.
1291  if (!PrevBB.canFallThrough()) {
1292
1293    // Now we know that there was no fall-through into this block, check to
1294    // see if it has a fall-through into its successor.
1295    bool CurFallsThru = MBB->canFallThrough();
1296
1297    if (!MBB->isLandingPad()) {
1298      // Check all the predecessors of this block.  If one of them has no fall
1299      // throughs, move this block right after it.
1300      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1301           E = MBB->pred_end(); PI != E; ++PI) {
1302        // Analyze the branch at the end of the pred.
1303        MachineBasicBlock *PredBB = *PI;
1304        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1305        MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
1306        SmallVector<MachineOperand, 4> PredCond;
1307        if (PredBB != MBB && !PredBB->canFallThrough() &&
1308            !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
1309            && (!CurFallsThru || !CurTBB || !CurFBB)
1310            && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1311          // If the current block doesn't fall through, just move it.
1312          // If the current block can fall through and does not end with a
1313          // conditional branch, we need to append an unconditional jump to
1314          // the (current) next block.  To avoid a possible compile-time
1315          // infinite loop, move blocks only backward in this case.
1316          // Also, if there are already 2 branches here, we cannot add a third;
1317          // this means we have the case
1318          // Bcc next
1319          // B elsewhere
1320          // next:
1321          if (CurFallsThru) {
1322            MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1323            CurCond.clear();
1324            TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1325          }
1326          MBB->moveAfter(PredBB);
1327          MadeChange = true;
1328          goto ReoptimizeBlock;
1329        }
1330      }
1331    }
1332
1333    if (!CurFallsThru) {
1334      // Check all successors to see if we can move this block before it.
1335      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1336           E = MBB->succ_end(); SI != E; ++SI) {
1337        // Analyze the branch at the end of the block before the succ.
1338        MachineBasicBlock *SuccBB = *SI;
1339        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1340
1341        // If this block doesn't already fall-through to that successor, and if
1342        // the succ doesn't already have a block that can fall through into it,
1343        // and if the successor isn't an EH destination, we can arrange for the
1344        // fallthrough to happen.
1345        if (SuccBB != MBB && &*SuccPrev != MBB &&
1346            !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1347            !SuccBB->isLandingPad()) {
1348          MBB->moveBefore(SuccBB);
1349          MadeChange = true;
1350          goto ReoptimizeBlock;
1351        }
1352      }
1353
1354      // Okay, there is no really great place to put this block.  If, however,
1355      // the block before this one would be a fall-through if this block were
1356      // removed, move this block to the end of the function.
1357      MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
1358      SmallVector<MachineOperand, 4> PrevCond;
1359      if (FallThrough != MF.end() &&
1360          !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1361          PrevBB.isSuccessor(FallThrough)) {
1362        MBB->moveAfter(--MF.end());
1363        MadeChange = true;
1364        return MadeChange;
1365      }
1366    }
1367  }
1368
1369  return MadeChange;
1370}
1371