1 //===- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Simple pass to fill delay slots with useful instructions.
11 //===----------------------------------------------------------------------===//
13 #include "MCTargetDesc/MipsMCNaCl.h"
15 #include "MipsInstrInfo.h"
16 #include "MipsRegisterInfo.h"
17 #include "MipsSubtarget.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/MC/MCInstrDesc.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Target/TargetMachine.h"
53 #define DEBUG_TYPE "mips-delay-slot-filler"
55 STATISTIC(FilledSlots
, "Number of delay slots filled");
56 STATISTIC(UsefulSlots
, "Number of delay slots filled with instructions that"
59 static cl::opt
<bool> DisableDelaySlotFiller(
60 "disable-mips-delay-filler",
62 cl::desc("Fill all delay slots with NOPs."),
65 static cl::opt
<bool> DisableForwardSearch(
66 "disable-mips-df-forward-search",
68 cl::desc("Disallow MIPS delay filler to search forward."),
71 static cl::opt
<bool> DisableSuccBBSearch(
72 "disable-mips-df-succbb-search",
74 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
77 static cl::opt
<bool> DisableBackwardSearch(
78 "disable-mips-df-backward-search",
80 cl::desc("Disallow MIPS delay filler to search backward."),
83 enum CompactBranchPolicy
{
84 CB_Never
, ///< The policy 'never' may in some circumstances or for some
85 ///< ISAs not be absolutely adhered to.
86 CB_Optimal
, ///< Optimal is the default and will produce compact branches
87 ///< when delay slots cannot be filled.
88 CB_Always
///< 'always' may in some circumstances may not be
89 ///< absolutely adhered to there may not be a corresponding
90 ///< compact form of a branch.
93 static cl::opt
<CompactBranchPolicy
> MipsCompactBranchPolicy(
94 "mips-compact-branches",cl::Optional
,
96 cl::desc("MIPS Specific: Compact branch policy."),
98 clEnumValN(CB_Never
, "never", "Do not use compact branches if possible."),
99 clEnumValN(CB_Optimal
, "optimal", "Use compact branches where appropiate (default)."),
100 clEnumValN(CB_Always
, "always", "Always use compact branches if possible.")
106 using Iter
= MachineBasicBlock::iterator
;
107 using ReverseIter
= MachineBasicBlock::reverse_iterator
;
108 using BB2BrMap
= SmallDenseMap
<MachineBasicBlock
*, MachineInstr
*, 2>;
112 RegDefsUses(const TargetRegisterInfo
&TRI
);
114 void init(const MachineInstr
&MI
);
116 /// This function sets all caller-saved registers in Defs.
117 void setCallerSaved(const MachineInstr
&MI
);
119 /// This function sets all unallocatable registers in Defs.
120 void setUnallocatableRegs(const MachineFunction
&MF
);
122 /// Set bits in Uses corresponding to MBB's live-out registers except for
123 /// the registers that are live-in to SuccBB.
124 void addLiveOut(const MachineBasicBlock
&MBB
,
125 const MachineBasicBlock
&SuccBB
);
127 bool update(const MachineInstr
&MI
, unsigned Begin
, unsigned End
);
130 bool checkRegDefsUses(BitVector
&NewDefs
, BitVector
&NewUses
, unsigned Reg
,
133 /// Returns true if Reg or its alias is in RegSet.
134 bool isRegInSet(const BitVector
&RegSet
, unsigned Reg
) const;
136 const TargetRegisterInfo
&TRI
;
137 BitVector Defs
, Uses
;
140 /// Base class for inspecting loads and stores.
141 class InspectMemInstr
{
143 InspectMemInstr(bool ForbidMemInstr_
) : ForbidMemInstr(ForbidMemInstr_
) {}
144 virtual ~InspectMemInstr() = default;
146 /// Return true if MI cannot be moved to delay slot.
147 bool hasHazard(const MachineInstr
&MI
);
150 /// Flags indicating whether loads or stores have been seen.
151 bool OrigSeenLoad
= false;
152 bool OrigSeenStore
= false;
153 bool SeenLoad
= false;
154 bool SeenStore
= false;
156 /// Memory instructions are not allowed to move to delay slot if this flag
161 virtual bool hasHazard_(const MachineInstr
&MI
) = 0;
164 /// This subclass rejects any memory instructions.
165 class NoMemInstr
: public InspectMemInstr
{
167 NoMemInstr() : InspectMemInstr(true) {}
170 bool hasHazard_(const MachineInstr
&MI
) override
{ return true; }
173 /// This subclass accepts loads from stacks and constant loads.
174 class LoadFromStackOrConst
: public InspectMemInstr
{
176 LoadFromStackOrConst() : InspectMemInstr(false) {}
179 bool hasHazard_(const MachineInstr
&MI
) override
;
182 /// This subclass uses memory dependence information to determine whether a
183 /// memory instruction can be moved to a delay slot.
184 class MemDefsUses
: public InspectMemInstr
{
186 MemDefsUses(const DataLayout
&DL
, const MachineFrameInfo
*MFI
);
189 using ValueType
= PointerUnion
<const Value
*, const PseudoSourceValue
*>;
191 bool hasHazard_(const MachineInstr
&MI
) override
;
193 /// Update Defs and Uses. Return true if there exist dependences that
194 /// disqualify the delay slot candidate between V and values in Uses and
196 bool updateDefsUses(ValueType V
, bool MayStore
);
198 /// Get the list of underlying objects of MI's memory operand.
199 bool getUnderlyingObjects(const MachineInstr
&MI
,
200 SmallVectorImpl
<ValueType
> &Objects
) const;
202 const MachineFrameInfo
*MFI
;
203 SmallPtrSet
<ValueType
, 4> Uses
, Defs
;
204 const DataLayout
&DL
;
206 /// Flags indicating whether loads or stores with no underlying objects have
208 bool SeenNoObjLoad
= false;
209 bool SeenNoObjStore
= false;
212 class MipsDelaySlotFiller
: public MachineFunctionPass
{
214 MipsDelaySlotFiller() : MachineFunctionPass(ID
) {
215 initializeMipsDelaySlotFillerPass(*PassRegistry::getPassRegistry());
218 StringRef
getPassName() const override
{ return "Mips Delay Slot Filler"; }
220 bool runOnMachineFunction(MachineFunction
&F
) override
{
222 bool Changed
= false;
223 for (MachineFunction::iterator FI
= F
.begin(), FE
= F
.end();
225 Changed
|= runOnMachineBasicBlock(*FI
);
227 // This pass invalidates liveness information when it reorders
228 // instructions to fill delay slot. Without this, -verify-machineinstrs
231 F
.getRegInfo().invalidateLiveness();
236 MachineFunctionProperties
getRequiredProperties() const override
{
237 return MachineFunctionProperties().set(
238 MachineFunctionProperties::Property::NoVRegs
);
241 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
242 AU
.addRequired
<MachineBranchProbabilityInfo
>();
243 MachineFunctionPass::getAnalysisUsage(AU
);
249 bool runOnMachineBasicBlock(MachineBasicBlock
&MBB
);
251 Iter
replaceWithCompactBranch(MachineBasicBlock
&MBB
, Iter Branch
,
254 /// This function checks if it is valid to move Candidate to the delay slot
255 /// and returns true if it isn't. It also updates memory and register
256 /// dependence information.
257 bool delayHasHazard(const MachineInstr
&Candidate
, RegDefsUses
&RegDU
,
258 InspectMemInstr
&IM
) const;
260 /// This function searches range [Begin, End) for an instruction that can be
261 /// moved to the delay slot. Returns true on success.
262 template<typename IterTy
>
263 bool searchRange(MachineBasicBlock
&MBB
, IterTy Begin
, IterTy End
,
264 RegDefsUses
&RegDU
, InspectMemInstr
&IM
, Iter Slot
,
265 IterTy
&Filler
) const;
267 /// This function searches in the backward direction for an instruction that
268 /// can be moved to the delay slot. Returns true on success.
269 bool searchBackward(MachineBasicBlock
&MBB
, MachineInstr
&Slot
) const;
271 /// This function searches MBB in the forward direction for an instruction
272 /// that can be moved to the delay slot. Returns true on success.
273 bool searchForward(MachineBasicBlock
&MBB
, Iter Slot
) const;
275 /// This function searches one of MBB's successor blocks for an instruction
276 /// that can be moved to the delay slot and inserts clones of the
277 /// instruction into the successor's predecessor blocks.
278 bool searchSuccBBs(MachineBasicBlock
&MBB
, Iter Slot
) const;
280 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
281 /// successor block that is not a landing pad.
282 MachineBasicBlock
*selectSuccBB(MachineBasicBlock
&B
) const;
284 /// This function analyzes MBB and returns an instruction with an unoccupied
285 /// slot that branches to Dst.
286 std::pair
<MipsInstrInfo::BranchType
, MachineInstr
*>
287 getBranch(MachineBasicBlock
&MBB
, const MachineBasicBlock
&Dst
) const;
289 /// Examine Pred and see if it is possible to insert an instruction into
290 /// one of its branches delay slot or its end.
291 bool examinePred(MachineBasicBlock
&Pred
, const MachineBasicBlock
&Succ
,
292 RegDefsUses
&RegDU
, bool &HasMultipleSuccs
,
293 BB2BrMap
&BrMap
) const;
295 bool terminateSearch(const MachineInstr
&Candidate
) const;
297 const TargetMachine
*TM
= nullptr;
300 } // end anonymous namespace
302 char MipsDelaySlotFiller::ID
= 0;
304 static bool hasUnoccupiedSlot(const MachineInstr
*MI
) {
305 return MI
->hasDelaySlot() && !MI
->isBundledWithSucc();
308 INITIALIZE_PASS(MipsDelaySlotFiller
, DEBUG_TYPE
,
309 "Fill delay slot for MIPS", false, false)
311 /// This function inserts clones of Filler into predecessor blocks.
312 static void insertDelayFiller(Iter Filler
, const BB2BrMap
&BrMap
) {
313 MachineFunction
*MF
= Filler
->getParent()->getParent();
315 for (BB2BrMap::const_iterator I
= BrMap
.begin(); I
!= BrMap
.end(); ++I
) {
317 MIBundleBuilder(I
->second
).append(MF
->CloneMachineInstr(&*Filler
));
320 I
->first
->insert(I
->first
->end(), MF
->CloneMachineInstr(&*Filler
));
325 /// This function adds registers Filler defines to MBB's live-in register list.
326 static void addLiveInRegs(Iter Filler
, MachineBasicBlock
&MBB
) {
327 for (unsigned I
= 0, E
= Filler
->getNumOperands(); I
!= E
; ++I
) {
328 const MachineOperand
&MO
= Filler
->getOperand(I
);
331 if (!MO
.isReg() || !MO
.isDef() || !(R
= MO
.getReg()))
335 const MachineFunction
&MF
= *MBB
.getParent();
336 assert(MF
.getSubtarget().getRegisterInfo()->getAllocatableSet(MF
).test(R
) &&
337 "Shouldn't move an instruction with unallocatable registers across "
338 "basic block boundaries.");
341 if (!MBB
.isLiveIn(R
))
346 RegDefsUses::RegDefsUses(const TargetRegisterInfo
&TRI
)
347 : TRI(TRI
), Defs(TRI
.getNumRegs(), false), Uses(TRI
.getNumRegs(), false) {}
349 void RegDefsUses::init(const MachineInstr
&MI
) {
350 // Add all register operands which are explicit and non-variadic.
351 update(MI
, 0, MI
.getDesc().getNumOperands());
353 // If MI is a call, add RA to Defs to prevent users of RA from going into
358 // Add all implicit register operands of branch instructions except
361 update(MI
, MI
.getDesc().getNumOperands(), MI
.getNumOperands());
362 Defs
.reset(Mips::AT
);
366 void RegDefsUses::setCallerSaved(const MachineInstr
&MI
) {
369 // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
370 // the delay slot. The reason is that RA/RA_64 must not be changed
371 // in the delay slot so that the callee can return to the caller.
372 if (MI
.definesRegister(Mips::RA
) || MI
.definesRegister(Mips::RA_64
)) {
374 Defs
.set(Mips::RA_64
);
377 // If MI is a call, add all caller-saved registers to Defs.
378 BitVector
CallerSavedRegs(TRI
.getNumRegs(), true);
380 CallerSavedRegs
.reset(Mips::ZERO
);
381 CallerSavedRegs
.reset(Mips::ZERO_64
);
383 for (const MCPhysReg
*R
= TRI
.getCalleeSavedRegs(MI
.getParent()->getParent());
385 for (MCRegAliasIterator
AI(*R
, &TRI
, true); AI
.isValid(); ++AI
)
386 CallerSavedRegs
.reset(*AI
);
388 Defs
|= CallerSavedRegs
;
391 void RegDefsUses::setUnallocatableRegs(const MachineFunction
&MF
) {
392 BitVector AllocSet
= TRI
.getAllocatableSet(MF
);
394 for (unsigned R
: AllocSet
.set_bits())
395 for (MCRegAliasIterator
AI(R
, &TRI
, false); AI
.isValid(); ++AI
)
398 AllocSet
.set(Mips::ZERO
);
399 AllocSet
.set(Mips::ZERO_64
);
401 Defs
|= AllocSet
.flip();
404 void RegDefsUses::addLiveOut(const MachineBasicBlock
&MBB
,
405 const MachineBasicBlock
&SuccBB
) {
406 for (MachineBasicBlock::const_succ_iterator SI
= MBB
.succ_begin(),
407 SE
= MBB
.succ_end(); SI
!= SE
; ++SI
)
409 for (const auto &LI
: (*SI
)->liveins())
410 Uses
.set(LI
.PhysReg
);
413 bool RegDefsUses::update(const MachineInstr
&MI
, unsigned Begin
, unsigned End
) {
414 BitVector
NewDefs(TRI
.getNumRegs()), NewUses(TRI
.getNumRegs());
415 bool HasHazard
= false;
417 for (unsigned I
= Begin
; I
!= End
; ++I
) {
418 const MachineOperand
&MO
= MI
.getOperand(I
);
420 if (MO
.isReg() && MO
.getReg())
421 HasHazard
|= checkRegDefsUses(NewDefs
, NewUses
, MO
.getReg(), MO
.isDef());
430 bool RegDefsUses::checkRegDefsUses(BitVector
&NewDefs
, BitVector
&NewUses
,
431 unsigned Reg
, bool IsDef
) const {
434 // check whether Reg has already been defined or used.
435 return (isRegInSet(Defs
, Reg
) || isRegInSet(Uses
, Reg
));
439 // check whether Reg has already been defined.
440 return isRegInSet(Defs
, Reg
);
443 bool RegDefsUses::isRegInSet(const BitVector
&RegSet
, unsigned Reg
) const {
444 // Check Reg and all aliased Registers.
445 for (MCRegAliasIterator
AI(Reg
, &TRI
, true); AI
.isValid(); ++AI
)
446 if (RegSet
.test(*AI
))
451 bool InspectMemInstr::hasHazard(const MachineInstr
&MI
) {
452 if (!MI
.mayStore() && !MI
.mayLoad())
458 OrigSeenLoad
= SeenLoad
;
459 OrigSeenStore
= SeenStore
;
460 SeenLoad
|= MI
.mayLoad();
461 SeenStore
|= MI
.mayStore();
463 // If MI is an ordered or volatile memory reference, disallow moving
464 // subsequent loads and stores to delay slot.
465 if (MI
.hasOrderedMemoryRef() && (OrigSeenLoad
|| OrigSeenStore
)) {
466 ForbidMemInstr
= true;
470 return hasHazard_(MI
);
473 bool LoadFromStackOrConst::hasHazard_(const MachineInstr
&MI
) {
477 if (!MI
.hasOneMemOperand() || !(*MI
.memoperands_begin())->getPseudoValue())
480 if (const PseudoSourceValue
*PSV
=
481 (*MI
.memoperands_begin())->getPseudoValue()) {
482 if (isa
<FixedStackPseudoSourceValue
>(PSV
))
484 return !PSV
->isConstant(nullptr) && !PSV
->isStack();
490 MemDefsUses::MemDefsUses(const DataLayout
&DL
, const MachineFrameInfo
*MFI_
)
491 : InspectMemInstr(false), MFI(MFI_
), DL(DL
) {}
493 bool MemDefsUses::hasHazard_(const MachineInstr
&MI
) {
494 bool HasHazard
= false;
496 // Check underlying object list.
497 SmallVector
<ValueType
, 4> Objs
;
498 if (getUnderlyingObjects(MI
, Objs
)) {
499 for (ValueType VT
: Objs
)
500 HasHazard
|= updateDefsUses(VT
, MI
.mayStore());
504 // No underlying objects found.
505 HasHazard
= MI
.mayStore() && (OrigSeenLoad
|| OrigSeenStore
);
506 HasHazard
|= MI
.mayLoad() || OrigSeenStore
;
508 SeenNoObjLoad
|= MI
.mayLoad();
509 SeenNoObjStore
|= MI
.mayStore();
514 bool MemDefsUses::updateDefsUses(ValueType V
, bool MayStore
) {
516 return !Defs
.insert(V
).second
|| Uses
.count(V
) || SeenNoObjStore
||
520 return Defs
.count(V
) || SeenNoObjStore
;
524 getUnderlyingObjects(const MachineInstr
&MI
,
525 SmallVectorImpl
<ValueType
> &Objects
) const {
526 if (!MI
.hasOneMemOperand())
529 auto & MMO
= **MI
.memoperands_begin();
531 if (const PseudoSourceValue
*PSV
= MMO
.getPseudoValue()) {
532 if (!PSV
->isAliased(MFI
))
534 Objects
.push_back(PSV
);
538 if (const Value
*V
= MMO
.getValue()) {
539 SmallVector
<const Value
*, 4> Objs
;
540 GetUnderlyingObjects(V
, Objs
, DL
);
542 for (const Value
*UValue
: Objs
) {
543 if (!isIdentifiedObject(V
))
546 Objects
.push_back(UValue
);
554 // Replace Branch with the compact branch instruction.
555 Iter
MipsDelaySlotFiller::replaceWithCompactBranch(MachineBasicBlock
&MBB
,
557 const DebugLoc
&DL
) {
558 const MipsSubtarget
&STI
= MBB
.getParent()->getSubtarget
<MipsSubtarget
>();
559 const MipsInstrInfo
*TII
= STI
.getInstrInfo();
561 unsigned NewOpcode
= TII
->getEquivalentCompactForm(Branch
);
562 Branch
= TII
->genInstrWithNewOpc(NewOpcode
, Branch
);
564 std::next(Branch
)->eraseFromParent();
568 // For given opcode returns opcode of corresponding instruction with short
570 // For the pseudo TAILCALL*_MM instructions return the short delay slot
571 // form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
572 // that is too short to make use of for tail calls.
573 static int getEquivalentCallShort(int Opcode
) {
576 return Mips::BGEZALS_MM
;
578 return Mips::BLTZALS_MM
;
581 return Mips::JALS_MM
;
583 return Mips::JALRS_MM
;
584 case Mips::JALR16_MM
:
585 return Mips::JALRS16_MM
;
586 case Mips::TAILCALL_MM
:
587 llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
588 case Mips::TAILCALLREG
:
589 return Mips::JR16_MM
;
591 llvm_unreachable("Unexpected call instruction for microMIPS.");
595 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
596 /// We assume there is only one delay slot per delayed instruction.
597 bool MipsDelaySlotFiller::runOnMachineBasicBlock(MachineBasicBlock
&MBB
) {
598 bool Changed
= false;
599 const MipsSubtarget
&STI
= MBB
.getParent()->getSubtarget
<MipsSubtarget
>();
600 bool InMicroMipsMode
= STI
.inMicroMipsMode();
601 const MipsInstrInfo
*TII
= STI
.getInstrInfo();
603 for (Iter I
= MBB
.begin(); I
!= MBB
.end(); ++I
) {
604 if (!hasUnoccupiedSlot(&*I
))
607 // Delay slot filling is disabled at -O0, or in microMIPS32R6.
608 if (!DisableDelaySlotFiller
&& (TM
->getOptLevel() != CodeGenOpt::None
) &&
609 !(InMicroMipsMode
&& STI
.hasMips32r6())) {
613 if (MipsCompactBranchPolicy
.getValue() != CB_Always
||
614 !TII
->getEquivalentCompactForm(I
)) {
615 if (searchBackward(MBB
, *I
)) {
617 } else if (I
->isTerminator()) {
618 if (searchSuccBBs(MBB
, I
)) {
621 } else if (searchForward(MBB
, I
)) {
627 // Get instruction with delay slot.
628 MachineBasicBlock::instr_iterator DSI
= I
.getInstrIterator();
630 if (InMicroMipsMode
&& TII
->getInstSizeInBytes(*std::next(DSI
)) == 2 &&
632 // If instruction in delay slot is 16b change opcode to
633 // corresponding instruction with short delay slot.
635 // TODO: Implement an instruction mapping table of 16bit opcodes to
636 // 32bit opcodes so that an instruction can be expanded. This would
637 // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
638 // TODO: Permit b16 when branching backwards to the same function
639 // if it is in range.
640 DSI
->setDesc(TII
->get(getEquivalentCallShort(DSI
->getOpcode())));
648 // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
649 // instead of adding NOP replace this instruction with the corresponding
650 // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
651 // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
652 // be replaced with JRC16_MM.
654 // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
655 // form of the CTI. For indirect jumps this will not require inserting a
656 // NOP and for branches will hopefully avoid requiring a NOP.
657 if ((InMicroMipsMode
||
658 (STI
.hasMips32r6() && MipsCompactBranchPolicy
!= CB_Never
)) &&
659 TII
->getEquivalentCompactForm(I
)) {
660 I
= replaceWithCompactBranch(MBB
, I
, I
->getDebugLoc());
665 // Bundle the NOP to the instruction with the delay slot.
666 BuildMI(MBB
, std::next(I
), I
->getDebugLoc(), TII
->get(Mips::NOP
));
667 MIBundleBuilder(MBB
, I
, std::next(I
, 2));
675 template <typename IterTy
>
676 bool MipsDelaySlotFiller::searchRange(MachineBasicBlock
&MBB
, IterTy Begin
,
677 IterTy End
, RegDefsUses
&RegDU
,
678 InspectMemInstr
&IM
, Iter Slot
,
679 IterTy
&Filler
) const {
680 for (IterTy I
= Begin
; I
!= End
;) {
685 if (CurrI
->isDebugInstr())
688 if (terminateSearch(*CurrI
))
691 assert((!CurrI
->isCall() && !CurrI
->isReturn() && !CurrI
->isBranch()) &&
692 "Cannot put calls, returns or branches in delay slot.");
694 if (CurrI
->isKill()) {
695 CurrI
->eraseFromParent();
699 if (delayHasHazard(*CurrI
, RegDU
, IM
))
702 const MipsSubtarget
&STI
= MBB
.getParent()->getSubtarget
<MipsSubtarget
>();
703 if (STI
.isTargetNaCl()) {
704 // In NaCl, instructions that must be masked are forbidden in delay slots.
705 // We only check for loads, stores and SP changes. Calls, returns and
706 // branches are not checked because non-NaCl targets never put them in
709 if ((isBasePlusOffsetMemoryAccess(CurrI
->getOpcode(), &AddrIdx
) &&
710 baseRegNeedsLoadStoreMask(CurrI
->getOperand(AddrIdx
).getReg())) ||
711 CurrI
->modifiesRegister(Mips::SP
, STI
.getRegisterInfo()))
715 bool InMicroMipsMode
= STI
.inMicroMipsMode();
716 const MipsInstrInfo
*TII
= STI
.getInstrInfo();
717 unsigned Opcode
= (*Slot
).getOpcode();
718 // This is complicated by the tail call optimization. For non-PIC code
719 // there is only a 32bit sized unconditional branch which can be assumed
720 // to be able to reach the target. b16 only has a range of +/- 1 KB.
721 // It's entirely possible that the target function is reachable with b16
722 // but we don't have enough information to make that decision.
723 if (InMicroMipsMode
&& TII
->getInstSizeInBytes(*CurrI
) == 2 &&
724 (Opcode
== Mips::JR
|| Opcode
== Mips::PseudoIndirectBranch
||
725 Opcode
== Mips::PseudoIndirectBranch_MM
||
726 Opcode
== Mips::PseudoReturn
|| Opcode
== Mips::TAILCALL
))
728 // Instructions LWP/SWP and MOVEP should not be in a delay slot as that
729 // results in unpredictable behaviour
730 if (InMicroMipsMode
&& (Opcode
== Mips::LWP_MM
|| Opcode
== Mips::SWP_MM
||
731 Opcode
== Mips::MOVEP_MM
))
741 bool MipsDelaySlotFiller::searchBackward(MachineBasicBlock
&MBB
,
742 MachineInstr
&Slot
) const {
743 if (DisableBackwardSearch
)
746 auto *Fn
= MBB
.getParent();
747 RegDefsUses
RegDU(*Fn
->getSubtarget().getRegisterInfo());
748 MemDefsUses
MemDU(Fn
->getDataLayout(), &Fn
->getFrameInfo());
753 MachineBasicBlock::iterator SlotI
= Slot
;
754 if (!searchRange(MBB
, ++SlotI
.getReverse(), MBB
.rend(), RegDU
, MemDU
, Slot
,
758 MBB
.splice(std::next(SlotI
), &MBB
, Filler
.getReverse());
759 MIBundleBuilder(MBB
, SlotI
, std::next(SlotI
, 2));
764 bool MipsDelaySlotFiller::searchForward(MachineBasicBlock
&MBB
,
766 // Can handle only calls.
767 if (DisableForwardSearch
|| !Slot
->isCall())
770 RegDefsUses
RegDU(*MBB
.getParent()->getSubtarget().getRegisterInfo());
774 RegDU
.setCallerSaved(*Slot
);
776 if (!searchRange(MBB
, std::next(Slot
), MBB
.end(), RegDU
, NM
, Slot
, Filler
))
779 MBB
.splice(std::next(Slot
), &MBB
, Filler
);
780 MIBundleBuilder(MBB
, Slot
, std::next(Slot
, 2));
785 bool MipsDelaySlotFiller::searchSuccBBs(MachineBasicBlock
&MBB
,
787 if (DisableSuccBBSearch
)
790 MachineBasicBlock
*SuccBB
= selectSuccBB(MBB
);
795 RegDefsUses
RegDU(*MBB
.getParent()->getSubtarget().getRegisterInfo());
796 bool HasMultipleSuccs
= false;
798 std::unique_ptr
<InspectMemInstr
> IM
;
800 auto *Fn
= MBB
.getParent();
802 // Iterate over SuccBB's predecessor list.
803 for (MachineBasicBlock::pred_iterator PI
= SuccBB
->pred_begin(),
804 PE
= SuccBB
->pred_end(); PI
!= PE
; ++PI
)
805 if (!examinePred(**PI
, *SuccBB
, RegDU
, HasMultipleSuccs
, BrMap
))
808 // Do not allow moving instructions which have unallocatable register operands
809 // across basic block boundaries.
810 RegDU
.setUnallocatableRegs(*Fn
);
812 // Only allow moving loads from stack or constants if any of the SuccBB's
813 // predecessors have multiple successors.
814 if (HasMultipleSuccs
) {
815 IM
.reset(new LoadFromStackOrConst());
817 const MachineFrameInfo
&MFI
= Fn
->getFrameInfo();
818 IM
.reset(new MemDefsUses(Fn
->getDataLayout(), &MFI
));
821 if (!searchRange(MBB
, SuccBB
->begin(), SuccBB
->end(), RegDU
, *IM
, Slot
,
825 insertDelayFiller(Filler
, BrMap
);
826 addLiveInRegs(Filler
, *SuccBB
);
827 Filler
->eraseFromParent();
833 MipsDelaySlotFiller::selectSuccBB(MachineBasicBlock
&B
) const {
837 // Select the successor with the larget edge weight.
838 auto &Prob
= getAnalysis
<MachineBranchProbabilityInfo
>();
839 MachineBasicBlock
*S
= *std::max_element(
840 B
.succ_begin(), B
.succ_end(),
841 [&](const MachineBasicBlock
*Dst0
, const MachineBasicBlock
*Dst1
) {
842 return Prob
.getEdgeProbability(&B
, Dst0
) <
843 Prob
.getEdgeProbability(&B
, Dst1
);
845 return S
->isEHPad() ? nullptr : S
;
848 std::pair
<MipsInstrInfo::BranchType
, MachineInstr
*>
849 MipsDelaySlotFiller::getBranch(MachineBasicBlock
&MBB
,
850 const MachineBasicBlock
&Dst
) const {
851 const MipsInstrInfo
*TII
=
852 MBB
.getParent()->getSubtarget
<MipsSubtarget
>().getInstrInfo();
853 MachineBasicBlock
*TrueBB
= nullptr, *FalseBB
= nullptr;
854 SmallVector
<MachineInstr
*, 2> BranchInstrs
;
855 SmallVector
<MachineOperand
, 2> Cond
;
857 MipsInstrInfo::BranchType R
=
858 TII
->analyzeBranch(MBB
, TrueBB
, FalseBB
, Cond
, false, BranchInstrs
);
860 if ((R
== MipsInstrInfo::BT_None
) || (R
== MipsInstrInfo::BT_NoBranch
))
861 return std::make_pair(R
, nullptr);
863 if (R
!= MipsInstrInfo::BT_CondUncond
) {
864 if (!hasUnoccupiedSlot(BranchInstrs
[0]))
865 return std::make_pair(MipsInstrInfo::BT_None
, nullptr);
867 assert(((R
!= MipsInstrInfo::BT_Uncond
) || (TrueBB
== &Dst
)));
869 return std::make_pair(R
, BranchInstrs
[0]);
872 assert((TrueBB
== &Dst
) || (FalseBB
== &Dst
));
874 // Examine the conditional branch. See if its slot is occupied.
875 if (hasUnoccupiedSlot(BranchInstrs
[0]))
876 return std::make_pair(MipsInstrInfo::BT_Cond
, BranchInstrs
[0]);
878 // If that fails, try the unconditional branch.
879 if (hasUnoccupiedSlot(BranchInstrs
[1]) && (FalseBB
== &Dst
))
880 return std::make_pair(MipsInstrInfo::BT_Uncond
, BranchInstrs
[1]);
882 return std::make_pair(MipsInstrInfo::BT_None
, nullptr);
885 bool MipsDelaySlotFiller::examinePred(MachineBasicBlock
&Pred
,
886 const MachineBasicBlock
&Succ
,
888 bool &HasMultipleSuccs
,
889 BB2BrMap
&BrMap
) const {
890 std::pair
<MipsInstrInfo::BranchType
, MachineInstr
*> P
=
891 getBranch(Pred
, Succ
);
893 // Return if either getBranch wasn't able to analyze the branches or there
894 // were no branches with unoccupied slots.
895 if (P
.first
== MipsInstrInfo::BT_None
)
898 if ((P
.first
!= MipsInstrInfo::BT_Uncond
) &&
899 (P
.first
!= MipsInstrInfo::BT_NoBranch
)) {
900 HasMultipleSuccs
= true;
901 RegDU
.addLiveOut(Pred
, Succ
);
904 BrMap
[&Pred
] = P
.second
;
908 bool MipsDelaySlotFiller::delayHasHazard(const MachineInstr
&Candidate
,
910 InspectMemInstr
&IM
) const {
911 assert(!Candidate
.isKill() &&
912 "KILL instructions should have been eliminated at this point.");
914 bool HasHazard
= Candidate
.isImplicitDef();
916 HasHazard
|= IM
.hasHazard(Candidate
);
917 HasHazard
|= RegDU
.update(Candidate
, 0, Candidate
.getNumOperands());
922 bool MipsDelaySlotFiller::terminateSearch(const MachineInstr
&Candidate
) const {
923 return (Candidate
.isTerminator() || Candidate
.isCall() ||
924 Candidate
.isPosition() || Candidate
.isInlineAsm() ||
925 Candidate
.hasUnmodeledSideEffects());
928 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
929 /// slots in Mips MachineFunctions
930 FunctionPass
*llvm::createMipsDelaySlotFillerPass() { return new MipsDelaySlotFiller(); }