blob: ddf8797d479f5e74a5ec18af7fc445afd22b0d61 [file] [log] [blame]
Matt Arsenault36919a42016-10-06 15:38:53 +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
Matt Arsenault36919a42016-10-06 15:38:53 +000010#include "llvm/CodeGen/Passes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000011#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000012#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000013#include "llvm/CodeGen/MachineFunctionPass.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000014#include "llvm/CodeGen/RegisterScavenging.h"
Matt Arsenault36919a42016-10-06 15:38:53 +000015#include "llvm/Target/TargetInstrInfo.h"
16#include "llvm/Target/TargetSubtargetInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000018#include "llvm/Support/Format.h"
19#include "llvm/Support/raw_ostream.h"
Matt Arsenault36919a42016-10-06 15:38:53 +000020
Tim Northover3b0846e2014-05-24 12:50:23 +000021using namespace llvm;
22
Matt Arsenault36919a42016-10-06 15:38:53 +000023#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000024
Tim Northover3b0846e2014-05-24 12:50:23 +000025STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000026STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000027STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000028
Matt Arsenault36919a42016-10-06 15:38:53 +000029#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000030
Tim Northover3b0846e2014-05-24 12:50:23 +000031namespace {
Matt Arsenault36919a42016-10-06 15:38:53 +000032class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000033 /// BasicBlockInfo - Information about the offset and size of a single
34 /// basic block.
35 struct BasicBlockInfo {
36 /// Offset - Distance from the beginning of the function to the beginning
37 /// of this basic block.
38 ///
39 /// The offset is always aligned as required by the basic block.
40 unsigned Offset;
41
42 /// Size - Size of the basic block in bytes. If the block contains
43 /// inline assembly, this is a worst case estimate.
44 ///
45 /// The size does not include any alignment padding whether from the
46 /// beginning of the block, or from an aligned jump table at the end.
47 unsigned Size;
48
49 BasicBlockInfo() : Offset(0), Size(0) {}
50
Matt Arsenaultef5bba02016-10-06 16:00:58 +000051 /// Compute the offset immediately following this block. \p MBB is the next
52 /// block.
53 unsigned postOffset(const MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +000054 unsigned PO = Offset + Size;
Matt Arsenaultef5bba02016-10-06 16:00:58 +000055 unsigned Align = MBB.getAlignment();
56 if (Align == 0)
57 return PO;
58
59 unsigned AlignAmt = 1 << Align;
60 unsigned ParentAlign = MBB.getParent()->getAlignment();
61 if (Align <= ParentAlign)
62 return PO + OffsetToAlignment(PO, AlignAmt);
63
64 // The alignment of this MBB is larger than the function's alignment, so we
65 // can't tell whether or not it will insert nops. Assume that it will.
66 return PO + AlignAmt + OffsetToAlignment(PO, AlignAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +000067 }
68 };
69
70 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000071 std::unique_ptr<RegScavenger> RS;
Tim Northover3b0846e2014-05-24 12:50:23 +000072
73 MachineFunction *MF;
Matt Arsenault36919a42016-10-06 15:38:53 +000074 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000075
76 bool relaxBranchInstructions();
77 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000078
79 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
80
Matt Arsenaultf7065e12016-08-02 07:20:09 +000081 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
Tim Northover3b0846e2014-05-24 12:50:23 +000082 void adjustBlockOffsets(MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000083 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000084
Matt Arsenaultf7065e12016-08-02 07:20:09 +000085 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +000086 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +000087 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +000088 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +000089 void dumpBBs();
90 void verify();
91
92public:
93 static char ID;
Matt Arsenault36919a42016-10-06 15:38:53 +000094 BranchRelaxation() : MachineFunctionPass(ID) { }
Tim Northover3b0846e2014-05-24 12:50:23 +000095
96 bool runOnMachineFunction(MachineFunction &MF) override;
97
Matt Arsenault36919a42016-10-06 15:38:53 +000098 StringRef getPassName() const override {
99 return BRANCH_RELAX_NAME;
100 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000101};
Matt Arsenault36919a42016-10-06 15:38:53 +0000102
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000103}
Tim Northover3b0846e2014-05-24 12:50:23 +0000104
Matt Arsenault36919a42016-10-06 15:38:53 +0000105char BranchRelaxation::ID = 0;
106char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
107
108INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000109
Tim Northover3b0846e2014-05-24 12:50:23 +0000110/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000111void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000112#ifndef NDEBUG
113 unsigned PrevNum = MF->begin()->getNumber();
114 for (MachineBasicBlock &MBB : *MF) {
115 unsigned Align = MBB.getAlignment();
116 unsigned Num = MBB.getNumber();
117 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000118 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Tim Northover3b0846e2014-05-24 12:50:23 +0000119 PrevNum = Num;
120 }
121#endif
122}
123
124/// print block size and offset information - debugging
Matt Arsenault36919a42016-10-06 15:38:53 +0000125void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 for (auto &MBB : *MF) {
127 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
128 dbgs() << format("BB#%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
129 << format("size=%#x\n", BBI.Size);
130 }
131}
132
Tim Northover3b0846e2014-05-24 12:50:23 +0000133/// scanFunction - Do the initial scan of the function, building up
134/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000135void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000136 BlockInfo.clear();
137 BlockInfo.resize(MF->getNumBlockIDs());
138
139 // First thing, compute the size of all basic blocks, and see if the function
140 // has any inline assembly in it. If so, we have to be conservative about
141 // alignment assumptions, as we don't know for sure the size of any
142 // instructions in the inline assembly.
143 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000144 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000145
146 // Compute block offsets and known bits.
147 adjustBlockOffsets(*MF->begin());
148}
149
150/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000151uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
152 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000153 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000154 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000155 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000156}
157
158/// getInstrOffset - Return the current offset of the specified machine
159/// instruction from the start of the function. This offset changes as stuff is
160/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000161unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000162 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000163
164 // The offset is composed of two things: the sum of the sizes of all MBB's
165 // before this instruction's block, and the offset from the start of the block
166 // it is in.
167 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
168
169 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000170 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000171 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000172 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000174
Tim Northover3b0846e2014-05-24 12:50:23 +0000175 return Offset;
176}
177
Matt Arsenault36919a42016-10-06 15:38:53 +0000178void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000179 unsigned PrevNum = Start.getNumber();
180 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
181 unsigned Num = MBB.getNumber();
182 if (!Num) // block zero is never changed from offset zero.
183 continue;
184 // Get the offset and known bits at the end of the layout predecessor.
185 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000186 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
187
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 PrevNum = Num;
189 }
190}
191
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000192 /// Insert a new empty basic block and insert it after \BB
193MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
194 // Create a new MBB for the code after the OrigBB.
195 MachineBasicBlock *NewBB =
196 MF->CreateMachineBasicBlock(BB.getBasicBlock());
197 MF->insert(++BB.getIterator(), NewBB);
198
199 // Insert an entry into BlockInfo to align it properly with the block numbers.
200 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
201
202 return NewBB;
203}
204
Tim Northover3b0846e2014-05-24 12:50:23 +0000205/// Split the basic block containing MI into two blocks, which are joined by
206/// an unconditional branch. Update data structures and renumber blocks to
207/// account for this change and returns the newly created block.
208/// NOTE: Successor list of the original BB is out of date after this function,
209/// and must be updated by the caller! Other transforms follow using this
210/// utility function, so no point updating now rather than waiting.
Matt Arsenault36919a42016-10-06 15:38:53 +0000211MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000212 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000213
214 // Create a new MBB for the code after the OrigBB.
215 MachineBasicBlock *NewBB =
216 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000217 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000218
219 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000220 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000221
222 // Add an unconditional branch from OrigBB to NewBB.
223 // Note the new unconditional branch is not being recorded.
224 // There doesn't seem to be meaningful DebugInfo available; this doesn't
225 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000226 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000227
228 // Insert an entry into BlockInfo to align it properly with the block numbers.
229 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
230
231 // Figure out how large the OrigBB is. As the first half of the original
232 // block, it cannot contain a tablejump. The size includes
233 // the new jump we added. (It should be possible to do this without
234 // recounting everything, but it's very confusing, and this is rarely
235 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000236 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000237
Matt Arsenault36919a42016-10-06 15:38:53 +0000238 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000239 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000240 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000241
242 // All BBOffsets following these blocks must be modified.
243 adjustBlockOffsets(*OrigBB);
244
245 ++NumSplit;
246
247 return NewBB;
248}
249
250/// isBlockInRange - Returns true if the distance between specific MI and
251/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000252bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000253 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000254 int64_t BrOffset = getInstrOffset(MI);
255 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000256
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000257 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000258 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000259
260 DEBUG(
261 dbgs() << "Out of range branch to destination BB#" << DestBB.getNumber()
262 << " from BB#" << MI.getParent()->getNumber()
263 << " to " << DestOffset
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000264 << " offset " << DestOffset - BrOffset
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000265 << '\t' << MI
266 );
267
268 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000269}
270
Tim Northover3b0846e2014-05-24 12:50:23 +0000271/// fixupConditionalBranch - Fix up a conditional branch whose destination is
272/// too far away to fit in its displacement field. It is converted to an inverse
273/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000274bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000275 DebugLoc DL = MI.getDebugLoc();
276 MachineBasicBlock *MBB = MI.getParent();
277 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
278 SmallVector<MachineOperand, 4> Cond;
279
280 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
281 assert(!Fail && "branches to be relaxed must be analyzable");
282 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000283
284 // Add an unconditional branch to the destination and invert the branch
285 // condition to jump over it:
286 // tbz L1
287 // =>
288 // tbnz L2
289 // b L1
290 // L2:
291
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000292 if (FBB && isBlockInRange(MI, *FBB)) {
293 // Last MI in the BB is an unconditional branch. We can simply invert the
294 // condition and swap destinations:
295 // beq L1
296 // b L2
297 // =>
298 // bne L2
299 // b L1
300 DEBUG(dbgs() << " Invert condition and swap "
301 "its destination with " << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000302
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000303 TII->reverseBranchCondition(Cond);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000304 int OldSize = 0, NewSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000305 TII->removeBranch(*MBB, &OldSize);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000306 TII->insertBranch(*MBB, FBB, TBB, Cond, DL, &NewSize);
Matt Arsenault5b549712016-08-02 08:30:06 +0000307
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000308 BlockInfo[MBB->getNumber()].Size += (NewSize - OldSize);
309 return true;
310 } else if (FBB) {
311 // We need to split the basic block here to obtain two long-range
312 // unconditional branches.
313 auto &NewBB = *MF->CreateMachineBasicBlock(MBB->getBasicBlock());
314 MF->insert(++MBB->getIterator(), &NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000315
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000316 // Insert an entry into BlockInfo to align it properly with the block
317 // numbers.
318 BlockInfo.insert(BlockInfo.begin() + NewBB.getNumber(), BasicBlockInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000319
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000320 unsigned &NewBBSize = BlockInfo[NewBB.getNumber()].Size;
321 int NewBrSize;
322 TII->insertUnconditionalBranch(NewBB, FBB, DL, &NewBrSize);
323 NewBBSize += NewBrSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000324
325 // Update the successor lists according to the transformation to follow.
326 // Do it here since if there's no split, no update is needed.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000327 MBB->replaceSuccessor(FBB, &NewBB);
328 NewBB.addSuccessor(FBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000329 }
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000330
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000331 // We now have an appropriate fall-through block in place (either naturally or
332 // just created), so we can invert the condition.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000333 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000334
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000335 DEBUG(dbgs() << " Insert B to BB#" << TBB->getNumber()
Tim Northover3b0846e2014-05-24 12:50:23 +0000336 << ", invert condition and change dest. to BB#"
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000337 << NextBB.getNumber() << '\n');
Tim Northover3b0846e2014-05-24 12:50:23 +0000338
Matt Arsenault5b549712016-08-02 08:30:06 +0000339 unsigned &MBBSize = BlockInfo[MBB->getNumber()].Size;
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000340
Matt Arsenault5b549712016-08-02 08:30:06 +0000341 // Insert a new conditional branch and a new unconditional branch.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000342 int RemovedSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000343 TII->reverseBranchCondition(Cond);
344 TII->removeBranch(*MBB, &RemovedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000345 MBBSize -= RemovedSize;
Matt Arsenault5b549712016-08-02 08:30:06 +0000346
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000347 int AddedSize = 0;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000348 TII->insertBranch(*MBB, &NextBB, TBB, Cond, DL, &AddedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000349 MBBSize += AddedSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000350
351 // Finally, keep the block offsets up to date.
352 adjustBlockOffsets(*MBB);
353 return true;
354}
355
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000356bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
357 MachineBasicBlock *MBB = MI.getParent();
358
359 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
360 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
361
362 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
363 int64_t SrcOffset = getInstrOffset(MI);
364
365 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
366
367 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
368
369 MachineBasicBlock *BranchBB = MBB;
370
371 // If this was an expanded conditional branch, there is already a single
372 // unconditional branch in a block.
373 if (!MBB->empty()) {
374 BranchBB = createNewBlockAfter(*MBB);
375
376 // Add live outs.
377 for (const MachineBasicBlock *Succ : MBB->successors()) {
378 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
379 BranchBB->addLiveIn(LiveIn);
380 }
381
Matt Arsenault691efe02016-10-12 15:32:04 +0000382 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000383 BranchBB->addSuccessor(DestBB);
384 MBB->replaceSuccessor(DestBB, BranchBB);
385 }
386
387 DebugLoc DL = MI.getDebugLoc();
388 MI.eraseFromParent();
389
390 // insertUnconditonalBranch may have inserted a new block.
391 BlockInfo[MBB->getNumber()].Size += TII->insertIndirectBranch(
392 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
393
394 computeBlockSize(*BranchBB);
395 adjustBlockOffsets(*MBB);
396 return true;
397}
398
Matt Arsenault36919a42016-10-06 15:38:53 +0000399bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000400 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000401
Tim Northover3b0846e2014-05-24 12:50:23 +0000402 // Relaxing branches involves creating new basic blocks, so re-eval
403 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000404 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
405 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000406
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000407 auto Last = MBB.rbegin();
408 if (Last == MBB.rend()) // Empty block.
409 continue;
410
411 // Expand the unconditional branch first if necessary. If there is a
412 // conditional branch, this will end up changing the branch destination of
413 // it to be over the newly inserted indirect branch block, which may avoid
414 // the need to try expanding the conditional branch first, saving an extra
415 // jump.
416 if (Last->isUnconditionalBranch()) {
417 // Unconditional branch destination might be unanalyzable, assume these
418 // are OK.
419 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
420 if (!isBlockInRange(*Last, *DestBB)) {
421 fixupUnconditionalBranch(*Last);
422 ++NumUnconditionalRelaxed;
423 Changed = true;
424 }
425 }
426 }
427
428 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000429 MachineBasicBlock::iterator Next;
430 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
431 J != MBB.end(); J = Next) {
432 Next = std::next(J);
433 MachineInstr &MI = *J;
434
435 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000436 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000437 if (!isBlockInRange(MI, *DestBB)) {
438 if (Next != MBB.end() && Next->isConditionalBranch()) {
439 // If there are multiple conditional branches, this isn't an
440 // analyzable block. Split later terminators into a new block so
441 // each one will be analyzable.
442
443 MachineBasicBlock *NewBB = splitBlockBeforeInstr(*Next);
444 NewBB->transferSuccessors(&MBB);
445 MBB.addSuccessor(NewBB);
446 MBB.addSuccessor(DestBB);
447
448 // Cleanup potential unconditional branch to successor block.
449 NewBB->updateTerminator();
450 MBB.updateTerminator();
451 } else {
452 fixupConditionalBranch(MI);
453 ++NumConditionalRelaxed;
454 }
455
456 Changed = true;
457
458 // This may have modified all of the terminators, so start over.
459 Next = MBB.getFirstTerminator();
460 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000461 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000462 }
463 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000464
Tim Northover3b0846e2014-05-24 12:50:23 +0000465 return Changed;
466}
467
Matt Arsenault36919a42016-10-06 15:38:53 +0000468bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 MF = &mf;
470
Matt Arsenault36919a42016-10-06 15:38:53 +0000471 DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000472
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000473 const TargetSubtargetInfo &ST = MF->getSubtarget();
474 TII = ST.getInstrInfo();
475
476 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
477 if (TRI->trackLivenessAfterRegAlloc(*MF))
478 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000479
480 // Renumber all of the machine basic blocks in the function, guaranteeing that
481 // the numbers agree with the position of the block in the function.
482 MF->RenumberBlocks();
483
484 // Do the initial scan of the function, building up information about the
485 // sizes of each block.
486 scanFunction();
487
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000488 DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000489
490 bool MadeChange = false;
491 while (relaxBranchInstructions())
492 MadeChange = true;
493
494 // After a while, this might be made debug-only, but it is not expensive.
495 verify();
496
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000497 DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000498
499 BlockInfo.clear();
500
501 return MadeChange;
502}