R600/SI: Fix incorrect encoding of DS_WRITE_B32 instructions
[oota-llvm.git] / lib / Target / R600 / SIInsertWaits.cpp
1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
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 /// \brief Insert wait instructions for memory reads and writes.
12 ///
13 /// Memory reads and writes are issued asynchronously, so we need to insert
14 /// S_WAITCNT instructions when we want to access any of their results or
15 /// overwrite any register that's used asynchronously.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "AMDGPU.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26
27 using namespace llvm;
28
29 namespace {
30
31 /// \brief One variable for each of the hardware counters
32 typedef union {
33   struct {
34     unsigned VM;
35     unsigned EXP;
36     unsigned LGKM;
37   } Named;
38   unsigned Array[3];
39
40 } Counters;
41
42 typedef Counters RegCounters[512];
43 typedef std::pair<unsigned, unsigned> RegInterval;
44
45 class SIInsertWaits : public MachineFunctionPass {
46
47 private:
48   static char ID;
49   const SIInstrInfo *TII;
50   const SIRegisterInfo *TRI;
51   const MachineRegisterInfo *MRI;
52
53   /// \brief Constant hardware limits
54   static const Counters WaitCounts;
55
56   /// \brief Constant zero value
57   static const Counters ZeroCounts;
58
59   /// \brief Counter values we have already waited on.
60   Counters WaitedOn;
61
62   /// \brief Counter values for last instruction issued.
63   Counters LastIssued;
64
65   /// \brief Registers used by async instructions.
66   RegCounters UsedRegs;
67
68   /// \brief Registers defined by async instructions.
69   RegCounters DefinedRegs;
70
71   /// \brief Different export instruction types seen since last wait.
72   unsigned ExpInstrTypesSeen;
73
74   /// \brief Get increment/decrement amount for this instruction.
75   Counters getHwCounts(MachineInstr &MI);
76
77   /// \brief Is operand relevant for async execution?
78   bool isOpRelevant(MachineOperand &Op);
79
80   /// \brief Get register interval an operand affects.
81   RegInterval getRegInterval(MachineOperand &Op);
82
83   /// \brief Handle instructions async components
84   void pushInstruction(MachineInstr &MI);
85
86   /// \brief Insert the actual wait instruction
87   bool insertWait(MachineBasicBlock &MBB,
88                   MachineBasicBlock::iterator I,
89                   const Counters &Counts);
90
91   /// \brief Do we need def2def checks?
92   bool unorderedDefines(MachineInstr &MI);
93
94   /// \brief Resolve all operand dependencies to counter requirements
95   Counters handleOperands(MachineInstr &MI);
96
97 public:
98   SIInsertWaits(TargetMachine &tm) :
99     MachineFunctionPass(ID),
100     TII(0),
101     TRI(0),
102     ExpInstrTypesSeen(0) { }
103
104   virtual bool runOnMachineFunction(MachineFunction &MF);
105
106   const char *getPassName() const {
107     return "SI insert wait  instructions";
108   }
109
110 };
111
112 } // End anonymous namespace
113
114 char SIInsertWaits::ID = 0;
115
116 const Counters SIInsertWaits::WaitCounts = { { 15, 7, 7 } };
117 const Counters SIInsertWaits::ZeroCounts = { { 0, 0, 0 } };
118
119 FunctionPass *llvm::createSIInsertWaits(TargetMachine &tm) {
120   return new SIInsertWaits(tm);
121 }
122
123 Counters SIInsertWaits::getHwCounts(MachineInstr &MI) {
124
125   uint64_t TSFlags = TII->get(MI.getOpcode()).TSFlags;
126   Counters Result;
127
128   Result.Named.VM = !!(TSFlags & SIInstrFlags::VM_CNT);
129
130   // Only consider stores or EXP for EXP_CNT
131   Result.Named.EXP = !!(TSFlags & SIInstrFlags::EXP_CNT &&
132       (MI.getOpcode() == AMDGPU::EXP || MI.getDesc().mayStore()));
133
134   // LGKM may uses larger values
135   if (TSFlags & SIInstrFlags::LGKM_CNT) {
136
137     const MachineOperand &Op = MI.getOperand(0);
138     assert(Op.isReg() && "First LGKM operand must be a register!");
139
140     unsigned Reg = Op.getReg();
141     unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
142     Result.Named.LGKM = Size > 4 ? 2 : 1;
143
144   } else {
145     Result.Named.LGKM = 0;
146   }
147
148   return Result;
149 }
150
151 bool SIInsertWaits::isOpRelevant(MachineOperand &Op) {
152
153   // Constants are always irrelevant
154   if (!Op.isReg())
155     return false;
156
157   // Defines are always relevant
158   if (Op.isDef())
159     return true;
160
161   // For exports all registers are relevant
162   MachineInstr &MI = *Op.getParent();
163   if (MI.getOpcode() == AMDGPU::EXP)
164     return true;
165
166   // For stores the stored value is also relevant
167   if (!MI.getDesc().mayStore())
168     return false;
169
170   for (MachineInstr::mop_iterator I = MI.operands_begin(),
171        E = MI.operands_end(); I != E; ++I) {
172
173     if (I->isReg() && I->isUse())
174       return Op.isIdenticalTo(*I);
175   }
176
177   return false;
178 }
179
180 RegInterval SIInsertWaits::getRegInterval(MachineOperand &Op) {
181
182   if (!Op.isReg())
183     return std::make_pair(0, 0);
184
185   unsigned Reg = Op.getReg();
186   unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
187
188   assert(Size >= 4);
189
190   RegInterval Result;
191   Result.first = TRI->getEncodingValue(Reg);
192   Result.second = Result.first + Size / 4;
193
194   return Result;
195 }
196
197 void SIInsertWaits::pushInstruction(MachineInstr &MI) {
198
199   // Get the hardware counter increments and sum them up
200   Counters Increment = getHwCounts(MI);
201   unsigned Sum = 0;
202
203   for (unsigned i = 0; i < 3; ++i) {
204     LastIssued.Array[i] += Increment.Array[i];
205     Sum += Increment.Array[i];
206   }
207
208   // If we don't increase anything then that's it
209   if (Sum == 0)
210     return;
211
212   // Remember which export instructions we have seen
213   if (Increment.Named.EXP) {
214     ExpInstrTypesSeen |= MI.getOpcode() == AMDGPU::EXP ? 1 : 2;
215   }
216
217   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
218
219     MachineOperand &Op = MI.getOperand(i);
220     if (!isOpRelevant(Op))
221       continue;
222
223     RegInterval Interval = getRegInterval(Op);
224     for (unsigned j = Interval.first; j < Interval.second; ++j) {
225
226       // Remember which registers we define
227       if (Op.isDef())
228         DefinedRegs[j] = LastIssued;
229
230       // and which one we are using
231       if (Op.isUse())
232         UsedRegs[j] = LastIssued;
233     }
234   }
235 }
236
237 bool SIInsertWaits::insertWait(MachineBasicBlock &MBB,
238                                MachineBasicBlock::iterator I,
239                                const Counters &Required) {
240
241   // End of program? No need to wait on anything
242   if (I != MBB.end() && I->getOpcode() == AMDGPU::S_ENDPGM)
243     return false;
244
245   // Figure out if the async instructions execute in order
246   bool Ordered[3];
247
248   // VM_CNT is always ordered
249   Ordered[0] = true;
250
251   // EXP_CNT is unordered if we have both EXP & VM-writes
252   Ordered[1] = ExpInstrTypesSeen == 3;
253
254   // LGKM_CNT is handled as always unordered. TODO: Handle LDS and GDS
255   Ordered[2] = false;
256
257   // The values we are going to put into the S_WAITCNT instruction
258   Counters Counts = WaitCounts;
259
260   // Do we really need to wait?
261   bool NeedWait = false;
262
263   for (unsigned i = 0; i < 3; ++i) {
264
265     if (Required.Array[i] <= WaitedOn.Array[i])
266       continue;
267
268     NeedWait = true;
269     
270     if (Ordered[i]) {
271       unsigned Value = LastIssued.Array[i] - Required.Array[i];
272
273       // adjust the value to the real hardware posibilities
274       Counts.Array[i] = std::min(Value, WaitCounts.Array[i]);
275
276     } else
277       Counts.Array[i] = 0;
278
279     // Remember on what we have waited on
280     WaitedOn.Array[i] = LastIssued.Array[i] - Counts.Array[i];
281   }
282
283   if (!NeedWait)
284     return false;
285
286   // Reset EXP_CNT instruction types
287   if (Counts.Named.EXP == 0)
288     ExpInstrTypesSeen = 0;
289
290   // Build the wait instruction
291   BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
292           .addImm((Counts.Named.VM & 0xF) |
293                   ((Counts.Named.EXP & 0x7) << 4) |
294                   ((Counts.Named.LGKM & 0x7) << 8));
295
296   return true;
297 }
298
299 /// \brief helper function for handleOperands
300 static void increaseCounters(Counters &Dst, const Counters &Src) {
301
302   for (unsigned i = 0; i < 3; ++i)
303     Dst.Array[i] = std::max(Dst.Array[i], Src.Array[i]);
304 }
305
306 Counters SIInsertWaits::handleOperands(MachineInstr &MI) {
307
308   Counters Result = ZeroCounts;
309
310   // For each register affected by this
311   // instruction increase the result sequence
312   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
313
314     MachineOperand &Op = MI.getOperand(i);
315     RegInterval Interval = getRegInterval(Op);
316     for (unsigned j = Interval.first; j < Interval.second; ++j) {
317
318       if (Op.isDef()) {
319         increaseCounters(Result, UsedRegs[j]);
320         increaseCounters(Result, DefinedRegs[j]);
321       }
322
323       if (Op.isUse())
324         increaseCounters(Result, DefinedRegs[j]);
325     }
326   }
327
328   return Result;
329 }
330
331 bool SIInsertWaits::runOnMachineFunction(MachineFunction &MF) {
332   bool Changes = false;
333
334   TII = static_cast<const SIInstrInfo*>(MF.getTarget().getInstrInfo());
335   TRI = static_cast<const SIRegisterInfo*>(MF.getTarget().getRegisterInfo());
336
337   MRI = &MF.getRegInfo();
338
339   WaitedOn = ZeroCounts;
340   LastIssued = ZeroCounts;
341
342   memset(&UsedRegs, 0, sizeof(UsedRegs));
343   memset(&DefinedRegs, 0, sizeof(DefinedRegs));
344
345   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
346        BI != BE; ++BI) {
347
348     MachineBasicBlock &MBB = *BI;
349     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
350          I != E; ++I) {
351
352       Changes |= insertWait(MBB, I, handleOperands(*I));
353       pushInstruction(*I);
354     }
355
356     // Wait for everything at the end of the MBB
357     Changes |= insertWait(MBB, MBB.getFirstTerminator(), LastIssued);
358   }
359
360   return Changes;
361 }