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