10b57cec5SDimitry Andric //===- BranchRelaxation.cpp -----------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric
90b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
100b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
110b57cec5SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
120b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
130b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
140b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
150b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
160b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
200b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
210b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
22480093f4SDimitry Andric #include "llvm/InitializePasses.h"
230b57cec5SDimitry Andric #include "llvm/Pass.h"
240b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
250b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
26bdd1243dSDimitry Andric #include "llvm/Support/ErrorHandling.h"
270b57cec5SDimitry Andric #include "llvm/Support/Format.h"
280b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
29*5f757f3fSDimitry Andric #include "llvm/Target/TargetMachine.h"
300b57cec5SDimitry Andric #include <cassert>
310b57cec5SDimitry Andric #include <cstdint>
320b57cec5SDimitry Andric #include <iterator>
330b57cec5SDimitry Andric #include <memory>
340b57cec5SDimitry Andric
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric
370b57cec5SDimitry Andric #define DEBUG_TYPE "branch-relaxation"
380b57cec5SDimitry Andric
390b57cec5SDimitry Andric STATISTIC(NumSplit, "Number of basic blocks split");
400b57cec5SDimitry Andric STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
410b57cec5SDimitry Andric STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
420b57cec5SDimitry Andric
430b57cec5SDimitry Andric #define BRANCH_RELAX_NAME "Branch relaxation pass"
440b57cec5SDimitry Andric
450b57cec5SDimitry Andric namespace {
460b57cec5SDimitry Andric
470b57cec5SDimitry Andric class BranchRelaxation : public MachineFunctionPass {
480b57cec5SDimitry Andric /// BasicBlockInfo - Information about the offset and size of a single
490b57cec5SDimitry Andric /// basic block.
500b57cec5SDimitry Andric struct BasicBlockInfo {
510b57cec5SDimitry Andric /// Offset - Distance from the beginning of the function to the beginning
520b57cec5SDimitry Andric /// of this basic block.
530b57cec5SDimitry Andric ///
540b57cec5SDimitry Andric /// The offset is always aligned as required by the basic block.
550b57cec5SDimitry Andric unsigned Offset = 0;
560b57cec5SDimitry Andric
570b57cec5SDimitry Andric /// Size - Size of the basic block in bytes. If the block contains
580b57cec5SDimitry Andric /// inline assembly, this is a worst case estimate.
590b57cec5SDimitry Andric ///
600b57cec5SDimitry Andric /// The size does not include any alignment padding whether from the
610b57cec5SDimitry Andric /// beginning of the block, or from an aligned jump table at the end.
620b57cec5SDimitry Andric unsigned Size = 0;
630b57cec5SDimitry Andric
640b57cec5SDimitry Andric BasicBlockInfo() = default;
650b57cec5SDimitry Andric
660b57cec5SDimitry Andric /// Compute the offset immediately following this block. \p MBB is the next
670b57cec5SDimitry Andric /// block.
postOffset__anon34c2968b0111::BranchRelaxation::BasicBlockInfo680b57cec5SDimitry Andric unsigned postOffset(const MachineBasicBlock &MBB) const {
698bcb0991SDimitry Andric const unsigned PO = Offset + Size;
708bcb0991SDimitry Andric const Align Alignment = MBB.getAlignment();
718bcb0991SDimitry Andric const Align ParentAlign = MBB.getParent()->getAlignment();
728bcb0991SDimitry Andric if (Alignment <= ParentAlign)
735ffd83dbSDimitry Andric return alignTo(PO, Alignment);
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric // The alignment of this MBB is larger than the function's alignment, so we
760b57cec5SDimitry Andric // can't tell whether or not it will insert nops. Assume that it will.
775ffd83dbSDimitry Andric return alignTo(PO, Alignment) + Alignment.value() - ParentAlign.value();
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric };
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric SmallVector<BasicBlockInfo, 16> BlockInfo;
82*5f757f3fSDimitry Andric
83*5f757f3fSDimitry Andric // The basic block after which trampolines are inserted. This is the last
84*5f757f3fSDimitry Andric // basic block that isn't in the cold section.
85*5f757f3fSDimitry Andric MachineBasicBlock *TrampolineInsertionPoint = nullptr;
86*5f757f3fSDimitry Andric SmallDenseSet<std::pair<MachineBasicBlock *, MachineBasicBlock *>>
87*5f757f3fSDimitry Andric RelaxedUnconditionals;
880b57cec5SDimitry Andric std::unique_ptr<RegScavenger> RS;
890b57cec5SDimitry Andric LivePhysRegs LiveRegs;
900b57cec5SDimitry Andric
9106c3fb27SDimitry Andric MachineFunction *MF = nullptr;
9206c3fb27SDimitry Andric const TargetRegisterInfo *TRI = nullptr;
9306c3fb27SDimitry Andric const TargetInstrInfo *TII = nullptr;
94*5f757f3fSDimitry Andric const TargetMachine *TM = nullptr;
950b57cec5SDimitry Andric
960b57cec5SDimitry Andric bool relaxBranchInstructions();
970b57cec5SDimitry Andric void scanFunction();
980b57cec5SDimitry Andric
99bdd1243dSDimitry Andric MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB);
100bdd1243dSDimitry Andric MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB,
101bdd1243dSDimitry Andric const BasicBlock *BB);
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
1040b57cec5SDimitry Andric MachineBasicBlock *DestBB);
1050b57cec5SDimitry Andric void adjustBlockOffsets(MachineBasicBlock &Start);
1060b57cec5SDimitry Andric bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
1070b57cec5SDimitry Andric
1080b57cec5SDimitry Andric bool fixupConditionalBranch(MachineInstr &MI);
1090b57cec5SDimitry Andric bool fixupUnconditionalBranch(MachineInstr &MI);
1100b57cec5SDimitry Andric uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
1110b57cec5SDimitry Andric unsigned getInstrOffset(const MachineInstr &MI) const;
1120b57cec5SDimitry Andric void dumpBBs();
1130b57cec5SDimitry Andric void verify();
1140b57cec5SDimitry Andric
1150b57cec5SDimitry Andric public:
1160b57cec5SDimitry Andric static char ID;
1170b57cec5SDimitry Andric
BranchRelaxation()1180b57cec5SDimitry Andric BranchRelaxation() : MachineFunctionPass(ID) {}
1190b57cec5SDimitry Andric
1200b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override;
1210b57cec5SDimitry Andric
getPassName() const1220b57cec5SDimitry Andric StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
1230b57cec5SDimitry Andric };
1240b57cec5SDimitry Andric
1250b57cec5SDimitry Andric } // end anonymous namespace
1260b57cec5SDimitry Andric
1270b57cec5SDimitry Andric char BranchRelaxation::ID = 0;
1280b57cec5SDimitry Andric
1290b57cec5SDimitry Andric char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
1300b57cec5SDimitry Andric
INITIALIZE_PASS(BranchRelaxation,DEBUG_TYPE,BRANCH_RELAX_NAME,false,false)1310b57cec5SDimitry Andric INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
1320b57cec5SDimitry Andric
1330b57cec5SDimitry Andric /// verify - check BBOffsets, BBSizes, alignment of islands
1340b57cec5SDimitry Andric void BranchRelaxation::verify() {
1350b57cec5SDimitry Andric #ifndef NDEBUG
1360b57cec5SDimitry Andric unsigned PrevNum = MF->begin()->getNumber();
1370b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *MF) {
1388bcb0991SDimitry Andric const unsigned Num = MBB.getNumber();
1390b57cec5SDimitry Andric assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
1400b57cec5SDimitry Andric assert(BlockInfo[Num].Size == computeBlockSize(MBB));
1410b57cec5SDimitry Andric PrevNum = Num;
1420b57cec5SDimitry Andric }
14306c3fb27SDimitry Andric
14406c3fb27SDimitry Andric for (MachineBasicBlock &MBB : *MF) {
14506c3fb27SDimitry Andric for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
14606c3fb27SDimitry Andric J != MBB.end(); J = std::next(J)) {
14706c3fb27SDimitry Andric MachineInstr &MI = *J;
14806c3fb27SDimitry Andric if (!MI.isConditionalBranch() && !MI.isUnconditionalBranch())
14906c3fb27SDimitry Andric continue;
15006c3fb27SDimitry Andric if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
15106c3fb27SDimitry Andric continue;
15206c3fb27SDimitry Andric MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
153*5f757f3fSDimitry Andric assert(isBlockInRange(MI, *DestBB) ||
154*5f757f3fSDimitry Andric RelaxedUnconditionals.contains({&MBB, DestBB}));
15506c3fb27SDimitry Andric }
15606c3fb27SDimitry Andric }
1570b57cec5SDimitry Andric #endif
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric
1600b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1610b57cec5SDimitry Andric /// print block size and offset information - debugging
dumpBBs()1620b57cec5SDimitry Andric LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
1630b57cec5SDimitry Andric for (auto &MBB : *MF) {
1640b57cec5SDimitry Andric const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
1658bcb0991SDimitry Andric dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
1660b57cec5SDimitry Andric << format("size=%#x\n", BBI.Size);
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric #endif
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric /// scanFunction - Do the initial scan of the function, building up
1720b57cec5SDimitry Andric /// information about each block.
scanFunction()1730b57cec5SDimitry Andric void BranchRelaxation::scanFunction() {
1740b57cec5SDimitry Andric BlockInfo.clear();
1750b57cec5SDimitry Andric BlockInfo.resize(MF->getNumBlockIDs());
1760b57cec5SDimitry Andric
177*5f757f3fSDimitry Andric TrampolineInsertionPoint = nullptr;
178*5f757f3fSDimitry Andric RelaxedUnconditionals.clear();
179*5f757f3fSDimitry Andric
1800b57cec5SDimitry Andric // First thing, compute the size of all basic blocks, and see if the function
1810b57cec5SDimitry Andric // has any inline assembly in it. If so, we have to be conservative about
1820b57cec5SDimitry Andric // alignment assumptions, as we don't know for sure the size of any
183*5f757f3fSDimitry Andric // instructions in the inline assembly. At the same time, place the
184*5f757f3fSDimitry Andric // trampoline insertion point at the end of the hot portion of the function.
185*5f757f3fSDimitry Andric for (MachineBasicBlock &MBB : *MF) {
1860b57cec5SDimitry Andric BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
1870b57cec5SDimitry Andric
188*5f757f3fSDimitry Andric if (MBB.getSectionID() != MBBSectionID::ColdSectionID)
189*5f757f3fSDimitry Andric TrampolineInsertionPoint = &MBB;
190*5f757f3fSDimitry Andric }
191*5f757f3fSDimitry Andric
1920b57cec5SDimitry Andric // Compute block offsets and known bits.
1930b57cec5SDimitry Andric adjustBlockOffsets(*MF->begin());
194*5f757f3fSDimitry Andric
195*5f757f3fSDimitry Andric if (TrampolineInsertionPoint == nullptr) {
196*5f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << " No suitable trampoline insertion point found in "
197*5f757f3fSDimitry Andric << MF->getName() << ".\n");
198*5f757f3fSDimitry Andric }
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric
2010b57cec5SDimitry Andric /// computeBlockSize - Compute the size for MBB.
computeBlockSize(const MachineBasicBlock & MBB) const2020b57cec5SDimitry Andric uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
2030b57cec5SDimitry Andric uint64_t Size = 0;
2040b57cec5SDimitry Andric for (const MachineInstr &MI : MBB)
2050b57cec5SDimitry Andric Size += TII->getInstSizeInBytes(MI);
2060b57cec5SDimitry Andric return Size;
2070b57cec5SDimitry Andric }
2080b57cec5SDimitry Andric
2090b57cec5SDimitry Andric /// getInstrOffset - Return the current offset of the specified machine
2100b57cec5SDimitry Andric /// instruction from the start of the function. This offset changes as stuff is
2110b57cec5SDimitry Andric /// moved around inside the function.
getInstrOffset(const MachineInstr & MI) const2120b57cec5SDimitry Andric unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
2130b57cec5SDimitry Andric const MachineBasicBlock *MBB = MI.getParent();
2140b57cec5SDimitry Andric
2150b57cec5SDimitry Andric // The offset is composed of two things: the sum of the sizes of all MBB's
2160b57cec5SDimitry Andric // before this instruction's block, and the offset from the start of the block
2170b57cec5SDimitry Andric // it is in.
2180b57cec5SDimitry Andric unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
2190b57cec5SDimitry Andric
2200b57cec5SDimitry Andric // Sum instructions before MI in MBB.
2210b57cec5SDimitry Andric for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
2220b57cec5SDimitry Andric assert(I != MBB->end() && "Didn't find MI in its own basic block?");
2230b57cec5SDimitry Andric Offset += TII->getInstSizeInBytes(*I);
2240b57cec5SDimitry Andric }
2250b57cec5SDimitry Andric
2260b57cec5SDimitry Andric return Offset;
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric
adjustBlockOffsets(MachineBasicBlock & Start)2290b57cec5SDimitry Andric void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
2300b57cec5SDimitry Andric unsigned PrevNum = Start.getNumber();
2315ffd83dbSDimitry Andric for (auto &MBB :
2325ffd83dbSDimitry Andric make_range(std::next(MachineFunction::iterator(Start)), MF->end())) {
2330b57cec5SDimitry Andric unsigned Num = MBB.getNumber();
2340b57cec5SDimitry Andric // Get the offset and known bits at the end of the layout predecessor.
2350b57cec5SDimitry Andric // Include the alignment of the current block.
2360b57cec5SDimitry Andric BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric PrevNum = Num;
2390b57cec5SDimitry Andric }
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric
242bdd1243dSDimitry Andric /// Insert a new empty MachineBasicBlock and insert it after \p OrigMBB
243bdd1243dSDimitry Andric MachineBasicBlock *
createNewBlockAfter(MachineBasicBlock & OrigBB)244bdd1243dSDimitry Andric BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {
245bdd1243dSDimitry Andric return createNewBlockAfter(OrigBB, OrigBB.getBasicBlock());
246bdd1243dSDimitry Andric }
247bdd1243dSDimitry Andric
248bdd1243dSDimitry Andric /// Insert a new empty MachineBasicBlock with \p BB as its BasicBlock
249bdd1243dSDimitry Andric /// and insert it after \p OrigMBB
250bdd1243dSDimitry Andric MachineBasicBlock *
createNewBlockAfter(MachineBasicBlock & OrigMBB,const BasicBlock * BB)251bdd1243dSDimitry Andric BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,
252bdd1243dSDimitry Andric const BasicBlock *BB) {
2530b57cec5SDimitry Andric // Create a new MBB for the code after the OrigBB.
254bdd1243dSDimitry Andric MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);
255bdd1243dSDimitry Andric MF->insert(++OrigMBB.getIterator(), NewBB);
2560b57cec5SDimitry Andric
257*5f757f3fSDimitry Andric // Place the new block in the same section as OrigBB
258*5f757f3fSDimitry Andric NewBB->setSectionID(OrigMBB.getSectionID());
259*5f757f3fSDimitry Andric NewBB->setIsEndSection(OrigMBB.isEndSection());
260*5f757f3fSDimitry Andric OrigMBB.setIsEndSection(false);
261*5f757f3fSDimitry Andric
2620b57cec5SDimitry Andric // Insert an entry into BlockInfo to align it properly with the block numbers.
2630b57cec5SDimitry Andric BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
2640b57cec5SDimitry Andric
2650b57cec5SDimitry Andric return NewBB;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric
2680b57cec5SDimitry Andric /// Split the basic block containing MI into two blocks, which are joined by
2690b57cec5SDimitry Andric /// an unconditional branch. Update data structures and renumber blocks to
2700b57cec5SDimitry Andric /// account for this change and returns the newly created block.
271*5f757f3fSDimitry Andric MachineBasicBlock *
splitBlockBeforeInstr(MachineInstr & MI,MachineBasicBlock * DestBB)272*5f757f3fSDimitry Andric BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
2730b57cec5SDimitry Andric MachineBasicBlock *DestBB) {
2740b57cec5SDimitry Andric MachineBasicBlock *OrigBB = MI.getParent();
2750b57cec5SDimitry Andric
2760b57cec5SDimitry Andric // Create a new MBB for the code after the OrigBB.
2770b57cec5SDimitry Andric MachineBasicBlock *NewBB =
2780b57cec5SDimitry Andric MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
2790b57cec5SDimitry Andric MF->insert(++OrigBB->getIterator(), NewBB);
2800b57cec5SDimitry Andric
281*5f757f3fSDimitry Andric // Place the new block in the same section as OrigBB.
282*5f757f3fSDimitry Andric NewBB->setSectionID(OrigBB->getSectionID());
283*5f757f3fSDimitry Andric NewBB->setIsEndSection(OrigBB->isEndSection());
284*5f757f3fSDimitry Andric OrigBB->setIsEndSection(false);
285*5f757f3fSDimitry Andric
2860b57cec5SDimitry Andric // Splice the instructions starting with MI over to NewBB.
2870b57cec5SDimitry Andric NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
2880b57cec5SDimitry Andric
2890b57cec5SDimitry Andric // Add an unconditional branch from OrigBB to NewBB.
2900b57cec5SDimitry Andric // Note the new unconditional branch is not being recorded.
2910b57cec5SDimitry Andric // There doesn't seem to be meaningful DebugInfo available; this doesn't
2920b57cec5SDimitry Andric // correspond to anything in the source.
2930b57cec5SDimitry Andric TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
2940b57cec5SDimitry Andric
2950b57cec5SDimitry Andric // Insert an entry into BlockInfo to align it properly with the block numbers.
2960b57cec5SDimitry Andric BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
2970b57cec5SDimitry Andric
2980b57cec5SDimitry Andric NewBB->transferSuccessors(OrigBB);
2990b57cec5SDimitry Andric OrigBB->addSuccessor(NewBB);
3000b57cec5SDimitry Andric OrigBB->addSuccessor(DestBB);
3010b57cec5SDimitry Andric
3020b57cec5SDimitry Andric // Cleanup potential unconditional branch to successor block.
3030b57cec5SDimitry Andric // Note that updateTerminator may change the size of the blocks.
3045ffd83dbSDimitry Andric OrigBB->updateTerminator(NewBB);
3050b57cec5SDimitry Andric
3060b57cec5SDimitry Andric // Figure out how large the OrigBB is. As the first half of the original
3070b57cec5SDimitry Andric // block, it cannot contain a tablejump. The size includes
3080b57cec5SDimitry Andric // the new jump we added. (It should be possible to do this without
3090b57cec5SDimitry Andric // recounting everything, but it's very confusing, and this is rarely
3100b57cec5SDimitry Andric // executed.)
3110b57cec5SDimitry Andric BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
3120b57cec5SDimitry Andric
3130b57cec5SDimitry Andric // Figure out how large the NewMBB is. As the second half of the original
3140b57cec5SDimitry Andric // block, it may contain a tablejump.
3150b57cec5SDimitry Andric BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
3160b57cec5SDimitry Andric
3170b57cec5SDimitry Andric // All BBOffsets following these blocks must be modified.
3180b57cec5SDimitry Andric adjustBlockOffsets(*OrigBB);
3190b57cec5SDimitry Andric
3200b57cec5SDimitry Andric // Need to fix live-in lists if we track liveness.
3210b57cec5SDimitry Andric if (TRI->trackLivenessAfterRegAlloc(*MF))
3220b57cec5SDimitry Andric computeAndAddLiveIns(LiveRegs, *NewBB);
3230b57cec5SDimitry Andric
3240b57cec5SDimitry Andric ++NumSplit;
3250b57cec5SDimitry Andric
3260b57cec5SDimitry Andric return NewBB;
3270b57cec5SDimitry Andric }
3280b57cec5SDimitry Andric
3290b57cec5SDimitry Andric /// isBlockInRange - Returns true if the distance between specific MI and
3300b57cec5SDimitry Andric /// specific BB can fit in MI's displacement field.
isBlockInRange(const MachineInstr & MI,const MachineBasicBlock & DestBB) const3310b57cec5SDimitry Andric bool BranchRelaxation::isBlockInRange(
3320b57cec5SDimitry Andric const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
3330b57cec5SDimitry Andric int64_t BrOffset = getInstrOffset(MI);
3340b57cec5SDimitry Andric int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
3350b57cec5SDimitry Andric
336*5f757f3fSDimitry Andric const MachineBasicBlock *SrcBB = MI.getParent();
337*5f757f3fSDimitry Andric
338*5f757f3fSDimitry Andric if (TII->isBranchOffsetInRange(MI.getOpcode(),
339*5f757f3fSDimitry Andric SrcBB->getSectionID() != DestBB.getSectionID()
340*5f757f3fSDimitry Andric ? TM->getMaxCodeSize()
341*5f757f3fSDimitry Andric : DestOffset - BrOffset))
3420b57cec5SDimitry Andric return true;
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Out of range branch to destination "
3450b57cec5SDimitry Andric << printMBBReference(DestBB) << " from "
3460b57cec5SDimitry Andric << printMBBReference(*MI.getParent()) << " to "
3470b57cec5SDimitry Andric << DestOffset << " offset " << DestOffset - BrOffset << '\t'
3480b57cec5SDimitry Andric << MI);
3490b57cec5SDimitry Andric
3500b57cec5SDimitry Andric return false;
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric
3530b57cec5SDimitry Andric /// fixupConditionalBranch - Fix up a conditional branch whose destination is
3540b57cec5SDimitry Andric /// too far away to fit in its displacement field. It is converted to an inverse
3550b57cec5SDimitry Andric /// conditional branch + an unconditional branch to the destination.
fixupConditionalBranch(MachineInstr & MI)3560b57cec5SDimitry Andric bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
3570b57cec5SDimitry Andric DebugLoc DL = MI.getDebugLoc();
3580b57cec5SDimitry Andric MachineBasicBlock *MBB = MI.getParent();
3590b57cec5SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
3600b57cec5SDimitry Andric MachineBasicBlock *NewBB = nullptr;
3610b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Cond;
3620b57cec5SDimitry Andric
3630b57cec5SDimitry Andric auto insertUncondBranch = [&](MachineBasicBlock *MBB,
3640b57cec5SDimitry Andric MachineBasicBlock *DestBB) {
3650b57cec5SDimitry Andric unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
3660b57cec5SDimitry Andric int NewBrSize = 0;
3670b57cec5SDimitry Andric TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
3680b57cec5SDimitry Andric BBSize += NewBrSize;
3690b57cec5SDimitry Andric };
3700b57cec5SDimitry Andric auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
3710b57cec5SDimitry Andric MachineBasicBlock *FBB,
3720b57cec5SDimitry Andric SmallVectorImpl<MachineOperand>& Cond) {
3730b57cec5SDimitry Andric unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
3740b57cec5SDimitry Andric int NewBrSize = 0;
3750b57cec5SDimitry Andric TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
3760b57cec5SDimitry Andric BBSize += NewBrSize;
3770b57cec5SDimitry Andric };
3780b57cec5SDimitry Andric auto removeBranch = [&](MachineBasicBlock *MBB) {
3790b57cec5SDimitry Andric unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
3800b57cec5SDimitry Andric int RemovedSize = 0;
3810b57cec5SDimitry Andric TII->removeBranch(*MBB, &RemovedSize);
3820b57cec5SDimitry Andric BBSize -= RemovedSize;
3830b57cec5SDimitry Andric };
3840b57cec5SDimitry Andric
3850b57cec5SDimitry Andric auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
3860b57cec5SDimitry Andric MachineBasicBlock *NewBB) {
3870b57cec5SDimitry Andric // Keep the block offsets up to date.
3880b57cec5SDimitry Andric adjustBlockOffsets(*MBB);
3890b57cec5SDimitry Andric
3900b57cec5SDimitry Andric // Need to fix live-in lists if we track liveness.
3910b57cec5SDimitry Andric if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
3920b57cec5SDimitry Andric computeAndAddLiveIns(LiveRegs, *NewBB);
3930b57cec5SDimitry Andric };
3940b57cec5SDimitry Andric
3950b57cec5SDimitry Andric bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
3960b57cec5SDimitry Andric assert(!Fail && "branches to be relaxed must be analyzable");
3970b57cec5SDimitry Andric (void)Fail;
3980b57cec5SDimitry Andric
399*5f757f3fSDimitry Andric // Since cross-section conditional branches to the cold section are rarely
400*5f757f3fSDimitry Andric // taken, try to avoid inverting the condition. Instead, add a "trampoline
401*5f757f3fSDimitry Andric // branch", which unconditionally branches to the branch destination. Place
402*5f757f3fSDimitry Andric // the trampoline branch at the end of the function and retarget the
403*5f757f3fSDimitry Andric // conditional branch to the trampoline.
404*5f757f3fSDimitry Andric // tbz L1
405*5f757f3fSDimitry Andric // =>
406*5f757f3fSDimitry Andric // tbz L1Trampoline
407*5f757f3fSDimitry Andric // ...
408*5f757f3fSDimitry Andric // L1Trampoline: b L1
409*5f757f3fSDimitry Andric if (MBB->getSectionID() != TBB->getSectionID() &&
410*5f757f3fSDimitry Andric TBB->getSectionID() == MBBSectionID::ColdSectionID &&
411*5f757f3fSDimitry Andric TrampolineInsertionPoint != nullptr) {
412*5f757f3fSDimitry Andric // If the insertion point is out of range, we can't put a trampoline there.
413*5f757f3fSDimitry Andric NewBB =
414*5f757f3fSDimitry Andric createNewBlockAfter(*TrampolineInsertionPoint, MBB->getBasicBlock());
415*5f757f3fSDimitry Andric
416*5f757f3fSDimitry Andric if (isBlockInRange(MI, *NewBB)) {
417*5f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << " Retarget destination to trampoline at "
418*5f757f3fSDimitry Andric << NewBB->back());
419*5f757f3fSDimitry Andric
420*5f757f3fSDimitry Andric insertUncondBranch(NewBB, TBB);
421*5f757f3fSDimitry Andric
422*5f757f3fSDimitry Andric // Update the successor lists to include the trampoline.
423*5f757f3fSDimitry Andric MBB->replaceSuccessor(TBB, NewBB);
424*5f757f3fSDimitry Andric NewBB->addSuccessor(TBB);
425*5f757f3fSDimitry Andric
426*5f757f3fSDimitry Andric // Replace branch in the current (MBB) block.
427*5f757f3fSDimitry Andric removeBranch(MBB);
428*5f757f3fSDimitry Andric insertBranch(MBB, NewBB, FBB, Cond);
429*5f757f3fSDimitry Andric
430*5f757f3fSDimitry Andric TrampolineInsertionPoint = NewBB;
431*5f757f3fSDimitry Andric finalizeBlockChanges(MBB, NewBB);
432*5f757f3fSDimitry Andric return true;
433*5f757f3fSDimitry Andric }
434*5f757f3fSDimitry Andric
435*5f757f3fSDimitry Andric LLVM_DEBUG(
436*5f757f3fSDimitry Andric dbgs() << " Trampoline insertion point out of range for Bcc from "
437*5f757f3fSDimitry Andric << printMBBReference(*MBB) << " to " << printMBBReference(*TBB)
438*5f757f3fSDimitry Andric << ".\n");
439*5f757f3fSDimitry Andric TrampolineInsertionPoint->setIsEndSection(NewBB->isEndSection());
440*5f757f3fSDimitry Andric MF->erase(NewBB);
441*5f757f3fSDimitry Andric }
442*5f757f3fSDimitry Andric
4430b57cec5SDimitry Andric // Add an unconditional branch to the destination and invert the branch
4440b57cec5SDimitry Andric // condition to jump over it:
4450b57cec5SDimitry Andric // tbz L1
4460b57cec5SDimitry Andric // =>
4470b57cec5SDimitry Andric // tbnz L2
4480b57cec5SDimitry Andric // b L1
4490b57cec5SDimitry Andric // L2:
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric bool ReversedCond = !TII->reverseBranchCondition(Cond);
4520b57cec5SDimitry Andric if (ReversedCond) {
4530b57cec5SDimitry Andric if (FBB && isBlockInRange(MI, *FBB)) {
4540b57cec5SDimitry Andric // Last MI in the BB is an unconditional branch. We can simply invert the
4550b57cec5SDimitry Andric // condition and swap destinations:
4560b57cec5SDimitry Andric // beq L1
4570b57cec5SDimitry Andric // b L2
4580b57cec5SDimitry Andric // =>
4590b57cec5SDimitry Andric // bne L2
4600b57cec5SDimitry Andric // b L1
4610b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Invert condition and swap "
4620b57cec5SDimitry Andric "its destination with "
4630b57cec5SDimitry Andric << MBB->back());
4640b57cec5SDimitry Andric
4650b57cec5SDimitry Andric removeBranch(MBB);
4660b57cec5SDimitry Andric insertBranch(MBB, FBB, TBB, Cond);
4670b57cec5SDimitry Andric finalizeBlockChanges(MBB, nullptr);
4680b57cec5SDimitry Andric return true;
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric if (FBB) {
4710b57cec5SDimitry Andric // We need to split the basic block here to obtain two long-range
4720b57cec5SDimitry Andric // unconditional branches.
4730b57cec5SDimitry Andric NewBB = createNewBlockAfter(*MBB);
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric insertUncondBranch(NewBB, FBB);
4760b57cec5SDimitry Andric // Update the succesor lists according to the transformation to follow.
4770b57cec5SDimitry Andric // Do it here since if there's no split, no update is needed.
4780b57cec5SDimitry Andric MBB->replaceSuccessor(FBB, NewBB);
4790b57cec5SDimitry Andric NewBB->addSuccessor(FBB);
4800b57cec5SDimitry Andric }
4810b57cec5SDimitry Andric
4820b57cec5SDimitry Andric // We now have an appropriate fall-through block in place (either naturally or
4830b57cec5SDimitry Andric // just created), so we can use the inverted the condition.
4840b57cec5SDimitry Andric MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
4850b57cec5SDimitry Andric
4860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
4870b57cec5SDimitry Andric << ", invert condition and change dest. to "
4880b57cec5SDimitry Andric << printMBBReference(NextBB) << '\n');
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric removeBranch(MBB);
4910b57cec5SDimitry Andric // Insert a new conditional branch and a new unconditional branch.
4920b57cec5SDimitry Andric insertBranch(MBB, &NextBB, TBB, Cond);
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric finalizeBlockChanges(MBB, NewBB);
4950b57cec5SDimitry Andric return true;
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric // Branch cond can't be inverted.
4980b57cec5SDimitry Andric // In this case we always add a block after the MBB.
4990b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
5000b57cec5SDimitry Andric << " Insert a new BB after " << MBB->back());
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric if (!FBB)
5030b57cec5SDimitry Andric FBB = &(*std::next(MachineFunction::iterator(MBB)));
5040b57cec5SDimitry Andric
5050b57cec5SDimitry Andric // This is the block with cond. branch and the distance to TBB is too long.
5060b57cec5SDimitry Andric // beq L1
5070b57cec5SDimitry Andric // L2:
5080b57cec5SDimitry Andric
5090b57cec5SDimitry Andric // We do the following transformation:
5100b57cec5SDimitry Andric // beq NewBB
5110b57cec5SDimitry Andric // b L2
5120b57cec5SDimitry Andric // NewBB:
5130b57cec5SDimitry Andric // b L1
5140b57cec5SDimitry Andric // L2:
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric NewBB = createNewBlockAfter(*MBB);
5170b57cec5SDimitry Andric insertUncondBranch(NewBB, TBB);
5180b57cec5SDimitry Andric
5190b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
5200b57cec5SDimitry Andric << printMBBReference(*NewBB)
5210b57cec5SDimitry Andric << " Keep the exiting condition.\n"
5220b57cec5SDimitry Andric << " Insert B to " << printMBBReference(*FBB) << ".\n"
5230b57cec5SDimitry Andric << " In the new BB: Insert B to "
5240b57cec5SDimitry Andric << printMBBReference(*TBB) << ".\n");
5250b57cec5SDimitry Andric
5260b57cec5SDimitry Andric // Update the successor lists according to the transformation to follow.
5270b57cec5SDimitry Andric MBB->replaceSuccessor(TBB, NewBB);
5280b57cec5SDimitry Andric NewBB->addSuccessor(TBB);
5290b57cec5SDimitry Andric
5300b57cec5SDimitry Andric // Replace branch in the current (MBB) block.
5310b57cec5SDimitry Andric removeBranch(MBB);
5320b57cec5SDimitry Andric insertBranch(MBB, NewBB, FBB, Cond);
5330b57cec5SDimitry Andric
5340b57cec5SDimitry Andric finalizeBlockChanges(MBB, NewBB);
5350b57cec5SDimitry Andric return true;
5360b57cec5SDimitry Andric }
5370b57cec5SDimitry Andric
fixupUnconditionalBranch(MachineInstr & MI)5380b57cec5SDimitry Andric bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
5390b57cec5SDimitry Andric MachineBasicBlock *MBB = MI.getParent();
540bdd1243dSDimitry Andric SmallVector<MachineOperand, 4> Cond;
5410b57cec5SDimitry Andric unsigned OldBrSize = TII->getInstSizeInBytes(MI);
5420b57cec5SDimitry Andric MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
5430b57cec5SDimitry Andric
5440b57cec5SDimitry Andric int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
5450b57cec5SDimitry Andric int64_t SrcOffset = getInstrOffset(MI);
5460b57cec5SDimitry Andric
547*5f757f3fSDimitry Andric assert(!TII->isBranchOffsetInRange(
548*5f757f3fSDimitry Andric MI.getOpcode(), MBB->getSectionID() != DestBB->getSectionID()
549*5f757f3fSDimitry Andric ? TM->getMaxCodeSize()
550*5f757f3fSDimitry Andric : DestOffset - SrcOffset));
5510b57cec5SDimitry Andric
5520b57cec5SDimitry Andric BlockInfo[MBB->getNumber()].Size -= OldBrSize;
5530b57cec5SDimitry Andric
5540b57cec5SDimitry Andric MachineBasicBlock *BranchBB = MBB;
5550b57cec5SDimitry Andric
5560b57cec5SDimitry Andric // If this was an expanded conditional branch, there is already a single
5570b57cec5SDimitry Andric // unconditional branch in a block.
5580b57cec5SDimitry Andric if (!MBB->empty()) {
5590b57cec5SDimitry Andric BranchBB = createNewBlockAfter(*MBB);
5600b57cec5SDimitry Andric
5610b57cec5SDimitry Andric // Add live outs.
5620b57cec5SDimitry Andric for (const MachineBasicBlock *Succ : MBB->successors()) {
5630b57cec5SDimitry Andric for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
5640b57cec5SDimitry Andric BranchBB->addLiveIn(LiveIn);
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric
5670b57cec5SDimitry Andric BranchBB->sortUniqueLiveIns();
5680b57cec5SDimitry Andric BranchBB->addSuccessor(DestBB);
5690b57cec5SDimitry Andric MBB->replaceSuccessor(DestBB, BranchBB);
570*5f757f3fSDimitry Andric if (TrampolineInsertionPoint == MBB)
571*5f757f3fSDimitry Andric TrampolineInsertionPoint = BranchBB;
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric
5740b57cec5SDimitry Andric DebugLoc DL = MI.getDebugLoc();
5750b57cec5SDimitry Andric MI.eraseFromParent();
5760b57cec5SDimitry Andric
577349cc55cSDimitry Andric // Create the optional restore block and, initially, place it at the end of
578349cc55cSDimitry Andric // function. That block will be placed later if it's used; otherwise, it will
579349cc55cSDimitry Andric // be erased.
580bdd1243dSDimitry Andric MachineBasicBlock *RestoreBB = createNewBlockAfter(MF->back(),
581bdd1243dSDimitry Andric DestBB->getBasicBlock());
582*5f757f3fSDimitry Andric std::prev(RestoreBB->getIterator())
583*5f757f3fSDimitry Andric ->setIsEndSection(RestoreBB->isEndSection());
584*5f757f3fSDimitry Andric RestoreBB->setIsEndSection(false);
585349cc55cSDimitry Andric
586349cc55cSDimitry Andric TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB, DL,
587*5f757f3fSDimitry Andric BranchBB->getSectionID() != DestBB->getSectionID()
588*5f757f3fSDimitry Andric ? TM->getMaxCodeSize()
589*5f757f3fSDimitry Andric : DestOffset - SrcOffset,
590*5f757f3fSDimitry Andric RS.get());
591349cc55cSDimitry Andric
592349cc55cSDimitry Andric BlockInfo[BranchBB->getNumber()].Size = computeBlockSize(*BranchBB);
5930b57cec5SDimitry Andric adjustBlockOffsets(*MBB);
594349cc55cSDimitry Andric
595*5f757f3fSDimitry Andric // If RestoreBB is required, place it appropriately.
596349cc55cSDimitry Andric if (!RestoreBB->empty()) {
597*5f757f3fSDimitry Andric // If the jump is Cold -> Hot, don't place the restore block (which is
598*5f757f3fSDimitry Andric // cold) in the middle of the function. Place it at the end.
599*5f757f3fSDimitry Andric if (MBB->getSectionID() == MBBSectionID::ColdSectionID &&
600*5f757f3fSDimitry Andric DestBB->getSectionID() != MBBSectionID::ColdSectionID) {
601*5f757f3fSDimitry Andric MachineBasicBlock *NewBB = createNewBlockAfter(*TrampolineInsertionPoint);
602*5f757f3fSDimitry Andric TII->insertUnconditionalBranch(*NewBB, DestBB, DebugLoc());
603*5f757f3fSDimitry Andric BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
604*5f757f3fSDimitry Andric
605*5f757f3fSDimitry Andric // New trampolines should be inserted after NewBB.
606*5f757f3fSDimitry Andric TrampolineInsertionPoint = NewBB;
607*5f757f3fSDimitry Andric
608*5f757f3fSDimitry Andric // Retarget the unconditional branch to the trampoline block.
609*5f757f3fSDimitry Andric BranchBB->replaceSuccessor(DestBB, NewBB);
610*5f757f3fSDimitry Andric NewBB->addSuccessor(DestBB);
611*5f757f3fSDimitry Andric
612*5f757f3fSDimitry Andric DestBB = NewBB;
613*5f757f3fSDimitry Andric }
614*5f757f3fSDimitry Andric
615*5f757f3fSDimitry Andric // In all other cases, try to place just before DestBB.
616*5f757f3fSDimitry Andric
617349cc55cSDimitry Andric // TODO: For multiple far branches to the same destination, there are
618349cc55cSDimitry Andric // chances that some restore blocks could be shared if they clobber the
619349cc55cSDimitry Andric // same registers and share the same restore sequence. So far, those
620349cc55cSDimitry Andric // restore blocks are just duplicated for each far branch.
621349cc55cSDimitry Andric assert(!DestBB->isEntryBlock());
622349cc55cSDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(DestBB->getIterator());
623bdd1243dSDimitry Andric // Fall through only if PrevBB has no unconditional branch as one of its
624bdd1243dSDimitry Andric // terminators.
625bdd1243dSDimitry Andric if (auto *FT = PrevBB->getLogicalFallThrough()) {
626349cc55cSDimitry Andric assert(FT == DestBB);
627349cc55cSDimitry Andric TII->insertUnconditionalBranch(*PrevBB, FT, DebugLoc());
628349cc55cSDimitry Andric BlockInfo[PrevBB->getNumber()].Size = computeBlockSize(*PrevBB);
629349cc55cSDimitry Andric }
630349cc55cSDimitry Andric // Now, RestoreBB could be placed directly before DestBB.
631349cc55cSDimitry Andric MF->splice(DestBB->getIterator(), RestoreBB->getIterator());
632349cc55cSDimitry Andric // Update successors and predecessors.
633349cc55cSDimitry Andric RestoreBB->addSuccessor(DestBB);
634349cc55cSDimitry Andric BranchBB->replaceSuccessor(DestBB, RestoreBB);
635349cc55cSDimitry Andric if (TRI->trackLivenessAfterRegAlloc(*MF))
636349cc55cSDimitry Andric computeAndAddLiveIns(LiveRegs, *RestoreBB);
637349cc55cSDimitry Andric // Compute the restore block size.
638349cc55cSDimitry Andric BlockInfo[RestoreBB->getNumber()].Size = computeBlockSize(*RestoreBB);
639349cc55cSDimitry Andric // Update the offset starting from the previous block.
640349cc55cSDimitry Andric adjustBlockOffsets(*PrevBB);
641*5f757f3fSDimitry Andric
642*5f757f3fSDimitry Andric // Fix up section information for RestoreBB and DestBB
643*5f757f3fSDimitry Andric RestoreBB->setSectionID(DestBB->getSectionID());
644*5f757f3fSDimitry Andric RestoreBB->setIsBeginSection(DestBB->isBeginSection());
645*5f757f3fSDimitry Andric DestBB->setIsBeginSection(false);
646*5f757f3fSDimitry Andric RelaxedUnconditionals.insert({BranchBB, RestoreBB});
647349cc55cSDimitry Andric } else {
648349cc55cSDimitry Andric // Remove restore block if it's not required.
649349cc55cSDimitry Andric MF->erase(RestoreBB);
650*5f757f3fSDimitry Andric RelaxedUnconditionals.insert({BranchBB, DestBB});
651349cc55cSDimitry Andric }
652349cc55cSDimitry Andric
6530b57cec5SDimitry Andric return true;
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric
relaxBranchInstructions()6560b57cec5SDimitry Andric bool BranchRelaxation::relaxBranchInstructions() {
6570b57cec5SDimitry Andric bool Changed = false;
6580b57cec5SDimitry Andric
6590b57cec5SDimitry Andric // Relaxing branches involves creating new basic blocks, so re-eval
6600b57cec5SDimitry Andric // end() for termination.
6614824e7fdSDimitry Andric for (MachineBasicBlock &MBB : *MF) {
6620b57cec5SDimitry Andric // Empty block?
6630b57cec5SDimitry Andric MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
6640b57cec5SDimitry Andric if (Last == MBB.end())
6650b57cec5SDimitry Andric continue;
6660b57cec5SDimitry Andric
6670b57cec5SDimitry Andric // Expand the unconditional branch first if necessary. If there is a
6680b57cec5SDimitry Andric // conditional branch, this will end up changing the branch destination of
6690b57cec5SDimitry Andric // it to be over the newly inserted indirect branch block, which may avoid
6700b57cec5SDimitry Andric // the need to try expanding the conditional branch first, saving an extra
6710b57cec5SDimitry Andric // jump.
6720b57cec5SDimitry Andric if (Last->isUnconditionalBranch()) {
6730b57cec5SDimitry Andric // Unconditional branch destination might be unanalyzable, assume these
6740b57cec5SDimitry Andric // are OK.
6750b57cec5SDimitry Andric if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
676*5f757f3fSDimitry Andric if (!isBlockInRange(*Last, *DestBB) && !TII->isTailCall(*Last) &&
677*5f757f3fSDimitry Andric !RelaxedUnconditionals.contains({&MBB, DestBB})) {
6780b57cec5SDimitry Andric fixupUnconditionalBranch(*Last);
6790b57cec5SDimitry Andric ++NumUnconditionalRelaxed;
6800b57cec5SDimitry Andric Changed = true;
6810b57cec5SDimitry Andric }
6820b57cec5SDimitry Andric }
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric
6850b57cec5SDimitry Andric // Loop over the conditional branches.
6860b57cec5SDimitry Andric MachineBasicBlock::iterator Next;
6870b57cec5SDimitry Andric for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
6880b57cec5SDimitry Andric J != MBB.end(); J = Next) {
6890b57cec5SDimitry Andric Next = std::next(J);
6900b57cec5SDimitry Andric MachineInstr &MI = *J;
6910b57cec5SDimitry Andric
692e8d8bef9SDimitry Andric if (!MI.isConditionalBranch())
693e8d8bef9SDimitry Andric continue;
694e8d8bef9SDimitry Andric
695e8d8bef9SDimitry Andric if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
696e8d8bef9SDimitry Andric // FAULTING_OP's destination is not encoded in the instruction stream
697e8d8bef9SDimitry Andric // and thus never needs relaxed.
698e8d8bef9SDimitry Andric continue;
699e8d8bef9SDimitry Andric
7000b57cec5SDimitry Andric MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
7010b57cec5SDimitry Andric if (!isBlockInRange(MI, *DestBB)) {
7020b57cec5SDimitry Andric if (Next != MBB.end() && Next->isConditionalBranch()) {
7030b57cec5SDimitry Andric // If there are multiple conditional branches, this isn't an
7040b57cec5SDimitry Andric // analyzable block. Split later terminators into a new block so
7050b57cec5SDimitry Andric // each one will be analyzable.
7060b57cec5SDimitry Andric
7070b57cec5SDimitry Andric splitBlockBeforeInstr(*Next, DestBB);
7080b57cec5SDimitry Andric } else {
7090b57cec5SDimitry Andric fixupConditionalBranch(MI);
7100b57cec5SDimitry Andric ++NumConditionalRelaxed;
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric
7130b57cec5SDimitry Andric Changed = true;
7140b57cec5SDimitry Andric
7150b57cec5SDimitry Andric // This may have modified all of the terminators, so start over.
7160b57cec5SDimitry Andric Next = MBB.getFirstTerminator();
7170b57cec5SDimitry Andric }
7180b57cec5SDimitry Andric }
7190b57cec5SDimitry Andric }
7200b57cec5SDimitry Andric
7210b57cec5SDimitry Andric return Changed;
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric
runOnMachineFunction(MachineFunction & mf)7240b57cec5SDimitry Andric bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
7250b57cec5SDimitry Andric MF = &mf;
7260b57cec5SDimitry Andric
7270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
7280b57cec5SDimitry Andric
7290b57cec5SDimitry Andric const TargetSubtargetInfo &ST = MF->getSubtarget();
7300b57cec5SDimitry Andric TII = ST.getInstrInfo();
731*5f757f3fSDimitry Andric TM = &MF->getTarget();
7320b57cec5SDimitry Andric
7330b57cec5SDimitry Andric TRI = ST.getRegisterInfo();
7340b57cec5SDimitry Andric if (TRI->trackLivenessAfterRegAlloc(*MF))
7350b57cec5SDimitry Andric RS.reset(new RegScavenger());
7360b57cec5SDimitry Andric
7370b57cec5SDimitry Andric // Renumber all of the machine basic blocks in the function, guaranteeing that
7380b57cec5SDimitry Andric // the numbers agree with the position of the block in the function.
7390b57cec5SDimitry Andric MF->RenumberBlocks();
7400b57cec5SDimitry Andric
7410b57cec5SDimitry Andric // Do the initial scan of the function, building up information about the
7420b57cec5SDimitry Andric // sizes of each block.
7430b57cec5SDimitry Andric scanFunction();
7440b57cec5SDimitry Andric
7450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
7460b57cec5SDimitry Andric
7470b57cec5SDimitry Andric bool MadeChange = false;
7480b57cec5SDimitry Andric while (relaxBranchInstructions())
7490b57cec5SDimitry Andric MadeChange = true;
7500b57cec5SDimitry Andric
7510b57cec5SDimitry Andric // After a while, this might be made debug-only, but it is not expensive.
7520b57cec5SDimitry Andric verify();
7530b57cec5SDimitry Andric
7540b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
7550b57cec5SDimitry Andric
7560b57cec5SDimitry Andric BlockInfo.clear();
757*5f757f3fSDimitry Andric RelaxedUnconditionals.clear();
7580b57cec5SDimitry Andric
7590b57cec5SDimitry Andric return MadeChange;
7600b57cec5SDimitry Andric }
761