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