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