blob: f5b629846aed6add3c549601b88729a0288175b9 [file] [log] [blame]
Akira Hatanaka1083eb12013-02-14 23:20:15 +00001//===-- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler ------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00007//
Akira Hatanakae2489122011-04-15 21:51:11 +00008//===----------------------------------------------------------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00009//
Akira Hatanaka1083eb12013-02-14 23:20:15 +000010// Simple pass to fill delay slots with useful instructions.
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000011//
Akira Hatanakae2489122011-04-15 21:51:11 +000012//===----------------------------------------------------------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000013
Sasa Stankovic5fddf612014-03-10 20:34:23 +000014#include "MCTargetDesc/MipsMCNaCl.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000015#include "Mips.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000016#include "MipsInstrInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000017#include "MipsTargetMachine.h"
Akira Hatanaka06bd1382013-02-14 23:40:57 +000018#include "llvm/ADT/BitVector.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000019#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Statistic.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000021#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/ValueTracking.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
Daniel Sanders308181e2014-06-12 10:44:10 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000027#include "llvm/CodeGen/PseudoSourceValue.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000028#include "llvm/Support/CommandLine.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000029#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetMachine.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000031#include "llvm/Target/TargetRegisterInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000032
33using namespace llvm;
34
Chandler Carruth84e68b22014-04-22 02:41:26 +000035#define DEBUG_TYPE "delay-slot-filler"
36
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000037STATISTIC(FilledSlots, "Number of delay slots filled");
Akira Hatanaka9e603442011-10-05 01:19:13 +000038STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
Akira Hatanaka02e760a2011-10-05 02:22:49 +000039 " are not NOP.");
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000040
Akira Hatanaka9d957842012-08-22 02:51:28 +000041static cl::opt<bool> DisableDelaySlotFiller(
42 "disable-mips-delay-filler",
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000043 cl::init(false),
Akira Hatanaka1083eb12013-02-14 23:20:15 +000044 cl::desc("Fill all delay slots with NOPs."),
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000045 cl::Hidden);
46
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000047static 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
Akira Hatanakae44e30c2013-03-01 01:02:36 +000053static 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
59static 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
Simon Dardis8d8f2f82016-05-17 10:21:43 +000065enum CompactBranchPolicy {
66 CB_Never, ///< The policy 'never' may in some circumstances or for some
67 ///< ISAs not be absolutely adhered to.
68 CB_Optimal, ///< Optimal is the default and will produce compact branches
69 ///< when delay slots cannot be filled.
70 CB_Always ///< 'always' may in some circumstances may not be
71 ///< absolutely adhered to there may not be a corresponding
72 ///< compact form of a branch.
73};
74
75static cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy(
76 "mips-compact-branches",cl::Optional,
77 cl::init(CB_Optimal),
78 cl::desc("MIPS Specific: Compact branch policy."),
79 cl::values(
80 clEnumValN(CB_Never, "never", "Do not use compact branches if possible."),
81 clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."),
82 clEnumValN(CB_Always, "always", "Always use compact branches if possible."),
83 clEnumValEnd
84 )
85);
86
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000087namespace {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000088 typedef MachineBasicBlock::iterator Iter;
89 typedef MachineBasicBlock::reverse_iterator ReverseIter;
90 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
91
Akira Hatanaka979899e2013-02-26 01:30:05 +000092 class RegDefsUses {
93 public:
Eric Christopher96e72c62015-01-29 23:27:36 +000094 RegDefsUses(const TargetRegisterInfo &TRI);
Akira Hatanaka979899e2013-02-26 01:30:05 +000095 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000096
97 /// This function sets all caller-saved registers in Defs.
98 void setCallerSaved(const MachineInstr &MI);
99
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000100 /// This function sets all unallocatable registers in Defs.
101 void setUnallocatableRegs(const MachineFunction &MF);
102
103 /// Set bits in Uses corresponding to MBB's live-out registers except for
104 /// the registers that are live-in to SuccBB.
105 void addLiveOut(const MachineBasicBlock &MBB,
106 const MachineBasicBlock &SuccBB);
107
Akira Hatanaka979899e2013-02-26 01:30:05 +0000108 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
109
110 private:
111 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
112 bool IsDef) const;
113
114 /// Returns true if Reg or its alias is in RegSet.
115 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
116
117 const TargetRegisterInfo &TRI;
118 BitVector Defs, Uses;
119 };
120
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000121 /// Base class for inspecting loads and stores.
122 class InspectMemInstr {
123 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000124 InspectMemInstr(bool ForbidMemInstr_)
125 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
126 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
127
128 /// Return true if MI cannot be moved to delay slot.
129 bool hasHazard(const MachineInstr &MI);
130
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000131 virtual ~InspectMemInstr() {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000132
133 protected:
134 /// Flags indicating whether loads or stores have been seen.
135 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
136
137 /// Memory instructions are not allowed to move to delay slot if this flag
138 /// is true.
139 bool ForbidMemInstr;
140
141 private:
142 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000143 };
144
145 /// This subclass rejects any memory instructions.
146 class NoMemInstr : public InspectMemInstr {
147 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000148 NoMemInstr() : InspectMemInstr(true) {}
149 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000150 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000151 };
152
153 /// This subclass accepts loads from stacks and constant loads.
154 class LoadFromStackOrConst : public InspectMemInstr {
155 public:
156 LoadFromStackOrConst() : InspectMemInstr(false) {}
157 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000158 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000159 };
160
161 /// This subclass uses memory dependence information to determine whether a
162 /// memory instruction can be moved to a delay slot.
163 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000164 public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000165 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000166
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000167 private:
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000168 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
169
Craig Topper56c590a2014-04-29 07:58:02 +0000170 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000171
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000172 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000173 /// disqualify the delay slot candidate between V and values in Uses and
174 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000175 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000176
177 /// Get the list of underlying objects of MI's memory operand.
178 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000179 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000180
181 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000182 SmallPtrSet<ValueType, 4> Uses, Defs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000183 const DataLayout &DL;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000184
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000185 /// Flags indicating whether loads or stores with no underlying objects have
186 /// been seen.
187 bool SeenNoObjLoad, SeenNoObjStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000188 };
189
Akira Hatanakaa0612812013-02-07 21:32:32 +0000190 class Filler : public MachineFunctionPass {
191 public:
Bruno Cardoso Lopesfde21cf2010-12-09 17:31:11 +0000192 Filler(TargetMachine &tm)
Bill Wendlingead89ef2013-06-07 07:04:14 +0000193 : MachineFunctionPass(ID), TM(tm) { }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000194
Craig Topper56c590a2014-04-29 07:58:02 +0000195 const char *getPassName() const override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000196 return "Mips Delay Slot Filler";
197 }
198
Craig Topper56c590a2014-04-29 07:58:02 +0000199 bool runOnMachineFunction(MachineFunction &F) override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000200 bool Changed = false;
201 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
202 FI != FE; ++FI)
203 Changed |= runOnMachineBasicBlock(*FI);
Daniel Sanders308181e2014-06-12 10:44:10 +0000204
205 // This pass invalidates liveness information when it reorders
206 // instructions to fill delay slot. Without this, -verify-machineinstrs
207 // will fail.
208 if (Changed)
209 F.getRegInfo().invalidateLiveness();
210
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000211 return Changed;
212 }
213
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000214 MachineFunctionProperties getRequiredProperties() const override {
215 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000216 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000217 }
218
Craig Topper56c590a2014-04-29 07:58:02 +0000219 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000220 AU.addRequired<MachineBranchProbabilityInfo>();
221 MachineFunctionPass::getAnalysisUsage(AU);
222 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000223
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000224 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000225 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
226
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000227 Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
228 const DebugLoc &DL);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000229
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000230 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000231 /// and returns true if it isn't. It also updates memory and register
232 /// dependence information.
233 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000234 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000235
Akira Hatanakaf815db52013-03-01 00:26:14 +0000236 /// This function searches range [Begin, End) for an instruction that can be
237 /// moved to the delay slot. Returns true on success.
238 template<typename IterTy>
239 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000240 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
241 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000242
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000243 /// This function searches in the backward direction for an instruction that
244 /// can be moved to the delay slot. Returns true on success.
245 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
246
247 /// This function searches MBB in the forward direction for an instruction
248 /// that can be moved to the delay slot. Returns true on success.
249 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000250
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000251 /// This function searches one of MBB's successor blocks for an instruction
252 /// that can be moved to the delay slot and inserts clones of the
253 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000254 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
255
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000256 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
257 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000258 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
259
260 /// This function analyzes MBB and returns an instruction with an unoccupied
261 /// slot that branches to Dst.
262 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
263 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
264
265 /// Examine Pred and see if it is possible to insert an instruction into
266 /// one of its branches delay slot or its end.
267 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
268 RegDefsUses &RegDU, bool &HasMultipleSuccs,
269 BB2BrMap &BrMap) const;
270
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000271 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000272
Akira Hatanakaa0612812013-02-07 21:32:32 +0000273 TargetMachine &TM;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000274
Akira Hatanakaa0612812013-02-07 21:32:32 +0000275 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000276 };
277 char Filler::ID = 0;
278} // end of anonymous namespace
279
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000280static bool hasUnoccupiedSlot(const MachineInstr *MI) {
281 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
282}
283
284/// This function inserts clones of Filler into predecessor blocks.
285static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
286 MachineFunction *MF = Filler->getParent()->getParent();
287
288 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
289 if (I->second) {
290 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
291 ++UsefulSlots;
292 } else {
293 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
294 }
295 }
296}
297
298/// This function adds registers Filler defines to MBB's live-in register list.
299static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
300 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
301 const MachineOperand &MO = Filler->getOperand(I);
302 unsigned R;
303
304 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
305 continue;
306
307#ifndef NDEBUG
308 const MachineFunction &MF = *MBB.getParent();
Eric Christopher96e72c62015-01-29 23:27:36 +0000309 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000310 "Shouldn't move an instruction with unallocatable registers across "
311 "basic block boundaries.");
312#endif
313
314 if (!MBB.isLiveIn(R))
315 MBB.addLiveIn(R);
316 }
317}
318
Eric Christopher96e72c62015-01-29 23:27:36 +0000319RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
320 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
Akira Hatanaka979899e2013-02-26 01:30:05 +0000321
322void RegDefsUses::init(const MachineInstr &MI) {
323 // Add all register operands which are explicit and non-variadic.
324 update(MI, 0, MI.getDesc().getNumOperands());
325
326 // If MI is a call, add RA to Defs to prevent users of RA from going into
327 // delay slot.
328 if (MI.isCall())
329 Defs.set(Mips::RA);
330
331 // Add all implicit register operands of branch instructions except
332 // register AT.
333 if (MI.isBranch()) {
334 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
335 Defs.reset(Mips::AT);
336 }
337}
338
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000339void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
340 assert(MI.isCall());
341
Vasileios Kalintiris70b744e2015-05-14 13:17:56 +0000342 // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
343 // the delay slot. The reason is that RA/RA_64 must not be changed
344 // in the delay slot so that the callee can return to the caller.
345 if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
346 Defs.set(Mips::RA);
347 Defs.set(Mips::RA_64);
348 }
349
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000350 // If MI is a call, add all caller-saved registers to Defs.
351 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
352
353 CallerSavedRegs.reset(Mips::ZERO);
354 CallerSavedRegs.reset(Mips::ZERO_64);
355
Eric Christopher7af952872015-03-11 21:41:28 +0000356 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
357 *R; ++R)
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000358 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
359 CallerSavedRegs.reset(*AI);
360
361 Defs |= CallerSavedRegs;
362}
363
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000364void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
365 BitVector AllocSet = TRI.getAllocatableSet(MF);
366
367 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
368 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
369 AllocSet.set(*AI);
370
371 AllocSet.set(Mips::ZERO);
372 AllocSet.set(Mips::ZERO_64);
373
374 Defs |= AllocSet.flip();
375}
376
377void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
378 const MachineBasicBlock &SuccBB) {
379 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
380 SE = MBB.succ_end(); SI != SE; ++SI)
381 if (*SI != &SuccBB)
Matthias Braund9da1622015-09-09 18:08:03 +0000382 for (const auto &LI : (*SI)->liveins())
383 Uses.set(LI.PhysReg);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000384}
385
Akira Hatanaka979899e2013-02-26 01:30:05 +0000386bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
387 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
388 bool HasHazard = false;
389
390 for (unsigned I = Begin; I != End; ++I) {
391 const MachineOperand &MO = MI.getOperand(I);
392
393 if (MO.isReg() && MO.getReg())
394 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
395 }
396
397 Defs |= NewDefs;
398 Uses |= NewUses;
399
400 return HasHazard;
401}
402
403bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
404 unsigned Reg, bool IsDef) const {
405 if (IsDef) {
406 NewDefs.set(Reg);
407 // check whether Reg has already been defined or used.
408 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
409 }
410
411 NewUses.set(Reg);
412 // check whether Reg has already been defined.
413 return isRegInSet(Defs, Reg);
414}
415
416bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
417 // Check Reg and all aliased Registers.
418 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
419 if (RegSet.test(*AI))
420 return true;
421 return false;
422}
423
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000424bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000425 if (!MI.mayStore() && !MI.mayLoad())
426 return false;
427
428 if (ForbidMemInstr)
429 return true;
430
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000431 OrigSeenLoad = SeenLoad;
432 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000433 SeenLoad |= MI.mayLoad();
434 SeenStore |= MI.mayStore();
435
436 // If MI is an ordered or volatile memory reference, disallow moving
437 // subsequent loads and stores to delay slot.
438 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
439 ForbidMemInstr = true;
440 return true;
441 }
442
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000443 return hasHazard_(MI);
444}
445
446bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
447 if (MI.mayStore())
448 return true;
449
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000450 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000451 return true;
452
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000453 if (const PseudoSourceValue *PSV =
454 (*MI.memoperands_begin())->getPseudoValue()) {
455 if (isa<FixedStackPseudoSourceValue>(PSV))
456 return false;
Alex Lorenze40c8a22015-08-11 23:09:45 +0000457 return !PSV->isConstant(nullptr) && !PSV->isStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000458 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000459
460 return true;
461}
462
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000463MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
464 : InspectMemInstr(false), MFI(MFI_), DL(DL), SeenNoObjLoad(false),
465 SeenNoObjStore(false) {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000466
467bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000468 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000469 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000470
471 // Check underlying object list.
472 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000473 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000474 I != Objs.end(); ++I)
475 HasHazard |= updateDefsUses(*I, MI.mayStore());
476
477 return HasHazard;
478 }
479
480 // No underlying objects found.
481 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
482 HasHazard |= MI.mayLoad() || OrigSeenStore;
483
484 SeenNoObjLoad |= MI.mayLoad();
485 SeenNoObjStore |= MI.mayStore();
486
487 return HasHazard;
488}
489
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000490bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000491 if (MayStore)
David Blaikie70573dc2014-11-19 07:49:26 +0000492 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
493 SeenNoObjLoad;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000494
495 Uses.insert(V);
496 return Defs.count(V) || SeenNoObjStore;
497}
498
499bool MemDefsUses::
500getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000501 SmallVectorImpl<ValueType> &Objects) const {
502 if (!MI.hasOneMemOperand() ||
503 (!(*MI.memoperands_begin())->getValue() &&
504 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000505 return false;
506
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000507 if (const PseudoSourceValue *PSV =
508 (*MI.memoperands_begin())->getPseudoValue()) {
509 if (!PSV->isAliased(MFI))
510 return false;
511 Objects.push_back(PSV);
512 return true;
513 }
514
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000515 const Value *V = (*MI.memoperands_begin())->getValue();
516
517 SmallVector<Value *, 4> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000518 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000519
Craig Topper31ee5862013-07-03 15:07:05 +0000520 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000521 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000522 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000523 return false;
524
525 Objects.push_back(*I);
526 }
527
528 return true;
529}
530
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000531// Replace Branch with the compact branch instruction.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000532Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
533 const DebugLoc &DL) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000534 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
535 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000536
Daniel Sanderse8efff32016-03-14 16:24:05 +0000537 unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
538 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000539
Daniel Sanderse8efff32016-03-14 16:24:05 +0000540 std::next(Branch)->eraseFromParent();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000541 return Branch;
542}
543
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000544// For given opcode returns opcode of corresponding instruction with short
545// delay slot.
Simon Dardis57f4ae42016-08-04 09:17:07 +0000546// For the pseudo TAILCALL*_MM instrunctions return the short delay slot
547// form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
548// that is too short to make use of for tail calls.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000549static int getEquivalentCallShort(int Opcode) {
550 switch (Opcode) {
551 case Mips::BGEZAL:
552 return Mips::BGEZALS_MM;
553 case Mips::BLTZAL:
554 return Mips::BLTZALS_MM;
555 case Mips::JAL:
556 return Mips::JALS_MM;
557 case Mips::JALR:
558 return Mips::JALRS_MM;
559 case Mips::JALR16_MM:
560 return Mips::JALRS16_MM;
Simon Dardis57f4ae42016-08-04 09:17:07 +0000561 case Mips::TAILCALL_MM:
562 llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
Simon Dardisea343152016-08-18 13:22:43 +0000563 case Mips::TAILCALLREG:
Simon Dardis57f4ae42016-08-04 09:17:07 +0000564 return Mips::JR16_MM;
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000565 default:
566 llvm_unreachable("Unexpected call instruction for microMIPS.");
567 }
568}
569
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000570/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000571/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000572bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000573 bool Changed = false;
Eric Christopher6b6db772015-02-02 23:03:43 +0000574 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
Eric Christopher96e72c62015-01-29 23:27:36 +0000575 bool InMicroMipsMode = STI.inMicroMipsMode();
576 const MipsInstrInfo *TII = STI.getInstrInfo();
Akira Hatanakae7b06972011-10-05 01:30:09 +0000577
Hrvoje Vargac45baf22016-03-23 10:29:38 +0000578 if (InMicroMipsMode && STI.hasMips32r6()) {
579 // This is microMIPS32r6 or microMIPS64r6 processor. Delay slot for
580 // branching instructions is not needed.
581 return Changed;
582 }
583
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000584 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000585 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000586 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000587
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000588 ++FilledSlots;
589 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000590
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000591 // Delay slot filling is disabled at -O0.
592 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
593 bool Filled = false;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000594
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000595 if (MipsCompactBranchPolicy.getValue() != CB_Always ||
596 !TII->getEquivalentCompactForm(I)) {
597 if (searchBackward(MBB, I)) {
598 Filled = true;
599 } else if (I->isTerminator()) {
600 if (searchSuccBBs(MBB, I)) {
601 Filled = true;
602 }
603 } else if (searchForward(MBB, I)) {
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000604 Filled = true;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000605 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000606 }
607
608 if (Filled) {
609 // Get instruction with delay slot.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000610 MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000611
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000612 if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000613 DSI->isCall()) {
614 // If instruction in delay slot is 16b change opcode to
615 // corresponding instruction with short delay slot.
Simon Dardis57f4ae42016-08-04 09:17:07 +0000616
617 // TODO: Implement an instruction mapping table of 16bit opcodes to
618 // 32bit opcodes so that an instruction can be expanded. This would
619 // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
620 // TODO: Permit b16 when branching backwards to the the same function
621 // if it is in range.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000622 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
623 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000624 continue;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000625 }
626 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000627
Simon Dardisd9d41f52016-04-05 12:50:29 +0000628 // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
629 // instead of adding NOP replace this instruction with the corresponding
630 // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
631 // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
632 // be replaced with JRC16_MM.
Daniel Sanderse8efff32016-03-14 16:24:05 +0000633
634 // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
Simon Dardisd9d41f52016-04-05 12:50:29 +0000635 // form of the CTI. For indirect jumps this will not require inserting a
636 // NOP and for branches will hopefully avoid requiring a NOP.
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000637 if ((InMicroMipsMode ||
638 (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
639 TII->getEquivalentCompactForm(I)) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000640 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
641 continue;
642 }
643
Jozef Kolek650a61a2015-02-13 17:51:27 +0000644 // Bundle the NOP to the instruction with the delay slot.
645 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
646 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000647 }
648
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000649 return Changed;
650}
651
652/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
653/// slots in Mips MachineFunctions
654FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
655 return new Filler(tm);
656}
657
Akira Hatanakaf815db52013-03-01 00:26:14 +0000658template<typename IterTy>
659bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000660 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
661 IterTy &Filler) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000662 bool IsReverseIter = std::is_convertible<IterTy, ReverseIter>::value;
663
664 for (IterTy I = Begin; I != End;) {
665 IterTy CurrI = I;
666 ++I;
667
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000668 // skip debug value
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000669 if (CurrI->isDebugValue())
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000670 continue;
671
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000672 if (terminateSearch(*CurrI))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000673 break;
674
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000675 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000676 "Cannot put calls, returns or branches in delay slot.");
677
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000678 if (CurrI->isKill()) {
679 CurrI->eraseFromParent();
680
681 // This special case is needed for reverse iterators, because when we
682 // erase an instruction, the iterators are updated to point to the next
683 // instruction.
684 if (IsReverseIter && I != End)
685 I = CurrI;
686 continue;
687 }
688
689 if (delayHasHazard(*CurrI, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000690 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000691
Eric Christopher6b6db772015-02-02 23:03:43 +0000692 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
693 if (STI.isTargetNaCl()) {
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000694 // In NaCl, instructions that must be masked are forbidden in delay slots.
695 // We only check for loads, stores and SP changes. Calls, returns and
696 // branches are not checked because non-NaCl targets never put them in
697 // delay slots.
698 unsigned AddrIdx;
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000699 if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
700 baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
701 CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000702 continue;
703 }
704
Eric Christopher6b6db772015-02-02 23:03:43 +0000705 bool InMicroMipsMode = STI.inMicroMipsMode();
706 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000707 unsigned Opcode = (*Slot).getOpcode();
Simon Dardis57f4ae42016-08-04 09:17:07 +0000708 // This is complicated by the tail call optimization. For non-PIC code
709 // there is only a 32bit sized unconditional branch which can be assumed
710 // to be able to reach the target. b16 only has a range of +/- 1 KB.
711 // It's entirely possible that the target function is reachable with b16
712 // but we don't have enough information to make that decision.
713 if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000714 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
Simon Dardis57f4ae42016-08-04 09:17:07 +0000715 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000716 continue;
717
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000718 Filler = CurrI;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000719 return true;
720 }
721
722 return false;
723}
724
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000725bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000726 if (DisableBackwardSearch)
727 return false;
728
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000729 auto *Fn = MBB.getParent();
730 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
Matthias Braun941a7052016-07-28 18:40:00 +0000731 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000732 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000733
734 RegDU.init(*Slot);
735
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000736 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Slot,
737 Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000738 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000739
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000740 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
741 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000742 ++UsefulSlots;
743 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000744}
745
746bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
747 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000748 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000749 return false;
750
Eric Christopher96e72c62015-01-29 23:27:36 +0000751 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000752 NoMemInstr NM;
753 Iter Filler;
754
755 RegDU.setCallerSaved(*Slot);
756
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000757 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000758 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000759
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000760 MBB.splice(std::next(Slot), &MBB, Filler);
761 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000762 ++UsefulSlots;
763 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000764}
765
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000766bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
767 if (DisableSuccBBSearch)
768 return false;
769
770 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
771
772 if (!SuccBB)
773 return false;
774
Eric Christopher96e72c62015-01-29 23:27:36 +0000775 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000776 bool HasMultipleSuccs = false;
777 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000778 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000779 Iter Filler;
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000780 auto *Fn = MBB.getParent();
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000781
782 // Iterate over SuccBB's predecessor list.
783 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
784 PE = SuccBB->pred_end(); PI != PE; ++PI)
785 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
786 return false;
787
788 // Do not allow moving instructions which have unallocatable register operands
789 // across basic block boundaries.
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000790 RegDU.setUnallocatableRegs(*Fn);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000791
792 // Only allow moving loads from stack or constants if any of the SuccBB's
793 // predecessors have multiple successors.
794 if (HasMultipleSuccs) {
795 IM.reset(new LoadFromStackOrConst());
796 } else {
Matthias Braun941a7052016-07-28 18:40:00 +0000797 const MachineFrameInfo &MFI = Fn->getFrameInfo();
798 IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000799 }
800
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000801 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
802 Filler))
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000803 return false;
804
805 insertDelayFiller(Filler, BrMap);
806 addLiveInRegs(Filler, *SuccBB);
807 Filler->eraseFromParent();
808
809 return true;
810}
811
812MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
813 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000814 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000815
816 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000817 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
Cong Hou1938f2e2015-11-24 08:51:23 +0000818 MachineBasicBlock *S = *std::max_element(
819 B.succ_begin(), B.succ_end(),
820 [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
821 return Prob.getEdgeProbability(&B, Dst0) <
822 Prob.getEdgeProbability(&B, Dst1);
823 });
Reid Kleckner0e288232015-08-27 23:27:47 +0000824 return S->isEHPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000825}
826
827std::pair<MipsInstrInfo::BranchType, MachineInstr *>
828Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
Eric Christopher6b6db772015-02-02 23:03:43 +0000829 const MipsInstrInfo *TII =
830 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +0000831 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000832 SmallVector<MachineInstr*, 2> BranchInstrs;
833 SmallVector<MachineOperand, 2> Cond;
834
835 MipsInstrInfo::BranchType R =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000836 TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000837
838 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000839 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000840
841 if (R != MipsInstrInfo::BT_CondUncond) {
842 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000843 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000844
845 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
846
847 return std::make_pair(R, BranchInstrs[0]);
848 }
849
850 assert((TrueBB == &Dst) || (FalseBB == &Dst));
851
852 // Examine the conditional branch. See if its slot is occupied.
853 if (hasUnoccupiedSlot(BranchInstrs[0]))
854 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
855
856 // If that fails, try the unconditional branch.
857 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
858 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
859
Craig Topper062a2ba2014-04-25 05:30:21 +0000860 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000861}
862
863bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
864 RegDefsUses &RegDU, bool &HasMultipleSuccs,
865 BB2BrMap &BrMap) const {
866 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
867 getBranch(Pred, Succ);
868
869 // Return if either getBranch wasn't able to analyze the branches or there
870 // were no branches with unoccupied slots.
871 if (P.first == MipsInstrInfo::BT_None)
872 return false;
873
874 if ((P.first != MipsInstrInfo::BT_Uncond) &&
875 (P.first != MipsInstrInfo::BT_NoBranch)) {
876 HasMultipleSuccs = true;
877 RegDU.addLiveOut(Pred, Succ);
878 }
879
880 BrMap[&Pred] = P.second;
881 return true;
882}
883
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000884bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000885 InspectMemInstr &IM) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000886 assert(!Candidate.isKill() &&
887 "KILL instructions should have been eliminated at this point.");
888
889 bool HasHazard = Candidate.isImplicitDef();
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000890
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000891 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000892 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000893
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000894 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000895}
896
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000897bool Filler::terminateSearch(const MachineInstr &Candidate) const {
898 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000899 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000900 Candidate.hasUnmodeledSideEffects());
901}