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
18#include "PPC.h"
19#include "MCTargetDesc/PPCPredicates.h"
20#include "PPCInstrBuilder.h"
21#include "PPCInstrInfo.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Target/TargetMachine.h"
26using namespace llvm;
27
28#define DEBUG_TYPE "ppc-branch-select"
29
30STATISTIC(NumExpanded, "Number of branches expanded to long format");
31
32namespace llvm {
33  void initializePPCBSelPass(PassRegistry&);
34}
35
36namespace {
37  struct PPCBSel : public MachineFunctionPass {
38    static char ID;
39    PPCBSel() : MachineFunctionPass(ID) {
40      initializePPCBSelPass(*PassRegistry::getPassRegistry());
41    }
42
43    /// BlockSizes - The sizes of the basic blocks in the function.
44    std::vector<unsigned> BlockSizes;
45
46    bool runOnMachineFunction(MachineFunction &Fn) override;
47
48    const char *getPassName() const override {
49      return "PowerPC Branch Selector";
50    }
51  };
52  char PPCBSel::ID = 0;
53}
54
55INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector",
56                false, false)
57
58/// createPPCBranchSelectionPass - returns an instance of the Branch Selection
59/// Pass
60///
61FunctionPass *llvm::createPPCBranchSelectionPass() {
62  return new PPCBSel();
63}
64
65bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {
66  const PPCInstrInfo *TII =
67                static_cast<const PPCInstrInfo*>(Fn.getTarget().getInstrInfo());
68  // Give the blocks of the function a dense, in-order, numbering.
69  Fn.RenumberBlocks();
70  BlockSizes.resize(Fn.getNumBlockIDs());
71
72  // Measure each MBB and compute a size for the entire function.
73  unsigned FuncSize = 0;
74  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
75       ++MFI) {
76    MachineBasicBlock *MBB = MFI;
77
78    unsigned BlockSize = 0;
79    for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();
80         MBBI != EE; ++MBBI)
81      BlockSize += TII->GetInstSizeInBytes(MBBI);
82
83    BlockSizes[MBB->getNumber()] = BlockSize;
84    FuncSize += BlockSize;
85  }
86
87  // If the entire function is smaller than the displacement of a branch field,
88  // we know we don't need to shrink any branches in this function.  This is a
89  // common case.
90  if (FuncSize < (1 << 15)) {
91    BlockSizes.clear();
92    return false;
93  }
94
95  // For each conditional branch, if the offset to its destination is larger
96  // than the offset field allows, transform it into a long branch sequence
97  // like this:
98  //   short branch:
99  //     bCC MBB
100  //   long branch:
101  //     b!CC $PC+8
102  //     b MBB
103  //
104  bool MadeChange = true;
105  bool EverMadeChange = false;
106  while (MadeChange) {
107    // Iteratively expand branches until we reach a fixed point.
108    MadeChange = false;
109
110    for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
111         ++MFI) {
112      MachineBasicBlock &MBB = *MFI;
113      unsigned MBBStartOffset = 0;
114      for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
115           I != E; ++I) {
116        MachineBasicBlock *Dest = nullptr;
117        if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm())
118          Dest = I->getOperand(2).getMBB();
119        else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) &&
120                 !I->getOperand(1).isImm())
121          Dest = I->getOperand(1).getMBB();
122        else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ ||
123                  I->getOpcode() == PPC::BDZ8  || I->getOpcode() == PPC::BDZ) &&
124                 !I->getOperand(0).isImm())
125          Dest = I->getOperand(0).getMBB();
126
127        if (!Dest) {
128          MBBStartOffset += TII->GetInstSizeInBytes(I);
129          continue;
130        }
131
132        // Determine the offset from the current branch to the destination
133        // block.
134        int BranchSize;
135        if (Dest->getNumber() <= MBB.getNumber()) {
136          // If this is a backwards branch, the delta is the offset from the
137          // start of this block to this branch, plus the sizes of all blocks
138          // from this block to the dest.
139          BranchSize = MBBStartOffset;
140
141          for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
142            BranchSize += BlockSizes[i];
143        } else {
144          // Otherwise, add the size of the blocks between this block and the
145          // dest to the number of bytes left in this block.
146          BranchSize = -MBBStartOffset;
147
148          for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
149            BranchSize += BlockSizes[i];
150        }
151
152        // If this branch is in range, ignore it.
153        if (isInt<16>(BranchSize)) {
154          MBBStartOffset += 4;
155          continue;
156        }
157
158        // Otherwise, we have to expand it to a long branch.
159        MachineInstr *OldBranch = I;
160        DebugLoc dl = OldBranch->getDebugLoc();
161
162        if (I->getOpcode() == PPC::BCC) {
163          // The BCC operands are:
164          // 0. PPC branch predicate
165          // 1. CR register
166          // 2. Target MBB
167          PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
168          unsigned CRReg = I->getOperand(1).getReg();
169
170          // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
171          BuildMI(MBB, I, dl, TII->get(PPC::BCC))
172            .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
173        } else if (I->getOpcode() == PPC::BC) {
174          unsigned CRBit = I->getOperand(0).getReg();
175          BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2);
176        } else if (I->getOpcode() == PPC::BCn) {
177          unsigned CRBit = I->getOperand(0).getReg();
178          BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2);
179        } else if (I->getOpcode() == PPC::BDNZ) {
180          BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2);
181        } else if (I->getOpcode() == PPC::BDNZ8) {
182          BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2);
183        } else if (I->getOpcode() == PPC::BDZ) {
184          BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2);
185        } else if (I->getOpcode() == PPC::BDZ8) {
186          BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2);
187        } else {
188           llvm_unreachable("Unhandled branch type!");
189        }
190
191        // Uncond branch to the real destination.
192        I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest);
193
194        // Remove the old branch from the function.
195        OldBranch->eraseFromParent();
196
197        // Remember that this instruction is 8-bytes, increase the size of the
198        // block by 4, remember to iterate.
199        BlockSizes[MBB.getNumber()] += 4;
200        MBBStartOffset += 8;
201        ++NumExpanded;
202        MadeChange = true;
203      }
204    }
205    EverMadeChange |= MadeChange;
206  }
207
208  BlockSizes.clear();
209  return true;
210}
211
212