blob: bcfbc12df01c96ed0a1cf7aafd40808e0c01e041 [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
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000065namespace {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000066 typedef MachineBasicBlock::iterator Iter;
67 typedef MachineBasicBlock::reverse_iterator ReverseIter;
68 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
69
Akira Hatanaka979899e2013-02-26 01:30:05 +000070 class RegDefsUses {
71 public:
72 RegDefsUses(TargetMachine &TM);
73 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000074
75 /// This function sets all caller-saved registers in Defs.
76 void setCallerSaved(const MachineInstr &MI);
77
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000078 /// This function sets all unallocatable registers in Defs.
79 void setUnallocatableRegs(const MachineFunction &MF);
80
81 /// Set bits in Uses corresponding to MBB's live-out registers except for
82 /// the registers that are live-in to SuccBB.
83 void addLiveOut(const MachineBasicBlock &MBB,
84 const MachineBasicBlock &SuccBB);
85
Akira Hatanaka979899e2013-02-26 01:30:05 +000086 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
87
88 private:
89 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
90 bool IsDef) const;
91
92 /// Returns true if Reg or its alias is in RegSet.
93 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
94
95 const TargetRegisterInfo &TRI;
96 BitVector Defs, Uses;
97 };
98
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000099 /// Base class for inspecting loads and stores.
100 class InspectMemInstr {
101 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000102 InspectMemInstr(bool ForbidMemInstr_)
103 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
104 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
105
106 /// Return true if MI cannot be moved to delay slot.
107 bool hasHazard(const MachineInstr &MI);
108
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000109 virtual ~InspectMemInstr() {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000110
111 protected:
112 /// Flags indicating whether loads or stores have been seen.
113 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
114
115 /// Memory instructions are not allowed to move to delay slot if this flag
116 /// is true.
117 bool ForbidMemInstr;
118
119 private:
120 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000121 };
122
123 /// This subclass rejects any memory instructions.
124 class NoMemInstr : public InspectMemInstr {
125 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000126 NoMemInstr() : InspectMemInstr(true) {}
127 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000128 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000129 };
130
131 /// This subclass accepts loads from stacks and constant loads.
132 class LoadFromStackOrConst : public InspectMemInstr {
133 public:
134 LoadFromStackOrConst() : InspectMemInstr(false) {}
135 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000136 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000137 };
138
139 /// This subclass uses memory dependence information to determine whether a
140 /// memory instruction can be moved to a delay slot.
141 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000142 public:
143 MemDefsUses(const MachineFrameInfo *MFI);
144
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000145 private:
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000146 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
147
Craig Topper56c590a2014-04-29 07:58:02 +0000148 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000149
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000150 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000151 /// disqualify the delay slot candidate between V and values in Uses and
152 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000153 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000154
155 /// Get the list of underlying objects of MI's memory operand.
156 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000157 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000158
159 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000160 SmallPtrSet<ValueType, 4> Uses, Defs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000161
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000162 /// Flags indicating whether loads or stores with no underlying objects have
163 /// been seen.
164 bool SeenNoObjLoad, SeenNoObjStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000165 };
166
Akira Hatanakaa0612812013-02-07 21:32:32 +0000167 class Filler : public MachineFunctionPass {
168 public:
Bruno Cardoso Lopesfde21cf2010-12-09 17:31:11 +0000169 Filler(TargetMachine &tm)
Bill Wendlingead89ef2013-06-07 07:04:14 +0000170 : MachineFunctionPass(ID), TM(tm) { }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000171
Craig Topper56c590a2014-04-29 07:58:02 +0000172 const char *getPassName() const override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000173 return "Mips Delay Slot Filler";
174 }
175
Craig Topper56c590a2014-04-29 07:58:02 +0000176 bool runOnMachineFunction(MachineFunction &F) override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000177 bool Changed = false;
178 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
179 FI != FE; ++FI)
180 Changed |= runOnMachineBasicBlock(*FI);
Daniel Sanders308181e2014-06-12 10:44:10 +0000181
182 // This pass invalidates liveness information when it reorders
183 // instructions to fill delay slot. Without this, -verify-machineinstrs
184 // will fail.
185 if (Changed)
186 F.getRegInfo().invalidateLiveness();
187
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000188 return Changed;
189 }
190
Craig Topper56c590a2014-04-29 07:58:02 +0000191 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000192 AU.addRequired<MachineBranchProbabilityInfo>();
193 MachineFunctionPass::getAnalysisUsage(AU);
194 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000195
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000196 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000197 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
198
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000199 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000200 /// and returns true if it isn't. It also updates memory and register
201 /// dependence information.
202 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000203 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000204
Akira Hatanakaf815db52013-03-01 00:26:14 +0000205 /// This function searches range [Begin, End) for an instruction that can be
206 /// moved to the delay slot. Returns true on success.
207 template<typename IterTy>
208 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000209 RegDefsUses &RegDU, InspectMemInstr &IM,
210 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000211
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000212 /// This function searches in the backward direction for an instruction that
213 /// can be moved to the delay slot. Returns true on success.
214 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
215
216 /// This function searches MBB in the forward direction for an instruction
217 /// that can be moved to the delay slot. Returns true on success.
218 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000219
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000220 /// This function searches one of MBB's successor blocks for an instruction
221 /// that can be moved to the delay slot and inserts clones of the
222 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000223 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
224
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000225 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
226 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000227 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
228
229 /// This function analyzes MBB and returns an instruction with an unoccupied
230 /// slot that branches to Dst.
231 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
232 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
233
234 /// Examine Pred and see if it is possible to insert an instruction into
235 /// one of its branches delay slot or its end.
236 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
237 RegDefsUses &RegDU, bool &HasMultipleSuccs,
238 BB2BrMap &BrMap) const;
239
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000240 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000241
Akira Hatanakaa0612812013-02-07 21:32:32 +0000242 TargetMachine &TM;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000243
Akira Hatanakaa0612812013-02-07 21:32:32 +0000244 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000245 };
246 char Filler::ID = 0;
247} // end of anonymous namespace
248
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000249static bool hasUnoccupiedSlot(const MachineInstr *MI) {
250 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
251}
252
253/// This function inserts clones of Filler into predecessor blocks.
254static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
255 MachineFunction *MF = Filler->getParent()->getParent();
256
257 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
258 if (I->second) {
259 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
260 ++UsefulSlots;
261 } else {
262 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
263 }
264 }
265}
266
267/// This function adds registers Filler defines to MBB's live-in register list.
268static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
269 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
270 const MachineOperand &MO = Filler->getOperand(I);
271 unsigned R;
272
273 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
274 continue;
275
276#ifndef NDEBUG
277 const MachineFunction &MF = *MBB.getParent();
278 assert(MF.getTarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
279 "Shouldn't move an instruction with unallocatable registers across "
280 "basic block boundaries.");
281#endif
282
283 if (!MBB.isLiveIn(R))
284 MBB.addLiveIn(R);
285 }
286}
287
Akira Hatanaka979899e2013-02-26 01:30:05 +0000288RegDefsUses::RegDefsUses(TargetMachine &TM)
289 : TRI(*TM.getRegisterInfo()), Defs(TRI.getNumRegs(), false),
290 Uses(TRI.getNumRegs(), false) {}
291
292void RegDefsUses::init(const MachineInstr &MI) {
293 // Add all register operands which are explicit and non-variadic.
294 update(MI, 0, MI.getDesc().getNumOperands());
295
296 // If MI is a call, add RA to Defs to prevent users of RA from going into
297 // delay slot.
298 if (MI.isCall())
299 Defs.set(Mips::RA);
300
301 // Add all implicit register operands of branch instructions except
302 // register AT.
303 if (MI.isBranch()) {
304 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
305 Defs.reset(Mips::AT);
306 }
307}
308
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000309void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
310 assert(MI.isCall());
311
312 // If MI is a call, add all caller-saved registers to Defs.
313 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
314
315 CallerSavedRegs.reset(Mips::ZERO);
316 CallerSavedRegs.reset(Mips::ZERO_64);
317
318 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
319 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
320 CallerSavedRegs.reset(*AI);
321
322 Defs |= CallerSavedRegs;
323}
324
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000325void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
326 BitVector AllocSet = TRI.getAllocatableSet(MF);
327
328 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
329 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
330 AllocSet.set(*AI);
331
332 AllocSet.set(Mips::ZERO);
333 AllocSet.set(Mips::ZERO_64);
334
335 Defs |= AllocSet.flip();
336}
337
338void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
339 const MachineBasicBlock &SuccBB) {
340 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
341 SE = MBB.succ_end(); SI != SE; ++SI)
342 if (*SI != &SuccBB)
343 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
344 LE = (*SI)->livein_end(); LI != LE; ++LI)
345 Uses.set(*LI);
346}
347
Akira Hatanaka979899e2013-02-26 01:30:05 +0000348bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
349 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
350 bool HasHazard = false;
351
352 for (unsigned I = Begin; I != End; ++I) {
353 const MachineOperand &MO = MI.getOperand(I);
354
355 if (MO.isReg() && MO.getReg())
356 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
357 }
358
359 Defs |= NewDefs;
360 Uses |= NewUses;
361
362 return HasHazard;
363}
364
365bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
366 unsigned Reg, bool IsDef) const {
367 if (IsDef) {
368 NewDefs.set(Reg);
369 // check whether Reg has already been defined or used.
370 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
371 }
372
373 NewUses.set(Reg);
374 // check whether Reg has already been defined.
375 return isRegInSet(Defs, Reg);
376}
377
378bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
379 // Check Reg and all aliased Registers.
380 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
381 if (RegSet.test(*AI))
382 return true;
383 return false;
384}
385
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000386bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000387 if (!MI.mayStore() && !MI.mayLoad())
388 return false;
389
390 if (ForbidMemInstr)
391 return true;
392
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000393 OrigSeenLoad = SeenLoad;
394 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000395 SeenLoad |= MI.mayLoad();
396 SeenStore |= MI.mayStore();
397
398 // If MI is an ordered or volatile memory reference, disallow moving
399 // subsequent loads and stores to delay slot.
400 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
401 ForbidMemInstr = true;
402 return true;
403 }
404
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000405 return hasHazard_(MI);
406}
407
408bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
409 if (MI.mayStore())
410 return true;
411
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000412 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000413 return true;
414
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000415 if (const PseudoSourceValue *PSV =
416 (*MI.memoperands_begin())->getPseudoValue()) {
417 if (isa<FixedStackPseudoSourceValue>(PSV))
418 return false;
Craig Topper062a2ba2014-04-25 05:30:21 +0000419 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000420 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000421
422 return true;
423}
424
425MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
426 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
427 SeenNoObjStore(false) {}
428
429bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000430 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000431 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000432
433 // Check underlying object list.
434 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000435 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000436 I != Objs.end(); ++I)
437 HasHazard |= updateDefsUses(*I, MI.mayStore());
438
439 return HasHazard;
440 }
441
442 // No underlying objects found.
443 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
444 HasHazard |= MI.mayLoad() || OrigSeenStore;
445
446 SeenNoObjLoad |= MI.mayLoad();
447 SeenNoObjStore |= MI.mayStore();
448
449 return HasHazard;
450}
451
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000452bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000453 if (MayStore)
454 return !Defs.insert(V) || Uses.count(V) || SeenNoObjStore || SeenNoObjLoad;
455
456 Uses.insert(V);
457 return Defs.count(V) || SeenNoObjStore;
458}
459
460bool MemDefsUses::
461getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000462 SmallVectorImpl<ValueType> &Objects) const {
463 if (!MI.hasOneMemOperand() ||
464 (!(*MI.memoperands_begin())->getValue() &&
465 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000466 return false;
467
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000468 if (const PseudoSourceValue *PSV =
469 (*MI.memoperands_begin())->getPseudoValue()) {
470 if (!PSV->isAliased(MFI))
471 return false;
472 Objects.push_back(PSV);
473 return true;
474 }
475
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000476 const Value *V = (*MI.memoperands_begin())->getValue();
477
478 SmallVector<Value *, 4> Objs;
479 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
480
Craig Topper31ee5862013-07-03 15:07:05 +0000481 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000482 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000483 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000484 return false;
485
486 Objects.push_back(*I);
487 }
488
489 return true;
490}
491
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000492/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000493/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000494bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000495 bool Changed = false;
Akira Hatanakae7b06972011-10-05 01:30:09 +0000496
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000497 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000498 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000499 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000500
Akira Hatanakaa0612812013-02-07 21:32:32 +0000501 ++FilledSlots;
502 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000503
Akira Hatanakaa0612812013-02-07 21:32:32 +0000504 // Delay slot filling is disabled at -O0.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000505 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
506 if (searchBackward(MBB, I))
507 continue;
508
509 if (I->isTerminator()) {
510 if (searchSuccBBs(MBB, I))
511 continue;
512 } else if (searchForward(MBB, I)) {
513 continue;
514 }
515 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000516
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000517 // Bundle the NOP to the instruction with the delay slot.
Bill Wendlingead89ef2013-06-07 07:04:14 +0000518 const MipsInstrInfo *TII =
519 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000520 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
521 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000522 }
523
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000524 return Changed;
525}
526
527/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
528/// slots in Mips MachineFunctions
529FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
530 return new Filler(tm);
531}
532
Akira Hatanakaf815db52013-03-01 00:26:14 +0000533template<typename IterTy>
534bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000535 RegDefsUses &RegDU, InspectMemInstr& IM,
Akira Hatanakaf815db52013-03-01 00:26:14 +0000536 IterTy &Filler) const {
537 for (IterTy I = Begin; I != End; ++I) {
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000538 // skip debug value
539 if (I->isDebugValue())
540 continue;
541
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000542 if (terminateSearch(*I))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000543 break;
544
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000545 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
546 "Cannot put calls, returns or branches in delay slot.");
547
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000548 if (delayHasHazard(*I, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000549 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000550
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000551 if (TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
552 // In NaCl, instructions that must be masked are forbidden in delay slots.
553 // We only check for loads, stores and SP changes. Calls, returns and
554 // branches are not checked because non-NaCl targets never put them in
555 // delay slots.
556 unsigned AddrIdx;
557 if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx)
558 && baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg()))
559 || I->modifiesRegister(Mips::SP, TM.getRegisterInfo()))
560 continue;
561 }
562
Akira Hatanakaf815db52013-03-01 00:26:14 +0000563 Filler = I;
564 return true;
565 }
566
567 return false;
568}
569
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000570bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000571 if (DisableBackwardSearch)
572 return false;
573
Akira Hatanakaf815db52013-03-01 00:26:14 +0000574 RegDefsUses RegDU(TM);
575 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000576 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000577
578 RegDU.init(*Slot);
579
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000580 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler))
581 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000582
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000583 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
584 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000585 ++UsefulSlots;
586 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000587}
588
589bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
590 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000591 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000592 return false;
593
594 RegDefsUses RegDU(TM);
595 NoMemInstr NM;
596 Iter Filler;
597
598 RegDU.setCallerSaved(*Slot);
599
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000600 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000601 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000602
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000603 MBB.splice(std::next(Slot), &MBB, Filler);
604 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000605 ++UsefulSlots;
606 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000607}
608
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000609bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
610 if (DisableSuccBBSearch)
611 return false;
612
613 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
614
615 if (!SuccBB)
616 return false;
617
618 RegDefsUses RegDU(TM);
619 bool HasMultipleSuccs = false;
620 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000621 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000622 Iter Filler;
623
624 // Iterate over SuccBB's predecessor list.
625 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
626 PE = SuccBB->pred_end(); PI != PE; ++PI)
627 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
628 return false;
629
630 // Do not allow moving instructions which have unallocatable register operands
631 // across basic block boundaries.
632 RegDU.setUnallocatableRegs(*MBB.getParent());
633
634 // Only allow moving loads from stack or constants if any of the SuccBB's
635 // predecessors have multiple successors.
636 if (HasMultipleSuccs) {
637 IM.reset(new LoadFromStackOrConst());
638 } else {
639 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
640 IM.reset(new MemDefsUses(MFI));
641 }
642
643 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler))
644 return false;
645
646 insertDelayFiller(Filler, BrMap);
647 addLiveInRegs(Filler, *SuccBB);
648 Filler->eraseFromParent();
649
650 return true;
651}
652
653MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
654 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000655 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000656
657 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000658 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
659 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
660 [&](const MachineBasicBlock *Dst0,
661 const MachineBasicBlock *Dst1) {
662 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
663 });
Craig Topper062a2ba2014-04-25 05:30:21 +0000664 return S->isLandingPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000665}
666
667std::pair<MipsInstrInfo::BranchType, MachineInstr *>
668Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
669 const MipsInstrInfo *TII =
670 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
Craig Topper062a2ba2014-04-25 05:30:21 +0000671 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000672 SmallVector<MachineInstr*, 2> BranchInstrs;
673 SmallVector<MachineOperand, 2> Cond;
674
675 MipsInstrInfo::BranchType R =
676 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
677
678 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000679 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000680
681 if (R != MipsInstrInfo::BT_CondUncond) {
682 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000683 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000684
685 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
686
687 return std::make_pair(R, BranchInstrs[0]);
688 }
689
690 assert((TrueBB == &Dst) || (FalseBB == &Dst));
691
692 // Examine the conditional branch. See if its slot is occupied.
693 if (hasUnoccupiedSlot(BranchInstrs[0]))
694 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
695
696 // If that fails, try the unconditional branch.
697 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
698 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
699
Craig Topper062a2ba2014-04-25 05:30:21 +0000700 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000701}
702
703bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
704 RegDefsUses &RegDU, bool &HasMultipleSuccs,
705 BB2BrMap &BrMap) const {
706 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
707 getBranch(Pred, Succ);
708
709 // Return if either getBranch wasn't able to analyze the branches or there
710 // were no branches with unoccupied slots.
711 if (P.first == MipsInstrInfo::BT_None)
712 return false;
713
714 if ((P.first != MipsInstrInfo::BT_Uncond) &&
715 (P.first != MipsInstrInfo::BT_NoBranch)) {
716 HasMultipleSuccs = true;
717 RegDU.addLiveOut(Pred, Succ);
718 }
719
720 BrMap[&Pred] = P.second;
721 return true;
722}
723
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000724bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000725 InspectMemInstr &IM) const {
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000726 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000727
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000728 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000729 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000730
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000731 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000732}
733
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000734bool Filler::terminateSearch(const MachineInstr &Candidate) const {
735 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000736 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000737 Candidate.hasUnmodeledSideEffects());
738}