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