1 //===-- PPCBranchSelector.cpp - Emit long conditional branches ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains a pass that scans a machine function to determine which
10 // conditional branches need more than 16 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.
15 //===----------------------------------------------------------------------===//
17 #include "MCTargetDesc/PPCPredicates.h"
19 #include "PPCInstrBuilder.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCSubtarget.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetMachine.h"
31 #define DEBUG_TYPE "ppc-branch-select"
33 STATISTIC(NumExpanded
, "Number of branches expanded to long format");
36 struct PPCBSel
: public MachineFunctionPass
{
38 PPCBSel() : MachineFunctionPass(ID
) {
39 initializePPCBSelPass(*PassRegistry::getPassRegistry());
42 // The sizes of the basic blocks in the function (the first
43 // element of the pair); the second element of the pair is the amount of the
44 // size that is due to potential padding.
45 std::vector
<std::pair
<unsigned, unsigned>> BlockSizes
;
47 // The first block number which has imprecise instruction address.
48 int FirstImpreciseBlock
= -1;
50 unsigned GetAlignmentAdjustment(MachineBasicBlock
&MBB
, unsigned Offset
);
51 unsigned ComputeBlockSizes(MachineFunction
&Fn
);
52 void modifyAdjustment(MachineFunction
&Fn
);
53 int computeBranchSize(MachineFunction
&Fn
,
54 const MachineBasicBlock
*Src
,
55 const MachineBasicBlock
*Dest
,
58 bool runOnMachineFunction(MachineFunction
&Fn
) override
;
60 MachineFunctionProperties
getRequiredProperties() const override
{
61 return MachineFunctionProperties().set(
62 MachineFunctionProperties::Property::NoVRegs
);
65 StringRef
getPassName() const override
{ return "PowerPC Branch Selector"; }
70 INITIALIZE_PASS(PPCBSel
, "ppc-branch-select", "PowerPC Branch Selector",
73 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection
76 FunctionPass
*llvm::createPPCBranchSelectionPass() {
80 /// In order to make MBB aligned, we need to add an adjustment value to the
82 unsigned PPCBSel::GetAlignmentAdjustment(MachineBasicBlock
&MBB
,
84 const llvm::Align Align
= MBB
.getAlignment();
88 const llvm::Align ParentAlign
= MBB
.getParent()->getAlignment();
90 if (Align
<= ParentAlign
)
91 return offsetToAlignment(Offset
, Align
);
93 // The alignment of this MBB is larger than the function's alignment, so we
94 // can't tell whether or not it will insert nops. Assume that it will.
95 if (FirstImpreciseBlock
< 0)
96 FirstImpreciseBlock
= MBB
.getNumber();
97 return Align
.value() + offsetToAlignment(Offset
, Align
);
100 /// We need to be careful about the offset of the first block in the function
101 /// because it might not have the function's alignment. This happens because,
102 /// under the ELFv2 ABI, for functions which require a TOC pointer, we add a
103 /// two-instruction sequence to the start of the function.
104 /// Note: This needs to be synchronized with the check in
105 /// PPCLinuxAsmPrinter::EmitFunctionBodyStart.
106 static inline unsigned GetInitialOffset(MachineFunction
&Fn
) {
107 unsigned InitialOffset
= 0;
108 if (Fn
.getSubtarget
<PPCSubtarget
>().isELFv2ABI() &&
109 !Fn
.getRegInfo().use_empty(PPC::X2
))
111 return InitialOffset
;
114 /// Measure each MBB and compute a size for the entire function.
115 unsigned PPCBSel::ComputeBlockSizes(MachineFunction
&Fn
) {
116 const PPCInstrInfo
*TII
=
117 static_cast<const PPCInstrInfo
*>(Fn
.getSubtarget().getInstrInfo());
118 unsigned FuncSize
= GetInitialOffset(Fn
);
120 for (MachineFunction::iterator MFI
= Fn
.begin(), E
= Fn
.end(); MFI
!= E
;
122 MachineBasicBlock
*MBB
= &*MFI
;
124 // The end of the previous block may have extra nops if this block has an
125 // alignment requirement.
126 if (MBB
->getNumber() > 0) {
127 unsigned AlignExtra
= GetAlignmentAdjustment(*MBB
, FuncSize
);
129 auto &BS
= BlockSizes
[MBB
->getNumber()-1];
130 BS
.first
+= AlignExtra
;
131 BS
.second
= AlignExtra
;
133 FuncSize
+= AlignExtra
;
136 unsigned BlockSize
= 0;
137 for (MachineInstr
&MI
: *MBB
) {
138 BlockSize
+= TII
->getInstSizeInBytes(MI
);
139 if (MI
.isInlineAsm() && (FirstImpreciseBlock
< 0))
140 FirstImpreciseBlock
= MBB
->getNumber();
143 BlockSizes
[MBB
->getNumber()].first
= BlockSize
;
144 FuncSize
+= BlockSize
;
150 /// Modify the basic block align adjustment.
151 void PPCBSel::modifyAdjustment(MachineFunction
&Fn
) {
152 unsigned Offset
= GetInitialOffset(Fn
);
153 for (MachineFunction::iterator MFI
= Fn
.begin(), E
= Fn
.end(); MFI
!= E
;
155 MachineBasicBlock
*MBB
= &*MFI
;
157 if (MBB
->getNumber() > 0) {
158 auto &BS
= BlockSizes
[MBB
->getNumber()-1];
159 BS
.first
-= BS
.second
;
162 unsigned AlignExtra
= GetAlignmentAdjustment(*MBB
, Offset
);
164 BS
.first
+= AlignExtra
;
165 BS
.second
= AlignExtra
;
167 Offset
+= AlignExtra
;
170 Offset
+= BlockSizes
[MBB
->getNumber()].first
;
174 /// Determine the offset from the branch in Src block to the Dest block.
175 /// BrOffset is the offset of the branch instruction inside Src block.
176 int PPCBSel::computeBranchSize(MachineFunction
&Fn
,
177 const MachineBasicBlock
*Src
,
178 const MachineBasicBlock
*Dest
,
181 unsigned MaxLogAlign
= 2;
182 bool NeedExtraAdjustment
= false;
183 if (Dest
->getNumber() <= Src
->getNumber()) {
184 // If this is a backwards branch, the delta is the offset from the
185 // start of this block to this branch, plus the sizes of all blocks
186 // from this block to the dest.
187 BranchSize
= BrOffset
;
188 MaxLogAlign
= std::max(MaxLogAlign
, Src
->getLogAlignment());
190 int DestBlock
= Dest
->getNumber();
191 BranchSize
+= BlockSizes
[DestBlock
].first
;
192 for (unsigned i
= DestBlock
+1, e
= Src
->getNumber(); i
< e
; ++i
) {
193 BranchSize
+= BlockSizes
[i
].first
;
195 std::max(MaxLogAlign
, Fn
.getBlockNumbered(i
)->getLogAlignment());
198 NeedExtraAdjustment
= (FirstImpreciseBlock
>= 0) &&
199 (DestBlock
>= FirstImpreciseBlock
);
201 // Otherwise, add the size of the blocks between this block and the
202 // dest to the number of bytes left in this block.
203 unsigned StartBlock
= Src
->getNumber();
204 BranchSize
= BlockSizes
[StartBlock
].first
- BrOffset
;
206 MaxLogAlign
= std::max(MaxLogAlign
, Dest
->getLogAlignment());
207 for (unsigned i
= StartBlock
+1, e
= Dest
->getNumber(); i
!= e
; ++i
) {
208 BranchSize
+= BlockSizes
[i
].first
;
210 std::max(MaxLogAlign
, Fn
.getBlockNumbered(i
)->getLogAlignment());
213 NeedExtraAdjustment
= (FirstImpreciseBlock
>= 0) &&
214 (Src
->getNumber() >= FirstImpreciseBlock
);
217 // We tend to over estimate code size due to large alignment and
218 // inline assembly. Usually it causes larger computed branch offset.
219 // But sometimes it may also causes smaller computed branch offset
220 // than actual branch offset. If the offset is close to the limit of
221 // encoding, it may cause problem at run time.
222 // Following is a simplified example.
233 // Actual offset: 0x8108 - 0x100 = 0x8008
234 // Computed offset: 0x8108 - 0x10c = 0x7ffc
236 // This example also shows when we can get the largest gap between
237 // estimated offset and actual offset. If there is an aligned block
238 // ABB between branch and target, assume its alignment is <align>
239 // bits. Now consider the accumulated function size FSIZE till the end
240 // of previous block PBB. If the estimated FSIZE is multiple of
241 // 2^<align>, we don't need any padding for the estimated address of
242 // ABB. If actual FSIZE at the end of PBB is 4 bytes more than
243 // multiple of 2^<align>, then we need (2^<align> - 4) bytes of
244 // padding. It also means the actual branch offset is (2^<align> - 4)
245 // larger than computed offset. Other actual FSIZE needs less padding
246 // bytes, so causes smaller gap between actual and computed offset.
248 // On the other hand, if the inline asm or large alignment occurs
249 // between the branch block and destination block, the estimated address
250 // can be <delta> larger than actual address. If padding bytes are
251 // needed for a later aligned block, the actual number of padding bytes
252 // is at most <delta> more than estimated padding bytes. So the actual
253 // aligned block address is less than or equal to the estimated aligned
254 // block address. So the actual branch offset is less than or equal to
255 // computed branch offset.
257 // The computed offset is at most ((1 << alignment) - 4) bytes smaller
258 // than actual offset. So we add this number to the offset for safety.
259 if (NeedExtraAdjustment
)
260 BranchSize
+= (1 << MaxLogAlign
) - 4;
265 bool PPCBSel::runOnMachineFunction(MachineFunction
&Fn
) {
266 const PPCInstrInfo
*TII
=
267 static_cast<const PPCInstrInfo
*>(Fn
.getSubtarget().getInstrInfo());
268 // Give the blocks of the function a dense, in-order, numbering.
270 BlockSizes
.resize(Fn
.getNumBlockIDs());
271 FirstImpreciseBlock
= -1;
273 // Measure each MBB and compute a size for the entire function.
274 unsigned FuncSize
= ComputeBlockSizes(Fn
);
276 // If the entire function is smaller than the displacement of a branch field,
277 // we know we don't need to shrink any branches in this function. This is a
279 if (FuncSize
< (1 << 15)) {
284 // For each conditional branch, if the offset to its destination is larger
285 // than the offset field allows, transform it into a long branch sequence
293 bool MadeChange
= true;
294 bool EverMadeChange
= false;
296 // Iteratively expand branches until we reach a fixed point.
299 for (MachineFunction::iterator MFI
= Fn
.begin(), E
= Fn
.end(); MFI
!= E
;
301 MachineBasicBlock
&MBB
= *MFI
;
302 unsigned MBBStartOffset
= 0;
303 for (MachineBasicBlock::iterator I
= MBB
.begin(), E
= MBB
.end();
305 MachineBasicBlock
*Dest
= nullptr;
306 if (I
->getOpcode() == PPC::BCC
&& !I
->getOperand(2).isImm())
307 Dest
= I
->getOperand(2).getMBB();
308 else if ((I
->getOpcode() == PPC::BC
|| I
->getOpcode() == PPC::BCn
) &&
309 !I
->getOperand(1).isImm())
310 Dest
= I
->getOperand(1).getMBB();
311 else if ((I
->getOpcode() == PPC::BDNZ8
|| I
->getOpcode() == PPC::BDNZ
||
312 I
->getOpcode() == PPC::BDZ8
|| I
->getOpcode() == PPC::BDZ
) &&
313 !I
->getOperand(0).isImm())
314 Dest
= I
->getOperand(0).getMBB();
317 MBBStartOffset
+= TII
->getInstSizeInBytes(*I
);
321 // Determine the offset from the current branch to the destination
323 int BranchSize
= computeBranchSize(Fn
, &MBB
, Dest
, MBBStartOffset
);
325 // If this branch is in range, ignore it.
326 if (isInt
<16>(BranchSize
)) {
331 // Otherwise, we have to expand it to a long branch.
332 MachineInstr
&OldBranch
= *I
;
333 DebugLoc dl
= OldBranch
.getDebugLoc();
335 if (I
->getOpcode() == PPC::BCC
) {
336 // The BCC operands are:
337 // 0. PPC branch predicate
340 PPC::Predicate Pred
= (PPC::Predicate
)I
->getOperand(0).getImm();
341 Register CRReg
= I
->getOperand(1).getReg();
343 // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
344 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BCC
))
345 .addImm(PPC::InvertPredicate(Pred
)).addReg(CRReg
).addImm(2);
346 } else if (I
->getOpcode() == PPC::BC
) {
347 Register CRBit
= I
->getOperand(0).getReg();
348 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BCn
)).addReg(CRBit
).addImm(2);
349 } else if (I
->getOpcode() == PPC::BCn
) {
350 Register CRBit
= I
->getOperand(0).getReg();
351 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BC
)).addReg(CRBit
).addImm(2);
352 } else if (I
->getOpcode() == PPC::BDNZ
) {
353 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDZ
)).addImm(2);
354 } else if (I
->getOpcode() == PPC::BDNZ8
) {
355 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDZ8
)).addImm(2);
356 } else if (I
->getOpcode() == PPC::BDZ
) {
357 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDNZ
)).addImm(2);
358 } else if (I
->getOpcode() == PPC::BDZ8
) {
359 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDNZ8
)).addImm(2);
361 llvm_unreachable("Unhandled branch type!");
364 // Uncond branch to the real destination.
365 I
= BuildMI(MBB
, I
, dl
, TII
->get(PPC::B
)).addMBB(Dest
);
367 // Remove the old branch from the function.
368 OldBranch
.eraseFromParent();
370 // Remember that this instruction is 8-bytes, increase the size of the
371 // block by 4, remember to iterate.
372 BlockSizes
[MBB
.getNumber()].first
+= 4;
380 // If we're going to iterate again, make sure we've updated our
381 // padding-based contributions to the block sizes.
382 modifyAdjustment(Fn
);
385 EverMadeChange
|= MadeChange
;