SystemZLongBranch.cpp revision 6227d5c690504c7ada5780c00a635b282c46e275
1//===-- SystemZLongBranch.cpp - Branch lengthening for SystemZ ------------===//
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 pass makes sure that all branches are in range.  There are several ways
11// in which this could be done.  One aggressive approach is to assume that all
12// branches are in range and successively replace those that turn out not
13// to be in range with a longer form (branch relaxation).  A simple
14// implementation is to continually walk through the function relaxing
15// branches until no more changes are needed and a fixed point is reached.
16// However, in the pathological worst case, this implementation is
17// quadratic in the number of blocks; relaxing branch N can make branch N-1
18// go out of range, which in turn can make branch N-2 go out of range,
19// and so on.
20//
21// An alternative approach is to assume that all branches must be
22// converted to their long forms, then reinstate the short forms of
23// branches that, even under this pessimistic assumption, turn out to be
24// in range (branch shortening).  This too can be implemented as a function
25// walk that is repeated until a fixed point is reached.  In general,
26// the result of shortening is not as good as that of relaxation, and
27// shortening is also quadratic in the worst case; shortening branch N
28// can bring branch N-1 in range of the short form, which in turn can do
29// the same for branch N-2, and so on.  The main advantage of shortening
30// is that each walk through the function produces valid code, so it is
31// possible to stop at any point after the first walk.  The quadraticness
32// could therefore be handled with a maximum pass count, although the
33// question then becomes: what maximum count should be used?
34//
35// On SystemZ, long branches are only needed for functions bigger than 64k,
36// which are relatively rare to begin with, and the long branch sequences
37// are actually relatively cheap.  It therefore doesn't seem worth spending
38// much compilation time on the problem.  Instead, the approach we take is:
39//
40// (1) Work out the address that each block would have if no branches
41//     need relaxing.  Exit the pass early if all branches are in range
42//     according to this assumption.
43//
44// (2) Work out the address that each block would have if all branches
45//     need relaxing.
46//
47// (3) Walk through the block calculating the final address of each instruction
48//     and relaxing those that need to be relaxed.  For backward branches,
49//     this check uses the final address of the target block, as calculated
50//     earlier in the walk.  For forward branches, this check uses the
51//     address of the target block that was calculated in (2).  Both checks
52//     give a conservatively-correct range.
53//
54//===----------------------------------------------------------------------===//
55
56#define DEBUG_TYPE "systemz-long-branch"
57
58#include "SystemZTargetMachine.h"
59#include "llvm/ADT/Statistic.h"
60#include "llvm/CodeGen/MachineFunctionPass.h"
61#include "llvm/CodeGen/MachineInstrBuilder.h"
62#include "llvm/IR/Function.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/MathExtras.h"
65#include "llvm/Target/TargetInstrInfo.h"
66#include "llvm/Target/TargetMachine.h"
67#include "llvm/Target/TargetRegisterInfo.h"
68
69using namespace llvm;
70
71STATISTIC(LongBranches, "Number of long branches.");
72
73namespace {
74  typedef MachineBasicBlock::iterator Iter;
75
76  // Represents positional information about a basic block.
77  struct MBBInfo {
78    // The address that we currently assume the block has.
79    uint64_t Address;
80
81    // The size of the block in bytes, excluding terminators.
82    // This value never changes.
83    uint64_t Size;
84
85    // The minimum alignment of the block, as a log2 value.
86    // This value never changes.
87    unsigned Alignment;
88
89    // The number of terminators in this block.  This value never changes.
90    unsigned NumTerminators;
91
92    MBBInfo()
93      : Address(0), Size(0), Alignment(0), NumTerminators(0) {}
94  };
95
96  // Represents the state of a block terminator.
97  struct TerminatorInfo {
98    // If this terminator is a relaxable branch, this points to the branch
99    // instruction, otherwise it is null.
100    MachineInstr *Branch;
101
102    // The address that we currently assume the terminator has.
103    uint64_t Address;
104
105    // The current size of the terminator in bytes.
106    uint64_t Size;
107
108    // If Branch is nonnull, this is the number of the target block,
109    // otherwise it is unused.
110    unsigned TargetBlock;
111
112    // If Branch is nonnull, this is the length of the longest relaxed form,
113    // otherwise it is zero.
114    unsigned ExtraRelaxSize;
115
116    TerminatorInfo() : Branch(0), Size(0), TargetBlock(0), ExtraRelaxSize(0) {}
117  };
118
119  // Used to keep track of the current position while iterating over the blocks.
120  struct BlockPosition {
121    // The address that we assume this position has.
122    uint64_t Address;
123
124    // The number of low bits in Address that are known to be the same
125    // as the runtime address.
126    unsigned KnownBits;
127
128    BlockPosition(unsigned InitialAlignment)
129      : Address(0), KnownBits(InitialAlignment) {}
130  };
131
132  class SystemZLongBranch : public MachineFunctionPass {
133  public:
134    static char ID;
135    SystemZLongBranch(const SystemZTargetMachine &tm)
136      : MachineFunctionPass(ID), TII(0) {}
137
138    virtual const char *getPassName() const {
139      return "SystemZ Long Branch";
140    }
141
142    bool runOnMachineFunction(MachineFunction &F);
143
144  private:
145    void skipNonTerminators(BlockPosition &Position, MBBInfo &Block);
146    void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator,
147                        bool AssumeRelaxed);
148    TerminatorInfo describeTerminator(MachineInstr *MI);
149    uint64_t initMBBInfo();
150    bool mustRelaxBranch(const TerminatorInfo &Terminator, uint64_t Address);
151    bool mustRelaxABranch();
152    void setWorstCaseAddresses();
153    void splitCompareBranch(MachineInstr *MI, unsigned CompareOpcode);
154    void relaxBranch(TerminatorInfo &Terminator);
155    void relaxBranches();
156
157    const SystemZInstrInfo *TII;
158    MachineFunction *MF;
159    SmallVector<MBBInfo, 16> MBBs;
160    SmallVector<TerminatorInfo, 16> Terminators;
161  };
162
163  char SystemZLongBranch::ID = 0;
164
165  const uint64_t MaxBackwardRange = 0x10000;
166  const uint64_t MaxForwardRange = 0xfffe;
167} // end of anonymous namespace
168
169FunctionPass *llvm::createSystemZLongBranchPass(SystemZTargetMachine &TM) {
170  return new SystemZLongBranch(TM);
171}
172
173// Position describes the state immediately before Block.  Update Block
174// accordingly and move Position to the end of the block's non-terminator
175// instructions.
176void SystemZLongBranch::skipNonTerminators(BlockPosition &Position,
177                                           MBBInfo &Block) {
178  if (Block.Alignment > Position.KnownBits) {
179    // When calculating the address of Block, we need to conservatively
180    // assume that Block had the worst possible misalignment.
181    Position.Address += ((uint64_t(1) << Block.Alignment) -
182                         (uint64_t(1) << Position.KnownBits));
183    Position.KnownBits = Block.Alignment;
184  }
185
186  // Align the addresses.
187  uint64_t AlignMask = (uint64_t(1) << Block.Alignment) - 1;
188  Position.Address = (Position.Address + AlignMask) & ~AlignMask;
189
190  // Record the block's position.
191  Block.Address = Position.Address;
192
193  // Move past the non-terminators in the block.
194  Position.Address += Block.Size;
195}
196
197// Position describes the state immediately before Terminator.
198// Update Terminator accordingly and move Position past it.
199// Assume that Terminator will be relaxed if AssumeRelaxed.
200void SystemZLongBranch::skipTerminator(BlockPosition &Position,
201                                       TerminatorInfo &Terminator,
202                                       bool AssumeRelaxed) {
203  Terminator.Address = Position.Address;
204  Position.Address += Terminator.Size;
205  if (AssumeRelaxed)
206    Position.Address += Terminator.ExtraRelaxSize;
207}
208
209// Return a description of terminator instruction MI.
210TerminatorInfo SystemZLongBranch::describeTerminator(MachineInstr *MI) {
211  TerminatorInfo Terminator;
212  Terminator.Size = TII->getInstSizeInBytes(MI);
213  if (MI->isConditionalBranch() || MI->isUnconditionalBranch()) {
214    switch (MI->getOpcode()) {
215    case SystemZ::J:
216      // Relaxes to JG, which is 2 bytes longer.
217      Terminator.ExtraRelaxSize = 2;
218      break;
219    case SystemZ::BRC:
220      // Relaxes to BRCL, which is 2 bytes longer.
221      Terminator.ExtraRelaxSize = 2;
222      break;
223    case SystemZ::CRJ:
224      // Relaxes to a CR/BRCL sequence, which is 2 bytes longer.
225      Terminator.ExtraRelaxSize = 2;
226      break;
227    case SystemZ::CGRJ:
228      // Relaxes to a CGR/BRCL sequence, which is 4 bytes longer.
229      Terminator.ExtraRelaxSize = 4;
230      break;
231    case SystemZ::CIJ:
232    case SystemZ::CGIJ:
233      // Relaxes to a C(G)HI/BRCL sequence, which is 4 bytes longer.
234      Terminator.ExtraRelaxSize = 4;
235      break;
236    default:
237      llvm_unreachable("Unrecognized branch instruction");
238    }
239    Terminator.Branch = MI;
240    Terminator.TargetBlock =
241      TII->getBranchInfo(MI).Target->getMBB()->getNumber();
242  }
243  return Terminator;
244}
245
246// Fill MBBs and Terminators, setting the addresses on the assumption
247// that no branches need relaxation.  Return the size of the function under
248// this assumption.
249uint64_t SystemZLongBranch::initMBBInfo() {
250  MF->RenumberBlocks();
251  unsigned NumBlocks = MF->size();
252
253  MBBs.clear();
254  MBBs.resize(NumBlocks);
255
256  Terminators.clear();
257  Terminators.reserve(NumBlocks);
258
259  BlockPosition Position(MF->getAlignment());
260  for (unsigned I = 0; I < NumBlocks; ++I) {
261    MachineBasicBlock *MBB = MF->getBlockNumbered(I);
262    MBBInfo &Block = MBBs[I];
263
264    // Record the alignment, for quick access.
265    Block.Alignment = MBB->getAlignment();
266
267    // Calculate the size of the fixed part of the block.
268    MachineBasicBlock::iterator MI = MBB->begin();
269    MachineBasicBlock::iterator End = MBB->end();
270    while (MI != End && !MI->isTerminator()) {
271      Block.Size += TII->getInstSizeInBytes(MI);
272      ++MI;
273    }
274    skipNonTerminators(Position, Block);
275
276    // Add the terminators.
277    while (MI != End) {
278      if (!MI->isDebugValue()) {
279        assert(MI->isTerminator() && "Terminator followed by non-terminator");
280        Terminators.push_back(describeTerminator(MI));
281        skipTerminator(Position, Terminators.back(), false);
282        ++Block.NumTerminators;
283      }
284      ++MI;
285    }
286  }
287
288  return Position.Address;
289}
290
291// Return true if, under current assumptions, Terminator would need to be
292// relaxed if it were placed at address Address.
293bool SystemZLongBranch::mustRelaxBranch(const TerminatorInfo &Terminator,
294                                        uint64_t Address) {
295  if (!Terminator.Branch)
296    return false;
297
298  const MBBInfo &Target = MBBs[Terminator.TargetBlock];
299  if (Address >= Target.Address) {
300    if (Address - Target.Address <= MaxBackwardRange)
301      return false;
302  } else {
303    if (Target.Address - Address <= MaxForwardRange)
304      return false;
305  }
306
307  return true;
308}
309
310// Return true if, under current assumptions, any terminator needs
311// to be relaxed.
312bool SystemZLongBranch::mustRelaxABranch() {
313  for (SmallVectorImpl<TerminatorInfo>::iterator TI = Terminators.begin(),
314         TE = Terminators.end(); TI != TE; ++TI)
315    if (mustRelaxBranch(*TI, TI->Address))
316      return true;
317  return false;
318}
319
320// Set the address of each block on the assumption that all branches
321// must be long.
322void SystemZLongBranch::setWorstCaseAddresses() {
323  SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
324  BlockPosition Position(MF->getAlignment());
325  for (SmallVectorImpl<MBBInfo>::iterator BI = MBBs.begin(), BE = MBBs.end();
326       BI != BE; ++BI) {
327    skipNonTerminators(Position, *BI);
328    for (unsigned BTI = 0, BTE = BI->NumTerminators; BTI != BTE; ++BTI) {
329      skipTerminator(Position, *TI, true);
330      ++TI;
331    }
332  }
333}
334
335// Split MI into the comparison given by CompareOpcode followed
336// a BRCL on the result.
337void SystemZLongBranch::splitCompareBranch(MachineInstr *MI,
338                                           unsigned CompareOpcode) {
339  MachineBasicBlock *MBB = MI->getParent();
340  DebugLoc DL = MI->getDebugLoc();
341  BuildMI(*MBB, MI, DL, TII->get(CompareOpcode))
342    .addOperand(MI->getOperand(0))
343    .addOperand(MI->getOperand(1));
344  MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL))
345    .addOperand(MI->getOperand(2))
346    .addOperand(MI->getOperand(3));
347  // The implicit use of CC is a killing use.
348  BRCL->getOperand(2).setIsKill();
349  MI->eraseFromParent();
350}
351
352// Relax the branch described by Terminator.
353void SystemZLongBranch::relaxBranch(TerminatorInfo &Terminator) {
354  MachineInstr *Branch = Terminator.Branch;
355  switch (Branch->getOpcode()) {
356  case SystemZ::J:
357    Branch->setDesc(TII->get(SystemZ::JG));
358    break;
359  case SystemZ::BRC:
360    Branch->setDesc(TII->get(SystemZ::BRCL));
361    break;
362  case SystemZ::CRJ:
363    splitCompareBranch(Branch, SystemZ::CR);
364    break;
365  case SystemZ::CGRJ:
366    splitCompareBranch(Branch, SystemZ::CGR);
367    break;
368  case SystemZ::CIJ:
369    splitCompareBranch(Branch, SystemZ::CHI);
370    break;
371  case SystemZ::CGIJ:
372    splitCompareBranch(Branch, SystemZ::CGHI);
373    break;
374  default:
375    llvm_unreachable("Unrecognized branch");
376  }
377
378  Terminator.Size += Terminator.ExtraRelaxSize;
379  Terminator.ExtraRelaxSize = 0;
380  Terminator.Branch = 0;
381
382  ++LongBranches;
383}
384
385// Run a shortening pass and relax any branches that need to be relaxed.
386void SystemZLongBranch::relaxBranches() {
387  SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
388  BlockPosition Position(MF->getAlignment());
389  for (SmallVectorImpl<MBBInfo>::iterator BI = MBBs.begin(), BE = MBBs.end();
390       BI != BE; ++BI) {
391    skipNonTerminators(Position, *BI);
392    for (unsigned BTI = 0, BTE = BI->NumTerminators; BTI != BTE; ++BTI) {
393      assert(Position.Address <= TI->Address &&
394             "Addresses shouldn't go forwards");
395      if (mustRelaxBranch(*TI, Position.Address))
396        relaxBranch(*TI);
397      skipTerminator(Position, *TI, false);
398      ++TI;
399    }
400  }
401}
402
403bool SystemZLongBranch::runOnMachineFunction(MachineFunction &F) {
404  TII = static_cast<const SystemZInstrInfo *>(F.getTarget().getInstrInfo());
405  MF = &F;
406  uint64_t Size = initMBBInfo();
407  if (Size <= MaxForwardRange || !mustRelaxABranch())
408    return false;
409
410  setWorstCaseAddresses();
411  relaxBranches();
412  return true;
413}
414