blob: 744612261c887bb7ebb1770648a88d27531d9a09 [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- BranchRelaxation.cpp -----------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
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//===----------------------------------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00009
Tim Northover3b0846e2014-05-24 12:50:23 +000010#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000011#include "llvm/ADT/Statistic.h"
Matthias Braun18198302016-12-16 23:55:37 +000012#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000013#include "llvm/CodeGen/MachineBasicBlock.h"
14#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000015#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000016#include "llvm/CodeGen/MachineInstr.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000017#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000018#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000019#include "llvm/CodeGen/TargetRegisterInfo.h"
20#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000022#include "llvm/IR/DebugLoc.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/Support/Format.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000027#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000028#include "llvm/Support/raw_ostream.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000029#include <cassert>
30#include <cstdint>
31#include <iterator>
32#include <memory>
Matt Arsenault36919a42016-10-06 15:38:53 +000033
Tim Northover3b0846e2014-05-24 12:50:23 +000034using namespace llvm;
35
Matt Arsenault36919a42016-10-06 15:38:53 +000036#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000037
Tim Northover3b0846e2014-05-24 12:50:23 +000038STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000039STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000040STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000041
Matt Arsenault36919a42016-10-06 15:38:53 +000042#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000043
Tim Northover3b0846e2014-05-24 12:50:23 +000044namespace {
Eugene Zelenko618c5552017-09-13 21:15:20 +000045
Matt Arsenault36919a42016-10-06 15:38:53 +000046class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000047 /// BasicBlockInfo - Information about the offset and size of a single
48 /// basic block.
49 struct BasicBlockInfo {
50 /// Offset - Distance from the beginning of the function to the beginning
51 /// of this basic block.
52 ///
53 /// The offset is always aligned as required by the basic block.
Eugene Zelenko618c5552017-09-13 21:15:20 +000054 unsigned Offset = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000055
56 /// Size - Size of the basic block in bytes. If the block contains
57 /// inline assembly, this is a worst case estimate.
58 ///
59 /// The size does not include any alignment padding whether from the
60 /// beginning of the block, or from an aligned jump table at the end.
Eugene Zelenko618c5552017-09-13 21:15:20 +000061 unsigned Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000062
Eugene Zelenko618c5552017-09-13 21:15:20 +000063 BasicBlockInfo() = default;
Tim Northover3b0846e2014-05-24 12:50:23 +000064
Matt Arsenaultef5bba02016-10-06 16:00:58 +000065 /// Compute the offset immediately following this block. \p MBB is the next
66 /// block.
67 unsigned postOffset(const MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +000068 unsigned PO = Offset + Size;
Matt Arsenaultef5bba02016-10-06 16:00:58 +000069 unsigned Align = MBB.getAlignment();
70 if (Align == 0)
71 return PO;
72
73 unsigned AlignAmt = 1 << Align;
74 unsigned ParentAlign = MBB.getParent()->getAlignment();
75 if (Align <= ParentAlign)
76 return PO + OffsetToAlignment(PO, AlignAmt);
77
78 // The alignment of this MBB is larger than the function's alignment, so we
79 // can't tell whether or not it will insert nops. Assume that it will.
80 return PO + AlignAmt + OffsetToAlignment(PO, AlignAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +000081 }
82 };
83
84 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000085 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000086 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000087
88 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000089 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000090 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000091
92 bool relaxBranchInstructions();
93 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000094
95 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
96
Matt Arsenault44deb792016-11-02 16:18:29 +000097 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
98 MachineBasicBlock *DestBB);
Tim Northover3b0846e2014-05-24 12:50:23 +000099 void adjustBlockOffsets(MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000100 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +0000101
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000102 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000103 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000104 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000105 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 void dumpBBs();
107 void verify();
108
109public:
110 static char ID;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000111
112 BranchRelaxation() : MachineFunctionPass(ID) {}
Tim Northover3b0846e2014-05-24 12:50:23 +0000113
114 bool runOnMachineFunction(MachineFunction &MF) override;
115
Eugene Zelenko618c5552017-09-13 21:15:20 +0000116 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000117};
Matt Arsenault36919a42016-10-06 15:38:53 +0000118
Eugene Zelenko618c5552017-09-13 21:15:20 +0000119} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000120
Matt Arsenault36919a42016-10-06 15:38:53 +0000121char BranchRelaxation::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000122
Matt Arsenault36919a42016-10-06 15:38:53 +0000123char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
124
125INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000126
Tim Northover3b0846e2014-05-24 12:50:23 +0000127/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000128void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000129#ifndef NDEBUG
130 unsigned PrevNum = MF->begin()->getNumber();
131 for (MachineBasicBlock &MBB : *MF) {
132 unsigned Align = MBB.getAlignment();
133 unsigned Num = MBB.getNumber();
134 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000135 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000136 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000137 PrevNum = Num;
138 }
139#endif
140}
141
Aaron Ballman615eb472017-10-15 14:32:27 +0000142#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000143/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000144LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 for (auto &MBB : *MF) {
146 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000147 dbgs() << format("%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
Tim Northover3b0846e2014-05-24 12:50:23 +0000148 << format("size=%#x\n", BBI.Size);
149 }
150}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000151#endif
Tim Northover3b0846e2014-05-24 12:50:23 +0000152
Tim Northover3b0846e2014-05-24 12:50:23 +0000153/// scanFunction - Do the initial scan of the function, building up
154/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000155void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000156 BlockInfo.clear();
157 BlockInfo.resize(MF->getNumBlockIDs());
158
159 // First thing, compute the size of all basic blocks, and see if the function
160 // has any inline assembly in it. If so, we have to be conservative about
161 // alignment assumptions, as we don't know for sure the size of any
162 // instructions in the inline assembly.
163 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000164 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000165
166 // Compute block offsets and known bits.
167 adjustBlockOffsets(*MF->begin());
168}
169
170/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000171uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
172 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000174 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000175 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000176}
177
178/// getInstrOffset - Return the current offset of the specified machine
179/// instruction from the start of the function. This offset changes as stuff is
180/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000181unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000182 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000183
184 // The offset is composed of two things: the sum of the sizes of all MBB's
185 // before this instruction's block, and the offset from the start of the block
186 // it is in.
187 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
188
189 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000190 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000192 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000194
Tim Northover3b0846e2014-05-24 12:50:23 +0000195 return Offset;
196}
197
Matt Arsenault36919a42016-10-06 15:38:53 +0000198void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000199 unsigned PrevNum = Start.getNumber();
200 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
201 unsigned Num = MBB.getNumber();
202 if (!Num) // block zero is never changed from offset zero.
203 continue;
204 // Get the offset and known bits at the end of the layout predecessor.
205 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000206 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
207
Tim Northover3b0846e2014-05-24 12:50:23 +0000208 PrevNum = Num;
209 }
210}
211
Eugene Zelenko618c5552017-09-13 21:15:20 +0000212/// Insert a new empty basic block and insert it after \BB
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000213MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
214 // Create a new MBB for the code after the OrigBB.
215 MachineBasicBlock *NewBB =
216 MF->CreateMachineBasicBlock(BB.getBasicBlock());
217 MF->insert(++BB.getIterator(), NewBB);
218
219 // Insert an entry into BlockInfo to align it properly with the block numbers.
220 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
221
222 return NewBB;
223}
224
Tim Northover3b0846e2014-05-24 12:50:23 +0000225/// Split the basic block containing MI into two blocks, which are joined by
226/// an unconditional branch. Update data structures and renumber blocks to
227/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000228MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
229 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000230 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000231
232 // Create a new MBB for the code after the OrigBB.
233 MachineBasicBlock *NewBB =
234 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000235 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000236
237 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000238 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000239
240 // Add an unconditional branch from OrigBB to NewBB.
241 // Note the new unconditional branch is not being recorded.
242 // There doesn't seem to be meaningful DebugInfo available; this doesn't
243 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000244 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000245
246 // Insert an entry into BlockInfo to align it properly with the block numbers.
247 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
248
Matt Arsenault44deb792016-11-02 16:18:29 +0000249 NewBB->transferSuccessors(OrigBB);
250 OrigBB->addSuccessor(NewBB);
251 OrigBB->addSuccessor(DestBB);
252
253 // Cleanup potential unconditional branch to successor block.
254 // Note that updateTerminator may change the size of the blocks.
255 NewBB->updateTerminator();
256 OrigBB->updateTerminator();
257
Tim Northover3b0846e2014-05-24 12:50:23 +0000258 // Figure out how large the OrigBB is. As the first half of the original
259 // block, it cannot contain a tablejump. The size includes
260 // the new jump we added. (It should be possible to do this without
261 // recounting everything, but it's very confusing, and this is rarely
262 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000263 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000264
Matt Arsenault36919a42016-10-06 15:38:53 +0000265 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000266 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000267 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000268
269 // All BBOffsets following these blocks must be modified.
270 adjustBlockOffsets(*OrigBB);
271
Matthias Braun18198302016-12-16 23:55:37 +0000272 // Need to fix live-in lists if we track liveness.
273 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braunc9056b82017-09-06 20:45:24 +0000274 computeAndAddLiveIns(LiveRegs, *NewBB);
Matthias Braun18198302016-12-16 23:55:37 +0000275
Tim Northover3b0846e2014-05-24 12:50:23 +0000276 ++NumSplit;
277
278 return NewBB;
279}
280
281/// isBlockInRange - Returns true if the distance between specific MI and
282/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000283bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000284 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000285 int64_t BrOffset = getInstrOffset(MI);
286 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000287
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000288 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000289 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000290
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000291 DEBUG(dbgs() << "Out of range branch to destination "
292 << printMBBReference(DestBB) << " from "
293 << printMBBReference(*MI.getParent()) << " to " << DestOffset
294 << " offset " << DestOffset - BrOffset << '\t' << MI);
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000295
296 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000297}
298
Tim Northover3b0846e2014-05-24 12:50:23 +0000299/// fixupConditionalBranch - Fix up a conditional branch whose destination is
300/// too far away to fit in its displacement field. It is converted to an inverse
301/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000302bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000303 DebugLoc DL = MI.getDebugLoc();
304 MachineBasicBlock *MBB = MI.getParent();
305 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000306 MachineBasicBlock *NewBB = nullptr;
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000307 SmallVector<MachineOperand, 4> Cond;
308
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000309 auto insertUncondBranch = [&](MachineBasicBlock *MBB,
310 MachineBasicBlock *DestBB) {
311 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
312 int NewBrSize = 0;
313 TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
314 BBSize += NewBrSize;
315 };
316 auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
317 MachineBasicBlock *FBB,
318 SmallVectorImpl<MachineOperand>& Cond) {
319 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
320 int NewBrSize = 0;
321 TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
322 BBSize += NewBrSize;
323 };
324 auto removeBranch = [&](MachineBasicBlock *MBB) {
325 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
326 int RemovedSize = 0;
327 TII->removeBranch(*MBB, &RemovedSize);
328 BBSize -= RemovedSize;
329 };
330
331 auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
332 MachineBasicBlock *NewBB) {
333 // Keep the block offsets up to date.
334 adjustBlockOffsets(*MBB);
335
336 // Need to fix live-in lists if we track liveness.
337 if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
338 computeAndAddLiveIns(LiveRegs, *NewBB);
339 };
340
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000341 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
342 assert(!Fail && "branches to be relaxed must be analyzable");
343 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000344
345 // Add an unconditional branch to the destination and invert the branch
346 // condition to jump over it:
347 // tbz L1
348 // =>
349 // tbnz L2
350 // b L1
351 // L2:
352
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000353 bool ReversedCond = !TII->reverseBranchCondition(Cond);
354 if (ReversedCond) {
355 if (FBB && isBlockInRange(MI, *FBB)) {
356 // Last MI in the BB is an unconditional branch. We can simply invert the
357 // condition and swap destinations:
358 // beq L1
359 // b L2
360 // =>
361 // bne L2
362 // b L1
363 DEBUG(dbgs() << " Invert condition and swap "
364 "its destination with " << 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
387 DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
388 << ", invert condition and change dest. to "
389 << printMBBReference(NextBB) << '\n');
390
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.
400 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
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000420 DEBUG(dbgs() << " Insert cond B to the new BB " << printMBBReference(*NewBB)
421 << " Keep the exiting condition.\n"
422 << " Insert B to " << printMBBReference(*FBB) << ".\n"
423 << " In the new BB: Insert B to "
424 << printMBBReference(*TBB) << ".\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000425
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000426 // Update the successor lists according to the transformation to follow.
427 MBB->replaceSuccessor(TBB, NewBB);
428 NewBB->addSuccessor(TBB);
429
430 // Replace branch in the current (MBB) block.
431 removeBranch(MBB);
432 insertBranch(MBB, NewBB, FBB, Cond);
433
434 finalizeBlockChanges(MBB, NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000435 return true;
436}
437
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000438bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
439 MachineBasicBlock *MBB = MI.getParent();
440
441 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
442 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
443
444 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
445 int64_t SrcOffset = getInstrOffset(MI);
446
447 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
448
449 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
450
451 MachineBasicBlock *BranchBB = MBB;
452
453 // If this was an expanded conditional branch, there is already a single
454 // unconditional branch in a block.
455 if (!MBB->empty()) {
456 BranchBB = createNewBlockAfter(*MBB);
457
458 // Add live outs.
459 for (const MachineBasicBlock *Succ : MBB->successors()) {
460 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
461 BranchBB->addLiveIn(LiveIn);
462 }
463
Matt Arsenault691efe02016-10-12 15:32:04 +0000464 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000465 BranchBB->addSuccessor(DestBB);
466 MBB->replaceSuccessor(DestBB, BranchBB);
467 }
468
469 DebugLoc DL = MI.getDebugLoc();
470 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000471 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000472 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
473
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000474 adjustBlockOffsets(*MBB);
475 return true;
476}
477
Matt Arsenault36919a42016-10-06 15:38:53 +0000478bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000480
Tim Northover3b0846e2014-05-24 12:50:23 +0000481 // Relaxing branches involves creating new basic blocks, so re-eval
482 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000483 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
484 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000485
Matthias Braun18198302016-12-16 23:55:37 +0000486 // Empty block?
487 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
488 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000489 continue;
490
491 // Expand the unconditional branch first if necessary. If there is a
492 // conditional branch, this will end up changing the branch destination of
493 // it to be over the newly inserted indirect branch block, which may avoid
494 // the need to try expanding the conditional branch first, saving an extra
495 // jump.
496 if (Last->isUnconditionalBranch()) {
497 // Unconditional branch destination might be unanalyzable, assume these
498 // are OK.
499 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
500 if (!isBlockInRange(*Last, *DestBB)) {
501 fixupUnconditionalBranch(*Last);
502 ++NumUnconditionalRelaxed;
503 Changed = true;
504 }
505 }
506 }
507
508 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000509 MachineBasicBlock::iterator Next;
510 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
511 J != MBB.end(); J = Next) {
512 Next = std::next(J);
513 MachineInstr &MI = *J;
514
515 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000516 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000517 if (!isBlockInRange(MI, *DestBB)) {
518 if (Next != MBB.end() && Next->isConditionalBranch()) {
519 // If there are multiple conditional branches, this isn't an
520 // analyzable block. Split later terminators into a new block so
521 // each one will be analyzable.
522
Matt Arsenault44deb792016-11-02 16:18:29 +0000523 splitBlockBeforeInstr(*Next, DestBB);
Matt Arsenault567631b2016-08-23 01:30:30 +0000524 } else {
525 fixupConditionalBranch(MI);
526 ++NumConditionalRelaxed;
527 }
528
529 Changed = true;
530
531 // This may have modified all of the terminators, so start over.
532 Next = MBB.getFirstTerminator();
533 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000534 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000535 }
536 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000537
Tim Northover3b0846e2014-05-24 12:50:23 +0000538 return Changed;
539}
540
Matt Arsenault36919a42016-10-06 15:38:53 +0000541bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000542 MF = &mf;
543
Matt Arsenault36919a42016-10-06 15:38:53 +0000544 DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000545
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000546 const TargetSubtargetInfo &ST = MF->getSubtarget();
547 TII = ST.getInstrInfo();
548
Matthias Braun18198302016-12-16 23:55:37 +0000549 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000550 if (TRI->trackLivenessAfterRegAlloc(*MF))
551 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000552
553 // Renumber all of the machine basic blocks in the function, guaranteeing that
554 // the numbers agree with the position of the block in the function.
555 MF->RenumberBlocks();
556
557 // Do the initial scan of the function, building up information about the
558 // sizes of each block.
559 scanFunction();
560
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000561 DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000562
563 bool MadeChange = false;
564 while (relaxBranchInstructions())
565 MadeChange = true;
566
567 // After a while, this might be made debug-only, but it is not expensive.
568 verify();
569
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000570 DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000571
572 BlockInfo.clear();
573
574 return MadeChange;
575}