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