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 #define DEBUG_TYPE "delay-slot-filler"
17 #include "MipsInstrInfo.h"
18 #include "MipsTargetMachine.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.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 STATISTIC(FilledSlots, "Number of delay slots filled");
36 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
39 static cl::opt<bool> DisableDelaySlotFiller(
40 "disable-mips-delay-filler",
42 cl::desc("Fill all delay slots with NOPs."),
45 static cl::opt<bool> DisableForwardSearch(
46 "disable-mips-df-forward-search",
48 cl::desc("Disallow MIPS delay filler to search forward."),
51 static cl::opt<bool> DisableSuccBBSearch(
52 "disable-mips-df-succbb-search",
54 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
57 static cl::opt<bool> DisableBackwardSearch(
58 "disable-mips-df-backward-search",
60 cl::desc("Disallow MIPS delay filler to search backward."),
64 typedef MachineBasicBlock::iterator Iter;
65 typedef MachineBasicBlock::reverse_iterator ReverseIter;
66 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
70 RegDefsUses(TargetMachine &TM);
71 void init(const MachineInstr &MI);
73 /// This function sets all caller-saved registers in Defs.
74 void setCallerSaved(const MachineInstr &MI);
76 /// This function sets all unallocatable registers in Defs.
77 void setUnallocatableRegs(const MachineFunction &MF);
79 /// Set bits in Uses corresponding to MBB's live-out registers except for
80 /// the registers that are live-in to SuccBB.
81 void addLiveOut(const MachineBasicBlock &MBB,
82 const MachineBasicBlock &SuccBB);
84 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
87 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
90 /// Returns true if Reg or its alias is in RegSet.
91 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
93 const TargetRegisterInfo &TRI;
97 /// Base class for inspecting loads and stores.
98 class InspectMemInstr {
100 InspectMemInstr(bool ForbidMemInstr_)
101 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
102 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
104 /// Return true if MI cannot be moved to delay slot.
105 bool hasHazard(const MachineInstr &MI);
107 virtual ~InspectMemInstr() {}
110 /// Flags indicating whether loads or stores have been seen.
111 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
113 /// Memory instructions are not allowed to move to delay slot if this flag
118 virtual bool hasHazard_(const MachineInstr &MI) = 0;
121 /// This subclass rejects any memory instructions.
122 class NoMemInstr : public InspectMemInstr {
124 NoMemInstr() : InspectMemInstr(true) {}
126 virtual bool hasHazard_(const MachineInstr &MI) { return true; }
129 /// This subclass accepts loads from stacks and constant loads.
130 class LoadFromStackOrConst : public InspectMemInstr {
132 LoadFromStackOrConst() : InspectMemInstr(false) {}
134 virtual bool hasHazard_(const MachineInstr &MI);
137 /// This subclass uses memory dependence information to determine whether a
138 /// memory instruction can be moved to a delay slot.
139 class MemDefsUses : public InspectMemInstr {
141 MemDefsUses(const MachineFrameInfo *MFI);
144 virtual bool hasHazard_(const MachineInstr &MI);
146 /// Update Defs and Uses. Return true if there exist dependences that
147 /// disqualify the delay slot candidate between V and values in Uses and
149 bool updateDefsUses(const Value *V, bool MayStore);
151 /// Get the list of underlying objects of MI's memory operand.
152 bool getUnderlyingObjects(const MachineInstr &MI,
153 SmallVectorImpl<const Value *> &Objects) const;
155 const MachineFrameInfo *MFI;
156 SmallPtrSet<const Value*, 4> Uses, Defs;
158 /// Flags indicating whether loads or stores with no underlying objects have
160 bool SeenNoObjLoad, SeenNoObjStore;
163 class Filler : public MachineFunctionPass {
165 Filler(TargetMachine &tm)
166 : MachineFunctionPass(ID), TM(tm) { }
168 virtual const char *getPassName() const {
169 return "Mips Delay Slot Filler";
172 bool runOnMachineFunction(MachineFunction &F) {
173 bool Changed = false;
174 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
176 Changed |= runOnMachineBasicBlock(*FI);
180 void getAnalysisUsage(AnalysisUsage &AU) const {
181 AU.addRequired<MachineBranchProbabilityInfo>();
182 MachineFunctionPass::getAnalysisUsage(AU);
186 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
188 /// This function checks if it is valid to move Candidate to the delay slot
189 /// and returns true if it isn't. It also updates memory and register
190 /// dependence information.
191 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
192 InspectMemInstr &IM) const;
194 /// This function searches range [Begin, End) for an instruction that can be
195 /// moved to the delay slot. Returns true on success.
196 template<typename IterTy>
197 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
198 RegDefsUses &RegDU, InspectMemInstr &IM,
199 IterTy &Filler) const;
201 /// This function searches in the backward direction for an instruction that
202 /// can be moved to the delay slot. Returns true on success.
203 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
205 /// This function searches MBB in the forward direction for an instruction
206 /// that can be moved to the delay slot. Returns true on success.
207 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
209 /// This function searches one of MBB's successor blocks for an instruction
210 /// that can be moved to the delay slot and inserts clones of the
211 /// instruction into the successor's predecessor blocks.
212 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
214 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
215 /// successor block that is not a landing pad.
216 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
218 /// This function analyzes MBB and returns an instruction with an unoccupied
219 /// slot that branches to Dst.
220 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
221 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
223 /// Examine Pred and see if it is possible to insert an instruction into
224 /// one of its branches delay slot or its end.
225 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
226 RegDefsUses &RegDU, bool &HasMultipleSuccs,
227 BB2BrMap &BrMap) const;
229 bool terminateSearch(const MachineInstr &Candidate) const;
236 } // end of anonymous namespace
238 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
239 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
242 /// This function inserts clones of Filler into predecessor blocks.
243 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
244 MachineFunction *MF = Filler->getParent()->getParent();
246 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
248 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
251 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
256 /// This function adds registers Filler defines to MBB's live-in register list.
257 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
258 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
259 const MachineOperand &MO = Filler->getOperand(I);
262 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
266 const MachineFunction &MF = *MBB.getParent();
267 assert(MF.getTarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
268 "Shouldn't move an instruction with unallocatable registers across "
269 "basic block boundaries.");
272 if (!MBB.isLiveIn(R))
277 RegDefsUses::RegDefsUses(TargetMachine &TM)
278 : TRI(*TM.getRegisterInfo()), Defs(TRI.getNumRegs(), false),
279 Uses(TRI.getNumRegs(), false) {}
281 void RegDefsUses::init(const MachineInstr &MI) {
282 // Add all register operands which are explicit and non-variadic.
283 update(MI, 0, MI.getDesc().getNumOperands());
285 // If MI is a call, add RA to Defs to prevent users of RA from going into
290 // Add all implicit register operands of branch instructions except
293 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
294 Defs.reset(Mips::AT);
298 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
301 // If MI is a call, add all caller-saved registers to Defs.
302 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
304 CallerSavedRegs.reset(Mips::ZERO);
305 CallerSavedRegs.reset(Mips::ZERO_64);
307 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
308 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
309 CallerSavedRegs.reset(*AI);
311 Defs |= CallerSavedRegs;
314 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
315 BitVector AllocSet = TRI.getAllocatableSet(MF);
317 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
318 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
321 AllocSet.set(Mips::ZERO);
322 AllocSet.set(Mips::ZERO_64);
324 Defs |= AllocSet.flip();
327 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
328 const MachineBasicBlock &SuccBB) {
329 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
330 SE = MBB.succ_end(); SI != SE; ++SI)
332 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
333 LE = (*SI)->livein_end(); LI != LE; ++LI)
337 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
338 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
339 bool HasHazard = false;
341 for (unsigned I = Begin; I != End; ++I) {
342 const MachineOperand &MO = MI.getOperand(I);
344 if (MO.isReg() && MO.getReg())
345 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
354 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
355 unsigned Reg, bool IsDef) const {
358 // check whether Reg has already been defined or used.
359 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
363 // check whether Reg has already been defined.
364 return isRegInSet(Defs, Reg);
367 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
368 // Check Reg and all aliased Registers.
369 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
370 if (RegSet.test(*AI))
375 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
376 if (!MI.mayStore() && !MI.mayLoad())
382 OrigSeenLoad = SeenLoad;
383 OrigSeenStore = SeenStore;
384 SeenLoad |= MI.mayLoad();
385 SeenStore |= MI.mayStore();
387 // If MI is an ordered or volatile memory reference, disallow moving
388 // subsequent loads and stores to delay slot.
389 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
390 ForbidMemInstr = true;
394 return hasHazard_(MI);
397 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
401 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getValue())
404 const Value *V = (*MI.memoperands_begin())->getValue();
406 if (isa<FixedStackPseudoSourceValue>(V))
409 if (const PseudoSourceValue *PSV = dyn_cast<const PseudoSourceValue>(V))
410 return !PSV->isConstant(0) && V != PseudoSourceValue::getStack();
415 MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
416 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
417 SeenNoObjStore(false) {}
419 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
420 bool HasHazard = false;
421 SmallVector<const Value *, 4> Objs;
423 // Check underlying object list.
424 if (getUnderlyingObjects(MI, Objs)) {
425 for (SmallVectorImpl<const Value *>::const_iterator I = Objs.begin();
426 I != Objs.end(); ++I)
427 HasHazard |= updateDefsUses(*I, MI.mayStore());
432 // No underlying objects found.
433 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
434 HasHazard |= MI.mayLoad() || OrigSeenStore;
436 SeenNoObjLoad |= MI.mayLoad();
437 SeenNoObjStore |= MI.mayStore();
442 bool MemDefsUses::updateDefsUses(const Value *V, bool MayStore) {
444 return !Defs.insert(V) || Uses.count(V) || SeenNoObjStore || SeenNoObjLoad;
447 return Defs.count(V) || SeenNoObjStore;
451 getUnderlyingObjects(const MachineInstr &MI,
452 SmallVectorImpl<const Value *> &Objects) const {
453 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getValue())
456 const Value *V = (*MI.memoperands_begin())->getValue();
458 SmallVector<Value *, 4> Objs;
459 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
461 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
463 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(*I)) {
464 if (PSV->isAliased(MFI))
466 } else if (!isIdentifiedObject(V))
469 Objects.push_back(*I);
475 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
476 /// We assume there is only one delay slot per delayed instruction.
477 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
478 bool Changed = false;
480 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
481 if (!hasUnoccupiedSlot(&*I))
487 // Delay slot filling is disabled at -O0.
488 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
489 if (searchBackward(MBB, I))
492 if (I->isTerminator()) {
493 if (searchSuccBBs(MBB, I))
495 } else if (searchForward(MBB, I)) {
500 // Bundle the NOP to the instruction with the delay slot.
501 const MipsInstrInfo *TII =
502 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
503 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
504 MIBundleBuilder(MBB, I, std::next(I, 2));
510 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
511 /// slots in Mips MachineFunctions
512 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
513 return new Filler(tm);
516 template<typename IterTy>
517 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
518 RegDefsUses &RegDU, InspectMemInstr& IM,
519 IterTy &Filler) const {
520 for (IterTy I = Begin; I != End; ++I) {
522 if (I->isDebugValue())
525 if (terminateSearch(*I))
528 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
529 "Cannot put calls, returns or branches in delay slot.");
531 if (delayHasHazard(*I, RegDU, IM))
541 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
542 if (DisableBackwardSearch)
545 RegDefsUses RegDU(TM);
546 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
551 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler))
554 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
555 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
560 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
561 // Can handle only calls.
562 if (DisableForwardSearch || !Slot->isCall())
565 RegDefsUses RegDU(TM);
569 RegDU.setCallerSaved(*Slot);
571 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler))
574 MBB.splice(std::next(Slot), &MBB, Filler);
575 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
580 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
581 if (DisableSuccBBSearch)
584 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
589 RegDefsUses RegDU(TM);
590 bool HasMultipleSuccs = false;
592 OwningPtr<InspectMemInstr> IM;
595 // Iterate over SuccBB's predecessor list.
596 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
597 PE = SuccBB->pred_end(); PI != PE; ++PI)
598 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
601 // Do not allow moving instructions which have unallocatable register operands
602 // across basic block boundaries.
603 RegDU.setUnallocatableRegs(*MBB.getParent());
605 // Only allow moving loads from stack or constants if any of the SuccBB's
606 // predecessors have multiple successors.
607 if (HasMultipleSuccs) {
608 IM.reset(new LoadFromStackOrConst());
610 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
611 IM.reset(new MemDefsUses(MFI));
614 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler))
617 insertDelayFiller(Filler, BrMap);
618 addLiveInRegs(Filler, *SuccBB);
619 Filler->eraseFromParent();
624 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
628 // Select the successor with the larget edge weight.
629 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
630 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
631 [&](const MachineBasicBlock *Dst0,
632 const MachineBasicBlock *Dst1) {
633 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
635 return S->isLandingPad() ? NULL : S;
638 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
639 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
640 const MipsInstrInfo *TII =
641 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
642 MachineBasicBlock *TrueBB = 0, *FalseBB = 0;
643 SmallVector<MachineInstr*, 2> BranchInstrs;
644 SmallVector<MachineOperand, 2> Cond;
646 MipsInstrInfo::BranchType R =
647 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
649 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
650 return std::make_pair(R, (MachineInstr*)NULL);
652 if (R != MipsInstrInfo::BT_CondUncond) {
653 if (!hasUnoccupiedSlot(BranchInstrs[0]))
654 return std::make_pair(MipsInstrInfo::BT_None, (MachineInstr*)NULL);
656 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
658 return std::make_pair(R, BranchInstrs[0]);
661 assert((TrueBB == &Dst) || (FalseBB == &Dst));
663 // Examine the conditional branch. See if its slot is occupied.
664 if (hasUnoccupiedSlot(BranchInstrs[0]))
665 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
667 // If that fails, try the unconditional branch.
668 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
669 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
671 return std::make_pair(MipsInstrInfo::BT_None, (MachineInstr*)NULL);
674 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
675 RegDefsUses &RegDU, bool &HasMultipleSuccs,
676 BB2BrMap &BrMap) const {
677 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
678 getBranch(Pred, Succ);
680 // Return if either getBranch wasn't able to analyze the branches or there
681 // were no branches with unoccupied slots.
682 if (P.first == MipsInstrInfo::BT_None)
685 if ((P.first != MipsInstrInfo::BT_Uncond) &&
686 (P.first != MipsInstrInfo::BT_NoBranch)) {
687 HasMultipleSuccs = true;
688 RegDU.addLiveOut(Pred, Succ);
691 BrMap[&Pred] = P.second;
695 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
696 InspectMemInstr &IM) const {
697 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
699 HasHazard |= IM.hasHazard(Candidate);
700 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
705 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
706 return (Candidate.isTerminator() || Candidate.isCall() ||
707 Candidate.isPosition() || Candidate.isInlineAsm() ||
708 Candidate.hasUnmodeledSideEffects());