LLVM 24.0.0git
SystemZLongBranch.cpp
Go to the documentation of this file.
1//===-- SystemZLongBranch.cpp - Branch lengthening for SystemZ ------------===//
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 pass makes sure that all branches are in range. There are several ways
10// in which this could be done. One aggressive approach is to assume that all
11// branches are in range and successively replace those that turn out not
12// to be in range with a longer form (branch relaxation). A simple
13// implementation is to continually walk through the function relaxing
14// branches until no more changes are needed and a fixed point is reached.
15// However, in the pathological worst case, this implementation is
16// quadratic in the number of blocks; relaxing branch N can make branch N-1
17// go out of range, which in turn can make branch N-2 go out of range,
18// and so on.
19//
20// An alternative approach is to assume that all branches must be
21// converted to their long forms, then reinstate the short forms of
22// branches that, even under this pessimistic assumption, turn out to be
23// in range (branch shortening). This too can be implemented as a function
24// walk that is repeated until a fixed point is reached. In general,
25// the result of shortening is not as good as that of relaxation, and
26// shortening is also quadratic in the worst case; shortening branch N
27// can bring branch N-1 in range of the short form, which in turn can do
28// the same for branch N-2, and so on. The main advantage of shortening
29// is that each walk through the function produces valid code, so it is
30// possible to stop at any point after the first walk. The quadraticness
31// could therefore be handled with a maximum pass count, although the
32// question then becomes: what maximum count should be used?
33//
34// On SystemZ, long branches are only needed for functions bigger than 64k,
35// which are relatively rare to begin with, and the long branch sequences
36// are actually relatively cheap. It therefore doesn't seem worth spending
37// much compilation time on the problem. Instead, the approach we take is:
38//
39// (1) Work out the address that each block would have if no branches
40// need relaxing. Exit the pass early if all branches are in range
41// according to this assumption.
42//
43// (2) Work out the address that each block would have if all branches
44// need relaxing.
45//
46// (3) Walk through the block calculating the final address of each instruction
47// and relaxing those that need to be relaxed. For backward branches,
48// this check uses the final address of the target block, as calculated
49// earlier in the walk. For forward branches, this check uses the
50// address of the target block that was calculated in (2). Both checks
51// give a conservatively-correct range.
52//
53//===----------------------------------------------------------------------===//
54
55#include "SystemZ.h"
56#include "SystemZInstrInfo.h"
59#include "llvm/ADT/Statistic.h"
60#include "llvm/ADT/StringRef.h"
68#include "llvm/IR/Analysis.h"
69#include "llvm/IR/DebugLoc.h"
70#include "llvm/Pass.h"
72#include <cassert>
73#include <cstdint>
74
75using namespace llvm;
76
77#define DEBUG_TYPE "systemz-long-branch"
78
79STATISTIC(LongBranches, "Number of long branches.");
80
81namespace {
82
83// Represents positional information about a basic block.
84struct MBBInfo {
85 // The address that we currently assume the block has.
86 uint64_t Address = 0;
87
88 // The size of the block in bytes, excluding terminators.
89 // This value never changes.
90 uint64_t Size = 0;
91
92 // The minimum alignment of the block.
93 // This value never changes.
94 Align Alignment;
95
96 // The number of terminators in this block. This value never changes.
97 unsigned NumTerminators = 0;
98
99 MBBInfo() = default;
100};
101
102// Represents the state of a block terminator.
103struct TerminatorInfo {
104 // If this terminator is a relaxable branch, this points to the branch
105 // instruction, otherwise it is null.
106 MachineInstr *Branch = nullptr;
107
108 // The address that we currently assume the terminator has.
109 uint64_t Address = 0;
110
111 // The current size of the terminator in bytes.
112 uint64_t Size = 0;
113
114 // If Branch is nonnull, this is the number of the target block,
115 // otherwise it is unused.
116 unsigned TargetBlock = 0;
117
118 // If Branch is nonnull, this is the length of the longest relaxed form,
119 // otherwise it is zero.
120 unsigned ExtraRelaxSize = 0;
121
122 TerminatorInfo() = default;
123};
124
125// Used to keep track of the current position while iterating over the blocks.
126struct BlockPosition {
127 // The address that we assume this position has.
128 uint64_t Address = 0;
129
130 // The number of low bits in Address that are known to be the same
131 // as the runtime address.
132 unsigned KnownBits;
133
134 BlockPosition(unsigned InitialLogAlignment)
135 : KnownBits(InitialLogAlignment) {}
136};
137
138class SystemZLongBranchLegacy : public MachineFunctionPass {
139public:
140 static char ID;
141
142 SystemZLongBranchLegacy() : MachineFunctionPass(ID) {}
143
144 bool runOnMachineFunction(MachineFunction &F) override;
145
146 MachineFunctionProperties getRequiredProperties() const override {
147 return MachineFunctionProperties().setNoVRegs();
148 }
149
150 void getAnalysisUsage(AnalysisUsage &AU) const override {
151 AU.setPreservesCFG();
153 }
154};
155
156class SystemZLongBranchImpl {
157 void skipNonTerminators(BlockPosition &Position, MBBInfo &Block);
158 void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator,
159 bool AssumeRelaxed);
160 TerminatorInfo describeTerminator(MachineInstr &MI);
161 uint64_t initMBBInfo();
162 bool mustRelaxBranch(const TerminatorInfo &Terminator, uint64_t Address);
163 bool mustRelaxABranch();
164 void setWorstCaseAddresses();
165 void splitBranchOnCount(MachineInstr *MI, unsigned AddOpcode);
166 void splitCompareBranch(MachineInstr *MI, unsigned CompareOpcode);
167 void relaxBranch(TerminatorInfo &Terminator);
168 void relaxBranches();
169
170 const SystemZInstrInfo *TII = nullptr;
171 MachineFunction *MF = nullptr;
174
175public:
176 bool runOnMachineFunction(MachineFunction &MF);
177};
178
179char SystemZLongBranchLegacy::ID = 0;
180
181const uint64_t MaxBackwardRange = 0x10000;
182const uint64_t MaxForwardRange = 0xfffe;
183
184} // end anonymous namespace
185
186INITIALIZE_PASS(SystemZLongBranchLegacy, DEBUG_TYPE, "SystemZ Long Branch",
187 false, false)
188
189// Position describes the state immediately before Block. Update Block
190// accordingly and move Position to the end of the block's non-terminator
191// instructions.
192void SystemZLongBranchImpl::skipNonTerminators(BlockPosition &Position,
193 MBBInfo &Block) {
194 if (Log2(Block.Alignment) > Position.KnownBits) {
195 // When calculating the address of Block, we need to conservatively
196 // assume that Block had the worst possible misalignment.
197 Position.Address +=
198 (Block.Alignment.value() - (uint64_t(1) << Position.KnownBits));
199 Position.KnownBits = Log2(Block.Alignment);
200 }
201
202 // Align the addresses.
203 Position.Address = alignTo(Position.Address, Block.Alignment);
204
205 // Record the block's position.
206 Block.Address = Position.Address;
207
208 // Move past the non-terminators in the block.
209 Position.Address += Block.Size;
210}
211
212// Position describes the state immediately before Terminator.
213// Update Terminator accordingly and move Position past it.
214// Assume that Terminator will be relaxed if AssumeRelaxed.
215void SystemZLongBranchImpl::skipTerminator(BlockPosition &Position,
216 TerminatorInfo &Terminator,
217 bool AssumeRelaxed) {
218 Terminator.Address = Position.Address;
219 Position.Address += Terminator.Size;
220 if (AssumeRelaxed)
221 Position.Address += Terminator.ExtraRelaxSize;
222}
223
224static unsigned getInstSizeInBytes(const MachineInstr &MI,
225 const SystemZInstrInfo *TII) {
226 unsigned Size = TII->getInstSizeInBytes(MI);
227 assert((Size ||
228 // These do not have a size:
229 MI.isDebugOrPseudoInstr() || MI.isPosition() || MI.isKill() ||
230 MI.isImplicitDef() || MI.getOpcode() == TargetOpcode::MEMBARRIER ||
231 MI.getOpcode() == TargetOpcode::INIT_UNDEF || MI.isFakeUse() ||
232 MI.getOpcode() == TargetOpcode::RELOC_NONE ||
233 MI.getOpcode() == SystemZ::FENCE ||
234 // These have a size that may be zero:
235 MI.isInlineAsm() || MI.getOpcode() == SystemZ::STACKMAP ||
236 MI.getOpcode() == SystemZ::PATCHPOINT ||
237 // EH_SjLj_Setup is a dummy terminator instruction of size 0,
238 // It is used to handle the clobber register for builtin setjmp.
239 MI.getOpcode() == SystemZ::EH_SjLj_Setup) &&
240 "Missing size value for instruction.");
241 return Size;
242}
243
244// Return a description of terminator instruction MI.
245TerminatorInfo SystemZLongBranchImpl::describeTerminator(MachineInstr &MI) {
246 TerminatorInfo Terminator;
248 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
249 switch (MI.getOpcode()) {
250 case SystemZ::J:
251 // Relaxes to JG, which is 2 bytes longer.
252 Terminator.ExtraRelaxSize = 2;
253 break;
254 case SystemZ::BRC:
255 // Relaxes to BRCL, which is 2 bytes longer.
256 Terminator.ExtraRelaxSize = 2;
257 break;
258 case SystemZ::BRCT:
259 case SystemZ::BRCTG:
260 // Relaxes to A(G)HI and BRCL, which is 6 bytes longer.
261 Terminator.ExtraRelaxSize = 6;
262 break;
263 case SystemZ::BRCTH:
264 // Never needs to be relaxed.
265 Terminator.ExtraRelaxSize = 0;
266 break;
267 case SystemZ::CRJ:
268 case SystemZ::CLRJ:
269 // Relaxes to a C(L)R/BRCL sequence, which is 2 bytes longer.
270 Terminator.ExtraRelaxSize = 2;
271 break;
272 case SystemZ::CGRJ:
273 case SystemZ::CLGRJ:
274 // Relaxes to a C(L)GR/BRCL sequence, which is 4 bytes longer.
275 Terminator.ExtraRelaxSize = 4;
276 break;
277 case SystemZ::CIJ:
278 case SystemZ::CGIJ:
279 // Relaxes to a C(G)HI/BRCL sequence, which is 4 bytes longer.
280 Terminator.ExtraRelaxSize = 4;
281 break;
282 case SystemZ::CLIJ:
283 case SystemZ::CLGIJ:
284 // Relaxes to a CL(G)FI/BRCL sequence, which is 6 bytes longer.
285 Terminator.ExtraRelaxSize = 6;
286 break;
287 default:
288 llvm_unreachable("Unrecognized branch instruction");
289 }
290 Terminator.Branch = &MI;
291 Terminator.TargetBlock =
292 TII->getBranchInfo(MI).getMBBTarget()->getNumber();
293 }
294 return Terminator;
295}
296
297// Fill MBBs and Terminators, setting the addresses on the assumption
298// that no branches need relaxation. Return the size of the function under
299// this assumption.
300uint64_t SystemZLongBranchImpl::initMBBInfo() {
301 MF->RenumberBlocks();
302 unsigned NumBlocks = MF->size();
303
304 MBBs.clear();
305 MBBs.resize(NumBlocks);
306
307 Terminators.clear();
308 Terminators.reserve(NumBlocks);
309
310 BlockPosition Position(Log2(MF->getAlignment()));
311 for (unsigned I = 0; I < NumBlocks; ++I) {
312 MachineBasicBlock *MBB = MF->getBlockNumbered(I);
313 MBBInfo &Block = MBBs[I];
314
315 // Record the alignment, for quick access.
316 Block.Alignment = MBB->getAlignment();
317
318 // Calculate the size of the fixed part of the block.
321 while (MI != End && !MI->isTerminator()) {
322 Block.Size += getInstSizeInBytes(*MI, TII);
323 ++MI;
324 }
325 skipNonTerminators(Position, Block);
326
327 // Add the terminators.
328 while (MI != End) {
329 if (!MI->isDebugInstr()) {
330 assert(MI->isTerminator() && "Terminator followed by non-terminator");
331 Terminators.push_back(describeTerminator(*MI));
332 skipTerminator(Position, Terminators.back(), false);
333 ++Block.NumTerminators;
334 }
335 ++MI;
336 }
337 }
338
339 return Position.Address;
340}
341
342// Return true if, under current assumptions, Terminator would need to be
343// relaxed if it were placed at address Address.
344bool SystemZLongBranchImpl::mustRelaxBranch(const TerminatorInfo &Terminator,
346 if (!Terminator.Branch || Terminator.ExtraRelaxSize == 0)
347 return false;
348
349 const MBBInfo &Target = MBBs[Terminator.TargetBlock];
350 if (Address >= Target.Address) {
351 if (Address - Target.Address <= MaxBackwardRange)
352 return false;
353 } else {
354 if (Target.Address - Address <= MaxForwardRange)
355 return false;
356 }
357
358 return true;
359}
360
361// Return true if, under current assumptions, any terminator needs
362// to be relaxed.
363bool SystemZLongBranchImpl::mustRelaxABranch() {
364 for (auto &Terminator : Terminators)
365 if (mustRelaxBranch(Terminator, Terminator.Address))
366 return true;
367 return false;
368}
369
370// Set the address of each block on the assumption that all branches
371// must be long.
372void SystemZLongBranchImpl::setWorstCaseAddresses() {
373 SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
374 BlockPosition Position(Log2(MF->getAlignment()));
375 for (auto &Block : MBBs) {
376 skipNonTerminators(Position, Block);
377 for (unsigned BTI = 0, BTE = Block.NumTerminators; BTI != BTE; ++BTI) {
378 skipTerminator(Position, *TI, true);
379 ++TI;
380 }
381 }
382}
383
384// Split BRANCH ON COUNT MI into the addition given by AddOpcode followed
385// by a BRCL on the result.
386void SystemZLongBranchImpl::splitBranchOnCount(MachineInstr *MI,
387 unsigned AddOpcode) {
388 MachineBasicBlock *MBB = MI->getParent();
389 DebugLoc DL = MI->getDebugLoc();
390 MachineInstr *AddImm = BuildMI(*MBB, MI, DL, TII->get(AddOpcode))
391 .add(MI->getOperand(0))
392 .add(MI->getOperand(1))
393 .addImm(-1);
394 MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL))
397 .add(MI->getOperand(2));
398 // The implicit use of CC is a killing use.
399 BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo());
400 // The result of the BRANCH ON COUNT MI is the new count in register 0, so the
401 // debug tracking needs to go to the result of the Add immediate.
403 MI->eraseFromParent();
404}
405
406// Split MI into the comparison given by CompareOpcode followed
407// a BRCL on the result.
408void SystemZLongBranchImpl::splitCompareBranch(MachineInstr *MI,
409 unsigned CompareOpcode) {
410 MachineBasicBlock *MBB = MI->getParent();
411 DebugLoc DL = MI->getDebugLoc();
412 BuildMI(*MBB, MI, DL, TII->get(CompareOpcode))
413 .add(MI->getOperand(0))
414 .add(MI->getOperand(1));
415 MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL))
417 .add(MI->getOperand(2))
418 .add(MI->getOperand(3));
419 // The implicit use of CC is a killing use.
420 BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo());
421 // Since we are replacing branches that did not compute any value, no debug
422 // value substitution is necessary.
423 MI->eraseFromParent();
424}
425
426// Relax the branch described by Terminator.
427void SystemZLongBranchImpl::relaxBranch(TerminatorInfo &Terminator) {
428 MachineInstr *Branch = Terminator.Branch;
429 switch (Branch->getOpcode()) {
430 case SystemZ::J:
431 Branch->setDesc(TII->get(SystemZ::JG));
432 break;
433 case SystemZ::BRC:
434 Branch->setDesc(TII->get(SystemZ::BRCL));
435 break;
436 case SystemZ::BRCT:
437 splitBranchOnCount(Branch, SystemZ::AHI);
438 break;
439 case SystemZ::BRCTG:
440 splitBranchOnCount(Branch, SystemZ::AGHI);
441 break;
442 case SystemZ::CRJ:
443 splitCompareBranch(Branch, SystemZ::CR);
444 break;
445 case SystemZ::CGRJ:
446 splitCompareBranch(Branch, SystemZ::CGR);
447 break;
448 case SystemZ::CIJ:
449 splitCompareBranch(Branch, SystemZ::CHI);
450 break;
451 case SystemZ::CGIJ:
452 splitCompareBranch(Branch, SystemZ::CGHI);
453 break;
454 case SystemZ::CLRJ:
455 splitCompareBranch(Branch, SystemZ::CLR);
456 break;
457 case SystemZ::CLGRJ:
458 splitCompareBranch(Branch, SystemZ::CLGR);
459 break;
460 case SystemZ::CLIJ:
461 splitCompareBranch(Branch, SystemZ::CLFI);
462 break;
463 case SystemZ::CLGIJ:
464 splitCompareBranch(Branch, SystemZ::CLGFI);
465 break;
466 default:
467 llvm_unreachable("Unrecognized branch");
468 }
469
470 Terminator.Size += Terminator.ExtraRelaxSize;
471 Terminator.ExtraRelaxSize = 0;
472 Terminator.Branch = nullptr;
473
474 ++LongBranches;
475}
476
477// Run a shortening pass and relax any branches that need to be relaxed.
478void SystemZLongBranchImpl::relaxBranches() {
479 SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
480 BlockPosition Position(Log2(MF->getAlignment()));
481 for (auto &Block : MBBs) {
482 skipNonTerminators(Position, Block);
483 for (unsigned BTI = 0, BTE = Block.NumTerminators; BTI != BTE; ++BTI) {
484 assert(Position.Address <= TI->Address &&
485 "Addresses shouldn't go forwards");
486 if (mustRelaxBranch(*TI, Position.Address))
487 relaxBranch(*TI);
488 skipTerminator(Position, *TI, false);
489 ++TI;
490 }
491 }
492}
493
494bool SystemZLongBranchImpl::runOnMachineFunction(MachineFunction &F) {
495 TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
496 MF = &F;
497 uint64_t Size = initMBBInfo();
498 if (Size <= MaxForwardRange || !mustRelaxABranch())
499 return false;
500
501 setWorstCaseAddresses();
502 relaxBranches();
503 return true;
504}
505
506FunctionPass *
508 return new SystemZLongBranchLegacy();
509}
510
511bool SystemZLongBranchLegacy::runOnMachineFunction(MachineFunction &MF) {
512 SystemZLongBranchImpl Impl;
513 return Impl.runOnMachineFunction(MF);
514}
515
516PreservedAnalyses
519 SystemZLongBranchImpl Impl;
520 return Impl.runOnMachineFunction(MF)
524}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static unsigned getInstSizeInBytes(const MachineInstr &MI, const SystemZInstrInfo *TII)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
const HexagonRegisterInfo & getRegisterInfo() const
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New, unsigned MaxOperand=UINT_MAX)
Create substitutions for any tracked values in Old, to point at New.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
Align getAlignment() const
getAlignment - Return the alignment of the function.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
LLVM_ABI bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const unsigned CCMASK_ICMP
Definition SystemZ.h:53
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:44
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
FunctionPass * createSystemZLongBranchLegacyPass(SystemZTargetMachine &TM)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39