R600/SI: Spill VGPRs to scratch space for compute shaders
[oota-llvm.git] / lib / Target / R600 / SIInstrInfo.cpp
1 //===-- SIInstrInfo.cpp - SI Instruction Information  ---------------------===//
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 SI Implementation of TargetInstrInfo.
12 //
13 //===----------------------------------------------------------------------===//
14
15
16 #include "SIInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIDefines.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/MC/MCInstrDesc.h"
26 #include "llvm/Support/Debug.h"
27
28 using namespace llvm;
29
30 SIInstrInfo::SIInstrInfo(const AMDGPUSubtarget &st)
31   : AMDGPUInstrInfo(st),
32     RI(st) { }
33
34 //===----------------------------------------------------------------------===//
35 // TargetInstrInfo callbacks
36 //===----------------------------------------------------------------------===//
37
38 static unsigned getNumOperandsNoGlue(SDNode *Node) {
39   unsigned N = Node->getNumOperands();
40   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
41     --N;
42   return N;
43 }
44
45 static SDValue findChainOperand(SDNode *Load) {
46   SDValue LastOp = Load->getOperand(getNumOperandsNoGlue(Load) - 1);
47   assert(LastOp.getValueType() == MVT::Other && "Chain missing from load node");
48   return LastOp;
49 }
50
51 /// \brief Returns true if both nodes have the same value for the given
52 ///        operand \p Op, or if both nodes do not have this operand.
53 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
54   unsigned Opc0 = N0->getMachineOpcode();
55   unsigned Opc1 = N1->getMachineOpcode();
56
57   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
58   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
59
60   if (Op0Idx == -1 && Op1Idx == -1)
61     return true;
62
63
64   if ((Op0Idx == -1 && Op1Idx != -1) ||
65       (Op1Idx == -1 && Op0Idx != -1))
66     return false;
67
68   // getNamedOperandIdx returns the index for the MachineInstr's operands,
69   // which includes the result as the first operand. We are indexing into the
70   // MachineSDNode's operands, so we need to skip the result operand to get
71   // the real index.
72   --Op0Idx;
73   --Op1Idx;
74
75   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
76 }
77
78 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
79                                           int64_t &Offset0,
80                                           int64_t &Offset1) const {
81   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
82     return false;
83
84   unsigned Opc0 = Load0->getMachineOpcode();
85   unsigned Opc1 = Load1->getMachineOpcode();
86
87   // Make sure both are actually loads.
88   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
89     return false;
90
91   if (isDS(Opc0) && isDS(Opc1)) {
92
93     // FIXME: Handle this case:
94     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
95       return false;
96
97     // Check base reg.
98     if (Load0->getOperand(1) != Load1->getOperand(1))
99       return false;
100
101     // Check chain.
102     if (findChainOperand(Load0) != findChainOperand(Load1))
103       return false;
104
105     // Skip read2 / write2 variants for simplicity.
106     // TODO: We should report true if the used offsets are adjacent (excluded
107     // st64 versions).
108     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
109         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
110       return false;
111
112     Offset0 = cast<ConstantSDNode>(Load0->getOperand(2))->getZExtValue();
113     Offset1 = cast<ConstantSDNode>(Load1->getOperand(2))->getZExtValue();
114     return true;
115   }
116
117   if (isSMRD(Opc0) && isSMRD(Opc1)) {
118     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
119
120     // Check base reg.
121     if (Load0->getOperand(0) != Load1->getOperand(0))
122       return false;
123
124     // Check chain.
125     if (findChainOperand(Load0) != findChainOperand(Load1))
126       return false;
127
128     Offset0 = cast<ConstantSDNode>(Load0->getOperand(1))->getZExtValue();
129     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getZExtValue();
130     return true;
131   }
132
133   // MUBUF and MTBUF can access the same addresses.
134   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
135
136     // MUBUF and MTBUF have vaddr at different indices.
137     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
138         findChainOperand(Load0) != findChainOperand(Load1) ||
139         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
140         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
141       return false;
142
143     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
144     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
145
146     if (OffIdx0 == -1 || OffIdx1 == -1)
147       return false;
148
149     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
150     // inlcude the output in the operand list, but SDNodes don't, we need to
151     // subtract the index by one.
152     --OffIdx0;
153     --OffIdx1;
154
155     SDValue Off0 = Load0->getOperand(OffIdx0);
156     SDValue Off1 = Load1->getOperand(OffIdx1);
157
158     // The offset might be a FrameIndexSDNode.
159     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
160       return false;
161
162     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
163     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
164     return true;
165   }
166
167   return false;
168 }
169
170 static bool isStride64(unsigned Opc) {
171   switch (Opc) {
172   case AMDGPU::DS_READ2ST64_B32:
173   case AMDGPU::DS_READ2ST64_B64:
174   case AMDGPU::DS_WRITE2ST64_B32:
175   case AMDGPU::DS_WRITE2ST64_B64:
176     return true;
177   default:
178     return false;
179   }
180 }
181
182 bool SIInstrInfo::getLdStBaseRegImmOfs(MachineInstr *LdSt,
183                                        unsigned &BaseReg, unsigned &Offset,
184                                        const TargetRegisterInfo *TRI) const {
185   unsigned Opc = LdSt->getOpcode();
186   if (isDS(Opc)) {
187     const MachineOperand *OffsetImm = getNamedOperand(*LdSt,
188                                                       AMDGPU::OpName::offset);
189     if (OffsetImm) {
190       // Normal, single offset LDS instruction.
191       const MachineOperand *AddrReg = getNamedOperand(*LdSt,
192                                                       AMDGPU::OpName::addr);
193
194       BaseReg = AddrReg->getReg();
195       Offset = OffsetImm->getImm();
196       return true;
197     }
198
199     // The 2 offset instructions use offset0 and offset1 instead. We can treat
200     // these as a load with a single offset if the 2 offsets are consecutive. We
201     // will use this for some partially aligned loads.
202     const MachineOperand *Offset0Imm = getNamedOperand(*LdSt,
203                                                        AMDGPU::OpName::offset0);
204     const MachineOperand *Offset1Imm = getNamedOperand(*LdSt,
205                                                        AMDGPU::OpName::offset1);
206
207     uint8_t Offset0 = Offset0Imm->getImm();
208     uint8_t Offset1 = Offset1Imm->getImm();
209     assert(Offset1 > Offset0);
210
211     if (Offset1 - Offset0 == 1) {
212       // Each of these offsets is in element sized units, so we need to convert
213       // to bytes of the individual reads.
214
215       unsigned EltSize;
216       if (LdSt->mayLoad())
217         EltSize = getOpRegClass(*LdSt, 0)->getSize() / 2;
218       else {
219         assert(LdSt->mayStore());
220         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
221         EltSize = getOpRegClass(*LdSt, Data0Idx)->getSize();
222       }
223
224       if (isStride64(Opc))
225         EltSize *= 64;
226
227       const MachineOperand *AddrReg = getNamedOperand(*LdSt,
228                                                       AMDGPU::OpName::addr);
229       BaseReg = AddrReg->getReg();
230       Offset = EltSize * Offset0;
231       return true;
232     }
233
234     return false;
235   }
236
237   if (isMUBUF(Opc) || isMTBUF(Opc)) {
238     if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::soffset) != -1)
239       return false;
240
241     const MachineOperand *AddrReg = getNamedOperand(*LdSt,
242                                                     AMDGPU::OpName::vaddr);
243     if (!AddrReg)
244       return false;
245
246     const MachineOperand *OffsetImm = getNamedOperand(*LdSt,
247                                                       AMDGPU::OpName::offset);
248     BaseReg = AddrReg->getReg();
249     Offset = OffsetImm->getImm();
250     return true;
251   }
252
253   if (isSMRD(Opc)) {
254     const MachineOperand *OffsetImm = getNamedOperand(*LdSt,
255                                                       AMDGPU::OpName::offset);
256     if (!OffsetImm)
257       return false;
258
259     const MachineOperand *SBaseReg = getNamedOperand(*LdSt,
260                                                      AMDGPU::OpName::sbase);
261     BaseReg = SBaseReg->getReg();
262     Offset = OffsetImm->getImm();
263     return true;
264   }
265
266   return false;
267 }
268
269 bool SIInstrInfo::shouldClusterLoads(MachineInstr *FirstLdSt,
270                                      MachineInstr *SecondLdSt,
271                                      unsigned NumLoads) const {
272   unsigned Opc0 = FirstLdSt->getOpcode();
273   unsigned Opc1 = SecondLdSt->getOpcode();
274
275   // TODO: This needs finer tuning
276   if (NumLoads > 4)
277     return false;
278
279   if (isDS(Opc0) && isDS(Opc1))
280     return true;
281
282   if (isSMRD(Opc0) && isSMRD(Opc1))
283     return true;
284
285   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1)))
286     return true;
287
288   return false;
289 }
290
291 void
292 SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
293                          MachineBasicBlock::iterator MI, DebugLoc DL,
294                          unsigned DestReg, unsigned SrcReg,
295                          bool KillSrc) const {
296
297   // If we are trying to copy to or from SCC, there is a bug somewhere else in
298   // the backend.  While it may be theoretically possible to do this, it should
299   // never be necessary.
300   assert(DestReg != AMDGPU::SCC && SrcReg != AMDGPU::SCC);
301
302   static const int16_t Sub0_15[] = {
303     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
304     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
305     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
306     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15, 0
307   };
308
309   static const int16_t Sub0_7[] = {
310     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
311     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7, 0
312   };
313
314   static const int16_t Sub0_3[] = {
315     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3, 0
316   };
317
318   static const int16_t Sub0_2[] = {
319     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, 0
320   };
321
322   static const int16_t Sub0_1[] = {
323     AMDGPU::sub0, AMDGPU::sub1, 0
324   };
325
326   unsigned Opcode;
327   const int16_t *SubIndices;
328
329   if (AMDGPU::SReg_32RegClass.contains(DestReg)) {
330     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
331     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
332             .addReg(SrcReg, getKillRegState(KillSrc));
333     return;
334
335   } else if (AMDGPU::SReg_64RegClass.contains(DestReg)) {
336     assert(AMDGPU::SReg_64RegClass.contains(SrcReg));
337     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
338             .addReg(SrcReg, getKillRegState(KillSrc));
339     return;
340
341   } else if (AMDGPU::SReg_128RegClass.contains(DestReg)) {
342     assert(AMDGPU::SReg_128RegClass.contains(SrcReg));
343     Opcode = AMDGPU::S_MOV_B32;
344     SubIndices = Sub0_3;
345
346   } else if (AMDGPU::SReg_256RegClass.contains(DestReg)) {
347     assert(AMDGPU::SReg_256RegClass.contains(SrcReg));
348     Opcode = AMDGPU::S_MOV_B32;
349     SubIndices = Sub0_7;
350
351   } else if (AMDGPU::SReg_512RegClass.contains(DestReg)) {
352     assert(AMDGPU::SReg_512RegClass.contains(SrcReg));
353     Opcode = AMDGPU::S_MOV_B32;
354     SubIndices = Sub0_15;
355
356   } else if (AMDGPU::VGPR_32RegClass.contains(DestReg)) {
357     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
358            AMDGPU::SReg_32RegClass.contains(SrcReg));
359     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
360             .addReg(SrcReg, getKillRegState(KillSrc));
361     return;
362
363   } else if (AMDGPU::VReg_64RegClass.contains(DestReg)) {
364     assert(AMDGPU::VReg_64RegClass.contains(SrcReg) ||
365            AMDGPU::SReg_64RegClass.contains(SrcReg));
366     Opcode = AMDGPU::V_MOV_B32_e32;
367     SubIndices = Sub0_1;
368
369   } else if (AMDGPU::VReg_96RegClass.contains(DestReg)) {
370     assert(AMDGPU::VReg_96RegClass.contains(SrcReg));
371     Opcode = AMDGPU::V_MOV_B32_e32;
372     SubIndices = Sub0_2;
373
374   } else if (AMDGPU::VReg_128RegClass.contains(DestReg)) {
375     assert(AMDGPU::VReg_128RegClass.contains(SrcReg) ||
376            AMDGPU::SReg_128RegClass.contains(SrcReg));
377     Opcode = AMDGPU::V_MOV_B32_e32;
378     SubIndices = Sub0_3;
379
380   } else if (AMDGPU::VReg_256RegClass.contains(DestReg)) {
381     assert(AMDGPU::VReg_256RegClass.contains(SrcReg) ||
382            AMDGPU::SReg_256RegClass.contains(SrcReg));
383     Opcode = AMDGPU::V_MOV_B32_e32;
384     SubIndices = Sub0_7;
385
386   } else if (AMDGPU::VReg_512RegClass.contains(DestReg)) {
387     assert(AMDGPU::VReg_512RegClass.contains(SrcReg) ||
388            AMDGPU::SReg_512RegClass.contains(SrcReg));
389     Opcode = AMDGPU::V_MOV_B32_e32;
390     SubIndices = Sub0_15;
391
392   } else {
393     llvm_unreachable("Can't copy register!");
394   }
395
396   while (unsigned SubIdx = *SubIndices++) {
397     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
398       get(Opcode), RI.getSubReg(DestReg, SubIdx));
399
400     Builder.addReg(RI.getSubReg(SrcReg, SubIdx), getKillRegState(KillSrc));
401
402     if (*SubIndices)
403       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
404   }
405 }
406
407 unsigned SIInstrInfo::commuteOpcode(unsigned Opcode) const {
408   int NewOpc;
409
410   // Try to map original to commuted opcode
411   if ((NewOpc = AMDGPU::getCommuteRev(Opcode)) != -1)
412     return NewOpc;
413
414   // Try to map commuted to original opcode
415   if ((NewOpc = AMDGPU::getCommuteOrig(Opcode)) != -1)
416     return NewOpc;
417
418   return Opcode;
419 }
420
421 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
422
423   if (DstRC->getSize() == 4) {
424     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
425   } else if (DstRC->getSize() == 8 && RI.isSGPRClass(DstRC)) {
426     return AMDGPU::S_MOV_B64;
427   } else if (DstRC->getSize() == 8 && !RI.isSGPRClass(DstRC)) {
428     return  AMDGPU::V_MOV_B64_PSEUDO;
429   }
430   return AMDGPU::COPY;
431 }
432
433 static bool shouldTryToSpillVGPRs(MachineFunction *MF) {
434
435   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
436
437   // FIXME: Implement spilling for other shader types.
438   return MFI->getShaderType() == ShaderType::COMPUTE;
439
440 }
441
442 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
443                                       MachineBasicBlock::iterator MI,
444                                       unsigned SrcReg, bool isKill,
445                                       int FrameIndex,
446                                       const TargetRegisterClass *RC,
447                                       const TargetRegisterInfo *TRI) const {
448   MachineFunction *MF = MBB.getParent();
449   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
450   MachineFrameInfo *FrameInfo = MF->getFrameInfo();
451   DebugLoc DL = MBB.findDebugLoc(MI);
452   int Opcode = -1;
453
454   if (RI.isSGPRClass(RC)) {
455     // We are only allowed to create one new instruction when spilling
456     // registers, so we need to use pseudo instruction for spilling
457     // SGPRs.
458     switch (RC->getSize() * 8) {
459       case 32:  Opcode = AMDGPU::SI_SPILL_S32_SAVE;  break;
460       case 64:  Opcode = AMDGPU::SI_SPILL_S64_SAVE;  break;
461       case 128: Opcode = AMDGPU::SI_SPILL_S128_SAVE; break;
462       case 256: Opcode = AMDGPU::SI_SPILL_S256_SAVE; break;
463       case 512: Opcode = AMDGPU::SI_SPILL_S512_SAVE; break;
464     }
465   } else if(shouldTryToSpillVGPRs(MF) && RI.hasVGPRs(RC)) {
466     MFI->setHasSpilledVGPRs();
467
468     switch(RC->getSize() * 8) {
469       case 32: Opcode = AMDGPU::SI_SPILL_V32_SAVE; break;
470       case 64: Opcode = AMDGPU::SI_SPILL_V64_SAVE; break;
471       case 96: Opcode = AMDGPU::SI_SPILL_V96_SAVE; break;
472       case 128: Opcode = AMDGPU::SI_SPILL_V128_SAVE; break;
473       case 256: Opcode = AMDGPU::SI_SPILL_V256_SAVE; break;
474       case 512: Opcode = AMDGPU::SI_SPILL_V512_SAVE; break;
475     }
476   }
477
478   if (Opcode != -1) {
479     FrameInfo->setObjectAlignment(FrameIndex, 4);
480     BuildMI(MBB, MI, DL, get(Opcode))
481             .addReg(SrcReg)
482             .addFrameIndex(FrameIndex)
483             // Place-holder registers, these will be filled in by
484             // SIPrepareScratchRegs.
485             .addReg(AMDGPU::SGPR0_SGPR1, RegState::Undef)
486             .addReg(AMDGPU::SGPR0, RegState::Undef);
487   } else {
488     LLVMContext &Ctx = MF->getFunction()->getContext();
489     Ctx.emitError("SIInstrInfo::storeRegToStackSlot - Do not know how to"
490                   " spill register");
491     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), AMDGPU::VGPR0)
492             .addReg(SrcReg);
493   }
494 }
495
496 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
497                                        MachineBasicBlock::iterator MI,
498                                        unsigned DestReg, int FrameIndex,
499                                        const TargetRegisterClass *RC,
500                                        const TargetRegisterInfo *TRI) const {
501   MachineFunction *MF = MBB.getParent();
502   MachineFrameInfo *FrameInfo = MF->getFrameInfo();
503   DebugLoc DL = MBB.findDebugLoc(MI);
504   int Opcode = -1;
505
506   if (RI.isSGPRClass(RC)){
507     switch(RC->getSize() * 8) {
508       case 32:  Opcode = AMDGPU::SI_SPILL_S32_RESTORE; break;
509       case 64:  Opcode = AMDGPU::SI_SPILL_S64_RESTORE;  break;
510       case 128: Opcode = AMDGPU::SI_SPILL_S128_RESTORE; break;
511       case 256: Opcode = AMDGPU::SI_SPILL_S256_RESTORE; break;
512       case 512: Opcode = AMDGPU::SI_SPILL_S512_RESTORE; break;
513     }
514   } else if(shouldTryToSpillVGPRs(MF) && RI.hasVGPRs(RC)) {
515     switch(RC->getSize() * 8) {
516       case 32: Opcode = AMDGPU::SI_SPILL_V32_RESTORE; break;
517       case 64: Opcode = AMDGPU::SI_SPILL_V64_RESTORE; break;
518       case 96: Opcode = AMDGPU::SI_SPILL_V96_RESTORE; break;
519       case 128: Opcode = AMDGPU::SI_SPILL_V128_RESTORE; break;
520       case 256: Opcode = AMDGPU::SI_SPILL_V256_RESTORE; break;
521       case 512: Opcode = AMDGPU::SI_SPILL_V512_RESTORE; break;
522     }
523   }
524
525   if (Opcode != -1) {
526     FrameInfo->setObjectAlignment(FrameIndex, 4);
527     BuildMI(MBB, MI, DL, get(Opcode), DestReg)
528             .addFrameIndex(FrameIndex)
529             // Place-holder registers, these will be filled in by
530             // SIPrepareScratchRegs.
531             .addReg(AMDGPU::SGPR0_SGPR1, RegState::Undef)
532             .addReg(AMDGPU::SGPR0, RegState::Undef);
533
534   } else {
535     LLVMContext &Ctx = MF->getFunction()->getContext();
536     Ctx.emitError("SIInstrInfo::loadRegFromStackSlot - Do not know how to"
537                   " restore register");
538     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
539             .addReg(AMDGPU::VGPR0);
540   }
541 }
542
543 /// \param @Offset Offset in bytes of the FrameIndex being spilled
544 unsigned SIInstrInfo::calculateLDSSpillAddress(MachineBasicBlock &MBB,
545                                                MachineBasicBlock::iterator MI,
546                                                RegScavenger *RS, unsigned TmpReg,
547                                                unsigned FrameOffset,
548                                                unsigned Size) const {
549   MachineFunction *MF = MBB.getParent();
550   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
551   const AMDGPUSubtarget &ST = MF->getTarget().getSubtarget<AMDGPUSubtarget>();
552   const SIRegisterInfo *TRI =
553       static_cast<const SIRegisterInfo*>(ST.getRegisterInfo());
554   DebugLoc DL = MBB.findDebugLoc(MI);
555   unsigned WorkGroupSize = MFI->getMaximumWorkGroupSize(*MF);
556   unsigned WavefrontSize = ST.getWavefrontSize();
557
558   unsigned TIDReg = MFI->getTIDReg();
559   if (!MFI->hasCalculatedTID()) {
560     MachineBasicBlock &Entry = MBB.getParent()->front();
561     MachineBasicBlock::iterator Insert = Entry.front();
562     DebugLoc DL = Insert->getDebugLoc();
563
564     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass);
565     if (TIDReg == AMDGPU::NoRegister)
566       return TIDReg;
567
568
569     if (MFI->getShaderType() == ShaderType::COMPUTE &&
570         WorkGroupSize > WavefrontSize) {
571
572       unsigned TIDIGXReg = TRI->getPreloadedValue(*MF, SIRegisterInfo::TIDIG_X);
573       unsigned TIDIGYReg = TRI->getPreloadedValue(*MF, SIRegisterInfo::TIDIG_Y);
574       unsigned TIDIGZReg = TRI->getPreloadedValue(*MF, SIRegisterInfo::TIDIG_Z);
575       unsigned InputPtrReg =
576           TRI->getPreloadedValue(*MF, SIRegisterInfo::INPUT_PTR);
577       static const unsigned TIDIGRegs[3] = {
578         TIDIGXReg, TIDIGYReg, TIDIGZReg
579       };
580       for (unsigned Reg : TIDIGRegs) {
581         if (!Entry.isLiveIn(Reg))
582           Entry.addLiveIn(Reg);
583       }
584
585       RS->enterBasicBlock(&Entry);
586       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
587       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
588       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
589               .addReg(InputPtrReg)
590               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
591       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
592               .addReg(InputPtrReg)
593               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
594
595       // NGROUPS.X * NGROUPS.Y
596       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
597               .addReg(STmp1)
598               .addReg(STmp0);
599       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
600       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
601               .addReg(STmp1)
602               .addReg(TIDIGXReg);
603       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
604       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
605               .addReg(STmp0)
606               .addReg(TIDIGYReg)
607               .addReg(TIDReg);
608       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
609       BuildMI(Entry, Insert, DL, get(AMDGPU::V_ADD_I32_e32), TIDReg)
610               .addReg(TIDReg)
611               .addReg(TIDIGZReg);
612     } else {
613       // Get the wave id
614       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
615               TIDReg)
616               .addImm(-1)
617               .addImm(0);
618
619       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e32),
620               TIDReg)
621               .addImm(-1)
622               .addReg(TIDReg);
623     }
624
625     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
626             TIDReg)
627             .addImm(2)
628             .addReg(TIDReg);
629     MFI->setTIDReg(TIDReg);
630   }
631
632   // Add FrameIndex to LDS offset
633   unsigned LDSOffset = MFI->LDSSize + (FrameOffset * WorkGroupSize);
634   BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), TmpReg)
635           .addImm(LDSOffset)
636           .addReg(TIDReg);
637
638   return TmpReg;
639 }
640
641 void SIInstrInfo::insertNOPs(MachineBasicBlock::iterator MI,
642                              int Count) const {
643   while (Count > 0) {
644     int Arg;
645     if (Count >= 8)
646       Arg = 7;
647     else
648       Arg = Count - 1;
649     Count -= 8;
650     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(AMDGPU::S_NOP))
651             .addImm(Arg);
652   }
653 }
654
655 bool SIInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
656   MachineBasicBlock &MBB = *MI->getParent();
657   DebugLoc DL = MBB.findDebugLoc(MI);
658   switch (MI->getOpcode()) {
659   default: return AMDGPUInstrInfo::expandPostRAPseudo(MI);
660
661   case AMDGPU::SI_CONSTDATA_PTR: {
662     unsigned Reg = MI->getOperand(0).getReg();
663     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
664     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
665
666     BuildMI(MBB, MI, DL, get(AMDGPU::S_GETPC_B64), Reg);
667
668     // Add 32-bit offset from this instruction to the start of the constant data.
669     BuildMI(MBB, MI, DL, get(AMDGPU::S_ADD_U32), RegLo)
670             .addReg(RegLo)
671             .addTargetIndex(AMDGPU::TI_CONSTDATA_START)
672             .addReg(AMDGPU::SCC, RegState::Define | RegState::Implicit);
673     BuildMI(MBB, MI, DL, get(AMDGPU::S_ADDC_U32), RegHi)
674             .addReg(RegHi)
675             .addImm(0)
676             .addReg(AMDGPU::SCC, RegState::Define | RegState::Implicit)
677             .addReg(AMDGPU::SCC, RegState::Implicit);
678     MI->eraseFromParent();
679     break;
680   }
681   case AMDGPU::SGPR_USE:
682     // This is just a placeholder for register allocation.
683     MI->eraseFromParent();
684     break;
685
686   case AMDGPU::V_MOV_B64_PSEUDO: {
687     unsigned Dst = MI->getOperand(0).getReg();
688     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
689     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
690
691     const MachineOperand &SrcOp = MI->getOperand(1);
692     // FIXME: Will this work for 64-bit floating point immediates?
693     assert(!SrcOp.isFPImm());
694     if (SrcOp.isImm()) {
695       APInt Imm(64, SrcOp.getImm());
696       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
697               .addImm(Imm.getLoBits(32).getZExtValue())
698               .addReg(Dst, RegState::Implicit);
699       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
700               .addImm(Imm.getHiBits(32).getZExtValue())
701               .addReg(Dst, RegState::Implicit);
702     } else {
703       assert(SrcOp.isReg());
704       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
705               .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
706               .addReg(Dst, RegState::Implicit);
707       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
708               .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
709               .addReg(Dst, RegState::Implicit);
710     }
711     MI->eraseFromParent();
712     break;
713   }
714   }
715   return true;
716 }
717
718 MachineInstr *SIInstrInfo::commuteInstruction(MachineInstr *MI,
719                                               bool NewMI) const {
720
721   if (MI->getNumOperands() < 3)
722     return nullptr;
723
724   int Src0Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
725                                            AMDGPU::OpName::src0);
726   assert(Src0Idx != -1 && "Should always have src0 operand");
727
728   MachineOperand &Src0 = MI->getOperand(Src0Idx);
729   if (!Src0.isReg())
730     return nullptr;
731
732   int Src1Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
733                                            AMDGPU::OpName::src1);
734   if (Src1Idx == -1)
735     return nullptr;
736
737   MachineOperand &Src1 = MI->getOperand(Src1Idx);
738
739   // Make sure it's legal to commute operands for VOP2.
740   if (isVOP2(MI->getOpcode()) &&
741       (!isOperandLegal(MI, Src0Idx, &Src1) ||
742        !isOperandLegal(MI, Src1Idx, &Src0))) {
743     return nullptr;
744     }
745
746   if (!Src1.isReg()) {
747     // Allow commuting instructions with Imm operands.
748     if (NewMI || !Src1.isImm() ||
749        (!isVOP2(MI->getOpcode()) && !isVOP3(MI->getOpcode()))) {
750       return nullptr;
751     }
752
753     // Be sure to copy the source modifiers to the right place.
754     if (MachineOperand *Src0Mods
755           = getNamedOperand(*MI, AMDGPU::OpName::src0_modifiers)) {
756       MachineOperand *Src1Mods
757         = getNamedOperand(*MI, AMDGPU::OpName::src1_modifiers);
758
759       int Src0ModsVal = Src0Mods->getImm();
760       if (!Src1Mods && Src0ModsVal != 0)
761         return nullptr;
762
763       // XXX - This assert might be a lie. It might be useful to have a neg
764       // modifier with 0.0.
765       int Src1ModsVal = Src1Mods->getImm();
766       assert((Src1ModsVal == 0) && "Not expecting modifiers with immediates");
767
768       Src1Mods->setImm(Src0ModsVal);
769       Src0Mods->setImm(Src1ModsVal);
770     }
771
772     unsigned Reg = Src0.getReg();
773     unsigned SubReg = Src0.getSubReg();
774     if (Src1.isImm())
775       Src0.ChangeToImmediate(Src1.getImm());
776     else
777       llvm_unreachable("Should only have immediates");
778
779     Src1.ChangeToRegister(Reg, false);
780     Src1.setSubReg(SubReg);
781   } else {
782     MI = TargetInstrInfo::commuteInstruction(MI, NewMI);
783   }
784
785   if (MI)
786     MI->setDesc(get(commuteOpcode(MI->getOpcode())));
787
788   return MI;
789 }
790
791 // This needs to be implemented because the source modifiers may be inserted
792 // between the true commutable operands, and the base
793 // TargetInstrInfo::commuteInstruction uses it.
794 bool SIInstrInfo::findCommutedOpIndices(MachineInstr *MI,
795                                         unsigned &SrcOpIdx1,
796                                         unsigned &SrcOpIdx2) const {
797   const MCInstrDesc &MCID = MI->getDesc();
798   if (!MCID.isCommutable())
799     return false;
800
801   unsigned Opc = MI->getOpcode();
802   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
803   if (Src0Idx == -1)
804     return false;
805
806   // FIXME: Workaround TargetInstrInfo::commuteInstruction asserting on
807   // immediate.
808   if (!MI->getOperand(Src0Idx).isReg())
809     return false;
810
811   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
812   if (Src1Idx == -1)
813     return false;
814
815   if (!MI->getOperand(Src1Idx).isReg())
816     return false;
817
818   // If any source modifiers are set, the generic instruction commuting won't
819   // understand how to copy the source modifiers.
820   if (hasModifiersSet(*MI, AMDGPU::OpName::src0_modifiers) ||
821       hasModifiersSet(*MI, AMDGPU::OpName::src1_modifiers))
822     return false;
823
824   SrcOpIdx1 = Src0Idx;
825   SrcOpIdx2 = Src1Idx;
826   return true;
827 }
828
829 MachineInstr *SIInstrInfo::buildMovInstr(MachineBasicBlock *MBB,
830                                          MachineBasicBlock::iterator I,
831                                          unsigned DstReg,
832                                          unsigned SrcReg) const {
833   return BuildMI(*MBB, I, MBB->findDebugLoc(I), get(AMDGPU::V_MOV_B32_e32),
834                  DstReg) .addReg(SrcReg);
835 }
836
837 bool SIInstrInfo::isMov(unsigned Opcode) const {
838   switch(Opcode) {
839   default: return false;
840   case AMDGPU::S_MOV_B32:
841   case AMDGPU::S_MOV_B64:
842   case AMDGPU::V_MOV_B32_e32:
843   case AMDGPU::V_MOV_B32_e64:
844     return true;
845   }
846 }
847
848 bool
849 SIInstrInfo::isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
850   return RC != &AMDGPU::EXECRegRegClass;
851 }
852
853 bool
854 SIInstrInfo::isTriviallyReMaterializable(const MachineInstr *MI,
855                                          AliasAnalysis *AA) const {
856   switch(MI->getOpcode()) {
857   default: return AMDGPUInstrInfo::isTriviallyReMaterializable(MI, AA);
858   case AMDGPU::S_MOV_B32:
859   case AMDGPU::S_MOV_B64:
860   case AMDGPU::V_MOV_B32_e32:
861     return MI->getOperand(1).isImm();
862   }
863 }
864
865 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
866                                 int WidthB, int OffsetB) {
867   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
868   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
869   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
870   return LowOffset + LowWidth <= HighOffset;
871 }
872
873 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr *MIa,
874                                                MachineInstr *MIb) const {
875   unsigned BaseReg0, Offset0;
876   unsigned BaseReg1, Offset1;
877
878   if (getLdStBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
879       getLdStBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
880     assert(MIa->hasOneMemOperand() && MIb->hasOneMemOperand() &&
881            "read2 / write2 not expected here yet");
882     unsigned Width0 = (*MIa->memoperands_begin())->getSize();
883     unsigned Width1 = (*MIb->memoperands_begin())->getSize();
884     if (BaseReg0 == BaseReg1 &&
885         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
886       return true;
887     }
888   }
889
890   return false;
891 }
892
893 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr *MIa,
894                                                   MachineInstr *MIb,
895                                                   AliasAnalysis *AA) const {
896   unsigned Opc0 = MIa->getOpcode();
897   unsigned Opc1 = MIb->getOpcode();
898
899   assert(MIa && (MIa->mayLoad() || MIa->mayStore()) &&
900          "MIa must load from or modify a memory location");
901   assert(MIb && (MIb->mayLoad() || MIb->mayStore()) &&
902          "MIb must load from or modify a memory location");
903
904   if (MIa->hasUnmodeledSideEffects() || MIb->hasUnmodeledSideEffects())
905     return false;
906
907   // XXX - Can we relax this between address spaces?
908   if (MIa->hasOrderedMemoryRef() || MIb->hasOrderedMemoryRef())
909     return false;
910
911   // TODO: Should we check the address space from the MachineMemOperand? That
912   // would allow us to distinguish objects we know don't alias based on the
913   // underlying addres space, even if it was lowered to a different one,
914   // e.g. private accesses lowered to use MUBUF instructions on a scratch
915   // buffer.
916   if (isDS(Opc0)) {
917     if (isDS(Opc1))
918       return checkInstOffsetsDoNotOverlap(MIa, MIb);
919
920     return !isFLAT(Opc1);
921   }
922
923   if (isMUBUF(Opc0) || isMTBUF(Opc0)) {
924     if (isMUBUF(Opc1) || isMTBUF(Opc1))
925       return checkInstOffsetsDoNotOverlap(MIa, MIb);
926
927     return !isFLAT(Opc1) && !isSMRD(Opc1);
928   }
929
930   if (isSMRD(Opc0)) {
931     if (isSMRD(Opc1))
932       return checkInstOffsetsDoNotOverlap(MIa, MIb);
933
934     return !isFLAT(Opc1) && !isMUBUF(Opc0) && !isMTBUF(Opc0);
935   }
936
937   if (isFLAT(Opc0)) {
938     if (isFLAT(Opc1))
939       return checkInstOffsetsDoNotOverlap(MIa, MIb);
940
941     return false;
942   }
943
944   return false;
945 }
946
947 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
948   int64_t SVal = Imm.getSExtValue();
949   if (SVal >= -16 && SVal <= 64)
950     return true;
951
952   if (Imm.getBitWidth() == 64) {
953     uint64_t Val = Imm.getZExtValue();
954     return (DoubleToBits(0.0) == Val) ||
955            (DoubleToBits(1.0) == Val) ||
956            (DoubleToBits(-1.0) == Val) ||
957            (DoubleToBits(0.5) == Val) ||
958            (DoubleToBits(-0.5) == Val) ||
959            (DoubleToBits(2.0) == Val) ||
960            (DoubleToBits(-2.0) == Val) ||
961            (DoubleToBits(4.0) == Val) ||
962            (DoubleToBits(-4.0) == Val);
963   }
964
965   // The actual type of the operand does not seem to matter as long
966   // as the bits match one of the inline immediate values.  For example:
967   //
968   // -nan has the hexadecimal encoding of 0xfffffffe which is -2 in decimal,
969   // so it is a legal inline immediate.
970   //
971   // 1065353216 has the hexadecimal encoding 0x3f800000 which is 1.0f in
972   // floating-point, so it is a legal inline immediate.
973   uint32_t Val = Imm.getZExtValue();
974
975   return (FloatToBits(0.0f) == Val) ||
976          (FloatToBits(1.0f) == Val) ||
977          (FloatToBits(-1.0f) == Val) ||
978          (FloatToBits(0.5f) == Val) ||
979          (FloatToBits(-0.5f) == Val) ||
980          (FloatToBits(2.0f) == Val) ||
981          (FloatToBits(-2.0f) == Val) ||
982          (FloatToBits(4.0f) == Val) ||
983          (FloatToBits(-4.0f) == Val);
984 }
985
986 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO) const {
987   if (MO.isImm())
988     return isInlineConstant(APInt(32, MO.getImm(), true));
989
990   return false;
991 }
992
993 bool SIInstrInfo::isLiteralConstant(const MachineOperand &MO) const {
994   return MO.isImm() && !isInlineConstant(MO);
995 }
996
997 static bool compareMachineOp(const MachineOperand &Op0,
998                              const MachineOperand &Op1) {
999   if (Op0.getType() != Op1.getType())
1000     return false;
1001
1002   switch (Op0.getType()) {
1003   case MachineOperand::MO_Register:
1004     return Op0.getReg() == Op1.getReg();
1005   case MachineOperand::MO_Immediate:
1006     return Op0.getImm() == Op1.getImm();
1007   default:
1008     llvm_unreachable("Didn't expect to be comparing these operand types");
1009   }
1010 }
1011
1012 bool SIInstrInfo::isImmOperandLegal(const MachineInstr *MI, unsigned OpNo,
1013                                  const MachineOperand &MO) const {
1014   const MCOperandInfo &OpInfo = get(MI->getOpcode()).OpInfo[OpNo];
1015
1016   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
1017
1018   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
1019     return true;
1020
1021   if (OpInfo.RegClass < 0)
1022     return false;
1023
1024   if (isLiteralConstant(MO))
1025     return RI.opCanUseLiteralConstant(OpInfo.OperandType);
1026
1027   return RI.opCanUseInlineConstant(OpInfo.OperandType);
1028 }
1029
1030 bool SIInstrInfo::canFoldOffset(unsigned OffsetSize, unsigned AS) const {
1031   switch (AS) {
1032   case AMDGPUAS::GLOBAL_ADDRESS: {
1033     // MUBUF instructions a 12-bit offset in bytes.
1034     return isUInt<12>(OffsetSize);
1035   }
1036   case AMDGPUAS::CONSTANT_ADDRESS: {
1037     // SMRD instructions have an 8-bit offset in dwords on SI and
1038     // a 20-bit offset in bytes on VI.
1039     if (RI.ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1040       return isUInt<20>(OffsetSize);
1041     else
1042       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1043   }
1044   case AMDGPUAS::LOCAL_ADDRESS:
1045   case AMDGPUAS::REGION_ADDRESS: {
1046     // The single offset versions have a 16-bit offset in bytes.
1047     return isUInt<16>(OffsetSize);
1048   }
1049   case AMDGPUAS::PRIVATE_ADDRESS:
1050     // Indirect register addressing does not use any offsets.
1051   default:
1052     return 0;
1053   }
1054 }
1055
1056 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
1057   return AMDGPU::getVOPe32(Opcode) != -1;
1058 }
1059
1060 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1061   // The src0_modifier operand is present on all instructions
1062   // that have modifiers.
1063
1064   return AMDGPU::getNamedOperandIdx(Opcode,
1065                                     AMDGPU::OpName::src0_modifiers) != -1;
1066 }
1067
1068 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1069                                   unsigned OpName) const {
1070   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1071   return Mods && Mods->getImm();
1072 }
1073
1074 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1075                                   const MachineOperand &MO) const {
1076   // Literal constants use the constant bus.
1077   if (isLiteralConstant(MO))
1078     return true;
1079
1080   if (!MO.isReg() || !MO.isUse())
1081     return false;
1082
1083   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1084     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
1085
1086   // FLAT_SCR is just an SGPR pair.
1087   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
1088     return true;
1089
1090   // EXEC register uses the constant bus.
1091   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
1092     return true;
1093
1094   // SGPRs use the constant bus
1095   if (MO.getReg() == AMDGPU::M0 || MO.getReg() == AMDGPU::VCC ||
1096       (!MO.isImplicit() &&
1097       (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
1098        AMDGPU::SGPR_64RegClass.contains(MO.getReg())))) {
1099     return true;
1100   }
1101
1102   return false;
1103 }
1104
1105 bool SIInstrInfo::verifyInstruction(const MachineInstr *MI,
1106                                     StringRef &ErrInfo) const {
1107   uint16_t Opcode = MI->getOpcode();
1108   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1109   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
1110   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
1111   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
1112
1113   // Make sure the number of operands is correct.
1114   const MCInstrDesc &Desc = get(Opcode);
1115   if (!Desc.isVariadic() &&
1116       Desc.getNumOperands() != MI->getNumExplicitOperands()) {
1117      ErrInfo = "Instruction has wrong number of operands.";
1118      return false;
1119   }
1120
1121   // Make sure the register classes are correct
1122   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
1123     if (MI->getOperand(i).isFPImm()) {
1124       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
1125                 "all fp values to integers.";
1126       return false;
1127     }
1128
1129     switch (Desc.OpInfo[i].OperandType) {
1130     case MCOI::OPERAND_REGISTER: {
1131       if (MI->getOperand(i).isImm() &&
1132           !isImmOperandLegal(MI, i, MI->getOperand(i))) {
1133           ErrInfo = "Illegal immediate value for operand.";
1134           return false;
1135         }
1136       }
1137       break;
1138     case MCOI::OPERAND_IMMEDIATE:
1139       // Check if this operand is an immediate.
1140       // FrameIndex operands will be replaced by immediates, so they are
1141       // allowed.
1142       if (!MI->getOperand(i).isImm() && !MI->getOperand(i).isFI()) {
1143         ErrInfo = "Expected immediate, but got non-immediate";
1144         return false;
1145       }
1146       // Fall-through
1147     default:
1148       continue;
1149     }
1150
1151     if (!MI->getOperand(i).isReg())
1152       continue;
1153
1154     int RegClass = Desc.OpInfo[i].RegClass;
1155     if (RegClass != -1) {
1156       unsigned Reg = MI->getOperand(i).getReg();
1157       if (TargetRegisterInfo::isVirtualRegister(Reg))
1158         continue;
1159
1160       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
1161       if (!RC->contains(Reg)) {
1162         ErrInfo = "Operand has incorrect register class.";
1163         return false;
1164       }
1165     }
1166   }
1167
1168
1169   // Verify VOP*
1170   if (isVOP1(Opcode) || isVOP2(Opcode) || isVOP3(Opcode) || isVOPC(Opcode)) {
1171     // Only look at the true operands. Only a real operand can use the constant
1172     // bus, and we don't want to check pseudo-operands like the source modifier
1173     // flags.
1174     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
1175
1176     unsigned ConstantBusCount = 0;
1177     unsigned SGPRUsed = AMDGPU::NoRegister;
1178     for (int OpIdx : OpIndices) {
1179       if (OpIdx == -1)
1180         break;
1181
1182       const MachineOperand &MO = MI->getOperand(OpIdx);
1183       if (usesConstantBus(MRI, MO)) {
1184         if (MO.isReg()) {
1185           if (MO.getReg() != SGPRUsed)
1186             ++ConstantBusCount;
1187           SGPRUsed = MO.getReg();
1188         } else {
1189           ++ConstantBusCount;
1190         }
1191       }
1192     }
1193     if (ConstantBusCount > 1) {
1194       ErrInfo = "VOP* instruction uses the constant bus more than once";
1195       return false;
1196     }
1197   }
1198
1199   // Verify SRC1 for VOP2 and VOPC
1200   if (Src1Idx != -1 && (isVOP2(Opcode) || isVOPC(Opcode))) {
1201     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
1202     if (Src1.isImm()) {
1203       ErrInfo = "VOP[2C] src1 cannot be an immediate.";
1204       return false;
1205     }
1206   }
1207
1208   // Verify VOP3
1209   if (isVOP3(Opcode)) {
1210     if (Src0Idx != -1 && isLiteralConstant(MI->getOperand(Src0Idx))) {
1211       ErrInfo = "VOP3 src0 cannot be a literal constant.";
1212       return false;
1213     }
1214     if (Src1Idx != -1 && isLiteralConstant(MI->getOperand(Src1Idx))) {
1215       ErrInfo = "VOP3 src1 cannot be a literal constant.";
1216       return false;
1217     }
1218     if (Src2Idx != -1 && isLiteralConstant(MI->getOperand(Src2Idx))) {
1219       ErrInfo = "VOP3 src2 cannot be a literal constant.";
1220       return false;
1221     }
1222   }
1223
1224   // Verify misc. restrictions on specific instructions.
1225   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
1226       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
1227     const MachineOperand &Src0 = MI->getOperand(Src0Idx);
1228     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
1229     const MachineOperand &Src2 = MI->getOperand(Src2Idx);
1230     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
1231       if (!compareMachineOp(Src0, Src1) &&
1232           !compareMachineOp(Src0, Src2)) {
1233         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
1234         return false;
1235       }
1236     }
1237   }
1238
1239   return true;
1240 }
1241
1242 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
1243   switch (MI.getOpcode()) {
1244   default: return AMDGPU::INSTRUCTION_LIST_END;
1245   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
1246   case AMDGPU::COPY: return AMDGPU::COPY;
1247   case AMDGPU::PHI: return AMDGPU::PHI;
1248   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
1249   case AMDGPU::S_MOV_B32:
1250     return MI.getOperand(1).isReg() ?
1251            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
1252   case AMDGPU::S_ADD_I32:
1253   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
1254   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
1255   case AMDGPU::S_SUB_I32:
1256   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
1257   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
1258   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
1259   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e32;
1260   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e32;
1261   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e32;
1262   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e32;
1263   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e32;
1264   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e32;
1265   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e32;
1266   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
1267   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
1268   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
1269   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
1270   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
1271   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
1272   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
1273   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
1274   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
1275   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
1276   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
1277   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
1278   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
1279   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
1280   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
1281   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
1282   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
1283   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
1284   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
1285   case AMDGPU::S_LOAD_DWORD_IMM:
1286   case AMDGPU::S_LOAD_DWORD_SGPR: return AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1287   case AMDGPU::S_LOAD_DWORDX2_IMM:
1288   case AMDGPU::S_LOAD_DWORDX2_SGPR: return AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1289   case AMDGPU::S_LOAD_DWORDX4_IMM:
1290   case AMDGPU::S_LOAD_DWORDX4_SGPR: return AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1291   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e32;
1292   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
1293   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
1294   }
1295 }
1296
1297 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
1298   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
1299 }
1300
1301 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
1302                                                       unsigned OpNo) const {
1303   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1304   const MCInstrDesc &Desc = get(MI.getOpcode());
1305   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
1306       Desc.OpInfo[OpNo].RegClass == -1) {
1307     unsigned Reg = MI.getOperand(OpNo).getReg();
1308
1309     if (TargetRegisterInfo::isVirtualRegister(Reg))
1310       return MRI.getRegClass(Reg);
1311     return RI.getRegClass(Reg);
1312   }
1313
1314   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
1315   return RI.getRegClass(RCID);
1316 }
1317
1318 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
1319   switch (MI.getOpcode()) {
1320   case AMDGPU::COPY:
1321   case AMDGPU::REG_SEQUENCE:
1322   case AMDGPU::PHI:
1323   case AMDGPU::INSERT_SUBREG:
1324     return RI.hasVGPRs(getOpRegClass(MI, 0));
1325   default:
1326     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
1327   }
1328 }
1329
1330 void SIInstrInfo::legalizeOpWithMove(MachineInstr *MI, unsigned OpIdx) const {
1331   MachineBasicBlock::iterator I = MI;
1332   MachineBasicBlock *MBB = MI->getParent();
1333   MachineOperand &MO = MI->getOperand(OpIdx);
1334   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1335   unsigned RCID = get(MI->getOpcode()).OpInfo[OpIdx].RegClass;
1336   const TargetRegisterClass *RC = RI.getRegClass(RCID);
1337   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1338   if (MO.isReg())
1339     Opcode = AMDGPU::COPY;
1340   else if (RI.isSGPRClass(RC))
1341     Opcode = AMDGPU::S_MOV_B32;
1342
1343
1344   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
1345   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
1346     VRC = &AMDGPU::VReg_64RegClass;
1347   else
1348     VRC = &AMDGPU::VGPR_32RegClass;
1349
1350   unsigned Reg = MRI.createVirtualRegister(VRC);
1351   DebugLoc DL = MBB->findDebugLoc(I);
1352   BuildMI(*MI->getParent(), I, DL, get(Opcode), Reg)
1353     .addOperand(MO);
1354   MO.ChangeToRegister(Reg, false);
1355 }
1356
1357 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
1358                                          MachineRegisterInfo &MRI,
1359                                          MachineOperand &SuperReg,
1360                                          const TargetRegisterClass *SuperRC,
1361                                          unsigned SubIdx,
1362                                          const TargetRegisterClass *SubRC)
1363                                          const {
1364   assert(SuperReg.isReg());
1365
1366   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
1367   unsigned SubReg = MRI.createVirtualRegister(SubRC);
1368
1369   // Just in case the super register is itself a sub-register, copy it to a new
1370   // value so we don't need to worry about merging its subreg index with the
1371   // SubIdx passed to this function. The register coalescer should be able to
1372   // eliminate this extra copy.
1373   MachineBasicBlock *MBB = MI->getParent();
1374   DebugLoc DL = MI->getDebugLoc();
1375
1376   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
1377     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
1378
1379   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1380     .addReg(NewSuperReg, 0, SubIdx);
1381
1382   return SubReg;
1383 }
1384
1385 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
1386   MachineBasicBlock::iterator MII,
1387   MachineRegisterInfo &MRI,
1388   MachineOperand &Op,
1389   const TargetRegisterClass *SuperRC,
1390   unsigned SubIdx,
1391   const TargetRegisterClass *SubRC) const {
1392   if (Op.isImm()) {
1393     // XXX - Is there a better way to do this?
1394     if (SubIdx == AMDGPU::sub0)
1395       return MachineOperand::CreateImm(Op.getImm() & 0xFFFFFFFF);
1396     if (SubIdx == AMDGPU::sub1)
1397       return MachineOperand::CreateImm(Op.getImm() >> 32);
1398
1399     llvm_unreachable("Unhandled register index for immediate");
1400   }
1401
1402   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
1403                                        SubIdx, SubRC);
1404   return MachineOperand::CreateReg(SubReg, false);
1405 }
1406
1407 unsigned SIInstrInfo::split64BitImm(SmallVectorImpl<MachineInstr *> &Worklist,
1408                                     MachineBasicBlock::iterator MI,
1409                                     MachineRegisterInfo &MRI,
1410                                     const TargetRegisterClass *RC,
1411                                     const MachineOperand &Op) const {
1412   MachineBasicBlock *MBB = MI->getParent();
1413   DebugLoc DL = MI->getDebugLoc();
1414   unsigned LoDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1415   unsigned HiDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1416   unsigned Dst = MRI.createVirtualRegister(RC);
1417
1418   MachineInstr *Lo = BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32),
1419                              LoDst)
1420     .addImm(Op.getImm() & 0xFFFFFFFF);
1421   MachineInstr *Hi = BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32),
1422                              HiDst)
1423     .addImm(Op.getImm() >> 32);
1424
1425   BuildMI(*MBB, MI, DL, get(TargetOpcode::REG_SEQUENCE), Dst)
1426     .addReg(LoDst)
1427     .addImm(AMDGPU::sub0)
1428     .addReg(HiDst)
1429     .addImm(AMDGPU::sub1);
1430
1431   Worklist.push_back(Lo);
1432   Worklist.push_back(Hi);
1433
1434   return Dst;
1435 }
1436
1437 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
1438 void SIInstrInfo::swapOperands(MachineBasicBlock::iterator Inst) const {
1439   assert(Inst->getNumExplicitOperands() == 3);
1440   MachineOperand Op1 = Inst->getOperand(1);
1441   Inst->RemoveOperand(1);
1442   Inst->addOperand(Op1);
1443 }
1444
1445 bool SIInstrInfo::isOperandLegal(const MachineInstr *MI, unsigned OpIdx,
1446                                  const MachineOperand *MO) const {
1447   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1448   const MCInstrDesc &InstDesc = get(MI->getOpcode());
1449   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
1450   const TargetRegisterClass *DefinedRC =
1451       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
1452   if (!MO)
1453     MO = &MI->getOperand(OpIdx);
1454
1455   if (isVALU(InstDesc.Opcode) && usesConstantBus(MRI, *MO)) {
1456     unsigned SGPRUsed =
1457         MO->isReg() ? MO->getReg() : (unsigned)AMDGPU::NoRegister;
1458     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1459       if (i == OpIdx)
1460         continue;
1461       if (usesConstantBus(MRI, MI->getOperand(i)) &&
1462           MI->getOperand(i).isReg() && MI->getOperand(i).getReg() != SGPRUsed) {
1463         return false;
1464       }
1465     }
1466   }
1467
1468   if (MO->isReg()) {
1469     assert(DefinedRC);
1470     const TargetRegisterClass *RC = MRI.getRegClass(MO->getReg());
1471
1472     // In order to be legal, the common sub-class must be equal to the
1473     // class of the current operand.  For example:
1474     //
1475     // v_mov_b32 s0 ; Operand defined as vsrc_32
1476     //              ; RI.getCommonSubClass(s0,vsrc_32) = sgpr ; LEGAL
1477     //
1478     // s_sendmsg 0, s0 ; Operand defined as m0reg
1479     //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
1480
1481     return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
1482   }
1483
1484
1485   // Handle non-register types that are treated like immediates.
1486   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
1487
1488   if (!DefinedRC) {
1489     // This operand expects an immediate.
1490     return true;
1491   }
1492
1493   return isImmOperandLegal(MI, OpIdx, *MO);
1494 }
1495
1496 void SIInstrInfo::legalizeOperands(MachineInstr *MI) const {
1497   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1498
1499   int Src0Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1500                                            AMDGPU::OpName::src0);
1501   int Src1Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1502                                            AMDGPU::OpName::src1);
1503   int Src2Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1504                                            AMDGPU::OpName::src2);
1505
1506   // Legalize VOP2
1507   if (isVOP2(MI->getOpcode()) && Src1Idx != -1) {
1508     // Legalize src0
1509     if (!isOperandLegal(MI, Src0Idx))
1510       legalizeOpWithMove(MI, Src0Idx);
1511
1512     // Legalize src1
1513     if (isOperandLegal(MI, Src1Idx))
1514       return;
1515
1516     // Usually src0 of VOP2 instructions allow more types of inputs
1517     // than src1, so try to commute the instruction to decrease our
1518     // chances of having to insert a MOV instruction to legalize src1.
1519     if (MI->isCommutable()) {
1520       if (commuteInstruction(MI))
1521         // If we are successful in commuting, then we know MI is legal, so
1522         // we are done.
1523         return;
1524     }
1525
1526     legalizeOpWithMove(MI, Src1Idx);
1527     return;
1528   }
1529
1530   // XXX - Do any VOP3 instructions read VCC?
1531   // Legalize VOP3
1532   if (isVOP3(MI->getOpcode())) {
1533     int VOP3Idx[3] = { Src0Idx, Src1Idx, Src2Idx };
1534
1535     // Find the one SGPR operand we are allowed to use.
1536     unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
1537
1538     for (unsigned i = 0; i < 3; ++i) {
1539       int Idx = VOP3Idx[i];
1540       if (Idx == -1)
1541         break;
1542       MachineOperand &MO = MI->getOperand(Idx);
1543
1544       if (MO.isReg()) {
1545         if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
1546           continue; // VGPRs are legal
1547
1548         assert(MO.getReg() != AMDGPU::SCC && "SCC operand to VOP3 instruction");
1549
1550         if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
1551           SGPRReg = MO.getReg();
1552           // We can use one SGPR in each VOP3 instruction.
1553           continue;
1554         }
1555       } else if (!isLiteralConstant(MO)) {
1556         // If it is not a register and not a literal constant, then it must be
1557         // an inline constant which is always legal.
1558         continue;
1559       }
1560       // If we make it this far, then the operand is not legal and we must
1561       // legalize it.
1562       legalizeOpWithMove(MI, Idx);
1563     }
1564   }
1565
1566   // Legalize REG_SEQUENCE and PHI
1567   // The register class of the operands much be the same type as the register
1568   // class of the output.
1569   if (MI->getOpcode() == AMDGPU::REG_SEQUENCE ||
1570       MI->getOpcode() == AMDGPU::PHI) {
1571     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
1572     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
1573       if (!MI->getOperand(i).isReg() ||
1574           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
1575         continue;
1576       const TargetRegisterClass *OpRC =
1577               MRI.getRegClass(MI->getOperand(i).getReg());
1578       if (RI.hasVGPRs(OpRC)) {
1579         VRC = OpRC;
1580       } else {
1581         SRC = OpRC;
1582       }
1583     }
1584
1585     // If any of the operands are VGPR registers, then they all most be
1586     // otherwise we will create illegal VGPR->SGPR copies when legalizing
1587     // them.
1588     if (VRC || !RI.isSGPRClass(getOpRegClass(*MI, 0))) {
1589       if (!VRC) {
1590         assert(SRC);
1591         VRC = RI.getEquivalentVGPRClass(SRC);
1592       }
1593       RC = VRC;
1594     } else {
1595       RC = SRC;
1596     }
1597
1598     // Update all the operands so they have the same type.
1599     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
1600       if (!MI->getOperand(i).isReg() ||
1601           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
1602         continue;
1603       unsigned DstReg = MRI.createVirtualRegister(RC);
1604       MachineBasicBlock *InsertBB;
1605       MachineBasicBlock::iterator Insert;
1606       if (MI->getOpcode() == AMDGPU::REG_SEQUENCE) {
1607         InsertBB = MI->getParent();
1608         Insert = MI;
1609       } else {
1610         // MI is a PHI instruction.
1611         InsertBB = MI->getOperand(i + 1).getMBB();
1612         Insert = InsertBB->getFirstTerminator();
1613       }
1614       BuildMI(*InsertBB, Insert, MI->getDebugLoc(),
1615               get(AMDGPU::COPY), DstReg)
1616               .addOperand(MI->getOperand(i));
1617       MI->getOperand(i).setReg(DstReg);
1618     }
1619   }
1620
1621   // Legalize INSERT_SUBREG
1622   // src0 must have the same register class as dst
1623   if (MI->getOpcode() == AMDGPU::INSERT_SUBREG) {
1624     unsigned Dst = MI->getOperand(0).getReg();
1625     unsigned Src0 = MI->getOperand(1).getReg();
1626     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
1627     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
1628     if (DstRC != Src0RC) {
1629       MachineBasicBlock &MBB = *MI->getParent();
1630       unsigned NewSrc0 = MRI.createVirtualRegister(DstRC);
1631       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::COPY), NewSrc0)
1632               .addReg(Src0);
1633       MI->getOperand(1).setReg(NewSrc0);
1634     }
1635     return;
1636   }
1637
1638   // Legalize MUBUF* instructions
1639   // FIXME: If we start using the non-addr64 instructions for compute, we
1640   // may need to legalize them here.
1641   int SRsrcIdx =
1642       AMDGPU::getNamedOperandIdx(MI->getOpcode(), AMDGPU::OpName::srsrc);
1643   if (SRsrcIdx != -1) {
1644     // We have an MUBUF instruction
1645     MachineOperand *SRsrc = &MI->getOperand(SRsrcIdx);
1646     unsigned SRsrcRC = get(MI->getOpcode()).OpInfo[SRsrcIdx].RegClass;
1647     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
1648                                              RI.getRegClass(SRsrcRC))) {
1649       // The operands are legal.
1650       // FIXME: We may need to legalize operands besided srsrc.
1651       return;
1652     }
1653
1654     MachineBasicBlock &MBB = *MI->getParent();
1655     // Extract the the ptr from the resource descriptor.
1656
1657     // SRsrcPtrLo = srsrc:sub0
1658     unsigned SRsrcPtrLo = buildExtractSubReg(MI, MRI, *SRsrc,
1659         &AMDGPU::VReg_128RegClass, AMDGPU::sub0, &AMDGPU::VGPR_32RegClass);
1660
1661     // SRsrcPtrHi = srsrc:sub1
1662     unsigned SRsrcPtrHi = buildExtractSubReg(MI, MRI, *SRsrc,
1663         &AMDGPU::VReg_128RegClass, AMDGPU::sub1, &AMDGPU::VGPR_32RegClass);
1664
1665     // Create an empty resource descriptor
1666     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1667     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1668     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1669     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
1670     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
1671
1672     // Zero64 = 0
1673     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B64),
1674             Zero64)
1675             .addImm(0);
1676
1677     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
1678     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1679             SRsrcFormatLo)
1680             .addImm(RsrcDataFormat & 0xFFFFFFFF);
1681
1682     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
1683     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1684             SRsrcFormatHi)
1685             .addImm(RsrcDataFormat >> 32);
1686
1687     // NewSRsrc = {Zero64, SRsrcFormat}
1688     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
1689             NewSRsrc)
1690             .addReg(Zero64)
1691             .addImm(AMDGPU::sub0_sub1)
1692             .addReg(SRsrcFormatLo)
1693             .addImm(AMDGPU::sub2)
1694             .addReg(SRsrcFormatHi)
1695             .addImm(AMDGPU::sub3);
1696
1697     MachineOperand *VAddr = getNamedOperand(*MI, AMDGPU::OpName::vaddr);
1698     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
1699     unsigned NewVAddrLo;
1700     unsigned NewVAddrHi;
1701     if (VAddr) {
1702       // This is already an ADDR64 instruction so we need to add the pointer
1703       // extracted from the resource descriptor to the current value of VAddr.
1704       NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1705       NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1706
1707       // NewVaddrLo = SRsrcPtrLo + VAddr:sub0
1708       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADD_I32_e32),
1709               NewVAddrLo)
1710               .addReg(SRsrcPtrLo)
1711               .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
1712               .addReg(AMDGPU::VCC, RegState::ImplicitDefine);
1713
1714       // NewVaddrHi = SRsrcPtrHi + VAddr:sub1
1715       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADDC_U32_e32),
1716               NewVAddrHi)
1717               .addReg(SRsrcPtrHi)
1718               .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
1719               .addReg(AMDGPU::VCC, RegState::ImplicitDefine)
1720               .addReg(AMDGPU::VCC, RegState::Implicit);
1721
1722     } else {
1723       // This instructions is the _OFFSET variant, so we need to convert it to
1724       // ADDR64.
1725       MachineOperand *VData = getNamedOperand(*MI, AMDGPU::OpName::vdata);
1726       MachineOperand *Offset = getNamedOperand(*MI, AMDGPU::OpName::offset);
1727       MachineOperand *SOffset = getNamedOperand(*MI, AMDGPU::OpName::soffset);
1728       assert(SOffset->isImm() && SOffset->getImm() == 0 && "Legalizing MUBUF "
1729              "with non-zero soffset is not implemented");
1730       (void)SOffset;
1731
1732       // Create the new instruction.
1733       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI->getOpcode());
1734       MachineInstr *Addr64 =
1735           BuildMI(MBB, MI, MI->getDebugLoc(), get(Addr64Opcode))
1736                   .addOperand(*VData)
1737                   .addOperand(*SRsrc)
1738                   .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
1739                                               // This will be replaced later
1740                                               // with the new value of vaddr.
1741                   .addOperand(*Offset);
1742
1743       MI->removeFromParent();
1744       MI = Addr64;
1745
1746       NewVAddrLo = SRsrcPtrLo;
1747       NewVAddrHi = SRsrcPtrHi;
1748       VAddr = getNamedOperand(*MI, AMDGPU::OpName::vaddr);
1749       SRsrc = getNamedOperand(*MI, AMDGPU::OpName::srsrc);
1750     }
1751
1752     // NewVaddr = {NewVaddrHi, NewVaddrLo}
1753     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
1754             NewVAddr)
1755             .addReg(NewVAddrLo)
1756             .addImm(AMDGPU::sub0)
1757             .addReg(NewVAddrHi)
1758             .addImm(AMDGPU::sub1);
1759
1760
1761     // Update the instruction to use NewVaddr
1762     VAddr->setReg(NewVAddr);
1763     // Update the instruction to use NewSRsrc
1764     SRsrc->setReg(NewSRsrc);
1765   }
1766 }
1767
1768 void SIInstrInfo::splitSMRD(MachineInstr *MI,
1769                             const TargetRegisterClass *HalfRC,
1770                             unsigned HalfImmOp, unsigned HalfSGPROp,
1771                             MachineInstr *&Lo, MachineInstr *&Hi) const {
1772
1773   DebugLoc DL = MI->getDebugLoc();
1774   MachineBasicBlock *MBB = MI->getParent();
1775   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1776   unsigned RegLo = MRI.createVirtualRegister(HalfRC);
1777   unsigned RegHi = MRI.createVirtualRegister(HalfRC);
1778   unsigned HalfSize = HalfRC->getSize();
1779   const MachineOperand *OffOp =
1780       getNamedOperand(*MI, AMDGPU::OpName::offset);
1781   const MachineOperand *SBase = getNamedOperand(*MI, AMDGPU::OpName::sbase);
1782
1783   // The SMRD has an 8-bit offset in dwords on SI and a 20-bit offset in bytes
1784   // on VI.
1785   if (OffOp) {
1786     bool isVI = RI.ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS;
1787     unsigned OffScale = isVI ? 1 : 4;
1788     // Handle the _IMM variant
1789     unsigned LoOffset = OffOp->getImm() * OffScale;
1790     unsigned HiOffset = LoOffset + HalfSize;
1791     Lo = BuildMI(*MBB, MI, DL, get(HalfImmOp), RegLo)
1792                   .addOperand(*SBase)
1793                   .addImm(LoOffset / OffScale);
1794
1795     if (!isUInt<20>(HiOffset) || (!isVI && !isUInt<8>(HiOffset / OffScale))) {
1796       unsigned OffsetSGPR =
1797           MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
1798       BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32), OffsetSGPR)
1799               .addImm(HiOffset); // The offset in register is in bytes.
1800       Hi = BuildMI(*MBB, MI, DL, get(HalfSGPROp), RegHi)
1801                     .addOperand(*SBase)
1802                     .addReg(OffsetSGPR);
1803     } else {
1804       Hi = BuildMI(*MBB, MI, DL, get(HalfImmOp), RegHi)
1805                      .addOperand(*SBase)
1806                      .addImm(HiOffset / OffScale);
1807     }
1808   } else {
1809     // Handle the _SGPR variant
1810     MachineOperand *SOff = getNamedOperand(*MI, AMDGPU::OpName::soff);
1811     Lo = BuildMI(*MBB, MI, DL, get(HalfSGPROp), RegLo)
1812                   .addOperand(*SBase)
1813                   .addOperand(*SOff);
1814     unsigned OffsetSGPR = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
1815     BuildMI(*MBB, MI, DL, get(AMDGPU::S_ADD_I32), OffsetSGPR)
1816             .addOperand(*SOff)
1817             .addImm(HalfSize);
1818     Hi = BuildMI(*MBB, MI, DL, get(HalfSGPROp))
1819                   .addOperand(*SBase)
1820                   .addReg(OffsetSGPR);
1821   }
1822
1823   unsigned SubLo, SubHi;
1824   switch (HalfSize) {
1825     case 4:
1826       SubLo = AMDGPU::sub0;
1827       SubHi = AMDGPU::sub1;
1828       break;
1829     case 8:
1830       SubLo = AMDGPU::sub0_sub1;
1831       SubHi = AMDGPU::sub2_sub3;
1832       break;
1833     case 16:
1834       SubLo = AMDGPU::sub0_sub1_sub2_sub3;
1835       SubHi = AMDGPU::sub4_sub5_sub6_sub7;
1836       break;
1837     case 32:
1838       SubLo = AMDGPU::sub0_sub1_sub2_sub3_sub4_sub5_sub6_sub7;
1839       SubHi = AMDGPU::sub8_sub9_sub10_sub11_sub12_sub13_sub14_sub15;
1840       break;
1841     default:
1842       llvm_unreachable("Unhandled HalfSize");
1843   }
1844
1845   BuildMI(*MBB, MI, DL, get(AMDGPU::REG_SEQUENCE))
1846           .addOperand(MI->getOperand(0))
1847           .addReg(RegLo)
1848           .addImm(SubLo)
1849           .addReg(RegHi)
1850           .addImm(SubHi);
1851 }
1852
1853 void SIInstrInfo::moveSMRDToVALU(MachineInstr *MI, MachineRegisterInfo &MRI) const {
1854   MachineBasicBlock *MBB = MI->getParent();
1855   switch (MI->getOpcode()) {
1856     case AMDGPU::S_LOAD_DWORD_IMM:
1857     case AMDGPU::S_LOAD_DWORD_SGPR:
1858     case AMDGPU::S_LOAD_DWORDX2_IMM:
1859     case AMDGPU::S_LOAD_DWORDX2_SGPR:
1860     case AMDGPU::S_LOAD_DWORDX4_IMM:
1861     case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1862       unsigned NewOpcode = getVALUOp(*MI);
1863       unsigned RegOffset;
1864       unsigned ImmOffset;
1865
1866       if (MI->getOperand(2).isReg()) {
1867         RegOffset = MI->getOperand(2).getReg();
1868         ImmOffset = 0;
1869       } else {
1870         assert(MI->getOperand(2).isImm());
1871         // SMRD instructions take a dword offsets on SI and byte offset on VI
1872         // and MUBUF instructions always take a byte offset.
1873         ImmOffset = MI->getOperand(2).getImm();
1874         if (RI.ST.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
1875           ImmOffset <<= 2;
1876         RegOffset = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1877
1878         if (isUInt<12>(ImmOffset)) {
1879           BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1880                   RegOffset)
1881                   .addImm(0);
1882         } else {
1883           BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1884                   RegOffset)
1885                   .addImm(ImmOffset);
1886           ImmOffset = 0;
1887         }
1888       }
1889
1890       unsigned SRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
1891       unsigned DWord0 = RegOffset;
1892       unsigned DWord1 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1893       unsigned DWord2 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1894       unsigned DWord3 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1895       uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
1896
1897       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord1)
1898               .addImm(0);
1899       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord2)
1900               .addImm(RsrcDataFormat & 0xFFFFFFFF);
1901       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord3)
1902               .addImm(RsrcDataFormat >> 32);
1903       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE), SRsrc)
1904               .addReg(DWord0)
1905               .addImm(AMDGPU::sub0)
1906               .addReg(DWord1)
1907               .addImm(AMDGPU::sub1)
1908               .addReg(DWord2)
1909               .addImm(AMDGPU::sub2)
1910               .addReg(DWord3)
1911               .addImm(AMDGPU::sub3);
1912       MI->setDesc(get(NewOpcode));
1913       if (MI->getOperand(2).isReg()) {
1914         MI->getOperand(2).setReg(MI->getOperand(1).getReg());
1915       } else {
1916         MI->getOperand(2).ChangeToRegister(MI->getOperand(1).getReg(), false);
1917       }
1918       MI->getOperand(1).setReg(SRsrc);
1919       MI->addOperand(*MBB->getParent(), MachineOperand::CreateImm(ImmOffset));
1920
1921       const TargetRegisterClass *NewDstRC =
1922           RI.getRegClass(get(NewOpcode).OpInfo[0].RegClass);
1923
1924       unsigned DstReg = MI->getOperand(0).getReg();
1925       unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
1926       MRI.replaceRegWith(DstReg, NewDstReg);
1927       break;
1928     }
1929     case AMDGPU::S_LOAD_DWORDX8_IMM:
1930     case AMDGPU::S_LOAD_DWORDX8_SGPR: {
1931       MachineInstr *Lo, *Hi;
1932       splitSMRD(MI, &AMDGPU::SReg_128RegClass, AMDGPU::S_LOAD_DWORDX4_IMM,
1933                 AMDGPU::S_LOAD_DWORDX4_SGPR, Lo, Hi);
1934       MI->eraseFromParent();
1935       moveSMRDToVALU(Lo, MRI);
1936       moveSMRDToVALU(Hi, MRI);
1937       break;
1938     }
1939
1940     case AMDGPU::S_LOAD_DWORDX16_IMM:
1941     case AMDGPU::S_LOAD_DWORDX16_SGPR: {
1942       MachineInstr *Lo, *Hi;
1943       splitSMRD(MI, &AMDGPU::SReg_256RegClass, AMDGPU::S_LOAD_DWORDX8_IMM,
1944                 AMDGPU::S_LOAD_DWORDX8_SGPR, Lo, Hi);
1945       MI->eraseFromParent();
1946       moveSMRDToVALU(Lo, MRI);
1947       moveSMRDToVALU(Hi, MRI);
1948       break;
1949     }
1950   }
1951 }
1952
1953 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
1954   SmallVector<MachineInstr *, 128> Worklist;
1955   Worklist.push_back(&TopInst);
1956
1957   while (!Worklist.empty()) {
1958     MachineInstr *Inst = Worklist.pop_back_val();
1959     MachineBasicBlock *MBB = Inst->getParent();
1960     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1961
1962     unsigned Opcode = Inst->getOpcode();
1963     unsigned NewOpcode = getVALUOp(*Inst);
1964
1965     // Handle some special cases
1966     switch (Opcode) {
1967     default:
1968       if (isSMRD(Inst->getOpcode())) {
1969         moveSMRDToVALU(Inst, MRI);
1970       }
1971       break;
1972     case AMDGPU::S_MOV_B64: {
1973       DebugLoc DL = Inst->getDebugLoc();
1974
1975       // If the source operand is a register we can replace this with a
1976       // copy.
1977       if (Inst->getOperand(1).isReg()) {
1978         MachineInstr *Copy = BuildMI(*MBB, Inst, DL, get(TargetOpcode::COPY))
1979           .addOperand(Inst->getOperand(0))
1980           .addOperand(Inst->getOperand(1));
1981         Worklist.push_back(Copy);
1982       } else {
1983         // Otherwise, we need to split this into two movs, because there is
1984         // no 64-bit VALU move instruction.
1985         unsigned Reg = Inst->getOperand(0).getReg();
1986         unsigned Dst = split64BitImm(Worklist,
1987                                      Inst,
1988                                      MRI,
1989                                      MRI.getRegClass(Reg),
1990                                      Inst->getOperand(1));
1991         MRI.replaceRegWith(Reg, Dst);
1992       }
1993       Inst->eraseFromParent();
1994       continue;
1995     }
1996     case AMDGPU::S_AND_B64:
1997       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32);
1998       Inst->eraseFromParent();
1999       continue;
2000
2001     case AMDGPU::S_OR_B64:
2002       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32);
2003       Inst->eraseFromParent();
2004       continue;
2005
2006     case AMDGPU::S_XOR_B64:
2007       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32);
2008       Inst->eraseFromParent();
2009       continue;
2010
2011     case AMDGPU::S_NOT_B64:
2012       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
2013       Inst->eraseFromParent();
2014       continue;
2015
2016     case AMDGPU::S_BCNT1_I32_B64:
2017       splitScalar64BitBCNT(Worklist, Inst);
2018       Inst->eraseFromParent();
2019       continue;
2020
2021     case AMDGPU::S_BFE_I64: {
2022       splitScalar64BitBFE(Worklist, Inst);
2023       Inst->eraseFromParent();
2024       continue;
2025     }
2026
2027     case AMDGPU::S_LSHL_B32:
2028       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
2029         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
2030         swapOperands(Inst);
2031       }
2032       break;
2033     case AMDGPU::S_ASHR_I32:
2034       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
2035         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
2036         swapOperands(Inst);
2037       }
2038       break;
2039     case AMDGPU::S_LSHR_B32:
2040       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
2041         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
2042         swapOperands(Inst);
2043       }
2044       break;
2045
2046     case AMDGPU::S_BFE_U64:
2047     case AMDGPU::S_BFM_B64:
2048       llvm_unreachable("Moving this op to VALU not implemented");
2049     }
2050
2051     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
2052       // We cannot move this instruction to the VALU, so we should try to
2053       // legalize its operands instead.
2054       legalizeOperands(Inst);
2055       continue;
2056     }
2057
2058     // Use the new VALU Opcode.
2059     const MCInstrDesc &NewDesc = get(NewOpcode);
2060     Inst->setDesc(NewDesc);
2061
2062     // Remove any references to SCC. Vector instructions can't read from it, and
2063     // We're just about to add the implicit use / defs of VCC, and we don't want
2064     // both.
2065     for (unsigned i = Inst->getNumOperands() - 1; i > 0; --i) {
2066       MachineOperand &Op = Inst->getOperand(i);
2067       if (Op.isReg() && Op.getReg() == AMDGPU::SCC)
2068         Inst->RemoveOperand(i);
2069     }
2070
2071     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
2072       // We are converting these to a BFE, so we need to add the missing
2073       // operands for the size and offset.
2074       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
2075       Inst->addOperand(MachineOperand::CreateImm(0));
2076       Inst->addOperand(MachineOperand::CreateImm(Size));
2077
2078     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
2079       // The VALU version adds the second operand to the result, so insert an
2080       // extra 0 operand.
2081       Inst->addOperand(MachineOperand::CreateImm(0));
2082     }
2083
2084     addDescImplicitUseDef(NewDesc, Inst);
2085
2086     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
2087       const MachineOperand &OffsetWidthOp = Inst->getOperand(2);
2088       // If we need to move this to VGPRs, we need to unpack the second operand
2089       // back into the 2 separate ones for bit offset and width.
2090       assert(OffsetWidthOp.isImm() &&
2091              "Scalar BFE is only implemented for constant width and offset");
2092       uint32_t Imm = OffsetWidthOp.getImm();
2093
2094       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2095       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2096       Inst->RemoveOperand(2); // Remove old immediate.
2097       Inst->addOperand(MachineOperand::CreateImm(Offset));
2098       Inst->addOperand(MachineOperand::CreateImm(BitWidth));
2099     }
2100
2101     // Update the destination register class.
2102
2103     const TargetRegisterClass *NewDstRC = getOpRegClass(*Inst, 0);
2104
2105     switch (Opcode) {
2106       // For target instructions, getOpRegClass just returns the virtual
2107       // register class associated with the operand, so we need to find an
2108       // equivalent VGPR register class in order to move the instruction to the
2109       // VALU.
2110     case AMDGPU::COPY:
2111     case AMDGPU::PHI:
2112     case AMDGPU::REG_SEQUENCE:
2113     case AMDGPU::INSERT_SUBREG:
2114       if (RI.hasVGPRs(NewDstRC))
2115         continue;
2116       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
2117       if (!NewDstRC)
2118         continue;
2119       break;
2120     default:
2121       break;
2122     }
2123
2124     unsigned DstReg = Inst->getOperand(0).getReg();
2125     unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
2126     MRI.replaceRegWith(DstReg, NewDstReg);
2127
2128     // Legalize the operands
2129     legalizeOperands(Inst);
2130
2131     for (MachineRegisterInfo::use_iterator I = MRI.use_begin(NewDstReg),
2132            E = MRI.use_end(); I != E; ++I) {
2133       MachineInstr &UseMI = *I->getParent();
2134       if (!canReadVGPR(UseMI, I.getOperandNo())) {
2135         Worklist.push_back(&UseMI);
2136       }
2137     }
2138   }
2139 }
2140
2141 //===----------------------------------------------------------------------===//
2142 // Indirect addressing callbacks
2143 //===----------------------------------------------------------------------===//
2144
2145 unsigned SIInstrInfo::calculateIndirectAddress(unsigned RegIndex,
2146                                                  unsigned Channel) const {
2147   assert(Channel == 0);
2148   return RegIndex;
2149 }
2150
2151 const TargetRegisterClass *SIInstrInfo::getIndirectAddrRegClass() const {
2152   return &AMDGPU::VGPR_32RegClass;
2153 }
2154
2155 void SIInstrInfo::splitScalar64BitUnaryOp(
2156   SmallVectorImpl<MachineInstr *> &Worklist,
2157   MachineInstr *Inst,
2158   unsigned Opcode) const {
2159   MachineBasicBlock &MBB = *Inst->getParent();
2160   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2161
2162   MachineOperand &Dest = Inst->getOperand(0);
2163   MachineOperand &Src0 = Inst->getOperand(1);
2164   DebugLoc DL = Inst->getDebugLoc();
2165
2166   MachineBasicBlock::iterator MII = Inst;
2167
2168   const MCInstrDesc &InstDesc = get(Opcode);
2169   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2170     MRI.getRegClass(Src0.getReg()) :
2171     &AMDGPU::SGPR_32RegClass;
2172
2173   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2174
2175   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2176                                                        AMDGPU::sub0, Src0SubRC);
2177
2178   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2179   const TargetRegisterClass *DestSubRC = RI.getSubRegClass(DestRC, AMDGPU::sub0);
2180
2181   unsigned DestSub0 = MRI.createVirtualRegister(DestRC);
2182   MachineInstr *LoHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2183     .addOperand(SrcReg0Sub0);
2184
2185   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2186                                                        AMDGPU::sub1, Src0SubRC);
2187
2188   unsigned DestSub1 = MRI.createVirtualRegister(DestSubRC);
2189   MachineInstr *HiHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2190     .addOperand(SrcReg0Sub1);
2191
2192   unsigned FullDestReg = MRI.createVirtualRegister(DestRC);
2193   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2194     .addReg(DestSub0)
2195     .addImm(AMDGPU::sub0)
2196     .addReg(DestSub1)
2197     .addImm(AMDGPU::sub1);
2198
2199   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2200
2201   // Try to legalize the operands in case we need to swap the order to keep it
2202   // valid.
2203   Worklist.push_back(LoHalf);
2204   Worklist.push_back(HiHalf);
2205 }
2206
2207 void SIInstrInfo::splitScalar64BitBinaryOp(
2208   SmallVectorImpl<MachineInstr *> &Worklist,
2209   MachineInstr *Inst,
2210   unsigned Opcode) const {
2211   MachineBasicBlock &MBB = *Inst->getParent();
2212   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2213
2214   MachineOperand &Dest = Inst->getOperand(0);
2215   MachineOperand &Src0 = Inst->getOperand(1);
2216   MachineOperand &Src1 = Inst->getOperand(2);
2217   DebugLoc DL = Inst->getDebugLoc();
2218
2219   MachineBasicBlock::iterator MII = Inst;
2220
2221   const MCInstrDesc &InstDesc = get(Opcode);
2222   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2223     MRI.getRegClass(Src0.getReg()) :
2224     &AMDGPU::SGPR_32RegClass;
2225
2226   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2227   const TargetRegisterClass *Src1RC = Src1.isReg() ?
2228     MRI.getRegClass(Src1.getReg()) :
2229     &AMDGPU::SGPR_32RegClass;
2230
2231   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
2232
2233   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2234                                                        AMDGPU::sub0, Src0SubRC);
2235   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2236                                                        AMDGPU::sub0, Src1SubRC);
2237
2238   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2239   const TargetRegisterClass *DestSubRC = RI.getSubRegClass(DestRC, AMDGPU::sub0);
2240
2241   unsigned DestSub0 = MRI.createVirtualRegister(DestRC);
2242   MachineInstr *LoHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2243     .addOperand(SrcReg0Sub0)
2244     .addOperand(SrcReg1Sub0);
2245
2246   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2247                                                        AMDGPU::sub1, Src0SubRC);
2248   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2249                                                        AMDGPU::sub1, Src1SubRC);
2250
2251   unsigned DestSub1 = MRI.createVirtualRegister(DestSubRC);
2252   MachineInstr *HiHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2253     .addOperand(SrcReg0Sub1)
2254     .addOperand(SrcReg1Sub1);
2255
2256   unsigned FullDestReg = MRI.createVirtualRegister(DestRC);
2257   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2258     .addReg(DestSub0)
2259     .addImm(AMDGPU::sub0)
2260     .addReg(DestSub1)
2261     .addImm(AMDGPU::sub1);
2262
2263   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2264
2265   // Try to legalize the operands in case we need to swap the order to keep it
2266   // valid.
2267   Worklist.push_back(LoHalf);
2268   Worklist.push_back(HiHalf);
2269 }
2270
2271 void SIInstrInfo::splitScalar64BitBCNT(SmallVectorImpl<MachineInstr *> &Worklist,
2272                                        MachineInstr *Inst) const {
2273   MachineBasicBlock &MBB = *Inst->getParent();
2274   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2275
2276   MachineBasicBlock::iterator MII = Inst;
2277   DebugLoc DL = Inst->getDebugLoc();
2278
2279   MachineOperand &Dest = Inst->getOperand(0);
2280   MachineOperand &Src = Inst->getOperand(1);
2281
2282   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e32);
2283   const TargetRegisterClass *SrcRC = Src.isReg() ?
2284     MRI.getRegClass(Src.getReg()) :
2285     &AMDGPU::SGPR_32RegClass;
2286
2287   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2288   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2289
2290   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
2291
2292   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2293                                                       AMDGPU::sub0, SrcSubRC);
2294   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2295                                                       AMDGPU::sub1, SrcSubRC);
2296
2297   MachineInstr *First = BuildMI(MBB, MII, DL, InstDesc, MidReg)
2298     .addOperand(SrcRegSub0)
2299     .addImm(0);
2300
2301   MachineInstr *Second = BuildMI(MBB, MII, DL, InstDesc, ResultReg)
2302     .addOperand(SrcRegSub1)
2303     .addReg(MidReg);
2304
2305   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2306
2307   Worklist.push_back(First);
2308   Worklist.push_back(Second);
2309 }
2310
2311 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
2312                                       MachineInstr *Inst) const {
2313   MachineBasicBlock &MBB = *Inst->getParent();
2314   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2315   MachineBasicBlock::iterator MII = Inst;
2316   DebugLoc DL = Inst->getDebugLoc();
2317
2318   MachineOperand &Dest = Inst->getOperand(0);
2319   uint32_t Imm = Inst->getOperand(2).getImm();
2320   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2321   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2322
2323   (void) Offset;
2324
2325   // Only sext_inreg cases handled.
2326   assert(Inst->getOpcode() == AMDGPU::S_BFE_I64 &&
2327          BitWidth <= 32 &&
2328          Offset == 0 &&
2329          "Not implemented");
2330
2331   if (BitWidth < 32) {
2332     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2333     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2334     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2335
2336     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
2337       .addReg(Inst->getOperand(1).getReg(), 0, AMDGPU::sub0)
2338       .addImm(0)
2339       .addImm(BitWidth);
2340
2341     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
2342       .addImm(31)
2343       .addReg(MidRegLo);
2344
2345     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2346       .addReg(MidRegLo)
2347       .addImm(AMDGPU::sub0)
2348       .addReg(MidRegHi)
2349       .addImm(AMDGPU::sub1);
2350
2351     MRI.replaceRegWith(Dest.getReg(), ResultReg);
2352     return;
2353   }
2354
2355   MachineOperand &Src = Inst->getOperand(1);
2356   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2357   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2358
2359   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
2360     .addImm(31)
2361     .addReg(Src.getReg(), 0, AMDGPU::sub0);
2362
2363   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2364     .addReg(Src.getReg(), 0, AMDGPU::sub0)
2365     .addImm(AMDGPU::sub0)
2366     .addReg(TmpReg)
2367     .addImm(AMDGPU::sub1);
2368
2369   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2370 }
2371
2372 void SIInstrInfo::addDescImplicitUseDef(const MCInstrDesc &NewDesc,
2373                                         MachineInstr *Inst) const {
2374   // Add the implict and explicit register definitions.
2375   if (NewDesc.ImplicitUses) {
2376     for (unsigned i = 0; NewDesc.ImplicitUses[i]; ++i) {
2377       unsigned Reg = NewDesc.ImplicitUses[i];
2378       Inst->addOperand(MachineOperand::CreateReg(Reg, false, true));
2379     }
2380   }
2381
2382   if (NewDesc.ImplicitDefs) {
2383     for (unsigned i = 0; NewDesc.ImplicitDefs[i]; ++i) {
2384       unsigned Reg = NewDesc.ImplicitDefs[i];
2385       Inst->addOperand(MachineOperand::CreateReg(Reg, true, true));
2386     }
2387   }
2388 }
2389
2390 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr *MI,
2391                                    int OpIndices[3]) const {
2392   const MCInstrDesc &Desc = get(MI->getOpcode());
2393
2394   // Find the one SGPR operand we are allowed to use.
2395   unsigned SGPRReg = AMDGPU::NoRegister;
2396
2397   // First we need to consider the instruction's operand requirements before
2398   // legalizing. Some operands are required to be SGPRs, such as implicit uses
2399   // of VCC, but we are still bound by the constant bus requirement to only use
2400   // one.
2401   //
2402   // If the operand's class is an SGPR, we can never move it.
2403
2404   for (const MachineOperand &MO : MI->implicit_operands()) {
2405     // We only care about reads.
2406     if (MO.isDef())
2407       continue;
2408
2409     if (MO.getReg() == AMDGPU::VCC)
2410       return AMDGPU::VCC;
2411
2412     if (MO.getReg() == AMDGPU::FLAT_SCR)
2413       return AMDGPU::FLAT_SCR;
2414   }
2415
2416   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
2417   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2418
2419   for (unsigned i = 0; i < 3; ++i) {
2420     int Idx = OpIndices[i];
2421     if (Idx == -1)
2422       break;
2423
2424     const MachineOperand &MO = MI->getOperand(Idx);
2425     if (RI.isSGPRClassID(Desc.OpInfo[Idx].RegClass))
2426       SGPRReg = MO.getReg();
2427
2428     if (MO.isReg() && RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2429       UsedSGPRs[i] = MO.getReg();
2430   }
2431
2432   if (SGPRReg != AMDGPU::NoRegister)
2433     return SGPRReg;
2434
2435   // We don't have a required SGPR operand, so we have a bit more freedom in
2436   // selecting operands to move.
2437
2438   // Try to select the most used SGPR. If an SGPR is equal to one of the
2439   // others, we choose that.
2440   //
2441   // e.g.
2442   // V_FMA_F32 v0, s0, s0, s0 -> No moves
2443   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
2444
2445   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
2446     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
2447       SGPRReg = UsedSGPRs[0];
2448   }
2449
2450   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
2451     if (UsedSGPRs[1] == UsedSGPRs[2])
2452       SGPRReg = UsedSGPRs[1];
2453   }
2454
2455   return SGPRReg;
2456 }
2457
2458 MachineInstrBuilder SIInstrInfo::buildIndirectWrite(
2459                                    MachineBasicBlock *MBB,
2460                                    MachineBasicBlock::iterator I,
2461                                    unsigned ValueReg,
2462                                    unsigned Address, unsigned OffsetReg) const {
2463   const DebugLoc &DL = MBB->findDebugLoc(I);
2464   unsigned IndirectBaseReg = AMDGPU::VGPR_32RegClass.getRegister(
2465                                       getIndirectIndexBegin(*MBB->getParent()));
2466
2467   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_DST_V1))
2468           .addReg(IndirectBaseReg, RegState::Define)
2469           .addOperand(I->getOperand(0))
2470           .addReg(IndirectBaseReg)
2471           .addReg(OffsetReg)
2472           .addImm(0)
2473           .addReg(ValueReg);
2474 }
2475
2476 MachineInstrBuilder SIInstrInfo::buildIndirectRead(
2477                                    MachineBasicBlock *MBB,
2478                                    MachineBasicBlock::iterator I,
2479                                    unsigned ValueReg,
2480                                    unsigned Address, unsigned OffsetReg) const {
2481   const DebugLoc &DL = MBB->findDebugLoc(I);
2482   unsigned IndirectBaseReg = AMDGPU::VGPR_32RegClass.getRegister(
2483                                       getIndirectIndexBegin(*MBB->getParent()));
2484
2485   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_SRC))
2486           .addOperand(I->getOperand(0))
2487           .addOperand(I->getOperand(1))
2488           .addReg(IndirectBaseReg)
2489           .addReg(OffsetReg)
2490           .addImm(0);
2491
2492 }
2493
2494 void SIInstrInfo::reserveIndirectRegisters(BitVector &Reserved,
2495                                             const MachineFunction &MF) const {
2496   int End = getIndirectIndexEnd(MF);
2497   int Begin = getIndirectIndexBegin(MF);
2498
2499   if (End == -1)
2500     return;
2501
2502
2503   for (int Index = Begin; Index <= End; ++Index)
2504     Reserved.set(AMDGPU::VGPR_32RegClass.getRegister(Index));
2505
2506   for (int Index = std::max(0, Begin - 1); Index <= End; ++Index)
2507     Reserved.set(AMDGPU::VReg_64RegClass.getRegister(Index));
2508
2509   for (int Index = std::max(0, Begin - 2); Index <= End; ++Index)
2510     Reserved.set(AMDGPU::VReg_96RegClass.getRegister(Index));
2511
2512   for (int Index = std::max(0, Begin - 3); Index <= End; ++Index)
2513     Reserved.set(AMDGPU::VReg_128RegClass.getRegister(Index));
2514
2515   for (int Index = std::max(0, Begin - 7); Index <= End; ++Index)
2516     Reserved.set(AMDGPU::VReg_256RegClass.getRegister(Index));
2517
2518   for (int Index = std::max(0, Begin - 15); Index <= End; ++Index)
2519     Reserved.set(AMDGPU::VReg_512RegClass.getRegister(Index));
2520 }
2521
2522 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
2523                                              unsigned OperandName) const {
2524   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
2525   if (Idx == -1)
2526     return nullptr;
2527
2528   return &MI.getOperand(Idx);
2529 }
2530
2531 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
2532   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
2533   if (ST.isAmdHsaOS())
2534     RsrcDataFormat |= (1ULL << 56);
2535
2536   return RsrcDataFormat;
2537 }