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