PPCBranchSelector.cpp revision 208954
1//===-- PPCBranchSelector.cpp - Emit long conditional branches-----*- C++ -*-=//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that scans a machine function to determine which
11// conditional branches need more than 16 bits of displacement to reach their
12// target basic block.  It does this in two passes; a calculation of basic block
13// positions pass, and a branch psuedo op to machine branch opcode pass.  This
14// pass should be run last, just before the assembly printer.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "ppc-branch-select"
19#include "PPC.h"
20#include "PPCInstrBuilder.h"
21#include "PPCInstrInfo.h"
22#include "PPCPredicates.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/MathExtras.h"
27using namespace llvm;
28
29STATISTIC(NumExpanded, "Number of branches expanded to long format");
30
31namespace {
32  struct PPCBSel : public MachineFunctionPass {
33    static char ID;
34    PPCBSel() : MachineFunctionPass(&ID) {}
35
36    /// BlockSizes - The sizes of the basic blocks in the function.
37    std::vector<unsigned> BlockSizes;
38
39    virtual bool runOnMachineFunction(MachineFunction &Fn);
40
41    virtual const char *getPassName() const {
42      return "PowerPC Branch Selector";
43    }
44  };
45  char PPCBSel::ID = 0;
46}
47
48/// createPPCBranchSelectionPass - returns an instance of the Branch Selection
49/// Pass
50///
51FunctionPass *llvm::createPPCBranchSelectionPass() {
52  return new PPCBSel();
53}
54
55bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {
56  const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
57  // Give the blocks of the function a dense, in-order, numbering.
58  Fn.RenumberBlocks();
59  BlockSizes.resize(Fn.getNumBlockIDs());
60
61  // Measure each MBB and compute a size for the entire function.
62  unsigned FuncSize = 0;
63  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
64       ++MFI) {
65    MachineBasicBlock *MBB = MFI;
66
67    unsigned BlockSize = 0;
68    for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();
69         MBBI != EE; ++MBBI)
70      BlockSize += TII->GetInstSizeInBytes(MBBI);
71
72    BlockSizes[MBB->getNumber()] = BlockSize;
73    FuncSize += BlockSize;
74  }
75
76  // If the entire function is smaller than the displacement of a branch field,
77  // we know we don't need to shrink any branches in this function.  This is a
78  // common case.
79  if (FuncSize < (1 << 15)) {
80    BlockSizes.clear();
81    return false;
82  }
83
84  // For each conditional branch, if the offset to its destination is larger
85  // than the offset field allows, transform it into a long branch sequence
86  // like this:
87  //   short branch:
88  //     bCC MBB
89  //   long branch:
90  //     b!CC $PC+8
91  //     b MBB
92  //
93  bool MadeChange = true;
94  bool EverMadeChange = false;
95  while (MadeChange) {
96    // Iteratively expand branches until we reach a fixed point.
97    MadeChange = false;
98
99    for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
100         ++MFI) {
101      MachineBasicBlock &MBB = *MFI;
102      unsigned MBBStartOffset = 0;
103      for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
104           I != E; ++I) {
105        if (I->getOpcode() != PPC::BCC || I->getOperand(2).isImm()) {
106          MBBStartOffset += TII->GetInstSizeInBytes(I);
107          continue;
108        }
109
110        // Determine the offset from the current branch to the destination
111        // block.
112        MachineBasicBlock *Dest = I->getOperand(2).getMBB();
113
114        int BranchSize;
115        if (Dest->getNumber() <= MBB.getNumber()) {
116          // If this is a backwards branch, the delta is the offset from the
117          // start of this block to this branch, plus the sizes of all blocks
118          // from this block to the dest.
119          BranchSize = MBBStartOffset;
120
121          for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
122            BranchSize += BlockSizes[i];
123        } else {
124          // Otherwise, add the size of the blocks between this block and the
125          // dest to the number of bytes left in this block.
126          BranchSize = -MBBStartOffset;
127
128          for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
129            BranchSize += BlockSizes[i];
130        }
131
132        // If this branch is in range, ignore it.
133        if (isInt<16>(BranchSize)) {
134          MBBStartOffset += 4;
135          continue;
136        }
137
138        // Otherwise, we have to expand it to a long branch.
139        // The BCC operands are:
140        // 0. PPC branch predicate
141        // 1. CR register
142        // 2. Target MBB
143        PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
144        unsigned CRReg = I->getOperand(1).getReg();
145
146        MachineInstr *OldBranch = I;
147        DebugLoc dl = OldBranch->getDebugLoc();
148
149        // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
150        BuildMI(MBB, I, dl, TII->get(PPC::BCC))
151          .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
152
153        // Uncond branch to the real destination.
154        I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest);
155
156        // Remove the old branch from the function.
157        OldBranch->eraseFromParent();
158
159        // Remember that this instruction is 8-bytes, increase the size of the
160        // block by 4, remember to iterate.
161        BlockSizes[MBB.getNumber()] += 4;
162        MBBStartOffset += 8;
163        ++NumExpanded;
164        MadeChange = true;
165      }
166    }
167    EverMadeChange |= MadeChange;
168  }
169
170  BlockSizes.clear();
171  return true;
172}
173
174