LLVM  9.0.0svn
MipsDelaySlotFiller.cpp
Go to the documentation of this file.
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 
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"
38 #include "llvm/MC/MCInstrDesc.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CodeGen.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 
60  "disable-mips-delay-filler",
61  cl::init(false),
62  cl::desc("Fill all delay slots with NOPs."),
63  cl::Hidden);
64 
66  "disable-mips-df-forward-search",
67  cl::init(true),
68  cl::desc("Disallow MIPS delay filler to search forward."),
69  cl::Hidden);
70 
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 
78  "disable-mips-df-backward-search",
79  cl::init(false),
80  cl::desc("Disallow MIPS delay filler to search backward."),
81  cl::Hidden);
82 
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 
94  "mips-compact-branches",cl::Optional,
96  cl::desc("MIPS Specific: Compact branch policy."),
97  cl::values(
98  clEnumValN(CB_Never, "never", "Do not use compact branches if possible."),
99  clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."),
100  clEnumValN(CB_Always, "always", "Always use compact branches if possible.")
101  )
102 );
103 
104 namespace {
105 
106  using Iter = MachineBasicBlock::iterator;
107  using ReverseIter = MachineBasicBlock::reverse_iterator;
109 
110  class RegDefsUses {
111  public:
112  RegDefsUses(const TargetRegisterInfo &TRI);
113 
114  void init(const MachineInstr &MI);
115 
116  /// This function sets all caller-saved registers in Defs.
117  void setCallerSaved(const MachineInstr &MI);
118 
119  /// This function sets all unallocatable registers in Defs.
120  void setUnallocatableRegs(const MachineFunction &MF);
121 
122  /// Set bits in Uses corresponding to MBB's live-out registers except for
123  /// the registers that are live-in to SuccBB.
124  void addLiveOut(const MachineBasicBlock &MBB,
125  const MachineBasicBlock &SuccBB);
126 
127  bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
128 
129  private:
130  bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
131  bool IsDef) const;
132 
133  /// Returns true if Reg or its alias is in RegSet.
134  bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
135 
136  const TargetRegisterInfo &TRI;
137  BitVector Defs, Uses;
138  };
139 
140  /// Base class for inspecting loads and stores.
141  class InspectMemInstr {
142  public:
143  InspectMemInstr(bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
144  virtual ~InspectMemInstr() = default;
145 
146  /// Return true if MI cannot be moved to delay slot.
147  bool hasHazard(const MachineInstr &MI);
148 
149  protected:
150  /// Flags indicating whether loads or stores have been seen.
151  bool OrigSeenLoad = false;
152  bool OrigSeenStore = false;
153  bool SeenLoad = false;
154  bool SeenStore = false;
155 
156  /// Memory instructions are not allowed to move to delay slot if this flag
157  /// is true.
158  bool ForbidMemInstr;
159 
160  private:
161  virtual bool hasHazard_(const MachineInstr &MI) = 0;
162  };
163 
164  /// This subclass rejects any memory instructions.
165  class NoMemInstr : public InspectMemInstr {
166  public:
167  NoMemInstr() : InspectMemInstr(true) {}
168 
169  private:
170  bool hasHazard_(const MachineInstr &MI) override { return true; }
171  };
172 
173  /// This subclass accepts loads from stacks and constant loads.
174  class LoadFromStackOrConst : public InspectMemInstr {
175  public:
176  LoadFromStackOrConst() : InspectMemInstr(false) {}
177 
178  private:
179  bool hasHazard_(const MachineInstr &MI) override;
180  };
181 
182  /// This subclass uses memory dependence information to determine whether a
183  /// memory instruction can be moved to a delay slot.
184  class MemDefsUses : public InspectMemInstr {
185  public:
186  MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
187 
188  private:
190 
191  bool hasHazard_(const MachineInstr &MI) override;
192 
193  /// Update Defs and Uses. Return true if there exist dependences that
194  /// disqualify the delay slot candidate between V and values in Uses and
195  /// Defs.
196  bool updateDefsUses(ValueType V, bool MayStore);
197 
198  /// Get the list of underlying objects of MI's memory operand.
200  SmallVectorImpl<ValueType> &Objects) const;
201 
202  const MachineFrameInfo *MFI;
203  SmallPtrSet<ValueType, 4> Uses, Defs;
204  const DataLayout &DL;
205 
206  /// Flags indicating whether loads or stores with no underlying objects have
207  /// been seen.
208  bool SeenNoObjLoad = false;
209  bool SeenNoObjStore = false;
210  };
211 
212  class MipsDelaySlotFiller : public MachineFunctionPass {
213  public:
214  MipsDelaySlotFiller() : MachineFunctionPass(ID) {
216  }
217 
218  StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
219 
220  bool runOnMachineFunction(MachineFunction &F) override {
221  TM = &F.getTarget();
222  bool Changed = false;
223  for (MachineFunction::iterator FI = F.begin(), FE = F.end();
224  FI != FE; ++FI)
225  Changed |= runOnMachineBasicBlock(*FI);
226 
227  // This pass invalidates liveness information when it reorders
228  // instructions to fill delay slot. Without this, -verify-machineinstrs
229  // will fail.
230  if (Changed)
232 
233  return Changed;
234  }
235 
236  MachineFunctionProperties getRequiredProperties() const override {
239  }
240 
241  void getAnalysisUsage(AnalysisUsage &AU) const override {
244  }
245 
246  static char ID;
247 
248  private:
249  bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
250 
251  Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
252  const DebugLoc &DL);
253 
254  /// This function checks if it is valid to move Candidate to the delay slot
255  /// and returns true if it isn't. It also updates memory and register
256  /// dependence information.
257  bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
258  InspectMemInstr &IM) const;
259 
260  /// This function searches range [Begin, End) for an instruction that can be
261  /// moved to the delay slot. Returns true on success.
262  template<typename IterTy>
263  bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
264  RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
265  IterTy &Filler) const;
266 
267  /// This function searches in the backward direction for an instruction that
268  /// can be moved to the delay slot. Returns true on success.
269  bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
270 
271  /// This function searches MBB in the forward direction for an instruction
272  /// that can be moved to the delay slot. Returns true on success.
273  bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
274 
275  /// This function searches one of MBB's successor blocks for an instruction
276  /// that can be moved to the delay slot and inserts clones of the
277  /// instruction into the successor's predecessor blocks.
278  bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
279 
280  /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
281  /// successor block that is not a landing pad.
282  MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
283 
284  /// This function analyzes MBB and returns an instruction with an unoccupied
285  /// slot that branches to Dst.
286  std::pair<MipsInstrInfo::BranchType, MachineInstr *>
287  getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
288 
289  /// Examine Pred and see if it is possible to insert an instruction into
290  /// one of its branches delay slot or its end.
291  bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
292  RegDefsUses &RegDU, bool &HasMultipleSuccs,
293  BB2BrMap &BrMap) const;
294 
295  bool terminateSearch(const MachineInstr &Candidate) const;
296 
297  const TargetMachine *TM = nullptr;
298  };
299 
300 } // end anonymous namespace
301 
302 char MipsDelaySlotFiller::ID = 0;
303 
304 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
305  return MI->hasDelaySlot() && !MI->isBundledWithSucc();
306 }
307 
308 INITIALIZE_PASS(MipsDelaySlotFiller, DEBUG_TYPE,
309  "Fill delay slot for MIPS", false, false)
310 
311 /// This function inserts clones of Filler into predecessor blocks.
312 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
313  MachineFunction *MF = Filler->getParent()->getParent();
314 
315  for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
316  if (I->second) {
317  MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
318  ++UsefulSlots;
319  } else {
320  I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
321  }
322  }
323 }
324 
325 /// This function adds registers Filler defines to MBB's live-in register list.
326 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
327  for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
328  const MachineOperand &MO = Filler->getOperand(I);
329  unsigned R;
330 
331  if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
332  continue;
333 
334 #ifndef NDEBUG
335  const MachineFunction &MF = *MBB.getParent();
337  "Shouldn't move an instruction with unallocatable registers across "
338  "basic block boundaries.");
339 #endif
340 
341  if (!MBB.isLiveIn(R))
342  MBB.addLiveIn(R);
343  }
344 }
345 
346 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
347  : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
348 
349 void RegDefsUses::init(const MachineInstr &MI) {
350  // Add all register operands which are explicit and non-variadic.
351  update(MI, 0, MI.getDesc().getNumOperands());
352 
353  // If MI is a call, add RA to Defs to prevent users of RA from going into
354  // delay slot.
355  if (MI.isCall())
356  Defs.set(Mips::RA);
357 
358  // Add all implicit register operands of branch instructions except
359  // register AT.
360  if (MI.isBranch()) {
361  update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
362  Defs.reset(Mips::AT);
363  }
364 }
365 
366 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
367  assert(MI.isCall());
368 
369  // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
370  // the delay slot. The reason is that RA/RA_64 must not be changed
371  // in the delay slot so that the callee can return to the caller.
372  if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
373  Defs.set(Mips::RA);
374  Defs.set(Mips::RA_64);
375  }
376 
377  // If MI is a call, add all caller-saved registers to Defs.
378  BitVector CallerSavedRegs(TRI.getNumRegs(), true);
379 
380  CallerSavedRegs.reset(Mips::ZERO);
381  CallerSavedRegs.reset(Mips::ZERO_64);
382 
383  for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
384  *R; ++R)
385  for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
386  CallerSavedRegs.reset(*AI);
387 
388  Defs |= CallerSavedRegs;
389 }
390 
391 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
392  BitVector AllocSet = TRI.getAllocatableSet(MF);
393 
394  for (unsigned R : AllocSet.set_bits())
395  for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
396  AllocSet.set(*AI);
397 
398  AllocSet.set(Mips::ZERO);
399  AllocSet.set(Mips::ZERO_64);
400 
401  Defs |= AllocSet.flip();
402 }
403 
404 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
405  const MachineBasicBlock &SuccBB) {
407  SE = MBB.succ_end(); SI != SE; ++SI)
408  if (*SI != &SuccBB)
409  for (const auto &LI : (*SI)->liveins())
410  Uses.set(LI.PhysReg);
411 }
412 
413 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
414  BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
415  bool HasHazard = false;
416 
417  for (unsigned I = Begin; I != End; ++I) {
418  const MachineOperand &MO = MI.getOperand(I);
419 
420  if (MO.isReg() && MO.getReg())
421  HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
422  }
423 
424  Defs |= NewDefs;
425  Uses |= NewUses;
426 
427  return HasHazard;
428 }
429 
430 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
431  unsigned Reg, bool IsDef) const {
432  if (IsDef) {
433  NewDefs.set(Reg);
434  // check whether Reg has already been defined or used.
435  return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
436  }
437 
438  NewUses.set(Reg);
439  // check whether Reg has already been defined.
440  return isRegInSet(Defs, Reg);
441 }
442 
443 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
444  // Check Reg and all aliased Registers.
445  for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
446  if (RegSet.test(*AI))
447  return true;
448  return false;
449 }
450 
451 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
452  if (!MI.mayStore() && !MI.mayLoad())
453  return false;
454 
455  if (ForbidMemInstr)
456  return true;
457 
458  OrigSeenLoad = SeenLoad;
459  OrigSeenStore = SeenStore;
460  SeenLoad |= MI.mayLoad();
461  SeenStore |= MI.mayStore();
462 
463  // If MI is an ordered or volatile memory reference, disallow moving
464  // subsequent loads and stores to delay slot.
465  if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
466  ForbidMemInstr = true;
467  return true;
468  }
469 
470  return hasHazard_(MI);
471 }
472 
473 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
474  if (MI.mayStore())
475  return true;
476 
477  if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
478  return true;
479 
480  if (const PseudoSourceValue *PSV =
481  (*MI.memoperands_begin())->getPseudoValue()) {
482  if (isa<FixedStackPseudoSourceValue>(PSV))
483  return false;
484  return !PSV->isConstant(nullptr) && !PSV->isStack();
485  }
486 
487  return true;
488 }
489 
490 MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
491  : InspectMemInstr(false), MFI(MFI_), DL(DL) {}
492 
493 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
494  bool HasHazard = false;
496 
497  // Check underlying object list.
498  if (getUnderlyingObjects(MI, Objs)) {
500  I != Objs.end(); ++I)
501  HasHazard |= updateDefsUses(*I, MI.mayStore());
502 
503  return HasHazard;
504  }
505 
506  // No underlying objects found.
507  HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
508  HasHazard |= MI.mayLoad() || OrigSeenStore;
509 
510  SeenNoObjLoad |= MI.mayLoad();
511  SeenNoObjStore |= MI.mayStore();
512 
513  return HasHazard;
514 }
515 
516 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
517  if (MayStore)
518  return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
519  SeenNoObjLoad;
520 
521  Uses.insert(V);
522  return Defs.count(V) || SeenNoObjStore;
523 }
524 
525 bool MemDefsUses::
527  SmallVectorImpl<ValueType> &Objects) const {
528  if (!MI.hasOneMemOperand() ||
529  (!(*MI.memoperands_begin())->getValue() &&
530  !(*MI.memoperands_begin())->getPseudoValue()))
531  return false;
532 
533  if (const PseudoSourceValue *PSV =
534  (*MI.memoperands_begin())->getPseudoValue()) {
535  if (!PSV->isAliased(MFI))
536  return false;
537  Objects.push_back(PSV);
538  return true;
539  }
540 
541  const Value *V = (*MI.memoperands_begin())->getValue();
542 
544  GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
545 
546  for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
547  I != E; ++I) {
548  if (!isIdentifiedObject(V))
549  return false;
550 
551  Objects.push_back(*I);
552  }
553 
554  return true;
555 }
556 
557 // Replace Branch with the compact branch instruction.
558 Iter MipsDelaySlotFiller::replaceWithCompactBranch(MachineBasicBlock &MBB,
559  Iter Branch,
560  const DebugLoc &DL) {
561  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
562  const MipsInstrInfo *TII = STI.getInstrInfo();
563 
564  unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
565  Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
566 
567  std::next(Branch)->eraseFromParent();
568  return Branch;
569 }
570 
571 // For given opcode returns opcode of corresponding instruction with short
572 // delay slot.
573 // For the pseudo TAILCALL*_MM instructions return the short delay slot
574 // form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
575 // that is too short to make use of for tail calls.
576 static int getEquivalentCallShort(int Opcode) {
577  switch (Opcode) {
578  case Mips::BGEZAL:
579  return Mips::BGEZALS_MM;
580  case Mips::BLTZAL:
581  return Mips::BLTZALS_MM;
582  case Mips::JAL:
583  case Mips::JAL_MM:
584  return Mips::JALS_MM;
585  case Mips::JALR:
586  return Mips::JALRS_MM;
587  case Mips::JALR16_MM:
588  return Mips::JALRS16_MM;
589  case Mips::TAILCALL_MM:
590  llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
591  case Mips::TAILCALLREG:
592  return Mips::JR16_MM;
593  default:
594  llvm_unreachable("Unexpected call instruction for microMIPS.");
595  }
596 }
597 
598 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
599 /// We assume there is only one delay slot per delayed instruction.
600 bool MipsDelaySlotFiller::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
601  bool Changed = false;
602  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
603  bool InMicroMipsMode = STI.inMicroMipsMode();
604  const MipsInstrInfo *TII = STI.getInstrInfo();
605 
606  for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
607  if (!hasUnoccupiedSlot(&*I))
608  continue;
609 
610  // Delay slot filling is disabled at -O0, or in microMIPS32R6.
611  if (!DisableDelaySlotFiller && (TM->getOptLevel() != CodeGenOpt::None) &&
612  !(InMicroMipsMode && STI.hasMips32r6())) {
613 
614  bool Filled = false;
615 
616  if (MipsCompactBranchPolicy.getValue() != CB_Always ||
617  !TII->getEquivalentCompactForm(I)) {
618  if (searchBackward(MBB, *I)) {
619  Filled = true;
620  } else if (I->isTerminator()) {
621  if (searchSuccBBs(MBB, I)) {
622  Filled = true;
623  }
624  } else if (searchForward(MBB, I)) {
625  Filled = true;
626  }
627  }
628 
629  if (Filled) {
630  // Get instruction with delay slot.
631  MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
632 
633  if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
634  DSI->isCall()) {
635  // If instruction in delay slot is 16b change opcode to
636  // corresponding instruction with short delay slot.
637 
638  // TODO: Implement an instruction mapping table of 16bit opcodes to
639  // 32bit opcodes so that an instruction can be expanded. This would
640  // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
641  // TODO: Permit b16 when branching backwards to the same function
642  // if it is in range.
643  DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
644  }
645  ++FilledSlots;
646  Changed = true;
647  continue;
648  }
649  }
650 
651  // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
652  // instead of adding NOP replace this instruction with the corresponding
653  // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
654  // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
655  // be replaced with JRC16_MM.
656 
657  // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
658  // form of the CTI. For indirect jumps this will not require inserting a
659  // NOP and for branches will hopefully avoid requiring a NOP.
660  if ((InMicroMipsMode ||
662  TII->getEquivalentCompactForm(I)) {
663  I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
664  Changed = true;
665  continue;
666  }
667 
668  // Bundle the NOP to the instruction with the delay slot.
669  BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
670  MIBundleBuilder(MBB, I, std::next(I, 2));
671  ++FilledSlots;
672  Changed = true;
673  }
674 
675  return Changed;
676 }
677 
678 template <typename IterTy>
679 bool MipsDelaySlotFiller::searchRange(MachineBasicBlock &MBB, IterTy Begin,
680  IterTy End, RegDefsUses &RegDU,
681  InspectMemInstr &IM, Iter Slot,
682  IterTy &Filler) const {
683  for (IterTy I = Begin; I != End;) {
684  IterTy CurrI = I;
685  ++I;
686 
687  // skip debug value
688  if (CurrI->isDebugInstr())
689  continue;
690 
691  if (terminateSearch(*CurrI))
692  break;
693 
694  assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
695  "Cannot put calls, returns or branches in delay slot.");
696 
697  if (CurrI->isKill()) {
698  CurrI->eraseFromParent();
699  continue;
700  }
701 
702  if (delayHasHazard(*CurrI, RegDU, IM))
703  continue;
704 
705  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
706  if (STI.isTargetNaCl()) {
707  // In NaCl, instructions that must be masked are forbidden in delay slots.
708  // We only check for loads, stores and SP changes. Calls, returns and
709  // branches are not checked because non-NaCl targets never put them in
710  // delay slots.
711  unsigned AddrIdx;
712  if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
713  baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
714  CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
715  continue;
716  }
717 
718  bool InMicroMipsMode = STI.inMicroMipsMode();
719  const MipsInstrInfo *TII = STI.getInstrInfo();
720  unsigned Opcode = (*Slot).getOpcode();
721  // This is complicated by the tail call optimization. For non-PIC code
722  // there is only a 32bit sized unconditional branch which can be assumed
723  // to be able to reach the target. b16 only has a range of +/- 1 KB.
724  // It's entirely possible that the target function is reachable with b16
725  // but we don't have enough information to make that decision.
726  if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
727  (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
728  Opcode == Mips::PseudoIndirectBranch_MM ||
729  Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
730  continue;
731  // Instructions LWP/SWP and MOVEP should not be in a delay slot as that
732  // results in unpredictable behaviour
733  if (InMicroMipsMode && (Opcode == Mips::LWP_MM || Opcode == Mips::SWP_MM ||
734  Opcode == Mips::MOVEP_MM))
735  continue;
736 
737  Filler = CurrI;
738  return true;
739  }
740 
741  return false;
742 }
743 
744 bool MipsDelaySlotFiller::searchBackward(MachineBasicBlock &MBB,
745  MachineInstr &Slot) const {
747  return false;
748 
749  auto *Fn = MBB.getParent();
750  RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
751  MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
752  ReverseIter Filler;
753 
754  RegDU.init(Slot);
755 
756  MachineBasicBlock::iterator SlotI = Slot;
757  if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
758  Filler))
759  return false;
760 
761  MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
762  MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
763  ++UsefulSlots;
764  return true;
765 }
766 
767 bool MipsDelaySlotFiller::searchForward(MachineBasicBlock &MBB,
768  Iter Slot) const {
769  // Can handle only calls.
770  if (DisableForwardSearch || !Slot->isCall())
771  return false;
772 
773  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
774  NoMemInstr NM;
775  Iter Filler;
776 
777  RegDU.setCallerSaved(*Slot);
778 
779  if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
780  return false;
781 
782  MBB.splice(std::next(Slot), &MBB, Filler);
783  MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
784  ++UsefulSlots;
785  return true;
786 }
787 
788 bool MipsDelaySlotFiller::searchSuccBBs(MachineBasicBlock &MBB,
789  Iter Slot) const {
791  return false;
792 
793  MachineBasicBlock *SuccBB = selectSuccBB(MBB);
794 
795  if (!SuccBB)
796  return false;
797 
798  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
799  bool HasMultipleSuccs = false;
800  BB2BrMap BrMap;
801  std::unique_ptr<InspectMemInstr> IM;
802  Iter Filler;
803  auto *Fn = MBB.getParent();
804 
805  // Iterate over SuccBB's predecessor list.
806  for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
807  PE = SuccBB->pred_end(); PI != PE; ++PI)
808  if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
809  return false;
810 
811  // Do not allow moving instructions which have unallocatable register operands
812  // across basic block boundaries.
813  RegDU.setUnallocatableRegs(*Fn);
814 
815  // Only allow moving loads from stack or constants if any of the SuccBB's
816  // predecessors have multiple successors.
817  if (HasMultipleSuccs) {
818  IM.reset(new LoadFromStackOrConst());
819  } else {
820  const MachineFrameInfo &MFI = Fn->getFrameInfo();
821  IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
822  }
823 
824  if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
825  Filler))
826  return false;
827 
828  insertDelayFiller(Filler, BrMap);
829  addLiveInRegs(Filler, *SuccBB);
830  Filler->eraseFromParent();
831 
832  return true;
833 }
834 
836 MipsDelaySlotFiller::selectSuccBB(MachineBasicBlock &B) const {
837  if (B.succ_empty())
838  return nullptr;
839 
840  // Select the successor with the larget edge weight.
841  auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
842  MachineBasicBlock *S = *std::max_element(
843  B.succ_begin(), B.succ_end(),
844  [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
845  return Prob.getEdgeProbability(&B, Dst0) <
846  Prob.getEdgeProbability(&B, Dst1);
847  });
848  return S->isEHPad() ? nullptr : S;
849 }
850 
851 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
852 MipsDelaySlotFiller::getBranch(MachineBasicBlock &MBB,
853  const MachineBasicBlock &Dst) const {
854  const MipsInstrInfo *TII =
855  MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
856  MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
857  SmallVector<MachineInstr*, 2> BranchInstrs;
859 
861  TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
862 
864  return std::make_pair(R, nullptr);
865 
866  if (R != MipsInstrInfo::BT_CondUncond) {
867  if (!hasUnoccupiedSlot(BranchInstrs[0]))
868  return std::make_pair(MipsInstrInfo::BT_None, nullptr);
869 
870  assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
871 
872  return std::make_pair(R, BranchInstrs[0]);
873  }
874 
875  assert((TrueBB == &Dst) || (FalseBB == &Dst));
876 
877  // Examine the conditional branch. See if its slot is occupied.
878  if (hasUnoccupiedSlot(BranchInstrs[0]))
879  return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
880 
881  // If that fails, try the unconditional branch.
882  if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
883  return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
884 
885  return std::make_pair(MipsInstrInfo::BT_None, nullptr);
886 }
887 
888 bool MipsDelaySlotFiller::examinePred(MachineBasicBlock &Pred,
889  const MachineBasicBlock &Succ,
890  RegDefsUses &RegDU,
891  bool &HasMultipleSuccs,
892  BB2BrMap &BrMap) const {
893  std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
894  getBranch(Pred, Succ);
895 
896  // Return if either getBranch wasn't able to analyze the branches or there
897  // were no branches with unoccupied slots.
898  if (P.first == MipsInstrInfo::BT_None)
899  return false;
900 
901  if ((P.first != MipsInstrInfo::BT_Uncond) &&
902  (P.first != MipsInstrInfo::BT_NoBranch)) {
903  HasMultipleSuccs = true;
904  RegDU.addLiveOut(Pred, Succ);
905  }
906 
907  BrMap[&Pred] = P.second;
908  return true;
909 }
910 
911 bool MipsDelaySlotFiller::delayHasHazard(const MachineInstr &Candidate,
912  RegDefsUses &RegDU,
913  InspectMemInstr &IM) const {
914  assert(!Candidate.isKill() &&
915  "KILL instructions should have been eliminated at this point.");
916 
917  bool HasHazard = Candidate.isImplicitDef();
918 
919  HasHazard |= IM.hasHazard(Candidate);
920  HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
921 
922  return HasHazard;
923 }
924 
925 bool MipsDelaySlotFiller::terminateSearch(const MachineInstr &Candidate) const {
926  return (Candidate.isTerminator() || Candidate.isCall() ||
927  Candidate.isPosition() || Candidate.isInlineAsm() ||
928  Candidate.hasUnmodeledSideEffects());
929 }
930 
931 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
932 /// slots in Mips MachineFunctions
933 FunctionPass *llvm::createMipsDelaySlotFillerPass() { return new MipsDelaySlotFiller(); }
BitVector getAllocatableSet(const MachineFunction &MF, const TargetRegisterClass *RC=nullptr) const
Returns a bitset indexed by register number indicating if a register is allocatable or not...
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
Return the number of bytes of code the specified instruction may be.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
BitVector & set()
Definition: BitVector.h:397
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:632
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:320
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Branch Analysis.
static cl::opt< CompactBranchPolicy > MipsCompactBranchPolicy("mips-compact-branches", cl::Optional, cl::init(CB_Optimal), cl::desc("MIPS Specific: Compact branch policy."), cl::values(clEnumValN(CB_Never, "never", "Do not use compact branches if possible."), clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."), clEnumValN(CB_Always, "always", "Always use compact branches if possible.")))
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool isBasePlusOffsetMemoryAccess(unsigned Opcode, unsigned *AddrIdx, bool *IsStore=nullptr)
unsigned getReg() const
getReg - Returns the register number.
static void getUnderlyingObjects(MachineInstr *MI, SmallVectorImpl< Value *> &Objs, const DataLayout &DL)
Return the underlying objects for the memory references of an instruction.
unsigned Reg
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
Definition: MachineInstr.h:740
bool isInlineAsm() const
const MipsInstrInfo * getInstrInfo() const override
bool test(unsigned Idx) const
Definition: BitVector.h:501
Optimal is the default and will produce compact branches when delay slots cannot be filled...
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions ...
static bool hasUnoccupiedSlot(const MachineInstr *MI)
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
F(f)
block Block Frequency true
static cl::opt< bool > DisableDelaySlotFiller("disable-mips-delay-filler", cl::init(false), cl::desc("Fill all delay slots with NOPs."), cl::Hidden)
SI optimize exec mask operations pre RA
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
bool inMicroMipsMode() const
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
Definition: MachineInstr.h:365
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:648
bool hasMips32r6() const
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool baseRegNeedsLoadStoreMask(unsigned Reg)
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB)
This function adds registers Filler defines to MBB&#39;s live-in register list.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:405
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
static cl::opt< bool > DisableBackwardSearch("disable-mips-df-backward-search", cl::init(false), cl::desc("Disallow MIPS delay filler to search backward."), cl::Hidden)
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
static cl::opt< bool > DisableForwardSearch("disable-mips-df-forward-search", cl::init(true), cl::desc("Disallow MIPS delay filler to search forward."), cl::Hidden)
virtual const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const =0
Return a null-terminated list of all of the callee-saved registers on this target.
reverse_iterator rend()
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
Definition: MachineInstr.h:656
bool isTargetNaCl() const
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Definition: MachineInstr.h:819
#define P(N)
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
INITIALIZE_PASS(MipsDelaySlotFiller, DEBUG_TYPE, "Fill delay slot for MIPS", false, false) static void insertDelayFiller(Iter Filler
This function inserts clones of Filler into predecessor blocks.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
MachineInstrBundleIterator< MachineInstr > iterator
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:643
&#39;always&#39; may in some circumstances may not be absolutely adhered to there may not be a corresponding ...
unsigned getEquivalentCompactForm(const MachineBasicBlock::iterator I) const
Determine the opcode of a non-delay slot form for a branch if one exists.
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
Definition: MachineInstr.h:548
BitVector & reset()
Definition: BitVector.h:438
CompactBranchPolicy
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
bool definesRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr fully defines the specified register.
std::vector< MachineBasicBlock * >::const_iterator const_succ_iterator
std::vector< MachineBasicBlock * >::iterator pred_iterator
static cl::opt< bool > DisableSuccBBSearch("disable-mips-df-succbb-search", cl::init(true), cl::desc("Disallow MIPS delay filler to search successor basic blocks."), cl::Hidden)
bool isImplicitDef() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:533
const MipsRegisterInfo * getRegisterInfo() const override
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
BitVector & flip()
Definition: BitVector.h:477
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
#define DEBUG_TYPE
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Special value supplied for machine level alias analysis.
static int getEquivalentCallShort(int Opcode)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:618
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const BB2BrMap & BrMap
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB &#39;Other&#39; at the position From, and insert it into this MBB right before &#39;...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool isEHPad() const
Returns true if the block is a landing pad.
#define I(x, y, z)
Definition: MD5.cpp:58
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
bool isKill() const
The policy &#39;never&#39; may in some circumstances or for some ISAs not be absolutely adhered to...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void GetUnderlyingObjects(Value *V, SmallVectorImpl< Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
MIBundleBuilder & append(MachineInstr *MI)
Insert MI into MBB by appending it to the instructions in the bundle.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:806
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
iterator_range< const_set_bits_iterator > set_bits() const
Definition: BitVector.h:129
LLVM Value Representation.
Definition: Value.h:72
bool isPosition() const
Definition: MachineInstr.h:994
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
void initializeMipsDelaySlotFillerPass(PassRegistry &)
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
Properties which a MachineFunction may have at a given point in time.
Helper class for constructing bundles of MachineInstrs.
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:86