blob: d027d5b154ebaf7145838d84dac017cd768188c7 [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- BranchRelaxation.cpp -----------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00008
Tim Northover3b0846e2014-05-24 12:50:23 +00009#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000010#include "llvm/ADT/Statistic.h"
Matthias Braun18198302016-12-16 23:55:37 +000011#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000012#include "llvm/CodeGen/MachineBasicBlock.h"
13#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000014#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000015#include "llvm/CodeGen/MachineInstr.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000016#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000017#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000018#include "llvm/CodeGen/TargetRegisterInfo.h"
19#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000020#include "llvm/Config/llvm-config.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000021#include "llvm/IR/DebugLoc.h"
22#include "llvm/Pass.h"
23#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000024#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/Format.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000026#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/Support/raw_ostream.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000028#include <cassert>
29#include <cstdint>
30#include <iterator>
31#include <memory>
Matt Arsenault36919a42016-10-06 15:38:53 +000032
Tim Northover3b0846e2014-05-24 12:50:23 +000033using namespace llvm;
34
Matt Arsenault36919a42016-10-06 15:38:53 +000035#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000036
Tim Northover3b0846e2014-05-24 12:50:23 +000037STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000038STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000039STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000040
Matt Arsenault36919a42016-10-06 15:38:53 +000041#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000042
Tim Northover3b0846e2014-05-24 12:50:23 +000043namespace {
Eugene Zelenko618c5552017-09-13 21:15:20 +000044
Matt Arsenault36919a42016-10-06 15:38:53 +000045class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000046 /// BasicBlockInfo - Information about the offset and size of a single
47 /// basic block.
48 struct BasicBlockInfo {
49 /// Offset - Distance from the beginning of the function to the beginning
50 /// of this basic block.
51 ///
52 /// The offset is always aligned as required by the basic block.
Eugene Zelenko618c5552017-09-13 21:15:20 +000053 unsigned Offset = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000054
55 /// Size - Size of the basic block in bytes. If the block contains
56 /// inline assembly, this is a worst case estimate.
57 ///
58 /// The size does not include any alignment padding whether from the
59 /// beginning of the block, or from an aligned jump table at the end.
Eugene Zelenko618c5552017-09-13 21:15:20 +000060 unsigned Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Eugene Zelenko618c5552017-09-13 21:15:20 +000062 BasicBlockInfo() = default;
Tim Northover3b0846e2014-05-24 12:50:23 +000063
Matt Arsenaultef5bba02016-10-06 16:00:58 +000064 /// Compute the offset immediately following this block. \p MBB is the next
65 /// block.
66 unsigned postOffset(const MachineBasicBlock &MBB) const {
Guillaume Chatelet48904e92019-09-11 11:16:48 +000067 const unsigned PO = Offset + Size;
68 const llvm::Align Align = MBB.getAlignment();
69 if (Align == 1)
Matt Arsenaultef5bba02016-10-06 16:00:58 +000070 return PO;
71
Guillaume Chatelet48904e92019-09-11 11:16:48 +000072 const llvm::Align ParentAlign = MBB.getParent()->getAlignment();
73 if (Align <= ParentAlign)
74 return PO + OffsetToAlignment(PO, Align.value());
Matt Arsenaultef5bba02016-10-06 16:00:58 +000075
76 // The alignment of this MBB is larger than the function's alignment, so we
77 // can't tell whether or not it will insert nops. Assume that it will.
Guillaume Chatelet48904e92019-09-11 11:16:48 +000078 return PO + Align.value() + OffsetToAlignment(PO, Align.value());
Tim Northover3b0846e2014-05-24 12:50:23 +000079 }
80 };
81
82 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000083 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000084 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000085
86 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000087 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000088 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000089
90 bool relaxBranchInstructions();
91 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000092
93 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
94
Matt Arsenault44deb792016-11-02 16:18:29 +000095 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
96 MachineBasicBlock *DestBB);
Fangrui Songcb0bab82018-07-16 18:51:40 +000097 void adjustBlockOffsets(MachineBasicBlock &Start);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000098 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000099
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000100 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000101 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000102 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000103 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +0000104 void dumpBBs();
105 void verify();
106
107public:
108 static char ID;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000109
110 BranchRelaxation() : MachineFunctionPass(ID) {}
Tim Northover3b0846e2014-05-24 12:50:23 +0000111
112 bool runOnMachineFunction(MachineFunction &MF) override;
113
Eugene Zelenko618c5552017-09-13 21:15:20 +0000114 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000115};
Matt Arsenault36919a42016-10-06 15:38:53 +0000116
Eugene Zelenko618c5552017-09-13 21:15:20 +0000117} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000118
Matt Arsenault36919a42016-10-06 15:38:53 +0000119char BranchRelaxation::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000120
Matt Arsenault36919a42016-10-06 15:38:53 +0000121char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
122
123INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000124
Tim Northover3b0846e2014-05-24 12:50:23 +0000125/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000126void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000127#ifndef NDEBUG
128 unsigned PrevNum = MF->begin()->getNumber();
129 for (MachineBasicBlock &MBB : *MF) {
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000130 unsigned LogAlign = MBB.getLogAlignment();
Tim Northover3b0846e2014-05-24 12:50:23 +0000131 unsigned Num = MBB.getNumber();
Guillaume Chateletaff45e42019-09-05 10:00:22 +0000132 assert(BlockInfo[Num].Offset % (1u << LogAlign) == 0);
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000133 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000134 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000135 PrevNum = Num;
136 }
137#endif
138}
139
Aaron Ballman615eb472017-10-15 14:32:27 +0000140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000141/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000142LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 for (auto &MBB : *MF) {
144 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
Evgeniy Stepanov187c63f2019-08-16 18:23:54 +0000145 dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
Tim Northover3b0846e2014-05-24 12:50:23 +0000146 << format("size=%#x\n", BBI.Size);
147 }
148}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000149#endif
Tim Northover3b0846e2014-05-24 12:50:23 +0000150
Tim Northover3b0846e2014-05-24 12:50:23 +0000151/// scanFunction - Do the initial scan of the function, building up
152/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000153void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000154 BlockInfo.clear();
155 BlockInfo.resize(MF->getNumBlockIDs());
156
157 // First thing, compute the size of all basic blocks, and see if the function
158 // has any inline assembly in it. If so, we have to be conservative about
159 // alignment assumptions, as we don't know for sure the size of any
160 // instructions in the inline assembly.
161 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000162 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000163
164 // Compute block offsets and known bits.
165 adjustBlockOffsets(*MF->begin());
166}
167
168/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000169uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
170 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000171 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000172 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000173 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000174}
175
176/// getInstrOffset - Return the current offset of the specified machine
177/// instruction from the start of the function. This offset changes as stuff is
178/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000179unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000180 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000181
182 // The offset is composed of two things: the sum of the sizes of all MBB's
183 // before this instruction's block, and the offset from the start of the block
184 // it is in.
185 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
186
187 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000188 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000190 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000192
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 return Offset;
194}
195
Matt Arsenault36919a42016-10-06 15:38:53 +0000196void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000197 unsigned PrevNum = Start.getNumber();
198 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
199 unsigned Num = MBB.getNumber();
200 if (!Num) // block zero is never changed from offset zero.
201 continue;
202 // Get the offset and known bits at the end of the layout predecessor.
203 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000204 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
205
Tim Northover3b0846e2014-05-24 12:50:23 +0000206 PrevNum = Num;
207 }
208}
209
Eugene Zelenko618c5552017-09-13 21:15:20 +0000210/// Insert a new empty basic block and insert it after \BB
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000211MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
212 // Create a new MBB for the code after the OrigBB.
213 MachineBasicBlock *NewBB =
214 MF->CreateMachineBasicBlock(BB.getBasicBlock());
215 MF->insert(++BB.getIterator(), NewBB);
216
217 // Insert an entry into BlockInfo to align it properly with the block numbers.
218 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
219
220 return NewBB;
221}
222
Tim Northover3b0846e2014-05-24 12:50:23 +0000223/// Split the basic block containing MI into two blocks, which are joined by
224/// an unconditional branch. Update data structures and renumber blocks to
225/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000226MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
227 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000228 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000229
230 // Create a new MBB for the code after the OrigBB.
231 MachineBasicBlock *NewBB =
232 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000233 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000234
235 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000236 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000237
238 // Add an unconditional branch from OrigBB to NewBB.
239 // Note the new unconditional branch is not being recorded.
240 // There doesn't seem to be meaningful DebugInfo available; this doesn't
241 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000242 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000243
244 // Insert an entry into BlockInfo to align it properly with the block numbers.
245 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
246
Matt Arsenault44deb792016-11-02 16:18:29 +0000247 NewBB->transferSuccessors(OrigBB);
248 OrigBB->addSuccessor(NewBB);
249 OrigBB->addSuccessor(DestBB);
250
251 // Cleanup potential unconditional branch to successor block.
252 // Note that updateTerminator may change the size of the blocks.
253 NewBB->updateTerminator();
254 OrigBB->updateTerminator();
255
Tim Northover3b0846e2014-05-24 12:50:23 +0000256 // Figure out how large the OrigBB is. As the first half of the original
257 // block, it cannot contain a tablejump. The size includes
258 // the new jump we added. (It should be possible to do this without
259 // recounting everything, but it's very confusing, and this is rarely
260 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000261 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000262
Matt Arsenault36919a42016-10-06 15:38:53 +0000263 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000264 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000265 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000266
267 // All BBOffsets following these blocks must be modified.
268 adjustBlockOffsets(*OrigBB);
269
Matthias Braun18198302016-12-16 23:55:37 +0000270 // Need to fix live-in lists if we track liveness.
271 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braunc9056b82017-09-06 20:45:24 +0000272 computeAndAddLiveIns(LiveRegs, *NewBB);
Matthias Braun18198302016-12-16 23:55:37 +0000273
Tim Northover3b0846e2014-05-24 12:50:23 +0000274 ++NumSplit;
275
276 return NewBB;
277}
278
279/// isBlockInRange - Returns true if the distance between specific MI and
280/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000281bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000282 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000283 int64_t BrOffset = getInstrOffset(MI);
284 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000285
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000286 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000287 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000288
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000289 LLVM_DEBUG(dbgs() << "Out of range branch to destination "
290 << printMBBReference(DestBB) << " from "
291 << printMBBReference(*MI.getParent()) << " to "
292 << DestOffset << " offset " << DestOffset - BrOffset << '\t'
293 << MI);
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000294
295 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000296}
297
Tim Northover3b0846e2014-05-24 12:50:23 +0000298/// fixupConditionalBranch - Fix up a conditional branch whose destination is
299/// too far away to fit in its displacement field. It is converted to an inverse
300/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000301bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Chandler Carruthbbddf212019-04-23 01:42:07 +0000302 DebugLoc DL = MI.getDebugLoc();
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000303 MachineBasicBlock *MBB = MI.getParent();
304 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000305 MachineBasicBlock *NewBB = nullptr;
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000306 SmallVector<MachineOperand, 4> Cond;
307
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000308 auto insertUncondBranch = [&](MachineBasicBlock *MBB,
309 MachineBasicBlock *DestBB) {
310 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
311 int NewBrSize = 0;
312 TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
313 BBSize += NewBrSize;
314 };
315 auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
316 MachineBasicBlock *FBB,
317 SmallVectorImpl<MachineOperand>& Cond) {
318 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
319 int NewBrSize = 0;
320 TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
321 BBSize += NewBrSize;
322 };
323 auto removeBranch = [&](MachineBasicBlock *MBB) {
324 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
325 int RemovedSize = 0;
326 TII->removeBranch(*MBB, &RemovedSize);
327 BBSize -= RemovedSize;
328 };
329
330 auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
331 MachineBasicBlock *NewBB) {
332 // Keep the block offsets up to date.
333 adjustBlockOffsets(*MBB);
334
335 // Need to fix live-in lists if we track liveness.
336 if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
337 computeAndAddLiveIns(LiveRegs, *NewBB);
338 };
339
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000340 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
341 assert(!Fail && "branches to be relaxed must be analyzable");
342 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000343
344 // Add an unconditional branch to the destination and invert the branch
345 // condition to jump over it:
346 // tbz L1
347 // =>
348 // tbnz L2
349 // b L1
350 // L2:
351
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000352 bool ReversedCond = !TII->reverseBranchCondition(Cond);
353 if (ReversedCond) {
354 if (FBB && isBlockInRange(MI, *FBB)) {
355 // Last MI in the BB is an unconditional branch. We can simply invert the
356 // condition and swap destinations:
357 // beq L1
358 // b L2
359 // =>
360 // bne L2
361 // b L1
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000362 LLVM_DEBUG(dbgs() << " Invert condition and swap "
363 "its destination with "
364 << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000365
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000366 removeBranch(MBB);
367 insertBranch(MBB, FBB, TBB, Cond);
368 finalizeBlockChanges(MBB, nullptr);
369 return true;
370 }
371 if (FBB) {
372 // We need to split the basic block here to obtain two long-range
373 // unconditional branches.
374 NewBB = createNewBlockAfter(*MBB);
Matt Arsenault5b549712016-08-02 08:30:06 +0000375
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000376 insertUncondBranch(NewBB, FBB);
377 // Update the succesor lists according to the transformation to follow.
378 // Do it here since if there's no split, no update is needed.
379 MBB->replaceSuccessor(FBB, NewBB);
380 NewBB->addSuccessor(FBB);
381 }
382
383 // We now have an appropriate fall-through block in place (either naturally or
384 // just created), so we can use the inverted the condition.
385 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
386
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000387 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
388 << ", invert condition and change dest. to "
389 << printMBBReference(NextBB) << '\n');
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000390
391 removeBranch(MBB);
392 // Insert a new conditional branch and a new unconditional branch.
393 insertBranch(MBB, &NextBB, TBB, Cond);
394
395 finalizeBlockChanges(MBB, NewBB);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000396 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000397 }
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000398 // Branch cond can't be inverted.
399 // In this case we always add a block after the MBB.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000400 LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
401 << " Insert a new BB after " << MBB->back());
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000402
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000403 if (!FBB)
404 FBB = &(*std::next(MachineFunction::iterator(MBB)));
Tim Northover3b0846e2014-05-24 12:50:23 +0000405
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000406 // This is the block with cond. branch and the distance to TBB is too long.
407 // beq L1
408 // L2:
Tim Northover3b0846e2014-05-24 12:50:23 +0000409
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000410 // We do the following transformation:
411 // beq NewBB
412 // b L2
413 // NewBB:
414 // b L1
415 // L2:
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000416
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000417 NewBB = createNewBlockAfter(*MBB);
418 insertUncondBranch(NewBB, TBB);
Matt Arsenault5b549712016-08-02 08:30:06 +0000419
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000420 LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
421 << printMBBReference(*NewBB)
422 << " Keep the exiting condition.\n"
423 << " Insert B to " << printMBBReference(*FBB) << ".\n"
424 << " In the new BB: Insert B to "
425 << printMBBReference(*TBB) << ".\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000426
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000427 // Update the successor lists according to the transformation to follow.
428 MBB->replaceSuccessor(TBB, NewBB);
429 NewBB->addSuccessor(TBB);
430
431 // Replace branch in the current (MBB) block.
432 removeBranch(MBB);
433 insertBranch(MBB, NewBB, FBB, Cond);
434
435 finalizeBlockChanges(MBB, NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000436 return true;
437}
438
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000439bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
440 MachineBasicBlock *MBB = MI.getParent();
441
442 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
443 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
444
445 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
446 int64_t SrcOffset = getInstrOffset(MI);
447
448 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
449
450 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
451
452 MachineBasicBlock *BranchBB = MBB;
453
454 // If this was an expanded conditional branch, there is already a single
455 // unconditional branch in a block.
456 if (!MBB->empty()) {
457 BranchBB = createNewBlockAfter(*MBB);
458
459 // Add live outs.
460 for (const MachineBasicBlock *Succ : MBB->successors()) {
461 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
462 BranchBB->addLiveIn(LiveIn);
463 }
464
Matt Arsenault691efe02016-10-12 15:32:04 +0000465 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000466 BranchBB->addSuccessor(DestBB);
467 MBB->replaceSuccessor(DestBB, BranchBB);
468 }
469
Chandler Carruthbbddf212019-04-23 01:42:07 +0000470 DebugLoc DL = MI.getDebugLoc();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000471 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000472 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000473 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
474
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000475 adjustBlockOffsets(*MBB);
476 return true;
477}
478
Matt Arsenault36919a42016-10-06 15:38:53 +0000479bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000480 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000481
Tim Northover3b0846e2014-05-24 12:50:23 +0000482 // Relaxing branches involves creating new basic blocks, so re-eval
483 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000484 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
485 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000486
Matthias Braun18198302016-12-16 23:55:37 +0000487 // Empty block?
488 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
489 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000490 continue;
491
492 // Expand the unconditional branch first if necessary. If there is a
493 // conditional branch, this will end up changing the branch destination of
494 // it to be over the newly inserted indirect branch block, which may avoid
495 // the need to try expanding the conditional branch first, saving an extra
496 // jump.
497 if (Last->isUnconditionalBranch()) {
498 // Unconditional branch destination might be unanalyzable, assume these
499 // are OK.
500 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
501 if (!isBlockInRange(*Last, *DestBB)) {
502 fixupUnconditionalBranch(*Last);
503 ++NumUnconditionalRelaxed;
504 Changed = true;
505 }
506 }
507 }
508
509 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000510 MachineBasicBlock::iterator Next;
511 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
512 J != MBB.end(); J = Next) {
513 Next = std::next(J);
514 MachineInstr &MI = *J;
515
516 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000517 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000518 if (!isBlockInRange(MI, *DestBB)) {
519 if (Next != MBB.end() && Next->isConditionalBranch()) {
520 // If there are multiple conditional branches, this isn't an
521 // analyzable block. Split later terminators into a new block so
522 // each one will be analyzable.
523
Matt Arsenault44deb792016-11-02 16:18:29 +0000524 splitBlockBeforeInstr(*Next, DestBB);
Matt Arsenault567631b2016-08-23 01:30:30 +0000525 } else {
526 fixupConditionalBranch(MI);
527 ++NumConditionalRelaxed;
528 }
529
530 Changed = true;
531
532 // This may have modified all of the terminators, so start over.
533 Next = MBB.getFirstTerminator();
534 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000535 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000536 }
537 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000538
Tim Northover3b0846e2014-05-24 12:50:23 +0000539 return Changed;
540}
541
Matt Arsenault36919a42016-10-06 15:38:53 +0000542bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000543 MF = &mf;
544
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000545 LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000546
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000547 const TargetSubtargetInfo &ST = MF->getSubtarget();
548 TII = ST.getInstrInfo();
549
Matthias Braun18198302016-12-16 23:55:37 +0000550 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000551 if (TRI->trackLivenessAfterRegAlloc(*MF))
552 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000553
554 // Renumber all of the machine basic blocks in the function, guaranteeing that
555 // the numbers agree with the position of the block in the function.
556 MF->RenumberBlocks();
557
558 // Do the initial scan of the function, building up information about the
559 // sizes of each block.
560 scanFunction();
561
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000562 LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000563
564 bool MadeChange = false;
565 while (relaxBranchInstructions())
566 MadeChange = true;
567
568 // After a while, this might be made debug-only, but it is not expensive.
569 verify();
570
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000572
573 BlockInfo.clear();
574
575 return MadeChange;
576}