BranchFolding.cpp revision 80629c85f1041df41b5158ebb03a4725af6ecd90
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    explicit 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->getOpcode() == TargetInstrInfo::INLINEASM) {
276      ++I1; ++I2;
277      break;
278    }
279    ++TailLen;
280  }
281  return TailLen;
282}
283
284/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
285/// after it, replacing it with an unconditional branch to NewDest.  This
286/// returns true if OldInst's block is modified, false if NewDest is modified.
287void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
288                                           MachineBasicBlock *NewDest) {
289  MachineBasicBlock *OldBB = OldInst->getParent();
290
291  // Remove all the old successors of OldBB from the CFG.
292  while (!OldBB->succ_empty())
293    OldBB->removeSuccessor(OldBB->succ_begin());
294
295  // Remove all the dead instructions from the end of OldBB.
296  OldBB->erase(OldInst, OldBB->end());
297
298  // If OldBB isn't immediately before OldBB, insert a branch to it.
299  if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
300    TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
301  OldBB->addSuccessor(NewDest);
302  ++NumTailMerge;
303}
304
305/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
306/// MBB so that the part before the iterator falls into the part starting at the
307/// iterator.  This returns the new MBB.
308MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
309                                            MachineBasicBlock::iterator BBI1) {
310  // Create the fall-through block.
311  MachineFunction::iterator MBBI = &CurMBB;
312  MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
313  CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
314
315  // Move all the successors of this block to the specified block.
316  while (!CurMBB.succ_empty()) {
317    MachineBasicBlock *S = *(CurMBB.succ_end()-1);
318    NewMBB->addSuccessor(S);
319    CurMBB.removeSuccessor(S);
320  }
321
322  // Add an edge from CurMBB to NewMBB for the fall-through.
323  CurMBB.addSuccessor(NewMBB);
324
325  // Splice the code over.
326  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
327
328  // For targets that use the register scavenger, we must maintain LiveIns.
329  if (RS) {
330    RS->enterBasicBlock(&CurMBB);
331    if (!CurMBB.empty())
332      RS->forward(prior(CurMBB.end()));
333    BitVector RegsLiveAtExit(RegInfo->getNumRegs());
334    RS->getRegsUsed(RegsLiveAtExit, false);
335    for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
336      if (RegsLiveAtExit[i])
337        NewMBB->addLiveIn(i);
338  }
339
340  return NewMBB;
341}
342
343/// EstimateRuntime - Make a rough estimate for how long it will take to run
344/// the specified code.
345static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
346                                MachineBasicBlock::iterator E,
347                                const TargetInstrInfo *TII) {
348  unsigned Time = 0;
349  for (; I != E; ++I) {
350    const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
351    if (TID.Flags & M_CALL_FLAG)
352      Time += 10;
353    else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
354      Time += 2;
355    else
356      ++Time;
357  }
358  return Time;
359}
360
361/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
362/// MBB2I and then insert an unconditional branch in the other block.  Determine
363/// which is the best to split
364static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
365                                  MachineBasicBlock::iterator MBB1I,
366                                  MachineBasicBlock *MBB2,
367                                  MachineBasicBlock::iterator MBB2I,
368                                  const TargetInstrInfo *TII,
369                                  MachineBasicBlock *PredBB) {
370  // If one block is the entry block, split the other one; we can't generate
371  // a branch to the entry block, as its label is not emitted.
372  MachineBasicBlock *Entry = MBB1->getParent()->begin();
373  if (MBB1 == Entry)
374    return false;
375  if (MBB2 == Entry)
376    return true;
377
378  // If one block falls through into the common successor, choose that
379  // one to split; it is one instruction less to do that.
380  if (PredBB) {
381    if (MBB1 == PredBB)
382      return true;
383    else if (MBB2 == PredBB)
384      return false;
385  }
386  // TODO: if we had some notion of which block was hotter, we could split
387  // the hot block, so it is the fall-through.  Since we don't have profile info
388  // make a decision based on which will hurt most to split.
389  unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
390  unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
391
392  // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
393  // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
394  // have a lower overall impact on the program execution.
395  return MBB1Time < MBB2Time;
396}
397
398// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
399// branches temporarily for tail merging).  In the case where CurMBB ends
400// with a conditional branch to the next block, optimize by reversing the
401// test and conditionally branching to SuccMBB instead.
402
403static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
404                    const TargetInstrInfo *TII) {
405  MachineFunction *MF = CurMBB->getParent();
406  MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
407  MachineBasicBlock *TBB = 0, *FBB = 0;
408  std::vector<MachineOperand> Cond;
409  if (I != MF->end() &&
410      !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
411    MachineBasicBlock *NextBB = I;
412    if (TBB == NextBB && Cond.size() && !FBB) {
413      if (!TII->ReverseBranchCondition(Cond)) {
414        TII->RemoveBranch(*CurMBB);
415        TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
416        return;
417      }
418    }
419  }
420  TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
421}
422
423static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
424                         const std::pair<unsigned,MachineBasicBlock*> &q) {
425    if (p.first < q.first)
426      return true;
427     else if (p.first > q.first)
428      return false;
429    else if (p.second->getNumber() < q.second->getNumber())
430      return true;
431    else if (p.second->getNumber() > q.second->getNumber())
432      return false;
433    else {
434      // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
435      // an object with itself.
436#ifndef _GLIBCXX_DEBUG
437      assert(0 && "Predecessor appears twice");
438#endif
439      return(false);
440    }
441}
442
443// See if any of the blocks in MergePotentials (which all have a common single
444// successor, or all have no successor) can be tail-merged.  If there is a
445// successor, any blocks in MergePotentials that are not tail-merged and
446// are not immediately before Succ must have an unconditional branch to
447// Succ added (but the predecessor/successor lists need no adjustment).
448// The lone predecessor of Succ that falls through into Succ,
449// if any, is given in PredBB.
450
451bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
452                                  MachineBasicBlock* PredBB) {
453  unsigned minCommonTailLength = (SuccBB ? 1 : 2);
454  MadeChange = false;
455
456  // Sort by hash value so that blocks with identical end sequences sort
457  // together.
458  std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
459
460  // Walk through equivalence sets looking for actual exact matches.
461  while (MergePotentials.size() > 1) {
462    unsigned CurHash  = (MergePotentials.end()-1)->first;
463    unsigned PrevHash = (MergePotentials.end()-2)->first;
464    MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
465
466    // If there is nothing that matches the hash of the current basic block,
467    // give up.
468    if (CurHash != PrevHash) {
469      if (SuccBB && CurMBB != PredBB)
470        FixTail(CurMBB, SuccBB, TII);
471      MergePotentials.pop_back();
472      continue;
473    }
474
475    // Look through all the pairs of blocks that have the same hash as this
476    // one, and find the pair that has the largest number of instructions in
477    // common.
478     // Since instructions may get combined later (e.g. single stores into
479    // store multiple) this measure is not particularly accurate.
480   MachineBasicBlock::iterator BBI1, BBI2;
481
482    unsigned FoundI = ~0U, FoundJ = ~0U;
483    unsigned maxCommonTailLength = 0U;
484    for (int i = MergePotentials.size()-1;
485         i != -1 && MergePotentials[i].first == CurHash; --i) {
486      for (int j = i-1;
487           j != -1 && MergePotentials[j].first == CurHash; --j) {
488        MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
489        unsigned CommonTailLen = ComputeCommonTailLength(
490                                                MergePotentials[i].second,
491                                                MergePotentials[j].second,
492                                                TrialBBI1, TrialBBI2);
493        if (CommonTailLen >= minCommonTailLength &&
494            CommonTailLen > maxCommonTailLength) {
495          FoundI = i;
496          FoundJ = j;
497          maxCommonTailLength = CommonTailLen;
498          BBI1 = TrialBBI1;
499          BBI2 = TrialBBI2;
500        }
501      }
502    }
503
504    // If we didn't find any pair that has at least minCommonTailLength
505    // instructions in common, bail out.  All entries with this
506    // hash code can go away now.
507    if (FoundI == ~0U) {
508      for (int i = MergePotentials.size()-1;
509           i != -1 && MergePotentials[i].first == CurHash; --i) {
510        // Put the unconditional branch back, if we need one.
511        CurMBB = MergePotentials[i].second;
512        if (SuccBB && CurMBB != PredBB)
513          FixTail(CurMBB, SuccBB, TII);
514        MergePotentials.pop_back();
515      }
516      continue;
517    }
518
519    // Otherwise, move the block(s) to the right position(s).  So that
520    // BBI1/2 will be valid, the last must be I and the next-to-last J.
521    if (FoundI != MergePotentials.size()-1)
522      std::swap(MergePotentials[FoundI], *(MergePotentials.end()-1));
523    if (FoundJ != MergePotentials.size()-2)
524      std::swap(MergePotentials[FoundJ], *(MergePotentials.end()-2));
525
526    CurMBB = (MergePotentials.end()-1)->second;
527    MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
528
529    // If neither block is the entire common tail, split the tail of one block
530    // to make it redundant with the other tail.  Also, we cannot jump to the
531    // entry block, so if one block is the entry block, split the other one.
532    MachineBasicBlock *Entry = CurMBB->getParent()->begin();
533    if (CurMBB->begin() == BBI1 && CurMBB != Entry)
534      ;   // CurMBB is common tail
535    else if (MBB2->begin() == BBI2 && MBB2 != Entry)
536      ;   // MBB2 is common tail
537    else {
538      if (0) { // Enable this to disable partial tail merges.
539        MergePotentials.pop_back();
540        continue;
541      }
542
543      // Decide whether we want to split CurMBB or MBB2.
544      if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
545        CurMBB = SplitMBBAt(*CurMBB, BBI1);
546        BBI1 = CurMBB->begin();
547        MergePotentials.back().second = CurMBB;
548      } else {
549        MBB2 = SplitMBBAt(*MBB2, BBI2);
550        BBI2 = MBB2->begin();
551        (MergePotentials.end()-2)->second = MBB2;
552      }
553    }
554
555    if (MBB2->begin() == BBI2 && MBB2 != Entry) {
556      // Hack the end off CurMBB, making it jump to MBBI@ instead.
557      ReplaceTailWithBranchTo(BBI1, MBB2);
558      // This modifies CurMBB, so remove it from the worklist.
559      MergePotentials.pop_back();
560    } else {
561      assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
562             "Didn't split block correctly?");
563      // Hack the end off MBB2, making it jump to CurMBB instead.
564      ReplaceTailWithBranchTo(BBI2, CurMBB);
565      // This modifies MBB2, so remove it from the worklist.
566      MergePotentials.erase(MergePotentials.end()-2);
567    }
568    MadeChange = true;
569  }
570  return MadeChange;
571}
572
573bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
574
575  if (!EnableTailMerge) return false;
576
577  MadeChange = false;
578
579  // First find blocks with no successors.
580  MergePotentials.clear();
581  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
582    if (I->succ_empty())
583      MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
584  }
585  // See if we can do any tail merging on those.
586  if (MergePotentials.size() < TailMergeThreshold)
587    MadeChange |= TryMergeBlocks(NULL, NULL);
588
589  // Look at blocks (IBB) with multiple predecessors (PBB).
590  // We change each predecessor to a canonical form, by
591  // (1) temporarily removing any unconditional branch from the predecessor
592  // to IBB, and
593  // (2) alter conditional branches so they branch to the other block
594  // not IBB; this may require adding back an unconditional branch to IBB
595  // later, where there wasn't one coming in.  E.g.
596  //   Bcc IBB
597  //   fallthrough to QBB
598  // here becomes
599  //   Bncc QBB
600  // with a conceptual B to IBB after that, which never actually exists.
601  // With those changes, we see whether the predecessors' tails match,
602  // and merge them if so.  We change things out of canonical form and
603  // back to the way they were later in the process.  (OptimizeBranches
604  // would undo some of this, but we can't use it, because we'd get into
605  // a compile-time infinite loop repeatedly doing and undoing the same
606  // transformations.)
607
608  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
609    if (!I->succ_empty() && I->pred_size() >= 2 &&
610         I->pred_size() < TailMergeThreshold) {
611      MachineBasicBlock *IBB = I;
612      MachineBasicBlock *PredBB = prior(I);
613      MergePotentials.clear();
614      for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
615                                            E2 = I->pred_end();
616           P != E2; ++P) {
617        MachineBasicBlock* PBB = *P;
618        // Skip blocks that loop to themselves, can't tail merge these.
619        if (PBB==IBB)
620          continue;
621        MachineBasicBlock *TBB = 0, *FBB = 0;
622        std::vector<MachineOperand> Cond;
623        if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
624          // Failing case:  IBB is the target of a cbr, and
625          // we cannot reverse the branch.
626          std::vector<MachineOperand> NewCond(Cond);
627          if (Cond.size() && TBB==IBB) {
628            if (TII->ReverseBranchCondition(NewCond))
629              continue;
630            // This is the QBB case described above
631            if (!FBB)
632              FBB = next(MachineFunction::iterator(PBB));
633          }
634          // Failing case:  the only way IBB can be reached from PBB is via
635          // exception handling.  Happens for landing pads.  Would be nice
636          // to have a bit in the edge so we didn't have to do all this.
637          if (IBB->isLandingPad()) {
638            MachineFunction::iterator IP = PBB;  IP++;
639            MachineBasicBlock* PredNextBB = NULL;
640            if (IP!=MF.end())
641              PredNextBB = IP;
642            if (TBB==NULL) {
643              if (IBB!=PredNextBB)      // fallthrough
644                continue;
645            } else if (FBB) {
646              if (TBB!=IBB && FBB!=IBB)   // cbr then ubr
647                continue;
648            } else if (Cond.size() == 0) {
649              if (TBB!=IBB)               // ubr
650                continue;
651            } else {
652              if (TBB!=IBB && IBB!=PredNextBB)  // cbr
653                continue;
654            }
655          }
656          // Remove the unconditional branch at the end, if any.
657          if (TBB && (Cond.size()==0 || FBB)) {
658            TII->RemoveBranch(*PBB);
659            if (Cond.size())
660              // reinsert conditional branch only, for now
661              TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
662          }
663          MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
664        }
665      }
666    if (MergePotentials.size() >= 2)
667      MadeChange |= TryMergeBlocks(I, PredBB);
668    // Reinsert an unconditional branch if needed.
669    // The 1 below can be either an original single predecessor, or a result
670    // of removing blocks in TryMergeBlocks.
671    PredBB = prior(I);      // this may have been changed in TryMergeBlocks
672    if (MergePotentials.size()==1 &&
673        (MergePotentials.begin())->second != PredBB)
674      FixTail((MergePotentials.begin())->second, I, TII);
675    }
676  }
677  return MadeChange;
678}
679
680//===----------------------------------------------------------------------===//
681//  Branch Optimization
682//===----------------------------------------------------------------------===//
683
684bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
685  MadeChange = false;
686
687  // Make sure blocks are numbered in order
688  MF.RenumberBlocks();
689
690  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
691    MachineBasicBlock *MBB = I++;
692    OptimizeBlock(MBB);
693
694    // If it is dead, remove it.
695    if (MBB->pred_empty()) {
696      RemoveDeadBlock(MBB);
697      MadeChange = true;
698      ++NumDeadBlocks;
699    }
700  }
701  return MadeChange;
702}
703
704
705/// CanFallThrough - Return true if the specified block (with the specified
706/// branch condition) can implicitly transfer control to the block after it by
707/// falling off the end of it.  This should return false if it can reach the
708/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
709///
710/// True is a conservative answer.
711///
712bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
713                                  bool BranchUnAnalyzable,
714                                  MachineBasicBlock *TBB, MachineBasicBlock *FBB,
715                                  const std::vector<MachineOperand> &Cond) {
716  MachineFunction::iterator Fallthrough = CurBB;
717  ++Fallthrough;
718  // If FallthroughBlock is off the end of the function, it can't fall through.
719  if (Fallthrough == CurBB->getParent()->end())
720    return false;
721
722  // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
723  if (!CurBB->isSuccessor(Fallthrough))
724    return false;
725
726  // If we couldn't analyze the branch, assume it could fall through.
727  if (BranchUnAnalyzable) return true;
728
729  // If there is no branch, control always falls through.
730  if (TBB == 0) return true;
731
732  // If there is some explicit branch to the fallthrough block, it can obviously
733  // reach, even though the branch should get folded to fall through implicitly.
734  if (MachineFunction::iterator(TBB) == Fallthrough ||
735      MachineFunction::iterator(FBB) == Fallthrough)
736    return true;
737
738  // If it's an unconditional branch to some block not the fall through, it
739  // doesn't fall through.
740  if (Cond.empty()) return false;
741
742  // Otherwise, if it is conditional and has no explicit false block, it falls
743  // through.
744  return FBB == 0;
745}
746
747/// CanFallThrough - Return true if the specified can implicitly transfer
748/// control to the block after it by falling off the end of it.  This should
749/// return false if it can reach the block after it, but it uses an explicit
750/// branch to do so (e.g. a table jump).
751///
752/// True is a conservative answer.
753///
754bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
755  MachineBasicBlock *TBB = 0, *FBB = 0;
756  std::vector<MachineOperand> Cond;
757  bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
758  return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
759}
760
761/// IsBetterFallthrough - Return true if it would be clearly better to
762/// fall-through to MBB1 than to fall through into MBB2.  This has to return
763/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
764/// result in infinite loops.
765static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
766                                MachineBasicBlock *MBB2,
767                                const TargetInstrInfo &TII) {
768  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
769  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
770  // optimize branches that branch to either a return block or an assert block
771  // into a fallthrough to the return.
772  if (MBB1->empty() || MBB2->empty()) return false;
773
774  MachineInstr *MBB1I = --MBB1->end();
775  MachineInstr *MBB2I = --MBB2->end();
776  return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
777}
778
779/// OptimizeBlock - Analyze and optimize control flow related to the specified
780/// block.  This is never called on the entry block.
781void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
782  MachineFunction::iterator FallThrough = MBB;
783  ++FallThrough;
784
785  // If this block is empty, make everyone use its fall-through, not the block
786  // explicitly.  Landing pads should not do this since the landing-pad table
787  // points to this block.
788  if (MBB->empty() && !MBB->isLandingPad()) {
789    // Dead block?  Leave for cleanup later.
790    if (MBB->pred_empty()) return;
791
792    if (FallThrough == MBB->getParent()->end()) {
793      // TODO: Simplify preds to not branch here if possible!
794    } else {
795      // Rewrite all predecessors of the old block to go to the fallthrough
796      // instead.
797      while (!MBB->pred_empty()) {
798        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
799        Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
800      }
801
802      // If MBB was the target of a jump table, update jump tables to go to the
803      // fallthrough instead.
804      MBB->getParent()->getJumpTableInfo()->
805        ReplaceMBBInJumpTables(MBB, FallThrough);
806      MadeChange = true;
807    }
808    return;
809  }
810
811  // Check to see if we can simplify the terminator of the block before this
812  // one.
813  MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
814
815  MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
816  std::vector<MachineOperand> PriorCond;
817  bool PriorUnAnalyzable =
818    TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
819  if (!PriorUnAnalyzable) {
820    // If the CFG for the prior block has extra edges, remove them.
821    MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
822                                              !PriorCond.empty());
823
824    // If the previous branch is conditional and both conditions go to the same
825    // destination, remove the branch, replacing it with an unconditional one or
826    // a fall-through.
827    if (PriorTBB && PriorTBB == PriorFBB) {
828      TII->RemoveBranch(PrevBB);
829      PriorCond.clear();
830      if (PriorTBB != MBB)
831        TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
832      MadeChange = true;
833      ++NumBranchOpts;
834      return OptimizeBlock(MBB);
835    }
836
837    // If the previous branch *only* branches to *this* block (conditional or
838    // not) remove the branch.
839    if (PriorTBB == MBB && PriorFBB == 0) {
840      TII->RemoveBranch(PrevBB);
841      MadeChange = true;
842      ++NumBranchOpts;
843      return OptimizeBlock(MBB);
844    }
845
846    // If the prior block branches somewhere else on the condition and here if
847    // the condition is false, remove the uncond second branch.
848    if (PriorFBB == MBB) {
849      TII->RemoveBranch(PrevBB);
850      TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
851      MadeChange = true;
852      ++NumBranchOpts;
853      return OptimizeBlock(MBB);
854    }
855
856    // If the prior block branches here on true and somewhere else on false, and
857    // if the branch condition is reversible, reverse the branch to create a
858    // fall-through.
859    if (PriorTBB == MBB) {
860      std::vector<MachineOperand> NewPriorCond(PriorCond);
861      if (!TII->ReverseBranchCondition(NewPriorCond)) {
862        TII->RemoveBranch(PrevBB);
863        TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
864        MadeChange = true;
865        ++NumBranchOpts;
866        return OptimizeBlock(MBB);
867      }
868    }
869
870    // If this block doesn't fall through (e.g. it ends with an uncond branch or
871    // has no successors) and if the pred falls through into this block, and if
872    // it would otherwise fall through into the block after this, move this
873    // block to the end of the function.
874    //
875    // We consider it more likely that execution will stay in the function (e.g.
876    // due to loops) than it is to exit it.  This asserts in loops etc, moving
877    // the assert condition out of the loop body.
878    if (!PriorCond.empty() && PriorFBB == 0 &&
879        MachineFunction::iterator(PriorTBB) == FallThrough &&
880        !CanFallThrough(MBB)) {
881      bool DoTransform = true;
882
883      // We have to be careful that the succs of PredBB aren't both no-successor
884      // blocks.  If neither have successors and if PredBB is the second from
885      // last block in the function, we'd just keep swapping the two blocks for
886      // last.  Only do the swap if one is clearly better to fall through than
887      // the other.
888      if (FallThrough == --MBB->getParent()->end() &&
889          !IsBetterFallthrough(PriorTBB, MBB, *TII))
890        DoTransform = false;
891
892      // We don't want to do this transformation if we have control flow like:
893      //   br cond BB2
894      // BB1:
895      //   ..
896      //   jmp BBX
897      // BB2:
898      //   ..
899      //   ret
900      //
901      // In this case, we could actually be moving the return block *into* a
902      // loop!
903      if (DoTransform && !MBB->succ_empty() &&
904          (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
905        DoTransform = false;
906
907
908      if (DoTransform) {
909        // Reverse the branch so we will fall through on the previous true cond.
910        std::vector<MachineOperand> NewPriorCond(PriorCond);
911        if (!TII->ReverseBranchCondition(NewPriorCond)) {
912          DOUT << "\nMoving MBB: " << *MBB;
913          DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
914
915          TII->RemoveBranch(PrevBB);
916          TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
917
918          // Move this block to the end of the function.
919          MBB->moveAfter(--MBB->getParent()->end());
920          MadeChange = true;
921          ++NumBranchOpts;
922          return;
923        }
924      }
925    }
926  }
927
928  // Analyze the branch in the current block.
929  MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
930  std::vector<MachineOperand> CurCond;
931  bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
932  if (!CurUnAnalyzable) {
933    // If the CFG for the prior block has extra edges, remove them.
934    MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
935
936    // If this is a two-way branch, and the FBB branches to this block, reverse
937    // the condition so the single-basic-block loop is faster.  Instead of:
938    //    Loop: xxx; jcc Out; jmp Loop
939    // we want:
940    //    Loop: xxx; jncc Loop; jmp Out
941    if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
942      std::vector<MachineOperand> NewCond(CurCond);
943      if (!TII->ReverseBranchCondition(NewCond)) {
944        TII->RemoveBranch(*MBB);
945        TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
946        MadeChange = true;
947        ++NumBranchOpts;
948        return OptimizeBlock(MBB);
949      }
950    }
951
952
953    // If this branch is the only thing in its block, see if we can forward
954    // other blocks across it.
955    if (CurTBB && CurCond.empty() && CurFBB == 0 &&
956        TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
957      // This block may contain just an unconditional branch.  Because there can
958      // be 'non-branch terminators' in the block, try removing the branch and
959      // then seeing if the block is empty.
960      TII->RemoveBranch(*MBB);
961
962      // If this block is just an unconditional branch to CurTBB, we can
963      // usually completely eliminate the block.  The only case we cannot
964      // completely eliminate the block is when the block before this one
965      // falls through into MBB and we can't understand the prior block's branch
966      // condition.
967      if (MBB->empty()) {
968        bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
969        if (PredHasNoFallThrough || !PriorUnAnalyzable ||
970            !PrevBB.isSuccessor(MBB)) {
971          // If the prior block falls through into us, turn it into an
972          // explicit branch to us to make updates simpler.
973          if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
974              PriorTBB != MBB && PriorFBB != MBB) {
975            if (PriorTBB == 0) {
976              assert(PriorCond.empty() && PriorFBB == 0 &&
977                     "Bad branch analysis");
978              PriorTBB = MBB;
979            } else {
980              assert(PriorFBB == 0 && "Machine CFG out of date!");
981              PriorFBB = MBB;
982            }
983            TII->RemoveBranch(PrevBB);
984            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
985          }
986
987          // Iterate through all the predecessors, revectoring each in-turn.
988          size_t PI = 0;
989          bool DidChange = false;
990          bool HasBranchToSelf = false;
991          while(PI != MBB->pred_size()) {
992            MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
993            if (PMBB == MBB) {
994              // If this block has an uncond branch to itself, leave it.
995              ++PI;
996              HasBranchToSelf = true;
997            } else {
998              DidChange = true;
999              PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1000            }
1001          }
1002
1003          // Change any jumptables to go to the new MBB.
1004          MBB->getParent()->getJumpTableInfo()->
1005            ReplaceMBBInJumpTables(MBB, CurTBB);
1006          if (DidChange) {
1007            ++NumBranchOpts;
1008            MadeChange = true;
1009            if (!HasBranchToSelf) return;
1010          }
1011        }
1012      }
1013
1014      // Add the branch back if the block is more than just an uncond branch.
1015      TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1016    }
1017  }
1018
1019  // If the prior block doesn't fall through into this block, and if this
1020  // block doesn't fall through into some other block, see if we can find a
1021  // place to move this block where a fall-through will happen.
1022  if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1023                      PriorTBB, PriorFBB, PriorCond)) {
1024    // Now we know that there was no fall-through into this block, check to
1025    // see if it has a fall-through into its successor.
1026    bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1027                                       CurCond);
1028
1029    if (!MBB->isLandingPad()) {
1030      // Check all the predecessors of this block.  If one of them has no fall
1031      // throughs, move this block right after it.
1032      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1033           E = MBB->pred_end(); PI != E; ++PI) {
1034        // Analyze the branch at the end of the pred.
1035        MachineBasicBlock *PredBB = *PI;
1036        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1037        if (PredBB != MBB && !CanFallThrough(PredBB)
1038            && (!CurFallsThru || !CurTBB || !CurFBB)
1039            && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1040          // If the current block doesn't fall through, just move it.
1041          // If the current block can fall through and does not end with a
1042          // conditional branch, we need to append an unconditional jump to
1043          // the (current) next block.  To avoid a possible compile-time
1044          // infinite loop, move blocks only backward in this case.
1045          // Also, if there are already 2 branches here, we cannot add a third;
1046          // this means we have the case
1047          // Bcc next
1048          // B elsewhere
1049          // next:
1050          if (CurFallsThru) {
1051            MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1052            CurCond.clear();
1053            TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1054          }
1055          MBB->moveAfter(PredBB);
1056          MadeChange = true;
1057          return OptimizeBlock(MBB);
1058        }
1059      }
1060    }
1061
1062    if (!CurFallsThru) {
1063      // Check all successors to see if we can move this block before it.
1064      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1065           E = MBB->succ_end(); SI != E; ++SI) {
1066        // Analyze the branch at the end of the block before the succ.
1067        MachineBasicBlock *SuccBB = *SI;
1068        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1069        std::vector<MachineOperand> SuccPrevCond;
1070
1071        // If this block doesn't already fall-through to that successor, and if
1072        // the succ doesn't already have a block that can fall through into it,
1073        // and if the successor isn't an EH destination, we can arrange for the
1074        // fallthrough to happen.
1075        if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1076            !SuccBB->isLandingPad()) {
1077          MBB->moveBefore(SuccBB);
1078          MadeChange = true;
1079          return OptimizeBlock(MBB);
1080        }
1081      }
1082
1083      // Okay, there is no really great place to put this block.  If, however,
1084      // the block before this one would be a fall-through if this block were
1085      // removed, move this block to the end of the function.
1086      if (FallThrough != MBB->getParent()->end() &&
1087          PrevBB.isSuccessor(FallThrough)) {
1088        MBB->moveAfter(--MBB->getParent()->end());
1089        MadeChange = true;
1090        return;
1091      }
1092    }
1093  }
1094}
1095