1 //===- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler -------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Simple pass to fill delay slots with useful instructions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MCTargetDesc/MipsMCNaCl.h"
14 #include "Mips.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"
45 #include <algorithm>
46 #include <cassert>
47 #include <iterator>
48 #include <memory>
49 #include <utility>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "mips-delay-slot-filler"
54 
55 STATISTIC(FilledSlots, "Number of delay slots filled");
56 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
57                        " are not NOP.");
58 
59 static cl::opt<bool> DisableDelaySlotFiller(
60   "disable-mips-delay-filler",
61   cl::init(false),
62   cl::desc("Fill all delay slots with NOPs."),
63   cl::Hidden);
64 
65 static cl::opt<bool> DisableForwardSearch(
66   "disable-mips-df-forward-search",
67   cl::init(true),
68   cl::desc("Disallow MIPS delay filler to search forward."),
69   cl::Hidden);
70 
71 static cl::opt<bool> DisableSuccBBSearch(
72   "disable-mips-df-succbb-search",
73   cl::init(true),
74   cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
75   cl::Hidden);
76 
77 static cl::opt<bool> DisableBackwardSearch(
78   "disable-mips-df-backward-search",
79   cl::init(false),
80   cl::desc("Disallow MIPS delay filler to search backward."),
81   cl::Hidden);
82 
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.
91 };
92 
93 static cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy(
94     "mips-compact-branches", cl::Optional, cl::init(CB_Optimal),
95     cl::desc("MIPS Specific: Compact branch policy."),
96     cl::values(clEnumValN(CB_Never, "never",
97                           "Do not use compact branches if possible."),
98                clEnumValN(CB_Optimal, "optimal",
99                           "Use compact branches where appropriate (default)."),
100                clEnumValN(CB_Always, "always",
101                           "Always use compact branches if possible.")));
102 
103 namespace {
104 
105   using Iter = MachineBasicBlock::iterator;
106   using ReverseIter = MachineBasicBlock::reverse_iterator;
107   using BB2BrMap = SmallDenseMap<MachineBasicBlock *, MachineInstr *, 2>;
108 
109   class RegDefsUses {
110   public:
111     RegDefsUses(const TargetRegisterInfo &TRI);
112 
113     void init(const MachineInstr &MI);
114 
115     /// This function sets all caller-saved registers in Defs.
116     void setCallerSaved(const MachineInstr &MI);
117 
118     /// This function sets all unallocatable registers in Defs.
119     void setUnallocatableRegs(const MachineFunction &MF);
120 
121     /// Set bits in Uses corresponding to MBB's live-out registers except for
122     /// the registers that are live-in to SuccBB.
123     void addLiveOut(const MachineBasicBlock &MBB,
124                     const MachineBasicBlock &SuccBB);
125 
126     bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
127 
128   private:
129     bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
130                           bool IsDef) const;
131 
132     /// Returns true if Reg or its alias is in RegSet.
133     bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
134 
135     const TargetRegisterInfo &TRI;
136     BitVector Defs, Uses;
137   };
138 
139   /// Base class for inspecting loads and stores.
140   class InspectMemInstr {
141   public:
142     InspectMemInstr(bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
143     virtual ~InspectMemInstr() = default;
144 
145     /// Return true if MI cannot be moved to delay slot.
146     bool hasHazard(const MachineInstr &MI);
147 
148   protected:
149     /// Flags indicating whether loads or stores have been seen.
150     bool OrigSeenLoad = false;
151     bool OrigSeenStore = false;
152     bool SeenLoad = false;
153     bool SeenStore = false;
154 
155     /// Memory instructions are not allowed to move to delay slot if this flag
156     /// is true.
157     bool ForbidMemInstr;
158 
159   private:
160     virtual bool hasHazard_(const MachineInstr &MI) = 0;
161   };
162 
163   /// This subclass rejects any memory instructions.
164   class NoMemInstr : public InspectMemInstr {
165   public:
166     NoMemInstr() : InspectMemInstr(true) {}
167 
168   private:
169     bool hasHazard_(const MachineInstr &MI) override { return true; }
170   };
171 
172   /// This subclass accepts loads from stacks and constant loads.
173   class LoadFromStackOrConst : public InspectMemInstr {
174   public:
175     LoadFromStackOrConst() : InspectMemInstr(false) {}
176 
177   private:
178     bool hasHazard_(const MachineInstr &MI) override;
179   };
180 
181   /// This subclass uses memory dependence information to determine whether a
182   /// memory instruction can be moved to a delay slot.
183   class MemDefsUses : public InspectMemInstr {
184   public:
185     explicit MemDefsUses(const MachineFrameInfo *MFI);
186 
187   private:
188     using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>;
189 
190     bool hasHazard_(const MachineInstr &MI) override;
191 
192     /// Update Defs and Uses. Return true if there exist dependences that
193     /// disqualify the delay slot candidate between V and values in Uses and
194     /// Defs.
195     bool updateDefsUses(ValueType V, bool MayStore);
196 
197     /// Get the list of underlying objects of MI's memory operand.
198     bool getUnderlyingObjects(const MachineInstr &MI,
199                               SmallVectorImpl<ValueType> &Objects) const;
200 
201     const MachineFrameInfo *MFI;
202     SmallPtrSet<ValueType, 4> Uses, Defs;
203 
204     /// Flags indicating whether loads or stores with no underlying objects have
205     /// been seen.
206     bool SeenNoObjLoad = false;
207     bool SeenNoObjStore = false;
208   };
209 
210   class MipsDelaySlotFiller : public MachineFunctionPass {
211   public:
212     MipsDelaySlotFiller() : MachineFunctionPass(ID) {
213       initializeMipsDelaySlotFillerPass(*PassRegistry::getPassRegistry());
214     }
215 
216     StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
217 
218     bool runOnMachineFunction(MachineFunction &F) override {
219       TM = &F.getTarget();
220       bool Changed = false;
221       for (MachineFunction::iterator FI = F.begin(), FE = F.end();
222            FI != FE; ++FI)
223         Changed |= runOnMachineBasicBlock(*FI);
224 
225       // This pass invalidates liveness information when it reorders
226       // instructions to fill delay slot. Without this, -verify-machineinstrs
227       // will fail.
228       if (Changed)
229         F.getRegInfo().invalidateLiveness();
230 
231       return Changed;
232     }
233 
234     MachineFunctionProperties getRequiredProperties() const override {
235       return MachineFunctionProperties().set(
236           MachineFunctionProperties::Property::NoVRegs);
237     }
238 
239     void getAnalysisUsage(AnalysisUsage &AU) const override {
240       AU.addRequired<MachineBranchProbabilityInfo>();
241       MachineFunctionPass::getAnalysisUsage(AU);
242     }
243 
244     static char ID;
245 
246   private:
247     bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
248 
249     Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
250                                   const DebugLoc &DL);
251 
252     /// This function checks if it is valid to move Candidate to the delay slot
253     /// and returns true if it isn't. It also updates memory and register
254     /// dependence information.
255     bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
256                         InspectMemInstr &IM) const;
257 
258     /// This function searches range [Begin, End) for an instruction that can be
259     /// moved to the delay slot. Returns true on success.
260     template<typename IterTy>
261     bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
262                      RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
263                      IterTy &Filler) const;
264 
265     /// This function searches in the backward direction for an instruction that
266     /// can be moved to the delay slot. Returns true on success.
267     bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
268 
269     /// This function searches MBB in the forward direction for an instruction
270     /// that can be moved to the delay slot. Returns true on success.
271     bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
272 
273     /// This function searches one of MBB's successor blocks for an instruction
274     /// that can be moved to the delay slot and inserts clones of the
275     /// instruction into the successor's predecessor blocks.
276     bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
277 
278     /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
279     /// successor block that is not a landing pad.
280     MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
281 
282     /// This function analyzes MBB and returns an instruction with an unoccupied
283     /// slot that branches to Dst.
284     std::pair<MipsInstrInfo::BranchType, MachineInstr *>
285     getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
286 
287     /// Examine Pred and see if it is possible to insert an instruction into
288     /// one of its branches delay slot or its end.
289     bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
290                      RegDefsUses &RegDU, bool &HasMultipleSuccs,
291                      BB2BrMap &BrMap) const;
292 
293     bool terminateSearch(const MachineInstr &Candidate) const;
294 
295     const TargetMachine *TM = nullptr;
296   };
297 
298 } // end anonymous namespace
299 
300 char MipsDelaySlotFiller::ID = 0;
301 
302 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
303   return MI->hasDelaySlot() && !MI->isBundledWithSucc();
304 }
305 
306 INITIALIZE_PASS(MipsDelaySlotFiller, DEBUG_TYPE,
307                 "Fill delay slot for MIPS", false, false)
308 
309 /// This function inserts clones of Filler into predecessor blocks.
310 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
311   MachineFunction *MF = Filler->getParent()->getParent();
312 
313   for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
314     if (I->second) {
315       MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
316       ++UsefulSlots;
317     } else {
318       I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
319     }
320   }
321 }
322 
323 /// This function adds registers Filler defines to MBB's live-in register list.
324 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
325   for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
326     const MachineOperand &MO = Filler->getOperand(I);
327     unsigned R;
328 
329     if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
330       continue;
331 
332 #ifndef NDEBUG
333     const MachineFunction &MF = *MBB.getParent();
334     assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
335            "Shouldn't move an instruction with unallocatable registers across "
336            "basic block boundaries.");
337 #endif
338 
339     if (!MBB.isLiveIn(R))
340       MBB.addLiveIn(R);
341   }
342 }
343 
344 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
345     : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
346 
347 void RegDefsUses::init(const MachineInstr &MI) {
348   // Add all register operands which are explicit and non-variadic.
349   update(MI, 0, MI.getDesc().getNumOperands());
350 
351   // If MI is a call, add RA to Defs to prevent users of RA from going into
352   // delay slot.
353   if (MI.isCall())
354     Defs.set(Mips::RA);
355 
356   // Add all implicit register operands of branch instructions except
357   // register AT.
358   if (MI.isBranch()) {
359     update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
360     Defs.reset(Mips::AT);
361   }
362 }
363 
364 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
365   assert(MI.isCall());
366 
367   // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
368   // the delay slot. The reason is that RA/RA_64 must not be changed
369   // in the delay slot so that the callee can return to the caller.
370   if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
371     Defs.set(Mips::RA);
372     Defs.set(Mips::RA_64);
373   }
374 
375   // If MI is a call, add all caller-saved registers to Defs.
376   BitVector CallerSavedRegs(TRI.getNumRegs(), true);
377 
378   CallerSavedRegs.reset(Mips::ZERO);
379   CallerSavedRegs.reset(Mips::ZERO_64);
380 
381   for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
382        *R; ++R)
383     for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
384       CallerSavedRegs.reset(*AI);
385 
386   Defs |= CallerSavedRegs;
387 }
388 
389 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
390   BitVector AllocSet = TRI.getAllocatableSet(MF);
391 
392   for (unsigned R : AllocSet.set_bits())
393     for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
394       AllocSet.set(*AI);
395 
396   AllocSet.set(Mips::ZERO);
397   AllocSet.set(Mips::ZERO_64);
398 
399   Defs |= AllocSet.flip();
400 }
401 
402 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
403                              const MachineBasicBlock &SuccBB) {
404   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
405        SE = MBB.succ_end(); SI != SE; ++SI)
406     if (*SI != &SuccBB)
407       for (const auto &LI : (*SI)->liveins())
408         Uses.set(LI.PhysReg);
409 }
410 
411 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
412   BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
413   bool HasHazard = false;
414 
415   for (unsigned I = Begin; I != End; ++I) {
416     const MachineOperand &MO = MI.getOperand(I);
417 
418     if (MO.isReg() && MO.getReg()) {
419       if (checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef())) {
420         LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found register hazard for operand "
421                           << I << ": ";
422                    MO.dump());
423         HasHazard = true;
424       }
425     }
426   }
427 
428   Defs |= NewDefs;
429   Uses |= NewUses;
430 
431   return HasHazard;
432 }
433 
434 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
435                                    unsigned Reg, bool IsDef) const {
436   if (IsDef) {
437     NewDefs.set(Reg);
438     // check whether Reg has already been defined or used.
439     return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
440   }
441 
442   NewUses.set(Reg);
443   // check whether Reg has already been defined.
444   return isRegInSet(Defs, Reg);
445 }
446 
447 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
448   // Check Reg and all aliased Registers.
449   for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
450     if (RegSet.test(*AI))
451       return true;
452   return false;
453 }
454 
455 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
456   if (!MI.mayStore() && !MI.mayLoad())
457     return false;
458 
459   if (ForbidMemInstr)
460     return true;
461 
462   OrigSeenLoad = SeenLoad;
463   OrigSeenStore = SeenStore;
464   SeenLoad |= MI.mayLoad();
465   SeenStore |= MI.mayStore();
466 
467   // If MI is an ordered or volatile memory reference, disallow moving
468   // subsequent loads and stores to delay slot.
469   if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
470     ForbidMemInstr = true;
471     return true;
472   }
473 
474   return hasHazard_(MI);
475 }
476 
477 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
478   if (MI.mayStore())
479     return true;
480 
481   if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
482     return true;
483 
484   if (const PseudoSourceValue *PSV =
485       (*MI.memoperands_begin())->getPseudoValue()) {
486     if (isa<FixedStackPseudoSourceValue>(PSV))
487       return false;
488     return !PSV->isConstant(nullptr) && !PSV->isStack();
489   }
490 
491   return true;
492 }
493 
494 MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
495     : InspectMemInstr(false), MFI(MFI_) {}
496 
497 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
498   bool HasHazard = false;
499 
500   // Check underlying object list.
501   SmallVector<ValueType, 4> Objs;
502   if (getUnderlyingObjects(MI, Objs)) {
503     for (ValueType VT : Objs)
504       HasHazard |= updateDefsUses(VT, MI.mayStore());
505     return HasHazard;
506   }
507 
508   // No underlying objects found.
509   HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
510   HasHazard |= MI.mayLoad() || OrigSeenStore;
511 
512   SeenNoObjLoad |= MI.mayLoad();
513   SeenNoObjStore |= MI.mayStore();
514 
515   return HasHazard;
516 }
517 
518 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
519   if (MayStore)
520     return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
521            SeenNoObjLoad;
522 
523   Uses.insert(V);
524   return Defs.count(V) || SeenNoObjStore;
525 }
526 
527 bool MemDefsUses::
528 getUnderlyingObjects(const MachineInstr &MI,
529                      SmallVectorImpl<ValueType> &Objects) const {
530   if (!MI.hasOneMemOperand())
531     return false;
532 
533   auto & MMO = **MI.memoperands_begin();
534 
535   if (const PseudoSourceValue *PSV = MMO.getPseudoValue()) {
536     if (!PSV->isAliased(MFI))
537       return false;
538     Objects.push_back(PSV);
539     return true;
540   }
541 
542   if (const Value *V = MMO.getValue()) {
543     SmallVector<const Value *, 4> Objs;
544     ::getUnderlyingObjects(V, Objs);
545 
546     for (const Value *UValue : Objs) {
547       if (!isIdentifiedObject(V))
548         return false;
549 
550       Objects.push_back(UValue);
551     }
552     return true;
553   }
554 
555   return false;
556 }
557 
558 // Replace Branch with the compact branch instruction.
559 Iter MipsDelaySlotFiller::replaceWithCompactBranch(MachineBasicBlock &MBB,
560                                                    Iter Branch,
561                                                    const DebugLoc &DL) {
562   const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
563   const MipsInstrInfo *TII = STI.getInstrInfo();
564 
565   unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
566   Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
567 
568   std::next(Branch)->eraseFromParent();
569   return Branch;
570 }
571 
572 // For given opcode returns opcode of corresponding instruction with short
573 // delay slot.
574 // For the pseudo TAILCALL*_MM instructions return the short delay slot
575 // form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
576 // that is too short to make use of for tail calls.
577 static int getEquivalentCallShort(int Opcode) {
578   switch (Opcode) {
579   case Mips::BGEZAL:
580     return Mips::BGEZALS_MM;
581   case Mips::BLTZAL:
582     return Mips::BLTZALS_MM;
583   case Mips::JAL:
584   case Mips::JAL_MM:
585     return Mips::JALS_MM;
586   case Mips::JALR:
587     return Mips::JALRS_MM;
588   case Mips::JALR16_MM:
589     return Mips::JALRS16_MM;
590   case Mips::TAILCALL_MM:
591     llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
592   case Mips::TAILCALLREG:
593     return Mips::JR16_MM;
594   default:
595     llvm_unreachable("Unexpected call instruction for microMIPS.");
596   }
597 }
598 
599 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
600 /// We assume there is only one delay slot per delayed instruction.
601 bool MipsDelaySlotFiller::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
602   bool Changed = false;
603   const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
604   bool InMicroMipsMode = STI.inMicroMipsMode();
605   const MipsInstrInfo *TII = STI.getInstrInfo();
606 
607   for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
608     if (!hasUnoccupiedSlot(&*I))
609       continue;
610 
611     // Delay slot filling is disabled at -O0, or in microMIPS32R6.
612     if (!DisableDelaySlotFiller && (TM->getOptLevel() != CodeGenOpt::None) &&
613         !(InMicroMipsMode && STI.hasMips32r6())) {
614 
615       bool Filled = false;
616 
617       if (MipsCompactBranchPolicy.getValue() != CB_Always ||
618            !TII->getEquivalentCompactForm(I)) {
619         if (searchBackward(MBB, *I)) {
620           LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot"
621                                           " in backwards search.\n");
622           Filled = true;
623         } else if (I->isTerminator()) {
624           if (searchSuccBBs(MBB, I)) {
625             Filled = true;
626             LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot"
627                                             " in successor BB search.\n");
628           }
629         } else if (searchForward(MBB, I)) {
630           LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot"
631                                           " in forwards search.\n");
632           Filled = true;
633         }
634       }
635 
636       if (Filled) {
637         // Get instruction with delay slot.
638         MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
639 
640         if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
641             DSI->isCall()) {
642           // If instruction in delay slot is 16b change opcode to
643           // corresponding instruction with short delay slot.
644 
645           // TODO: Implement an instruction mapping table of 16bit opcodes to
646           // 32bit opcodes so that an instruction can be expanded. This would
647           // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
648           // TODO: Permit b16 when branching backwards to the same function
649           // if it is in range.
650           DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
651         }
652         ++FilledSlots;
653         Changed = true;
654         continue;
655       }
656     }
657 
658     // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
659     // instead of adding NOP replace this instruction with the corresponding
660     // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
661     // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
662     // be replaced with JRC16_MM.
663 
664     // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
665     // form of the CTI. For indirect jumps this will not require inserting a
666     // NOP and for branches will hopefully avoid requiring a NOP.
667     if ((InMicroMipsMode ||
668          (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
669         TII->getEquivalentCompactForm(I)) {
670       I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
671       Changed = true;
672       continue;
673     }
674 
675     // Bundle the NOP to the instruction with the delay slot.
676     LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": could not fill delay slot for ";
677                I->dump());
678     BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
679     MIBundleBuilder(MBB, I, std::next(I, 2));
680     ++FilledSlots;
681     Changed = true;
682   }
683 
684   return Changed;
685 }
686 
687 template <typename IterTy>
688 bool MipsDelaySlotFiller::searchRange(MachineBasicBlock &MBB, IterTy Begin,
689                                       IterTy End, RegDefsUses &RegDU,
690                                       InspectMemInstr &IM, Iter Slot,
691                                       IterTy &Filler) const {
692   for (IterTy I = Begin; I != End;) {
693     IterTy CurrI = I;
694     ++I;
695     LLVM_DEBUG(dbgs() << DEBUG_TYPE ": checking instruction: "; CurrI->dump());
696     // skip debug value
697     if (CurrI->isDebugInstr()) {
698       LLVM_DEBUG(dbgs() << DEBUG_TYPE ": ignoring debug instruction: ";
699                  CurrI->dump());
700       continue;
701     }
702 
703     if (CurrI->isBundle()) {
704       LLVM_DEBUG(dbgs() << DEBUG_TYPE ": ignoring BUNDLE instruction: ";
705                  CurrI->dump());
706       // However, we still need to update the register def-use information.
707       RegDU.update(*CurrI, 0, CurrI->getNumOperands());
708       continue;
709     }
710 
711     if (terminateSearch(*CurrI)) {
712       LLVM_DEBUG(dbgs() << DEBUG_TYPE ": should terminate search: ";
713                  CurrI->dump());
714       break;
715     }
716 
717     assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
718            "Cannot put calls, returns or branches in delay slot.");
719 
720     if (CurrI->isKill()) {
721       CurrI->eraseFromParent();
722       continue;
723     }
724 
725     if (delayHasHazard(*CurrI, RegDU, IM))
726       continue;
727 
728     const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
729     if (STI.isTargetNaCl()) {
730       // In NaCl, instructions that must be masked are forbidden in delay slots.
731       // We only check for loads, stores and SP changes.  Calls, returns and
732       // branches are not checked because non-NaCl targets never put them in
733       // delay slots.
734       unsigned AddrIdx;
735       if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
736            baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
737           CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
738         continue;
739     }
740 
741     bool InMicroMipsMode = STI.inMicroMipsMode();
742     const MipsInstrInfo *TII = STI.getInstrInfo();
743     unsigned Opcode = (*Slot).getOpcode();
744     // This is complicated by the tail call optimization. For non-PIC code
745     // there is only a 32bit sized unconditional branch which can be assumed
746     // to be able to reach the target. b16 only has a range of +/- 1 KB.
747     // It's entirely possible that the target function is reachable with b16
748     // but we don't have enough information to make that decision.
749      if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
750         (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
751          Opcode == Mips::PseudoIndirectBranch_MM ||
752          Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
753       continue;
754      // Instructions LWP/SWP and MOVEP should not be in a delay slot as that
755      // results in unpredictable behaviour
756      if (InMicroMipsMode && (Opcode == Mips::LWP_MM || Opcode == Mips::SWP_MM ||
757                              Opcode == Mips::MOVEP_MM))
758        continue;
759 
760     Filler = CurrI;
761     LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot: ";
762                CurrI->dump());
763 
764     return true;
765   }
766 
767   return false;
768 }
769 
770 bool MipsDelaySlotFiller::searchBackward(MachineBasicBlock &MBB,
771                                          MachineInstr &Slot) const {
772   if (DisableBackwardSearch)
773     return false;
774 
775   auto *Fn = MBB.getParent();
776   RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
777   MemDefsUses MemDU(&Fn->getFrameInfo());
778   ReverseIter Filler;
779 
780   RegDU.init(Slot);
781 
782   MachineBasicBlock::iterator SlotI = Slot;
783   if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
784                    Filler)) {
785     LLVM_DEBUG(dbgs() << DEBUG_TYPE ": could not find instruction for delay "
786                                     "slot using backwards search.\n");
787     return false;
788   }
789 
790   MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
791   MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
792   ++UsefulSlots;
793   return true;
794 }
795 
796 bool MipsDelaySlotFiller::searchForward(MachineBasicBlock &MBB,
797                                         Iter Slot) const {
798   // Can handle only calls.
799   if (DisableForwardSearch || !Slot->isCall())
800     return false;
801 
802   RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
803   NoMemInstr NM;
804   Iter Filler;
805 
806   RegDU.setCallerSaved(*Slot);
807 
808   if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler)) {
809     LLVM_DEBUG(dbgs() << DEBUG_TYPE ": could not find instruction for delay "
810                                     "slot using forwards search.\n");
811     return false;
812   }
813 
814   MBB.splice(std::next(Slot), &MBB, Filler);
815   MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
816   ++UsefulSlots;
817   return true;
818 }
819 
820 bool MipsDelaySlotFiller::searchSuccBBs(MachineBasicBlock &MBB,
821                                         Iter Slot) const {
822   if (DisableSuccBBSearch)
823     return false;
824 
825   MachineBasicBlock *SuccBB = selectSuccBB(MBB);
826 
827   if (!SuccBB)
828     return false;
829 
830   RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
831   bool HasMultipleSuccs = false;
832   BB2BrMap BrMap;
833   std::unique_ptr<InspectMemInstr> IM;
834   Iter Filler;
835   auto *Fn = MBB.getParent();
836 
837   // Iterate over SuccBB's predecessor list.
838   for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
839        PE = SuccBB->pred_end(); PI != PE; ++PI)
840     if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
841       return false;
842 
843   // Do not allow moving instructions which have unallocatable register operands
844   // across basic block boundaries.
845   RegDU.setUnallocatableRegs(*Fn);
846 
847   // Only allow moving loads from stack or constants if any of the SuccBB's
848   // predecessors have multiple successors.
849   if (HasMultipleSuccs) {
850     IM.reset(new LoadFromStackOrConst());
851   } else {
852     const MachineFrameInfo &MFI = Fn->getFrameInfo();
853     IM.reset(new MemDefsUses(&MFI));
854   }
855 
856   if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
857                    Filler))
858     return false;
859 
860   insertDelayFiller(Filler, BrMap);
861   addLiveInRegs(Filler, *SuccBB);
862   Filler->eraseFromParent();
863 
864   return true;
865 }
866 
867 MachineBasicBlock *
868 MipsDelaySlotFiller::selectSuccBB(MachineBasicBlock &B) const {
869   if (B.succ_empty())
870     return nullptr;
871 
872   // Select the successor with the larget edge weight.
873   auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
874   MachineBasicBlock *S = *std::max_element(
875       B.succ_begin(), B.succ_end(),
876       [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
877         return Prob.getEdgeProbability(&B, Dst0) <
878                Prob.getEdgeProbability(&B, Dst1);
879       });
880   return S->isEHPad() ? nullptr : S;
881 }
882 
883 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
884 MipsDelaySlotFiller::getBranch(MachineBasicBlock &MBB,
885                                const MachineBasicBlock &Dst) const {
886   const MipsInstrInfo *TII =
887       MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
888   MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
889   SmallVector<MachineInstr*, 2> BranchInstrs;
890   SmallVector<MachineOperand, 2> Cond;
891 
892   MipsInstrInfo::BranchType R =
893       TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
894 
895   if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
896     return std::make_pair(R, nullptr);
897 
898   if (R != MipsInstrInfo::BT_CondUncond) {
899     if (!hasUnoccupiedSlot(BranchInstrs[0]))
900       return std::make_pair(MipsInstrInfo::BT_None, nullptr);
901 
902     assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
903 
904     return std::make_pair(R, BranchInstrs[0]);
905   }
906 
907   assert((TrueBB == &Dst) || (FalseBB == &Dst));
908 
909   // Examine the conditional branch. See if its slot is occupied.
910   if (hasUnoccupiedSlot(BranchInstrs[0]))
911     return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
912 
913   // If that fails, try the unconditional branch.
914   if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
915     return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
916 
917   return std::make_pair(MipsInstrInfo::BT_None, nullptr);
918 }
919 
920 bool MipsDelaySlotFiller::examinePred(MachineBasicBlock &Pred,
921                                       const MachineBasicBlock &Succ,
922                                       RegDefsUses &RegDU,
923                                       bool &HasMultipleSuccs,
924                                       BB2BrMap &BrMap) const {
925   std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
926       getBranch(Pred, Succ);
927 
928   // Return if either getBranch wasn't able to analyze the branches or there
929   // were no branches with unoccupied slots.
930   if (P.first == MipsInstrInfo::BT_None)
931     return false;
932 
933   if ((P.first != MipsInstrInfo::BT_Uncond) &&
934       (P.first != MipsInstrInfo::BT_NoBranch)) {
935     HasMultipleSuccs = true;
936     RegDU.addLiveOut(Pred, Succ);
937   }
938 
939   BrMap[&Pred] = P.second;
940   return true;
941 }
942 
943 bool MipsDelaySlotFiller::delayHasHazard(const MachineInstr &Candidate,
944                                          RegDefsUses &RegDU,
945                                          InspectMemInstr &IM) const {
946   assert(!Candidate.isKill() &&
947          "KILL instructions should have been eliminated at this point.");
948 
949   bool HasHazard = Candidate.isImplicitDef();
950 
951   HasHazard |= IM.hasHazard(Candidate);
952   HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
953 
954   return HasHazard;
955 }
956 
957 bool MipsDelaySlotFiller::terminateSearch(const MachineInstr &Candidate) const {
958   return (Candidate.isTerminator() || Candidate.isCall() ||
959           Candidate.isPosition() || Candidate.isInlineAsm() ||
960           Candidate.hasUnmodeledSideEffects());
961 }
962 
963 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
964 /// slots in Mips MachineFunctions
965 FunctionPass *llvm::createMipsDelaySlotFillerPass() {
966   return new MipsDelaySlotFiller();
967 }
968