LLVM  8.0.1
PPCBranchSelector.cpp
Go to the documentation of this file.
1 //===-- PPCBranchSelector.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 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 pseudo op to machine branch opcode pass. This
14 // pass should be run last, just before the assembly printer.
15 //
16 //===----------------------------------------------------------------------===//
17 
19 #include "PPC.h"
20 #include "PPCInstrBuilder.h"
21 #include "PPCInstrInfo.h"
22 #include "PPCSubtarget.h"
23 #include "llvm/ADT/Statistic.h"
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "ppc-branch-select"
32 
33 STATISTIC(NumExpanded, "Number of branches expanded to long format");
34 
35 namespace llvm {
37 }
38 
39 namespace {
40  struct PPCBSel : public MachineFunctionPass {
41  static char ID;
42  PPCBSel() : MachineFunctionPass(ID) {
44  }
45 
46  // The sizes of the basic blocks in the function (the first
47  // element of the pair); the second element of the pair is the amount of the
48  // size that is due to potential padding.
49  std::vector<std::pair<unsigned, unsigned>> BlockSizes;
50 
51  bool runOnMachineFunction(MachineFunction &Fn) override;
52 
53  MachineFunctionProperties getRequiredProperties() const override {
56  }
57 
58  StringRef getPassName() const override { return "PowerPC Branch Selector"; }
59  };
60  char PPCBSel::ID = 0;
61 }
62 
63 INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector",
64  false, false)
65 
66 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection
67 /// Pass
68 ///
70  return new PPCBSel();
71 }
72 
73 bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {
74  const PPCInstrInfo *TII =
75  static_cast<const PPCInstrInfo *>(Fn.getSubtarget().getInstrInfo());
76  // Give the blocks of the function a dense, in-order, numbering.
77  Fn.RenumberBlocks();
78  BlockSizes.resize(Fn.getNumBlockIDs());
79 
80  auto GetAlignmentAdjustment =
81  [](MachineBasicBlock &MBB, unsigned Offset) -> unsigned {
82  unsigned Align = MBB.getAlignment();
83  if (!Align)
84  return 0;
85 
86  unsigned AlignAmt = 1 << Align;
87  unsigned ParentAlign = MBB.getParent()->getAlignment();
88 
89  if (Align <= ParentAlign)
90  return OffsetToAlignment(Offset, AlignAmt);
91 
92  // The alignment of this MBB is larger than the function's alignment, so we
93  // can't tell whether or not it will insert nops. Assume that it will.
94  return AlignAmt + OffsetToAlignment(Offset, AlignAmt);
95  };
96 
97  // We need to be careful about the offset of the first block in the function
98  // because it might not have the function's alignment. This happens because,
99  // under the ELFv2 ABI, for functions which require a TOC pointer, we add a
100  // two-instruction sequence to the start of the function.
101  // Note: This needs to be synchronized with the check in
102  // PPCLinuxAsmPrinter::EmitFunctionBodyStart.
103  unsigned InitialOffset = 0;
104  if (Fn.getSubtarget<PPCSubtarget>().isELFv2ABI() &&
105  !Fn.getRegInfo().use_empty(PPC::X2))
106  InitialOffset = 8;
107 
108  // Measure each MBB and compute a size for the entire function.
109  unsigned FuncSize = InitialOffset;
110  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
111  ++MFI) {
112  MachineBasicBlock *MBB = &*MFI;
113 
114  // The end of the previous block may have extra nops if this block has an
115  // alignment requirement.
116  if (MBB->getNumber() > 0) {
117  unsigned AlignExtra = GetAlignmentAdjustment(*MBB, FuncSize);
118 
119  auto &BS = BlockSizes[MBB->getNumber()-1];
120  BS.first += AlignExtra;
121  BS.second = AlignExtra;
122 
123  FuncSize += AlignExtra;
124  }
125 
126  unsigned BlockSize = 0;
127  for (MachineInstr &MI : *MBB)
128  BlockSize += TII->getInstSizeInBytes(MI);
129 
130  BlockSizes[MBB->getNumber()].first = BlockSize;
131  FuncSize += BlockSize;
132  }
133 
134  // If the entire function is smaller than the displacement of a branch field,
135  // we know we don't need to shrink any branches in this function. This is a
136  // common case.
137  if (FuncSize < (1 << 15)) {
138  BlockSizes.clear();
139  return false;
140  }
141 
142  // For each conditional branch, if the offset to its destination is larger
143  // than the offset field allows, transform it into a long branch sequence
144  // like this:
145  // short branch:
146  // bCC MBB
147  // long branch:
148  // b!CC $PC+8
149  // b MBB
150  //
151  bool MadeChange = true;
152  bool EverMadeChange = false;
153  while (MadeChange) {
154  // Iteratively expand branches until we reach a fixed point.
155  MadeChange = false;
156 
157  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
158  ++MFI) {
159  MachineBasicBlock &MBB = *MFI;
160  unsigned MBBStartOffset = 0;
161  for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
162  I != E; ++I) {
163  MachineBasicBlock *Dest = nullptr;
164  if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm())
165  Dest = I->getOperand(2).getMBB();
166  else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) &&
167  !I->getOperand(1).isImm())
168  Dest = I->getOperand(1).getMBB();
169  else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ ||
170  I->getOpcode() == PPC::BDZ8 || I->getOpcode() == PPC::BDZ) &&
171  !I->getOperand(0).isImm())
172  Dest = I->getOperand(0).getMBB();
173 
174  if (!Dest) {
175  MBBStartOffset += TII->getInstSizeInBytes(*I);
176  continue;
177  }
178 
179  // Determine the offset from the current branch to the destination
180  // block.
181  int BranchSize;
182  if (Dest->getNumber() <= MBB.getNumber()) {
183  // If this is a backwards branch, the delta is the offset from the
184  // start of this block to this branch, plus the sizes of all blocks
185  // from this block to the dest.
186  BranchSize = MBBStartOffset;
187 
188  for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
189  BranchSize += BlockSizes[i].first;
190  } else {
191  // Otherwise, add the size of the blocks between this block and the
192  // dest to the number of bytes left in this block.
193  BranchSize = -MBBStartOffset;
194 
195  for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
196  BranchSize += BlockSizes[i].first;
197  }
198 
199  // If this branch is in range, ignore it.
200  if (isInt<16>(BranchSize)) {
201  MBBStartOffset += 4;
202  continue;
203  }
204 
205  // Otherwise, we have to expand it to a long branch.
206  MachineInstr &OldBranch = *I;
207  DebugLoc dl = OldBranch.getDebugLoc();
208 
209  if (I->getOpcode() == PPC::BCC) {
210  // The BCC operands are:
211  // 0. PPC branch predicate
212  // 1. CR register
213  // 2. Target MBB
214  PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
215  unsigned CRReg = I->getOperand(1).getReg();
216 
217  // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
218  BuildMI(MBB, I, dl, TII->get(PPC::BCC))
219  .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
220  } else if (I->getOpcode() == PPC::BC) {
221  unsigned CRBit = I->getOperand(0).getReg();
222  BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2);
223  } else if (I->getOpcode() == PPC::BCn) {
224  unsigned CRBit = I->getOperand(0).getReg();
225  BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2);
226  } else if (I->getOpcode() == PPC::BDNZ) {
227  BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2);
228  } else if (I->getOpcode() == PPC::BDNZ8) {
229  BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2);
230  } else if (I->getOpcode() == PPC::BDZ) {
231  BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2);
232  } else if (I->getOpcode() == PPC::BDZ8) {
233  BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2);
234  } else {
235  llvm_unreachable("Unhandled branch type!");
236  }
237 
238  // Uncond branch to the real destination.
239  I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest);
240 
241  // Remove the old branch from the function.
242  OldBranch.eraseFromParent();
243 
244  // Remember that this instruction is 8-bytes, increase the size of the
245  // block by 4, remember to iterate.
246  BlockSizes[MBB.getNumber()].first += 4;
247  MBBStartOffset += 8;
248  ++NumExpanded;
249  MadeChange = true;
250  }
251  }
252 
253  if (MadeChange) {
254  // If we're going to iterate again, make sure we've updated our
255  // padding-based contributions to the block sizes.
256  unsigned Offset = InitialOffset;
257  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
258  ++MFI) {
259  MachineBasicBlock *MBB = &*MFI;
260 
261  if (MBB->getNumber() > 0) {
262  auto &BS = BlockSizes[MBB->getNumber()-1];
263  BS.first -= BS.second;
264  Offset -= BS.second;
265 
266  unsigned AlignExtra = GetAlignmentAdjustment(*MBB, Offset);
267 
268  BS.first += AlignExtra;
269  BS.second = AlignExtra;
270 
271  Offset += AlignExtra;
272  }
273 
274  Offset += BlockSizes[MBB->getNumber()].first;
275  }
276  }
277 
278  EverMadeChange |= MadeChange;
279  }
280 
281  BlockSizes.clear();
282  return true;
283 }
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID&#39;s allocated.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:383
constexpr bool isInt< 16 >(int64_t x)
Definition: MathExtras.h:306
STATISTIC(NumFunctions, "Total number of functions")
A debug info location.
Definition: DebugLoc.h:34
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
void initializePPCBSelPass(PassRegistry &)
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
unsigned getAlignment() const
getAlignment - Return the alignment (log2, not bytes) of the function.
CHAIN = BDNZ CHAIN, DESTBB - These are used to create counter-based loops.
bool isELFv2ABI() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
FunctionPass * createPPCBranchSelectionPass()
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
unsigned getAlignment() const
Return alignment of the basic block.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned first
static const int BlockSize
Definition: TarWriter.cpp:34
Iterator for intrusive lists based on ilist_node.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:27
bool use_empty(unsigned RegNo) const
use_empty - Return true if there are no instructions using the specified register.
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:64
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Predicate InvertPredicate(Predicate Opcode)
Invert the specified predicate. != -> ==, < -> >=.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector", false, false) FunctionPass *llvm
createPPCBranchSelectionPass - returns an instance of the Branch Selection Pass
uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: MathExtras.h:727
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:39
Properties which a MachineFunction may have at a given point in time.