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."),
66 typedef MachineBasicBlock::iterator Iter;
67 typedef MachineBasicBlock::reverse_iterator ReverseIter;
68 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
72 RegDefsUses(const TargetRegisterInfo &TRI);
73 void init(const MachineInstr &MI);
75 /// This function sets all caller-saved registers in Defs.
76 void setCallerSaved(const MachineInstr &MI);
78 /// This function sets all unallocatable registers in Defs.
79 void setUnallocatableRegs(const MachineFunction &MF);
81 /// Set bits in Uses corresponding to MBB's live-out registers except for
82 /// the registers that are live-in to SuccBB.
83 void addLiveOut(const MachineBasicBlock &MBB,
84 const MachineBasicBlock &SuccBB);
86 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
89 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
92 /// Returns true if Reg or its alias is in RegSet.
93 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
95 const TargetRegisterInfo &TRI;
99 /// Base class for inspecting loads and stores.
100 class InspectMemInstr {
102 InspectMemInstr(bool ForbidMemInstr_)
103 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
104 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
106 /// Return true if MI cannot be moved to delay slot.
107 bool hasHazard(const MachineInstr &MI);
109 virtual ~InspectMemInstr() {}
112 /// Flags indicating whether loads or stores have been seen.
113 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
115 /// Memory instructions are not allowed to move to delay slot if this flag
120 virtual bool hasHazard_(const MachineInstr &MI) = 0;
123 /// This subclass rejects any memory instructions.
124 class NoMemInstr : public InspectMemInstr {
126 NoMemInstr() : InspectMemInstr(true) {}
128 bool hasHazard_(const MachineInstr &MI) override { return true; }
131 /// This subclass accepts loads from stacks and constant loads.
132 class LoadFromStackOrConst : public InspectMemInstr {
134 LoadFromStackOrConst() : InspectMemInstr(false) {}
136 bool hasHazard_(const MachineInstr &MI) override;
139 /// This subclass uses memory dependence information to determine whether a
140 /// memory instruction can be moved to a delay slot.
141 class MemDefsUses : public InspectMemInstr {
143 MemDefsUses(const MachineFrameInfo *MFI);
146 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
148 bool hasHazard_(const MachineInstr &MI) override;
150 /// Update Defs and Uses. Return true if there exist dependences that
151 /// disqualify the delay slot candidate between V and values in Uses and
153 bool updateDefsUses(ValueType V, bool MayStore);
155 /// Get the list of underlying objects of MI's memory operand.
156 bool getUnderlyingObjects(const MachineInstr &MI,
157 SmallVectorImpl<ValueType> &Objects) const;
159 const MachineFrameInfo *MFI;
160 SmallPtrSet<ValueType, 4> Uses, Defs;
162 /// Flags indicating whether loads or stores with no underlying objects have
164 bool SeenNoObjLoad, SeenNoObjStore;
167 class Filler : public MachineFunctionPass {
169 Filler(TargetMachine &tm)
170 : MachineFunctionPass(ID), TM(tm) { }
172 const char *getPassName() const override {
173 return "Mips Delay Slot Filler";
176 bool runOnMachineFunction(MachineFunction &F) override {
177 bool Changed = false;
178 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
180 Changed |= runOnMachineBasicBlock(*FI);
182 // This pass invalidates liveness information when it reorders
183 // instructions to fill delay slot. Without this, -verify-machineinstrs
186 F.getRegInfo().invalidateLiveness();
191 void getAnalysisUsage(AnalysisUsage &AU) const override {
192 AU.addRequired<MachineBranchProbabilityInfo>();
193 MachineFunctionPass::getAnalysisUsage(AU);
197 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
199 Iter replaceWithCompactBranch(MachineBasicBlock &MBB,
200 Iter Branch, DebugLoc DL);
202 Iter replaceWithCompactJump(MachineBasicBlock &MBB,
203 Iter Jump, DebugLoc DL);
205 /// This function checks if it is valid to move Candidate to the delay slot
206 /// and returns true if it isn't. It also updates memory and register
207 /// dependence information.
208 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
209 InspectMemInstr &IM) const;
211 /// This function searches range [Begin, End) for an instruction that can be
212 /// moved to the delay slot. Returns true on success.
213 template<typename IterTy>
214 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
215 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
216 IterTy &Filler) const;
218 /// This function searches in the backward direction for an instruction that
219 /// can be moved to the delay slot. Returns true on success.
220 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
222 /// This function searches MBB in the forward direction for an instruction
223 /// that can be moved to the delay slot. Returns true on success.
224 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
226 /// This function searches one of MBB's successor blocks for an instruction
227 /// that can be moved to the delay slot and inserts clones of the
228 /// instruction into the successor's predecessor blocks.
229 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
231 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
232 /// successor block that is not a landing pad.
233 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
235 /// This function analyzes MBB and returns an instruction with an unoccupied
236 /// slot that branches to Dst.
237 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
238 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
240 /// Examine Pred and see if it is possible to insert an instruction into
241 /// one of its branches delay slot or its end.
242 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
243 RegDefsUses &RegDU, bool &HasMultipleSuccs,
244 BB2BrMap &BrMap) const;
246 bool terminateSearch(const MachineInstr &Candidate) const;
253 } // end of anonymous namespace
255 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
256 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
259 /// This function inserts clones of Filler into predecessor blocks.
260 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
261 MachineFunction *MF = Filler->getParent()->getParent();
263 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
265 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
268 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
273 /// This function adds registers Filler defines to MBB's live-in register list.
274 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
275 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
276 const MachineOperand &MO = Filler->getOperand(I);
279 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
283 const MachineFunction &MF = *MBB.getParent();
284 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
285 "Shouldn't move an instruction with unallocatable registers across "
286 "basic block boundaries.");
289 if (!MBB.isLiveIn(R))
294 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
295 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
297 void RegDefsUses::init(const MachineInstr &MI) {
298 // Add all register operands which are explicit and non-variadic.
299 update(MI, 0, MI.getDesc().getNumOperands());
301 // If MI is a call, add RA to Defs to prevent users of RA from going into
306 // Add all implicit register operands of branch instructions except
309 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
310 Defs.reset(Mips::AT);
314 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
317 // If MI is a call, add all caller-saved registers to Defs.
318 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
320 CallerSavedRegs.reset(Mips::ZERO);
321 CallerSavedRegs.reset(Mips::ZERO_64);
323 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
324 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
325 CallerSavedRegs.reset(*AI);
327 Defs |= CallerSavedRegs;
330 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
331 BitVector AllocSet = TRI.getAllocatableSet(MF);
333 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
334 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
337 AllocSet.set(Mips::ZERO);
338 AllocSet.set(Mips::ZERO_64);
340 Defs |= AllocSet.flip();
343 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
344 const MachineBasicBlock &SuccBB) {
345 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
346 SE = MBB.succ_end(); SI != SE; ++SI)
348 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
349 LE = (*SI)->livein_end(); LI != LE; ++LI)
353 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
354 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
355 bool HasHazard = false;
357 for (unsigned I = Begin; I != End; ++I) {
358 const MachineOperand &MO = MI.getOperand(I);
360 if (MO.isReg() && MO.getReg())
361 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
370 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
371 unsigned Reg, bool IsDef) const {
374 // check whether Reg has already been defined or used.
375 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
379 // check whether Reg has already been defined.
380 return isRegInSet(Defs, Reg);
383 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
384 // Check Reg and all aliased Registers.
385 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
386 if (RegSet.test(*AI))
391 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
392 if (!MI.mayStore() && !MI.mayLoad())
398 OrigSeenLoad = SeenLoad;
399 OrigSeenStore = SeenStore;
400 SeenLoad |= MI.mayLoad();
401 SeenStore |= MI.mayStore();
403 // If MI is an ordered or volatile memory reference, disallow moving
404 // subsequent loads and stores to delay slot.
405 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
406 ForbidMemInstr = true;
410 return hasHazard_(MI);
413 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
417 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
420 if (const PseudoSourceValue *PSV =
421 (*MI.memoperands_begin())->getPseudoValue()) {
422 if (isa<FixedStackPseudoSourceValue>(PSV))
424 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
430 MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
431 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
432 SeenNoObjStore(false) {}
434 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
435 bool HasHazard = false;
436 SmallVector<ValueType, 4> Objs;
438 // Check underlying object list.
439 if (getUnderlyingObjects(MI, Objs)) {
440 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
441 I != Objs.end(); ++I)
442 HasHazard |= updateDefsUses(*I, MI.mayStore());
447 // No underlying objects found.
448 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
449 HasHazard |= MI.mayLoad() || OrigSeenStore;
451 SeenNoObjLoad |= MI.mayLoad();
452 SeenNoObjStore |= MI.mayStore();
457 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
459 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
463 return Defs.count(V) || SeenNoObjStore;
467 getUnderlyingObjects(const MachineInstr &MI,
468 SmallVectorImpl<ValueType> &Objects) const {
469 if (!MI.hasOneMemOperand() ||
470 (!(*MI.memoperands_begin())->getValue() &&
471 !(*MI.memoperands_begin())->getPseudoValue()))
474 if (const PseudoSourceValue *PSV =
475 (*MI.memoperands_begin())->getPseudoValue()) {
476 if (!PSV->isAliased(MFI))
478 Objects.push_back(PSV);
482 const Value *V = (*MI.memoperands_begin())->getValue();
484 SmallVector<Value *, 4> Objs;
485 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
487 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
489 if (!isIdentifiedObject(V))
492 Objects.push_back(*I);
498 // Replace Branch with the compact branch instruction.
499 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB,
500 Iter Branch, DebugLoc DL) {
501 const MipsInstrInfo *TII =
502 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
505 (((unsigned) Branch->getOpcode()) == Mips::BEQ) ? Mips::BEQZC_MM
508 const MCInstrDesc &NewDesc = TII->get(NewOpcode);
509 MachineInstrBuilder MIB = BuildMI(MBB, Branch, DL, NewDesc);
511 MIB.addReg(Branch->getOperand(0).getReg());
512 MIB.addMBB(Branch->getOperand(2).getMBB());
514 Iter tmpIter = Branch;
515 Branch = std::prev(Branch);
521 // Replace Jumps with the compact jump instruction.
522 Iter Filler::replaceWithCompactJump(MachineBasicBlock &MBB,
523 Iter Jump, DebugLoc DL) {
524 const MipsInstrInfo *TII =
525 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
527 const MCInstrDesc &NewDesc = TII->get(Mips::JRC16_MM);
528 MachineInstrBuilder MIB = BuildMI(MBB, Jump, DL, NewDesc);
530 MIB.addReg(Jump->getOperand(0).getReg());
533 Jump = std::prev(Jump);
539 // For given opcode returns opcode of corresponding instruction with short
541 static int getEquivalentCallShort(int Opcode) {
544 return Mips::BGEZALS_MM;
546 return Mips::BLTZALS_MM;
548 return Mips::JALS_MM;
550 return Mips::JALRS_MM;
551 case Mips::JALR16_MM:
552 return Mips::JALRS16_MM;
554 llvm_unreachable("Unexpected call instruction for microMIPS.");
558 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
559 /// We assume there is only one delay slot per delayed instruction.
560 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
561 bool Changed = false;
562 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
563 bool InMicroMipsMode = STI.inMicroMipsMode();
564 const MipsInstrInfo *TII = STI.getInstrInfo();
566 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
567 if (!hasUnoccupiedSlot(&*I))
573 // Delay slot filling is disabled at -O0.
574 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
577 if (searchBackward(MBB, I)) {
579 } else if (I->isTerminator()) {
580 if (searchSuccBBs(MBB, I)) {
583 } else if (searchForward(MBB, I)) {
588 // Get instruction with delay slot.
589 MachineBasicBlock::instr_iterator DSI(I);
591 if (InMicroMipsMode && TII->GetInstSizeInBytes(std::next(DSI)) == 2 &&
593 // If instruction in delay slot is 16b change opcode to
594 // corresponding instruction with short delay slot.
595 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
602 // If instruction is BEQ or BNE with one ZERO register, then instead of
603 // adding NOP replace this instruction with the corresponding compact
604 // branch instruction, i.e. BEQZC or BNEZC.
605 unsigned Opcode = I->getOpcode();
606 if (InMicroMipsMode) {
610 if (((unsigned) I->getOperand(1).getReg()) == Mips::ZERO) {
611 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
616 case Mips::PseudoReturn:
617 case Mips::PseudoIndirectBranch:
618 // For microMIPS the PseudoReturn and PseudoIndirectBranch are allways
619 // expanded to JR_MM, so they can be replaced with JRC16_MM.
620 I = replaceWithCompactJump(MBB, I, I->getDebugLoc());
626 // Bundle the NOP to the instruction with the delay slot.
627 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
628 MIBundleBuilder(MBB, I, std::next(I, 2));
634 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
635 /// slots in Mips MachineFunctions
636 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
637 return new Filler(tm);
640 template<typename IterTy>
641 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
642 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
643 IterTy &Filler) const {
644 for (IterTy I = Begin; I != End; ++I) {
646 if (I->isDebugValue())
649 if (terminateSearch(*I))
652 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
653 "Cannot put calls, returns or branches in delay slot.");
655 if (delayHasHazard(*I, RegDU, IM))
658 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
659 if (STI.isTargetNaCl()) {
660 // In NaCl, instructions that must be masked are forbidden in delay slots.
661 // We only check for loads, stores and SP changes. Calls, returns and
662 // branches are not checked because non-NaCl targets never put them in
665 if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx) &&
666 baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg())) ||
667 I->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
671 bool InMicroMipsMode = STI.inMicroMipsMode();
672 const MipsInstrInfo *TII = STI.getInstrInfo();
673 unsigned Opcode = (*Slot).getOpcode();
674 if (InMicroMipsMode && TII->GetInstSizeInBytes(&(*I)) == 2 &&
675 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
676 Opcode == Mips::PseudoReturn))
686 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
687 if (DisableBackwardSearch)
690 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
691 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
696 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Slot,
700 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
701 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
706 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
707 // Can handle only calls.
708 if (DisableForwardSearch || !Slot->isCall())
711 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
715 RegDU.setCallerSaved(*Slot);
717 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
720 MBB.splice(std::next(Slot), &MBB, Filler);
721 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
726 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
727 if (DisableSuccBBSearch)
730 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
735 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
736 bool HasMultipleSuccs = false;
738 std::unique_ptr<InspectMemInstr> IM;
741 // Iterate over SuccBB's predecessor list.
742 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
743 PE = SuccBB->pred_end(); PI != PE; ++PI)
744 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
747 // Do not allow moving instructions which have unallocatable register operands
748 // across basic block boundaries.
749 RegDU.setUnallocatableRegs(*MBB.getParent());
751 // Only allow moving loads from stack or constants if any of the SuccBB's
752 // predecessors have multiple successors.
753 if (HasMultipleSuccs) {
754 IM.reset(new LoadFromStackOrConst());
756 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
757 IM.reset(new MemDefsUses(MFI));
760 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
764 insertDelayFiller(Filler, BrMap);
765 addLiveInRegs(Filler, *SuccBB);
766 Filler->eraseFromParent();
771 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
775 // Select the successor with the larget edge weight.
776 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
777 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
778 [&](const MachineBasicBlock *Dst0,
779 const MachineBasicBlock *Dst1) {
780 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
782 return S->isLandingPad() ? nullptr : S;
785 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
786 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
787 const MipsInstrInfo *TII =
788 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
789 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
790 SmallVector<MachineInstr*, 2> BranchInstrs;
791 SmallVector<MachineOperand, 2> Cond;
793 MipsInstrInfo::BranchType R =
794 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
796 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
797 return std::make_pair(R, nullptr);
799 if (R != MipsInstrInfo::BT_CondUncond) {
800 if (!hasUnoccupiedSlot(BranchInstrs[0]))
801 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
803 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
805 return std::make_pair(R, BranchInstrs[0]);
808 assert((TrueBB == &Dst) || (FalseBB == &Dst));
810 // Examine the conditional branch. See if its slot is occupied.
811 if (hasUnoccupiedSlot(BranchInstrs[0]))
812 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
814 // If that fails, try the unconditional branch.
815 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
816 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
818 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
821 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
822 RegDefsUses &RegDU, bool &HasMultipleSuccs,
823 BB2BrMap &BrMap) const {
824 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
825 getBranch(Pred, Succ);
827 // Return if either getBranch wasn't able to analyze the branches or there
828 // were no branches with unoccupied slots.
829 if (P.first == MipsInstrInfo::BT_None)
832 if ((P.first != MipsInstrInfo::BT_Uncond) &&
833 (P.first != MipsInstrInfo::BT_NoBranch)) {
834 HasMultipleSuccs = true;
835 RegDU.addLiveOut(Pred, Succ);
838 BrMap[&Pred] = P.second;
842 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
843 InspectMemInstr &IM) const {
844 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
846 HasHazard |= IM.hasHazard(Candidate);
847 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
852 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
853 return (Candidate.isTerminator() || Candidate.isCall() ||
854 Candidate.isPosition() || Candidate.isInlineAsm() ||
855 Candidate.hasUnmodeledSideEffects());