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 #include "SIInstrInfo.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "GCNHazardRecognizer.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/CodeGen/ScheduleDAG.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/Support/Debug.h"
28 
29 using namespace llvm;
30 
31 SIInstrInfo::SIInstrInfo(const SISubtarget &ST)
32   : AMDGPUInstrInfo(ST), RI(), ST(ST) {}
33 
34 //===----------------------------------------------------------------------===//
35 // TargetInstrInfo callbacks
36 //===----------------------------------------------------------------------===//
37 
38 static unsigned getNumOperandsNoGlue(SDNode *Node) {
39   unsigned N = Node->getNumOperands();
40   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
41     --N;
42   return N;
43 }
44 
45 static SDValue findChainOperand(SDNode *Load) {
46   SDValue LastOp = Load->getOperand(getNumOperandsNoGlue(Load) - 1);
47   assert(LastOp.getValueType() == MVT::Other && "Chain missing from load node");
48   return LastOp;
49 }
50 
51 /// \brief Returns true if both nodes have the same value for the given
52 ///        operand \p Op, or if both nodes do not have this operand.
53 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
54   unsigned Opc0 = N0->getMachineOpcode();
55   unsigned Opc1 = N1->getMachineOpcode();
56 
57   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
58   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
59 
60   if (Op0Idx == -1 && Op1Idx == -1)
61     return true;
62 
63 
64   if ((Op0Idx == -1 && Op1Idx != -1) ||
65       (Op1Idx == -1 && Op0Idx != -1))
66     return false;
67 
68   // getNamedOperandIdx returns the index for the MachineInstr's operands,
69   // which includes the result as the first operand. We are indexing into the
70   // MachineSDNode's operands, so we need to skip the result operand to get
71   // the real index.
72   --Op0Idx;
73   --Op1Idx;
74 
75   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
76 }
77 
78 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
79                                                     AliasAnalysis *AA) const {
80   // TODO: The generic check fails for VALU instructions that should be
81   // rematerializable due to implicit reads of exec. We really want all of the
82   // generic logic for this except for this.
83   switch (MI.getOpcode()) {
84   case AMDGPU::V_MOV_B32_e32:
85   case AMDGPU::V_MOV_B32_e64:
86   case AMDGPU::V_MOV_B64_PSEUDO:
87     return true;
88   default:
89     return false;
90   }
91 }
92 
93 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
94                                           int64_t &Offset0,
95                                           int64_t &Offset1) const {
96   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
97     return false;
98 
99   unsigned Opc0 = Load0->getMachineOpcode();
100   unsigned Opc1 = Load1->getMachineOpcode();
101 
102   // Make sure both are actually loads.
103   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
104     return false;
105 
106   if (isDS(Opc0) && isDS(Opc1)) {
107 
108     // FIXME: Handle this case:
109     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
110       return false;
111 
112     // Check base reg.
113     if (Load0->getOperand(1) != Load1->getOperand(1))
114       return false;
115 
116     // Check chain.
117     if (findChainOperand(Load0) != findChainOperand(Load1))
118       return false;
119 
120     // Skip read2 / write2 variants for simplicity.
121     // TODO: We should report true if the used offsets are adjacent (excluded
122     // st64 versions).
123     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
124         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
125       return false;
126 
127     Offset0 = cast<ConstantSDNode>(Load0->getOperand(2))->getZExtValue();
128     Offset1 = cast<ConstantSDNode>(Load1->getOperand(2))->getZExtValue();
129     return true;
130   }
131 
132   if (isSMRD(Opc0) && isSMRD(Opc1)) {
133     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
134 
135     // Check base reg.
136     if (Load0->getOperand(0) != Load1->getOperand(0))
137       return false;
138 
139     const ConstantSDNode *Load0Offset =
140         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
141     const ConstantSDNode *Load1Offset =
142         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
143 
144     if (!Load0Offset || !Load1Offset)
145       return false;
146 
147     // Check chain.
148     if (findChainOperand(Load0) != findChainOperand(Load1))
149       return false;
150 
151     Offset0 = Load0Offset->getZExtValue();
152     Offset1 = Load1Offset->getZExtValue();
153     return true;
154   }
155 
156   // MUBUF and MTBUF can access the same addresses.
157   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
158 
159     // MUBUF and MTBUF have vaddr at different indices.
160     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
161         findChainOperand(Load0) != findChainOperand(Load1) ||
162         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
163         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
164       return false;
165 
166     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
167     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
168 
169     if (OffIdx0 == -1 || OffIdx1 == -1)
170       return false;
171 
172     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
173     // inlcude the output in the operand list, but SDNodes don't, we need to
174     // subtract the index by one.
175     --OffIdx0;
176     --OffIdx1;
177 
178     SDValue Off0 = Load0->getOperand(OffIdx0);
179     SDValue Off1 = Load1->getOperand(OffIdx1);
180 
181     // The offset might be a FrameIndexSDNode.
182     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
183       return false;
184 
185     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
186     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
187     return true;
188   }
189 
190   return false;
191 }
192 
193 static bool isStride64(unsigned Opc) {
194   switch (Opc) {
195   case AMDGPU::DS_READ2ST64_B32:
196   case AMDGPU::DS_READ2ST64_B64:
197   case AMDGPU::DS_WRITE2ST64_B32:
198   case AMDGPU::DS_WRITE2ST64_B64:
199     return true;
200   default:
201     return false;
202   }
203 }
204 
205 bool SIInstrInfo::getMemOpBaseRegImmOfs(MachineInstr &LdSt, unsigned &BaseReg,
206                                         int64_t &Offset,
207                                         const TargetRegisterInfo *TRI) const {
208   unsigned Opc = LdSt.getOpcode();
209 
210   if (isDS(LdSt)) {
211     const MachineOperand *OffsetImm =
212         getNamedOperand(LdSt, AMDGPU::OpName::offset);
213     if (OffsetImm) {
214       // Normal, single offset LDS instruction.
215       const MachineOperand *AddrReg =
216           getNamedOperand(LdSt, AMDGPU::OpName::addr);
217 
218       BaseReg = AddrReg->getReg();
219       Offset = OffsetImm->getImm();
220       return true;
221     }
222 
223     // The 2 offset instructions use offset0 and offset1 instead. We can treat
224     // these as a load with a single offset if the 2 offsets are consecutive. We
225     // will use this for some partially aligned loads.
226     const MachineOperand *Offset0Imm =
227         getNamedOperand(LdSt, AMDGPU::OpName::offset0);
228     const MachineOperand *Offset1Imm =
229         getNamedOperand(LdSt, AMDGPU::OpName::offset1);
230 
231     uint8_t Offset0 = Offset0Imm->getImm();
232     uint8_t Offset1 = Offset1Imm->getImm();
233 
234     if (Offset1 > Offset0 && Offset1 - Offset0 == 1) {
235       // Each of these offsets is in element sized units, so we need to convert
236       // to bytes of the individual reads.
237 
238       unsigned EltSize;
239       if (LdSt.mayLoad())
240         EltSize = getOpRegClass(LdSt, 0)->getSize() / 2;
241       else {
242         assert(LdSt.mayStore());
243         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
244         EltSize = getOpRegClass(LdSt, Data0Idx)->getSize();
245       }
246 
247       if (isStride64(Opc))
248         EltSize *= 64;
249 
250       const MachineOperand *AddrReg =
251           getNamedOperand(LdSt, AMDGPU::OpName::addr);
252       BaseReg = AddrReg->getReg();
253       Offset = EltSize * Offset0;
254       return true;
255     }
256 
257     return false;
258   }
259 
260   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
261     if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::soffset) != -1)
262       return false;
263 
264     const MachineOperand *AddrReg =
265         getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
266     if (!AddrReg)
267       return false;
268 
269     const MachineOperand *OffsetImm =
270         getNamedOperand(LdSt, AMDGPU::OpName::offset);
271     BaseReg = AddrReg->getReg();
272     Offset = OffsetImm->getImm();
273     return true;
274   }
275 
276   if (isSMRD(LdSt)) {
277     const MachineOperand *OffsetImm =
278         getNamedOperand(LdSt, AMDGPU::OpName::offset);
279     if (!OffsetImm)
280       return false;
281 
282     const MachineOperand *SBaseReg =
283         getNamedOperand(LdSt, AMDGPU::OpName::sbase);
284     BaseReg = SBaseReg->getReg();
285     Offset = OffsetImm->getImm();
286     return true;
287   }
288 
289   if (isFLAT(LdSt)) {
290     const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::addr);
291     BaseReg = AddrReg->getReg();
292     Offset = 0;
293     return true;
294   }
295 
296   return false;
297 }
298 
299 bool SIInstrInfo::shouldClusterMemOps(MachineInstr &FirstLdSt,
300                                       MachineInstr &SecondLdSt,
301                                       unsigned NumLoads) const {
302   const MachineOperand *FirstDst = nullptr;
303   const MachineOperand *SecondDst = nullptr;
304 
305   if (isDS(FirstLdSt) && isDS(SecondLdSt)) {
306     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
307     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
308   }
309 
310   if (isSMRD(FirstLdSt) && isSMRD(SecondLdSt)) {
311     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::sdst);
312     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::sdst);
313   }
314 
315   if ((isMUBUF(FirstLdSt) && isMUBUF(SecondLdSt)) ||
316       (isMTBUF(FirstLdSt) && isMTBUF(SecondLdSt))) {
317     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdata);
318     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdata);
319   }
320 
321   if (!FirstDst || !SecondDst)
322     return false;
323 
324   // Try to limit clustering based on the total number of bytes loaded
325   // rather than the number of instructions.  This is done to help reduce
326   // register pressure.  The method used is somewhat inexact, though,
327   // because it assumes that all loads in the cluster will load the
328   // same number of bytes as FirstLdSt.
329 
330   // The unit of this value is bytes.
331   // FIXME: This needs finer tuning.
332   unsigned LoadClusterThreshold = 16;
333 
334   const MachineRegisterInfo &MRI =
335       FirstLdSt.getParent()->getParent()->getRegInfo();
336   const TargetRegisterClass *DstRC = MRI.getRegClass(FirstDst->getReg());
337 
338   return (NumLoads * DstRC->getSize()) <= LoadClusterThreshold;
339 }
340 
341 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
342                               MachineBasicBlock::iterator MI,
343                               const DebugLoc &DL, unsigned DestReg,
344                               unsigned SrcReg, bool KillSrc) const {
345 
346   // If we are trying to copy to or from SCC, there is a bug somewhere else in
347   // the backend.  While it may be theoretically possible to do this, it should
348   // never be necessary.
349   assert(DestReg != AMDGPU::SCC && SrcReg != AMDGPU::SCC);
350 
351   static const int16_t Sub0_15[] = {
352     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
353     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
354     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
355     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
356   };
357 
358   static const int16_t Sub0_15_64[] = {
359     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
360     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
361     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
362     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
363   };
364 
365   static const int16_t Sub0_7[] = {
366     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
367     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
368   };
369 
370   static const int16_t Sub0_7_64[] = {
371     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
372     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
373   };
374 
375   static const int16_t Sub0_3[] = {
376     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
377   };
378 
379   static const int16_t Sub0_3_64[] = {
380     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
381   };
382 
383   static const int16_t Sub0_2[] = {
384     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2,
385   };
386 
387   static const int16_t Sub0_1[] = {
388     AMDGPU::sub0, AMDGPU::sub1,
389   };
390 
391   unsigned Opcode;
392   ArrayRef<int16_t> SubIndices;
393 
394   if (AMDGPU::SReg_32RegClass.contains(DestReg)) {
395     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
396     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
397             .addReg(SrcReg, getKillRegState(KillSrc));
398     return;
399 
400   } else if (AMDGPU::SReg_64RegClass.contains(DestReg)) {
401     if (DestReg == AMDGPU::VCC) {
402       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
403         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
404           .addReg(SrcReg, getKillRegState(KillSrc));
405       } else {
406         // FIXME: Hack until VReg_1 removed.
407         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
408         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_I32_e32))
409           .addImm(0)
410           .addReg(SrcReg, getKillRegState(KillSrc));
411       }
412 
413       return;
414     }
415 
416     assert(AMDGPU::SReg_64RegClass.contains(SrcReg));
417     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
418             .addReg(SrcReg, getKillRegState(KillSrc));
419     return;
420 
421   } else if (AMDGPU::SReg_128RegClass.contains(DestReg)) {
422     assert(AMDGPU::SReg_128RegClass.contains(SrcReg));
423     Opcode = AMDGPU::S_MOV_B64;
424     SubIndices = Sub0_3_64;
425 
426   } else if (AMDGPU::SReg_256RegClass.contains(DestReg)) {
427     assert(AMDGPU::SReg_256RegClass.contains(SrcReg));
428     Opcode = AMDGPU::S_MOV_B64;
429     SubIndices = Sub0_7_64;
430 
431   } else if (AMDGPU::SReg_512RegClass.contains(DestReg)) {
432     assert(AMDGPU::SReg_512RegClass.contains(SrcReg));
433     Opcode = AMDGPU::S_MOV_B64;
434     SubIndices = Sub0_15_64;
435 
436   } else if (AMDGPU::VGPR_32RegClass.contains(DestReg)) {
437     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
438            AMDGPU::SReg_32RegClass.contains(SrcReg));
439     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
440             .addReg(SrcReg, getKillRegState(KillSrc));
441     return;
442 
443   } else if (AMDGPU::VReg_64RegClass.contains(DestReg)) {
444     assert(AMDGPU::VReg_64RegClass.contains(SrcReg) ||
445            AMDGPU::SReg_64RegClass.contains(SrcReg));
446     Opcode = AMDGPU::V_MOV_B32_e32;
447     SubIndices = Sub0_1;
448 
449   } else if (AMDGPU::VReg_96RegClass.contains(DestReg)) {
450     assert(AMDGPU::VReg_96RegClass.contains(SrcReg));
451     Opcode = AMDGPU::V_MOV_B32_e32;
452     SubIndices = Sub0_2;
453 
454   } else if (AMDGPU::VReg_128RegClass.contains(DestReg)) {
455     assert(AMDGPU::VReg_128RegClass.contains(SrcReg) ||
456            AMDGPU::SReg_128RegClass.contains(SrcReg));
457     Opcode = AMDGPU::V_MOV_B32_e32;
458     SubIndices = Sub0_3;
459 
460   } else if (AMDGPU::VReg_256RegClass.contains(DestReg)) {
461     assert(AMDGPU::VReg_256RegClass.contains(SrcReg) ||
462            AMDGPU::SReg_256RegClass.contains(SrcReg));
463     Opcode = AMDGPU::V_MOV_B32_e32;
464     SubIndices = Sub0_7;
465 
466   } else if (AMDGPU::VReg_512RegClass.contains(DestReg)) {
467     assert(AMDGPU::VReg_512RegClass.contains(SrcReg) ||
468            AMDGPU::SReg_512RegClass.contains(SrcReg));
469     Opcode = AMDGPU::V_MOV_B32_e32;
470     SubIndices = Sub0_15;
471 
472   } else {
473     llvm_unreachable("Can't copy register!");
474   }
475 
476   bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
477 
478   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
479     unsigned SubIdx;
480     if (Forward)
481       SubIdx = SubIndices[Idx];
482     else
483       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
484 
485     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
486       get(Opcode), RI.getSubReg(DestReg, SubIdx));
487 
488     Builder.addReg(RI.getSubReg(SrcReg, SubIdx));
489 
490     if (Idx == SubIndices.size() - 1)
491       Builder.addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
492 
493     if (Idx == 0)
494       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
495 
496     Builder.addReg(SrcReg, RegState::Implicit);
497   }
498 }
499 
500 int SIInstrInfo::commuteOpcode(const MachineInstr &MI) const {
501   const unsigned Opcode = MI.getOpcode();
502 
503   int NewOpc;
504 
505   // Try to map original to commuted opcode
506   NewOpc = AMDGPU::getCommuteRev(Opcode);
507   if (NewOpc != -1)
508     // Check if the commuted (REV) opcode exists on the target.
509     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
510 
511   // Try to map commuted to original opcode
512   NewOpc = AMDGPU::getCommuteOrig(Opcode);
513   if (NewOpc != -1)
514     // Check if the original (non-REV) opcode exists on the target.
515     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
516 
517   return Opcode;
518 }
519 
520 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
521 
522   if (DstRC->getSize() == 4) {
523     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
524   } else if (DstRC->getSize() == 8 && RI.isSGPRClass(DstRC)) {
525     return AMDGPU::S_MOV_B64;
526   } else if (DstRC->getSize() == 8 && !RI.isSGPRClass(DstRC)) {
527     return  AMDGPU::V_MOV_B64_PSEUDO;
528   }
529   return AMDGPU::COPY;
530 }
531 
532 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
533   switch (Size) {
534   case 4:
535     return AMDGPU::SI_SPILL_S32_SAVE;
536   case 8:
537     return AMDGPU::SI_SPILL_S64_SAVE;
538   case 16:
539     return AMDGPU::SI_SPILL_S128_SAVE;
540   case 32:
541     return AMDGPU::SI_SPILL_S256_SAVE;
542   case 64:
543     return AMDGPU::SI_SPILL_S512_SAVE;
544   default:
545     llvm_unreachable("unknown register size");
546   }
547 }
548 
549 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
550   switch (Size) {
551   case 4:
552     return AMDGPU::SI_SPILL_V32_SAVE;
553   case 8:
554     return AMDGPU::SI_SPILL_V64_SAVE;
555   case 12:
556     return AMDGPU::SI_SPILL_V96_SAVE;
557   case 16:
558     return AMDGPU::SI_SPILL_V128_SAVE;
559   case 32:
560     return AMDGPU::SI_SPILL_V256_SAVE;
561   case 64:
562     return AMDGPU::SI_SPILL_V512_SAVE;
563   default:
564     llvm_unreachable("unknown register size");
565   }
566 }
567 
568 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
569                                       MachineBasicBlock::iterator MI,
570                                       unsigned SrcReg, bool isKill,
571                                       int FrameIndex,
572                                       const TargetRegisterClass *RC,
573                                       const TargetRegisterInfo *TRI) const {
574   MachineFunction *MF = MBB.getParent();
575   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
576   MachineFrameInfo *FrameInfo = MF->getFrameInfo();
577   DebugLoc DL = MBB.findDebugLoc(MI);
578 
579   unsigned Size = FrameInfo->getObjectSize(FrameIndex);
580   unsigned Align = FrameInfo->getObjectAlignment(FrameIndex);
581   MachinePointerInfo PtrInfo
582     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
583   MachineMemOperand *MMO
584     = MF->getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
585                                Size, Align);
586 
587   if (RI.isSGPRClass(RC)) {
588     MFI->setHasSpilledSGPRs();
589 
590     if (TargetRegisterInfo::isVirtualRegister(SrcReg) && RC->getSize() == 4) {
591       // m0 may not be allowed for readlane.
592       MachineRegisterInfo &MRI = MF->getRegInfo();
593       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
594     }
595 
596     // We are only allowed to create one new instruction when spilling
597     // registers, so we need to use pseudo instruction for spilling
598     // SGPRs.
599     unsigned Opcode = getSGPRSpillSaveOpcode(RC->getSize());
600     BuildMI(MBB, MI, DL, get(Opcode))
601       .addReg(SrcReg, getKillRegState(isKill)) // src
602       .addFrameIndex(FrameIndex) // frame_idx
603       .addMemOperand(MMO);
604 
605     return;
606   }
607 
608   if (!ST.isVGPRSpillingEnabled(*MF->getFunction())) {
609     LLVMContext &Ctx = MF->getFunction()->getContext();
610     Ctx.emitError("SIInstrInfo::storeRegToStackSlot - Do not know how to"
611                   " spill register");
612     BuildMI(MBB, MI, DL, get(AMDGPU::KILL))
613       .addReg(SrcReg);
614 
615     return;
616   }
617 
618   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
619 
620   unsigned Opcode = getVGPRSpillSaveOpcode(RC->getSize());
621   MFI->setHasSpilledVGPRs();
622   BuildMI(MBB, MI, DL, get(Opcode))
623     .addReg(SrcReg, getKillRegState(isKill)) // src
624     .addFrameIndex(FrameIndex)        // frame_idx
625     .addReg(MFI->getScratchRSrcReg())       // scratch_rsrc
626     .addReg(MFI->getScratchWaveOffsetReg()) // scratch_offset
627     .addImm(0)                              // offset
628     .addMemOperand(MMO);
629 }
630 
631 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
632   switch (Size) {
633   case 4:
634     return AMDGPU::SI_SPILL_S32_RESTORE;
635   case 8:
636     return AMDGPU::SI_SPILL_S64_RESTORE;
637   case 16:
638     return AMDGPU::SI_SPILL_S128_RESTORE;
639   case 32:
640     return AMDGPU::SI_SPILL_S256_RESTORE;
641   case 64:
642     return AMDGPU::SI_SPILL_S512_RESTORE;
643   default:
644     llvm_unreachable("unknown register size");
645   }
646 }
647 
648 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
649   switch (Size) {
650   case 4:
651     return AMDGPU::SI_SPILL_V32_RESTORE;
652   case 8:
653     return AMDGPU::SI_SPILL_V64_RESTORE;
654   case 12:
655     return AMDGPU::SI_SPILL_V96_RESTORE;
656   case 16:
657     return AMDGPU::SI_SPILL_V128_RESTORE;
658   case 32:
659     return AMDGPU::SI_SPILL_V256_RESTORE;
660   case 64:
661     return AMDGPU::SI_SPILL_V512_RESTORE;
662   default:
663     llvm_unreachable("unknown register size");
664   }
665 }
666 
667 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
668                                        MachineBasicBlock::iterator MI,
669                                        unsigned DestReg, int FrameIndex,
670                                        const TargetRegisterClass *RC,
671                                        const TargetRegisterInfo *TRI) const {
672   MachineFunction *MF = MBB.getParent();
673   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
674   MachineFrameInfo *FrameInfo = MF->getFrameInfo();
675   DebugLoc DL = MBB.findDebugLoc(MI);
676   unsigned Align = FrameInfo->getObjectAlignment(FrameIndex);
677   unsigned Size = FrameInfo->getObjectSize(FrameIndex);
678 
679   MachinePointerInfo PtrInfo
680     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
681 
682   MachineMemOperand *MMO = MF->getMachineMemOperand(
683     PtrInfo, MachineMemOperand::MOLoad, Size, Align);
684 
685   if (RI.isSGPRClass(RC)) {
686     // FIXME: Maybe this should not include a memoperand because it will be
687     // lowered to non-memory instructions.
688     unsigned Opcode = getSGPRSpillRestoreOpcode(RC->getSize());
689 
690     if (TargetRegisterInfo::isVirtualRegister(DestReg) && RC->getSize() == 4) {
691       // m0 may not be allowed for readlane.
692       MachineRegisterInfo &MRI = MF->getRegInfo();
693       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0RegClass);
694     }
695 
696     BuildMI(MBB, MI, DL, get(Opcode), DestReg)
697       .addFrameIndex(FrameIndex) // frame_idx
698       .addMemOperand(MMO);
699 
700     return;
701   }
702 
703   if (!ST.isVGPRSpillingEnabled(*MF->getFunction())) {
704     LLVMContext &Ctx = MF->getFunction()->getContext();
705     Ctx.emitError("SIInstrInfo::loadRegFromStackSlot - Do not know how to"
706                   " restore register");
707     BuildMI(MBB, MI, DL, get(AMDGPU::IMPLICIT_DEF), DestReg);
708 
709     return;
710   }
711 
712   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
713 
714   unsigned Opcode = getVGPRSpillRestoreOpcode(RC->getSize());
715   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
716     .addFrameIndex(FrameIndex)        // frame_idx
717     .addReg(MFI->getScratchRSrcReg())       // scratch_rsrc
718     .addReg(MFI->getScratchWaveOffsetReg()) // scratch_offset
719     .addImm(0)                              // offset
720     .addMemOperand(MMO);
721 }
722 
723 /// \param @Offset Offset in bytes of the FrameIndex being spilled
724 unsigned SIInstrInfo::calculateLDSSpillAddress(
725     MachineBasicBlock &MBB, MachineInstr &MI, RegScavenger *RS, unsigned TmpReg,
726     unsigned FrameOffset, unsigned Size) const {
727   MachineFunction *MF = MBB.getParent();
728   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
729   const SISubtarget &ST = MF->getSubtarget<SISubtarget>();
730   const SIRegisterInfo *TRI = ST.getRegisterInfo();
731   DebugLoc DL = MBB.findDebugLoc(MI);
732   unsigned WorkGroupSize = MFI->getMaximumWorkGroupSize(*MF);
733   unsigned WavefrontSize = ST.getWavefrontSize();
734 
735   unsigned TIDReg = MFI->getTIDReg();
736   if (!MFI->hasCalculatedTID()) {
737     MachineBasicBlock &Entry = MBB.getParent()->front();
738     MachineBasicBlock::iterator Insert = Entry.front();
739     DebugLoc DL = Insert->getDebugLoc();
740 
741     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass);
742     if (TIDReg == AMDGPU::NoRegister)
743       return TIDReg;
744 
745     if (!AMDGPU::isShader(MF->getFunction()->getCallingConv()) &&
746         WorkGroupSize > WavefrontSize) {
747 
748       unsigned TIDIGXReg
749         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_X);
750       unsigned TIDIGYReg
751         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Y);
752       unsigned TIDIGZReg
753         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Z);
754       unsigned InputPtrReg =
755           TRI->getPreloadedValue(*MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
756       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
757         if (!Entry.isLiveIn(Reg))
758           Entry.addLiveIn(Reg);
759       }
760 
761       RS->enterBasicBlock(Entry);
762       // FIXME: Can we scavenge an SReg_64 and access the subregs?
763       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
764       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
765       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
766               .addReg(InputPtrReg)
767               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
768       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
769               .addReg(InputPtrReg)
770               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
771 
772       // NGROUPS.X * NGROUPS.Y
773       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
774               .addReg(STmp1)
775               .addReg(STmp0);
776       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
777       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
778               .addReg(STmp1)
779               .addReg(TIDIGXReg);
780       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
781       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
782               .addReg(STmp0)
783               .addReg(TIDIGYReg)
784               .addReg(TIDReg);
785       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
786       BuildMI(Entry, Insert, DL, get(AMDGPU::V_ADD_I32_e32), TIDReg)
787               .addReg(TIDReg)
788               .addReg(TIDIGZReg);
789     } else {
790       // Get the wave id
791       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
792               TIDReg)
793               .addImm(-1)
794               .addImm(0);
795 
796       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
797               TIDReg)
798               .addImm(-1)
799               .addReg(TIDReg);
800     }
801 
802     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
803             TIDReg)
804             .addImm(2)
805             .addReg(TIDReg);
806     MFI->setTIDReg(TIDReg);
807   }
808 
809   // Add FrameIndex to LDS offset
810   unsigned LDSOffset = MFI->LDSSize + (FrameOffset * WorkGroupSize);
811   BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), TmpReg)
812           .addImm(LDSOffset)
813           .addReg(TIDReg);
814 
815   return TmpReg;
816 }
817 
818 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
819                                    MachineBasicBlock::iterator MI,
820                                    int Count) const {
821   DebugLoc DL = MBB.findDebugLoc(MI);
822   while (Count > 0) {
823     int Arg;
824     if (Count >= 8)
825       Arg = 7;
826     else
827       Arg = Count - 1;
828     Count -= 8;
829     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
830             .addImm(Arg);
831   }
832 }
833 
834 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
835                              MachineBasicBlock::iterator MI) const {
836   insertWaitStates(MBB, MI, 1);
837 }
838 
839 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) const {
840   switch (MI.getOpcode()) {
841   default: return 1; // FIXME: Do wait states equal cycles?
842 
843   case AMDGPU::S_NOP:
844     return MI.getOperand(0).getImm() + 1;
845   }
846 }
847 
848 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
849   MachineBasicBlock &MBB = *MI.getParent();
850   DebugLoc DL = MBB.findDebugLoc(MI);
851   switch (MI.getOpcode()) {
852   default: return AMDGPUInstrInfo::expandPostRAPseudo(MI);
853 
854   case AMDGPU::V_MOV_B64_PSEUDO: {
855     unsigned Dst = MI.getOperand(0).getReg();
856     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
857     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
858 
859     const MachineOperand &SrcOp = MI.getOperand(1);
860     // FIXME: Will this work for 64-bit floating point immediates?
861     assert(!SrcOp.isFPImm());
862     if (SrcOp.isImm()) {
863       APInt Imm(64, SrcOp.getImm());
864       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
865         .addImm(Imm.getLoBits(32).getZExtValue())
866         .addReg(Dst, RegState::Implicit | RegState::Define);
867       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
868         .addImm(Imm.getHiBits(32).getZExtValue())
869         .addReg(Dst, RegState::Implicit | RegState::Define);
870     } else {
871       assert(SrcOp.isReg());
872       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
873         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
874         .addReg(Dst, RegState::Implicit | RegState::Define);
875       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
876         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
877         .addReg(Dst, RegState::Implicit | RegState::Define);
878     }
879     MI.eraseFromParent();
880     break;
881   }
882 
883   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
884     unsigned Dst = MI.getOperand(0).getReg();
885     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
886     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
887     unsigned Src0 = MI.getOperand(1).getReg();
888     unsigned Src1 = MI.getOperand(2).getReg();
889     const MachineOperand &SrcCond = MI.getOperand(3);
890 
891     BuildMI(MBB, MI, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
892       .addReg(RI.getSubReg(Src0, AMDGPU::sub0))
893       .addReg(RI.getSubReg(Src1, AMDGPU::sub0))
894       .addReg(SrcCond.getReg())
895       .addReg(Dst, RegState::Implicit | RegState::Define);
896     BuildMI(MBB, MI, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
897       .addReg(RI.getSubReg(Src0, AMDGPU::sub1))
898       .addReg(RI.getSubReg(Src1, AMDGPU::sub1))
899       .addReg(SrcCond.getReg(), getKillRegState(SrcCond.isKill()))
900       .addReg(Dst, RegState::Implicit | RegState::Define);
901     MI.eraseFromParent();
902     break;
903   }
904 
905   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
906     const SIRegisterInfo *TRI
907       = static_cast<const SIRegisterInfo *>(ST.getRegisterInfo());
908     MachineFunction &MF = *MBB.getParent();
909     unsigned Reg = MI.getOperand(0).getReg();
910     unsigned RegLo = TRI->getSubReg(Reg, AMDGPU::sub0);
911     unsigned RegHi = TRI->getSubReg(Reg, AMDGPU::sub1);
912 
913     // Create a bundle so these instructions won't be re-ordered by the
914     // post-RA scheduler.
915     MIBundleBuilder Bundler(MBB, MI);
916     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
917 
918     // Add 32-bit offset from this instruction to the start of the
919     // constant data.
920     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
921                        .addReg(RegLo)
922                        .addOperand(MI.getOperand(1)));
923     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
924                            .addReg(RegHi)
925                            .addImm(0));
926 
927     llvm::finalizeBundle(MBB, Bundler.begin());
928 
929     MI.eraseFromParent();
930     break;
931   }
932   }
933   return true;
934 }
935 
936 /// Commutes the operands in the given instruction.
937 /// The commutable operands are specified by their indices OpIdx0 and OpIdx1.
938 ///
939 /// Do not call this method for a non-commutable instruction or for
940 /// non-commutable pair of operand indices OpIdx0 and OpIdx1.
941 /// Even though the instruction is commutable, the method may still
942 /// fail to commute the operands, null pointer is returned in such cases.
943 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
944                                                   unsigned OpIdx0,
945                                                   unsigned OpIdx1) const {
946   int CommutedOpcode = commuteOpcode(MI);
947   if (CommutedOpcode == -1)
948     return nullptr;
949 
950   int Src0Idx =
951       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
952   MachineOperand &Src0 = MI.getOperand(Src0Idx);
953   if (!Src0.isReg())
954     return nullptr;
955 
956   int Src1Idx =
957       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
958 
959   if ((OpIdx0 != static_cast<unsigned>(Src0Idx) ||
960        OpIdx1 != static_cast<unsigned>(Src1Idx)) &&
961       (OpIdx0 != static_cast<unsigned>(Src1Idx) ||
962        OpIdx1 != static_cast<unsigned>(Src0Idx)))
963     return nullptr;
964 
965   MachineOperand &Src1 = MI.getOperand(Src1Idx);
966 
967   if (isVOP2(MI) || isVOPC(MI)) {
968     const MCInstrDesc &InstrDesc = MI.getDesc();
969     // For VOP2 and VOPC instructions, any operand type is valid to use for
970     // src0.  Make sure we can use the src0 as src1.
971     //
972     // We could be stricter here and only allow commuting if there is a reason
973     // to do so. i.e. if both operands are VGPRs there is no real benefit,
974     // although MachineCSE attempts to find matches by commuting.
975     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
976     if (!isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0))
977       return nullptr;
978   }
979 
980   MachineInstr *CommutedMI = &MI;
981   if (!Src1.isReg()) {
982     // Allow commuting instructions with Imm operands.
983     if (NewMI || !Src1.isImm() || (!isVOP2(MI) && !isVOP3(MI))) {
984       return nullptr;
985     }
986     // Be sure to copy the source modifiers to the right place.
987     if (MachineOperand *Src0Mods =
988             getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)) {
989       MachineOperand *Src1Mods =
990           getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
991 
992       int Src0ModsVal = Src0Mods->getImm();
993       if (!Src1Mods && Src0ModsVal != 0)
994         return nullptr;
995 
996       // XXX - This assert might be a lie. It might be useful to have a neg
997       // modifier with 0.0.
998       int Src1ModsVal = Src1Mods->getImm();
999       assert((Src1ModsVal == 0) && "Not expecting modifiers with immediates");
1000 
1001       Src1Mods->setImm(Src0ModsVal);
1002       Src0Mods->setImm(Src1ModsVal);
1003     }
1004 
1005     unsigned Reg = Src0.getReg();
1006     unsigned SubReg = Src0.getSubReg();
1007     if (Src1.isImm())
1008       Src0.ChangeToImmediate(Src1.getImm());
1009     else
1010       llvm_unreachable("Should only have immediates");
1011 
1012     Src1.ChangeToRegister(Reg, false);
1013     Src1.setSubReg(SubReg);
1014   } else {
1015     CommutedMI =
1016         TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx0, OpIdx1);
1017   }
1018 
1019   if (CommutedMI)
1020     CommutedMI->setDesc(get(CommutedOpcode));
1021 
1022   return CommutedMI;
1023 }
1024 
1025 // This needs to be implemented because the source modifiers may be inserted
1026 // between the true commutable operands, and the base
1027 // TargetInstrInfo::commuteInstruction uses it.
1028 bool SIInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx0,
1029                                         unsigned &SrcOpIdx1) const {
1030   const MCInstrDesc &MCID = MI.getDesc();
1031   if (!MCID.isCommutable())
1032     return false;
1033 
1034   unsigned Opc = MI.getOpcode();
1035   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1036   if (Src0Idx == -1)
1037     return false;
1038 
1039   // FIXME: Workaround TargetInstrInfo::commuteInstruction asserting on
1040   // immediate. Also, immediate src0 operand is not handled in
1041   // SIInstrInfo::commuteInstruction();
1042   if (!MI.getOperand(Src0Idx).isReg())
1043     return false;
1044 
1045   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1046   if (Src1Idx == -1)
1047     return false;
1048 
1049   MachineOperand &Src1 = MI.getOperand(Src1Idx);
1050   if (Src1.isImm()) {
1051     // SIInstrInfo::commuteInstruction() does support commuting the immediate
1052     // operand src1 in 2 and 3 operand instructions.
1053     if (!isVOP2(MI.getOpcode()) && !isVOP3(MI.getOpcode()))
1054       return false;
1055   } else if (Src1.isReg()) {
1056     // If any source modifiers are set, the generic instruction commuting won't
1057     // understand how to copy the source modifiers.
1058     if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1059         hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers))
1060       return false;
1061   } else
1062     return false;
1063 
1064   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1065 }
1066 
1067 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1068   switch (Cond) {
1069   case SIInstrInfo::SCC_TRUE:
1070     return AMDGPU::S_CBRANCH_SCC1;
1071   case SIInstrInfo::SCC_FALSE:
1072     return AMDGPU::S_CBRANCH_SCC0;
1073   case SIInstrInfo::VCCNZ:
1074     return AMDGPU::S_CBRANCH_VCCNZ;
1075   case SIInstrInfo::VCCZ:
1076     return AMDGPU::S_CBRANCH_VCCZ;
1077   case SIInstrInfo::EXECNZ:
1078     return AMDGPU::S_CBRANCH_EXECNZ;
1079   case SIInstrInfo::EXECZ:
1080     return AMDGPU::S_CBRANCH_EXECZ;
1081   default:
1082     llvm_unreachable("invalid branch predicate");
1083   }
1084 }
1085 
1086 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1087   switch (Opcode) {
1088   case AMDGPU::S_CBRANCH_SCC0:
1089     return SCC_FALSE;
1090   case AMDGPU::S_CBRANCH_SCC1:
1091     return SCC_TRUE;
1092   case AMDGPU::S_CBRANCH_VCCNZ:
1093     return VCCNZ;
1094   case AMDGPU::S_CBRANCH_VCCZ:
1095     return VCCZ;
1096   case AMDGPU::S_CBRANCH_EXECNZ:
1097     return EXECNZ;
1098   case AMDGPU::S_CBRANCH_EXECZ:
1099     return EXECZ;
1100   default:
1101     return INVALID_BR;
1102   }
1103 }
1104 
1105 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1106                                 MachineBasicBlock *&FBB,
1107                                 SmallVectorImpl<MachineOperand> &Cond,
1108                                 bool AllowModify) const {
1109   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1110 
1111   if (I == MBB.end())
1112     return false;
1113 
1114   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1115     // Unconditional Branch
1116     TBB = I->getOperand(0).getMBB();
1117     return false;
1118   }
1119 
1120   BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1121   if (Pred == INVALID_BR)
1122     return true;
1123 
1124   MachineBasicBlock *CondBB = I->getOperand(0).getMBB();
1125   Cond.push_back(MachineOperand::CreateImm(Pred));
1126 
1127   ++I;
1128 
1129   if (I == MBB.end()) {
1130     // Conditional branch followed by fall-through.
1131     TBB = CondBB;
1132     return false;
1133   }
1134 
1135   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1136     TBB = CondBB;
1137     FBB = I->getOperand(0).getMBB();
1138     return false;
1139   }
1140 
1141   return true;
1142 }
1143 
1144 unsigned SIInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
1145   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1146 
1147   unsigned Count = 0;
1148   while (I != MBB.end()) {
1149     MachineBasicBlock::iterator Next = std::next(I);
1150     I->eraseFromParent();
1151     ++Count;
1152     I = Next;
1153   }
1154 
1155   return Count;
1156 }
1157 
1158 unsigned SIInstrInfo::InsertBranch(MachineBasicBlock &MBB,
1159                                    MachineBasicBlock *TBB,
1160                                    MachineBasicBlock *FBB,
1161                                    ArrayRef<MachineOperand> Cond,
1162                                    const DebugLoc &DL) const {
1163 
1164   if (!FBB && Cond.empty()) {
1165     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1166       .addMBB(TBB);
1167     return 1;
1168   }
1169 
1170   assert(TBB && Cond[0].isImm());
1171 
1172   unsigned Opcode
1173     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
1174 
1175   if (!FBB) {
1176     BuildMI(&MBB, DL, get(Opcode))
1177       .addMBB(TBB);
1178     return 1;
1179   }
1180 
1181   assert(TBB && FBB);
1182 
1183   BuildMI(&MBB, DL, get(Opcode))
1184     .addMBB(TBB);
1185   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1186     .addMBB(FBB);
1187 
1188   return 2;
1189 }
1190 
1191 bool SIInstrInfo::ReverseBranchCondition(
1192   SmallVectorImpl<MachineOperand> &Cond) const {
1193   assert(Cond.size() == 1);
1194   Cond[0].setImm(-Cond[0].getImm());
1195   return false;
1196 }
1197 
1198 static void removeModOperands(MachineInstr &MI) {
1199   unsigned Opc = MI.getOpcode();
1200   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1201                                               AMDGPU::OpName::src0_modifiers);
1202   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1203                                               AMDGPU::OpName::src1_modifiers);
1204   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1205                                               AMDGPU::OpName::src2_modifiers);
1206 
1207   MI.RemoveOperand(Src2ModIdx);
1208   MI.RemoveOperand(Src1ModIdx);
1209   MI.RemoveOperand(Src0ModIdx);
1210 }
1211 
1212 // TODO: Maybe this should be removed this and custom fold everything in
1213 // SIFoldOperands?
1214 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1215                                 unsigned Reg, MachineRegisterInfo *MRI) const {
1216   if (!MRI->hasOneNonDBGUse(Reg))
1217     return false;
1218 
1219   unsigned Opc = UseMI.getOpcode();
1220   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64) {
1221     // Don't fold if we are using source modifiers. The new VOP2 instructions
1222     // don't have them.
1223     if (hasModifiersSet(UseMI, AMDGPU::OpName::src0_modifiers) ||
1224         hasModifiersSet(UseMI, AMDGPU::OpName::src1_modifiers) ||
1225         hasModifiersSet(UseMI, AMDGPU::OpName::src2_modifiers)) {
1226       return false;
1227     }
1228 
1229     const MachineOperand &ImmOp = DefMI.getOperand(1);
1230 
1231     // If this is a free constant, there's no reason to do this.
1232     // TODO: We could fold this here instead of letting SIFoldOperands do it
1233     // later.
1234     if (isInlineConstant(ImmOp, 4))
1235       return false;
1236 
1237     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
1238     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
1239     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
1240 
1241     // Multiplied part is the constant: Use v_madmk_f32
1242     // We should only expect these to be on src0 due to canonicalizations.
1243     if (Src0->isReg() && Src0->getReg() == Reg) {
1244       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1245         return false;
1246 
1247       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
1248         return false;
1249 
1250       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
1251 
1252       const int64_t Imm = DefMI.getOperand(1).getImm();
1253 
1254       // FIXME: This would be a lot easier if we could return a new instruction
1255       // instead of having to modify in place.
1256 
1257       // Remove these first since they are at the end.
1258       UseMI.RemoveOperand(
1259           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1260       UseMI.RemoveOperand(
1261           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1262 
1263       unsigned Src1Reg = Src1->getReg();
1264       unsigned Src1SubReg = Src1->getSubReg();
1265       Src0->setReg(Src1Reg);
1266       Src0->setSubReg(Src1SubReg);
1267       Src0->setIsKill(Src1->isKill());
1268 
1269       if (Opc == AMDGPU::V_MAC_F32_e64) {
1270         UseMI.untieRegOperand(
1271             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1272       }
1273 
1274       Src1->ChangeToImmediate(Imm);
1275 
1276       removeModOperands(UseMI);
1277       UseMI.setDesc(get(AMDGPU::V_MADMK_F32));
1278 
1279       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1280       if (DeleteDef)
1281         DefMI.eraseFromParent();
1282 
1283       return true;
1284     }
1285 
1286     // Added part is the constant: Use v_madak_f32
1287     if (Src2->isReg() && Src2->getReg() == Reg) {
1288       // Not allowed to use constant bus for another operand.
1289       // We can however allow an inline immediate as src0.
1290       if (!Src0->isImm() &&
1291           (Src0->isReg() && RI.isSGPRClass(MRI->getRegClass(Src0->getReg()))))
1292         return false;
1293 
1294       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1295         return false;
1296 
1297       const int64_t Imm = DefMI.getOperand(1).getImm();
1298 
1299       // FIXME: This would be a lot easier if we could return a new instruction
1300       // instead of having to modify in place.
1301 
1302       // Remove these first since they are at the end.
1303       UseMI.RemoveOperand(
1304           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1305       UseMI.RemoveOperand(
1306           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1307 
1308       if (Opc == AMDGPU::V_MAC_F32_e64) {
1309         UseMI.untieRegOperand(
1310             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1311       }
1312 
1313       // ChangingToImmediate adds Src2 back to the instruction.
1314       Src2->ChangeToImmediate(Imm);
1315 
1316       // These come before src2.
1317       removeModOperands(UseMI);
1318       UseMI.setDesc(get(AMDGPU::V_MADAK_F32));
1319 
1320       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1321       if (DeleteDef)
1322         DefMI.eraseFromParent();
1323 
1324       return true;
1325     }
1326   }
1327 
1328   return false;
1329 }
1330 
1331 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
1332                                 int WidthB, int OffsetB) {
1333   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1334   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1335   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1336   return LowOffset + LowWidth <= HighOffset;
1337 }
1338 
1339 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr &MIa,
1340                                                MachineInstr &MIb) const {
1341   unsigned BaseReg0, BaseReg1;
1342   int64_t Offset0, Offset1;
1343 
1344   if (getMemOpBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
1345       getMemOpBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
1346 
1347     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
1348       // FIXME: Handle ds_read2 / ds_write2.
1349       return false;
1350     }
1351     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
1352     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
1353     if (BaseReg0 == BaseReg1 &&
1354         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
1355       return true;
1356     }
1357   }
1358 
1359   return false;
1360 }
1361 
1362 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr &MIa,
1363                                                   MachineInstr &MIb,
1364                                                   AliasAnalysis *AA) const {
1365   assert((MIa.mayLoad() || MIa.mayStore()) &&
1366          "MIa must load from or modify a memory location");
1367   assert((MIb.mayLoad() || MIb.mayStore()) &&
1368          "MIb must load from or modify a memory location");
1369 
1370   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
1371     return false;
1372 
1373   // XXX - Can we relax this between address spaces?
1374   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1375     return false;
1376 
1377   // TODO: Should we check the address space from the MachineMemOperand? That
1378   // would allow us to distinguish objects we know don't alias based on the
1379   // underlying address space, even if it was lowered to a different one,
1380   // e.g. private accesses lowered to use MUBUF instructions on a scratch
1381   // buffer.
1382   if (isDS(MIa)) {
1383     if (isDS(MIb))
1384       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1385 
1386     return !isFLAT(MIb);
1387   }
1388 
1389   if (isMUBUF(MIa) || isMTBUF(MIa)) {
1390     if (isMUBUF(MIb) || isMTBUF(MIb))
1391       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1392 
1393     return !isFLAT(MIb) && !isSMRD(MIb);
1394   }
1395 
1396   if (isSMRD(MIa)) {
1397     if (isSMRD(MIb))
1398       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1399 
1400     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
1401   }
1402 
1403   if (isFLAT(MIa)) {
1404     if (isFLAT(MIb))
1405       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1406 
1407     return false;
1408   }
1409 
1410   return false;
1411 }
1412 
1413 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
1414                                                  MachineInstr &MI,
1415                                                  LiveVariables *LV) const {
1416 
1417   switch (MI.getOpcode()) {
1418   default:
1419     return nullptr;
1420   case AMDGPU::V_MAC_F32_e64:
1421     break;
1422   case AMDGPU::V_MAC_F32_e32: {
1423     const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1424     if (Src0->isImm() && !isInlineConstant(*Src0, 4))
1425       return nullptr;
1426     break;
1427   }
1428   }
1429 
1430   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
1431   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1432   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
1433   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
1434 
1435   return BuildMI(*MBB, MI, MI.getDebugLoc(), get(AMDGPU::V_MAD_F32))
1436       .addOperand(*Dst)
1437       .addImm(0) // Src0 mods
1438       .addOperand(*Src0)
1439       .addImm(0) // Src1 mods
1440       .addOperand(*Src1)
1441       .addImm(0) // Src mods
1442       .addOperand(*Src2)
1443       .addImm(0)  // clamp
1444       .addImm(0); // omod
1445 }
1446 
1447 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1448                                        const MachineBasicBlock *MBB,
1449                                        const MachineFunction &MF) const {
1450   // XXX - Do we want the SP check in the base implementation?
1451 
1452   // Target-independent instructions do not have an implicit-use of EXEC, even
1453   // when they operate on VGPRs. Treating EXEC modifications as scheduling
1454   // boundaries prevents incorrect movements of such instructions.
1455   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
1456          MI.modifiesRegister(AMDGPU::EXEC, &RI);
1457 }
1458 
1459 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
1460   int64_t SVal = Imm.getSExtValue();
1461   if (SVal >= -16 && SVal <= 64)
1462     return true;
1463 
1464   if (Imm.getBitWidth() == 64) {
1465     uint64_t Val = Imm.getZExtValue();
1466     return (DoubleToBits(0.0) == Val) ||
1467            (DoubleToBits(1.0) == Val) ||
1468            (DoubleToBits(-1.0) == Val) ||
1469            (DoubleToBits(0.5) == Val) ||
1470            (DoubleToBits(-0.5) == Val) ||
1471            (DoubleToBits(2.0) == Val) ||
1472            (DoubleToBits(-2.0) == Val) ||
1473            (DoubleToBits(4.0) == Val) ||
1474            (DoubleToBits(-4.0) == Val);
1475   }
1476 
1477   // The actual type of the operand does not seem to matter as long
1478   // as the bits match one of the inline immediate values.  For example:
1479   //
1480   // -nan has the hexadecimal encoding of 0xfffffffe which is -2 in decimal,
1481   // so it is a legal inline immediate.
1482   //
1483   // 1065353216 has the hexadecimal encoding 0x3f800000 which is 1.0f in
1484   // floating-point, so it is a legal inline immediate.
1485   uint32_t Val = Imm.getZExtValue();
1486 
1487   return (FloatToBits(0.0f) == Val) ||
1488          (FloatToBits(1.0f) == Val) ||
1489          (FloatToBits(-1.0f) == Val) ||
1490          (FloatToBits(0.5f) == Val) ||
1491          (FloatToBits(-0.5f) == Val) ||
1492          (FloatToBits(2.0f) == Val) ||
1493          (FloatToBits(-2.0f) == Val) ||
1494          (FloatToBits(4.0f) == Val) ||
1495          (FloatToBits(-4.0f) == Val);
1496 }
1497 
1498 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
1499                                    unsigned OpSize) const {
1500   if (MO.isImm()) {
1501     // MachineOperand provides no way to tell the true operand size, since it
1502     // only records a 64-bit value. We need to know the size to determine if a
1503     // 32-bit floating point immediate bit pattern is legal for an integer
1504     // immediate. It would be for any 32-bit integer operand, but would not be
1505     // for a 64-bit one.
1506 
1507     unsigned BitSize = 8 * OpSize;
1508     return isInlineConstant(APInt(BitSize, MO.getImm(), true));
1509   }
1510 
1511   return false;
1512 }
1513 
1514 bool SIInstrInfo::isLiteralConstant(const MachineOperand &MO,
1515                                     unsigned OpSize) const {
1516   return MO.isImm() && !isInlineConstant(MO, OpSize);
1517 }
1518 
1519 static bool compareMachineOp(const MachineOperand &Op0,
1520                              const MachineOperand &Op1) {
1521   if (Op0.getType() != Op1.getType())
1522     return false;
1523 
1524   switch (Op0.getType()) {
1525   case MachineOperand::MO_Register:
1526     return Op0.getReg() == Op1.getReg();
1527   case MachineOperand::MO_Immediate:
1528     return Op0.getImm() == Op1.getImm();
1529   default:
1530     llvm_unreachable("Didn't expect to be comparing these operand types");
1531   }
1532 }
1533 
1534 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
1535                                     const MachineOperand &MO) const {
1536   const MCOperandInfo &OpInfo = get(MI.getOpcode()).OpInfo[OpNo];
1537 
1538   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
1539 
1540   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
1541     return true;
1542 
1543   if (OpInfo.RegClass < 0)
1544     return false;
1545 
1546   unsigned OpSize = RI.getRegClass(OpInfo.RegClass)->getSize();
1547   if (isLiteralConstant(MO, OpSize))
1548     return RI.opCanUseLiteralConstant(OpInfo.OperandType);
1549 
1550   return RI.opCanUseInlineConstant(OpInfo.OperandType);
1551 }
1552 
1553 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
1554   int Op32 = AMDGPU::getVOPe32(Opcode);
1555   if (Op32 == -1)
1556     return false;
1557 
1558   return pseudoToMCOpcode(Op32) != -1;
1559 }
1560 
1561 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1562   // The src0_modifier operand is present on all instructions
1563   // that have modifiers.
1564 
1565   return AMDGPU::getNamedOperandIdx(Opcode,
1566                                     AMDGPU::OpName::src0_modifiers) != -1;
1567 }
1568 
1569 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1570                                   unsigned OpName) const {
1571   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1572   return Mods && Mods->getImm();
1573 }
1574 
1575 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1576                                   const MachineOperand &MO,
1577                                   unsigned OpSize) const {
1578   // Literal constants use the constant bus.
1579   if (isLiteralConstant(MO, OpSize))
1580     return true;
1581 
1582   if (!MO.isReg() || !MO.isUse())
1583     return false;
1584 
1585   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1586     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
1587 
1588   // FLAT_SCR is just an SGPR pair.
1589   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
1590     return true;
1591 
1592   // EXEC register uses the constant bus.
1593   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
1594     return true;
1595 
1596   // SGPRs use the constant bus
1597   return (MO.getReg() == AMDGPU::VCC || MO.getReg() == AMDGPU::M0 ||
1598           (!MO.isImplicit() &&
1599            (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
1600             AMDGPU::SGPR_64RegClass.contains(MO.getReg()))));
1601 }
1602 
1603 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
1604   for (const MachineOperand &MO : MI.implicit_operands()) {
1605     // We only care about reads.
1606     if (MO.isDef())
1607       continue;
1608 
1609     switch (MO.getReg()) {
1610     case AMDGPU::VCC:
1611     case AMDGPU::M0:
1612     case AMDGPU::FLAT_SCR:
1613       return MO.getReg();
1614 
1615     default:
1616       break;
1617     }
1618   }
1619 
1620   return AMDGPU::NoRegister;
1621 }
1622 
1623 static bool shouldReadExec(const MachineInstr &MI) {
1624   if (SIInstrInfo::isVALU(MI)) {
1625     switch (MI.getOpcode()) {
1626     case AMDGPU::V_READLANE_B32:
1627     case AMDGPU::V_READLANE_B32_si:
1628     case AMDGPU::V_READLANE_B32_vi:
1629     case AMDGPU::V_WRITELANE_B32:
1630     case AMDGPU::V_WRITELANE_B32_si:
1631     case AMDGPU::V_WRITELANE_B32_vi:
1632       return false;
1633     }
1634 
1635     return true;
1636   }
1637 
1638   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
1639       SIInstrInfo::isSALU(MI) ||
1640       SIInstrInfo::isSMRD(MI))
1641     return false;
1642 
1643   return true;
1644 }
1645 
1646 static bool isSubRegOf(const SIRegisterInfo &TRI,
1647                        const MachineOperand &SuperVec,
1648                        const MachineOperand &SubReg) {
1649   if (TargetRegisterInfo::isPhysicalRegister(SubReg.getReg()))
1650     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
1651 
1652   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
1653          SubReg.getReg() == SuperVec.getReg();
1654 }
1655 
1656 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
1657                                     StringRef &ErrInfo) const {
1658   uint16_t Opcode = MI.getOpcode();
1659   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1660   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
1661   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
1662   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
1663 
1664   // Make sure the number of operands is correct.
1665   const MCInstrDesc &Desc = get(Opcode);
1666   if (!Desc.isVariadic() &&
1667       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
1668     ErrInfo = "Instruction has wrong number of operands.";
1669     return false;
1670   }
1671 
1672   // Make sure the register classes are correct.
1673   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
1674     if (MI.getOperand(i).isFPImm()) {
1675       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
1676                 "all fp values to integers.";
1677       return false;
1678     }
1679 
1680     int RegClass = Desc.OpInfo[i].RegClass;
1681 
1682     switch (Desc.OpInfo[i].OperandType) {
1683     case MCOI::OPERAND_REGISTER:
1684       if (MI.getOperand(i).isImm()) {
1685         ErrInfo = "Illegal immediate value for operand.";
1686         return false;
1687       }
1688       break;
1689     case AMDGPU::OPERAND_REG_IMM32:
1690       break;
1691     case AMDGPU::OPERAND_REG_INLINE_C:
1692       if (isLiteralConstant(MI.getOperand(i),
1693                             RI.getRegClass(RegClass)->getSize())) {
1694         ErrInfo = "Illegal immediate value for operand.";
1695         return false;
1696       }
1697       break;
1698     case MCOI::OPERAND_IMMEDIATE:
1699     case AMDGPU::OPERAND_KIMM32:
1700       // Check if this operand is an immediate.
1701       // FrameIndex operands will be replaced by immediates, so they are
1702       // allowed.
1703       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
1704         ErrInfo = "Expected immediate, but got non-immediate";
1705         return false;
1706       }
1707       // Fall-through
1708     default:
1709       continue;
1710     }
1711 
1712     if (!MI.getOperand(i).isReg())
1713       continue;
1714 
1715     if (RegClass != -1) {
1716       unsigned Reg = MI.getOperand(i).getReg();
1717       if (Reg == AMDGPU::NoRegister ||
1718           TargetRegisterInfo::isVirtualRegister(Reg))
1719         continue;
1720 
1721       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
1722       if (!RC->contains(Reg)) {
1723         ErrInfo = "Operand has incorrect register class.";
1724         return false;
1725       }
1726     }
1727   }
1728 
1729   // Verify VOP*
1730   if (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI)) {
1731     // Only look at the true operands. Only a real operand can use the constant
1732     // bus, and we don't want to check pseudo-operands like the source modifier
1733     // flags.
1734     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
1735 
1736     unsigned ConstantBusCount = 0;
1737 
1738     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
1739       ++ConstantBusCount;
1740 
1741     unsigned SGPRUsed = findImplicitSGPRRead(MI);
1742     if (SGPRUsed != AMDGPU::NoRegister)
1743       ++ConstantBusCount;
1744 
1745     for (int OpIdx : OpIndices) {
1746       if (OpIdx == -1)
1747         break;
1748       const MachineOperand &MO = MI.getOperand(OpIdx);
1749       if (usesConstantBus(MRI, MO, getOpSize(Opcode, OpIdx))) {
1750         if (MO.isReg()) {
1751           if (MO.getReg() != SGPRUsed)
1752             ++ConstantBusCount;
1753           SGPRUsed = MO.getReg();
1754         } else {
1755           ++ConstantBusCount;
1756         }
1757       }
1758     }
1759     if (ConstantBusCount > 1) {
1760       ErrInfo = "VOP* instruction uses the constant bus more than once";
1761       return false;
1762     }
1763   }
1764 
1765   // Verify misc. restrictions on specific instructions.
1766   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
1767       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
1768     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
1769     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
1770     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
1771     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
1772       if (!compareMachineOp(Src0, Src1) &&
1773           !compareMachineOp(Src0, Src2)) {
1774         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
1775         return false;
1776       }
1777     }
1778   }
1779 
1780   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
1781       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
1782       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
1783       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
1784     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
1785                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
1786 
1787     const unsigned StaticNumOps = Desc.getNumOperands() +
1788       Desc.getNumImplicitUses();
1789     const unsigned NumImplicitOps = IsDst ? 2 : 1;
1790 
1791     if (MI.getNumOperands() != StaticNumOps + NumImplicitOps) {
1792       ErrInfo = "missing implicit register operands";
1793       return false;
1794     }
1795 
1796     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
1797     if (IsDst) {
1798       if (!Dst->isUse()) {
1799         ErrInfo = "v_movreld_b32 vdst should be a use operand";
1800         return false;
1801       }
1802 
1803       unsigned UseOpIdx;
1804       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
1805           UseOpIdx != StaticNumOps + 1) {
1806         ErrInfo = "movrel implicit operands should be tied";
1807         return false;
1808       }
1809     }
1810 
1811     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
1812     const MachineOperand &ImpUse
1813       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
1814     if (!ImpUse.isReg() || !ImpUse.isUse() ||
1815         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
1816       ErrInfo = "src0 should be subreg of implicit vector use";
1817       return false;
1818     }
1819   }
1820 
1821   // Make sure we aren't losing exec uses in the td files. This mostly requires
1822   // being careful when using let Uses to try to add other use registers.
1823   if (shouldReadExec(MI)) {
1824     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
1825       ErrInfo = "VALU instruction does not implicitly read exec mask";
1826       return false;
1827     }
1828   }
1829 
1830   return true;
1831 }
1832 
1833 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
1834   switch (MI.getOpcode()) {
1835   default: return AMDGPU::INSTRUCTION_LIST_END;
1836   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
1837   case AMDGPU::COPY: return AMDGPU::COPY;
1838   case AMDGPU::PHI: return AMDGPU::PHI;
1839   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
1840   case AMDGPU::S_MOV_B32:
1841     return MI.getOperand(1).isReg() ?
1842            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
1843   case AMDGPU::S_ADD_I32:
1844   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
1845   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
1846   case AMDGPU::S_SUB_I32:
1847   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
1848   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
1849   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
1850   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e32;
1851   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e32;
1852   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e32;
1853   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e32;
1854   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e32;
1855   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e32;
1856   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e32;
1857   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
1858   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
1859   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
1860   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
1861   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
1862   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
1863   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
1864   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
1865   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
1866   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
1867   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
1868   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
1869   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
1870   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
1871   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
1872   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
1873   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
1874   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
1875   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
1876   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
1877   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
1878   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
1879   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
1880   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
1881   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
1882   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
1883   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
1884   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
1885   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
1886   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
1887   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
1888   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
1889   }
1890 }
1891 
1892 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
1893   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
1894 }
1895 
1896 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
1897                                                       unsigned OpNo) const {
1898   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1899   const MCInstrDesc &Desc = get(MI.getOpcode());
1900   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
1901       Desc.OpInfo[OpNo].RegClass == -1) {
1902     unsigned Reg = MI.getOperand(OpNo).getReg();
1903 
1904     if (TargetRegisterInfo::isVirtualRegister(Reg))
1905       return MRI.getRegClass(Reg);
1906     return RI.getPhysRegClass(Reg);
1907   }
1908 
1909   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
1910   return RI.getRegClass(RCID);
1911 }
1912 
1913 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
1914   switch (MI.getOpcode()) {
1915   case AMDGPU::COPY:
1916   case AMDGPU::REG_SEQUENCE:
1917   case AMDGPU::PHI:
1918   case AMDGPU::INSERT_SUBREG:
1919     return RI.hasVGPRs(getOpRegClass(MI, 0));
1920   default:
1921     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
1922   }
1923 }
1924 
1925 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
1926   MachineBasicBlock::iterator I = MI;
1927   MachineBasicBlock *MBB = MI.getParent();
1928   MachineOperand &MO = MI.getOperand(OpIdx);
1929   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1930   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
1931   const TargetRegisterClass *RC = RI.getRegClass(RCID);
1932   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1933   if (MO.isReg())
1934     Opcode = AMDGPU::COPY;
1935   else if (RI.isSGPRClass(RC))
1936     Opcode = AMDGPU::S_MOV_B32;
1937 
1938   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
1939   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
1940     VRC = &AMDGPU::VReg_64RegClass;
1941   else
1942     VRC = &AMDGPU::VGPR_32RegClass;
1943 
1944   unsigned Reg = MRI.createVirtualRegister(VRC);
1945   DebugLoc DL = MBB->findDebugLoc(I);
1946   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).addOperand(MO);
1947   MO.ChangeToRegister(Reg, false);
1948 }
1949 
1950 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
1951                                          MachineRegisterInfo &MRI,
1952                                          MachineOperand &SuperReg,
1953                                          const TargetRegisterClass *SuperRC,
1954                                          unsigned SubIdx,
1955                                          const TargetRegisterClass *SubRC)
1956                                          const {
1957   MachineBasicBlock *MBB = MI->getParent();
1958   DebugLoc DL = MI->getDebugLoc();
1959   unsigned SubReg = MRI.createVirtualRegister(SubRC);
1960 
1961   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
1962     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1963       .addReg(SuperReg.getReg(), 0, SubIdx);
1964     return SubReg;
1965   }
1966 
1967   // Just in case the super register is itself a sub-register, copy it to a new
1968   // value so we don't need to worry about merging its subreg index with the
1969   // SubIdx passed to this function. The register coalescer should be able to
1970   // eliminate this extra copy.
1971   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
1972 
1973   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
1974     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
1975 
1976   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1977     .addReg(NewSuperReg, 0, SubIdx);
1978 
1979   return SubReg;
1980 }
1981 
1982 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
1983   MachineBasicBlock::iterator MII,
1984   MachineRegisterInfo &MRI,
1985   MachineOperand &Op,
1986   const TargetRegisterClass *SuperRC,
1987   unsigned SubIdx,
1988   const TargetRegisterClass *SubRC) const {
1989   if (Op.isImm()) {
1990     // XXX - Is there a better way to do this?
1991     if (SubIdx == AMDGPU::sub0)
1992       return MachineOperand::CreateImm(Op.getImm() & 0xFFFFFFFF);
1993     if (SubIdx == AMDGPU::sub1)
1994       return MachineOperand::CreateImm(Op.getImm() >> 32);
1995 
1996     llvm_unreachable("Unhandled register index for immediate");
1997   }
1998 
1999   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
2000                                        SubIdx, SubRC);
2001   return MachineOperand::CreateReg(SubReg, false);
2002 }
2003 
2004 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
2005 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
2006   assert(Inst.getNumExplicitOperands() == 3);
2007   MachineOperand Op1 = Inst.getOperand(1);
2008   Inst.RemoveOperand(1);
2009   Inst.addOperand(Op1);
2010 }
2011 
2012 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
2013                                     const MCOperandInfo &OpInfo,
2014                                     const MachineOperand &MO) const {
2015   if (!MO.isReg())
2016     return false;
2017 
2018   unsigned Reg = MO.getReg();
2019   const TargetRegisterClass *RC =
2020     TargetRegisterInfo::isVirtualRegister(Reg) ?
2021     MRI.getRegClass(Reg) :
2022     RI.getPhysRegClass(Reg);
2023 
2024   const SIRegisterInfo *TRI =
2025       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
2026   RC = TRI->getSubRegClass(RC, MO.getSubReg());
2027 
2028   // In order to be legal, the common sub-class must be equal to the
2029   // class of the current operand.  For example:
2030   //
2031   // v_mov_b32 s0 ; Operand defined as vsrc_32
2032   //              ; RI.getCommonSubClass(s0,vsrc_32) = sgpr ; LEGAL
2033   //
2034   // s_sendmsg 0, s0 ; Operand defined as m0reg
2035   //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
2036 
2037   return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
2038 }
2039 
2040 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
2041                                      const MCOperandInfo &OpInfo,
2042                                      const MachineOperand &MO) const {
2043   if (MO.isReg())
2044     return isLegalRegOperand(MRI, OpInfo, MO);
2045 
2046   // Handle non-register types that are treated like immediates.
2047   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
2048   return true;
2049 }
2050 
2051 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
2052                                  const MachineOperand *MO) const {
2053   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2054   const MCInstrDesc &InstDesc = MI.getDesc();
2055   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
2056   const TargetRegisterClass *DefinedRC =
2057       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
2058   if (!MO)
2059     MO = &MI.getOperand(OpIdx);
2060 
2061   if (isVALU(MI) && usesConstantBus(MRI, *MO, DefinedRC->getSize())) {
2062 
2063     RegSubRegPair SGPRUsed;
2064     if (MO->isReg())
2065       SGPRUsed = RegSubRegPair(MO->getReg(), MO->getSubReg());
2066 
2067     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2068       if (i == OpIdx)
2069         continue;
2070       const MachineOperand &Op = MI.getOperand(i);
2071       if (Op.isReg()) {
2072         if ((Op.getReg() != SGPRUsed.Reg || Op.getSubReg() != SGPRUsed.SubReg) &&
2073             usesConstantBus(MRI, Op, getOpSize(MI, i))) {
2074           return false;
2075         }
2076       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
2077         return false;
2078       }
2079     }
2080   }
2081 
2082   if (MO->isReg()) {
2083     assert(DefinedRC);
2084     return isLegalRegOperand(MRI, OpInfo, *MO);
2085   }
2086 
2087   // Handle non-register types that are treated like immediates.
2088   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
2089 
2090   if (!DefinedRC) {
2091     // This operand expects an immediate.
2092     return true;
2093   }
2094 
2095   return isImmOperandLegal(MI, OpIdx, *MO);
2096 }
2097 
2098 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
2099                                        MachineInstr &MI) const {
2100   unsigned Opc = MI.getOpcode();
2101   const MCInstrDesc &InstrDesc = get(Opc);
2102 
2103   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2104   MachineOperand &Src1 = MI.getOperand(Src1Idx);
2105 
2106   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
2107   // we need to only have one constant bus use.
2108   //
2109   // Note we do not need to worry about literal constants here. They are
2110   // disabled for the operand type for instructions because they will always
2111   // violate the one constant bus use rule.
2112   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
2113   if (HasImplicitSGPR) {
2114     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2115     MachineOperand &Src0 = MI.getOperand(Src0Idx);
2116 
2117     if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg()))
2118       legalizeOpWithMove(MI, Src0Idx);
2119   }
2120 
2121   // VOP2 src0 instructions support all operand types, so we don't need to check
2122   // their legality. If src1 is already legal, we don't need to do anything.
2123   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
2124     return;
2125 
2126   // We do not use commuteInstruction here because it is too aggressive and will
2127   // commute if it is possible. We only want to commute here if it improves
2128   // legality. This can be called a fairly large number of times so don't waste
2129   // compile time pointlessly swapping and checking legality again.
2130   if (HasImplicitSGPR || !MI.isCommutable()) {
2131     legalizeOpWithMove(MI, Src1Idx);
2132     return;
2133   }
2134 
2135   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2136   MachineOperand &Src0 = MI.getOperand(Src0Idx);
2137 
2138   // If src0 can be used as src1, commuting will make the operands legal.
2139   // Otherwise we have to give up and insert a move.
2140   //
2141   // TODO: Other immediate-like operand kinds could be commuted if there was a
2142   // MachineOperand::ChangeTo* for them.
2143   if ((!Src1.isImm() && !Src1.isReg()) ||
2144       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
2145     legalizeOpWithMove(MI, Src1Idx);
2146     return;
2147   }
2148 
2149   int CommutedOpc = commuteOpcode(MI);
2150   if (CommutedOpc == -1) {
2151     legalizeOpWithMove(MI, Src1Idx);
2152     return;
2153   }
2154 
2155   MI.setDesc(get(CommutedOpc));
2156 
2157   unsigned Src0Reg = Src0.getReg();
2158   unsigned Src0SubReg = Src0.getSubReg();
2159   bool Src0Kill = Src0.isKill();
2160 
2161   if (Src1.isImm())
2162     Src0.ChangeToImmediate(Src1.getImm());
2163   else if (Src1.isReg()) {
2164     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
2165     Src0.setSubReg(Src1.getSubReg());
2166   } else
2167     llvm_unreachable("Should only have register or immediate operands");
2168 
2169   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
2170   Src1.setSubReg(Src0SubReg);
2171 }
2172 
2173 // Legalize VOP3 operands. Because all operand types are supported for any
2174 // operand, and since literal constants are not allowed and should never be
2175 // seen, we only need to worry about inserting copies if we use multiple SGPR
2176 // operands.
2177 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
2178                                        MachineInstr &MI) const {
2179   unsigned Opc = MI.getOpcode();
2180 
2181   int VOP3Idx[3] = {
2182     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
2183     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
2184     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
2185   };
2186 
2187   // Find the one SGPR operand we are allowed to use.
2188   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
2189 
2190   for (unsigned i = 0; i < 3; ++i) {
2191     int Idx = VOP3Idx[i];
2192     if (Idx == -1)
2193       break;
2194     MachineOperand &MO = MI.getOperand(Idx);
2195 
2196     // We should never see a VOP3 instruction with an illegal immediate operand.
2197     if (!MO.isReg())
2198       continue;
2199 
2200     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2201       continue; // VGPRs are legal
2202 
2203     if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
2204       SGPRReg = MO.getReg();
2205       // We can use one SGPR in each VOP3 instruction.
2206       continue;
2207     }
2208 
2209     // If we make it this far, then the operand is not legal and we must
2210     // legalize it.
2211     legalizeOpWithMove(MI, Idx);
2212   }
2213 }
2214 
2215 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
2216                                          MachineRegisterInfo &MRI) const {
2217   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
2218   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
2219   unsigned DstReg = MRI.createVirtualRegister(SRC);
2220   unsigned SubRegs = VRC->getSize() / 4;
2221 
2222   SmallVector<unsigned, 8> SRegs;
2223   for (unsigned i = 0; i < SubRegs; ++i) {
2224     unsigned SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2225     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2226             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
2227         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
2228     SRegs.push_back(SGPR);
2229   }
2230 
2231   MachineInstrBuilder MIB =
2232       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2233               get(AMDGPU::REG_SEQUENCE), DstReg);
2234   for (unsigned i = 0; i < SubRegs; ++i) {
2235     MIB.addReg(SRegs[i]);
2236     MIB.addImm(RI.getSubRegFromChannel(i));
2237   }
2238   return DstReg;
2239 }
2240 
2241 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
2242                                        MachineInstr &MI) const {
2243 
2244   // If the pointer is store in VGPRs, then we need to move them to
2245   // SGPRs using v_readfirstlane.  This is safe because we only select
2246   // loads with uniform pointers to SMRD instruction so we know the
2247   // pointer value is uniform.
2248   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
2249   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
2250       unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
2251       SBase->setReg(SGPR);
2252   }
2253 }
2254 
2255 void SIInstrInfo::legalizeOperands(MachineInstr &MI) const {
2256   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2257 
2258   // Legalize VOP2
2259   if (isVOP2(MI) || isVOPC(MI)) {
2260     legalizeOperandsVOP2(MRI, MI);
2261     return;
2262   }
2263 
2264   // Legalize VOP3
2265   if (isVOP3(MI)) {
2266     legalizeOperandsVOP3(MRI, MI);
2267     return;
2268   }
2269 
2270   // Legalize SMRD
2271   if (isSMRD(MI)) {
2272     legalizeOperandsSMRD(MRI, MI);
2273     return;
2274   }
2275 
2276   // Legalize REG_SEQUENCE and PHI
2277   // The register class of the operands much be the same type as the register
2278   // class of the output.
2279   if (MI.getOpcode() == AMDGPU::PHI) {
2280     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
2281     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
2282       if (!MI.getOperand(i).isReg() ||
2283           !TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
2284         continue;
2285       const TargetRegisterClass *OpRC =
2286           MRI.getRegClass(MI.getOperand(i).getReg());
2287       if (RI.hasVGPRs(OpRC)) {
2288         VRC = OpRC;
2289       } else {
2290         SRC = OpRC;
2291       }
2292     }
2293 
2294     // If any of the operands are VGPR registers, then they all most be
2295     // otherwise we will create illegal VGPR->SGPR copies when legalizing
2296     // them.
2297     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
2298       if (!VRC) {
2299         assert(SRC);
2300         VRC = RI.getEquivalentVGPRClass(SRC);
2301       }
2302       RC = VRC;
2303     } else {
2304       RC = SRC;
2305     }
2306 
2307     // Update all the operands so they have the same type.
2308     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2309       MachineOperand &Op = MI.getOperand(I);
2310       if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2311         continue;
2312       unsigned DstReg = MRI.createVirtualRegister(RC);
2313 
2314       // MI is a PHI instruction.
2315       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
2316       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
2317 
2318       BuildMI(*InsertBB, Insert, MI.getDebugLoc(), get(AMDGPU::COPY), DstReg)
2319           .addOperand(Op);
2320       Op.setReg(DstReg);
2321     }
2322   }
2323 
2324   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
2325   // VGPR dest type and SGPR sources, insert copies so all operands are
2326   // VGPRs. This seems to help operand folding / the register coalescer.
2327   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
2328     MachineBasicBlock *MBB = MI.getParent();
2329     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
2330     if (RI.hasVGPRs(DstRC)) {
2331       // Update all the operands so they are VGPR register classes. These may
2332       // not be the same register class because REG_SEQUENCE supports mixing
2333       // subregister index types e.g. sub0_sub1 + sub2 + sub3
2334       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2335         MachineOperand &Op = MI.getOperand(I);
2336         if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2337           continue;
2338 
2339         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
2340         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
2341         if (VRC == OpRC)
2342           continue;
2343 
2344         unsigned DstReg = MRI.createVirtualRegister(VRC);
2345 
2346         BuildMI(*MBB, MI, MI.getDebugLoc(), get(AMDGPU::COPY), DstReg)
2347             .addOperand(Op);
2348 
2349         Op.setReg(DstReg);
2350         Op.setIsKill();
2351       }
2352     }
2353 
2354     return;
2355   }
2356 
2357   // Legalize INSERT_SUBREG
2358   // src0 must have the same register class as dst
2359   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
2360     unsigned Dst = MI.getOperand(0).getReg();
2361     unsigned Src0 = MI.getOperand(1).getReg();
2362     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
2363     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
2364     if (DstRC != Src0RC) {
2365       MachineBasicBlock &MBB = *MI.getParent();
2366       unsigned NewSrc0 = MRI.createVirtualRegister(DstRC);
2367       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::COPY), NewSrc0)
2368           .addReg(Src0);
2369       MI.getOperand(1).setReg(NewSrc0);
2370     }
2371     return;
2372   }
2373 
2374   // Legalize MIMG
2375   if (isMIMG(MI)) {
2376     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
2377     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
2378       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
2379       SRsrc->setReg(SGPR);
2380     }
2381 
2382     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
2383     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
2384       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
2385       SSamp->setReg(SGPR);
2386     }
2387     return;
2388   }
2389 
2390   // Legalize MUBUF* instructions
2391   // FIXME: If we start using the non-addr64 instructions for compute, we
2392   // may need to legalize them here.
2393   int SRsrcIdx =
2394       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
2395   if (SRsrcIdx != -1) {
2396     // We have an MUBUF instruction
2397     MachineOperand *SRsrc = &MI.getOperand(SRsrcIdx);
2398     unsigned SRsrcRC = get(MI.getOpcode()).OpInfo[SRsrcIdx].RegClass;
2399     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
2400                                              RI.getRegClass(SRsrcRC))) {
2401       // The operands are legal.
2402       // FIXME: We may need to legalize operands besided srsrc.
2403       return;
2404     }
2405 
2406     MachineBasicBlock &MBB = *MI.getParent();
2407 
2408     // Extract the ptr from the resource descriptor.
2409     unsigned SRsrcPtr = buildExtractSubReg(MI, MRI, *SRsrc,
2410       &AMDGPU::VReg_128RegClass, AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
2411 
2412     // Create an empty resource descriptor
2413     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2414     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2415     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2416     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
2417     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
2418 
2419     // Zero64 = 0
2420     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B64), Zero64)
2421         .addImm(0);
2422 
2423     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
2424     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
2425         .addImm(RsrcDataFormat & 0xFFFFFFFF);
2426 
2427     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
2428     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
2429         .addImm(RsrcDataFormat >> 32);
2430 
2431     // NewSRsrc = {Zero64, SRsrcFormat}
2432     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewSRsrc)
2433         .addReg(Zero64)
2434         .addImm(AMDGPU::sub0_sub1)
2435         .addReg(SRsrcFormatLo)
2436         .addImm(AMDGPU::sub2)
2437         .addReg(SRsrcFormatHi)
2438         .addImm(AMDGPU::sub3);
2439 
2440     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
2441     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2442     if (VAddr) {
2443       // This is already an ADDR64 instruction so we need to add the pointer
2444       // extracted from the resource descriptor to the current value of VAddr.
2445       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2446       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2447 
2448       // NewVaddrLo = SRsrcPtr:sub0 + VAddr:sub0
2449       DebugLoc DL = MI.getDebugLoc();
2450       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), NewVAddrLo)
2451         .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2452         .addReg(VAddr->getReg(), 0, AMDGPU::sub0);
2453 
2454       // NewVaddrHi = SRsrcPtr:sub1 + VAddr:sub1
2455       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e32), NewVAddrHi)
2456         .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2457         .addReg(VAddr->getReg(), 0, AMDGPU::sub1);
2458 
2459       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2460       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
2461           .addReg(NewVAddrLo)
2462           .addImm(AMDGPU::sub0)
2463           .addReg(NewVAddrHi)
2464           .addImm(AMDGPU::sub1);
2465     } else {
2466       // This instructions is the _OFFSET variant, so we need to convert it to
2467       // ADDR64.
2468       assert(MBB.getParent()->getSubtarget<SISubtarget>().getGeneration()
2469              < SISubtarget::VOLCANIC_ISLANDS &&
2470              "FIXME: Need to emit flat atomics here");
2471 
2472       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
2473       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
2474       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
2475       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
2476 
2477       // Atomics rith return have have an additional tied operand and are
2478       // missing some of the special bits.
2479       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
2480       MachineInstr *Addr64;
2481 
2482       if (!VDataIn) {
2483         // Regular buffer load / store.
2484         MachineInstrBuilder MIB =
2485             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
2486                 .addOperand(*VData)
2487                 .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
2488                 // This will be replaced later
2489                 // with the new value of vaddr.
2490                 .addOperand(*SRsrc)
2491                 .addOperand(*SOffset)
2492                 .addOperand(*Offset);
2493 
2494         // Atomics do not have this operand.
2495         if (const MachineOperand *GLC =
2496                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
2497           MIB.addImm(GLC->getImm());
2498         }
2499 
2500         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
2501 
2502         if (const MachineOperand *TFE =
2503                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
2504           MIB.addImm(TFE->getImm());
2505         }
2506 
2507         MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
2508         Addr64 = MIB;
2509       } else {
2510         // Atomics with return.
2511         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
2512                      .addOperand(*VData)
2513                      .addOperand(*VDataIn)
2514                      .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
2515                      // This will be replaced later
2516                      // with the new value of vaddr.
2517                      .addOperand(*SRsrc)
2518                      .addOperand(*SOffset)
2519                      .addOperand(*Offset)
2520                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
2521                      .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
2522       }
2523 
2524       MI.removeFromParent();
2525 
2526       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2527       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
2528               NewVAddr)
2529           .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2530           .addImm(AMDGPU::sub0)
2531           .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2532           .addImm(AMDGPU::sub1);
2533 
2534       VAddr = getNamedOperand(*Addr64, AMDGPU::OpName::vaddr);
2535       SRsrc = getNamedOperand(*Addr64, AMDGPU::OpName::srsrc);
2536     }
2537 
2538     // Update the instruction to use NewVaddr
2539     VAddr->setReg(NewVAddr);
2540     // Update the instruction to use NewSRsrc
2541     SRsrc->setReg(NewSRsrc);
2542   }
2543 }
2544 
2545 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
2546   SmallVector<MachineInstr *, 128> Worklist;
2547   Worklist.push_back(&TopInst);
2548 
2549   while (!Worklist.empty()) {
2550     MachineInstr &Inst = *Worklist.pop_back_val();
2551     MachineBasicBlock *MBB = Inst.getParent();
2552     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
2553 
2554     unsigned Opcode = Inst.getOpcode();
2555     unsigned NewOpcode = getVALUOp(Inst);
2556 
2557     // Handle some special cases
2558     switch (Opcode) {
2559     default:
2560       break;
2561     case AMDGPU::S_AND_B64:
2562       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_AND_B32_e64);
2563       Inst.eraseFromParent();
2564       continue;
2565 
2566     case AMDGPU::S_OR_B64:
2567       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_OR_B32_e64);
2568       Inst.eraseFromParent();
2569       continue;
2570 
2571     case AMDGPU::S_XOR_B64:
2572       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_XOR_B32_e64);
2573       Inst.eraseFromParent();
2574       continue;
2575 
2576     case AMDGPU::S_NOT_B64:
2577       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::V_NOT_B32_e32);
2578       Inst.eraseFromParent();
2579       continue;
2580 
2581     case AMDGPU::S_BCNT1_I32_B64:
2582       splitScalar64BitBCNT(Worklist, Inst);
2583       Inst.eraseFromParent();
2584       continue;
2585 
2586     case AMDGPU::S_BFE_I64: {
2587       splitScalar64BitBFE(Worklist, Inst);
2588       Inst.eraseFromParent();
2589       continue;
2590     }
2591 
2592     case AMDGPU::S_LSHL_B32:
2593       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2594         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
2595         swapOperands(Inst);
2596       }
2597       break;
2598     case AMDGPU::S_ASHR_I32:
2599       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2600         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
2601         swapOperands(Inst);
2602       }
2603       break;
2604     case AMDGPU::S_LSHR_B32:
2605       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2606         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
2607         swapOperands(Inst);
2608       }
2609       break;
2610     case AMDGPU::S_LSHL_B64:
2611       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2612         NewOpcode = AMDGPU::V_LSHLREV_B64;
2613         swapOperands(Inst);
2614       }
2615       break;
2616     case AMDGPU::S_ASHR_I64:
2617       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2618         NewOpcode = AMDGPU::V_ASHRREV_I64;
2619         swapOperands(Inst);
2620       }
2621       break;
2622     case AMDGPU::S_LSHR_B64:
2623       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2624         NewOpcode = AMDGPU::V_LSHRREV_B64;
2625         swapOperands(Inst);
2626       }
2627       break;
2628 
2629     case AMDGPU::S_ABS_I32:
2630       lowerScalarAbs(Worklist, Inst);
2631       Inst.eraseFromParent();
2632       continue;
2633 
2634     case AMDGPU::S_CBRANCH_SCC0:
2635     case AMDGPU::S_CBRANCH_SCC1:
2636       // Clear unused bits of vcc
2637       BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
2638               AMDGPU::VCC)
2639           .addReg(AMDGPU::EXEC)
2640           .addReg(AMDGPU::VCC);
2641       break;
2642 
2643     case AMDGPU::S_BFE_U64:
2644     case AMDGPU::S_BFM_B64:
2645       llvm_unreachable("Moving this op to VALU not implemented");
2646     }
2647 
2648     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
2649       // We cannot move this instruction to the VALU, so we should try to
2650       // legalize its operands instead.
2651       legalizeOperands(Inst);
2652       continue;
2653     }
2654 
2655     // Use the new VALU Opcode.
2656     const MCInstrDesc &NewDesc = get(NewOpcode);
2657     Inst.setDesc(NewDesc);
2658 
2659     // Remove any references to SCC. Vector instructions can't read from it, and
2660     // We're just about to add the implicit use / defs of VCC, and we don't want
2661     // both.
2662     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
2663       MachineOperand &Op = Inst.getOperand(i);
2664       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
2665         Inst.RemoveOperand(i);
2666         addSCCDefUsersToVALUWorklist(Inst, Worklist);
2667       }
2668     }
2669 
2670     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
2671       // We are converting these to a BFE, so we need to add the missing
2672       // operands for the size and offset.
2673       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
2674       Inst.addOperand(MachineOperand::CreateImm(0));
2675       Inst.addOperand(MachineOperand::CreateImm(Size));
2676 
2677     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
2678       // The VALU version adds the second operand to the result, so insert an
2679       // extra 0 operand.
2680       Inst.addOperand(MachineOperand::CreateImm(0));
2681     }
2682 
2683     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
2684 
2685     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
2686       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
2687       // If we need to move this to VGPRs, we need to unpack the second operand
2688       // back into the 2 separate ones for bit offset and width.
2689       assert(OffsetWidthOp.isImm() &&
2690              "Scalar BFE is only implemented for constant width and offset");
2691       uint32_t Imm = OffsetWidthOp.getImm();
2692 
2693       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2694       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2695       Inst.RemoveOperand(2);                     // Remove old immediate.
2696       Inst.addOperand(MachineOperand::CreateImm(Offset));
2697       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
2698     }
2699 
2700     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
2701     unsigned NewDstReg = AMDGPU::NoRegister;
2702     if (HasDst) {
2703       // Update the destination register class.
2704       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
2705       if (!NewDstRC)
2706         continue;
2707 
2708       unsigned DstReg = Inst.getOperand(0).getReg();
2709       NewDstReg = MRI.createVirtualRegister(NewDstRC);
2710       MRI.replaceRegWith(DstReg, NewDstReg);
2711     }
2712 
2713     // Legalize the operands
2714     legalizeOperands(Inst);
2715 
2716     if (HasDst)
2717      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
2718   }
2719 }
2720 
2721 void SIInstrInfo::lowerScalarAbs(SmallVectorImpl<MachineInstr *> &Worklist,
2722                                  MachineInstr &Inst) const {
2723   MachineBasicBlock &MBB = *Inst.getParent();
2724   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2725   MachineBasicBlock::iterator MII = Inst;
2726   DebugLoc DL = Inst.getDebugLoc();
2727 
2728   MachineOperand &Dest = Inst.getOperand(0);
2729   MachineOperand &Src = Inst.getOperand(1);
2730   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2731   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2732 
2733   BuildMI(MBB, MII, DL, get(AMDGPU::V_SUB_I32_e32), TmpReg)
2734     .addImm(0)
2735     .addReg(Src.getReg());
2736 
2737   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
2738     .addReg(Src.getReg())
2739     .addReg(TmpReg);
2740 
2741   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2742   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2743 }
2744 
2745 void SIInstrInfo::splitScalar64BitUnaryOp(
2746     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
2747     unsigned Opcode) const {
2748   MachineBasicBlock &MBB = *Inst.getParent();
2749   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2750 
2751   MachineOperand &Dest = Inst.getOperand(0);
2752   MachineOperand &Src0 = Inst.getOperand(1);
2753   DebugLoc DL = Inst.getDebugLoc();
2754 
2755   MachineBasicBlock::iterator MII = Inst;
2756 
2757   const MCInstrDesc &InstDesc = get(Opcode);
2758   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2759     MRI.getRegClass(Src0.getReg()) :
2760     &AMDGPU::SGPR_32RegClass;
2761 
2762   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2763 
2764   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2765                                                        AMDGPU::sub0, Src0SubRC);
2766 
2767   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2768   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
2769   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
2770 
2771   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
2772   BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2773     .addOperand(SrcReg0Sub0);
2774 
2775   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2776                                                        AMDGPU::sub1, Src0SubRC);
2777 
2778   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
2779   BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2780     .addOperand(SrcReg0Sub1);
2781 
2782   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
2783   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2784     .addReg(DestSub0)
2785     .addImm(AMDGPU::sub0)
2786     .addReg(DestSub1)
2787     .addImm(AMDGPU::sub1);
2788 
2789   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2790 
2791   // We don't need to legalizeOperands here because for a single operand, src0
2792   // will support any kind of input.
2793 
2794   // Move all users of this moved value.
2795   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
2796 }
2797 
2798 void SIInstrInfo::splitScalar64BitBinaryOp(
2799     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
2800     unsigned Opcode) const {
2801   MachineBasicBlock &MBB = *Inst.getParent();
2802   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2803 
2804   MachineOperand &Dest = Inst.getOperand(0);
2805   MachineOperand &Src0 = Inst.getOperand(1);
2806   MachineOperand &Src1 = Inst.getOperand(2);
2807   DebugLoc DL = Inst.getDebugLoc();
2808 
2809   MachineBasicBlock::iterator MII = Inst;
2810 
2811   const MCInstrDesc &InstDesc = get(Opcode);
2812   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2813     MRI.getRegClass(Src0.getReg()) :
2814     &AMDGPU::SGPR_32RegClass;
2815 
2816   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2817   const TargetRegisterClass *Src1RC = Src1.isReg() ?
2818     MRI.getRegClass(Src1.getReg()) :
2819     &AMDGPU::SGPR_32RegClass;
2820 
2821   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
2822 
2823   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2824                                                        AMDGPU::sub0, Src0SubRC);
2825   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2826                                                        AMDGPU::sub0, Src1SubRC);
2827 
2828   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2829   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
2830   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
2831 
2832   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
2833   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2834                               .addOperand(SrcReg0Sub0)
2835                               .addOperand(SrcReg1Sub0);
2836 
2837   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2838                                                        AMDGPU::sub1, Src0SubRC);
2839   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2840                                                        AMDGPU::sub1, Src1SubRC);
2841 
2842   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
2843   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2844                               .addOperand(SrcReg0Sub1)
2845                               .addOperand(SrcReg1Sub1);
2846 
2847   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
2848   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2849     .addReg(DestSub0)
2850     .addImm(AMDGPU::sub0)
2851     .addReg(DestSub1)
2852     .addImm(AMDGPU::sub1);
2853 
2854   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2855 
2856   // Try to legalize the operands in case we need to swap the order to keep it
2857   // valid.
2858   legalizeOperands(LoHalf);
2859   legalizeOperands(HiHalf);
2860 
2861   // Move all users of this moved vlaue.
2862   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
2863 }
2864 
2865 void SIInstrInfo::splitScalar64BitBCNT(
2866     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst) const {
2867   MachineBasicBlock &MBB = *Inst.getParent();
2868   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2869 
2870   MachineBasicBlock::iterator MII = Inst;
2871   DebugLoc DL = Inst.getDebugLoc();
2872 
2873   MachineOperand &Dest = Inst.getOperand(0);
2874   MachineOperand &Src = Inst.getOperand(1);
2875 
2876   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
2877   const TargetRegisterClass *SrcRC = Src.isReg() ?
2878     MRI.getRegClass(Src.getReg()) :
2879     &AMDGPU::SGPR_32RegClass;
2880 
2881   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2882   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2883 
2884   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
2885 
2886   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2887                                                       AMDGPU::sub0, SrcSubRC);
2888   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2889                                                       AMDGPU::sub1, SrcSubRC);
2890 
2891   BuildMI(MBB, MII, DL, InstDesc, MidReg)
2892     .addOperand(SrcRegSub0)
2893     .addImm(0);
2894 
2895   BuildMI(MBB, MII, DL, InstDesc, ResultReg)
2896     .addOperand(SrcRegSub1)
2897     .addReg(MidReg);
2898 
2899   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2900 
2901   // We don't need to legalize operands here. src0 for etiher instruction can be
2902   // an SGPR, and the second input is unused or determined here.
2903   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2904 }
2905 
2906 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
2907                                       MachineInstr &Inst) const {
2908   MachineBasicBlock &MBB = *Inst.getParent();
2909   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2910   MachineBasicBlock::iterator MII = Inst;
2911   DebugLoc DL = Inst.getDebugLoc();
2912 
2913   MachineOperand &Dest = Inst.getOperand(0);
2914   uint32_t Imm = Inst.getOperand(2).getImm();
2915   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2916   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2917 
2918   (void) Offset;
2919 
2920   // Only sext_inreg cases handled.
2921   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
2922          Offset == 0 && "Not implemented");
2923 
2924   if (BitWidth < 32) {
2925     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2926     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2927     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2928 
2929     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
2930         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
2931         .addImm(0)
2932         .addImm(BitWidth);
2933 
2934     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
2935       .addImm(31)
2936       .addReg(MidRegLo);
2937 
2938     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2939       .addReg(MidRegLo)
2940       .addImm(AMDGPU::sub0)
2941       .addReg(MidRegHi)
2942       .addImm(AMDGPU::sub1);
2943 
2944     MRI.replaceRegWith(Dest.getReg(), ResultReg);
2945     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2946     return;
2947   }
2948 
2949   MachineOperand &Src = Inst.getOperand(1);
2950   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2951   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2952 
2953   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
2954     .addImm(31)
2955     .addReg(Src.getReg(), 0, AMDGPU::sub0);
2956 
2957   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2958     .addReg(Src.getReg(), 0, AMDGPU::sub0)
2959     .addImm(AMDGPU::sub0)
2960     .addReg(TmpReg)
2961     .addImm(AMDGPU::sub1);
2962 
2963   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2964   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2965 }
2966 
2967 void SIInstrInfo::addUsersToMoveToVALUWorklist(
2968   unsigned DstReg,
2969   MachineRegisterInfo &MRI,
2970   SmallVectorImpl<MachineInstr *> &Worklist) const {
2971   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
2972          E = MRI.use_end(); I != E; ++I) {
2973     MachineInstr &UseMI = *I->getParent();
2974     if (!canReadVGPR(UseMI, I.getOperandNo())) {
2975       Worklist.push_back(&UseMI);
2976     }
2977   }
2978 }
2979 
2980 void SIInstrInfo::addSCCDefUsersToVALUWorklist(
2981     MachineInstr &SCCDefInst, SmallVectorImpl<MachineInstr *> &Worklist) const {
2982   // This assumes that all the users of SCC are in the same block
2983   // as the SCC def.
2984   for (MachineInstr &MI :
2985        llvm::make_range(MachineBasicBlock::iterator(SCCDefInst),
2986                         SCCDefInst.getParent()->end())) {
2987     // Exit if we find another SCC def.
2988     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC) != -1)
2989       return;
2990 
2991     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC) != -1)
2992       Worklist.push_back(&MI);
2993   }
2994 }
2995 
2996 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
2997   const MachineInstr &Inst) const {
2998   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
2999 
3000   switch (Inst.getOpcode()) {
3001   // For target instructions, getOpRegClass just returns the virtual register
3002   // class associated with the operand, so we need to find an equivalent VGPR
3003   // register class in order to move the instruction to the VALU.
3004   case AMDGPU::COPY:
3005   case AMDGPU::PHI:
3006   case AMDGPU::REG_SEQUENCE:
3007   case AMDGPU::INSERT_SUBREG:
3008     if (RI.hasVGPRs(NewDstRC))
3009       return nullptr;
3010 
3011     NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
3012     if (!NewDstRC)
3013       return nullptr;
3014     return NewDstRC;
3015   default:
3016     return NewDstRC;
3017   }
3018 }
3019 
3020 // Find the one SGPR operand we are allowed to use.
3021 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
3022                                    int OpIndices[3]) const {
3023   const MCInstrDesc &Desc = MI.getDesc();
3024 
3025   // Find the one SGPR operand we are allowed to use.
3026   //
3027   // First we need to consider the instruction's operand requirements before
3028   // legalizing. Some operands are required to be SGPRs, such as implicit uses
3029   // of VCC, but we are still bound by the constant bus requirement to only use
3030   // one.
3031   //
3032   // If the operand's class is an SGPR, we can never move it.
3033 
3034   unsigned SGPRReg = findImplicitSGPRRead(MI);
3035   if (SGPRReg != AMDGPU::NoRegister)
3036     return SGPRReg;
3037 
3038   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
3039   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3040 
3041   for (unsigned i = 0; i < 3; ++i) {
3042     int Idx = OpIndices[i];
3043     if (Idx == -1)
3044       break;
3045 
3046     const MachineOperand &MO = MI.getOperand(Idx);
3047     if (!MO.isReg())
3048       continue;
3049 
3050     // Is this operand statically required to be an SGPR based on the operand
3051     // constraints?
3052     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
3053     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
3054     if (IsRequiredSGPR)
3055       return MO.getReg();
3056 
3057     // If this could be a VGPR or an SGPR, Check the dynamic register class.
3058     unsigned Reg = MO.getReg();
3059     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
3060     if (RI.isSGPRClass(RegRC))
3061       UsedSGPRs[i] = Reg;
3062   }
3063 
3064   // We don't have a required SGPR operand, so we have a bit more freedom in
3065   // selecting operands to move.
3066 
3067   // Try to select the most used SGPR. If an SGPR is equal to one of the
3068   // others, we choose that.
3069   //
3070   // e.g.
3071   // V_FMA_F32 v0, s0, s0, s0 -> No moves
3072   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
3073 
3074   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
3075   // prefer those.
3076 
3077   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
3078     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
3079       SGPRReg = UsedSGPRs[0];
3080   }
3081 
3082   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
3083     if (UsedSGPRs[1] == UsedSGPRs[2])
3084       SGPRReg = UsedSGPRs[1];
3085   }
3086 
3087   return SGPRReg;
3088 }
3089 
3090 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
3091                                              unsigned OperandName) const {
3092   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
3093   if (Idx == -1)
3094     return nullptr;
3095 
3096   return &MI.getOperand(Idx);
3097 }
3098 
3099 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
3100   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
3101   if (ST.isAmdHsaOS()) {
3102     RsrcDataFormat |= (1ULL << 56);
3103 
3104     if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3105       // Set MTYPE = 2
3106       RsrcDataFormat |= (2ULL << 59);
3107   }
3108 
3109   return RsrcDataFormat;
3110 }
3111 
3112 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
3113   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
3114                     AMDGPU::RSRC_TID_ENABLE |
3115                     0xffffffff; // Size;
3116 
3117   uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
3118 
3119   Rsrc23 |= (EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT) |
3120             // IndexStride = 64
3121             (UINT64_C(3) << AMDGPU::RSRC_INDEX_STRIDE_SHIFT);
3122 
3123   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
3124   // Clear them unless we want a huge stride.
3125   if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3126     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
3127 
3128   return Rsrc23;
3129 }
3130 
3131 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
3132   unsigned Opc = MI.getOpcode();
3133 
3134   return isSMRD(Opc);
3135 }
3136 
3137 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
3138   unsigned Opc = MI.getOpcode();
3139 
3140   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
3141 }
3142 
3143 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
3144   unsigned Opc = MI.getOpcode();
3145   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
3146   unsigned DescSize = Desc.getSize();
3147 
3148   // If we have a definitive size, we can use it. Otherwise we need to inspect
3149   // the operands to know the size.
3150   if (DescSize == 8 || DescSize == 4)
3151     return DescSize;
3152 
3153   assert(DescSize == 0);
3154 
3155   // 4-byte instructions may have a 32-bit literal encoded after them. Check
3156   // operands that coud ever be literals.
3157   if (isVALU(MI) || isSALU(MI)) {
3158     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3159     if (Src0Idx == -1)
3160       return 4; // No operands.
3161 
3162     if (isLiteralConstant(MI.getOperand(Src0Idx), getOpSize(MI, Src0Idx)))
3163       return 8;
3164 
3165     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3166     if (Src1Idx == -1)
3167       return 4;
3168 
3169     if (isLiteralConstant(MI.getOperand(Src1Idx), getOpSize(MI, Src1Idx)))
3170       return 8;
3171 
3172     return 4;
3173   }
3174 
3175   switch (Opc) {
3176   case TargetOpcode::IMPLICIT_DEF:
3177   case TargetOpcode::KILL:
3178   case TargetOpcode::DBG_VALUE:
3179   case TargetOpcode::BUNDLE:
3180   case TargetOpcode::EH_LABEL:
3181     return 0;
3182   case TargetOpcode::INLINEASM: {
3183     const MachineFunction *MF = MI.getParent()->getParent();
3184     const char *AsmStr = MI.getOperand(0).getSymbolName();
3185     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
3186   }
3187   default:
3188     llvm_unreachable("unable to find instruction size");
3189   }
3190 }
3191 
3192 ArrayRef<std::pair<int, const char *>>
3193 SIInstrInfo::getSerializableTargetIndices() const {
3194   static const std::pair<int, const char *> TargetIndices[] = {
3195       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
3196       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
3197       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
3198       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
3199       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
3200   return makeArrayRef(TargetIndices);
3201 }
3202 
3203 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
3204 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
3205 ScheduleHazardRecognizer *
3206 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
3207                                             const ScheduleDAG *DAG) const {
3208   return new GCNHazardRecognizer(DAG->MF);
3209 }
3210 
3211 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
3212 /// pass.
3213 ScheduleHazardRecognizer *
3214 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
3215   return new GCNHazardRecognizer(MF);
3216 }
3217