OSDN Git Service

Update aosp/master LLVM for rebase to r230699.
[android-x86/external-llvm.git] / lib / Target / Mips / MipsDelaySlotFiller.cpp
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 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
162     /// Flags indicating whether loads or stores with no underlying objects have
163     /// been seen.
164     bool SeenNoObjLoad, SeenNoObjStore;
165   };
166
167   class Filler : public MachineFunctionPass {
168   public:
169     Filler(TargetMachine &tm)
170       : MachineFunctionPass(ID), TM(tm) { }
171
172     const char *getPassName() const override {
173       return "Mips Delay Slot Filler";
174     }
175
176     bool runOnMachineFunction(MachineFunction &F) override {
177       bool Changed = false;
178       for (MachineFunction::iterator FI = F.begin(), FE = F.end();
179            FI != FE; ++FI)
180         Changed |= runOnMachineBasicBlock(*FI);
181
182       // This pass invalidates liveness information when it reorders
183       // instructions to fill delay slot. Without this, -verify-machineinstrs
184       // will fail.
185       if (Changed)
186         F.getRegInfo().invalidateLiveness();
187
188       return Changed;
189     }
190
191     void getAnalysisUsage(AnalysisUsage &AU) const override {
192       AU.addRequired<MachineBranchProbabilityInfo>();
193       MachineFunctionPass::getAnalysisUsage(AU);
194     }
195
196   private:
197     bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
198
199     Iter replaceWithCompactBranch(MachineBasicBlock &MBB,
200                                   Iter Branch, DebugLoc DL);
201
202     Iter replaceWithCompactJump(MachineBasicBlock &MBB,
203                                 Iter Jump, DebugLoc DL);
204
205     /// This function checks if it is valid to move Candidate to the delay slot
206     /// and returns true if it isn't. It also updates memory and register
207     /// dependence information.
208     bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
209                         InspectMemInstr &IM) const;
210
211     /// This function searches range [Begin, End) for an instruction that can be
212     /// moved to the delay slot. Returns true on success.
213     template<typename IterTy>
214     bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
215                      RegDefsUses &RegDU, InspectMemInstr &IM,
216                      IterTy &Filler, Iter Slot) const;
217
218     /// This function searches in the backward direction for an instruction that
219     /// can be moved to the delay slot. Returns true on success.
220     bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
221
222     /// This function searches MBB in the forward direction for an instruction
223     /// that can be moved to the delay slot. Returns true on success.
224     bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
225
226     /// This function searches one of MBB's successor blocks for an instruction
227     /// that can be moved to the delay slot and inserts clones of the
228     /// instruction into the successor's predecessor blocks.
229     bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
230
231     /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
232     /// successor block that is not a landing pad.
233     MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
234
235     /// This function analyzes MBB and returns an instruction with an unoccupied
236     /// slot that branches to Dst.
237     std::pair<MipsInstrInfo::BranchType, MachineInstr *>
238     getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
239
240     /// Examine Pred and see if it is possible to insert an instruction into
241     /// one of its branches delay slot or its end.
242     bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
243                      RegDefsUses &RegDU, bool &HasMultipleSuccs,
244                      BB2BrMap &BrMap) const;
245
246     bool terminateSearch(const MachineInstr &Candidate) const;
247
248     TargetMachine &TM;
249
250     static char ID;
251   };
252   char Filler::ID = 0;
253 } // end of anonymous namespace
254
255 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
256   return MI->hasDelaySlot() && !MI->isBundledWithSucc();
257 }
258
259 /// This function inserts clones of Filler into predecessor blocks.
260 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
261   MachineFunction *MF = Filler->getParent()->getParent();
262
263   for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
264     if (I->second) {
265       MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
266       ++UsefulSlots;
267     } else {
268       I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
269     }
270   }
271 }
272
273 /// This function adds registers Filler defines to MBB's live-in register list.
274 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
275   for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
276     const MachineOperand &MO = Filler->getOperand(I);
277     unsigned R;
278
279     if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
280       continue;
281
282 #ifndef NDEBUG
283     const MachineFunction &MF = *MBB.getParent();
284     assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
285            "Shouldn't move an instruction with unallocatable registers across "
286            "basic block boundaries.");
287 #endif
288
289     if (!MBB.isLiveIn(R))
290       MBB.addLiveIn(R);
291   }
292 }
293
294 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
295     : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
296
297 void RegDefsUses::init(const MachineInstr &MI) {
298   // Add all register operands which are explicit and non-variadic.
299   update(MI, 0, MI.getDesc().getNumOperands());
300
301   // If MI is a call, add RA to Defs to prevent users of RA from going into
302   // delay slot.
303   if (MI.isCall())
304     Defs.set(Mips::RA);
305
306   // Add all implicit register operands of branch instructions except
307   // register AT.
308   if (MI.isBranch()) {
309     update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
310     Defs.reset(Mips::AT);
311   }
312 }
313
314 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
315   assert(MI.isCall());
316
317   // If MI is a call, add all caller-saved registers to Defs.
318   BitVector CallerSavedRegs(TRI.getNumRegs(), true);
319
320   CallerSavedRegs.reset(Mips::ZERO);
321   CallerSavedRegs.reset(Mips::ZERO_64);
322
323   for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
324     for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
325       CallerSavedRegs.reset(*AI);
326
327   Defs |= CallerSavedRegs;
328 }
329
330 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
331   BitVector AllocSet = TRI.getAllocatableSet(MF);
332
333   for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
334     for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
335       AllocSet.set(*AI);
336
337   AllocSet.set(Mips::ZERO);
338   AllocSet.set(Mips::ZERO_64);
339
340   Defs |= AllocSet.flip();
341 }
342
343 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
344                              const MachineBasicBlock &SuccBB) {
345   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
346        SE = MBB.succ_end(); SI != SE; ++SI)
347     if (*SI != &SuccBB)
348       for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
349            LE = (*SI)->livein_end(); LI != LE; ++LI)
350         Uses.set(*LI);
351 }
352
353 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
354   BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
355   bool HasHazard = false;
356
357   for (unsigned I = Begin; I != End; ++I) {
358     const MachineOperand &MO = MI.getOperand(I);
359
360     if (MO.isReg() && MO.getReg())
361       HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
362   }
363
364   Defs |= NewDefs;
365   Uses |= NewUses;
366
367   return HasHazard;
368 }
369
370 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
371                                    unsigned Reg, bool IsDef) const {
372   if (IsDef) {
373     NewDefs.set(Reg);
374     // check whether Reg has already been defined or used.
375     return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
376   }
377
378   NewUses.set(Reg);
379   // check whether Reg has already been defined.
380   return isRegInSet(Defs, Reg);
381 }
382
383 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
384   // Check Reg and all aliased Registers.
385   for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
386     if (RegSet.test(*AI))
387       return true;
388   return false;
389 }
390
391 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
392   if (!MI.mayStore() && !MI.mayLoad())
393     return false;
394
395   if (ForbidMemInstr)
396     return true;
397
398   OrigSeenLoad = SeenLoad;
399   OrigSeenStore = SeenStore;
400   SeenLoad |= MI.mayLoad();
401   SeenStore |= MI.mayStore();
402
403   // If MI is an ordered or volatile memory reference, disallow moving
404   // subsequent loads and stores to delay slot.
405   if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
406     ForbidMemInstr = true;
407     return true;
408   }
409
410   return hasHazard_(MI);
411 }
412
413 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
414   if (MI.mayStore())
415     return true;
416
417   if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
418     return true;
419
420   if (const PseudoSourceValue *PSV =
421       (*MI.memoperands_begin())->getPseudoValue()) {
422     if (isa<FixedStackPseudoSourceValue>(PSV))
423       return false;
424     return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
425   }
426
427   return true;
428 }
429
430 MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
431   : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
432     SeenNoObjStore(false) {}
433
434 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
435   bool HasHazard = false;
436   SmallVector<ValueType, 4> Objs;
437
438   // Check underlying object list.
439   if (getUnderlyingObjects(MI, Objs)) {
440     for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
441          I != Objs.end(); ++I)
442       HasHazard |= updateDefsUses(*I, MI.mayStore());
443
444     return HasHazard;
445   }
446
447   // No underlying objects found.
448   HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
449   HasHazard |= MI.mayLoad() || OrigSeenStore;
450
451   SeenNoObjLoad |= MI.mayLoad();
452   SeenNoObjStore |= MI.mayStore();
453
454   return HasHazard;
455 }
456
457 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
458   if (MayStore)
459     return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
460            SeenNoObjLoad;
461
462   Uses.insert(V);
463   return Defs.count(V) || SeenNoObjStore;
464 }
465
466 bool MemDefsUses::
467 getUnderlyingObjects(const MachineInstr &MI,
468                      SmallVectorImpl<ValueType> &Objects) const {
469   if (!MI.hasOneMemOperand() ||
470       (!(*MI.memoperands_begin())->getValue() &&
471        !(*MI.memoperands_begin())->getPseudoValue()))
472     return false;
473
474   if (const PseudoSourceValue *PSV =
475       (*MI.memoperands_begin())->getPseudoValue()) {
476     if (!PSV->isAliased(MFI))
477       return false;
478     Objects.push_back(PSV);
479     return true;
480   }
481
482   const Value *V = (*MI.memoperands_begin())->getValue();
483
484   SmallVector<Value *, 4> Objs;
485   GetUnderlyingObjects(const_cast<Value *>(V), Objs);
486
487   for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
488        I != E; ++I) {
489     if (!isIdentifiedObject(V))
490       return false;
491
492     Objects.push_back(*I);
493   }
494
495   return true;
496 }
497
498 // Replace Branch with the compact branch instruction.
499 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB,
500                                       Iter Branch, DebugLoc DL) {
501   const MipsInstrInfo *TII =
502       MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
503
504   unsigned NewOpcode =
505     (((unsigned) Branch->getOpcode()) == Mips::BEQ) ? Mips::BEQZC_MM
506                                                     : Mips::BNEZC_MM;
507
508   const MCInstrDesc &NewDesc = TII->get(NewOpcode);
509   MachineInstrBuilder MIB = BuildMI(MBB, Branch, DL, NewDesc);
510
511   MIB.addReg(Branch->getOperand(0).getReg());
512   MIB.addMBB(Branch->getOperand(2).getMBB());
513
514   Iter tmpIter = Branch;
515   Branch = std::prev(Branch);
516   MBB.erase(tmpIter);
517
518   return Branch;
519 }
520
521 // Replace Jumps with the compact jump instruction.
522 Iter Filler::replaceWithCompactJump(MachineBasicBlock &MBB,
523                                     Iter Jump, DebugLoc DL) {
524   const MipsInstrInfo *TII =
525       MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
526
527   const MCInstrDesc &NewDesc = TII->get(Mips::JRC16_MM);
528   MachineInstrBuilder MIB = BuildMI(MBB, Jump, DL, NewDesc);
529
530   MIB.addReg(Jump->getOperand(0).getReg());
531
532   Iter tmpIter = Jump;
533   Jump = std::prev(Jump);
534   MBB.erase(tmpIter);
535
536   return Jump;
537 }
538
539 // For given opcode returns opcode of corresponding instruction with short
540 // delay slot.
541 static int getEquivalentCallShort(int Opcode) {
542   switch (Opcode) {
543   case Mips::BGEZAL:
544     return Mips::BGEZALS_MM;
545   case Mips::BLTZAL:
546     return Mips::BLTZALS_MM;
547   case Mips::JAL:
548     return Mips::JALS_MM;
549   case Mips::JALR:
550     return Mips::JALRS_MM;
551   case Mips::JALR16_MM:
552     return Mips::JALRS16_MM;
553   default:
554     llvm_unreachable("Unexpected call instruction for microMIPS.");
555   }
556 }
557
558 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
559 /// We assume there is only one delay slot per delayed instruction.
560 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
561   bool Changed = false;
562   const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
563   bool InMicroMipsMode = STI.inMicroMipsMode();
564   const MipsInstrInfo *TII = STI.getInstrInfo();
565
566   for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
567     if (!hasUnoccupiedSlot(&*I))
568       continue;
569
570     ++FilledSlots;
571     Changed = true;
572
573     // Delay slot filling is disabled at -O0.
574     if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
575       bool Filled = false;
576
577       if (searchBackward(MBB, I)) {
578         Filled = true;
579       } else if (I->isTerminator()) {
580         if (searchSuccBBs(MBB, I)) {
581           Filled = true;
582         }
583       } else if (searchForward(MBB, I)) {
584         Filled = true;
585       }
586
587       if (Filled) {
588         // Get instruction with delay slot.
589         MachineBasicBlock::instr_iterator DSI(I);
590
591         if (InMicroMipsMode && TII->GetInstSizeInBytes(std::next(DSI)) == 2 &&
592             DSI->isCall()) {
593           // If instruction in delay slot is 16b change opcode to
594           // corresponding instruction with short delay slot.
595           DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
596         }
597
598         continue;
599       }
600     }
601
602     // If instruction is BEQ or BNE with one ZERO register, then instead of
603     // adding NOP replace this instruction with the corresponding compact
604     // branch instruction, i.e. BEQZC or BNEZC.
605     unsigned Opcode = I->getOpcode();
606     if (InMicroMipsMode) {
607       switch (Opcode) {
608         case Mips::BEQ:
609         case Mips::BNE:
610           if (((unsigned) I->getOperand(1).getReg()) == Mips::ZERO) {
611             I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
612             continue;
613           }
614           break;
615         case Mips::JR:
616         case Mips::PseudoReturn:
617         case Mips::PseudoIndirectBranch:
618           // For microMIPS the PseudoReturn and PseudoIndirectBranch are allways
619           // expanded to JR_MM, so they can be replaced with JRC16_MM.
620           I = replaceWithCompactJump(MBB, I, I->getDebugLoc());
621           continue;
622         default:
623           break;
624       }
625     }
626     // Bundle the NOP to the instruction with the delay slot.
627     BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
628     MIBundleBuilder(MBB, I, std::next(I, 2));
629   }
630
631   return Changed;
632 }
633
634 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
635 /// slots in Mips MachineFunctions
636 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
637   return new Filler(tm);
638 }
639
640 template<typename IterTy>
641 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
642                          RegDefsUses &RegDU, InspectMemInstr& IM,
643                          IterTy &Filler, Iter Slot) const {
644   for (IterTy I = Begin; I != End; ++I) {
645     // skip debug value
646     if (I->isDebugValue())
647       continue;
648
649     if (terminateSearch(*I))
650       break;
651
652     assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
653            "Cannot put calls, returns or branches in delay slot.");
654
655     if (delayHasHazard(*I, RegDU, IM))
656       continue;
657
658     const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
659     if (STI.isTargetNaCl()) {
660       // In NaCl, instructions that must be masked are forbidden in delay slots.
661       // We only check for loads, stores and SP changes.  Calls, returns and
662       // branches are not checked because non-NaCl targets never put them in
663       // delay slots.
664       unsigned AddrIdx;
665       if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx) &&
666            baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg())) ||
667           I->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
668         continue;
669     }
670
671     bool InMicroMipsMode = STI.inMicroMipsMode();
672     const MipsInstrInfo *TII = STI.getInstrInfo();
673     unsigned Opcode = (*Slot).getOpcode();
674     if (InMicroMipsMode && TII->GetInstSizeInBytes(&(*I)) == 2 &&
675         (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
676          Opcode == Mips::PseudoReturn))
677       continue;
678
679     Filler = I;
680     return true;
681   }
682
683   return false;
684 }
685
686 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
687   if (DisableBackwardSearch)
688     return false;
689
690   RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
691   MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
692   ReverseIter Filler;
693
694   RegDU.init(*Slot);
695
696   if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler,
697       Slot))
698     return false;
699
700   MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
701   MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
702   ++UsefulSlots;
703   return true;
704 }
705
706 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
707   // Can handle only calls.
708   if (DisableForwardSearch || !Slot->isCall())
709     return false;
710
711   RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
712   NoMemInstr NM;
713   Iter Filler;
714
715   RegDU.setCallerSaved(*Slot);
716
717   if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler, Slot))
718     return false;
719
720   MBB.splice(std::next(Slot), &MBB, Filler);
721   MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
722   ++UsefulSlots;
723   return true;
724 }
725
726 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
727   if (DisableSuccBBSearch)
728     return false;
729
730   MachineBasicBlock *SuccBB = selectSuccBB(MBB);
731
732   if (!SuccBB)
733     return false;
734
735   RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
736   bool HasMultipleSuccs = false;
737   BB2BrMap BrMap;
738   std::unique_ptr<InspectMemInstr> IM;
739   Iter Filler;
740
741   // Iterate over SuccBB's predecessor list.
742   for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
743        PE = SuccBB->pred_end(); PI != PE; ++PI)
744     if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
745       return false;
746
747   // Do not allow moving instructions which have unallocatable register operands
748   // across basic block boundaries.
749   RegDU.setUnallocatableRegs(*MBB.getParent());
750
751   // Only allow moving loads from stack or constants if any of the SuccBB's
752   // predecessors have multiple successors.
753   if (HasMultipleSuccs) {
754     IM.reset(new LoadFromStackOrConst());
755   } else {
756     const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
757     IM.reset(new MemDefsUses(MFI));
758   }
759
760   if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler,
761       Slot))
762     return false;
763
764   insertDelayFiller(Filler, BrMap);
765   addLiveInRegs(Filler, *SuccBB);
766   Filler->eraseFromParent();
767
768   return true;
769 }
770
771 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
772   if (B.succ_empty())
773     return nullptr;
774
775   // Select the successor with the larget edge weight.
776   auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
777   MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
778                                            [&](const MachineBasicBlock *Dst0,
779                                                const MachineBasicBlock *Dst1) {
780     return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
781   });
782   return S->isLandingPad() ? nullptr : S;
783 }
784
785 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
786 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
787   const MipsInstrInfo *TII =
788       MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
789   MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
790   SmallVector<MachineInstr*, 2> BranchInstrs;
791   SmallVector<MachineOperand, 2> Cond;
792
793   MipsInstrInfo::BranchType R =
794     TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
795
796   if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
797     return std::make_pair(R, nullptr);
798
799   if (R != MipsInstrInfo::BT_CondUncond) {
800     if (!hasUnoccupiedSlot(BranchInstrs[0]))
801       return std::make_pair(MipsInstrInfo::BT_None, nullptr);
802
803     assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
804
805     return std::make_pair(R, BranchInstrs[0]);
806   }
807
808   assert((TrueBB == &Dst) || (FalseBB == &Dst));
809
810   // Examine the conditional branch. See if its slot is occupied.
811   if (hasUnoccupiedSlot(BranchInstrs[0]))
812     return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
813
814   // If that fails, try the unconditional branch.
815   if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
816     return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
817
818   return std::make_pair(MipsInstrInfo::BT_None, nullptr);
819 }
820
821 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
822                          RegDefsUses &RegDU, bool &HasMultipleSuccs,
823                          BB2BrMap &BrMap) const {
824   std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
825     getBranch(Pred, Succ);
826
827   // Return if either getBranch wasn't able to analyze the branches or there
828   // were no branches with unoccupied slots.
829   if (P.first == MipsInstrInfo::BT_None)
830     return false;
831
832   if ((P.first != MipsInstrInfo::BT_Uncond) &&
833       (P.first != MipsInstrInfo::BT_NoBranch)) {
834     HasMultipleSuccs = true;
835     RegDU.addLiveOut(Pred, Succ);
836   }
837
838   BrMap[&Pred] = P.second;
839   return true;
840 }
841
842 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
843                             InspectMemInstr &IM) const {
844   bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
845
846   HasHazard |= IM.hasHazard(Candidate);
847   HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
848
849   return HasHazard;
850 }
851
852 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
853   return (Candidate.isTerminator() || Candidate.isCall() ||
854           Candidate.isPosition() || Candidate.isInlineAsm() ||
855           Candidate.hasUnmodeledSideEffects());
856 }