MSP430BranchSelector.cpp revision 2062875a7d8f7dd94a20d9e3a298e9e216efb4b5
1//===-- MSP430BranchSelector.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 10 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 "msp430-branch-select"
19#include "MSP430.h"
20#include "MSP430InstrInfo.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Support/MathExtras.h"
26using namespace llvm;
27
28STATISTIC(NumExpanded, "Number of branches expanded to long format");
29
30namespace {
31  struct MSP430BSel : public MachineFunctionPass {
32    static char ID;
33    MSP430BSel() : MachineFunctionPass(&ID) {}
34
35    /// BlockSizes - The sizes of the basic blocks in the function.
36    std::vector<unsigned> BlockSizes;
37
38    virtual bool runOnMachineFunction(MachineFunction &Fn);
39
40    virtual const char *getPassName() const {
41      return "MSP430 Branch Selector";
42    }
43  };
44  char MSP430BSel::ID = 0;
45}
46
47/// createMSP430BranchSelectionPass - returns an instance of the Branch
48/// Selection Pass
49///
50FunctionPass *llvm::createMSP430BranchSelectionPass() {
51  return new MSP430BSel();
52}
53
54bool MSP430BSel::runOnMachineFunction(MachineFunction &Fn) {
55  const MSP430InstrInfo *TII = (MSP430InstrInfo*)Fn.getTarget().getInstrInfo();
56  // Give the blocks of the function a dense, in-order, numbering.
57  Fn.RenumberBlocks();
58  BlockSizes.resize(Fn.getNumBlockIDs());
59
60  // Measure each MBB and compute a size for the entire function.
61  unsigned FuncSize = 0;
62  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
63       ++MFI) {
64    MachineBasicBlock *MBB = MFI;
65
66    unsigned BlockSize = 0;
67    for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();
68         MBBI != EE; ++MBBI)
69      BlockSize += TII->GetInstSizeInBytes(MBBI);
70
71    BlockSizes[MBB->getNumber()] = BlockSize;
72    FuncSize += BlockSize;
73  }
74
75  // If the entire function is smaller than the displacement of a branch field,
76  // we know we don't need to shrink any branches in this function.  This is a
77  // common case.
78  if (FuncSize < (1 << 9)) {
79    BlockSizes.clear();
80    return false;
81  }
82
83  // For each conditional branch, if the offset to its destination is larger
84  // than the offset field allows, transform it into a long branch sequence
85  // like this:
86  //   short branch:
87  //     bCC MBB
88  //   long branch:
89  //     b!CC $PC+6
90  //     b MBB
91  //
92  bool MadeChange = true;
93  bool EverMadeChange = false;
94  while (MadeChange) {
95    // Iteratively expand branches until we reach a fixed point.
96    MadeChange = false;
97
98    for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
99         ++MFI) {
100      MachineBasicBlock &MBB = *MFI;
101      unsigned MBBStartOffset = 0;
102      for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
103           I != E; ++I) {
104        if ((I->getOpcode() != MSP430::JCC || I->getOperand(0).isImm()) &&
105            I->getOpcode() != MSP430::JMP) {
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(0).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<10>(BranchSize)) {
134          MBBStartOffset += 2;
135          continue;
136        }
137
138        // Otherwise, we have to expand it to a long branch.
139        unsigned NewSize;
140        MachineInstr *OldBranch = I;
141        DebugLoc dl = OldBranch->getDebugLoc();
142
143        if (I->getOpcode() == MSP430::JMP) {
144          NewSize = 4;
145        } else {
146          // The BCC operands are:
147          // 0. MSP430 branch predicate
148          // 1. Target MBB
149          SmallVector<MachineOperand, 1> Cond;
150          Cond.push_back(I->getOperand(1));
151
152          // Jump over the uncond branch inst (i.e. $+6) on opposite condition.
153          TII->ReverseBranchCondition(Cond);
154          BuildMI(MBB, I, dl, TII->get(MSP430::JCC))
155            .addImm(4).addOperand(Cond[0]);
156
157          NewSize = 6;
158        }
159        // Uncond branch to the real destination.
160        I = BuildMI(MBB, I, dl, TII->get(MSP430::Bi)).addMBB(Dest);
161
162        // Remove the old branch from the function.
163        OldBranch->eraseFromParent();
164
165        // Remember that this instruction is NewSize bytes, increase the size of the
166        // block by NewSize-2, remember to iterate.
167        BlockSizes[MBB.getNumber()] += NewSize-2;
168        MBBStartOffset += NewSize;
169
170        ++NumExpanded;
171        MadeChange = true;
172      }
173    }
174    EverMadeChange |= MadeChange;
175  }
176
177  BlockSizes.clear();
178  return true;
179}
180