BranchFolding.cpp revision 154e1047184384afd0a701a9f8816459cf0b3490
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#include "llvm/CodeGen/Passes.h"
20#include "llvm/CodeGen/MachineDebugInfo.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineJumpTableInfo.h"
23#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/STLExtras.h"
28#include <algorithm>
29using namespace llvm;
30
31static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
32static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
33static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
34static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
35
36namespace {
37  struct BranchFolder : public MachineFunctionPass {
38    virtual bool runOnMachineFunction(MachineFunction &MF);
39    virtual const char *getPassName() const { return "Control Flow Optimizer"; }
40    const TargetInstrInfo *TII;
41    MachineDebugInfo *MDI;
42    bool MadeChange;
43  private:
44    // Tail Merging.
45    bool TailMergeBlocks(MachineFunction &MF);
46    void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
47                                 MachineBasicBlock *NewDest);
48    MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
49                                  MachineBasicBlock::iterator BBI1);
50
51    // Branch optzn.
52    bool OptimizeBranches(MachineFunction &MF);
53    void OptimizeBlock(MachineBasicBlock *MBB);
54    void RemoveDeadBlock(MachineBasicBlock *MBB);
55
56    bool CanFallThrough(MachineBasicBlock *CurBB);
57    bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
58                        MachineBasicBlock *TBB, MachineBasicBlock *FBB,
59                        const std::vector<MachineOperand> &Cond);
60  };
61}
62
63FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
64
65/// RemoveDeadBlock - Remove the specified dead machine basic block from the
66/// function, updating the CFG.
67void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
68  assert(MBB->pred_empty() && "MBB must be dead!");
69
70  MachineFunction *MF = MBB->getParent();
71  // drop all successors.
72  while (!MBB->succ_empty())
73    MBB->removeSuccessor(MBB->succ_end()-1);
74
75  // If there is DWARF info to active, check to see if there are any DWARF_LABEL
76  // records in the basic block.  If so, unregister them from MachineDebugInfo.
77  if (MDI && !MBB->empty()) {
78    unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
79    assert(DWARF_LABELOpc &&
80           "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
81
82    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
83         I != E; ++I) {
84      if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
85        // The label ID # is always operand #0, an immediate.
86        MDI->InvalidateLabel(I->getOperand(0).getImm());
87      }
88    }
89  }
90
91  // Remove the block.
92  MF->getBasicBlockList().erase(MBB);
93}
94
95bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
96  TII = MF.getTarget().getInstrInfo();
97  if (!TII) return false;
98
99  MDI = getAnalysisToUpdate<MachineDebugInfo>();
100
101  bool EverMadeChange = false;
102  bool MadeChangeThisIteration = true;
103  while (MadeChangeThisIteration) {
104    MadeChangeThisIteration = false;
105    MadeChangeThisIteration |= TailMergeBlocks(MF);
106    MadeChangeThisIteration |= OptimizeBranches(MF);
107    EverMadeChange |= MadeChangeThisIteration;
108  }
109
110  // See if any jump tables have become mergable or dead as the code generator
111  // did its thing.
112  MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
113  const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
114  if (!JTs.empty()) {
115    // Figure out how these jump tables should be merged.
116    std::vector<unsigned> JTMapping;
117    JTMapping.reserve(JTs.size());
118
119    // We always keep the 0th jump table.
120    JTMapping.push_back(0);
121
122    // Scan the jump tables, seeing if there are any duplicates.  Note that this
123    // is N^2, which should be fixed someday.
124    for (unsigned i = 1, e = JTs.size(); i != e; ++i)
125      JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
126
127    // If a jump table was merge with another one, walk the function rewriting
128    // references to jump tables to reference the new JT ID's.  Keep track of
129    // whether we see a jump table idx, if not, we can delete the JT.
130    std::vector<bool> JTIsLive;
131    JTIsLive.resize(JTs.size());
132    for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
133         BB != E; ++BB) {
134      for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
135           I != E; ++I)
136        for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
137          MachineOperand &Op = I->getOperand(op);
138          if (!Op.isJumpTableIndex()) continue;
139          unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
140          Op.setJumpTableIndex(NewIdx);
141
142          // Remember that this JT is live.
143          JTIsLive[NewIdx] = true;
144        }
145    }
146
147    // Finally, remove dead jump tables.  This happens either because the
148    // indirect jump was unreachable (and thus deleted) or because the jump
149    // table was merged with some other one.
150    for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
151      if (!JTIsLive[i]) {
152        JTI->RemoveJumpTable(i);
153        EverMadeChange = true;
154      }
155  }
156
157  return EverMadeChange;
158}
159
160//===----------------------------------------------------------------------===//
161//  Tail Merging of Blocks
162//===----------------------------------------------------------------------===//
163
164/// HashMachineInstr - Compute a hash value for MI and its operands.
165static unsigned HashMachineInstr(const MachineInstr *MI) {
166  unsigned Hash = MI->getOpcode();
167  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
168    const MachineOperand &Op = MI->getOperand(i);
169
170    // Merge in bits from the operand if easy.
171    unsigned OperandHash = 0;
172    switch (Op.getType()) {
173    case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
174    case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
175    case MachineOperand::MO_MachineBasicBlock:
176      OperandHash = Op.getMachineBasicBlock()->getNumber();
177      break;
178    case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
179    case MachineOperand::MO_ConstantPoolIndex:
180      OperandHash = Op.getConstantPoolIndex();
181      break;
182    case MachineOperand::MO_JumpTableIndex:
183      OperandHash = Op.getJumpTableIndex();
184      break;
185    case MachineOperand::MO_GlobalAddress:
186    case MachineOperand::MO_ExternalSymbol:
187      // Global address / external symbol are too hard, don't bother, but do
188      // pull in the offset.
189      OperandHash = Op.getOffset();
190      break;
191    default: break;
192    }
193
194    Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
195  }
196  return Hash;
197}
198
199/// HashEndOfMBB - Hash the last two instructions in the MBB.  We hash two
200/// instructions, because cross-jumping only saves code when at least two
201/// instructions are removed (since a branch must be inserted).
202static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
203  MachineBasicBlock::const_iterator I = MBB->end();
204  if (I == MBB->begin())
205    return 0;   // Empty MBB.
206
207  --I;
208  unsigned Hash = HashMachineInstr(I);
209
210  if (I == MBB->begin())
211    return Hash;   // Single instr MBB.
212
213  --I;
214  // Hash in the second-to-last instruction.
215  Hash ^= HashMachineInstr(I) << 2;
216  return Hash;
217}
218
219/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
220/// of instructions they actually have in common together at their end.  Return
221/// iterators for the first shared instruction in each block.
222static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
223                                        MachineBasicBlock *MBB2,
224                                        MachineBasicBlock::iterator &I1,
225                                        MachineBasicBlock::iterator &I2) {
226  I1 = MBB1->end();
227  I2 = MBB2->end();
228
229  unsigned TailLen = 0;
230  while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
231    --I1; --I2;
232    if (!I1->isIdenticalTo(I2)) {
233      ++I1; ++I2;
234      break;
235    }
236    ++TailLen;
237  }
238  return TailLen;
239}
240
241/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
242/// after it, replacing it with an unconditional branch to NewDest.  This
243/// returns true if OldInst's block is modified, false if NewDest is modified.
244void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
245                                           MachineBasicBlock *NewDest) {
246  MachineBasicBlock *OldBB = OldInst->getParent();
247
248  // Remove all the old successors of OldBB from the CFG.
249  while (!OldBB->succ_empty())
250    OldBB->removeSuccessor(OldBB->succ_begin());
251
252  // Remove all the dead instructions from the end of OldBB.
253  OldBB->erase(OldInst, OldBB->end());
254
255  // If OldBB isn't immediately before OldBB, insert a branch to it.
256  if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
257    TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
258  OldBB->addSuccessor(NewDest);
259  ++NumTailMerge;
260}
261
262/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
263/// MBB so that the part before the iterator falls into the part starting at the
264/// iterator.  This returns the new MBB.
265MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
266                                            MachineBasicBlock::iterator BBI1) {
267  // Create the fall-through block.
268  MachineFunction::iterator MBBI = &CurMBB;
269  MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
270  CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
271
272  // Move all the successors of this block to the specified block.
273  while (!CurMBB.succ_empty()) {
274    MachineBasicBlock *S = *(CurMBB.succ_end()-1);
275    NewMBB->addSuccessor(S);
276    CurMBB.removeSuccessor(S);
277  }
278
279  // Add an edge from CurMBB to NewMBB for the fall-through.
280  CurMBB.addSuccessor(NewMBB);
281
282  // Splice the code over.
283  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
284  return NewMBB;
285}
286
287/// EstimateRuntime - Make a rough estimate for how long it will take to run
288/// the specified code.
289static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
290                                MachineBasicBlock::iterator E,
291                                const TargetInstrInfo *TII) {
292  unsigned Time = 0;
293  for (; I != E; ++I) {
294    const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
295    if (TID.Flags & M_CALL_FLAG)
296      Time += 10;
297    else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
298      Time += 2;
299    else
300      ++Time;
301  }
302  return Time;
303}
304
305/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
306/// MBB2I and then insert an unconditional branch in the other block.  Determine
307/// which is the best to split
308static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
309                                  MachineBasicBlock::iterator MBB1I,
310                                  MachineBasicBlock *MBB2,
311                                  MachineBasicBlock::iterator MBB2I,
312                                  const TargetInstrInfo *TII) {
313  // TODO: if we had some notion of which block was hotter, we could split
314  // the hot block, so it is the fall-through.  Since we don't have profile info
315  // make a decision based on which will hurt most to split.
316  unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
317  unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
318
319  // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
320  // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
321  // have a lower overall impact on the program execution.
322  return MBB1Time < MBB2Time;
323}
324
325bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
326  MadeChange = false;
327
328  if (!EnableTailMerge) return false;
329
330  // Find blocks with no successors.
331  std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
332  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
333    if (I->succ_empty())
334      MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
335  }
336
337  // Sort by hash value so that blocks with identical end sequences sort
338  // together.
339  std::stable_sort(MergePotentials.begin(), MergePotentials.end());
340
341  // Walk through equivalence sets looking for actual exact matches.
342  while (MergePotentials.size() > 1) {
343    unsigned CurHash  = (MergePotentials.end()-1)->first;
344    unsigned PrevHash = (MergePotentials.end()-2)->first;
345    MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
346
347    // If there is nothing that matches the hash of the current basic block,
348    // give up.
349    if (CurHash != PrevHash) {
350      MergePotentials.pop_back();
351      continue;
352    }
353
354    // Determine the actual length of the shared tail between these two basic
355    // blocks.  Because the hash can have collisions, it's possible that this is
356    // less than 2.
357    MachineBasicBlock::iterator BBI1, BBI2;
358    unsigned CommonTailLen =
359      ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
360                              BBI1, BBI2);
361
362    // If the tails don't have at least two instructions in common, see if there
363    // is anything else in the equivalence class that does match.
364    if (CommonTailLen < 2) {
365      unsigned FoundMatch = ~0U;
366      for (int i = MergePotentials.size()-2;
367           i != -1 && MergePotentials[i].first == CurHash; --i) {
368        CommonTailLen = ComputeCommonTailLength(CurMBB,
369                                                MergePotentials[i].second,
370                                                BBI1, BBI2);
371        if (CommonTailLen >= 2) {
372          FoundMatch = i;
373          break;
374        }
375      }
376
377      // If we didn't find anything that has at least two instructions matching
378      // this one, bail out.
379      if (FoundMatch == ~0U) {
380        MergePotentials.pop_back();
381        continue;
382      }
383
384      // Otherwise, move the matching block to the right position.
385      std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
386    }
387
388    MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
389
390    // If neither block is the entire common tail, split the tail of one block
391    // to make it redundant with the other tail.
392    if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
393      if (0) { // Enable this to disable partial tail merges.
394        MergePotentials.pop_back();
395        continue;
396      }
397
398      // Decide whether we want to split CurMBB or MBB2.
399      if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
400        CurMBB = SplitMBBAt(*CurMBB, BBI1);
401        BBI1 = CurMBB->begin();
402        MergePotentials.back().second = CurMBB;
403      } else {
404        MBB2 = SplitMBBAt(*MBB2, BBI2);
405        BBI2 = MBB2->begin();
406        (MergePotentials.end()-2)->second = MBB2;
407      }
408    }
409
410    if (MBB2->begin() == BBI2) {
411      // Hack the end off CurMBB, making it jump to MBBI@ instead.
412      ReplaceTailWithBranchTo(BBI1, MBB2);
413      // This modifies CurMBB, so remove it from the worklist.
414      MergePotentials.pop_back();
415    } else {
416      assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
417      // Hack the end off MBB2, making it jump to CurMBB instead.
418      ReplaceTailWithBranchTo(BBI2, CurMBB);
419      // This modifies MBB2, so remove it from the worklist.
420      MergePotentials.erase(MergePotentials.end()-2);
421    }
422    MadeChange = true;
423  }
424
425  return MadeChange;
426}
427
428
429//===----------------------------------------------------------------------===//
430//  Branch Optimization
431//===----------------------------------------------------------------------===//
432
433bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
434  MadeChange = false;
435
436  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
437    MachineBasicBlock *MBB = I++;
438    OptimizeBlock(MBB);
439
440    // If it is dead, remove it.
441    if (MBB->pred_empty()) {
442      RemoveDeadBlock(MBB);
443      MadeChange = true;
444      ++NumDeadBlocks;
445    }
446  }
447  return MadeChange;
448}
449
450
451/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
452/// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
453/// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
454/// be null.
455static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
456                                 MachineBasicBlock *DestA,
457                                 MachineBasicBlock *DestB,
458                                 bool isCond,
459                                 MachineFunction::iterator FallThru) {
460  bool MadeChange = false;
461  bool AddedFallThrough = false;
462
463  // If this block ends with a conditional branch that falls through to its
464  // successor, set DestB as the successor.
465  if (isCond) {
466    if (DestB == 0 && FallThru != MBB.getParent()->end()) {
467      DestB = FallThru;
468      AddedFallThrough = true;
469    }
470  } else {
471    // If this is an unconditional branch with no explicit dest, it must just be
472    // a fallthrough into DestB.
473    if (DestA == 0 && FallThru != MBB.getParent()->end()) {
474      DestA = FallThru;
475      AddedFallThrough = true;
476    }
477  }
478
479  MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
480  while (SI != MBB.succ_end()) {
481    if (*SI == DestA) {
482      DestA = 0;
483      ++SI;
484    } else if (*SI == DestB) {
485      DestB = 0;
486      ++SI;
487    } else {
488      // Otherwise, this is a superfluous edge, remove it.
489      MBB.removeSuccessor(SI);
490      MadeChange = true;
491    }
492  }
493  if (!AddedFallThrough) {
494    assert(DestA == 0 && DestB == 0 &&
495           "MachineCFG is missing edges!");
496  } else if (isCond) {
497    assert(DestA == 0 && "MachineCFG is missing edges!");
498  }
499  return MadeChange;
500}
501
502
503/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
504/// 'Old', change the code and CFG so that it branches to 'New' instead.
505static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
506                                   MachineBasicBlock *Old,
507                                   MachineBasicBlock *New,
508                                   const TargetInstrInfo *TII) {
509  assert(Old != New && "Cannot replace self with self!");
510
511  MachineBasicBlock::iterator I = BB->end();
512  while (I != BB->begin()) {
513    --I;
514    if (!TII->isTerminatorInstr(I->getOpcode())) break;
515
516    // Scan the operands of this machine instruction, replacing any uses of Old
517    // with New.
518    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
519      if (I->getOperand(i).isMachineBasicBlock() &&
520          I->getOperand(i).getMachineBasicBlock() == Old)
521        I->getOperand(i).setMachineBasicBlock(New);
522  }
523
524  // Update the successor information.
525  std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
526  for (int i = Succs.size()-1; i >= 0; --i)
527    if (Succs[i] == Old) {
528      BB->removeSuccessor(Old);
529      BB->addSuccessor(New);
530    }
531}
532
533/// CanFallThrough - Return true if the specified block (with the specified
534/// branch condition) can implicitly transfer control to the block after it by
535/// falling off the end of it.  This should return false if it can reach the
536/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
537///
538/// True is a conservative answer.
539///
540bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
541                                  bool BranchUnAnalyzable,
542                                  MachineBasicBlock *TBB, MachineBasicBlock *FBB,
543                                  const std::vector<MachineOperand> &Cond) {
544  MachineFunction::iterator Fallthrough = CurBB;
545  ++Fallthrough;
546  // If FallthroughBlock is off the end of the function, it can't fall through.
547  if (Fallthrough == CurBB->getParent()->end())
548    return false;
549
550  // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
551  if (!CurBB->isSuccessor(Fallthrough))
552    return false;
553
554  // If we couldn't analyze the branch, assume it could fall through.
555  if (BranchUnAnalyzable) return true;
556
557  // If there is no branch, control always falls through.
558  if (TBB == 0) return true;
559
560  // If there is some explicit branch to the fallthrough block, it can obviously
561  // reach, even though the branch should get folded to fall through implicitly.
562  if (MachineFunction::iterator(TBB) == Fallthrough ||
563      MachineFunction::iterator(FBB) == Fallthrough)
564    return true;
565
566  // If it's an unconditional branch to some block not the fall through, it
567  // doesn't fall through.
568  if (Cond.empty()) return false;
569
570  // Otherwise, if it is conditional and has no explicit false block, it falls
571  // through.
572  return FBB == 0;
573}
574
575/// CanFallThrough - Return true if the specified can implicitly transfer
576/// control to the block after it by falling off the end of it.  This should
577/// return false if it can reach the block after it, but it uses an explicit
578/// branch to do so (e.g. a table jump).
579///
580/// True is a conservative answer.
581///
582bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
583  MachineBasicBlock *TBB = 0, *FBB = 0;
584  std::vector<MachineOperand> Cond;
585  bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
586  return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
587}
588
589/// IsBetterFallthrough - Return true if it would be clearly better to
590/// fall-through to MBB1 than to fall through into MBB2.  This has to return
591/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
592/// result in infinite loops.
593static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
594                                MachineBasicBlock *MBB2,
595                                const TargetInstrInfo &TII) {
596  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
597  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
598  // optimize branches that branch to either a return block or an assert block
599  // into a fallthrough to the return.
600  if (MBB1->empty() || MBB2->empty()) return false;
601
602  MachineInstr *MBB1I = --MBB1->end();
603  MachineInstr *MBB2I = --MBB2->end();
604  return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
605}
606
607/// OptimizeBlock - Analyze and optimize control flow related to the specified
608/// block.  This is never called on the entry block.
609void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
610  MachineFunction::iterator FallThrough = MBB;
611  ++FallThrough;
612
613  // If this block is empty, make everyone use its fall-through, not the block
614  // explicitly.
615  if (MBB->empty()) {
616    // Dead block?  Leave for cleanup later.
617    if (MBB->pred_empty()) return;
618
619    if (FallThrough == MBB->getParent()->end()) {
620      // TODO: Simplify preds to not branch here if possible!
621    } else {
622      // Rewrite all predecessors of the old block to go to the fallthrough
623      // instead.
624      while (!MBB->pred_empty()) {
625        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
626        ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
627      }
628
629      // If MBB was the target of a jump table, update jump tables to go to the
630      // fallthrough instead.
631      MBB->getParent()->getJumpTableInfo()->
632        ReplaceMBBInJumpTables(MBB, FallThrough);
633      MadeChange = true;
634    }
635    return;
636  }
637
638  // Check to see if we can simplify the terminator of the block before this
639  // one.
640  MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
641
642  MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
643  std::vector<MachineOperand> PriorCond;
644  bool PriorUnAnalyzable =
645    TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
646  if (!PriorUnAnalyzable) {
647    // If the CFG for the prior block has extra edges, remove them.
648    MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
649                                       !PriorCond.empty(), MBB);
650
651    // If the previous branch is conditional and both conditions go to the same
652    // destination, remove the branch, replacing it with an unconditional one or
653    // a fall-through.
654    if (PriorTBB && PriorTBB == PriorFBB) {
655      TII->RemoveBranch(PrevBB);
656      PriorCond.clear();
657      if (PriorTBB != MBB)
658        TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
659      MadeChange = true;
660      ++NumBranchOpts;
661      return OptimizeBlock(MBB);
662    }
663
664    // If the previous branch *only* branches to *this* block (conditional or
665    // not) remove the branch.
666    if (PriorTBB == MBB && PriorFBB == 0) {
667      TII->RemoveBranch(PrevBB);
668      MadeChange = true;
669      ++NumBranchOpts;
670      return OptimizeBlock(MBB);
671    }
672
673    // If the prior block branches somewhere else on the condition and here if
674    // the condition is false, remove the uncond second branch.
675    if (PriorFBB == MBB) {
676      TII->RemoveBranch(PrevBB);
677      TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
678      MadeChange = true;
679      ++NumBranchOpts;
680      return OptimizeBlock(MBB);
681    }
682
683    // If the prior block branches here on true and somewhere else on false, and
684    // if the branch condition is reversible, reverse the branch to create a
685    // fall-through.
686    if (PriorTBB == MBB) {
687      std::vector<MachineOperand> NewPriorCond(PriorCond);
688      if (!TII->ReverseBranchCondition(NewPriorCond)) {
689        TII->RemoveBranch(PrevBB);
690        TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
691        MadeChange = true;
692        ++NumBranchOpts;
693        return OptimizeBlock(MBB);
694      }
695    }
696
697    // If this block doesn't fall through (e.g. it ends with an uncond branch or
698    // has no successors) and if the pred falls through into this block, and if
699    // it would otherwise fall through into the block after this, move this
700    // block to the end of the function.
701    //
702    // We consider it more likely that execution will stay in the function (e.g.
703    // due to loops) than it is to exit it.  This asserts in loops etc, moving
704    // the assert condition out of the loop body.
705    if (!PriorCond.empty() && PriorFBB == 0 &&
706        MachineFunction::iterator(PriorTBB) == FallThrough &&
707        !CanFallThrough(MBB)) {
708      // We have to be careful that the succs of PredBB aren't both no-successor
709      // blocks.  If neither have successors and if PredBB is the second from
710      // last block in the function, we'd just keep swapping the two blocks for
711      // last.  Only do the swap if one is clearly better to fall through than
712      // the other.
713      if (FallThrough != --MBB->getParent()->end() ||
714          IsBetterFallthrough(PriorTBB, MBB, *TII)) {
715
716        // Reverse the branch so we will fall through on the previous true cond.
717        std::vector<MachineOperand> NewPriorCond(PriorCond);
718        if (!TII->ReverseBranchCondition(NewPriorCond)) {
719          TII->RemoveBranch(PrevBB);
720          TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
721
722          // Move this block to the end of the function.
723          MBB->moveAfter(--MBB->getParent()->end());
724          MadeChange = true;
725          ++NumBranchOpts;
726          return;
727        }
728      }
729    }
730  }
731
732  // Analyze the branch in the current block.
733  MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
734  std::vector<MachineOperand> CurCond;
735  bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
736  if (!CurUnAnalyzable) {
737    // If the CFG for the prior block has extra edges, remove them.
738    MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
739                                       !CurCond.empty(),
740                                       ++MachineFunction::iterator(MBB));
741
742    // If this is a two-way branch, and the FBB branches to this block, reverse
743    // the condition so the single-basic-block loop is faster.  Instead of:
744    //    Loop: xxx; jcc Out; jmp Loop
745    // we want:
746    //    Loop: xxx; jncc Loop; jmp Out
747    if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
748      std::vector<MachineOperand> NewCond(CurCond);
749      if (!TII->ReverseBranchCondition(NewCond)) {
750        TII->RemoveBranch(*MBB);
751        TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
752        MadeChange = true;
753        ++NumBranchOpts;
754        return OptimizeBlock(MBB);
755      }
756    }
757
758
759    // If this branch is the only thing in its block, see if we can forward
760    // other blocks across it.
761    if (CurTBB && CurCond.empty() && CurFBB == 0 &&
762        TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
763      // This block may contain just an unconditional branch.  Because there can
764      // be 'non-branch terminators' in the block, try removing the branch and
765      // then seeing if the block is empty.
766      TII->RemoveBranch(*MBB);
767
768      // If this block is just an unconditional branch to CurTBB, we can
769      // usually completely eliminate the block.  The only case we cannot
770      // completely eliminate the block is when the block before this one
771      // falls through into MBB and we can't understand the prior block's branch
772      // condition.
773      if (MBB->empty()) {
774        bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
775        if (PredHasNoFallThrough || !PriorUnAnalyzable ||
776            !PrevBB.isSuccessor(MBB)) {
777          // If the prior block falls through into us, turn it into an
778          // explicit branch to us to make updates simpler.
779          if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
780              PriorTBB != MBB && PriorFBB != MBB) {
781            if (PriorTBB == 0) {
782              assert(PriorCond.empty() && PriorFBB == 0 &&
783                     "Bad branch analysis");
784              PriorTBB = MBB;
785            } else {
786              assert(PriorFBB == 0 && "Machine CFG out of date!");
787              PriorFBB = MBB;
788            }
789            TII->RemoveBranch(PrevBB);
790            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
791          }
792
793          // Iterate through all the predecessors, revectoring each in-turn.
794          MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
795          bool DidChange = false;
796          bool HasBranchToSelf = false;
797          while (PI != MBB->pred_end()) {
798            if (*PI == MBB) {
799              // If this block has an uncond branch to itself, leave it.
800              ++PI;
801              HasBranchToSelf = true;
802            } else {
803              DidChange = true;
804              ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
805            }
806          }
807
808          // Change any jumptables to go to the new MBB.
809          MBB->getParent()->getJumpTableInfo()->
810            ReplaceMBBInJumpTables(MBB, CurTBB);
811          if (DidChange) {
812            ++NumBranchOpts;
813            MadeChange = true;
814            if (!HasBranchToSelf) return;
815          }
816        }
817      }
818
819      // Add the branch back if the block is more than just an uncond branch.
820      TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
821    }
822  }
823
824  // If the prior block doesn't fall through into this block, and if this
825  // block doesn't fall through into some other block, see if we can find a
826  // place to move this block where a fall-through will happen.
827  if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
828                      PriorTBB, PriorFBB, PriorCond)) {
829    // Now we know that there was no fall-through into this block, check to
830    // see if it has a fall-through into its successor.
831    if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
832      // Check all the predecessors of this block.  If one of them has no fall
833      // throughs, move this block right after it.
834      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
835           E = MBB->pred_end(); PI != E; ++PI) {
836        // Analyze the branch at the end of the pred.
837        MachineBasicBlock *PredBB = *PI;
838        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
839        std::vector<MachineOperand> PredCond;
840        if (PredBB != MBB && !CanFallThrough(PredBB)) {
841          MBB->moveAfter(PredBB);
842          MadeChange = true;
843          return OptimizeBlock(MBB);
844        }
845      }
846
847      // Check all successors to see if we can move this block before it.
848      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
849           E = MBB->succ_end(); SI != E; ++SI) {
850        // Analyze the branch at the end of the block before the succ.
851        MachineBasicBlock *SuccBB = *SI;
852        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
853        std::vector<MachineOperand> SuccPrevCond;
854        if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
855          MBB->moveBefore(SuccBB);
856          MadeChange = true;
857          return OptimizeBlock(MBB);
858        }
859      }
860
861      // Okay, there is no really great place to put this block.  If, however,
862      // the block before this one would be a fall-through if this block were
863      // removed, move this block to the end of the function.
864      if (FallThrough != MBB->getParent()->end() &&
865          PrevBB.isSuccessor(FallThrough)) {
866        MBB->moveAfter(--MBB->getParent()->end());
867        MadeChange = true;
868        return;
869      }
870    }
871  }
872}
873