blob: 27ee12c4c5ff2a0f67cba22f2dd36104aa75c485 [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
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"
Tim Northover3b0846e2014-05-24 12:50:23 +000013#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/CodeGen/Passes.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000015#include "llvm/CodeGen/RegisterScavenging.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "llvm/Support/Format.h"
18#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/Target/TargetInstrInfo.h"
20#include "llvm/Target/TargetSubtargetInfo.h"
Matt Arsenault36919a42016-10-06 15:38:53 +000021
Tim Northover3b0846e2014-05-24 12:50:23 +000022using namespace llvm;
23
Matt Arsenault36919a42016-10-06 15:38:53 +000024#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000025
Tim Northover3b0846e2014-05-24 12:50:23 +000026STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000027STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000028STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000029
Matt Arsenault36919a42016-10-06 15:38:53 +000030#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000031
Tim Northover3b0846e2014-05-24 12:50:23 +000032namespace {
Matt Arsenault36919a42016-10-06 15:38:53 +000033class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000034 /// BasicBlockInfo - Information about the offset and size of a single
35 /// basic block.
36 struct BasicBlockInfo {
37 /// Offset - Distance from the beginning of the function to the beginning
38 /// of this basic block.
39 ///
40 /// The offset is always aligned as required by the basic block.
41 unsigned Offset;
42
43 /// Size - Size of the basic block in bytes. If the block contains
44 /// inline assembly, this is a worst case estimate.
45 ///
46 /// The size does not include any alignment padding whether from the
47 /// beginning of the block, or from an aligned jump table at the end.
48 unsigned Size;
49
50 BasicBlockInfo() : Offset(0), Size(0) {}
51
Matt Arsenaultef5bba02016-10-06 16:00:58 +000052 /// Compute the offset immediately following this block. \p MBB is the next
53 /// block.
54 unsigned postOffset(const MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +000055 unsigned PO = Offset + Size;
Matt Arsenaultef5bba02016-10-06 16:00:58 +000056 unsigned Align = MBB.getAlignment();
57 if (Align == 0)
58 return PO;
59
60 unsigned AlignAmt = 1 << Align;
61 unsigned ParentAlign = MBB.getParent()->getAlignment();
62 if (Align <= ParentAlign)
63 return PO + OffsetToAlignment(PO, AlignAmt);
64
65 // The alignment of this MBB is larger than the function's alignment, so we
66 // can't tell whether or not it will insert nops. Assume that it will.
67 return PO + AlignAmt + OffsetToAlignment(PO, AlignAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +000068 }
69 };
70
71 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000072 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000073 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000074
75 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000076 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000077 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000078
79 bool relaxBranchInstructions();
80 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000081
82 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
83
Matt Arsenault44deb792016-11-02 16:18:29 +000084 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
85 MachineBasicBlock *DestBB);
Tim Northover3b0846e2014-05-24 12:50:23 +000086 void adjustBlockOffsets(MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000087 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000088
Matt Arsenaultf7065e12016-08-02 07:20:09 +000089 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +000090 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +000091 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +000092 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +000093 void dumpBBs();
94 void verify();
95
96public:
97 static char ID;
Matt Arsenault36919a42016-10-06 15:38:53 +000098 BranchRelaxation() : MachineFunctionPass(ID) { }
Tim Northover3b0846e2014-05-24 12:50:23 +000099
100 bool runOnMachineFunction(MachineFunction &MF) override;
101
Matt Arsenault36919a42016-10-06 15:38:53 +0000102 StringRef getPassName() const override {
103 return BRANCH_RELAX_NAME;
104 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000105};
Matt Arsenault36919a42016-10-06 15:38:53 +0000106
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000107}
Tim Northover3b0846e2014-05-24 12:50:23 +0000108
Matt Arsenault36919a42016-10-06 15:38:53 +0000109char BranchRelaxation::ID = 0;
110char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
111
112INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000113
Tim Northover3b0846e2014-05-24 12:50:23 +0000114/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000115void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000116#ifndef NDEBUG
117 unsigned PrevNum = MF->begin()->getNumber();
118 for (MachineBasicBlock &MBB : *MF) {
119 unsigned Align = MBB.getAlignment();
120 unsigned Num = MBB.getNumber();
121 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000122 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000123 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000124 PrevNum = Num;
125 }
126#endif
127}
128
Matthias Braun8c209aa2017-01-28 02:02:38 +0000129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000130/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000131LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000132 for (auto &MBB : *MF) {
133 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
134 dbgs() << format("BB#%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
135 << format("size=%#x\n", BBI.Size);
136 }
137}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000138#endif
Tim Northover3b0846e2014-05-24 12:50:23 +0000139
Tim Northover3b0846e2014-05-24 12:50:23 +0000140/// scanFunction - Do the initial scan of the function, building up
141/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000142void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 BlockInfo.clear();
144 BlockInfo.resize(MF->getNumBlockIDs());
145
146 // First thing, compute the size of all basic blocks, and see if the function
147 // has any inline assembly in it. If so, we have to be conservative about
148 // alignment assumptions, as we don't know for sure the size of any
149 // instructions in the inline assembly.
150 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000151 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000152
153 // Compute block offsets and known bits.
154 adjustBlockOffsets(*MF->begin());
155}
156
157/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000158uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
159 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000160 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000161 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000162 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000163}
164
165/// getInstrOffset - Return the current offset of the specified machine
166/// instruction from the start of the function. This offset changes as stuff is
167/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000168unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000169 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000170
171 // The offset is composed of two things: the sum of the sizes of all MBB's
172 // before this instruction's block, and the offset from the start of the block
173 // it is in.
174 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
175
176 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000177 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000178 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000179 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000180 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000181
Tim Northover3b0846e2014-05-24 12:50:23 +0000182 return Offset;
183}
184
Matt Arsenault36919a42016-10-06 15:38:53 +0000185void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 unsigned PrevNum = Start.getNumber();
187 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
188 unsigned Num = MBB.getNumber();
189 if (!Num) // block zero is never changed from offset zero.
190 continue;
191 // Get the offset and known bits at the end of the layout predecessor.
192 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000193 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
194
Tim Northover3b0846e2014-05-24 12:50:23 +0000195 PrevNum = Num;
196 }
197}
198
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000199 /// Insert a new empty basic block and insert it after \BB
200MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
201 // Create a new MBB for the code after the OrigBB.
202 MachineBasicBlock *NewBB =
203 MF->CreateMachineBasicBlock(BB.getBasicBlock());
204 MF->insert(++BB.getIterator(), NewBB);
205
206 // Insert an entry into BlockInfo to align it properly with the block numbers.
207 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
208
209 return NewBB;
210}
211
Tim Northover3b0846e2014-05-24 12:50:23 +0000212/// Split the basic block containing MI into two blocks, which are joined by
213/// an unconditional branch. Update data structures and renumber blocks to
214/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000215MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
216 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000217 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000218
219 // Create a new MBB for the code after the OrigBB.
220 MachineBasicBlock *NewBB =
221 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000222 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000223
224 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000225 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000226
227 // Add an unconditional branch from OrigBB to NewBB.
228 // Note the new unconditional branch is not being recorded.
229 // There doesn't seem to be meaningful DebugInfo available; this doesn't
230 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000231 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000232
233 // Insert an entry into BlockInfo to align it properly with the block numbers.
234 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
235
Matt Arsenault44deb792016-11-02 16:18:29 +0000236
237 NewBB->transferSuccessors(OrigBB);
238 OrigBB->addSuccessor(NewBB);
239 OrigBB->addSuccessor(DestBB);
240
241 // Cleanup potential unconditional branch to successor block.
242 // Note that updateTerminator may change the size of the blocks.
243 NewBB->updateTerminator();
244 OrigBB->updateTerminator();
245
Tim Northover3b0846e2014-05-24 12:50:23 +0000246 // Figure out how large the OrigBB is. As the first half of the original
247 // block, it cannot contain a tablejump. The size includes
248 // the new jump we added. (It should be possible to do this without
249 // recounting everything, but it's very confusing, and this is rarely
250 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000251 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000252
Matt Arsenault36919a42016-10-06 15:38:53 +0000253 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000254 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000255 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000256
257 // All BBOffsets following these blocks must be modified.
258 adjustBlockOffsets(*OrigBB);
259
Matthias Braun18198302016-12-16 23:55:37 +0000260 // Need to fix live-in lists if we track liveness.
261 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braune51c4352017-05-26 06:32:31 +0000262 computeLiveIns(LiveRegs, MF->getRegInfo(), *NewBB);
Matthias Braun18198302016-12-16 23:55:37 +0000263
Tim Northover3b0846e2014-05-24 12:50:23 +0000264 ++NumSplit;
265
266 return NewBB;
267}
268
269/// isBlockInRange - Returns true if the distance between specific MI and
270/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000271bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000272 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000273 int64_t BrOffset = getInstrOffset(MI);
274 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000275
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000276 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000277 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000278
279 DEBUG(
280 dbgs() << "Out of range branch to destination BB#" << DestBB.getNumber()
281 << " from BB#" << MI.getParent()->getNumber()
282 << " to " << DestOffset
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000283 << " offset " << DestOffset - BrOffset
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000284 << '\t' << MI
285 );
286
287 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000288}
289
Tim Northover3b0846e2014-05-24 12:50:23 +0000290/// fixupConditionalBranch - Fix up a conditional branch whose destination is
291/// too far away to fit in its displacement field. It is converted to an inverse
292/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000293bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000294 DebugLoc DL = MI.getDebugLoc();
295 MachineBasicBlock *MBB = MI.getParent();
296 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
297 SmallVector<MachineOperand, 4> Cond;
298
299 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
300 assert(!Fail && "branches to be relaxed must be analyzable");
301 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000302
303 // Add an unconditional branch to the destination and invert the branch
304 // condition to jump over it:
305 // tbz L1
306 // =>
307 // tbnz L2
308 // b L1
309 // L2:
310
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000311 if (FBB && isBlockInRange(MI, *FBB)) {
312 // Last MI in the BB is an unconditional branch. We can simply invert the
313 // condition and swap destinations:
314 // beq L1
315 // b L2
316 // =>
317 // bne L2
318 // b L1
319 DEBUG(dbgs() << " Invert condition and swap "
320 "its destination with " << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000321
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000322 TII->reverseBranchCondition(Cond);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000323 int OldSize = 0, NewSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000324 TII->removeBranch(*MBB, &OldSize);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000325 TII->insertBranch(*MBB, FBB, TBB, Cond, DL, &NewSize);
Matt Arsenault5b549712016-08-02 08:30:06 +0000326
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000327 BlockInfo[MBB->getNumber()].Size += (NewSize - OldSize);
328 return true;
329 } else if (FBB) {
330 // We need to split the basic block here to obtain two long-range
331 // unconditional branches.
332 auto &NewBB = *MF->CreateMachineBasicBlock(MBB->getBasicBlock());
333 MF->insert(++MBB->getIterator(), &NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000334
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000335 // Insert an entry into BlockInfo to align it properly with the block
336 // numbers.
337 BlockInfo.insert(BlockInfo.begin() + NewBB.getNumber(), BasicBlockInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000338
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000339 unsigned &NewBBSize = BlockInfo[NewBB.getNumber()].Size;
340 int NewBrSize;
341 TII->insertUnconditionalBranch(NewBB, FBB, DL, &NewBrSize);
342 NewBBSize += NewBrSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000343
344 // Update the successor lists according to the transformation to follow.
345 // Do it here since if there's no split, no update is needed.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000346 MBB->replaceSuccessor(FBB, &NewBB);
347 NewBB.addSuccessor(FBB);
Matthias Braun24dc63a2017-05-27 00:53:48 +0000348
349 // Need to fix live-in lists if we track liveness.
350 if (TRI->trackLivenessAfterRegAlloc(*MF))
351 computeLiveIns(LiveRegs, MF->getRegInfo(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000352 }
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000353
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000354 // We now have an appropriate fall-through block in place (either naturally or
355 // just created), so we can invert the condition.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000356 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000357
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000358 DEBUG(dbgs() << " Insert B to BB#" << TBB->getNumber()
Tim Northover3b0846e2014-05-24 12:50:23 +0000359 << ", invert condition and change dest. to BB#"
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000360 << NextBB.getNumber() << '\n');
Tim Northover3b0846e2014-05-24 12:50:23 +0000361
Matt Arsenault5b549712016-08-02 08:30:06 +0000362 unsigned &MBBSize = BlockInfo[MBB->getNumber()].Size;
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000363
Matt Arsenault5b549712016-08-02 08:30:06 +0000364 // Insert a new conditional branch and a new unconditional branch.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000365 int RemovedSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000366 TII->reverseBranchCondition(Cond);
367 TII->removeBranch(*MBB, &RemovedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000368 MBBSize -= RemovedSize;
Matt Arsenault5b549712016-08-02 08:30:06 +0000369
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000370 int AddedSize = 0;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000371 TII->insertBranch(*MBB, &NextBB, TBB, Cond, DL, &AddedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000372 MBBSize += AddedSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000373
374 // Finally, keep the block offsets up to date.
375 adjustBlockOffsets(*MBB);
376 return true;
377}
378
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000379bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
380 MachineBasicBlock *MBB = MI.getParent();
381
382 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
383 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
384
385 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
386 int64_t SrcOffset = getInstrOffset(MI);
387
388 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
389
390 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
391
392 MachineBasicBlock *BranchBB = MBB;
393
394 // If this was an expanded conditional branch, there is already a single
395 // unconditional branch in a block.
396 if (!MBB->empty()) {
397 BranchBB = createNewBlockAfter(*MBB);
398
399 // Add live outs.
400 for (const MachineBasicBlock *Succ : MBB->successors()) {
401 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
402 BranchBB->addLiveIn(LiveIn);
403 }
404
Matt Arsenault691efe02016-10-12 15:32:04 +0000405 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000406 BranchBB->addSuccessor(DestBB);
407 MBB->replaceSuccessor(DestBB, BranchBB);
408 }
409
410 DebugLoc DL = MI.getDebugLoc();
411 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000412 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000413 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
414
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000415 adjustBlockOffsets(*MBB);
416 return true;
417}
418
Matt Arsenault36919a42016-10-06 15:38:53 +0000419bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000420 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000421
Tim Northover3b0846e2014-05-24 12:50:23 +0000422 // Relaxing branches involves creating new basic blocks, so re-eval
423 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000424 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
425 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000426
Matthias Braun18198302016-12-16 23:55:37 +0000427 // Empty block?
428 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
429 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000430 continue;
431
432 // Expand the unconditional branch first if necessary. If there is a
433 // conditional branch, this will end up changing the branch destination of
434 // it to be over the newly inserted indirect branch block, which may avoid
435 // the need to try expanding the conditional branch first, saving an extra
436 // jump.
437 if (Last->isUnconditionalBranch()) {
438 // Unconditional branch destination might be unanalyzable, assume these
439 // are OK.
440 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
441 if (!isBlockInRange(*Last, *DestBB)) {
442 fixupUnconditionalBranch(*Last);
443 ++NumUnconditionalRelaxed;
444 Changed = true;
445 }
446 }
447 }
448
449 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000450 MachineBasicBlock::iterator Next;
451 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
452 J != MBB.end(); J = Next) {
453 Next = std::next(J);
454 MachineInstr &MI = *J;
455
456 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000457 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000458 if (!isBlockInRange(MI, *DestBB)) {
459 if (Next != MBB.end() && Next->isConditionalBranch()) {
460 // If there are multiple conditional branches, this isn't an
461 // analyzable block. Split later terminators into a new block so
462 // each one will be analyzable.
463
Matt Arsenault44deb792016-11-02 16:18:29 +0000464 splitBlockBeforeInstr(*Next, DestBB);
Matt Arsenault567631b2016-08-23 01:30:30 +0000465 } else {
466 fixupConditionalBranch(MI);
467 ++NumConditionalRelaxed;
468 }
469
470 Changed = true;
471
472 // This may have modified all of the terminators, so start over.
473 Next = MBB.getFirstTerminator();
474 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000475 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000476 }
477 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000478
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 return Changed;
480}
481
Matt Arsenault36919a42016-10-06 15:38:53 +0000482bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000483 MF = &mf;
484
Matt Arsenault36919a42016-10-06 15:38:53 +0000485 DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000486
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000487 const TargetSubtargetInfo &ST = MF->getSubtarget();
488 TII = ST.getInstrInfo();
489
Matthias Braun18198302016-12-16 23:55:37 +0000490 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000491 if (TRI->trackLivenessAfterRegAlloc(*MF))
492 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000493
494 // Renumber all of the machine basic blocks in the function, guaranteeing that
495 // the numbers agree with the position of the block in the function.
496 MF->RenumberBlocks();
497
498 // Do the initial scan of the function, building up information about the
499 // sizes of each block.
500 scanFunction();
501
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000502 DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000503
504 bool MadeChange = false;
505 while (relaxBranchInstructions())
506 MadeChange = true;
507
508 // After a while, this might be made debug-only, but it is not expensive.
509 verify();
510
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000511 DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000512
513 BlockInfo.clear();
514
515 return MadeChange;
516}