1 //===----------------------- MipsBranchExpansion.cpp ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This pass do two things:
12 /// - it expands a branch or jump instruction into a long branch if its offset
13 /// is too large to fit into its immediate field,
14 /// - it inserts nops to prevent forbidden slot hazards.
16 /// The reason why this pass combines these two tasks is that one of these two
17 /// tasks can break the result of the previous one.
19 /// Example of that is a situation where at first, no branch should be expanded,
20 /// but after adding at least one nop somewhere in the code to prevent a
21 /// forbidden slot hazard, offset of some branches may go out of range. In that
22 /// case it is necessary to check again if there is some branch that needs
23 /// expansion. On the other hand, expanding some branch may cause a control
24 /// transfer instruction to appear in the forbidden slot, which is a hazard that
25 /// should be fixed. This pass alternates between this two tasks untill no
26 /// changes are made. Only then we can be sure that all branches are expanded
27 /// properly, and no hazard situations exist.
29 /// Regarding branch expanding:
31 /// When branch instruction like beqzc or bnezc has offset that is too large
32 /// to fit into its immediate field, it has to be expanded to another
33 /// instruction or series of instructions.
35 /// FIXME: Fix pc-region jump instructions which cross 256MB segment boundaries.
36 /// TODO: Handle out of range bc, b (pseudo) instructions.
38 /// Regarding compact branch hazard prevention:
40 /// Hazards handled: forbidden slots for MIPSR6.
42 /// A forbidden slot hazard occurs when a compact branch instruction is executed
43 /// and the adjacent instruction in memory is a control transfer instruction
44 /// such as a branch or jump, ERET, ERETNC, DERET, WAIT and PAUSE.
48 /// 0x8004 bnec a1,v0,<P+0x18>
49 /// 0x8008 beqc a1,a2,<P+0x54>
51 /// In such cases, the processor is required to signal a Reserved Instruction
54 /// Here, if the instruction at 0x8004 is executed, the processor will raise an
55 /// exception as there is a control transfer instruction at 0x8008.
57 /// There are two sources of forbidden slot hazards:
59 /// A) A previous pass has created a compact branch directly.
60 /// B) Transforming a delay slot branch into compact branch. This case can be
61 /// difficult to process as lookahead for hazards is insufficient, as
62 /// backwards delay slot fillling can also produce hazards in previously
63 /// processed instuctions.
65 /// In future this pass can be extended (or new pass can be created) to handle
66 /// other pipeline hazards, such as various MIPS1 hazards, processor errata that
67 /// require instruction reorganization, etc.
69 /// This pass has to run after the delay slot filler as that pass can introduce
70 /// pipeline hazards such as compact branch hazard, hence the existing hazard
71 /// recognizer is not suitable.
73 //===----------------------------------------------------------------------===//
75 #include "MCTargetDesc/MipsABIInfo.h"
76 #include "MCTargetDesc/MipsBaseInfo.h"
77 #include "MCTargetDesc/MipsMCNaCl.h"
78 #include "MCTargetDesc/MipsMCTargetDesc.h"
80 #include "MipsInstrInfo.h"
81 #include "MipsMachineFunction.h"
82 #include "MipsSubtarget.h"
83 #include "MipsTargetMachine.h"
84 #include "llvm/ADT/SmallVector.h"
85 #include "llvm/ADT/Statistic.h"
86 #include "llvm/ADT/StringRef.h"
87 #include "llvm/CodeGen/MachineBasicBlock.h"
88 #include "llvm/CodeGen/MachineFunction.h"
89 #include "llvm/CodeGen/MachineFunctionPass.h"
90 #include "llvm/CodeGen/MachineInstr.h"
91 #include "llvm/CodeGen/MachineInstrBuilder.h"
92 #include "llvm/CodeGen/MachineModuleInfo.h"
93 #include "llvm/CodeGen/MachineOperand.h"
94 #include "llvm/CodeGen/TargetSubtargetInfo.h"
95 #include "llvm/IR/DebugLoc.h"
96 #include "llvm/Support/CommandLine.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Target/TargetMachine.h"
106 using namespace llvm;
108 #define DEBUG_TYPE "mips-branch-expansion"
110 STATISTIC(NumInsertedNops, "Number of nops inserted");
111 STATISTIC(LongBranches, "Number of long branches.");
114 SkipLongBranch("skip-mips-long-branch", cl::init(false),
115 cl::desc("MIPS: Skip branch expansion pass."), cl::Hidden);
118 ForceLongBranch("force-mips-long-branch", cl::init(false),
119 cl::desc("MIPS: Expand all branches to long format."),
124 using Iter = MachineBasicBlock::iterator;
125 using ReverseIter = MachineBasicBlock::reverse_iterator;
129 bool HasLongBranch = false;
130 MachineInstr *Br = nullptr;
135 class MipsBranchExpansion : public MachineFunctionPass {
139 MipsBranchExpansion() : MachineFunctionPass(ID), ABI(MipsABIInfo::Unknown()) {
140 initializeMipsBranchExpansionPass(*PassRegistry::getPassRegistry());
143 StringRef getPassName() const override {
144 return "Mips Branch Expansion Pass";
147 bool runOnMachineFunction(MachineFunction &F) override;
149 MachineFunctionProperties getRequiredProperties() const override {
150 return MachineFunctionProperties().set(
151 MachineFunctionProperties::Property::NoVRegs);
155 void splitMBB(MachineBasicBlock *MBB);
157 int64_t computeOffset(const MachineInstr *Br);
158 uint64_t computeOffsetFromTheBeginning(int MBB);
159 void replaceBranch(MachineBasicBlock &MBB, Iter Br, const DebugLoc &DL,
160 MachineBasicBlock *MBBOpnd);
161 bool buildProperJumpMI(MachineBasicBlock *MBB,
162 MachineBasicBlock::iterator Pos, DebugLoc DL);
163 void expandToLongBranch(MBBInfo &Info);
164 bool handleForbiddenSlot();
165 bool handlePossibleLongBranch();
167 const MipsSubtarget *STI;
168 const MipsInstrInfo *TII;
170 MachineFunction *MFp;
171 SmallVector<MBBInfo, 16> MBBInfos;
174 bool ForceLongBranchFirstPass = false;
177 } // end of anonymous namespace
179 char MipsBranchExpansion::ID = 0;
181 INITIALIZE_PASS(MipsBranchExpansion, DEBUG_TYPE,
182 "Expand out of range branch instructions and fix forbidden"
186 /// Returns a pass that clears pipeline hazards.
187 FunctionPass *llvm::createMipsBranchExpansion() {
188 return new MipsBranchExpansion();
191 // Find the next real instruction from the current position in current basic
193 static Iter getNextMachineInstrInBB(Iter Position) {
194 Iter I = Position, E = Position->getParent()->end();
195 I = std::find_if_not(I, E,
196 [](const Iter &Insn) { return Insn->isTransient(); });
201 // Find the next real instruction from the current position, looking through
202 // basic block boundaries.
203 static std::pair<Iter, bool> getNextMachineInstr(Iter Position,
204 MachineBasicBlock *Parent) {
205 if (Position == Parent->end()) {
207 MachineBasicBlock *Succ = Parent->getNextNode();
208 if (Succ != nullptr && Parent->isSuccessor(Succ)) {
209 Position = Succ->begin();
212 return std::make_pair(Position, true);
214 } while (Parent->empty());
217 Iter Instr = getNextMachineInstrInBB(Position);
218 if (Instr == Parent->end()) {
219 return getNextMachineInstr(Instr, Parent);
221 return std::make_pair(Instr, false);
224 /// Iterate over list of Br's operands and search for a MachineBasicBlock
226 static MachineBasicBlock *getTargetMBB(const MachineInstr &Br) {
227 for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
228 const MachineOperand &MO = Br.getOperand(I);
234 llvm_unreachable("This instruction does not have an MBB operand.");
237 // Traverse the list of instructions backwards until a non-debug instruction is
238 // found or it reaches E.
239 static ReverseIter getNonDebugInstr(ReverseIter B, const ReverseIter &E) {
241 if (!B->isDebugInstr())
247 // Split MBB if it has two direct jumps/branches.
248 void MipsBranchExpansion::splitMBB(MachineBasicBlock *MBB) {
249 ReverseIter End = MBB->rend();
250 ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
252 // Return if MBB has no branch instructions.
253 if ((LastBr == End) ||
254 (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
257 ReverseIter FirstBr = getNonDebugInstr(std::next(LastBr), End);
259 // MBB has only one branch instruction if FirstBr is not a branch
261 if ((FirstBr == End) ||
262 (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
265 assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
267 // Create a new MBB. Move instructions in MBB to the newly created MBB.
268 MachineBasicBlock *NewMBB =
269 MFp->CreateMachineBasicBlock(MBB->getBasicBlock());
271 // Insert NewMBB and fix control flow.
272 MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
273 NewMBB->transferSuccessors(MBB);
274 if (Tgt != getTargetMBB(*LastBr))
275 NewMBB->removeSuccessor(Tgt, true);
276 MBB->addSuccessor(NewMBB);
277 MBB->addSuccessor(Tgt);
278 MFp->insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
280 NewMBB->splice(NewMBB->end(), MBB, LastBr.getReverse(), MBB->end());
284 void MipsBranchExpansion::initMBBInfo() {
285 // Split the MBBs if they have two branches. Each basic block should have at
286 // most one branch after this loop is executed.
287 for (auto &MBB : *MFp)
290 MFp->RenumberBlocks();
292 MBBInfos.resize(MFp->size());
294 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
295 MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
297 // Compute size of MBB.
298 for (MachineBasicBlock::instr_iterator MI = MBB->instr_begin();
299 MI != MBB->instr_end(); ++MI)
300 MBBInfos[I].Size += TII->getInstSizeInBytes(*MI);
304 // Compute offset of branch in number of bytes.
305 int64_t MipsBranchExpansion::computeOffset(const MachineInstr *Br) {
307 int ThisMBB = Br->getParent()->getNumber();
308 int TargetMBB = getTargetMBB(*Br)->getNumber();
310 // Compute offset of a forward branch.
311 if (ThisMBB < TargetMBB) {
312 for (int N = ThisMBB + 1; N < TargetMBB; ++N)
313 Offset += MBBInfos[N].Size;
318 // Compute offset of a backward branch.
319 for (int N = ThisMBB; N >= TargetMBB; --N)
320 Offset += MBBInfos[N].Size;
325 // Returns the distance in bytes up until MBB
326 uint64_t MipsBranchExpansion::computeOffsetFromTheBeginning(int MBB) {
328 for (int N = 0; N < MBB; ++N)
329 Offset += MBBInfos[N].Size;
333 // Replace Br with a branch which has the opposite condition code and a
334 // MachineBasicBlock operand MBBOpnd.
335 void MipsBranchExpansion::replaceBranch(MachineBasicBlock &MBB, Iter Br,
337 MachineBasicBlock *MBBOpnd) {
338 unsigned NewOpc = TII->getOppositeBranchOpc(Br->getOpcode());
339 const MCInstrDesc &NewDesc = TII->get(NewOpc);
341 MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
343 for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
344 MachineOperand &MO = Br->getOperand(I);
347 assert(MO.isMBB() && "MBB operand expected.");
351 MIB.addReg(MO.getReg());
356 if (Br->hasDelaySlot()) {
357 // Bundle the instruction in the delay slot to the newly created branch
358 // and erase the original branch.
359 assert(Br->isBundledWithSucc());
360 MachineBasicBlock::instr_iterator II = Br.getInstrIterator();
361 MIBundleBuilder(&*MIB).append((++II)->removeFromBundle());
363 Br->eraseFromParent();
366 bool MipsBranchExpansion::buildProperJumpMI(MachineBasicBlock *MBB,
367 MachineBasicBlock::iterator Pos,
369 bool HasR6 = ABI.IsN64() ? STI->hasMips64r6() : STI->hasMips32r6();
370 bool AddImm = HasR6 && !STI->useIndirectJumpsHazard();
372 unsigned JR = ABI.IsN64() ? Mips::JR64 : Mips::JR;
373 unsigned JIC = ABI.IsN64() ? Mips::JIC64 : Mips::JIC;
374 unsigned JR_HB = ABI.IsN64() ? Mips::JR_HB64 : Mips::JR_HB;
375 unsigned JR_HB_R6 = ABI.IsN64() ? Mips::JR_HB64_R6 : Mips::JR_HB_R6;
378 if (STI->useIndirectJumpsHazard())
379 JumpOp = HasR6 ? JR_HB_R6 : JR_HB;
381 JumpOp = HasR6 ? JIC : JR;
383 if (JumpOp == Mips::JIC && STI->inMicroMipsMode())
384 JumpOp = Mips::JIC_MMR6;
386 unsigned ATReg = ABI.IsN64() ? Mips::AT_64 : Mips::AT;
387 MachineInstrBuilder Instr =
388 BuildMI(*MBB, Pos, DL, TII->get(JumpOp)).addReg(ATReg);
395 // Expand branch instructions to long branches.
396 // TODO: This function has to be fixed for beqz16 and bnez16, because it
397 // currently assumes that all branches have 16-bit offsets, and will produce
398 // wrong code if branches whose allowed offsets are [-128, -126, ..., 126]
400 void MipsBranchExpansion::expandToLongBranch(MBBInfo &I) {
401 MachineBasicBlock::iterator Pos;
402 MachineBasicBlock *MBB = I.Br->getParent(), *TgtMBB = getTargetMBB(*I.Br);
403 DebugLoc DL = I.Br->getDebugLoc();
404 const BasicBlock *BB = MBB->getBasicBlock();
405 MachineFunction::iterator FallThroughMBB = ++MachineFunction::iterator(MBB);
406 MachineBasicBlock *LongBrMBB = MFp->CreateMachineBasicBlock(BB);
408 MFp->insert(FallThroughMBB, LongBrMBB);
409 MBB->replaceSuccessor(TgtMBB, LongBrMBB);
412 MachineBasicBlock *BalTgtMBB = MFp->CreateMachineBasicBlock(BB);
413 MFp->insert(FallThroughMBB, BalTgtMBB);
414 LongBrMBB->addSuccessor(BalTgtMBB);
415 BalTgtMBB->addSuccessor(TgtMBB);
417 // We must select between the MIPS32r6/MIPS64r6 BALC (which is a normal
418 // instruction) and the pre-MIPS32r6/MIPS64r6 definition (which is an
419 // pseudo-instruction wrapping BGEZAL).
420 const unsigned BalOp =
422 ? STI->inMicroMipsMode() ? Mips::BALC_MMR6 : Mips::BALC
423 : STI->inMicroMipsMode() ? Mips::BAL_BR_MM : Mips::BAL_BR;
428 // addiu $sp, $sp, -8
430 // lui $at, %hi($tgt - $baltgt)
432 // addiu $at, $at, %lo($tgt - $baltgt)
434 // addu $at, $ra, $at
443 // addiu $sp, $sp, -8
445 // lui $at, %hi($tgt - $baltgt)
446 // addiu $at, $at, %lo($tgt - $baltgt)
449 // addu $at, $ra, $at
455 Pos = LongBrMBB->begin();
457 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
460 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SW))
465 // LUi and ADDiu instructions create 32-bit offset of the target basic
466 // block from the target of BAL(C) instruction. We cannot use immediate
467 // value for this offset because it cannot be determined accurately when
468 // the program has inline assembly statements. We therefore use the
469 // relocation expressions %hi($tgt-$baltgt) and %lo($tgt-$baltgt) which
470 // are resolved during the fixup, so the values will always be correct.
472 // Since we cannot create %hi($tgt-$baltgt) and %lo($tgt-$baltgt)
473 // expressions at this point (it is possible only at the MC layer),
474 // we replace LUi and ADDiu with pseudo instructions
475 // LONG_BRANCH_LUi and LONG_BRANCH_ADDiu, and add both basic
476 // blocks as operands to these instructions. When lowering these pseudo
477 // instructions to LUi and ADDiu in the MC layer, we will create
478 // %hi($tgt-$baltgt) and %lo($tgt-$baltgt) expressions and add them as
479 // operands to lowered instructions.
481 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi), Mips::AT)
482 .addMBB(TgtMBB, MipsII::MO_ABS_HI)
485 MachineInstrBuilder BalInstr =
486 BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
487 MachineInstrBuilder ADDiuInstr =
488 BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_ADDiu), Mips::AT)
490 .addMBB(TgtMBB, MipsII::MO_ABS_LO)
492 if (STI->hasMips32r6()) {
493 LongBrMBB->insert(Pos, ADDiuInstr);
494 LongBrMBB->insert(Pos, BalInstr);
496 LongBrMBB->insert(Pos, BalInstr);
497 LongBrMBB->insert(Pos, ADDiuInstr);
498 LongBrMBB->rbegin()->bundleWithPred();
501 Pos = BalTgtMBB->begin();
503 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDu), Mips::AT)
506 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LW), Mips::RA)
509 if (STI->isTargetNaCl())
510 // Bundle-align the target of indirect branch JR.
511 TgtMBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
513 // In NaCl, modifying the sp is not allowed in branch delay slot.
514 // For MIPS32R6, we can skip using a delay slot branch.
515 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
517 if (STI->isTargetNaCl() || !hasDelaySlot) {
518 BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::ADDiu), Mips::SP)
523 if (STI->isTargetNaCl()) {
524 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::NOP));
526 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
530 BalTgtMBB->rbegin()->bundleWithPred();
535 // daddiu $sp, $sp, -16
537 // daddiu $at, $zero, %hi($tgt - $baltgt)
540 // daddiu $at, $at, %lo($tgt - $baltgt)
542 // daddu $at, $ra, $at
545 // daddiu $sp, $sp, 16
550 // daddiu $sp, $sp, -16
552 // daddiu $at, $zero, %hi($tgt - $baltgt)
554 // daddiu $at, $at, %lo($tgt - $baltgt)
557 // daddu $at, $ra, $at
559 // daddiu $sp, $sp, 16
563 // We assume the branch is within-function, and that offset is within
564 // +/- 2GB. High 32 bits will therefore always be zero.
566 // Note that this will work even if the offset is negative, because
567 // of the +1 modification that's added in that case. For example, if the
568 // offset is -1MB (0xFFFFFFFFFFF00000), the computation for %higher is
570 // 0xFFFFFFFFFFF00000 + 0x80008000 = 0x000000007FF08000
572 // and the bits [47:32] are zero. For %highest
574 // 0xFFFFFFFFFFF00000 + 0x800080008000 = 0x000080007FF08000
576 // and the bits [63:48] are zero.
578 Pos = LongBrMBB->begin();
580 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
583 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SD))
587 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
589 .addReg(Mips::ZERO_64)
590 .addMBB(TgtMBB, MipsII::MO_ABS_HI)
592 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
596 MachineInstrBuilder BalInstr =
597 BuildMI(*MFp, DL, TII->get(BalOp)).addMBB(BalTgtMBB);
598 MachineInstrBuilder DADDiuInstr =
599 BuildMI(*MFp, DL, TII->get(Mips::LONG_BRANCH_DADDiu), Mips::AT_64)
601 .addMBB(TgtMBB, MipsII::MO_ABS_LO)
603 if (STI->hasMips32r6()) {
604 LongBrMBB->insert(Pos, DADDiuInstr);
605 LongBrMBB->insert(Pos, BalInstr);
607 LongBrMBB->insert(Pos, BalInstr);
608 LongBrMBB->insert(Pos, DADDiuInstr);
609 LongBrMBB->rbegin()->bundleWithPred();
612 Pos = BalTgtMBB->begin();
614 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDu), Mips::AT_64)
616 .addReg(Mips::AT_64);
617 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LD), Mips::RA_64)
621 bool hasDelaySlot = buildProperJumpMI(BalTgtMBB, Pos, DL);
622 // If there is no delay slot, Insert stack adjustment before
624 BuildMI(*BalTgtMBB, std::prev(Pos), DL, TII->get(Mips::DADDiu),
629 BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
632 BalTgtMBB->rbegin()->bundleWithPred();
636 Pos = LongBrMBB->begin();
637 LongBrMBB->addSuccessor(TgtMBB);
639 // Compute the position of the potentiall jump instruction (basic blocks
640 // before + 4 for the instruction)
641 uint64_t JOffset = computeOffsetFromTheBeginning(MBB->getNumber()) +
642 MBBInfos[MBB->getNumber()].Size + 4;
643 uint64_t TgtMBBOffset = computeOffsetFromTheBeginning(TgtMBB->getNumber());
644 // If it's a forward jump, then TgtMBBOffset will be shifted by two
646 if (JOffset < TgtMBBOffset)
647 TgtMBBOffset += 2 * 4;
648 // Compare 4 upper bits to check if it's the same segment
649 bool SameSegmentJump = JOffset >> 28 == TgtMBBOffset >> 28;
651 if (STI->hasMips32r6() && TII->isBranchOffsetInRange(Mips::BC, I.Offset)) {
657 BuildMI(*LongBrMBB, Pos, DL,
658 TII->get(STI->inMicroMipsMode() ? Mips::BC_MMR6 : Mips::BC))
660 } else if (SameSegmentJump) {
667 MIBundleBuilder(*LongBrMBB, Pos)
668 .append(BuildMI(*MFp, DL, TII->get(Mips::J)).addMBB(TgtMBB))
669 .append(BuildMI(*MFp, DL, TII->get(Mips::NOP)));
671 // At this point, offset where we need to branch does not fit into
672 // immediate field of the branch instruction and is not in the same
673 // segment as jump instruction. Therefore we will break it into couple
674 // instructions, where we first load the offset into register, and then we
675 // do branch register.
677 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op_64),
679 .addMBB(TgtMBB, MipsII::MO_HIGHEST);
680 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
683 .addMBB(TgtMBB, MipsII::MO_HIGHER);
684 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
687 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
690 .addMBB(TgtMBB, MipsII::MO_ABS_HI);
691 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
694 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu2Op),
697 .addMBB(TgtMBB, MipsII::MO_ABS_LO);
699 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi2Op),
701 .addMBB(TgtMBB, MipsII::MO_ABS_HI);
702 BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_ADDiu2Op),
705 .addMBB(TgtMBB, MipsII::MO_ABS_LO);
707 buildProperJumpMI(LongBrMBB, Pos, DL);
711 if (I.Br->isUnconditionalBranch()) {
712 // Change branch destination.
713 assert(I.Br->getDesc().getNumOperands() == 1);
714 I.Br->RemoveOperand(0);
715 I.Br->addOperand(MachineOperand::CreateMBB(LongBrMBB));
717 // Change branch destination and reverse condition.
718 replaceBranch(*MBB, I.Br, DL, &*FallThroughMBB);
721 static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII) {
722 MachineBasicBlock &MBB = F.front();
723 MachineBasicBlock::iterator I = MBB.begin();
724 DebugLoc DL = MBB.findDebugLoc(MBB.begin());
725 BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::V0)
726 .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
727 BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::V0)
729 .addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
730 MBB.removeLiveIn(Mips::V0);
733 bool MipsBranchExpansion::handleForbiddenSlot() {
734 // Forbidden slot hazards are only defined for MIPSR6 but not microMIPSR6.
735 if (!STI->hasMips32r6() || STI->inMicroMipsMode())
738 bool Changed = false;
740 for (MachineFunction::iterator FI = MFp->begin(); FI != MFp->end(); ++FI) {
741 for (Iter I = FI->begin(); I != FI->end(); ++I) {
743 // Forbidden slot hazard handling. Use lookahead over state.
744 if (!TII->HasForbiddenSlot(*I))
748 bool LastInstInFunction =
749 std::next(I) == FI->end() && std::next(FI) == MFp->end();
750 if (!LastInstInFunction) {
751 std::pair<Iter, bool> Res = getNextMachineInstr(std::next(I), &*FI);
752 LastInstInFunction |= Res.second;
756 if (LastInstInFunction || !TII->SafeInForbiddenSlot(*Inst)) {
758 MachineBasicBlock::instr_iterator Iit = I->getIterator();
759 if (std::next(Iit) == FI->end() ||
760 std::next(Iit)->getOpcode() != Mips::NOP) {
762 MIBundleBuilder(&*I).append(
763 BuildMI(*MFp, I->getDebugLoc(), TII->get(Mips::NOP)));
773 bool MipsBranchExpansion::handlePossibleLongBranch() {
774 if (STI->inMips16Mode() || !STI->enableLongBranchPass())
780 bool EverMadeChange = false, MadeChange = true;
787 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
788 MachineBasicBlock *MBB = MFp->getBlockNumbered(I);
789 // Search for MBB's branch instruction.
790 ReverseIter End = MBB->rend();
791 ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
793 if ((Br != End) && Br->isBranch() && !Br->isIndirectBranch() &&
794 (Br->isConditionalBranch() ||
795 (Br->isUnconditionalBranch() && IsPIC))) {
796 int64_t Offset = computeOffset(&*Br);
798 if (STI->isTargetNaCl()) {
799 // The offset calculation does not include sandboxing instructions
800 // that will be added later in the MC layer. Since at this point we
801 // don't know the exact amount of code that "sandboxing" will add, we
802 // conservatively estimate that code will not grow more than 100%.
806 if (ForceLongBranchFirstPass ||
807 !TII->isBranchOffsetInRange(Br->getOpcode(), Offset)) {
808 MBBInfos[I].Offset = Offset;
809 MBBInfos[I].Br = &*Br;
814 ForceLongBranchFirstPass = false;
816 SmallVectorImpl<MBBInfo>::iterator I, E = MBBInfos.end();
818 for (I = MBBInfos.begin(); I != E; ++I) {
819 // Skip if this MBB doesn't have a branch or the branch has already been
820 // converted to a long branch.
824 expandToLongBranch(*I);
826 EverMadeChange = MadeChange = true;
829 MFp->RenumberBlocks();
832 return EverMadeChange;
835 bool MipsBranchExpansion::runOnMachineFunction(MachineFunction &MF) {
836 const TargetMachine &TM = MF.getTarget();
837 IsPIC = TM.isPositionIndependent();
838 ABI = static_cast<const MipsTargetMachine &>(TM).getABI();
839 STI = &static_cast<const MipsSubtarget &>(MF.getSubtarget());
840 TII = static_cast<const MipsInstrInfo *>(STI->getInstrInfo());
842 if (IsPIC && ABI.IsO32() &&
843 MF.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
848 ForceLongBranchFirstPass = ForceLongBranch;
849 // Run these two at least once
850 bool longBranchChanged = handlePossibleLongBranch();
851 bool forbiddenSlotChanged = handleForbiddenSlot();
853 bool Changed = longBranchChanged || forbiddenSlotChanged;
855 // Then run them alternatively while there are changes
856 while (forbiddenSlotChanged) {
857 longBranchChanged = handlePossibleLongBranch();
858 if (!longBranchChanged)
860 forbiddenSlotChanged = handleForbiddenSlot();