blob: 47ccbfbc426b7410d2b82db2d98a987c20200e91 [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
14#define DEBUG_TYPE "delay-slot-filler"
15
16#include "Mips.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000017#include "MipsInstrInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000018#include "MipsTargetMachine.h"
Akira Hatanaka06bd1382013-02-14 23:40:57 +000019#include "llvm/ADT/BitVector.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Statistic.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/ValueTracking.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000024#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000025#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/MachineInstrBuilder.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
35STATISTIC(FilledSlots, "Number of delay slots filled");
Akira Hatanaka9e603442011-10-05 01:19:13 +000036STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
Akira Hatanaka02e760a2011-10-05 02:22:49 +000037 " are not NOP.");
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000038
Akira Hatanaka9d957842012-08-22 02:51:28 +000039static cl::opt<bool> DisableDelaySlotFiller(
40 "disable-mips-delay-filler",
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000041 cl::init(false),
Akira Hatanaka1083eb12013-02-14 23:20:15 +000042 cl::desc("Fill all delay slots with NOPs."),
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000043 cl::Hidden);
44
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000045static cl::opt<bool> DisableForwardSearch(
46 "disable-mips-df-forward-search",
47 cl::init(true),
48 cl::desc("Disallow MIPS delay filler to search forward."),
49 cl::Hidden);
50
Akira Hatanakae44e30c2013-03-01 01:02:36 +000051static cl::opt<bool> DisableSuccBBSearch(
52 "disable-mips-df-succbb-search",
53 cl::init(true),
54 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
55 cl::Hidden);
56
57static cl::opt<bool> DisableBackwardSearch(
58 "disable-mips-df-backward-search",
59 cl::init(false),
60 cl::desc("Disallow MIPS delay filler to search backward."),
61 cl::Hidden);
62
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000063namespace {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000064 typedef MachineBasicBlock::iterator Iter;
65 typedef MachineBasicBlock::reverse_iterator ReverseIter;
66 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
67
Akira Hatanaka979899e2013-02-26 01:30:05 +000068 class RegDefsUses {
69 public:
70 RegDefsUses(TargetMachine &TM);
71 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000072
73 /// This function sets all caller-saved registers in Defs.
74 void setCallerSaved(const MachineInstr &MI);
75
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000076 /// This function sets all unallocatable registers in Defs.
77 void setUnallocatableRegs(const MachineFunction &MF);
78
79 /// Set bits in Uses corresponding to MBB's live-out registers except for
80 /// the registers that are live-in to SuccBB.
81 void addLiveOut(const MachineBasicBlock &MBB,
82 const MachineBasicBlock &SuccBB);
83
Akira Hatanaka979899e2013-02-26 01:30:05 +000084 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
85
86 private:
87 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
88 bool IsDef) const;
89
90 /// Returns true if Reg or its alias is in RegSet.
91 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
92
93 const TargetRegisterInfo &TRI;
94 BitVector Defs, Uses;
95 };
96
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000097 /// Base class for inspecting loads and stores.
98 class InspectMemInstr {
99 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000100 InspectMemInstr(bool ForbidMemInstr_)
101 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
102 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
103
104 /// Return true if MI cannot be moved to delay slot.
105 bool hasHazard(const MachineInstr &MI);
106
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000107 virtual ~InspectMemInstr() {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000108
109 protected:
110 /// Flags indicating whether loads or stores have been seen.
111 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
112
113 /// Memory instructions are not allowed to move to delay slot if this flag
114 /// is true.
115 bool ForbidMemInstr;
116
117 private:
118 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000119 };
120
121 /// This subclass rejects any memory instructions.
122 class NoMemInstr : public InspectMemInstr {
123 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000124 NoMemInstr() : InspectMemInstr(true) {}
125 private:
126 virtual bool hasHazard_(const MachineInstr &MI) { return true; }
127 };
128
129 /// This subclass accepts loads from stacks and constant loads.
130 class LoadFromStackOrConst : public InspectMemInstr {
131 public:
132 LoadFromStackOrConst() : InspectMemInstr(false) {}
133 private:
134 virtual bool hasHazard_(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000135 };
136
137 /// This subclass uses memory dependence information to determine whether a
138 /// memory instruction can be moved to a delay slot.
139 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000140 public:
141 MemDefsUses(const MachineFrameInfo *MFI);
142
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000143 private:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000144 virtual bool hasHazard_(const MachineInstr &MI);
145
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000146 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000147 /// disqualify the delay slot candidate between V and values in Uses and
148 /// Defs.
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000149 bool updateDefsUses(const Value *V, bool MayStore);
150
151 /// Get the list of underlying objects of MI's memory operand.
152 bool getUnderlyingObjects(const MachineInstr &MI,
153 SmallVectorImpl<const Value *> &Objects) const;
154
155 const MachineFrameInfo *MFI;
156 SmallPtrSet<const Value*, 4> Uses, Defs;
157
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000158 /// Flags indicating whether loads or stores with no underlying objects have
159 /// been seen.
160 bool SeenNoObjLoad, SeenNoObjStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000161 };
162
Akira Hatanakaa0612812013-02-07 21:32:32 +0000163 class Filler : public MachineFunctionPass {
164 public:
Bruno Cardoso Lopesfde21cf2010-12-09 17:31:11 +0000165 Filler(TargetMachine &tm)
Bill Wendlingead89ef2013-06-07 07:04:14 +0000166 : MachineFunctionPass(ID), TM(tm) { }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000167
168 virtual const char *getPassName() const {
169 return "Mips Delay Slot Filler";
170 }
171
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000172 bool runOnMachineFunction(MachineFunction &F) {
173 bool Changed = false;
174 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
175 FI != FE; ++FI)
176 Changed |= runOnMachineBasicBlock(*FI);
177 return Changed;
178 }
179
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000180 void getAnalysisUsage(AnalysisUsage &AU) const {
181 AU.addRequired<MachineBranchProbabilityInfo>();
182 MachineFunctionPass::getAnalysisUsage(AU);
183 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000184
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000185 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000186 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
187
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000188 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000189 /// and returns true if it isn't. It also updates memory and register
190 /// dependence information.
191 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000192 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000193
Akira Hatanakaf815db52013-03-01 00:26:14 +0000194 /// This function searches range [Begin, End) for an instruction that can be
195 /// moved to the delay slot. Returns true on success.
196 template<typename IterTy>
197 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000198 RegDefsUses &RegDU, InspectMemInstr &IM,
199 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000200
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000201 /// This function searches in the backward direction for an instruction that
202 /// can be moved to the delay slot. Returns true on success.
203 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
204
205 /// This function searches MBB in the forward direction for an instruction
206 /// that can be moved to the delay slot. Returns true on success.
207 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000208
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000209 /// This function searches one of MBB's successor blocks for an instruction
210 /// that can be moved to the delay slot and inserts clones of the
211 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000212 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
213
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000214 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
215 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000216 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
217
218 /// This function analyzes MBB and returns an instruction with an unoccupied
219 /// slot that branches to Dst.
220 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
221 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
222
223 /// Examine Pred and see if it is possible to insert an instruction into
224 /// one of its branches delay slot or its end.
225 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
226 RegDefsUses &RegDU, bool &HasMultipleSuccs,
227 BB2BrMap &BrMap) const;
228
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000229 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000230
Akira Hatanakaa0612812013-02-07 21:32:32 +0000231 TargetMachine &TM;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000232
Akira Hatanakaa0612812013-02-07 21:32:32 +0000233 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000234 };
235 char Filler::ID = 0;
236} // end of anonymous namespace
237
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000238static bool hasUnoccupiedSlot(const MachineInstr *MI) {
239 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
240}
241
242/// This function inserts clones of Filler into predecessor blocks.
243static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
244 MachineFunction *MF = Filler->getParent()->getParent();
245
246 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
247 if (I->second) {
248 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
249 ++UsefulSlots;
250 } else {
251 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
252 }
253 }
254}
255
256/// This function adds registers Filler defines to MBB's live-in register list.
257static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
258 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
259 const MachineOperand &MO = Filler->getOperand(I);
260 unsigned R;
261
262 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
263 continue;
264
265#ifndef NDEBUG
266 const MachineFunction &MF = *MBB.getParent();
267 assert(MF.getTarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
268 "Shouldn't move an instruction with unallocatable registers across "
269 "basic block boundaries.");
270#endif
271
272 if (!MBB.isLiveIn(R))
273 MBB.addLiveIn(R);
274 }
275}
276
Akira Hatanaka979899e2013-02-26 01:30:05 +0000277RegDefsUses::RegDefsUses(TargetMachine &TM)
278 : TRI(*TM.getRegisterInfo()), Defs(TRI.getNumRegs(), false),
279 Uses(TRI.getNumRegs(), false) {}
280
281void RegDefsUses::init(const MachineInstr &MI) {
282 // Add all register operands which are explicit and non-variadic.
283 update(MI, 0, MI.getDesc().getNumOperands());
284
285 // If MI is a call, add RA to Defs to prevent users of RA from going into
286 // delay slot.
287 if (MI.isCall())
288 Defs.set(Mips::RA);
289
290 // Add all implicit register operands of branch instructions except
291 // register AT.
292 if (MI.isBranch()) {
293 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
294 Defs.reset(Mips::AT);
295 }
296}
297
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000298void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
299 assert(MI.isCall());
300
301 // If MI is a call, add all caller-saved registers to Defs.
302 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
303
304 CallerSavedRegs.reset(Mips::ZERO);
305 CallerSavedRegs.reset(Mips::ZERO_64);
306
307 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
308 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
309 CallerSavedRegs.reset(*AI);
310
311 Defs |= CallerSavedRegs;
312}
313
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000314void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
315 BitVector AllocSet = TRI.getAllocatableSet(MF);
316
317 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
318 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
319 AllocSet.set(*AI);
320
321 AllocSet.set(Mips::ZERO);
322 AllocSet.set(Mips::ZERO_64);
323
324 Defs |= AllocSet.flip();
325}
326
327void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
328 const MachineBasicBlock &SuccBB) {
329 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
330 SE = MBB.succ_end(); SI != SE; ++SI)
331 if (*SI != &SuccBB)
332 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
333 LE = (*SI)->livein_end(); LI != LE; ++LI)
334 Uses.set(*LI);
335}
336
Akira Hatanaka979899e2013-02-26 01:30:05 +0000337bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
338 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
339 bool HasHazard = false;
340
341 for (unsigned I = Begin; I != End; ++I) {
342 const MachineOperand &MO = MI.getOperand(I);
343
344 if (MO.isReg() && MO.getReg())
345 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
346 }
347
348 Defs |= NewDefs;
349 Uses |= NewUses;
350
351 return HasHazard;
352}
353
354bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
355 unsigned Reg, bool IsDef) const {
356 if (IsDef) {
357 NewDefs.set(Reg);
358 // check whether Reg has already been defined or used.
359 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
360 }
361
362 NewUses.set(Reg);
363 // check whether Reg has already been defined.
364 return isRegInSet(Defs, Reg);
365}
366
367bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
368 // Check Reg and all aliased Registers.
369 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
370 if (RegSet.test(*AI))
371 return true;
372 return false;
373}
374
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000375bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000376 if (!MI.mayStore() && !MI.mayLoad())
377 return false;
378
379 if (ForbidMemInstr)
380 return true;
381
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000382 OrigSeenLoad = SeenLoad;
383 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000384 SeenLoad |= MI.mayLoad();
385 SeenStore |= MI.mayStore();
386
387 // If MI is an ordered or volatile memory reference, disallow moving
388 // subsequent loads and stores to delay slot.
389 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
390 ForbidMemInstr = true;
391 return true;
392 }
393
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000394 return hasHazard_(MI);
395}
396
397bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
398 if (MI.mayStore())
399 return true;
400
401 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getValue())
402 return true;
403
404 const Value *V = (*MI.memoperands_begin())->getValue();
405
406 if (isa<FixedStackPseudoSourceValue>(V))
407 return false;
408
409 if (const PseudoSourceValue *PSV = dyn_cast<const PseudoSourceValue>(V))
Akira Hatanakaaf4211a2013-09-28 00:12:32 +0000410 return !PSV->isConstant(0) && V != PseudoSourceValue::getStack();
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000411
412 return true;
413}
414
415MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
416 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
417 SeenNoObjStore(false) {}
418
419bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000420 bool HasHazard = false;
421 SmallVector<const Value *, 4> Objs;
422
423 // Check underlying object list.
424 if (getUnderlyingObjects(MI, Objs)) {
Craig Topper31ee5862013-07-03 15:07:05 +0000425 for (SmallVectorImpl<const Value *>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000426 I != Objs.end(); ++I)
427 HasHazard |= updateDefsUses(*I, MI.mayStore());
428
429 return HasHazard;
430 }
431
432 // No underlying objects found.
433 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
434 HasHazard |= MI.mayLoad() || OrigSeenStore;
435
436 SeenNoObjLoad |= MI.mayLoad();
437 SeenNoObjStore |= MI.mayStore();
438
439 return HasHazard;
440}
441
442bool MemDefsUses::updateDefsUses(const Value *V, bool MayStore) {
443 if (MayStore)
444 return !Defs.insert(V) || Uses.count(V) || SeenNoObjStore || SeenNoObjLoad;
445
446 Uses.insert(V);
447 return Defs.count(V) || SeenNoObjStore;
448}
449
450bool MemDefsUses::
451getUnderlyingObjects(const MachineInstr &MI,
452 SmallVectorImpl<const Value *> &Objects) const {
453 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getValue())
454 return false;
455
456 const Value *V = (*MI.memoperands_begin())->getValue();
457
458 SmallVector<Value *, 4> Objs;
459 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
460
Craig Topper31ee5862013-07-03 15:07:05 +0000461 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000462 I != E; ++I) {
463 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(*I)) {
464 if (PSV->isAliased(MFI))
465 return false;
466 } else if (!isIdentifiedObject(V))
467 return false;
468
469 Objects.push_back(*I);
470 }
471
472 return true;
473}
474
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000475/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000476/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000477bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000478 bool Changed = false;
Akira Hatanakae7b06972011-10-05 01:30:09 +0000479
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000480 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000481 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000482 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000483
Akira Hatanakaa0612812013-02-07 21:32:32 +0000484 ++FilledSlots;
485 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000486
Akira Hatanakaa0612812013-02-07 21:32:32 +0000487 // Delay slot filling is disabled at -O0.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000488 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
489 if (searchBackward(MBB, I))
490 continue;
491
492 if (I->isTerminator()) {
493 if (searchSuccBBs(MBB, I))
494 continue;
495 } else if (searchForward(MBB, I)) {
496 continue;
497 }
498 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000499
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000500 // Bundle the NOP to the instruction with the delay slot.
Bill Wendlingead89ef2013-06-07 07:04:14 +0000501 const MipsInstrInfo *TII =
502 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000503 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
504 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000505 }
506
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000507 return Changed;
508}
509
510/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
511/// slots in Mips MachineFunctions
512FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
513 return new Filler(tm);
514}
515
Akira Hatanakaf815db52013-03-01 00:26:14 +0000516template<typename IterTy>
517bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000518 RegDefsUses &RegDU, InspectMemInstr& IM,
Akira Hatanakaf815db52013-03-01 00:26:14 +0000519 IterTy &Filler) const {
520 for (IterTy I = Begin; I != End; ++I) {
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000521 // skip debug value
522 if (I->isDebugValue())
523 continue;
524
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000525 if (terminateSearch(*I))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000526 break;
527
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000528 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
529 "Cannot put calls, returns or branches in delay slot.");
530
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000531 if (delayHasHazard(*I, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000532 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000533
Akira Hatanakaf815db52013-03-01 00:26:14 +0000534 Filler = I;
535 return true;
536 }
537
538 return false;
539}
540
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000541bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000542 if (DisableBackwardSearch)
543 return false;
544
Akira Hatanakaf815db52013-03-01 00:26:14 +0000545 RegDefsUses RegDU(TM);
546 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000547 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000548
549 RegDU.init(*Slot);
550
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000551 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler))
552 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000553
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000554 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
555 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000556 ++UsefulSlots;
557 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000558}
559
560bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
561 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000562 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000563 return false;
564
565 RegDefsUses RegDU(TM);
566 NoMemInstr NM;
567 Iter Filler;
568
569 RegDU.setCallerSaved(*Slot);
570
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000571 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000572 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000573
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000574 MBB.splice(std::next(Slot), &MBB, Filler);
575 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000576 ++UsefulSlots;
577 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000578}
579
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000580bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
581 if (DisableSuccBBSearch)
582 return false;
583
584 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
585
586 if (!SuccBB)
587 return false;
588
589 RegDefsUses RegDU(TM);
590 bool HasMultipleSuccs = false;
591 BB2BrMap BrMap;
592 OwningPtr<InspectMemInstr> IM;
593 Iter Filler;
594
595 // Iterate over SuccBB's predecessor list.
596 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
597 PE = SuccBB->pred_end(); PI != PE; ++PI)
598 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
599 return false;
600
601 // Do not allow moving instructions which have unallocatable register operands
602 // across basic block boundaries.
603 RegDU.setUnallocatableRegs(*MBB.getParent());
604
605 // Only allow moving loads from stack or constants if any of the SuccBB's
606 // predecessors have multiple successors.
607 if (HasMultipleSuccs) {
608 IM.reset(new LoadFromStackOrConst());
609 } else {
610 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
611 IM.reset(new MemDefsUses(MFI));
612 }
613
614 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler))
615 return false;
616
617 insertDelayFiller(Filler, BrMap);
618 addLiveInRegs(Filler, *SuccBB);
619 Filler->eraseFromParent();
620
621 return true;
622}
623
624MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
625 if (B.succ_empty())
626 return NULL;
627
628 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000629 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
630 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
631 [&](const MachineBasicBlock *Dst0,
632 const MachineBasicBlock *Dst1) {
633 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
634 });
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000635 return S->isLandingPad() ? NULL : S;
636}
637
638std::pair<MipsInstrInfo::BranchType, MachineInstr *>
639Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
640 const MipsInstrInfo *TII =
641 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
642 MachineBasicBlock *TrueBB = 0, *FalseBB = 0;
643 SmallVector<MachineInstr*, 2> BranchInstrs;
644 SmallVector<MachineOperand, 2> Cond;
645
646 MipsInstrInfo::BranchType R =
647 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
648
649 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
650 return std::make_pair(R, (MachineInstr*)NULL);
651
652 if (R != MipsInstrInfo::BT_CondUncond) {
653 if (!hasUnoccupiedSlot(BranchInstrs[0]))
654 return std::make_pair(MipsInstrInfo::BT_None, (MachineInstr*)NULL);
655
656 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
657
658 return std::make_pair(R, BranchInstrs[0]);
659 }
660
661 assert((TrueBB == &Dst) || (FalseBB == &Dst));
662
663 // Examine the conditional branch. See if its slot is occupied.
664 if (hasUnoccupiedSlot(BranchInstrs[0]))
665 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
666
667 // If that fails, try the unconditional branch.
668 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
669 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
670
671 return std::make_pair(MipsInstrInfo::BT_None, (MachineInstr*)NULL);
672}
673
674bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
675 RegDefsUses &RegDU, bool &HasMultipleSuccs,
676 BB2BrMap &BrMap) const {
677 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
678 getBranch(Pred, Succ);
679
680 // Return if either getBranch wasn't able to analyze the branches or there
681 // were no branches with unoccupied slots.
682 if (P.first == MipsInstrInfo::BT_None)
683 return false;
684
685 if ((P.first != MipsInstrInfo::BT_Uncond) &&
686 (P.first != MipsInstrInfo::BT_NoBranch)) {
687 HasMultipleSuccs = true;
688 RegDU.addLiveOut(Pred, Succ);
689 }
690
691 BrMap[&Pred] = P.second;
692 return true;
693}
694
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000695bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000696 InspectMemInstr &IM) const {
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000697 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000698
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000699 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000700 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000701
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000702 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000703}
704
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000705bool Filler::terminateSearch(const MachineInstr &Candidate) const {
706 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000707 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000708 Candidate.hasUnmodeledSideEffects());
709}