blob: c821084f68cfb8bccd307185fced59bf1ec39560 [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)."),
Mehdi Amini732afdd2016-10-08 19:41:06 +000082 clEnumValN(CB_Always, "always", "Always use compact branches if possible.")
Simon Dardis8d8f2f82016-05-17 10:21:43 +000083 )
84);
85
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000086namespace {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000087 typedef MachineBasicBlock::iterator Iter;
88 typedef MachineBasicBlock::reverse_iterator ReverseIter;
89 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
90
Akira Hatanaka979899e2013-02-26 01:30:05 +000091 class RegDefsUses {
92 public:
Eric Christopher96e72c62015-01-29 23:27:36 +000093 RegDefsUses(const TargetRegisterInfo &TRI);
Akira Hatanaka979899e2013-02-26 01:30:05 +000094 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000095
96 /// This function sets all caller-saved registers in Defs.
97 void setCallerSaved(const MachineInstr &MI);
98
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000099 /// This function sets all unallocatable registers in Defs.
100 void setUnallocatableRegs(const MachineFunction &MF);
101
102 /// Set bits in Uses corresponding to MBB's live-out registers except for
103 /// the registers that are live-in to SuccBB.
104 void addLiveOut(const MachineBasicBlock &MBB,
105 const MachineBasicBlock &SuccBB);
106
Akira Hatanaka979899e2013-02-26 01:30:05 +0000107 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
108
109 private:
110 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
111 bool IsDef) const;
112
113 /// Returns true if Reg or its alias is in RegSet.
114 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
115
116 const TargetRegisterInfo &TRI;
117 BitVector Defs, Uses;
118 };
119
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000120 /// Base class for inspecting loads and stores.
121 class InspectMemInstr {
122 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000123 InspectMemInstr(bool ForbidMemInstr_)
124 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
125 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
126
127 /// Return true if MI cannot be moved to delay slot.
128 bool hasHazard(const MachineInstr &MI);
129
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000130 virtual ~InspectMemInstr() {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000131
132 protected:
133 /// Flags indicating whether loads or stores have been seen.
134 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
135
136 /// Memory instructions are not allowed to move to delay slot if this flag
137 /// is true.
138 bool ForbidMemInstr;
139
140 private:
141 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000142 };
143
144 /// This subclass rejects any memory instructions.
145 class NoMemInstr : public InspectMemInstr {
146 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000147 NoMemInstr() : InspectMemInstr(true) {}
148 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000149 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000150 };
151
152 /// This subclass accepts loads from stacks and constant loads.
153 class LoadFromStackOrConst : public InspectMemInstr {
154 public:
155 LoadFromStackOrConst() : InspectMemInstr(false) {}
156 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000157 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000158 };
159
160 /// This subclass uses memory dependence information to determine whether a
161 /// memory instruction can be moved to a delay slot.
162 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000163 public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000164 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000165
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000166 private:
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000167 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
168
Craig Topper56c590a2014-04-29 07:58:02 +0000169 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000170
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000171 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000172 /// disqualify the delay slot candidate between V and values in Uses and
173 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000174 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000175
176 /// Get the list of underlying objects of MI's memory operand.
177 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000178 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000179
180 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000181 SmallPtrSet<ValueType, 4> Uses, Defs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000182 const DataLayout &DL;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000183
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000184 /// Flags indicating whether loads or stores with no underlying objects have
185 /// been seen.
186 bool SeenNoObjLoad, SeenNoObjStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000187 };
188
Akira Hatanakaa0612812013-02-07 21:32:32 +0000189 class Filler : public MachineFunctionPass {
190 public:
Bruno Cardoso Lopesfde21cf2010-12-09 17:31:11 +0000191 Filler(TargetMachine &tm)
Bill Wendlingead89ef2013-06-07 07:04:14 +0000192 : MachineFunctionPass(ID), TM(tm) { }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000193
Mehdi Amini117296c2016-10-01 02:56:57 +0000194 StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000195
Craig Topper56c590a2014-04-29 07:58:02 +0000196 bool runOnMachineFunction(MachineFunction &F) override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000197 bool Changed = false;
198 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
199 FI != FE; ++FI)
200 Changed |= runOnMachineBasicBlock(*FI);
Daniel Sanders308181e2014-06-12 10:44:10 +0000201
202 // This pass invalidates liveness information when it reorders
203 // instructions to fill delay slot. Without this, -verify-machineinstrs
204 // will fail.
205 if (Changed)
206 F.getRegInfo().invalidateLiveness();
207
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000208 return Changed;
209 }
210
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000211 MachineFunctionProperties getRequiredProperties() const override {
212 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000213 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000214 }
215
Craig Topper56c590a2014-04-29 07:58:02 +0000216 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000217 AU.addRequired<MachineBranchProbabilityInfo>();
218 MachineFunctionPass::getAnalysisUsage(AU);
219 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000220
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000221 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000222 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
223
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000224 Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
225 const DebugLoc &DL);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000226
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000227 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000228 /// and returns true if it isn't. It also updates memory and register
229 /// dependence information.
230 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000231 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000232
Akira Hatanakaf815db52013-03-01 00:26:14 +0000233 /// This function searches range [Begin, End) for an instruction that can be
234 /// moved to the delay slot. Returns true on success.
235 template<typename IterTy>
236 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000237 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
238 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000239
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000240 /// This function searches in the backward direction for an instruction that
241 /// can be moved to the delay slot. Returns true on success.
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000242 bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000243
244 /// This function searches MBB in the forward direction for an instruction
245 /// that can be moved to the delay slot. Returns true on success.
246 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000247
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000248 /// This function searches one of MBB's successor blocks for an instruction
249 /// that can be moved to the delay slot and inserts clones of the
250 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000251 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
252
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000253 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
254 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000255 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
256
257 /// This function analyzes MBB and returns an instruction with an unoccupied
258 /// slot that branches to Dst.
259 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
260 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
261
262 /// Examine Pred and see if it is possible to insert an instruction into
263 /// one of its branches delay slot or its end.
264 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
265 RegDefsUses &RegDU, bool &HasMultipleSuccs,
266 BB2BrMap &BrMap) const;
267
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000268 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000269
Akira Hatanakaa0612812013-02-07 21:32:32 +0000270 TargetMachine &TM;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000271
Akira Hatanakaa0612812013-02-07 21:32:32 +0000272 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000273 };
274 char Filler::ID = 0;
275} // end of anonymous namespace
276
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000277static bool hasUnoccupiedSlot(const MachineInstr *MI) {
278 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
279}
280
281/// This function inserts clones of Filler into predecessor blocks.
282static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
283 MachineFunction *MF = Filler->getParent()->getParent();
284
285 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
286 if (I->second) {
287 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
288 ++UsefulSlots;
289 } else {
290 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
291 }
292 }
293}
294
295/// This function adds registers Filler defines to MBB's live-in register list.
296static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
297 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
298 const MachineOperand &MO = Filler->getOperand(I);
299 unsigned R;
300
301 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
302 continue;
303
304#ifndef NDEBUG
305 const MachineFunction &MF = *MBB.getParent();
Eric Christopher96e72c62015-01-29 23:27:36 +0000306 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000307 "Shouldn't move an instruction with unallocatable registers across "
308 "basic block boundaries.");
309#endif
310
311 if (!MBB.isLiveIn(R))
312 MBB.addLiveIn(R);
313 }
314}
315
Eric Christopher96e72c62015-01-29 23:27:36 +0000316RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
317 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
Akira Hatanaka979899e2013-02-26 01:30:05 +0000318
319void RegDefsUses::init(const MachineInstr &MI) {
320 // Add all register operands which are explicit and non-variadic.
321 update(MI, 0, MI.getDesc().getNumOperands());
322
323 // If MI is a call, add RA to Defs to prevent users of RA from going into
324 // delay slot.
325 if (MI.isCall())
326 Defs.set(Mips::RA);
327
328 // Add all implicit register operands of branch instructions except
329 // register AT.
330 if (MI.isBranch()) {
331 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
332 Defs.reset(Mips::AT);
333 }
334}
335
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000336void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
337 assert(MI.isCall());
338
Vasileios Kalintiris70b744e2015-05-14 13:17:56 +0000339 // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
340 // the delay slot. The reason is that RA/RA_64 must not be changed
341 // in the delay slot so that the callee can return to the caller.
342 if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
343 Defs.set(Mips::RA);
344 Defs.set(Mips::RA_64);
345 }
346
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000347 // If MI is a call, add all caller-saved registers to Defs.
348 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
349
350 CallerSavedRegs.reset(Mips::ZERO);
351 CallerSavedRegs.reset(Mips::ZERO_64);
352
Eric Christopher7af952872015-03-11 21:41:28 +0000353 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
354 *R; ++R)
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000355 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
356 CallerSavedRegs.reset(*AI);
357
358 Defs |= CallerSavedRegs;
359}
360
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000361void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
362 BitVector AllocSet = TRI.getAllocatableSet(MF);
363
364 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
365 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
366 AllocSet.set(*AI);
367
368 AllocSet.set(Mips::ZERO);
369 AllocSet.set(Mips::ZERO_64);
370
371 Defs |= AllocSet.flip();
372}
373
374void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
375 const MachineBasicBlock &SuccBB) {
376 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
377 SE = MBB.succ_end(); SI != SE; ++SI)
378 if (*SI != &SuccBB)
Matthias Braund9da1622015-09-09 18:08:03 +0000379 for (const auto &LI : (*SI)->liveins())
380 Uses.set(LI.PhysReg);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000381}
382
Akira Hatanaka979899e2013-02-26 01:30:05 +0000383bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
384 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
385 bool HasHazard = false;
386
387 for (unsigned I = Begin; I != End; ++I) {
388 const MachineOperand &MO = MI.getOperand(I);
389
390 if (MO.isReg() && MO.getReg())
391 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
392 }
393
394 Defs |= NewDefs;
395 Uses |= NewUses;
396
397 return HasHazard;
398}
399
400bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
401 unsigned Reg, bool IsDef) const {
402 if (IsDef) {
403 NewDefs.set(Reg);
404 // check whether Reg has already been defined or used.
405 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
406 }
407
408 NewUses.set(Reg);
409 // check whether Reg has already been defined.
410 return isRegInSet(Defs, Reg);
411}
412
413bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
414 // Check Reg and all aliased Registers.
415 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
416 if (RegSet.test(*AI))
417 return true;
418 return false;
419}
420
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000421bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000422 if (!MI.mayStore() && !MI.mayLoad())
423 return false;
424
425 if (ForbidMemInstr)
426 return true;
427
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000428 OrigSeenLoad = SeenLoad;
429 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000430 SeenLoad |= MI.mayLoad();
431 SeenStore |= MI.mayStore();
432
433 // If MI is an ordered or volatile memory reference, disallow moving
434 // subsequent loads and stores to delay slot.
435 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
436 ForbidMemInstr = true;
437 return true;
438 }
439
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000440 return hasHazard_(MI);
441}
442
443bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
444 if (MI.mayStore())
445 return true;
446
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000447 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000448 return true;
449
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000450 if (const PseudoSourceValue *PSV =
451 (*MI.memoperands_begin())->getPseudoValue()) {
452 if (isa<FixedStackPseudoSourceValue>(PSV))
453 return false;
Alex Lorenze40c8a22015-08-11 23:09:45 +0000454 return !PSV->isConstant(nullptr) && !PSV->isStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000455 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000456
457 return true;
458}
459
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000460MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
461 : InspectMemInstr(false), MFI(MFI_), DL(DL), SeenNoObjLoad(false),
462 SeenNoObjStore(false) {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000463
464bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000465 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000466 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000467
468 // Check underlying object list.
469 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000470 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000471 I != Objs.end(); ++I)
472 HasHazard |= updateDefsUses(*I, MI.mayStore());
473
474 return HasHazard;
475 }
476
477 // No underlying objects found.
478 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
479 HasHazard |= MI.mayLoad() || OrigSeenStore;
480
481 SeenNoObjLoad |= MI.mayLoad();
482 SeenNoObjStore |= MI.mayStore();
483
484 return HasHazard;
485}
486
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000487bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000488 if (MayStore)
David Blaikie70573dc2014-11-19 07:49:26 +0000489 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
490 SeenNoObjLoad;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000491
492 Uses.insert(V);
493 return Defs.count(V) || SeenNoObjStore;
494}
495
496bool MemDefsUses::
497getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000498 SmallVectorImpl<ValueType> &Objects) const {
499 if (!MI.hasOneMemOperand() ||
500 (!(*MI.memoperands_begin())->getValue() &&
501 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000502 return false;
503
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000504 if (const PseudoSourceValue *PSV =
505 (*MI.memoperands_begin())->getPseudoValue()) {
506 if (!PSV->isAliased(MFI))
507 return false;
508 Objects.push_back(PSV);
509 return true;
510 }
511
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000512 const Value *V = (*MI.memoperands_begin())->getValue();
513
514 SmallVector<Value *, 4> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000515 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000516
Craig Topper31ee5862013-07-03 15:07:05 +0000517 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000518 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000519 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000520 return false;
521
522 Objects.push_back(*I);
523 }
524
525 return true;
526}
527
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000528// Replace Branch with the compact branch instruction.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000529Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
530 const DebugLoc &DL) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000531 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
532 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000533
Daniel Sanderse8efff32016-03-14 16:24:05 +0000534 unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
535 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000536
Daniel Sanderse8efff32016-03-14 16:24:05 +0000537 std::next(Branch)->eraseFromParent();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000538 return Branch;
539}
540
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000541// For given opcode returns opcode of corresponding instruction with short
542// delay slot.
Simon Dardis57f4ae42016-08-04 09:17:07 +0000543// For the pseudo TAILCALL*_MM instrunctions return the short delay slot
544// form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
545// that is too short to make use of for tail calls.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000546static int getEquivalentCallShort(int Opcode) {
547 switch (Opcode) {
548 case Mips::BGEZAL:
549 return Mips::BGEZALS_MM;
550 case Mips::BLTZAL:
551 return Mips::BLTZALS_MM;
552 case Mips::JAL:
553 return Mips::JALS_MM;
554 case Mips::JALR:
555 return Mips::JALRS_MM;
556 case Mips::JALR16_MM:
557 return Mips::JALRS16_MM;
Simon Dardis57f4ae42016-08-04 09:17:07 +0000558 case Mips::TAILCALL_MM:
559 llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
Simon Dardisea343152016-08-18 13:22:43 +0000560 case Mips::TAILCALLREG:
Simon Dardis57f4ae42016-08-04 09:17:07 +0000561 return Mips::JR16_MM;
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000562 default:
563 llvm_unreachable("Unexpected call instruction for microMIPS.");
564 }
565}
566
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000567/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000568/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000569bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000570 bool Changed = false;
Eric Christopher6b6db772015-02-02 23:03:43 +0000571 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
Eric Christopher96e72c62015-01-29 23:27:36 +0000572 bool InMicroMipsMode = STI.inMicroMipsMode();
573 const MipsInstrInfo *TII = STI.getInstrInfo();
Akira Hatanakae7b06972011-10-05 01:30:09 +0000574
Hrvoje Vargac45baf22016-03-23 10:29:38 +0000575 if (InMicroMipsMode && STI.hasMips32r6()) {
576 // This is microMIPS32r6 or microMIPS64r6 processor. Delay slot for
577 // branching instructions is not needed.
578 return Changed;
579 }
580
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000581 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000582 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000583 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000584
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000585 ++FilledSlots;
586 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000587
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000588 // Delay slot filling is disabled at -O0.
589 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
590 bool Filled = false;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000591
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000592 if (MipsCompactBranchPolicy.getValue() != CB_Always ||
593 !TII->getEquivalentCompactForm(I)) {
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000594 if (searchBackward(MBB, *I)) {
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000595 Filled = true;
596 } else if (I->isTerminator()) {
597 if (searchSuccBBs(MBB, I)) {
598 Filled = true;
599 }
600 } else if (searchForward(MBB, I)) {
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000601 Filled = true;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000602 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000603 }
604
605 if (Filled) {
606 // Get instruction with delay slot.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000607 MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000608
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000609 if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000610 DSI->isCall()) {
611 // If instruction in delay slot is 16b change opcode to
612 // corresponding instruction with short delay slot.
Simon Dardis57f4ae42016-08-04 09:17:07 +0000613
614 // TODO: Implement an instruction mapping table of 16bit opcodes to
615 // 32bit opcodes so that an instruction can be expanded. This would
616 // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
617 // TODO: Permit b16 when branching backwards to the the same function
618 // if it is in range.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000619 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
620 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000621 continue;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000622 }
623 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000624
Simon Dardisd9d41f52016-04-05 12:50:29 +0000625 // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
626 // instead of adding NOP replace this instruction with the corresponding
627 // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
628 // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
629 // be replaced with JRC16_MM.
Daniel Sanderse8efff32016-03-14 16:24:05 +0000630
631 // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
Simon Dardisd9d41f52016-04-05 12:50:29 +0000632 // form of the CTI. For indirect jumps this will not require inserting a
633 // NOP and for branches will hopefully avoid requiring a NOP.
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000634 if ((InMicroMipsMode ||
635 (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
636 TII->getEquivalentCompactForm(I)) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000637 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
638 continue;
639 }
640
Jozef Kolek650a61a2015-02-13 17:51:27 +0000641 // Bundle the NOP to the instruction with the delay slot.
642 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
643 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000644 }
645
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000646 return Changed;
647}
648
649/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
650/// slots in Mips MachineFunctions
651FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
652 return new Filler(tm);
653}
654
Akira Hatanakaf815db52013-03-01 00:26:14 +0000655template<typename IterTy>
656bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000657 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
658 IterTy &Filler) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000659 for (IterTy I = Begin; I != End;) {
660 IterTy CurrI = I;
661 ++I;
662
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000663 // skip debug value
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000664 if (CurrI->isDebugValue())
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000665 continue;
666
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000667 if (terminateSearch(*CurrI))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000668 break;
669
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000670 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000671 "Cannot put calls, returns or branches in delay slot.");
672
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000673 if (CurrI->isKill()) {
674 CurrI->eraseFromParent();
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000675 continue;
676 }
677
678 if (delayHasHazard(*CurrI, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000679 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000680
Eric Christopher6b6db772015-02-02 23:03:43 +0000681 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
682 if (STI.isTargetNaCl()) {
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000683 // In NaCl, instructions that must be masked are forbidden in delay slots.
684 // We only check for loads, stores and SP changes. Calls, returns and
685 // branches are not checked because non-NaCl targets never put them in
686 // delay slots.
687 unsigned AddrIdx;
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000688 if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
689 baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
690 CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000691 continue;
692 }
693
Eric Christopher6b6db772015-02-02 23:03:43 +0000694 bool InMicroMipsMode = STI.inMicroMipsMode();
695 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000696 unsigned Opcode = (*Slot).getOpcode();
Simon Dardis57f4ae42016-08-04 09:17:07 +0000697 // This is complicated by the tail call optimization. For non-PIC code
698 // there is only a 32bit sized unconditional branch which can be assumed
699 // to be able to reach the target. b16 only has a range of +/- 1 KB.
700 // It's entirely possible that the target function is reachable with b16
701 // but we don't have enough information to make that decision.
702 if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000703 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
Simon Dardis57f4ae42016-08-04 09:17:07 +0000704 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000705 continue;
706
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000707 Filler = CurrI;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000708 return true;
709 }
710
711 return false;
712}
713
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000714bool Filler::searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000715 if (DisableBackwardSearch)
716 return false;
717
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000718 auto *Fn = MBB.getParent();
719 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
Matthias Braun941a7052016-07-28 18:40:00 +0000720 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000721 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000722
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000723 RegDU.init(Slot);
Akira Hatanakaf815db52013-03-01 00:26:14 +0000724
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000725 MachineBasicBlock::iterator SlotI = Slot;
726 if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000727 Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000728 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000729
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000730 MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
731 MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000732 ++UsefulSlots;
733 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000734}
735
736bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
737 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000738 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000739 return false;
740
Eric Christopher96e72c62015-01-29 23:27:36 +0000741 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000742 NoMemInstr NM;
743 Iter Filler;
744
745 RegDU.setCallerSaved(*Slot);
746
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000747 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000748 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000749
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000750 MBB.splice(std::next(Slot), &MBB, Filler);
751 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000752 ++UsefulSlots;
753 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000754}
755
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000756bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
757 if (DisableSuccBBSearch)
758 return false;
759
760 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
761
762 if (!SuccBB)
763 return false;
764
Eric Christopher96e72c62015-01-29 23:27:36 +0000765 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000766 bool HasMultipleSuccs = false;
767 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000768 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000769 Iter Filler;
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000770 auto *Fn = MBB.getParent();
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000771
772 // Iterate over SuccBB's predecessor list.
773 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
774 PE = SuccBB->pred_end(); PI != PE; ++PI)
775 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
776 return false;
777
778 // Do not allow moving instructions which have unallocatable register operands
779 // across basic block boundaries.
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000780 RegDU.setUnallocatableRegs(*Fn);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000781
782 // Only allow moving loads from stack or constants if any of the SuccBB's
783 // predecessors have multiple successors.
784 if (HasMultipleSuccs) {
785 IM.reset(new LoadFromStackOrConst());
786 } else {
Matthias Braun941a7052016-07-28 18:40:00 +0000787 const MachineFrameInfo &MFI = Fn->getFrameInfo();
788 IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000789 }
790
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000791 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
792 Filler))
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000793 return false;
794
795 insertDelayFiller(Filler, BrMap);
796 addLiveInRegs(Filler, *SuccBB);
797 Filler->eraseFromParent();
798
799 return true;
800}
801
802MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
803 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000804 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000805
806 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000807 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
Cong Hou1938f2e2015-11-24 08:51:23 +0000808 MachineBasicBlock *S = *std::max_element(
809 B.succ_begin(), B.succ_end(),
810 [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
811 return Prob.getEdgeProbability(&B, Dst0) <
812 Prob.getEdgeProbability(&B, Dst1);
813 });
Reid Kleckner0e288232015-08-27 23:27:47 +0000814 return S->isEHPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000815}
816
817std::pair<MipsInstrInfo::BranchType, MachineInstr *>
818Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
Eric Christopher6b6db772015-02-02 23:03:43 +0000819 const MipsInstrInfo *TII =
820 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +0000821 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000822 SmallVector<MachineInstr*, 2> BranchInstrs;
823 SmallVector<MachineOperand, 2> Cond;
824
825 MipsInstrInfo::BranchType R =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000826 TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000827
828 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000829 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000830
831 if (R != MipsInstrInfo::BT_CondUncond) {
832 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000833 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000834
835 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
836
837 return std::make_pair(R, BranchInstrs[0]);
838 }
839
840 assert((TrueBB == &Dst) || (FalseBB == &Dst));
841
842 // Examine the conditional branch. See if its slot is occupied.
843 if (hasUnoccupiedSlot(BranchInstrs[0]))
844 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
845
846 // If that fails, try the unconditional branch.
847 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
848 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
849
Craig Topper062a2ba2014-04-25 05:30:21 +0000850 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000851}
852
853bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
854 RegDefsUses &RegDU, bool &HasMultipleSuccs,
855 BB2BrMap &BrMap) const {
856 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
857 getBranch(Pred, Succ);
858
859 // Return if either getBranch wasn't able to analyze the branches or there
860 // were no branches with unoccupied slots.
861 if (P.first == MipsInstrInfo::BT_None)
862 return false;
863
864 if ((P.first != MipsInstrInfo::BT_Uncond) &&
865 (P.first != MipsInstrInfo::BT_NoBranch)) {
866 HasMultipleSuccs = true;
867 RegDU.addLiveOut(Pred, Succ);
868 }
869
870 BrMap[&Pred] = P.second;
871 return true;
872}
873
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000874bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000875 InspectMemInstr &IM) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000876 assert(!Candidate.isKill() &&
877 "KILL instructions should have been eliminated at this point.");
878
879 bool HasHazard = Candidate.isImplicitDef();
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000880
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000881 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000882 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000883
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000884 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000885}
886
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000887bool Filler::terminateSearch(const MachineInstr &Candidate) const {
888 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000889 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000890 Candidate.hasUnmodeledSideEffects());
891}