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