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