107#define DEBUG_TYPE "mips-branch-expansion"
119 bool HasLongBranch =
false;
129 MipsBranchExpansionLegacy() : MachineFunctionPass(ID) {}
131 StringRef getPassName()
const override {
132 return "Mips Branch Expansion Pass";
137 MachineFunctionProperties getRequiredProperties()
const override {
138 return MachineFunctionProperties().setNoVRegs();
142class MipsBranchExpansionImpl {
145 int64_t computeOffset(
const MachineInstr *Br);
147 void replaceBranch(MachineBasicBlock &
MBB, Iter Br,
const DebugLoc &
DL,
148 MachineBasicBlock *MBBOpnd);
149 bool buildProperJumpMI(MachineBasicBlock *
MBB,
151 void expandToLongBranch(MBBInfo &Info);
152 template <
typename Pred,
typename Safe>
153 bool handleSlot(
Pred Predicate, Safe SafeInSlot);
154 bool handleForbiddenSlot();
155 bool handleFPUDelaySlot();
156 bool handleLoadDelaySlot();
157 bool handlePossibleLongBranch();
159 unsigned distanceToHILOWrite(MachineBasicBlock &
MBB,
163 const MipsSubtarget *STI;
164 const MipsInstrInfo *TII;
170 bool ForceLongBranchFirstPass =
false;
178char MipsBranchExpansionLegacy::ID = 0;
181 "Expand out of range branch instructions and fix forbidden"
187 return new MipsBranchExpansionLegacy();
193 Iter
I = Position,
E = Position->getParent()->end();
194 I = std::find_if_not(
I,
E,
195 [](
const Iter &Insn) {
return Insn->isTransient(); });
204 if (Position == Parent->
end()) {
207 if (Succ !=
nullptr && Parent->
isSuccessor(Succ)) {
208 Position = Succ->
begin();
211 return std::make_pair(Position,
true);
213 }
while (Parent->
empty());
217 if (Instr == Parent->
end()) {
220 return std::make_pair(Instr,
false);
240 if (!
B->isDebugInstr())
252 if ((LastBr ==
End) ||
253 (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
260 if ((FirstBr ==
End) ||
261 (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
264 assert(!FirstBr->isIndirectBranch() &&
"Unexpected indirect branch found.");
267 MachineBasicBlock *NewMBB =
283void MipsBranchExpansionImpl::initMBBInfo() {
286 for (
auto &
MBB : *MFp)
289 MFp->RenumberBlocks();
291 MBBInfos.resize(MFp->size());
293 for (
unsigned I = 0,
E = MBBInfos.size();
I <
E; ++
I) {
294 MachineBasicBlock *
MBB = MFp->getBlockNumbered(
I);
297 for (MachineInstr &
MI : *
MBB)
303int64_t MipsBranchExpansionImpl::computeOffset(
const MachineInstr *Br) {
309 if (ThisMBB < TargetMBB) {
310 for (
int N = ThisMBB + 1;
N < TargetMBB; ++
N)
317 for (
int N = ThisMBB;
N >= TargetMBB; --
N)
324uint64_t MipsBranchExpansionImpl::computeOffsetFromTheBeginning(
int MBB) {
326 for (
int N = 0;
N <
MBB; ++
N)
333void MipsBranchExpansionImpl::replaceBranch(MachineBasicBlock &
MBB, Iter Br,
335 MachineBasicBlock *MBBOpnd) {
336 unsigned NewOpc =
TII->getOppositeBranchOpc(Br->getOpcode());
337 const MCInstrDesc &NewDesc =
TII->get(NewOpc);
339 MachineInstrBuilder MIB =
BuildMI(
MBB, Br,
DL, NewDesc);
341 for (
unsigned I = 0,
E = Br->getDesc().getNumOperands();
I <
E; ++
I) {
342 MachineOperand &MO = Br->getOperand(
I);
351 if (!
TII->isBranchWithImm(Br->getOpcode()))
363 if (Br->hasDelaySlot()) {
366 assert(Br->isBundledWithSucc());
368 MIBundleBuilder(&*MIB).append((++
II)->removeFromBundle());
370 Br->eraseFromParent();
373bool MipsBranchExpansionImpl::buildProperJumpMI(MachineBasicBlock *
MBB,
379 unsigned JR = ABI.
IsN64() ? Mips::JR64 : Mips::JR;
380 unsigned JIC = ABI.
IsN64() ? Mips::JIC64 : Mips::JIC;
381 unsigned JR_HB = ABI.
IsN64() ? Mips::JR_HB64 : Mips::JR_HB;
382 unsigned JR_HB_R6 = ABI.
IsN64() ? Mips::JR_HB64_R6 : Mips::JR_HB_R6;
386 JumpOp = HasR6 ? JR_HB_R6 : JR_HB;
388 JumpOp = HasR6 ? JIC : JR;
391 JumpOp = Mips::JIC_MMR6;
393 unsigned ATReg = ABI.
IsN64() ? Mips::R1_64 : Mips::R1;
394 MachineInstrBuilder
Instr =
407void MipsBranchExpansionImpl::expandToLongBranch(MBBInfo &
I) {
413 MachineBasicBlock *LongBrMBB = MFp->CreateMachineBasicBlock(BB);
415 MFp->insert(FallThroughMBB, LongBrMBB);
419 MachineBasicBlock *BalTgtMBB = MFp->CreateMachineBasicBlock(BB);
420 MFp->insert(FallThroughMBB, BalTgtMBB);
427 const unsigned BalOp =
462 Pos = LongBrMBB->
begin();
488 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_LUi), Mips::R1)
492 MachineInstrBuilder BalInstr =
494 MachineInstrBuilder ADDiuInstr =
495 BuildMI(*MFp,
DL,
TII->get(Mips::LONG_BRANCH_ADDiu), Mips::R1)
500 LongBrMBB->
insert(Pos, ADDiuInstr);
501 LongBrMBB->
insert(Pos, BalInstr);
503 LongBrMBB->
insert(Pos, BalInstr);
504 LongBrMBB->
insert(Pos, ADDiuInstr);
505 LongBrMBB->
rbegin()->bundleWithPred();
508 Pos = BalTgtMBB->
begin();
510 BuildMI(*BalTgtMBB, Pos,
DL,
TII->get(Mips::ADDu), Mips::R1)
518 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos,
DL);
529 BalTgtMBB->
rbegin()->bundleWithPred();
577 Pos = LongBrMBB->
begin();
586 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_DADDiu),
591 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::DSLL), Mips::R1_64)
595 MachineInstrBuilder BalInstr =
597 MachineInstrBuilder DADDiuInstr =
598 BuildMI(*MFp,
DL,
TII->get(Mips::LONG_BRANCH_DADDiu), Mips::R1_64)
603 LongBrMBB->
insert(Pos, DADDiuInstr);
604 LongBrMBB->
insert(Pos, BalInstr);
606 LongBrMBB->
insert(Pos, BalInstr);
607 LongBrMBB->
insert(Pos, DADDiuInstr);
608 LongBrMBB->
rbegin()->bundleWithPred();
611 Pos = BalTgtMBB->
begin();
613 BuildMI(*BalTgtMBB, Pos,
DL,
TII->get(Mips::DADDu), Mips::R1_64)
620 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos,
DL);
623 BuildMI(*BalTgtMBB, std::prev(Pos),
DL,
TII->get(Mips::DADDiu),
631 BalTgtMBB->
rbegin()->bundleWithPred();
635 Pos = LongBrMBB->
begin();
642 uint64_t TgtMBBOffset = computeOffsetFromTheBeginning(TgtMBB->getNumber());
645 if (JOffset < TgtMBBOffset)
646 TgtMBBOffset += 2 * 4;
648 bool SameSegmentJump = JOffset >> 28 == TgtMBBOffset >> 28;
659 }
else if (SameSegmentJump) {
667 TII->insertNop(*LongBrMBB, Pos,
DL)->bundleWithPred();
675 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_LUi2Op_64),
678 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_DADDiu2Op),
682 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::DSLL), Mips::R1_64)
685 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_DADDiu2Op),
689 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::DSLL), Mips::R1_64)
692 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_DADDiu2Op),
697 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_LUi2Op),
700 BuildMI(*LongBrMBB, Pos,
DL,
TII->get(Mips::LONG_BRANCH_ADDiu2Op),
705 buildProperJumpMI(LongBrMBB, Pos,
DL);
709 if (
I.Br->isUnconditionalBranch()) {
711 assert(
I.Br->getDesc().getNumOperands() == 1);
712 I.Br->removeOperand(0);
716 replaceBranch(*
MBB,
I.Br,
DL, &*FallThroughMBB);
728 MBB.removeLiveIn(Mips::R2);
736unsigned MipsBranchExpansionImpl::distanceToHILOWrite(
740 if (
I->isTransient())
743 if (!
TII->SafeAfterMflo(*
I))
751 if (
unsigned D = distanceToHILOWrite(*Succ, Succ->instr_begin(), Dist))
752 Min = Min ? std::min(Min,
D) :
D;
759 switch (
MI.getOpcode()) {
765 return MI.getOperand(0).getReg() == Mips::R0 &&
766 MI.getOperand(1).getReg() == Mips::R0 &&
767 MI.getOperand(2).getImm() == 0;
773template <
typename Pred,
typename Safe>
774bool MipsBranchExpansionImpl::handleSlot(
Pred Predicate, Safe SafeInSlot) {
778 for (Iter
I = FI->begin();
I != FI->end(); ++
I) {
785 bool LastInstInFunction =
786 std::next(
I) == FI->end() && std::next(FI) == MFp->end();
787 if (!LastInstInFunction) {
789 LastInstInFunction |= Res.second;
793 if (LastInstInFunction || !SafeInSlot(*IInSlot, *
I)) {
795 if (std::next(Iit) == FI->end() || !
isNop(*std::next(Iit))) {
797 TII->insertNop(*(
I->getParent()), std::next(
I),
I->getDebugLoc())
808bool MipsBranchExpansionImpl::handleMFLO() {
816 for (MachineBasicBlock &
MBB : *MFp) {
820 if (!
TII->IsMfloOrMfhi(*
I))
823 if (!
I->isBundledWithPred()) {
824 unsigned Dist = distanceToHILOWrite(
MBB, std::next(
I), 0);
833 for (
unsigned N = 0;
W !=
E; ++
W)
834 if (!
W->isTransient() && ++
N == Dist)
838 for (; Dist <= 2; ++Dist) {
839 MachineInstrBuilder Nop =
TII->insertNop(
MBB, Pos,
I->getDebugLoc());
851 unsigned Dist = distanceToHILOWrite(*Succ, Succ->instr_begin(), 0);
852 Iter Pos = Succ->empty() ? Succ->end()
854 for (; Dist && Dist <= 2; ++Dist) {
855 TII->insertNop(*Succ, Pos,
I->getDebugLoc());
866bool MipsBranchExpansionImpl::handleForbiddenSlot() {
872 [
this](
auto &
I) ->
bool {
return TII->HasForbiddenSlot(
I); },
873 [
this](
auto &IInSlot,
auto &
I) ->
bool {
874 return TII->SafeInForbiddenSlot(IInSlot);
878bool MipsBranchExpansionImpl::handleFPUDelaySlot() {
883 return handleSlot([
this](
auto &
I) ->
bool {
return TII->HasFPUDelaySlot(
I); },
884 [
this](
auto &IInSlot,
auto &
I) ->
bool {
885 return TII->SafeInFPUDelaySlot(IInSlot,
I);
889bool MipsBranchExpansionImpl::handleLoadDelaySlot() {
895 [
this](
auto &
I) ->
bool {
return TII->HasLoadDelaySlot(
I); },
896 [
this](
auto &IInSlot,
auto &
I) ->
bool {
897 return TII->SafeInLoadDelaySlot(IInSlot,
I);
901bool MipsBranchExpansionImpl::handlePossibleLongBranch() {
905 if (STI->
getCLOpts().skip_mips_long_branch)
908 bool EverMadeChange =
false, MadeChange =
true;
915 for (
unsigned I = 0,
E = MBBInfos.size();
I <
E; ++
I) {
916 MachineBasicBlock *
MBB = MFp->getBlockNumbered(
I);
921 if ((Br !=
End) && Br->isBranch() && !Br->isIndirectBranch() &&
922 (Br->isConditionalBranch() ||
923 (Br->isUnconditionalBranch() && IsPIC))) {
924 int64_t
Offset = computeOffset(&*Br);
926 if (ForceLongBranchFirstPass ||
929 MBBInfos[
I].Br = &*Br;
934 ForceLongBranchFirstPass =
false;
938 for (
I = MBBInfos.begin();
I !=
E; ++
I) {
944 expandToLongBranch(*
I);
946 EverMadeChange = MadeChange =
true;
949 MFp->RenumberBlocks();
952 return EverMadeChange;
955bool MipsBranchExpansionImpl::runOnMachineFunction(
MachineFunction &MF) {
956 const TargetMachine &TM = MF.
getTarget();
962 if (IsPIC &&
ABI.IsO32() &&
963 MF.
getInfo<MipsFunctionInfo>()->globalBaseRegSet())
968 ForceLongBranchFirstPass = STI->
getCLOpts().force_mips_long_branch;
976 bool LongBranchChanged;
978 Changed |= handleForbiddenSlot();
979 Changed |= handleFPUDelaySlot();
980 Changed |= handleLoadDelaySlot();
981 LongBranchChanged = handlePossibleLongBranch();
983 }
while (LongBranchChanged);
988bool MipsBranchExpansionLegacy::runOnMachineFunction(
MachineFunction &MF) {
989 MipsBranchExpansionImpl Impl;
990 return Impl.runOnMachineFunction(MF);
996 MipsBranchExpansionImpl Impl;
997 return Impl.runOnMachineFunction(MF)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::pair< Iter, bool > getNextMachineInstr(Iter Position, MachineBasicBlock *Parent)
static MachineBasicBlock * getTargetMBB(const MachineInstr &Br)
Iterate over list of Br's operands and search for a MachineBasicBlock operand.
static bool isNop(const MachineInstr &MI)
static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII)
static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E)
static Iter getNextMachineInstrInBB(Iter Position)
uint64_t IntrinsicInst * II
static bool splitMBB(BlockSplitInfo &BSI)
Splits a MachineBasicBlock to branch before SplitBefore.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool InBlock(const Value *V, const BasicBlock *BB)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
FunctionPass class - This class is used to implement most global optimizations.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
instr_iterator instr_begin()
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI void bundleWithPred()
Bundle this instruction with its predecessor.
const MachineBasicBlock * getParent() const
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
MachineBasicBlock * getMBB() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
static MipsABIInfo Unknown()
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool inMicroMipsMode() const
const MipsInstrInfo * getInstrInfo() const override
bool useIndirectJumpsHazard() const
bool inMips16Mode() const
const MipsOptions & getCLOpts() const
const MipsABIInfo & getABI() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
typename SuperClass::iterator iterator
bool isPositionIndependent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
constexpr MCPhysReg RA_64
constexpr MCPhysReg SP_64
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
NodeAddr< InstrNode * > Instr
This is an optimization pass for GlobalISel generic memory operations.
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
FunctionPass * createMipsBranchExpansionLegacyPass()
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ End
Run the machine verifier once, at the end of the pipeline.