1//===-- MSP430BranchSelector.cpp - Emit long conditional branches ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that scans a machine function to determine which
10// conditional branches need more than 10 bits of displacement to reach their
11// target basic block. It does this in two passes; a calculation of basic block
12// positions pass, and a branch pseudo op to machine branch opcode pass. This
13// pass should be run last, just before the assembly printer.
14//
15//===----------------------------------------------------------------------===//
16
17#include "MSP430.h"
18#include "MSP430InstrInfo.h"
19#include "MSP430Subtarget.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/CodeGen/MachineFunctionAnalysisManager.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachinePassManager.h"
25#include "llvm/IR/Analysis.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Target/TargetMachine.h"
29using namespace llvm;
30
31#define DEBUG_TYPE "msp430-branch-select"
32
33STATISTIC(NumSplit, "Number of machine basic blocks split");
34STATISTIC(NumExpanded, "Number of branches expanded to long format");
35
36namespace {
37class MSP430BSelImpl {
38
39 typedef SmallVector<int, 16> OffsetVector;
40
41 MachineFunction *MF;
42 const MSP430InstrInfo *TII;
43
44 unsigned measureFunction(OffsetVector &BlockOffsets,
45 MachineBasicBlock *FromBB = nullptr);
46 bool expandBranches(OffsetVector &BlockOffsets);
47
48public:
49 bool runOnMachineFunction(MachineFunction &MF);
50};
51
52class MSP430BranchSelectLegacyPass : public MachineFunctionPass {
53public:
54 static char ID;
55 MSP430BranchSelectLegacyPass() : MachineFunctionPass(ID) {}
56
57 bool runOnMachineFunction(MachineFunction &MF) override;
58
59 MachineFunctionProperties getRequiredProperties() const override {
60 return MachineFunctionProperties().setNoVRegs();
61 }
62
63 StringRef getPassName() const override { return "MSP430 Branch Selector"; }
64};
65
66char MSP430BranchSelectLegacyPass::ID = 0;
67} // namespace
68
69static bool isInRage(int DistanceInBytes) {
70 // According to CC430 Family User's Guide, Section 4.5.1.3, branch
71 // instructions have the signed 10-bit word offset field, so first we need to
72 // convert the distance from bytes to words, then check if it fits in 10-bit
73 // signed integer.
74 const int WordSize = 2;
75
76 assert((DistanceInBytes % WordSize == 0) &&
77 "Branch offset should be word aligned!");
78
79 int Words = DistanceInBytes / WordSize;
80 return isInt<10>(x: Words);
81}
82
83/// Measure each basic block, fill the BlockOffsets, and return the size of
84/// the function, starting with BB
85unsigned MSP430BSelImpl::measureFunction(OffsetVector &BlockOffsets,
86 MachineBasicBlock *FromBB) {
87 // Give the blocks of the function a dense, in-order, numbering.
88 MF->RenumberBlocks(MBBFrom: FromBB);
89
90 MachineFunction::iterator Begin;
91 if (FromBB == nullptr) {
92 Begin = MF->begin();
93 } else {
94 Begin = FromBB->getIterator();
95 }
96
97 BlockOffsets.resize(N: MF->getNumBlockIDs());
98
99 unsigned TotalSize = BlockOffsets[Begin->getNumber()];
100 for (auto &MBB : make_range(x: Begin, y: MF->end())) {
101 BlockOffsets[MBB.getNumber()] = TotalSize;
102 for (MachineInstr &MI : MBB) {
103 TotalSize += TII->getInstSizeInBytes(MI);
104 }
105 }
106 return TotalSize;
107}
108
109/// Do expand branches and split the basic blocks if necessary.
110/// Returns true if made any change.
111bool MSP430BSelImpl::expandBranches(OffsetVector &BlockOffsets) {
112 // For each conditional branch, if the offset to its destination is larger
113 // than the offset field allows, transform it into a long branch sequence
114 // like this:
115 // short branch:
116 // bCC MBB
117 // long branch:
118 // b!CC $PC+6
119 // b MBB
120 //
121 bool MadeChange = false;
122 for (auto MBB = MF->begin(), E = MF->end(); MBB != E; ++MBB) {
123 unsigned MBBStartOffset = 0;
124 for (auto MI = MBB->begin(), EE = MBB->end(); MI != EE; ++MI) {
125 MBBStartOffset += TII->getInstSizeInBytes(MI: *MI);
126
127 // If this instruction is not a short branch then skip it.
128 if (MI->getOpcode() != MSP430::JCC && MI->getOpcode() != MSP430::JMP) {
129 continue;
130 }
131
132 MachineBasicBlock *DestBB = MI->getOperand(i: 0).getMBB();
133 // Determine the distance from the current branch to the destination
134 // block. MBBStartOffset already includes the size of the current branch
135 // instruction.
136 int BlockDistance =
137 BlockOffsets[DestBB->getNumber()] - BlockOffsets[MBB->getNumber()];
138 int BranchDistance = BlockDistance - MBBStartOffset;
139
140 // If this branch is in range, ignore it.
141 if (isInRage(DistanceInBytes: BranchDistance)) {
142 continue;
143 }
144
145 LLVM_DEBUG(dbgs() << " Found a branch that needs expanding, "
146 << printMBBReference(*DestBB) << ", Distance "
147 << BranchDistance << "\n");
148
149 // If JCC is not the last instruction we need to split the MBB.
150 if (MI->getOpcode() == MSP430::JCC && std::next(x: MI) != EE) {
151
152 LLVM_DEBUG(dbgs() << " Found a basic block that needs to be split, "
153 << printMBBReference(*MBB) << "\n");
154
155 // Create a new basic block.
156 MachineBasicBlock *NewBB =
157 MF->CreateMachineBasicBlock(BB: MBB->getBasicBlock());
158 MF->insert(MBBI: std::next(x: MBB), MBB: NewBB);
159
160 // Splice the instructions following MI over to the NewBB.
161 NewBB->splice(Where: NewBB->end(), Other: &*MBB, From: std::next(x: MI), To: MBB->end());
162
163 // Update the successor lists.
164 for (MachineBasicBlock *Succ : MBB->successors()) {
165 if (Succ == DestBB) {
166 continue;
167 }
168 MBB->replaceSuccessor(Old: Succ, New: NewBB);
169 NewBB->addSuccessor(Succ);
170 }
171
172 // We introduced a new MBB so all following blocks should be numbered
173 // and measured again.
174 measureFunction(BlockOffsets, FromBB: &*MBB);
175
176 ++NumSplit;
177
178 // It may be not necessary to start all over at this point, but it's
179 // safer do this anyway.
180 return true;
181 }
182
183 MachineInstr &OldBranch = *MI;
184 DebugLoc dl = OldBranch.getDebugLoc();
185 int InstrSizeDiff = -TII->getInstSizeInBytes(MI: OldBranch);
186
187 if (MI->getOpcode() == MSP430::JCC) {
188 MachineBasicBlock *NextMBB = &*std::next(x: MBB);
189 assert(MBB->isSuccessor(NextMBB) &&
190 "This block must have a layout successor!");
191
192 // The BCC operands are:
193 // 0. Target MBB
194 // 1. MSP430 branch predicate
195 SmallVector<MachineOperand, 1> Cond;
196 Cond.push_back(Elt: MI->getOperand(i: 1));
197
198 // Jump over the long branch on the opposite condition
199 TII->reverseBranchCondition(Cond);
200 MI = BuildMI(BB&: *MBB, I: MI, MIMD: dl, MCID: TII->get(Opcode: MSP430::JCC))
201 .addMBB(MBB: NextMBB)
202 .add(MO: Cond[0]);
203 InstrSizeDiff += TII->getInstSizeInBytes(MI: *MI);
204 ++MI;
205 }
206
207 // Unconditional branch to the real destination.
208 MI = BuildMI(BB&: *MBB, I: MI, MIMD: dl, MCID: TII->get(Opcode: MSP430::Bi)).addMBB(MBB: DestBB);
209 InstrSizeDiff += TII->getInstSizeInBytes(MI: *MI);
210
211 // Remove the old branch from the function.
212 OldBranch.eraseFromParent();
213
214 // The size of a new instruction is different from the old one, so we need
215 // to correct all block offsets.
216 for (int i = MBB->getNumber() + 1, e = BlockOffsets.size(); i < e; ++i) {
217 BlockOffsets[i] += InstrSizeDiff;
218 }
219 MBBStartOffset += InstrSizeDiff;
220
221 ++NumExpanded;
222 MadeChange = true;
223 }
224 }
225 return MadeChange;
226}
227
228bool MSP430BSelImpl::runOnMachineFunction(MachineFunction &mf) {
229 MF = &mf;
230 TII = static_cast<const MSP430InstrInfo *>(MF->getSubtarget().getInstrInfo());
231
232 // If the pass is disabled, just bail early.
233 if (!MF->getSubtarget<MSP430Subtarget>().getCLOpts().branch_select)
234 return false;
235
236 LLVM_DEBUG(dbgs() << "\n********** " << DEBUG_TYPE << " **********\n");
237
238 // BlockOffsets - Contains the distance from the beginning of the function to
239 // the beginning of each basic block.
240 OffsetVector BlockOffsets;
241
242 unsigned FunctionSize = measureFunction(BlockOffsets);
243 // If the entire function is smaller than the displacement of a branch field,
244 // we know we don't need to expand any branches in this
245 // function. This is a common case.
246 if (isInRage(DistanceInBytes: FunctionSize)) {
247 return false;
248 }
249
250 // Iteratively expand branches until we reach a fixed point.
251 bool MadeChange = false;
252 while (expandBranches(BlockOffsets))
253 MadeChange = true;
254
255 return MadeChange;
256}
257
258bool MSP430BranchSelectLegacyPass::runOnMachineFunction(MachineFunction &MF) {
259 return MSP430BSelImpl().runOnMachineFunction(mf&: MF);
260}
261
262PreservedAnalyses
263MSP430BranchSelectPass::run(MachineFunction &MF,
264 MachineFunctionAnalysisManager &MFAM) {
265 return MSP430BSelImpl().runOnMachineFunction(mf&: MF)
266 ? getMachineFunctionPassPreservedAnalyses()
267 : PreservedAnalyses::all();
268}
269
270/// Returns an instance of the Branch Selection Pass
271FunctionPass *llvm::createMSP430BranchSelectLegacyPass() {
272 return new MSP430BranchSelectLegacyPass();
273}
274