LLVM  5.0.0
R600Packetizer.cpp
Go to the documentation of this file.
1 //===----- R600Packetizer.cpp - VLIW packetizer ---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This pass implements instructions packetization for R600. It unsets isLast
12 /// bit of instructions inside a bundle and substitutes src register with
13 /// PreviousVector when applicable.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "AMDGPU.h"
18 #include "AMDGPUSubtarget.h"
19 #include "R600InstrInfo.h"
24 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Support/Debug.h"
28 
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "packets"
32 
33 namespace {
34 
35 class R600Packetizer : public MachineFunctionPass {
36 
37 public:
38  static char ID;
39  R600Packetizer() : MachineFunctionPass(ID) {}
40 
41  void getAnalysisUsage(AnalysisUsage &AU) const override {
42  AU.setPreservesCFG();
48  }
49 
50  StringRef getPassName() const override { return "R600 Packetizer"; }
51 
52  bool runOnMachineFunction(MachineFunction &Fn) override;
53 };
54 char R600Packetizer::ID = 0;
55 
56 class R600PacketizerList : public VLIWPacketizerList {
57 private:
58  const R600InstrInfo *TII;
59  const R600RegisterInfo &TRI;
60  bool VLIW5;
61  bool ConsideredInstUsesAlreadyWrittenVectorElement;
62 
63  unsigned getSlot(const MachineInstr &MI) const {
64  return TRI.getHWRegChan(MI.getOperand(0).getReg());
65  }
66 
67  /// \returns register to PV chan mapping for bundle/single instructions that
68  /// immediately precedes I.
70  const {
72  I--;
73  if (!TII->isALUInstr(I->getOpcode()) && !I->isBundle())
74  return Result;
76  if (I->isBundle())
77  BI++;
78  int LastDstChan = -1;
79  do {
80  bool isTrans = false;
81  int BISlot = getSlot(*BI);
82  if (LastDstChan >= BISlot)
83  isTrans = true;
84  LastDstChan = BISlot;
85  if (TII->isPredicated(*BI))
86  continue;
87  int OperandIdx = TII->getOperandIdx(BI->getOpcode(), AMDGPU::OpName::write);
88  if (OperandIdx > -1 && BI->getOperand(OperandIdx).getImm() == 0)
89  continue;
90  int DstIdx = TII->getOperandIdx(BI->getOpcode(), AMDGPU::OpName::dst);
91  if (DstIdx == -1) {
92  continue;
93  }
94  unsigned Dst = BI->getOperand(DstIdx).getReg();
95  if (isTrans || TII->isTransOnly(*BI)) {
96  Result[Dst] = AMDGPU::PS;
97  continue;
98  }
99  if (BI->getOpcode() == AMDGPU::DOT4_r600 ||
100  BI->getOpcode() == AMDGPU::DOT4_eg) {
101  Result[Dst] = AMDGPU::PV_X;
102  continue;
103  }
104  if (Dst == AMDGPU::OQAP) {
105  continue;
106  }
107  unsigned PVReg = 0;
108  switch (TRI.getHWRegChan(Dst)) {
109  case 0:
110  PVReg = AMDGPU::PV_X;
111  break;
112  case 1:
113  PVReg = AMDGPU::PV_Y;
114  break;
115  case 2:
116  PVReg = AMDGPU::PV_Z;
117  break;
118  case 3:
119  PVReg = AMDGPU::PV_W;
120  break;
121  default:
122  llvm_unreachable("Invalid Chan");
123  }
124  Result[Dst] = PVReg;
125  } while ((++BI)->isBundledWithPred());
126  return Result;
127  }
128 
129  void substitutePV(MachineInstr &MI, const DenseMap<unsigned, unsigned> &PVs)
130  const {
131  unsigned Ops[] = {
132  AMDGPU::OpName::src0,
133  AMDGPU::OpName::src1,
134  AMDGPU::OpName::src2
135  };
136  for (unsigned i = 0; i < 3; i++) {
137  int OperandIdx = TII->getOperandIdx(MI.getOpcode(), Ops[i]);
138  if (OperandIdx < 0)
139  continue;
140  unsigned Src = MI.getOperand(OperandIdx).getReg();
142  if (It != PVs.end())
143  MI.getOperand(OperandIdx).setReg(It->second);
144  }
145  }
146 public:
147  // Ctor.
148  R600PacketizerList(MachineFunction &MF, const R600Subtarget &ST,
149  MachineLoopInfo &MLI)
150  : VLIWPacketizerList(MF, MLI, nullptr),
151  TII(ST.getInstrInfo()),
152  TRI(TII->getRegisterInfo()) {
153  VLIW5 = !ST.hasCaymanISA();
154  }
155 
156  // initPacketizerState - initialize some internal flags.
157  void initPacketizerState() override {
158  ConsideredInstUsesAlreadyWrittenVectorElement = false;
159  }
160 
161  // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
162  bool ignorePseudoInstruction(const MachineInstr &MI,
163  const MachineBasicBlock *MBB) override {
164  return false;
165  }
166 
167  // isSoloInstruction - return true if instruction MI can not be packetized
168  // with any other instruction, which means that MI itself is a packet.
169  bool isSoloInstruction(const MachineInstr &MI) override {
170  if (TII->isVector(MI))
171  return true;
172  if (!TII->isALUInstr(MI.getOpcode()))
173  return true;
174  if (MI.getOpcode() == AMDGPU::GROUP_BARRIER)
175  return true;
176  // XXX: This can be removed once the packetizer properly handles all the
177  // LDS instruction group restrictions.
178  return TII->isLDSInstr(MI.getOpcode());
179  }
180 
181  // isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
182  // together.
183  bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) override {
184  MachineInstr *MII = SUI->getInstr(), *MIJ = SUJ->getInstr();
185  if (getSlot(*MII) == getSlot(*MIJ))
186  ConsideredInstUsesAlreadyWrittenVectorElement = true;
187  // Does MII and MIJ share the same pred_sel ?
188  int OpI = TII->getOperandIdx(MII->getOpcode(), AMDGPU::OpName::pred_sel),
189  OpJ = TII->getOperandIdx(MIJ->getOpcode(), AMDGPU::OpName::pred_sel);
190  unsigned PredI = (OpI > -1)?MII->getOperand(OpI).getReg():0,
191  PredJ = (OpJ > -1)?MIJ->getOperand(OpJ).getReg():0;
192  if (PredI != PredJ)
193  return false;
194  if (SUJ->isSucc(SUI)) {
195  for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {
196  const SDep &Dep = SUJ->Succs[i];
197  if (Dep.getSUnit() != SUI)
198  continue;
199  if (Dep.getKind() == SDep::Anti)
200  continue;
201  if (Dep.getKind() == SDep::Output)
202  if (MII->getOperand(0).getReg() != MIJ->getOperand(0).getReg())
203  continue;
204  return false;
205  }
206  }
207 
208  bool ARDef =
209  TII->definesAddressRegister(*MII) || TII->definesAddressRegister(*MIJ);
210  bool ARUse =
211  TII->usesAddressRegister(*MII) || TII->usesAddressRegister(*MIJ);
212 
213  return !ARDef || !ARUse;
214  }
215 
216  // isLegalToPruneDependencies - Is it legal to prune dependece between SUI
217  // and SUJ.
218  bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) override {
219  return false;
220  }
221 
222  void setIsLastBit(MachineInstr *MI, unsigned Bit) const {
223  unsigned LastOp = TII->getOperandIdx(MI->getOpcode(), AMDGPU::OpName::last);
224  MI->getOperand(LastOp).setImm(Bit);
225  }
226 
227  bool isBundlableWithCurrentPMI(MachineInstr &MI,
229  std::vector<R600InstrInfo::BankSwizzle> &BS,
230  bool &isTransSlot) {
231  isTransSlot = TII->isTransOnly(MI);
232  assert (!isTransSlot || VLIW5);
233 
234  // Is the dst reg sequence legal ?
235  if (!isTransSlot && !CurrentPacketMIs.empty()) {
236  if (getSlot(MI) <= getSlot(*CurrentPacketMIs.back())) {
237  if (ConsideredInstUsesAlreadyWrittenVectorElement &&
238  !TII->isVectorOnly(MI) && VLIW5) {
239  isTransSlot = true;
240  DEBUG({
241  dbgs() << "Considering as Trans Inst :";
242  MI.dump();
243  });
244  }
245  else
246  return false;
247  }
248  }
249 
250  // Are the Constants limitations met ?
251  CurrentPacketMIs.push_back(&MI);
252  if (!TII->fitsConstReadLimitations(CurrentPacketMIs)) {
253  DEBUG({
254  dbgs() << "Couldn't pack :\n";
255  MI.dump();
256  dbgs() << "with the following packets :\n";
257  for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
258  CurrentPacketMIs[i]->dump();
259  dbgs() << "\n";
260  }
261  dbgs() << "because of Consts read limitations\n";
262  });
263  CurrentPacketMIs.pop_back();
264  return false;
265  }
266 
267  // Is there a BankSwizzle set that meet Read Port limitations ?
268  if (!TII->fitsReadPortLimitations(CurrentPacketMIs,
269  PV, BS, isTransSlot)) {
270  DEBUG({
271  dbgs() << "Couldn't pack :\n";
272  MI.dump();
273  dbgs() << "with the following packets :\n";
274  for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
275  CurrentPacketMIs[i]->dump();
276  dbgs() << "\n";
277  }
278  dbgs() << "because of Read port limitations\n";
279  });
280  CurrentPacketMIs.pop_back();
281  return false;
282  }
283 
284  // We cannot read LDS source registers from the Trans slot.
285  if (isTransSlot && TII->readsLDSSrcReg(MI))
286  return false;
287 
288  CurrentPacketMIs.pop_back();
289  return true;
290  }
291 
292  MachineBasicBlock::iterator addToPacket(MachineInstr &MI) override {
293  MachineBasicBlock::iterator FirstInBundle =
294  CurrentPacketMIs.empty() ? &MI : CurrentPacketMIs.front();
295  const DenseMap<unsigned, unsigned> &PV =
296  getPreviousVector(FirstInBundle);
297  std::vector<R600InstrInfo::BankSwizzle> BS;
298  bool isTransSlot;
299 
300  if (isBundlableWithCurrentPMI(MI, PV, BS, isTransSlot)) {
301  for (unsigned i = 0, e = CurrentPacketMIs.size(); i < e; i++) {
302  MachineInstr *MI = CurrentPacketMIs[i];
303  unsigned Op = TII->getOperandIdx(MI->getOpcode(),
304  AMDGPU::OpName::bank_swizzle);
305  MI->getOperand(Op).setImm(BS[i]);
306  }
307  unsigned Op =
308  TII->getOperandIdx(MI.getOpcode(), AMDGPU::OpName::bank_swizzle);
309  MI.getOperand(Op).setImm(BS.back());
310  if (!CurrentPacketMIs.empty())
311  setIsLastBit(CurrentPacketMIs.back(), 0);
312  substitutePV(MI, PV);
314  if (isTransSlot) {
315  endPacket(std::next(It)->getParent(), std::next(It));
316  }
317  return It;
318  }
319  endPacket(MI.getParent(), MI);
320  if (TII->isTransOnly(MI))
321  return MI;
323  }
324 };
325 
326 bool R600Packetizer::runOnMachineFunction(MachineFunction &Fn) {
328  const R600InstrInfo *TII = ST.getInstrInfo();
329 
330  MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
331 
332  // Instantiate the packetizer.
333  R600PacketizerList Packetizer(Fn, ST, MLI);
334 
335  // DFA state table should not be empty.
336  assert(Packetizer.getResourceTracker() && "Empty DFA table!");
337 
338  if (Packetizer.getResourceTracker()->getInstrItins()->isEmpty())
339  return false;
340 
341  //
342  // Loop over all basic blocks and remove KILL pseudo-instructions
343  // These instructions confuse the dependence analysis. Consider:
344  // D0 = ... (Insn 0)
345  // R0 = KILL R0, D0 (Insn 1)
346  // R0 = ... (Insn 2)
347  // Here, Insn 1 will result in the dependence graph not emitting an output
348  // dependence between Insn 0 and Insn 2. This can lead to incorrect
349  // packetization
350  //
351  for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
352  MBB != MBBe; ++MBB) {
353  MachineBasicBlock::iterator End = MBB->end();
354  MachineBasicBlock::iterator MI = MBB->begin();
355  while (MI != End) {
356  if (MI->isKill() || MI->getOpcode() == AMDGPU::IMPLICIT_DEF ||
357  (MI->getOpcode() == AMDGPU::CF_ALU && !MI->getOperand(8).getImm())) {
358  MachineBasicBlock::iterator DeleteMI = MI;
359  ++MI;
360  MBB->erase(DeleteMI);
361  End = MBB->end();
362  continue;
363  }
364  ++MI;
365  }
366  }
367 
368  // Loop over all of the basic blocks.
369  for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
370  MBB != MBBe; ++MBB) {
371  // Find scheduling regions and schedule / packetize each region.
372  unsigned RemainingCount = MBB->size();
373  for(MachineBasicBlock::iterator RegionEnd = MBB->end();
374  RegionEnd != MBB->begin();) {
375  // The next region starts above the previous region. Look backward in the
376  // instruction stream until we find the nearest boundary.
377  MachineBasicBlock::iterator I = RegionEnd;
378  for(;I != MBB->begin(); --I, --RemainingCount) {
379  if (TII->isSchedulingBoundary(*std::prev(I), &*MBB, Fn))
380  break;
381  }
382  I = MBB->begin();
383 
384  // Skip empty scheduling regions.
385  if (I == RegionEnd) {
386  RegionEnd = std::prev(RegionEnd);
387  --RemainingCount;
388  continue;
389  }
390  // Skip regions with one instruction.
391  if (I == std::prev(RegionEnd)) {
392  RegionEnd = std::prev(RegionEnd);
393  continue;
394  }
395 
396  Packetizer.PacketizeMIs(&*MBB, &*I, RegionEnd);
397  RegionEnd = I;
398  }
399  }
400 
401  return true;
402 
403 }
404 
405 } // end anonymous namespace
406 
408  return new R600Packetizer();
409 }
bool hasCaymanISA() const
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
AMDGPU specific subclass of TargetSubtarget.
Interface definition for R600InstrInfo.
unsigned getHWRegChan(unsigned reg) const
get the HW encoding for a register's channel.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Definition: ScheduleDAG.h:378
A register anti-dependence (aka WAR).
Definition: ScheduleDAG.h:55
AnalysisUsage & addRequired()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
Kind getKind() const
Returns an enum value representing the kind of the dependence.
Definition: ScheduleDAG.h:496
const HexagonRegisterInfo & getRegisterInfo() const
HexagonInstrInfo specifics.
A register output-dependence (aka WAW).
Definition: ScheduleDAG.h:56
virtual MachineBasicBlock::iterator addToPacket(MachineInstr &MI)
hexagon Hexagon Packetizer
void dump() const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:139
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:131
Scheduling dependency.
Definition: ScheduleDAG.h:50
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Represent the analysis usage information of a pass.
const R600InstrInfo * getInstrInfo() const override
static const unsigned End
void setImm(int64_t immVal)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
static void write(bool isBE, void *P, T V)
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
Iterator for intrusive lists based on ilist_node.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
FunctionPass * createR600Packetizer()
llvm_unreachable("Unknown RegBank!")
Representation of each machine instruction.
Definition: MachineInstr.h:59
SUnit * getSUnit() const
Definition: ScheduleDAG.h:490
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
iterator end()
Definition: DenseMap.h:73
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
Definition: ScheduleDAG.h:444
Instructions::iterator instr_iterator
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< SDep, 4 > Succs
All sunit successors.
Definition: ScheduleDAG.h:262
static const Function * getParent(const Value *V)
#define DEBUG(X)
Definition: Debug.h:118
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Scheduling unit. This is a node in the scheduling DAG.
Definition: ScheduleDAG.h:247