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" 60 "disable-mips-delay-filler",
62 cl::desc(
"Fill all delay slots with NOPs."),
66 "disable-mips-df-forward-search",
68 cl::desc(
"Disallow MIPS delay filler to search forward."),
72 "disable-mips-df-succbb-search",
74 cl::desc(
"Disallow MIPS delay filler to search successor basic blocks."),
78 "disable-mips-df-backward-search",
80 cl::desc(
"Disallow MIPS delay filler to search backward."),
95 cl::desc(
"MIPS Specific: Compact branch policy."),
97 "Do not use compact branches if possible."),
99 "Use compact branches where appropiate (default)."),
101 "Always use compact branches if possible.")));
126 bool update(
const MachineInstr &
MI,
unsigned Begin,
unsigned End);
133 bool isRegInSet(
const BitVector &RegSet,
unsigned Reg)
const;
140 class InspectMemInstr {
142 InspectMemInstr(
bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
143 virtual ~InspectMemInstr() =
default;
150 bool OrigSeenLoad =
false;
151 bool OrigSeenStore =
false;
152 bool SeenLoad =
false;
153 bool SeenStore =
false;
164 class NoMemInstr :
public InspectMemInstr {
166 NoMemInstr() : InspectMemInstr(
true) {}
173 class LoadFromStackOrConst :
public InspectMemInstr {
175 LoadFromStackOrConst() : InspectMemInstr(
false) {}
183 class MemDefsUses :
public InspectMemInstr {
207 bool SeenNoObjLoad =
false;
208 bool SeenNoObjStore =
false;
217 StringRef getPassName()
const override {
return "Mips Delay Slot Filler"; }
221 bool Changed =
false;
224 Changed |= runOnMachineBasicBlock(*FI);
256 bool delayHasHazard(
const MachineInstr &Candidate, RegDefsUses &RegDU,
257 InspectMemInstr &IM)
const;
261 template<
typename IterTy>
263 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
264 IterTy &Filler)
const;
285 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
291 RegDefsUses &RegDU,
bool &HasMultipleSuccs,
292 BB2BrMap &
BrMap)
const;
294 bool terminateSearch(
const MachineInstr &Candidate)
const;
308 "Fill delay slot for MIPS",
false,
false)
311 static
void insertDelayFiller(Iter Filler,
const BB2BrMap &
BrMap) {
314 for (BB2BrMap::const_iterator
I = BrMap.begin();
I != BrMap.end(); ++
I) {
326 for (
unsigned I = 0,
E = Filler->getNumOperands();
I !=
E; ++
I) {
336 "Shouldn't move an instruction with unallocatable registers across " 337 "basic block boundaries.");
361 Defs.reset(Mips::AT);
365 void RegDefsUses::setCallerSaved(
const MachineInstr &MI) {
373 Defs.set(Mips::RA_64);
379 CallerSavedRegs.
reset(Mips::ZERO);
380 CallerSavedRegs.
reset(Mips::ZERO_64);
385 CallerSavedRegs.
reset(*AI);
387 Defs |= CallerSavedRegs;
393 for (
unsigned R : AllocSet.
set_bits())
397 AllocSet.
set(Mips::ZERO);
398 AllocSet.
set(Mips::ZERO_64);
400 Defs |= AllocSet.
flip();
408 for (
const auto &LI : (*SI)->liveins())
409 Uses.
set(LI.PhysReg);
412 bool RegDefsUses::update(
const MachineInstr &MI,
unsigned Begin,
unsigned End) {
414 bool HasHazard =
false;
416 for (
unsigned I = Begin;
I != End; ++
I) {
420 if (checkRegDefsUses(NewDefs, NewUses, MO.
getReg(), MO.
isDef())) {
436 unsigned Reg,
bool IsDef)
const {
440 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
445 return isRegInSet(Defs, Reg);
448 bool RegDefsUses::isRegInSet(
const BitVector &RegSet,
unsigned Reg)
const {
451 if (RegSet.
test(*AI))
456 bool InspectMemInstr::hasHazard(
const MachineInstr &MI) {
463 OrigSeenLoad = SeenLoad;
464 OrigSeenStore = SeenStore;
471 ForbidMemInstr =
true;
475 return hasHazard_(MI);
478 bool LoadFromStackOrConst::hasHazard_(
const MachineInstr &MI) {
487 if (isa<FixedStackPseudoSourceValue>(PSV))
489 return !PSV->isConstant(
nullptr) && !PSV->isStack();
496 : InspectMemInstr(
false), MFI(MFI_), DL(DL) {}
499 bool HasHazard =
false;
505 HasHazard |= updateDefsUses(VT, MI.
mayStore());
510 HasHazard = MI.
mayStore() && (OrigSeenLoad || OrigSeenStore);
511 HasHazard |= MI.
mayLoad() || OrigSeenStore;
521 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
525 return Defs.count(V) || SeenNoObjStore;
537 if (!PSV->isAliased(MFI))
543 if (
const Value *V = MMO.getValue()) {
547 for (
const Value *UValue : Objs) {
567 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
569 std::next(Branch)->eraseFromParent();
581 return Mips::BGEZALS_MM;
583 return Mips::BLTZALS_MM;
586 return Mips::JALS_MM;
588 return Mips::JALRS_MM;
589 case Mips::JALR16_MM:
590 return Mips::JALRS16_MM;
591 case Mips::TAILCALL_MM:
593 case Mips::TAILCALLREG:
594 return Mips::JR16_MM;
603 bool Changed =
false;
620 if (searchBackward(MBB, *
I)) {
622 " in backwards search.\n");
624 }
else if (
I->isTerminator()) {
625 if (searchSuccBBs(MBB,
I)) {
628 " in successor BB search.\n");
630 }
else if (searchForward(MBB,
I)) {
632 " in forwards search.\n");
668 if ((InMicroMipsMode ||
671 I = replaceWithCompactBranch(MBB,
I,
I->getDebugLoc());
679 BuildMI(MBB, std::next(
I),
I->getDebugLoc(), TII->get(Mips::NOP));
688 template <
typename IterTy>
690 IterTy End, RegDefsUses &RegDU,
691 InspectMemInstr &IM, Iter Slot,
692 IterTy &Filler)
const {
693 for (IterTy
I = Begin;
I != End;) {
698 if (CurrI->isDebugInstr()) {
704 if (CurrI->isBundle()) {
708 RegDU.update(*CurrI, 0, CurrI->getNumOperands());
712 if (terminateSearch(*CurrI)) {
718 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
719 "Cannot put calls, returns or branches in delay slot.");
721 if (CurrI->isKill()) {
722 CurrI->eraseFromParent();
726 if (delayHasHazard(*CurrI, RegDU, IM))
744 unsigned Opcode = (*Slot).getOpcode();
751 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
752 Opcode == Mips::PseudoIndirectBranch_MM ||
753 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
757 if (InMicroMipsMode && (Opcode == Mips::LWP_MM || Opcode == Mips::SWP_MM ||
758 Opcode == Mips::MOVEP_MM))
777 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
778 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
784 if (!searchRange(MBB, ++SlotI.
getReverse(), MBB.
rend(), RegDU, MemDU, Slot,
787 "slot using backwards search.\n");
791 MBB.
splice(std::next(SlotI), &MBB, Filler.getReverse());
807 RegDU.setCallerSaved(*Slot);
809 if (!searchRange(MBB, std::next(Slot), MBB.
end(), RegDU, NM, Slot, Filler)) {
811 "slot using forwards search.\n");
815 MBB.
splice(std::next(Slot), &MBB, Filler);
832 bool HasMultipleSuccs =
false;
834 std::unique_ptr<InspectMemInstr> IM;
840 PE = SuccBB->
pred_end(); PI != PE; ++PI)
841 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
846 RegDU.setUnallocatableRegs(*Fn);
850 if (HasMultipleSuccs) {
851 IM.reset(
new LoadFromStackOrConst());
854 IM.reset(
new MemDefsUses(Fn->getDataLayout(), &MFI));
857 if (!searchRange(MBB, SuccBB->
begin(), SuccBB->
end(), RegDU, *IM, Slot,
861 insertDelayFiller(Filler, BrMap);
863 Filler->eraseFromParent();
874 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
878 return Prob.getEdgeProbability(&B, Dst0) <
879 Prob.getEdgeProbability(&B, Dst1);
881 return S->
isEHPad() ? nullptr : S;
884 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
894 TII->
analyzeBranch(MBB, TrueBB, FalseBB, Cond,
false, BranchInstrs);
897 return std::make_pair(R,
nullptr);
905 return std::make_pair(R, BranchInstrs[0]);
908 assert((TrueBB == &Dst) || (FalseBB == &Dst));
924 bool &HasMultipleSuccs,
925 BB2BrMap &BrMap)
const {
926 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
P =
927 getBranch(Pred, Succ);
936 HasMultipleSuccs =
true;
937 RegDU.addLiveOut(Pred, Succ);
940 BrMap[&Pred] = P.second;
944 bool MipsDelaySlotFiller::delayHasHazard(
const MachineInstr &Candidate,
946 InspectMemInstr &IM)
const {
948 "KILL instructions should have been eliminated at this point.");
952 HasHazard |= IM.hasHazard(Candidate);
953 HasHazard |= RegDU.update(Candidate, 0, Candidate.
getNumOperands());
958 bool MipsDelaySlotFiller::terminateSearch(
const MachineInstr &Candidate)
const {
967 return new MipsDelaySlotFiller();
BitVector getAllocatableSet(const MachineFunction &MF, const TargetRegisterClass *RC=nullptr) const
Returns a bitset indexed by register number indicating if a register is allocatable or not...
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
Return the number of bytes of code the specified instruction may be.
A parsed version of the target data layout string in and methods for querying it. ...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isCall(QueryType Type=AnyInBundle) const
This class represents lattice values for constants.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Branch Analysis.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool isBasePlusOffsetMemoryAccess(unsigned Opcode, unsigned *AddrIdx, bool *IsStore=nullptr)
void push_back(const T &Elt)
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
const MipsInstrInfo * getInstrInfo() const override
bool test(unsigned Idx) const
Optimal is the default and will produce compact branches when delay slots cannot be filled...
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions ...
static bool hasUnoccupiedSlot(const MachineInstr *MI)
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
block Block Frequency true
static void getUnderlyingObjects(const MachineInstr *MI, SmallVectorImpl< const Value *> &Objs, const DataLayout &DL)
Return the underlying objects for the memory references of an instruction.
static cl::opt< bool > DisableDelaySlotFiller("disable-mips-delay-filler", cl::init(false), cl::desc("Fill all delay slots with NOPs."), cl::Hidden)
SI optimize exec mask operations pre RA
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
bool inMicroMipsMode() const
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool baseRegNeedsLoadStoreMask(unsigned Reg)
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB)
This function adds registers Filler defines to MBB's live-in register list.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
static cl::opt< bool > DisableBackwardSearch("disable-mips-df-backward-search", cl::init(false), cl::desc("Disallow MIPS delay filler to search backward."), cl::Hidden)
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
static cl::opt< bool > DisableForwardSearch("disable-mips-df-forward-search", cl::init(true), cl::desc("Disallow MIPS delay filler to search forward."), cl::Hidden)
virtual const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const =0
Return a null-terminated list of all of the callee-saved registers on this target.
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
bool isTargetNaCl() const
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
INITIALIZE_PASS(MipsDelaySlotFiller, DEBUG_TYPE, "Fill delay slot for MIPS", false, false) static void insertDelayFiller(Iter Filler
This function inserts clones of Filler into predecessor blocks.
initializer< Ty > init(const Ty &Val)
MachineInstrBundleIterator< MachineInstr > iterator
void GetUnderlyingObjects(const Value *V, SmallVectorImpl< const Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
'always' may in some circumstances may not be absolutely adhered to there may not be a corresponding ...
unsigned getEquivalentCompactForm(const MachineBasicBlock::iterator I) const
Determine the opcode of a non-delay slot form for a branch if one exists.
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr fully defines the specified register.
FunctionPass class - This class is used to implement most global optimizations.
std::vector< MachineBasicBlock * >::const_iterator const_succ_iterator
std::vector< MachineBasicBlock * >::iterator pred_iterator
succ_iterator succ_begin()
static cl::opt< bool > DisableSuccBBSearch("disable-mips-df-succbb-search", cl::init(true), cl::desc("Disallow MIPS delay filler to search successor basic blocks."), cl::Hidden)
bool isImplicitDef() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
pred_iterator pred_begin()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
const MipsRegisterInfo * getRegisterInfo() const override
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Special value supplied for machine level alias analysis.
static int getEquivalentCallShort(int Opcode)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
const MachineBasicBlock * getParent() const
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic 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 '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool isEHPad() const
Returns true if the block is a landing pad.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
The policy 'never' may in some circumstances or for some ISAs not be absolutely adhered to...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MIBundleBuilder & append(MachineInstr *MI)
Insert MI into MBB by appending it to the instructions in the bundle.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
iterator_range< const_set_bits_iterator > set_bits() const
LLVM Value Representation.
static cl::opt< CompactBranchPolicy > MipsCompactBranchPolicy("mips-compact-branches", cl::Optional, cl::init(CB_Optimal), cl::desc("MIPS Specific: Compact branch policy."), cl::values(clEnumValN(CB_Never, "never", "Do not use compact branches if possible."), clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."), clEnumValN(CB_Always, "always", "Always use compact branches if possible.")))
Primary interface to the complete machine description for the target machine.
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
StringRef - Represent a constant reference to a string, i.e.
Register getReg() const
getReg - Returns the register number.
void initializeMipsDelaySlotFillerPass(PassRegistry &)
const MachineOperand & getOperand(unsigned i) const
Properties which a MachineFunction may have at a given point in time.
Helper class for constructing bundles of MachineInstrs.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...