1 //===-- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler ------------------===//
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 //===----------------------------------------------------------------------===//
10 // Simple pass to fill delay slots with useful instructions.
12 //===----------------------------------------------------------------------===//
14 #include "MCTargetDesc/MipsMCNaCl.h"
16 #include "MipsInstrInfo.h"
17 #include "MipsTargetMachine.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
35 #define DEBUG_TYPE "delay-slot-filler"
37 STATISTIC(FilledSlots, "Number of delay slots filled");
38 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
41 static cl::opt<bool> DisableDelaySlotFiller(
42 "disable-mips-delay-filler",
44 cl::desc("Fill all delay slots with NOPs."),
47 static cl::opt<bool> DisableForwardSearch(
48 "disable-mips-df-forward-search",
50 cl::desc("Disallow MIPS delay filler to search forward."),
53 static cl::opt<bool> DisableSuccBBSearch(
54 "disable-mips-df-succbb-search",
56 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
59 static cl::opt<bool> DisableBackwardSearch(
60 "disable-mips-df-backward-search",
62 cl::desc("Disallow MIPS delay filler to search backward."),
65 enum CompactBranchPolicy {
66 CB_Never, ///< The policy 'never' may in some circumstances or for some
67 ///< ISAs not be absolutely adhered to.
68 CB_Optimal, ///< Optimal is the default and will produce compact branches
69 ///< when delay slots cannot be filled.
70 CB_Always ///< 'always' may in some circumstances may not be
71 ///< absolutely adhered to there may not be a corresponding
72 ///< compact form of a branch.
75 static cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy(
76 "mips-compact-branches",cl::Optional,
78 cl::desc("MIPS Specific: Compact branch policy."),
80 clEnumValN(CB_Never, "never", "Do not use compact branches if possible."),
81 clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."),
82 clEnumValN(CB_Always, "always", "Always use compact branches if possible.")
87 typedef MachineBasicBlock::iterator Iter;
88 typedef MachineBasicBlock::reverse_iterator ReverseIter;
89 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
93 RegDefsUses(const TargetRegisterInfo &TRI);
94 void init(const MachineInstr &MI);
96 /// This function sets all caller-saved registers in Defs.
97 void setCallerSaved(const MachineInstr &MI);
99 /// This function sets all unallocatable registers in Defs.
100 void setUnallocatableRegs(const MachineFunction &MF);
102 /// Set bits in Uses corresponding to MBB's live-out registers except for
103 /// the registers that are live-in to SuccBB.
104 void addLiveOut(const MachineBasicBlock &MBB,
105 const MachineBasicBlock &SuccBB);
107 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
110 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
113 /// Returns true if Reg or its alias is in RegSet.
114 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
116 const TargetRegisterInfo &TRI;
117 BitVector Defs, Uses;
120 /// Base class for inspecting loads and stores.
121 class InspectMemInstr {
123 InspectMemInstr(bool ForbidMemInstr_)
124 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
125 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
127 /// Return true if MI cannot be moved to delay slot.
128 bool hasHazard(const MachineInstr &MI);
130 virtual ~InspectMemInstr() {}
133 /// Flags indicating whether loads or stores have been seen.
134 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
136 /// Memory instructions are not allowed to move to delay slot if this flag
141 virtual bool hasHazard_(const MachineInstr &MI) = 0;
144 /// This subclass rejects any memory instructions.
145 class NoMemInstr : public InspectMemInstr {
147 NoMemInstr() : InspectMemInstr(true) {}
149 bool hasHazard_(const MachineInstr &MI) override { return true; }
152 /// This subclass accepts loads from stacks and constant loads.
153 class LoadFromStackOrConst : public InspectMemInstr {
155 LoadFromStackOrConst() : InspectMemInstr(false) {}
157 bool hasHazard_(const MachineInstr &MI) override;
160 /// This subclass uses memory dependence information to determine whether a
161 /// memory instruction can be moved to a delay slot.
162 class MemDefsUses : public InspectMemInstr {
164 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
167 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
169 bool hasHazard_(const MachineInstr &MI) override;
171 /// Update Defs and Uses. Return true if there exist dependences that
172 /// disqualify the delay slot candidate between V and values in Uses and
174 bool updateDefsUses(ValueType V, bool MayStore);
176 /// Get the list of underlying objects of MI's memory operand.
177 bool getUnderlyingObjects(const MachineInstr &MI,
178 SmallVectorImpl<ValueType> &Objects) const;
180 const MachineFrameInfo *MFI;
181 SmallPtrSet<ValueType, 4> Uses, Defs;
182 const DataLayout &DL;
184 /// Flags indicating whether loads or stores with no underlying objects have
186 bool SeenNoObjLoad, SeenNoObjStore;
189 class Filler : public MachineFunctionPass {
191 Filler(TargetMachine &tm)
192 : MachineFunctionPass(ID), TM(tm) { }
194 StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
196 bool runOnMachineFunction(MachineFunction &F) override {
197 bool Changed = false;
198 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
200 Changed |= runOnMachineBasicBlock(*FI);
202 // This pass invalidates liveness information when it reorders
203 // instructions to fill delay slot. Without this, -verify-machineinstrs
206 F.getRegInfo().invalidateLiveness();
211 MachineFunctionProperties getRequiredProperties() const override {
212 return MachineFunctionProperties().set(
213 MachineFunctionProperties::Property::NoVRegs);
216 void getAnalysisUsage(AnalysisUsage &AU) const override {
217 AU.addRequired<MachineBranchProbabilityInfo>();
218 MachineFunctionPass::getAnalysisUsage(AU);
222 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
224 Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
227 /// This function checks if it is valid to move Candidate to the delay slot
228 /// and returns true if it isn't. It also updates memory and register
229 /// dependence information.
230 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
231 InspectMemInstr &IM) const;
233 /// This function searches range [Begin, End) for an instruction that can be
234 /// moved to the delay slot. Returns true on success.
235 template<typename IterTy>
236 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
237 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
238 IterTy &Filler) const;
240 /// This function searches in the backward direction for an instruction that
241 /// can be moved to the delay slot. Returns true on success.
242 bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
244 /// This function searches MBB in the forward direction for an instruction
245 /// that can be moved to the delay slot. Returns true on success.
246 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
248 /// This function searches one of MBB's successor blocks for an instruction
249 /// that can be moved to the delay slot and inserts clones of the
250 /// instruction into the successor's predecessor blocks.
251 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
253 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
254 /// successor block that is not a landing pad.
255 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
257 /// This function analyzes MBB and returns an instruction with an unoccupied
258 /// slot that branches to Dst.
259 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
260 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
262 /// Examine Pred and see if it is possible to insert an instruction into
263 /// one of its branches delay slot or its end.
264 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
265 RegDefsUses &RegDU, bool &HasMultipleSuccs,
266 BB2BrMap &BrMap) const;
268 bool terminateSearch(const MachineInstr &Candidate) const;
275 } // end of anonymous namespace
277 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
278 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
281 /// This function inserts clones of Filler into predecessor blocks.
282 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
283 MachineFunction *MF = Filler->getParent()->getParent();
285 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
287 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
290 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
295 /// This function adds registers Filler defines to MBB's live-in register list.
296 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
297 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
298 const MachineOperand &MO = Filler->getOperand(I);
301 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
305 const MachineFunction &MF = *MBB.getParent();
306 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
307 "Shouldn't move an instruction with unallocatable registers across "
308 "basic block boundaries.");
311 if (!MBB.isLiveIn(R))
316 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
317 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
319 void RegDefsUses::init(const MachineInstr &MI) {
320 // Add all register operands which are explicit and non-variadic.
321 update(MI, 0, MI.getDesc().getNumOperands());
323 // If MI is a call, add RA to Defs to prevent users of RA from going into
328 // Add all implicit register operands of branch instructions except
331 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
332 Defs.reset(Mips::AT);
336 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
339 // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
340 // the delay slot. The reason is that RA/RA_64 must not be changed
341 // in the delay slot so that the callee can return to the caller.
342 if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
344 Defs.set(Mips::RA_64);
347 // If MI is a call, add all caller-saved registers to Defs.
348 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
350 CallerSavedRegs.reset(Mips::ZERO);
351 CallerSavedRegs.reset(Mips::ZERO_64);
353 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
355 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
356 CallerSavedRegs.reset(*AI);
358 Defs |= CallerSavedRegs;
361 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
362 BitVector AllocSet = TRI.getAllocatableSet(MF);
364 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
365 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
368 AllocSet.set(Mips::ZERO);
369 AllocSet.set(Mips::ZERO_64);
371 Defs |= AllocSet.flip();
374 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
375 const MachineBasicBlock &SuccBB) {
376 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
377 SE = MBB.succ_end(); SI != SE; ++SI)
379 for (const auto &LI : (*SI)->liveins())
380 Uses.set(LI.PhysReg);
383 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
384 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
385 bool HasHazard = false;
387 for (unsigned I = Begin; I != End; ++I) {
388 const MachineOperand &MO = MI.getOperand(I);
390 if (MO.isReg() && MO.getReg())
391 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
400 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
401 unsigned Reg, bool IsDef) const {
404 // check whether Reg has already been defined or used.
405 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
409 // check whether Reg has already been defined.
410 return isRegInSet(Defs, Reg);
413 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
414 // Check Reg and all aliased Registers.
415 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
416 if (RegSet.test(*AI))
421 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
422 if (!MI.mayStore() && !MI.mayLoad())
428 OrigSeenLoad = SeenLoad;
429 OrigSeenStore = SeenStore;
430 SeenLoad |= MI.mayLoad();
431 SeenStore |= MI.mayStore();
433 // If MI is an ordered or volatile memory reference, disallow moving
434 // subsequent loads and stores to delay slot.
435 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
436 ForbidMemInstr = true;
440 return hasHazard_(MI);
443 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
447 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
450 if (const PseudoSourceValue *PSV =
451 (*MI.memoperands_begin())->getPseudoValue()) {
452 if (isa<FixedStackPseudoSourceValue>(PSV))
454 return !PSV->isConstant(nullptr) && !PSV->isStack();
460 MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
461 : InspectMemInstr(false), MFI(MFI_), DL(DL), SeenNoObjLoad(false),
462 SeenNoObjStore(false) {}
464 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
465 bool HasHazard = false;
466 SmallVector<ValueType, 4> Objs;
468 // Check underlying object list.
469 if (getUnderlyingObjects(MI, Objs)) {
470 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
471 I != Objs.end(); ++I)
472 HasHazard |= updateDefsUses(*I, MI.mayStore());
477 // No underlying objects found.
478 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
479 HasHazard |= MI.mayLoad() || OrigSeenStore;
481 SeenNoObjLoad |= MI.mayLoad();
482 SeenNoObjStore |= MI.mayStore();
487 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
489 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
493 return Defs.count(V) || SeenNoObjStore;
497 getUnderlyingObjects(const MachineInstr &MI,
498 SmallVectorImpl<ValueType> &Objects) const {
499 if (!MI.hasOneMemOperand() ||
500 (!(*MI.memoperands_begin())->getValue() &&
501 !(*MI.memoperands_begin())->getPseudoValue()))
504 if (const PseudoSourceValue *PSV =
505 (*MI.memoperands_begin())->getPseudoValue()) {
506 if (!PSV->isAliased(MFI))
508 Objects.push_back(PSV);
512 const Value *V = (*MI.memoperands_begin())->getValue();
514 SmallVector<Value *, 4> Objs;
515 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
517 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
519 if (!isIdentifiedObject(V))
522 Objects.push_back(*I);
528 // Replace Branch with the compact branch instruction.
529 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
530 const DebugLoc &DL) {
531 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
532 const MipsInstrInfo *TII = STI.getInstrInfo();
534 unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
535 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
537 std::next(Branch)->eraseFromParent();
541 // For given opcode returns opcode of corresponding instruction with short
543 // For the pseudo TAILCALL*_MM instrunctions return the short delay slot
544 // form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
545 // that is too short to make use of for tail calls.
546 static int getEquivalentCallShort(int Opcode) {
549 return Mips::BGEZALS_MM;
551 return Mips::BLTZALS_MM;
553 return Mips::JALS_MM;
555 return Mips::JALRS_MM;
556 case Mips::JALR16_MM:
557 return Mips::JALRS16_MM;
558 case Mips::TAILCALL_MM:
559 llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
560 case Mips::TAILCALLREG:
561 return Mips::JR16_MM;
563 llvm_unreachable("Unexpected call instruction for microMIPS.");
567 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
568 /// We assume there is only one delay slot per delayed instruction.
569 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
570 bool Changed = false;
571 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
572 bool InMicroMipsMode = STI.inMicroMipsMode();
573 const MipsInstrInfo *TII = STI.getInstrInfo();
575 if (InMicroMipsMode && STI.hasMips32r6()) {
576 // This is microMIPS32r6 or microMIPS64r6 processor. Delay slot for
577 // branching instructions is not needed.
581 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
582 if (!hasUnoccupiedSlot(&*I))
588 // Delay slot filling is disabled at -O0.
589 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
592 if (MipsCompactBranchPolicy.getValue() != CB_Always ||
593 !TII->getEquivalentCompactForm(I)) {
594 if (searchBackward(MBB, *I)) {
596 } else if (I->isTerminator()) {
597 if (searchSuccBBs(MBB, I)) {
600 } else if (searchForward(MBB, I)) {
606 // Get instruction with delay slot.
607 MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
609 if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
611 // If instruction in delay slot is 16b change opcode to
612 // corresponding instruction with short delay slot.
614 // TODO: Implement an instruction mapping table of 16bit opcodes to
615 // 32bit opcodes so that an instruction can be expanded. This would
616 // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
617 // TODO: Permit b16 when branching backwards to the the same function
618 // if it is in range.
619 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
625 // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
626 // instead of adding NOP replace this instruction with the corresponding
627 // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
628 // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
629 // be replaced with JRC16_MM.
631 // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
632 // form of the CTI. For indirect jumps this will not require inserting a
633 // NOP and for branches will hopefully avoid requiring a NOP.
634 if ((InMicroMipsMode ||
635 (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
636 TII->getEquivalentCompactForm(I)) {
637 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
641 // Bundle the NOP to the instruction with the delay slot.
642 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
643 MIBundleBuilder(MBB, I, std::next(I, 2));
649 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
650 /// slots in Mips MachineFunctions
651 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
652 return new Filler(tm);
655 template<typename IterTy>
656 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
657 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
658 IterTy &Filler) const {
659 for (IterTy I = Begin; I != End;) {
664 if (CurrI->isDebugValue())
667 if (terminateSearch(*CurrI))
670 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
671 "Cannot put calls, returns or branches in delay slot.");
673 if (CurrI->isKill()) {
674 CurrI->eraseFromParent();
678 if (delayHasHazard(*CurrI, RegDU, IM))
681 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
682 if (STI.isTargetNaCl()) {
683 // In NaCl, instructions that must be masked are forbidden in delay slots.
684 // We only check for loads, stores and SP changes. Calls, returns and
685 // branches are not checked because non-NaCl targets never put them in
688 if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
689 baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
690 CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
694 bool InMicroMipsMode = STI.inMicroMipsMode();
695 const MipsInstrInfo *TII = STI.getInstrInfo();
696 unsigned Opcode = (*Slot).getOpcode();
697 // This is complicated by the tail call optimization. For non-PIC code
698 // there is only a 32bit sized unconditional branch which can be assumed
699 // to be able to reach the target. b16 only has a range of +/- 1 KB.
700 // It's entirely possible that the target function is reachable with b16
701 // but we don't have enough information to make that decision.
702 if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
703 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
704 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
714 bool Filler::searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const {
715 if (DisableBackwardSearch)
718 auto *Fn = MBB.getParent();
719 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
720 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
725 MachineBasicBlock::iterator SlotI = Slot;
726 if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
730 MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
731 MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
736 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
737 // Can handle only calls.
738 if (DisableForwardSearch || !Slot->isCall())
741 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
745 RegDU.setCallerSaved(*Slot);
747 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
750 MBB.splice(std::next(Slot), &MBB, Filler);
751 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
756 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
757 if (DisableSuccBBSearch)
760 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
765 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
766 bool HasMultipleSuccs = false;
768 std::unique_ptr<InspectMemInstr> IM;
770 auto *Fn = MBB.getParent();
772 // Iterate over SuccBB's predecessor list.
773 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
774 PE = SuccBB->pred_end(); PI != PE; ++PI)
775 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
778 // Do not allow moving instructions which have unallocatable register operands
779 // across basic block boundaries.
780 RegDU.setUnallocatableRegs(*Fn);
782 // Only allow moving loads from stack or constants if any of the SuccBB's
783 // predecessors have multiple successors.
784 if (HasMultipleSuccs) {
785 IM.reset(new LoadFromStackOrConst());
787 const MachineFrameInfo &MFI = Fn->getFrameInfo();
788 IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
791 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
795 insertDelayFiller(Filler, BrMap);
796 addLiveInRegs(Filler, *SuccBB);
797 Filler->eraseFromParent();
802 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
806 // Select the successor with the larget edge weight.
807 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
808 MachineBasicBlock *S = *std::max_element(
809 B.succ_begin(), B.succ_end(),
810 [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
811 return Prob.getEdgeProbability(&B, Dst0) <
812 Prob.getEdgeProbability(&B, Dst1);
814 return S->isEHPad() ? nullptr : S;
817 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
818 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
819 const MipsInstrInfo *TII =
820 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
821 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
822 SmallVector<MachineInstr*, 2> BranchInstrs;
823 SmallVector<MachineOperand, 2> Cond;
825 MipsInstrInfo::BranchType R =
826 TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
828 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
829 return std::make_pair(R, nullptr);
831 if (R != MipsInstrInfo::BT_CondUncond) {
832 if (!hasUnoccupiedSlot(BranchInstrs[0]))
833 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
835 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
837 return std::make_pair(R, BranchInstrs[0]);
840 assert((TrueBB == &Dst) || (FalseBB == &Dst));
842 // Examine the conditional branch. See if its slot is occupied.
843 if (hasUnoccupiedSlot(BranchInstrs[0]))
844 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
846 // If that fails, try the unconditional branch.
847 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
848 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
850 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
853 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
854 RegDefsUses &RegDU, bool &HasMultipleSuccs,
855 BB2BrMap &BrMap) const {
856 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
857 getBranch(Pred, Succ);
859 // Return if either getBranch wasn't able to analyze the branches or there
860 // were no branches with unoccupied slots.
861 if (P.first == MipsInstrInfo::BT_None)
864 if ((P.first != MipsInstrInfo::BT_Uncond) &&
865 (P.first != MipsInstrInfo::BT_NoBranch)) {
866 HasMultipleSuccs = true;
867 RegDU.addLiveOut(Pred, Succ);
870 BrMap[&Pred] = P.second;
874 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
875 InspectMemInstr &IM) const {
876 assert(!Candidate.isKill() &&
877 "KILL instructions should have been eliminated at this point.");
879 bool HasHazard = Candidate.isImplicitDef();
881 HasHazard |= IM.hasHazard(Candidate);
882 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
887 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
888 return (Candidate.isTerminator() || Candidate.isCall() ||
889 Candidate.isPosition() || Candidate.isInlineAsm() ||
890 Candidate.hasUnmodeledSideEffects());