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                                    *MF);
743     if (TIDReg == AMDGPU::NoRegister)
744       return TIDReg;
745 
746     if (!AMDGPU::isShader(MF->getFunction()->getCallingConv()) &&
747         WorkGroupSize > WavefrontSize) {
748 
749       unsigned TIDIGXReg
750         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_X);
751       unsigned TIDIGYReg
752         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Y);
753       unsigned TIDIGZReg
754         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Z);
755       unsigned InputPtrReg =
756           TRI->getPreloadedValue(*MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
757       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
758         if (!Entry.isLiveIn(Reg))
759           Entry.addLiveIn(Reg);
760       }
761 
762       RS->enterBasicBlock(Entry);
763       // FIXME: Can we scavenge an SReg_64 and access the subregs?
764       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
765       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
766       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
767               .addReg(InputPtrReg)
768               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
769       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
770               .addReg(InputPtrReg)
771               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
772 
773       // NGROUPS.X * NGROUPS.Y
774       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
775               .addReg(STmp1)
776               .addReg(STmp0);
777       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
778       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
779               .addReg(STmp1)
780               .addReg(TIDIGXReg);
781       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
782       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
783               .addReg(STmp0)
784               .addReg(TIDIGYReg)
785               .addReg(TIDReg);
786       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
787       BuildMI(Entry, Insert, DL, get(AMDGPU::V_ADD_I32_e32), TIDReg)
788               .addReg(TIDReg)
789               .addReg(TIDIGZReg);
790     } else {
791       // Get the wave id
792       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
793               TIDReg)
794               .addImm(-1)
795               .addImm(0);
796 
797       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
798               TIDReg)
799               .addImm(-1)
800               .addReg(TIDReg);
801     }
802 
803     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
804             TIDReg)
805             .addImm(2)
806             .addReg(TIDReg);
807     MFI->setTIDReg(TIDReg);
808   }
809 
810   // Add FrameIndex to LDS offset
811   unsigned LDSOffset = MFI->getLDSSize() + (FrameOffset * WorkGroupSize);
812   BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), TmpReg)
813           .addImm(LDSOffset)
814           .addReg(TIDReg);
815 
816   return TmpReg;
817 }
818 
819 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
820                                    MachineBasicBlock::iterator MI,
821                                    int Count) const {
822   DebugLoc DL = MBB.findDebugLoc(MI);
823   while (Count > 0) {
824     int Arg;
825     if (Count >= 8)
826       Arg = 7;
827     else
828       Arg = Count - 1;
829     Count -= 8;
830     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
831             .addImm(Arg);
832   }
833 }
834 
835 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
836                              MachineBasicBlock::iterator MI) const {
837   insertWaitStates(MBB, MI, 1);
838 }
839 
840 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) const {
841   switch (MI.getOpcode()) {
842   default: return 1; // FIXME: Do wait states equal cycles?
843 
844   case AMDGPU::S_NOP:
845     return MI.getOperand(0).getImm() + 1;
846   }
847 }
848 
849 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
850   MachineBasicBlock &MBB = *MI.getParent();
851   DebugLoc DL = MBB.findDebugLoc(MI);
852   switch (MI.getOpcode()) {
853   default: return AMDGPUInstrInfo::expandPostRAPseudo(MI);
854 
855   case AMDGPU::V_MOV_B64_PSEUDO: {
856     unsigned Dst = MI.getOperand(0).getReg();
857     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
858     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
859 
860     const MachineOperand &SrcOp = MI.getOperand(1);
861     // FIXME: Will this work for 64-bit floating point immediates?
862     assert(!SrcOp.isFPImm());
863     if (SrcOp.isImm()) {
864       APInt Imm(64, SrcOp.getImm());
865       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
866         .addImm(Imm.getLoBits(32).getZExtValue())
867         .addReg(Dst, RegState::Implicit | RegState::Define);
868       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
869         .addImm(Imm.getHiBits(32).getZExtValue())
870         .addReg(Dst, RegState::Implicit | RegState::Define);
871     } else {
872       assert(SrcOp.isReg());
873       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
874         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
875         .addReg(Dst, RegState::Implicit | RegState::Define);
876       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
877         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
878         .addReg(Dst, RegState::Implicit | RegState::Define);
879     }
880     MI.eraseFromParent();
881     break;
882   }
883 
884   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
885     unsigned Dst = MI.getOperand(0).getReg();
886     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
887     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
888     unsigned Src0 = MI.getOperand(1).getReg();
889     unsigned Src1 = MI.getOperand(2).getReg();
890     const MachineOperand &SrcCond = MI.getOperand(3);
891 
892     BuildMI(MBB, MI, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
893       .addReg(RI.getSubReg(Src0, AMDGPU::sub0))
894       .addReg(RI.getSubReg(Src1, AMDGPU::sub0))
895       .addReg(SrcCond.getReg())
896       .addReg(Dst, RegState::Implicit | RegState::Define);
897     BuildMI(MBB, MI, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
898       .addReg(RI.getSubReg(Src0, AMDGPU::sub1))
899       .addReg(RI.getSubReg(Src1, AMDGPU::sub1))
900       .addReg(SrcCond.getReg(), getKillRegState(SrcCond.isKill()))
901       .addReg(Dst, RegState::Implicit | RegState::Define);
902     MI.eraseFromParent();
903     break;
904   }
905 
906   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
907     MachineFunction &MF = *MBB.getParent();
908     unsigned Reg = MI.getOperand(0).getReg();
909     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
910     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
911 
912     // Create a bundle so these instructions won't be re-ordered by the
913     // post-RA scheduler.
914     MIBundleBuilder Bundler(MBB, MI);
915     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
916 
917     // Add 32-bit offset from this instruction to the start of the
918     // constant data.
919     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
920                        .addReg(RegLo)
921                        .addOperand(MI.getOperand(1)));
922     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
923                            .addReg(RegHi)
924                            .addImm(0));
925 
926     llvm::finalizeBundle(MBB, Bundler.begin());
927 
928     MI.eraseFromParent();
929     break;
930   }
931   }
932   return true;
933 }
934 
935 /// Commutes the operands in the given instruction.
936 /// The commutable operands are specified by their indices OpIdx0 and OpIdx1.
937 ///
938 /// Do not call this method for a non-commutable instruction or for
939 /// non-commutable pair of operand indices OpIdx0 and OpIdx1.
940 /// Even though the instruction is commutable, the method may still
941 /// fail to commute the operands, null pointer is returned in such cases.
942 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
943                                                   unsigned OpIdx0,
944                                                   unsigned OpIdx1) const {
945   int CommutedOpcode = commuteOpcode(MI);
946   if (CommutedOpcode == -1)
947     return nullptr;
948 
949   int Src0Idx =
950       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
951   MachineOperand &Src0 = MI.getOperand(Src0Idx);
952   if (!Src0.isReg())
953     return nullptr;
954 
955   int Src1Idx =
956       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
957 
958   if ((OpIdx0 != static_cast<unsigned>(Src0Idx) ||
959        OpIdx1 != static_cast<unsigned>(Src1Idx)) &&
960       (OpIdx0 != static_cast<unsigned>(Src1Idx) ||
961        OpIdx1 != static_cast<unsigned>(Src0Idx)))
962     return nullptr;
963 
964   MachineOperand &Src1 = MI.getOperand(Src1Idx);
965 
966   if (isVOP2(MI) || isVOPC(MI)) {
967     const MCInstrDesc &InstrDesc = MI.getDesc();
968     // For VOP2 and VOPC instructions, any operand type is valid to use for
969     // src0.  Make sure we can use the src0 as src1.
970     //
971     // We could be stricter here and only allow commuting if there is a reason
972     // to do so. i.e. if both operands are VGPRs there is no real benefit,
973     // although MachineCSE attempts to find matches by commuting.
974     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
975     if (!isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0))
976       return nullptr;
977   }
978 
979   MachineInstr *CommutedMI = &MI;
980   if (!Src1.isReg()) {
981     // Allow commuting instructions with Imm operands.
982     if (NewMI || !Src1.isImm() || (!isVOP2(MI) && !isVOP3(MI))) {
983       return nullptr;
984     }
985     // Be sure to copy the source modifiers to the right place.
986     if (MachineOperand *Src0Mods =
987             getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)) {
988       MachineOperand *Src1Mods =
989           getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
990 
991       int Src0ModsVal = Src0Mods->getImm();
992       if (!Src1Mods && Src0ModsVal != 0)
993         return nullptr;
994 
995       // XXX - This assert might be a lie. It might be useful to have a neg
996       // modifier with 0.0.
997       int Src1ModsVal = Src1Mods->getImm();
998       assert((Src1ModsVal == 0) && "Not expecting modifiers with immediates");
999 
1000       Src1Mods->setImm(Src0ModsVal);
1001       Src0Mods->setImm(Src1ModsVal);
1002     }
1003 
1004     unsigned Reg = Src0.getReg();
1005     unsigned SubReg = Src0.getSubReg();
1006     if (Src1.isImm())
1007       Src0.ChangeToImmediate(Src1.getImm());
1008     else
1009       llvm_unreachable("Should only have immediates");
1010 
1011     Src1.ChangeToRegister(Reg, false);
1012     Src1.setSubReg(SubReg);
1013   } else {
1014     CommutedMI =
1015         TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx0, OpIdx1);
1016   }
1017 
1018   if (CommutedMI)
1019     CommutedMI->setDesc(get(CommutedOpcode));
1020 
1021   return CommutedMI;
1022 }
1023 
1024 // This needs to be implemented because the source modifiers may be inserted
1025 // between the true commutable operands, and the base
1026 // TargetInstrInfo::commuteInstruction uses it.
1027 bool SIInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx0,
1028                                         unsigned &SrcOpIdx1) const {
1029   const MCInstrDesc &MCID = MI.getDesc();
1030   if (!MCID.isCommutable())
1031     return false;
1032 
1033   unsigned Opc = MI.getOpcode();
1034   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1035   if (Src0Idx == -1)
1036     return false;
1037 
1038   // FIXME: Workaround TargetInstrInfo::commuteInstruction asserting on
1039   // immediate. Also, immediate src0 operand is not handled in
1040   // SIInstrInfo::commuteInstruction();
1041   if (!MI.getOperand(Src0Idx).isReg())
1042     return false;
1043 
1044   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1045   if (Src1Idx == -1)
1046     return false;
1047 
1048   MachineOperand &Src1 = MI.getOperand(Src1Idx);
1049   if (Src1.isImm()) {
1050     // SIInstrInfo::commuteInstruction() does support commuting the immediate
1051     // operand src1 in 2 and 3 operand instructions.
1052     if (!isVOP2(MI.getOpcode()) && !isVOP3(MI.getOpcode()))
1053       return false;
1054   } else if (Src1.isReg()) {
1055     // If any source modifiers are set, the generic instruction commuting won't
1056     // understand how to copy the source modifiers.
1057     if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1058         hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers))
1059       return false;
1060   } else
1061     return false;
1062 
1063   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1064 }
1065 
1066 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1067   switch (Cond) {
1068   case SIInstrInfo::SCC_TRUE:
1069     return AMDGPU::S_CBRANCH_SCC1;
1070   case SIInstrInfo::SCC_FALSE:
1071     return AMDGPU::S_CBRANCH_SCC0;
1072   case SIInstrInfo::VCCNZ:
1073     return AMDGPU::S_CBRANCH_VCCNZ;
1074   case SIInstrInfo::VCCZ:
1075     return AMDGPU::S_CBRANCH_VCCZ;
1076   case SIInstrInfo::EXECNZ:
1077     return AMDGPU::S_CBRANCH_EXECNZ;
1078   case SIInstrInfo::EXECZ:
1079     return AMDGPU::S_CBRANCH_EXECZ;
1080   default:
1081     llvm_unreachable("invalid branch predicate");
1082   }
1083 }
1084 
1085 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1086   switch (Opcode) {
1087   case AMDGPU::S_CBRANCH_SCC0:
1088     return SCC_FALSE;
1089   case AMDGPU::S_CBRANCH_SCC1:
1090     return SCC_TRUE;
1091   case AMDGPU::S_CBRANCH_VCCNZ:
1092     return VCCNZ;
1093   case AMDGPU::S_CBRANCH_VCCZ:
1094     return VCCZ;
1095   case AMDGPU::S_CBRANCH_EXECNZ:
1096     return EXECNZ;
1097   case AMDGPU::S_CBRANCH_EXECZ:
1098     return EXECZ;
1099   default:
1100     return INVALID_BR;
1101   }
1102 }
1103 
1104 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1105                                 MachineBasicBlock *&FBB,
1106                                 SmallVectorImpl<MachineOperand> &Cond,
1107                                 bool AllowModify) const {
1108   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1109 
1110   if (I == MBB.end())
1111     return false;
1112 
1113   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1114     // Unconditional Branch
1115     TBB = I->getOperand(0).getMBB();
1116     return false;
1117   }
1118 
1119   BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1120   if (Pred == INVALID_BR)
1121     return true;
1122 
1123   MachineBasicBlock *CondBB = I->getOperand(0).getMBB();
1124   Cond.push_back(MachineOperand::CreateImm(Pred));
1125 
1126   ++I;
1127 
1128   if (I == MBB.end()) {
1129     // Conditional branch followed by fall-through.
1130     TBB = CondBB;
1131     return false;
1132   }
1133 
1134   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1135     TBB = CondBB;
1136     FBB = I->getOperand(0).getMBB();
1137     return false;
1138   }
1139 
1140   return true;
1141 }
1142 
1143 unsigned SIInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
1144   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1145 
1146   unsigned Count = 0;
1147   while (I != MBB.end()) {
1148     MachineBasicBlock::iterator Next = std::next(I);
1149     I->eraseFromParent();
1150     ++Count;
1151     I = Next;
1152   }
1153 
1154   return Count;
1155 }
1156 
1157 unsigned SIInstrInfo::InsertBranch(MachineBasicBlock &MBB,
1158                                    MachineBasicBlock *TBB,
1159                                    MachineBasicBlock *FBB,
1160                                    ArrayRef<MachineOperand> Cond,
1161                                    const DebugLoc &DL) const {
1162 
1163   if (!FBB && Cond.empty()) {
1164     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1165       .addMBB(TBB);
1166     return 1;
1167   }
1168 
1169   assert(TBB && Cond[0].isImm());
1170 
1171   unsigned Opcode
1172     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
1173 
1174   if (!FBB) {
1175     BuildMI(&MBB, DL, get(Opcode))
1176       .addMBB(TBB);
1177     return 1;
1178   }
1179 
1180   assert(TBB && FBB);
1181 
1182   BuildMI(&MBB, DL, get(Opcode))
1183     .addMBB(TBB);
1184   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1185     .addMBB(FBB);
1186 
1187   return 2;
1188 }
1189 
1190 bool SIInstrInfo::ReverseBranchCondition(
1191   SmallVectorImpl<MachineOperand> &Cond) const {
1192   assert(Cond.size() == 1);
1193   Cond[0].setImm(-Cond[0].getImm());
1194   return false;
1195 }
1196 
1197 static void removeModOperands(MachineInstr &MI) {
1198   unsigned Opc = MI.getOpcode();
1199   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1200                                               AMDGPU::OpName::src0_modifiers);
1201   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1202                                               AMDGPU::OpName::src1_modifiers);
1203   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1204                                               AMDGPU::OpName::src2_modifiers);
1205 
1206   MI.RemoveOperand(Src2ModIdx);
1207   MI.RemoveOperand(Src1ModIdx);
1208   MI.RemoveOperand(Src0ModIdx);
1209 }
1210 
1211 // TODO: Maybe this should be removed this and custom fold everything in
1212 // SIFoldOperands?
1213 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1214                                 unsigned Reg, MachineRegisterInfo *MRI) const {
1215   if (!MRI->hasOneNonDBGUse(Reg))
1216     return false;
1217 
1218   unsigned Opc = UseMI.getOpcode();
1219   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64) {
1220     // Don't fold if we are using source modifiers. The new VOP2 instructions
1221     // don't have them.
1222     if (hasModifiersSet(UseMI, AMDGPU::OpName::src0_modifiers) ||
1223         hasModifiersSet(UseMI, AMDGPU::OpName::src1_modifiers) ||
1224         hasModifiersSet(UseMI, AMDGPU::OpName::src2_modifiers)) {
1225       return false;
1226     }
1227 
1228     const MachineOperand &ImmOp = DefMI.getOperand(1);
1229 
1230     // If this is a free constant, there's no reason to do this.
1231     // TODO: We could fold this here instead of letting SIFoldOperands do it
1232     // later.
1233     if (isInlineConstant(ImmOp, 4))
1234       return false;
1235 
1236     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
1237     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
1238     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
1239 
1240     // Multiplied part is the constant: Use v_madmk_f32
1241     // We should only expect these to be on src0 due to canonicalizations.
1242     if (Src0->isReg() && Src0->getReg() == Reg) {
1243       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1244         return false;
1245 
1246       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
1247         return false;
1248 
1249       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
1250 
1251       const int64_t Imm = DefMI.getOperand(1).getImm();
1252 
1253       // FIXME: This would be a lot easier if we could return a new instruction
1254       // instead of having to modify in place.
1255 
1256       // Remove these first since they are at the end.
1257       UseMI.RemoveOperand(
1258           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1259       UseMI.RemoveOperand(
1260           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1261 
1262       unsigned Src1Reg = Src1->getReg();
1263       unsigned Src1SubReg = Src1->getSubReg();
1264       Src0->setReg(Src1Reg);
1265       Src0->setSubReg(Src1SubReg);
1266       Src0->setIsKill(Src1->isKill());
1267 
1268       if (Opc == AMDGPU::V_MAC_F32_e64) {
1269         UseMI.untieRegOperand(
1270             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1271       }
1272 
1273       Src1->ChangeToImmediate(Imm);
1274 
1275       removeModOperands(UseMI);
1276       UseMI.setDesc(get(AMDGPU::V_MADMK_F32));
1277 
1278       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1279       if (DeleteDef)
1280         DefMI.eraseFromParent();
1281 
1282       return true;
1283     }
1284 
1285     // Added part is the constant: Use v_madak_f32
1286     if (Src2->isReg() && Src2->getReg() == Reg) {
1287       // Not allowed to use constant bus for another operand.
1288       // We can however allow an inline immediate as src0.
1289       if (!Src0->isImm() &&
1290           (Src0->isReg() && RI.isSGPRClass(MRI->getRegClass(Src0->getReg()))))
1291         return false;
1292 
1293       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1294         return false;
1295 
1296       const int64_t Imm = DefMI.getOperand(1).getImm();
1297 
1298       // FIXME: This would be a lot easier if we could return a new instruction
1299       // instead of having to modify in place.
1300 
1301       // Remove these first since they are at the end.
1302       UseMI.RemoveOperand(
1303           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1304       UseMI.RemoveOperand(
1305           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1306 
1307       if (Opc == AMDGPU::V_MAC_F32_e64) {
1308         UseMI.untieRegOperand(
1309             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1310       }
1311 
1312       // ChangingToImmediate adds Src2 back to the instruction.
1313       Src2->ChangeToImmediate(Imm);
1314 
1315       // These come before src2.
1316       removeModOperands(UseMI);
1317       UseMI.setDesc(get(AMDGPU::V_MADAK_F32));
1318 
1319       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1320       if (DeleteDef)
1321         DefMI.eraseFromParent();
1322 
1323       return true;
1324     }
1325   }
1326 
1327   return false;
1328 }
1329 
1330 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
1331                                 int WidthB, int OffsetB) {
1332   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1333   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1334   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1335   return LowOffset + LowWidth <= HighOffset;
1336 }
1337 
1338 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr &MIa,
1339                                                MachineInstr &MIb) const {
1340   unsigned BaseReg0, BaseReg1;
1341   int64_t Offset0, Offset1;
1342 
1343   if (getMemOpBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
1344       getMemOpBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
1345 
1346     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
1347       // FIXME: Handle ds_read2 / ds_write2.
1348       return false;
1349     }
1350     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
1351     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
1352     if (BaseReg0 == BaseReg1 &&
1353         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
1354       return true;
1355     }
1356   }
1357 
1358   return false;
1359 }
1360 
1361 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr &MIa,
1362                                                   MachineInstr &MIb,
1363                                                   AliasAnalysis *AA) const {
1364   assert((MIa.mayLoad() || MIa.mayStore()) &&
1365          "MIa must load from or modify a memory location");
1366   assert((MIb.mayLoad() || MIb.mayStore()) &&
1367          "MIb must load from or modify a memory location");
1368 
1369   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
1370     return false;
1371 
1372   // XXX - Can we relax this between address spaces?
1373   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1374     return false;
1375 
1376   // TODO: Should we check the address space from the MachineMemOperand? That
1377   // would allow us to distinguish objects we know don't alias based on the
1378   // underlying address space, even if it was lowered to a different one,
1379   // e.g. private accesses lowered to use MUBUF instructions on a scratch
1380   // buffer.
1381   if (isDS(MIa)) {
1382     if (isDS(MIb))
1383       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1384 
1385     return !isFLAT(MIb);
1386   }
1387 
1388   if (isMUBUF(MIa) || isMTBUF(MIa)) {
1389     if (isMUBUF(MIb) || isMTBUF(MIb))
1390       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1391 
1392     return !isFLAT(MIb) && !isSMRD(MIb);
1393   }
1394 
1395   if (isSMRD(MIa)) {
1396     if (isSMRD(MIb))
1397       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1398 
1399     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
1400   }
1401 
1402   if (isFLAT(MIa)) {
1403     if (isFLAT(MIb))
1404       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1405 
1406     return false;
1407   }
1408 
1409   return false;
1410 }
1411 
1412 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
1413                                                  MachineInstr &MI,
1414                                                  LiveVariables *LV) const {
1415 
1416   switch (MI.getOpcode()) {
1417   default:
1418     return nullptr;
1419   case AMDGPU::V_MAC_F32_e64:
1420     break;
1421   case AMDGPU::V_MAC_F32_e32: {
1422     const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1423     if (Src0->isImm() && !isInlineConstant(*Src0, 4))
1424       return nullptr;
1425     break;
1426   }
1427   }
1428 
1429   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
1430   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1431   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
1432   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
1433 
1434   return BuildMI(*MBB, MI, MI.getDebugLoc(), get(AMDGPU::V_MAD_F32))
1435       .addOperand(*Dst)
1436       .addImm(0) // Src0 mods
1437       .addOperand(*Src0)
1438       .addImm(0) // Src1 mods
1439       .addOperand(*Src1)
1440       .addImm(0) // Src mods
1441       .addOperand(*Src2)
1442       .addImm(0)  // clamp
1443       .addImm(0); // omod
1444 }
1445 
1446 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1447                                        const MachineBasicBlock *MBB,
1448                                        const MachineFunction &MF) const {
1449   // XXX - Do we want the SP check in the base implementation?
1450 
1451   // Target-independent instructions do not have an implicit-use of EXEC, even
1452   // when they operate on VGPRs. Treating EXEC modifications as scheduling
1453   // boundaries prevents incorrect movements of such instructions.
1454   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
1455          MI.modifiesRegister(AMDGPU::EXEC, &RI);
1456 }
1457 
1458 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
1459   int64_t SVal = Imm.getSExtValue();
1460   if (SVal >= -16 && SVal <= 64)
1461     return true;
1462 
1463   if (Imm.getBitWidth() == 64) {
1464     uint64_t Val = Imm.getZExtValue();
1465     return (DoubleToBits(0.0) == Val) ||
1466            (DoubleToBits(1.0) == Val) ||
1467            (DoubleToBits(-1.0) == Val) ||
1468            (DoubleToBits(0.5) == Val) ||
1469            (DoubleToBits(-0.5) == Val) ||
1470            (DoubleToBits(2.0) == Val) ||
1471            (DoubleToBits(-2.0) == Val) ||
1472            (DoubleToBits(4.0) == Val) ||
1473            (DoubleToBits(-4.0) == Val);
1474   }
1475 
1476   // The actual type of the operand does not seem to matter as long
1477   // as the bits match one of the inline immediate values.  For example:
1478   //
1479   // -nan has the hexadecimal encoding of 0xfffffffe which is -2 in decimal,
1480   // so it is a legal inline immediate.
1481   //
1482   // 1065353216 has the hexadecimal encoding 0x3f800000 which is 1.0f in
1483   // floating-point, so it is a legal inline immediate.
1484   uint32_t Val = Imm.getZExtValue();
1485 
1486   return (FloatToBits(0.0f) == Val) ||
1487          (FloatToBits(1.0f) == Val) ||
1488          (FloatToBits(-1.0f) == Val) ||
1489          (FloatToBits(0.5f) == Val) ||
1490          (FloatToBits(-0.5f) == Val) ||
1491          (FloatToBits(2.0f) == Val) ||
1492          (FloatToBits(-2.0f) == Val) ||
1493          (FloatToBits(4.0f) == Val) ||
1494          (FloatToBits(-4.0f) == Val);
1495 }
1496 
1497 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
1498                                    unsigned OpSize) const {
1499   if (MO.isImm()) {
1500     // MachineOperand provides no way to tell the true operand size, since it
1501     // only records a 64-bit value. We need to know the size to determine if a
1502     // 32-bit floating point immediate bit pattern is legal for an integer
1503     // immediate. It would be for any 32-bit integer operand, but would not be
1504     // for a 64-bit one.
1505 
1506     unsigned BitSize = 8 * OpSize;
1507     return isInlineConstant(APInt(BitSize, MO.getImm(), true));
1508   }
1509 
1510   return false;
1511 }
1512 
1513 bool SIInstrInfo::isLiteralConstant(const MachineOperand &MO,
1514                                     unsigned OpSize) const {
1515   return MO.isImm() && !isInlineConstant(MO, OpSize);
1516 }
1517 
1518 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
1519                                         unsigned OpSize) const {
1520   switch (MO.getType()) {
1521   case MachineOperand::MO_Register:
1522     return false;
1523   case MachineOperand::MO_Immediate:
1524     return !isInlineConstant(MO, OpSize);
1525   case MachineOperand::MO_FrameIndex:
1526   case MachineOperand::MO_MachineBasicBlock:
1527   case MachineOperand::MO_ExternalSymbol:
1528   case MachineOperand::MO_GlobalAddress:
1529   case MachineOperand::MO_MCSymbol:
1530     return true;
1531   default:
1532     llvm_unreachable("unexpected operand type");
1533   }
1534 }
1535 
1536 static bool compareMachineOp(const MachineOperand &Op0,
1537                              const MachineOperand &Op1) {
1538   if (Op0.getType() != Op1.getType())
1539     return false;
1540 
1541   switch (Op0.getType()) {
1542   case MachineOperand::MO_Register:
1543     return Op0.getReg() == Op1.getReg();
1544   case MachineOperand::MO_Immediate:
1545     return Op0.getImm() == Op1.getImm();
1546   default:
1547     llvm_unreachable("Didn't expect to be comparing these operand types");
1548   }
1549 }
1550 
1551 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
1552                                     const MachineOperand &MO) const {
1553   const MCOperandInfo &OpInfo = get(MI.getOpcode()).OpInfo[OpNo];
1554 
1555   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
1556 
1557   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
1558     return true;
1559 
1560   if (OpInfo.RegClass < 0)
1561     return false;
1562 
1563   unsigned OpSize = RI.getRegClass(OpInfo.RegClass)->getSize();
1564   if (isLiteralConstant(MO, OpSize))
1565     return RI.opCanUseLiteralConstant(OpInfo.OperandType);
1566 
1567   return RI.opCanUseInlineConstant(OpInfo.OperandType);
1568 }
1569 
1570 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
1571   int Op32 = AMDGPU::getVOPe32(Opcode);
1572   if (Op32 == -1)
1573     return false;
1574 
1575   return pseudoToMCOpcode(Op32) != -1;
1576 }
1577 
1578 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1579   // The src0_modifier operand is present on all instructions
1580   // that have modifiers.
1581 
1582   return AMDGPU::getNamedOperandIdx(Opcode,
1583                                     AMDGPU::OpName::src0_modifiers) != -1;
1584 }
1585 
1586 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1587                                   unsigned OpName) const {
1588   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1589   return Mods && Mods->getImm();
1590 }
1591 
1592 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1593                                   const MachineOperand &MO,
1594                                   unsigned OpSize) const {
1595   // Literal constants use the constant bus.
1596   if (isLiteralConstant(MO, OpSize))
1597     return true;
1598 
1599   if (!MO.isReg() || !MO.isUse())
1600     return false;
1601 
1602   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1603     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
1604 
1605   // FLAT_SCR is just an SGPR pair.
1606   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
1607     return true;
1608 
1609   // EXEC register uses the constant bus.
1610   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
1611     return true;
1612 
1613   // SGPRs use the constant bus
1614   return (MO.getReg() == AMDGPU::VCC || MO.getReg() == AMDGPU::M0 ||
1615           (!MO.isImplicit() &&
1616            (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
1617             AMDGPU::SGPR_64RegClass.contains(MO.getReg()))));
1618 }
1619 
1620 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
1621   for (const MachineOperand &MO : MI.implicit_operands()) {
1622     // We only care about reads.
1623     if (MO.isDef())
1624       continue;
1625 
1626     switch (MO.getReg()) {
1627     case AMDGPU::VCC:
1628     case AMDGPU::M0:
1629     case AMDGPU::FLAT_SCR:
1630       return MO.getReg();
1631 
1632     default:
1633       break;
1634     }
1635   }
1636 
1637   return AMDGPU::NoRegister;
1638 }
1639 
1640 static bool shouldReadExec(const MachineInstr &MI) {
1641   if (SIInstrInfo::isVALU(MI)) {
1642     switch (MI.getOpcode()) {
1643     case AMDGPU::V_READLANE_B32:
1644     case AMDGPU::V_READLANE_B32_si:
1645     case AMDGPU::V_READLANE_B32_vi:
1646     case AMDGPU::V_WRITELANE_B32:
1647     case AMDGPU::V_WRITELANE_B32_si:
1648     case AMDGPU::V_WRITELANE_B32_vi:
1649       return false;
1650     }
1651 
1652     return true;
1653   }
1654 
1655   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
1656       SIInstrInfo::isSALU(MI) ||
1657       SIInstrInfo::isSMRD(MI))
1658     return false;
1659 
1660   return true;
1661 }
1662 
1663 static bool isSubRegOf(const SIRegisterInfo &TRI,
1664                        const MachineOperand &SuperVec,
1665                        const MachineOperand &SubReg) {
1666   if (TargetRegisterInfo::isPhysicalRegister(SubReg.getReg()))
1667     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
1668 
1669   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
1670          SubReg.getReg() == SuperVec.getReg();
1671 }
1672 
1673 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
1674                                     StringRef &ErrInfo) const {
1675   uint16_t Opcode = MI.getOpcode();
1676   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1677   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
1678   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
1679   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
1680 
1681   // Make sure the number of operands is correct.
1682   const MCInstrDesc &Desc = get(Opcode);
1683   if (!Desc.isVariadic() &&
1684       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
1685     ErrInfo = "Instruction has wrong number of operands.";
1686     return false;
1687   }
1688 
1689   // Make sure the register classes are correct.
1690   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
1691     if (MI.getOperand(i).isFPImm()) {
1692       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
1693                 "all fp values to integers.";
1694       return false;
1695     }
1696 
1697     int RegClass = Desc.OpInfo[i].RegClass;
1698 
1699     switch (Desc.OpInfo[i].OperandType) {
1700     case MCOI::OPERAND_REGISTER:
1701       if (MI.getOperand(i).isImm()) {
1702         ErrInfo = "Illegal immediate value for operand.";
1703         return false;
1704       }
1705       break;
1706     case AMDGPU::OPERAND_REG_IMM32:
1707       break;
1708     case AMDGPU::OPERAND_REG_INLINE_C:
1709       if (isLiteralConstant(MI.getOperand(i),
1710                             RI.getRegClass(RegClass)->getSize())) {
1711         ErrInfo = "Illegal immediate value for operand.";
1712         return false;
1713       }
1714       break;
1715     case MCOI::OPERAND_IMMEDIATE:
1716     case AMDGPU::OPERAND_KIMM32:
1717       // Check if this operand is an immediate.
1718       // FrameIndex operands will be replaced by immediates, so they are
1719       // allowed.
1720       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
1721         ErrInfo = "Expected immediate, but got non-immediate";
1722         return false;
1723       }
1724       LLVM_FALLTHROUGH;
1725     default:
1726       continue;
1727     }
1728 
1729     if (!MI.getOperand(i).isReg())
1730       continue;
1731 
1732     if (RegClass != -1) {
1733       unsigned Reg = MI.getOperand(i).getReg();
1734       if (Reg == AMDGPU::NoRegister ||
1735           TargetRegisterInfo::isVirtualRegister(Reg))
1736         continue;
1737 
1738       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
1739       if (!RC->contains(Reg)) {
1740         ErrInfo = "Operand has incorrect register class.";
1741         return false;
1742       }
1743     }
1744   }
1745 
1746   // Verify VOP*
1747   if (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI)) {
1748     // Only look at the true operands. Only a real operand can use the constant
1749     // bus, and we don't want to check pseudo-operands like the source modifier
1750     // flags.
1751     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
1752 
1753     unsigned ConstantBusCount = 0;
1754 
1755     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
1756       ++ConstantBusCount;
1757 
1758     unsigned SGPRUsed = findImplicitSGPRRead(MI);
1759     if (SGPRUsed != AMDGPU::NoRegister)
1760       ++ConstantBusCount;
1761 
1762     for (int OpIdx : OpIndices) {
1763       if (OpIdx == -1)
1764         break;
1765       const MachineOperand &MO = MI.getOperand(OpIdx);
1766       if (usesConstantBus(MRI, MO, getOpSize(Opcode, OpIdx))) {
1767         if (MO.isReg()) {
1768           if (MO.getReg() != SGPRUsed)
1769             ++ConstantBusCount;
1770           SGPRUsed = MO.getReg();
1771         } else {
1772           ++ConstantBusCount;
1773         }
1774       }
1775     }
1776     if (ConstantBusCount > 1) {
1777       ErrInfo = "VOP* instruction uses the constant bus more than once";
1778       return false;
1779     }
1780   }
1781 
1782   // Verify misc. restrictions on specific instructions.
1783   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
1784       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
1785     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
1786     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
1787     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
1788     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
1789       if (!compareMachineOp(Src0, Src1) &&
1790           !compareMachineOp(Src0, Src2)) {
1791         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
1792         return false;
1793       }
1794     }
1795   }
1796 
1797   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
1798       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
1799       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
1800       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
1801     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
1802                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
1803 
1804     const unsigned StaticNumOps = Desc.getNumOperands() +
1805       Desc.getNumImplicitUses();
1806     const unsigned NumImplicitOps = IsDst ? 2 : 1;
1807 
1808     if (MI.getNumOperands() != StaticNumOps + NumImplicitOps) {
1809       ErrInfo = "missing implicit register operands";
1810       return false;
1811     }
1812 
1813     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
1814     if (IsDst) {
1815       if (!Dst->isUse()) {
1816         ErrInfo = "v_movreld_b32 vdst should be a use operand";
1817         return false;
1818       }
1819 
1820       unsigned UseOpIdx;
1821       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
1822           UseOpIdx != StaticNumOps + 1) {
1823         ErrInfo = "movrel implicit operands should be tied";
1824         return false;
1825       }
1826     }
1827 
1828     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
1829     const MachineOperand &ImpUse
1830       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
1831     if (!ImpUse.isReg() || !ImpUse.isUse() ||
1832         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
1833       ErrInfo = "src0 should be subreg of implicit vector use";
1834       return false;
1835     }
1836   }
1837 
1838   // Make sure we aren't losing exec uses in the td files. This mostly requires
1839   // being careful when using let Uses to try to add other use registers.
1840   if (shouldReadExec(MI)) {
1841     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
1842       ErrInfo = "VALU instruction does not implicitly read exec mask";
1843       return false;
1844     }
1845   }
1846 
1847   return true;
1848 }
1849 
1850 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
1851   switch (MI.getOpcode()) {
1852   default: return AMDGPU::INSTRUCTION_LIST_END;
1853   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
1854   case AMDGPU::COPY: return AMDGPU::COPY;
1855   case AMDGPU::PHI: return AMDGPU::PHI;
1856   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
1857   case AMDGPU::S_MOV_B32:
1858     return MI.getOperand(1).isReg() ?
1859            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
1860   case AMDGPU::S_ADD_I32:
1861   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
1862   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
1863   case AMDGPU::S_SUB_I32:
1864   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
1865   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
1866   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
1867   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e32;
1868   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e32;
1869   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e32;
1870   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e32;
1871   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e32;
1872   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e32;
1873   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e32;
1874   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
1875   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
1876   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
1877   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
1878   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
1879   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
1880   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
1881   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
1882   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
1883   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
1884   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
1885   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
1886   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
1887   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
1888   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
1889   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
1890   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
1891   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
1892   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
1893   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
1894   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
1895   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
1896   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
1897   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
1898   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
1899   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
1900   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
1901   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
1902   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
1903   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
1904   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
1905   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
1906   }
1907 }
1908 
1909 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
1910   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
1911 }
1912 
1913 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
1914                                                       unsigned OpNo) const {
1915   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1916   const MCInstrDesc &Desc = get(MI.getOpcode());
1917   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
1918       Desc.OpInfo[OpNo].RegClass == -1) {
1919     unsigned Reg = MI.getOperand(OpNo).getReg();
1920 
1921     if (TargetRegisterInfo::isVirtualRegister(Reg))
1922       return MRI.getRegClass(Reg);
1923     return RI.getPhysRegClass(Reg);
1924   }
1925 
1926   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
1927   return RI.getRegClass(RCID);
1928 }
1929 
1930 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
1931   switch (MI.getOpcode()) {
1932   case AMDGPU::COPY:
1933   case AMDGPU::REG_SEQUENCE:
1934   case AMDGPU::PHI:
1935   case AMDGPU::INSERT_SUBREG:
1936     return RI.hasVGPRs(getOpRegClass(MI, 0));
1937   default:
1938     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
1939   }
1940 }
1941 
1942 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
1943   MachineBasicBlock::iterator I = MI;
1944   MachineBasicBlock *MBB = MI.getParent();
1945   MachineOperand &MO = MI.getOperand(OpIdx);
1946   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1947   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
1948   const TargetRegisterClass *RC = RI.getRegClass(RCID);
1949   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1950   if (MO.isReg())
1951     Opcode = AMDGPU::COPY;
1952   else if (RI.isSGPRClass(RC))
1953     Opcode = AMDGPU::S_MOV_B32;
1954 
1955   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
1956   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
1957     VRC = &AMDGPU::VReg_64RegClass;
1958   else
1959     VRC = &AMDGPU::VGPR_32RegClass;
1960 
1961   unsigned Reg = MRI.createVirtualRegister(VRC);
1962   DebugLoc DL = MBB->findDebugLoc(I);
1963   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).addOperand(MO);
1964   MO.ChangeToRegister(Reg, false);
1965 }
1966 
1967 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
1968                                          MachineRegisterInfo &MRI,
1969                                          MachineOperand &SuperReg,
1970                                          const TargetRegisterClass *SuperRC,
1971                                          unsigned SubIdx,
1972                                          const TargetRegisterClass *SubRC)
1973                                          const {
1974   MachineBasicBlock *MBB = MI->getParent();
1975   DebugLoc DL = MI->getDebugLoc();
1976   unsigned SubReg = MRI.createVirtualRegister(SubRC);
1977 
1978   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
1979     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1980       .addReg(SuperReg.getReg(), 0, SubIdx);
1981     return SubReg;
1982   }
1983 
1984   // Just in case the super register is itself a sub-register, copy it to a new
1985   // value so we don't need to worry about merging its subreg index with the
1986   // SubIdx passed to this function. The register coalescer should be able to
1987   // eliminate this extra copy.
1988   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
1989 
1990   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
1991     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
1992 
1993   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1994     .addReg(NewSuperReg, 0, SubIdx);
1995 
1996   return SubReg;
1997 }
1998 
1999 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
2000   MachineBasicBlock::iterator MII,
2001   MachineRegisterInfo &MRI,
2002   MachineOperand &Op,
2003   const TargetRegisterClass *SuperRC,
2004   unsigned SubIdx,
2005   const TargetRegisterClass *SubRC) const {
2006   if (Op.isImm()) {
2007     // XXX - Is there a better way to do this?
2008     if (SubIdx == AMDGPU::sub0)
2009       return MachineOperand::CreateImm(Op.getImm() & 0xFFFFFFFF);
2010     if (SubIdx == AMDGPU::sub1)
2011       return MachineOperand::CreateImm(Op.getImm() >> 32);
2012 
2013     llvm_unreachable("Unhandled register index for immediate");
2014   }
2015 
2016   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
2017                                        SubIdx, SubRC);
2018   return MachineOperand::CreateReg(SubReg, false);
2019 }
2020 
2021 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
2022 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
2023   assert(Inst.getNumExplicitOperands() == 3);
2024   MachineOperand Op1 = Inst.getOperand(1);
2025   Inst.RemoveOperand(1);
2026   Inst.addOperand(Op1);
2027 }
2028 
2029 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
2030                                     const MCOperandInfo &OpInfo,
2031                                     const MachineOperand &MO) const {
2032   if (!MO.isReg())
2033     return false;
2034 
2035   unsigned Reg = MO.getReg();
2036   const TargetRegisterClass *RC =
2037     TargetRegisterInfo::isVirtualRegister(Reg) ?
2038     MRI.getRegClass(Reg) :
2039     RI.getPhysRegClass(Reg);
2040 
2041   const SIRegisterInfo *TRI =
2042       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
2043   RC = TRI->getSubRegClass(RC, MO.getSubReg());
2044 
2045   // In order to be legal, the common sub-class must be equal to the
2046   // class of the current operand.  For example:
2047   //
2048   // v_mov_b32 s0 ; Operand defined as vsrc_32
2049   //              ; RI.getCommonSubClass(s0,vsrc_32) = sgpr ; LEGAL
2050   //
2051   // s_sendmsg 0, s0 ; Operand defined as m0reg
2052   //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
2053 
2054   return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
2055 }
2056 
2057 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
2058                                      const MCOperandInfo &OpInfo,
2059                                      const MachineOperand &MO) const {
2060   if (MO.isReg())
2061     return isLegalRegOperand(MRI, OpInfo, MO);
2062 
2063   // Handle non-register types that are treated like immediates.
2064   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
2065   return true;
2066 }
2067 
2068 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
2069                                  const MachineOperand *MO) const {
2070   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2071   const MCInstrDesc &InstDesc = MI.getDesc();
2072   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
2073   const TargetRegisterClass *DefinedRC =
2074       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
2075   if (!MO)
2076     MO = &MI.getOperand(OpIdx);
2077 
2078   if (isVALU(MI) && usesConstantBus(MRI, *MO, DefinedRC->getSize())) {
2079 
2080     RegSubRegPair SGPRUsed;
2081     if (MO->isReg())
2082       SGPRUsed = RegSubRegPair(MO->getReg(), MO->getSubReg());
2083 
2084     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2085       if (i == OpIdx)
2086         continue;
2087       const MachineOperand &Op = MI.getOperand(i);
2088       if (Op.isReg()) {
2089         if ((Op.getReg() != SGPRUsed.Reg || Op.getSubReg() != SGPRUsed.SubReg) &&
2090             usesConstantBus(MRI, Op, getOpSize(MI, i))) {
2091           return false;
2092         }
2093       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
2094         return false;
2095       }
2096     }
2097   }
2098 
2099   if (MO->isReg()) {
2100     assert(DefinedRC);
2101     return isLegalRegOperand(MRI, OpInfo, *MO);
2102   }
2103 
2104   // Handle non-register types that are treated like immediates.
2105   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
2106 
2107   if (!DefinedRC) {
2108     // This operand expects an immediate.
2109     return true;
2110   }
2111 
2112   return isImmOperandLegal(MI, OpIdx, *MO);
2113 }
2114 
2115 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
2116                                        MachineInstr &MI) const {
2117   unsigned Opc = MI.getOpcode();
2118   const MCInstrDesc &InstrDesc = get(Opc);
2119 
2120   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2121   MachineOperand &Src1 = MI.getOperand(Src1Idx);
2122 
2123   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
2124   // we need to only have one constant bus use.
2125   //
2126   // Note we do not need to worry about literal constants here. They are
2127   // disabled for the operand type for instructions because they will always
2128   // violate the one constant bus use rule.
2129   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
2130   if (HasImplicitSGPR) {
2131     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2132     MachineOperand &Src0 = MI.getOperand(Src0Idx);
2133 
2134     if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg()))
2135       legalizeOpWithMove(MI, Src0Idx);
2136   }
2137 
2138   // VOP2 src0 instructions support all operand types, so we don't need to check
2139   // their legality. If src1 is already legal, we don't need to do anything.
2140   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
2141     return;
2142 
2143   // We do not use commuteInstruction here because it is too aggressive and will
2144   // commute if it is possible. We only want to commute here if it improves
2145   // legality. This can be called a fairly large number of times so don't waste
2146   // compile time pointlessly swapping and checking legality again.
2147   if (HasImplicitSGPR || !MI.isCommutable()) {
2148     legalizeOpWithMove(MI, Src1Idx);
2149     return;
2150   }
2151 
2152   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2153   MachineOperand &Src0 = MI.getOperand(Src0Idx);
2154 
2155   // If src0 can be used as src1, commuting will make the operands legal.
2156   // Otherwise we have to give up and insert a move.
2157   //
2158   // TODO: Other immediate-like operand kinds could be commuted if there was a
2159   // MachineOperand::ChangeTo* for them.
2160   if ((!Src1.isImm() && !Src1.isReg()) ||
2161       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
2162     legalizeOpWithMove(MI, Src1Idx);
2163     return;
2164   }
2165 
2166   int CommutedOpc = commuteOpcode(MI);
2167   if (CommutedOpc == -1) {
2168     legalizeOpWithMove(MI, Src1Idx);
2169     return;
2170   }
2171 
2172   MI.setDesc(get(CommutedOpc));
2173 
2174   unsigned Src0Reg = Src0.getReg();
2175   unsigned Src0SubReg = Src0.getSubReg();
2176   bool Src0Kill = Src0.isKill();
2177 
2178   if (Src1.isImm())
2179     Src0.ChangeToImmediate(Src1.getImm());
2180   else if (Src1.isReg()) {
2181     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
2182     Src0.setSubReg(Src1.getSubReg());
2183   } else
2184     llvm_unreachable("Should only have register or immediate operands");
2185 
2186   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
2187   Src1.setSubReg(Src0SubReg);
2188 }
2189 
2190 // Legalize VOP3 operands. Because all operand types are supported for any
2191 // operand, and since literal constants are not allowed and should never be
2192 // seen, we only need to worry about inserting copies if we use multiple SGPR
2193 // operands.
2194 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
2195                                        MachineInstr &MI) const {
2196   unsigned Opc = MI.getOpcode();
2197 
2198   int VOP3Idx[3] = {
2199     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
2200     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
2201     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
2202   };
2203 
2204   // Find the one SGPR operand we are allowed to use.
2205   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
2206 
2207   for (unsigned i = 0; i < 3; ++i) {
2208     int Idx = VOP3Idx[i];
2209     if (Idx == -1)
2210       break;
2211     MachineOperand &MO = MI.getOperand(Idx);
2212 
2213     // We should never see a VOP3 instruction with an illegal immediate operand.
2214     if (!MO.isReg())
2215       continue;
2216 
2217     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2218       continue; // VGPRs are legal
2219 
2220     if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
2221       SGPRReg = MO.getReg();
2222       // We can use one SGPR in each VOP3 instruction.
2223       continue;
2224     }
2225 
2226     // If we make it this far, then the operand is not legal and we must
2227     // legalize it.
2228     legalizeOpWithMove(MI, Idx);
2229   }
2230 }
2231 
2232 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
2233                                          MachineRegisterInfo &MRI) const {
2234   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
2235   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
2236   unsigned DstReg = MRI.createVirtualRegister(SRC);
2237   unsigned SubRegs = VRC->getSize() / 4;
2238 
2239   SmallVector<unsigned, 8> SRegs;
2240   for (unsigned i = 0; i < SubRegs; ++i) {
2241     unsigned SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2242     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2243             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
2244         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
2245     SRegs.push_back(SGPR);
2246   }
2247 
2248   MachineInstrBuilder MIB =
2249       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2250               get(AMDGPU::REG_SEQUENCE), DstReg);
2251   for (unsigned i = 0; i < SubRegs; ++i) {
2252     MIB.addReg(SRegs[i]);
2253     MIB.addImm(RI.getSubRegFromChannel(i));
2254   }
2255   return DstReg;
2256 }
2257 
2258 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
2259                                        MachineInstr &MI) const {
2260 
2261   // If the pointer is store in VGPRs, then we need to move them to
2262   // SGPRs using v_readfirstlane.  This is safe because we only select
2263   // loads with uniform pointers to SMRD instruction so we know the
2264   // pointer value is uniform.
2265   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
2266   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
2267       unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
2268       SBase->setReg(SGPR);
2269   }
2270 }
2271 
2272 void SIInstrInfo::legalizeOperands(MachineInstr &MI) const {
2273   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2274 
2275   // Legalize VOP2
2276   if (isVOP2(MI) || isVOPC(MI)) {
2277     legalizeOperandsVOP2(MRI, MI);
2278     return;
2279   }
2280 
2281   // Legalize VOP3
2282   if (isVOP3(MI)) {
2283     legalizeOperandsVOP3(MRI, MI);
2284     return;
2285   }
2286 
2287   // Legalize SMRD
2288   if (isSMRD(MI)) {
2289     legalizeOperandsSMRD(MRI, MI);
2290     return;
2291   }
2292 
2293   // Legalize REG_SEQUENCE and PHI
2294   // The register class of the operands much be the same type as the register
2295   // class of the output.
2296   if (MI.getOpcode() == AMDGPU::PHI) {
2297     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
2298     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
2299       if (!MI.getOperand(i).isReg() ||
2300           !TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
2301         continue;
2302       const TargetRegisterClass *OpRC =
2303           MRI.getRegClass(MI.getOperand(i).getReg());
2304       if (RI.hasVGPRs(OpRC)) {
2305         VRC = OpRC;
2306       } else {
2307         SRC = OpRC;
2308       }
2309     }
2310 
2311     // If any of the operands are VGPR registers, then they all most be
2312     // otherwise we will create illegal VGPR->SGPR copies when legalizing
2313     // them.
2314     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
2315       if (!VRC) {
2316         assert(SRC);
2317         VRC = RI.getEquivalentVGPRClass(SRC);
2318       }
2319       RC = VRC;
2320     } else {
2321       RC = SRC;
2322     }
2323 
2324     // Update all the operands so they have the same type.
2325     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2326       MachineOperand &Op = MI.getOperand(I);
2327       if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2328         continue;
2329       unsigned DstReg = MRI.createVirtualRegister(RC);
2330 
2331       // MI is a PHI instruction.
2332       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
2333       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
2334 
2335       BuildMI(*InsertBB, Insert, MI.getDebugLoc(), get(AMDGPU::COPY), DstReg)
2336           .addOperand(Op);
2337       Op.setReg(DstReg);
2338     }
2339   }
2340 
2341   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
2342   // VGPR dest type and SGPR sources, insert copies so all operands are
2343   // VGPRs. This seems to help operand folding / the register coalescer.
2344   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
2345     MachineBasicBlock *MBB = MI.getParent();
2346     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
2347     if (RI.hasVGPRs(DstRC)) {
2348       // Update all the operands so they are VGPR register classes. These may
2349       // not be the same register class because REG_SEQUENCE supports mixing
2350       // subregister index types e.g. sub0_sub1 + sub2 + sub3
2351       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2352         MachineOperand &Op = MI.getOperand(I);
2353         if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2354           continue;
2355 
2356         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
2357         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
2358         if (VRC == OpRC)
2359           continue;
2360 
2361         unsigned DstReg = MRI.createVirtualRegister(VRC);
2362 
2363         BuildMI(*MBB, MI, MI.getDebugLoc(), get(AMDGPU::COPY), DstReg)
2364             .addOperand(Op);
2365 
2366         Op.setReg(DstReg);
2367         Op.setIsKill();
2368       }
2369     }
2370 
2371     return;
2372   }
2373 
2374   // Legalize INSERT_SUBREG
2375   // src0 must have the same register class as dst
2376   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
2377     unsigned Dst = MI.getOperand(0).getReg();
2378     unsigned Src0 = MI.getOperand(1).getReg();
2379     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
2380     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
2381     if (DstRC != Src0RC) {
2382       MachineBasicBlock &MBB = *MI.getParent();
2383       unsigned NewSrc0 = MRI.createVirtualRegister(DstRC);
2384       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::COPY), NewSrc0)
2385           .addReg(Src0);
2386       MI.getOperand(1).setReg(NewSrc0);
2387     }
2388     return;
2389   }
2390 
2391   // Legalize MIMG
2392   if (isMIMG(MI)) {
2393     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
2394     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
2395       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
2396       SRsrc->setReg(SGPR);
2397     }
2398 
2399     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
2400     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
2401       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
2402       SSamp->setReg(SGPR);
2403     }
2404     return;
2405   }
2406 
2407   // Legalize MUBUF* instructions
2408   // FIXME: If we start using the non-addr64 instructions for compute, we
2409   // may need to legalize them here.
2410   int SRsrcIdx =
2411       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
2412   if (SRsrcIdx != -1) {
2413     // We have an MUBUF instruction
2414     MachineOperand *SRsrc = &MI.getOperand(SRsrcIdx);
2415     unsigned SRsrcRC = get(MI.getOpcode()).OpInfo[SRsrcIdx].RegClass;
2416     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
2417                                              RI.getRegClass(SRsrcRC))) {
2418       // The operands are legal.
2419       // FIXME: We may need to legalize operands besided srsrc.
2420       return;
2421     }
2422 
2423     MachineBasicBlock &MBB = *MI.getParent();
2424 
2425     // Extract the ptr from the resource descriptor.
2426     unsigned SRsrcPtr = buildExtractSubReg(MI, MRI, *SRsrc,
2427       &AMDGPU::VReg_128RegClass, AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
2428 
2429     // Create an empty resource descriptor
2430     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2431     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2432     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2433     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
2434     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
2435 
2436     // Zero64 = 0
2437     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B64), Zero64)
2438         .addImm(0);
2439 
2440     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
2441     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
2442         .addImm(RsrcDataFormat & 0xFFFFFFFF);
2443 
2444     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
2445     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
2446         .addImm(RsrcDataFormat >> 32);
2447 
2448     // NewSRsrc = {Zero64, SRsrcFormat}
2449     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewSRsrc)
2450         .addReg(Zero64)
2451         .addImm(AMDGPU::sub0_sub1)
2452         .addReg(SRsrcFormatLo)
2453         .addImm(AMDGPU::sub2)
2454         .addReg(SRsrcFormatHi)
2455         .addImm(AMDGPU::sub3);
2456 
2457     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
2458     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2459     if (VAddr) {
2460       // This is already an ADDR64 instruction so we need to add the pointer
2461       // extracted from the resource descriptor to the current value of VAddr.
2462       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2463       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2464 
2465       // NewVaddrLo = SRsrcPtr:sub0 + VAddr:sub0
2466       DebugLoc DL = MI.getDebugLoc();
2467       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), NewVAddrLo)
2468         .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2469         .addReg(VAddr->getReg(), 0, AMDGPU::sub0);
2470 
2471       // NewVaddrHi = SRsrcPtr:sub1 + VAddr:sub1
2472       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e32), NewVAddrHi)
2473         .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2474         .addReg(VAddr->getReg(), 0, AMDGPU::sub1);
2475 
2476       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2477       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
2478           .addReg(NewVAddrLo)
2479           .addImm(AMDGPU::sub0)
2480           .addReg(NewVAddrHi)
2481           .addImm(AMDGPU::sub1);
2482     } else {
2483       // This instructions is the _OFFSET variant, so we need to convert it to
2484       // ADDR64.
2485       assert(MBB.getParent()->getSubtarget<SISubtarget>().getGeneration()
2486              < SISubtarget::VOLCANIC_ISLANDS &&
2487              "FIXME: Need to emit flat atomics here");
2488 
2489       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
2490       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
2491       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
2492       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
2493 
2494       // Atomics rith return have have an additional tied operand and are
2495       // missing some of the special bits.
2496       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
2497       MachineInstr *Addr64;
2498 
2499       if (!VDataIn) {
2500         // Regular buffer load / store.
2501         MachineInstrBuilder MIB =
2502             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
2503                 .addOperand(*VData)
2504                 .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
2505                 // This will be replaced later
2506                 // with the new value of vaddr.
2507                 .addOperand(*SRsrc)
2508                 .addOperand(*SOffset)
2509                 .addOperand(*Offset);
2510 
2511         // Atomics do not have this operand.
2512         if (const MachineOperand *GLC =
2513                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
2514           MIB.addImm(GLC->getImm());
2515         }
2516 
2517         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
2518 
2519         if (const MachineOperand *TFE =
2520                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
2521           MIB.addImm(TFE->getImm());
2522         }
2523 
2524         MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
2525         Addr64 = MIB;
2526       } else {
2527         // Atomics with return.
2528         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
2529                      .addOperand(*VData)
2530                      .addOperand(*VDataIn)
2531                      .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
2532                      // This will be replaced later
2533                      // with the new value of vaddr.
2534                      .addOperand(*SRsrc)
2535                      .addOperand(*SOffset)
2536                      .addOperand(*Offset)
2537                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
2538                      .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
2539       }
2540 
2541       MI.removeFromParent();
2542 
2543       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2544       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
2545               NewVAddr)
2546           .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2547           .addImm(AMDGPU::sub0)
2548           .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2549           .addImm(AMDGPU::sub1);
2550 
2551       VAddr = getNamedOperand(*Addr64, AMDGPU::OpName::vaddr);
2552       SRsrc = getNamedOperand(*Addr64, AMDGPU::OpName::srsrc);
2553     }
2554 
2555     // Update the instruction to use NewVaddr
2556     VAddr->setReg(NewVAddr);
2557     // Update the instruction to use NewSRsrc
2558     SRsrc->setReg(NewSRsrc);
2559   }
2560 }
2561 
2562 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
2563   SmallVector<MachineInstr *, 128> Worklist;
2564   Worklist.push_back(&TopInst);
2565 
2566   while (!Worklist.empty()) {
2567     MachineInstr &Inst = *Worklist.pop_back_val();
2568     MachineBasicBlock *MBB = Inst.getParent();
2569     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
2570 
2571     unsigned Opcode = Inst.getOpcode();
2572     unsigned NewOpcode = getVALUOp(Inst);
2573 
2574     // Handle some special cases
2575     switch (Opcode) {
2576     default:
2577       break;
2578     case AMDGPU::S_AND_B64:
2579       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_AND_B32_e64);
2580       Inst.eraseFromParent();
2581       continue;
2582 
2583     case AMDGPU::S_OR_B64:
2584       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_OR_B32_e64);
2585       Inst.eraseFromParent();
2586       continue;
2587 
2588     case AMDGPU::S_XOR_B64:
2589       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_XOR_B32_e64);
2590       Inst.eraseFromParent();
2591       continue;
2592 
2593     case AMDGPU::S_NOT_B64:
2594       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::V_NOT_B32_e32);
2595       Inst.eraseFromParent();
2596       continue;
2597 
2598     case AMDGPU::S_BCNT1_I32_B64:
2599       splitScalar64BitBCNT(Worklist, Inst);
2600       Inst.eraseFromParent();
2601       continue;
2602 
2603     case AMDGPU::S_BFE_I64: {
2604       splitScalar64BitBFE(Worklist, Inst);
2605       Inst.eraseFromParent();
2606       continue;
2607     }
2608 
2609     case AMDGPU::S_LSHL_B32:
2610       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2611         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
2612         swapOperands(Inst);
2613       }
2614       break;
2615     case AMDGPU::S_ASHR_I32:
2616       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2617         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
2618         swapOperands(Inst);
2619       }
2620       break;
2621     case AMDGPU::S_LSHR_B32:
2622       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2623         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
2624         swapOperands(Inst);
2625       }
2626       break;
2627     case AMDGPU::S_LSHL_B64:
2628       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2629         NewOpcode = AMDGPU::V_LSHLREV_B64;
2630         swapOperands(Inst);
2631       }
2632       break;
2633     case AMDGPU::S_ASHR_I64:
2634       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2635         NewOpcode = AMDGPU::V_ASHRREV_I64;
2636         swapOperands(Inst);
2637       }
2638       break;
2639     case AMDGPU::S_LSHR_B64:
2640       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2641         NewOpcode = AMDGPU::V_LSHRREV_B64;
2642         swapOperands(Inst);
2643       }
2644       break;
2645 
2646     case AMDGPU::S_ABS_I32:
2647       lowerScalarAbs(Worklist, Inst);
2648       Inst.eraseFromParent();
2649       continue;
2650 
2651     case AMDGPU::S_CBRANCH_SCC0:
2652     case AMDGPU::S_CBRANCH_SCC1:
2653       // Clear unused bits of vcc
2654       BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
2655               AMDGPU::VCC)
2656           .addReg(AMDGPU::EXEC)
2657           .addReg(AMDGPU::VCC);
2658       break;
2659 
2660     case AMDGPU::S_BFE_U64:
2661     case AMDGPU::S_BFM_B64:
2662       llvm_unreachable("Moving this op to VALU not implemented");
2663     }
2664 
2665     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
2666       // We cannot move this instruction to the VALU, so we should try to
2667       // legalize its operands instead.
2668       legalizeOperands(Inst);
2669       continue;
2670     }
2671 
2672     // Use the new VALU Opcode.
2673     const MCInstrDesc &NewDesc = get(NewOpcode);
2674     Inst.setDesc(NewDesc);
2675 
2676     // Remove any references to SCC. Vector instructions can't read from it, and
2677     // We're just about to add the implicit use / defs of VCC, and we don't want
2678     // both.
2679     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
2680       MachineOperand &Op = Inst.getOperand(i);
2681       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
2682         Inst.RemoveOperand(i);
2683         addSCCDefUsersToVALUWorklist(Inst, Worklist);
2684       }
2685     }
2686 
2687     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
2688       // We are converting these to a BFE, so we need to add the missing
2689       // operands for the size and offset.
2690       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
2691       Inst.addOperand(MachineOperand::CreateImm(0));
2692       Inst.addOperand(MachineOperand::CreateImm(Size));
2693 
2694     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
2695       // The VALU version adds the second operand to the result, so insert an
2696       // extra 0 operand.
2697       Inst.addOperand(MachineOperand::CreateImm(0));
2698     }
2699 
2700     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
2701 
2702     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
2703       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
2704       // If we need to move this to VGPRs, we need to unpack the second operand
2705       // back into the 2 separate ones for bit offset and width.
2706       assert(OffsetWidthOp.isImm() &&
2707              "Scalar BFE is only implemented for constant width and offset");
2708       uint32_t Imm = OffsetWidthOp.getImm();
2709 
2710       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2711       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2712       Inst.RemoveOperand(2);                     // Remove old immediate.
2713       Inst.addOperand(MachineOperand::CreateImm(Offset));
2714       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
2715     }
2716 
2717     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
2718     unsigned NewDstReg = AMDGPU::NoRegister;
2719     if (HasDst) {
2720       // Update the destination register class.
2721       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
2722       if (!NewDstRC)
2723         continue;
2724 
2725       unsigned DstReg = Inst.getOperand(0).getReg();
2726       NewDstReg = MRI.createVirtualRegister(NewDstRC);
2727       MRI.replaceRegWith(DstReg, NewDstReg);
2728     }
2729 
2730     // Legalize the operands
2731     legalizeOperands(Inst);
2732 
2733     if (HasDst)
2734      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
2735   }
2736 }
2737 
2738 void SIInstrInfo::lowerScalarAbs(SmallVectorImpl<MachineInstr *> &Worklist,
2739                                  MachineInstr &Inst) const {
2740   MachineBasicBlock &MBB = *Inst.getParent();
2741   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2742   MachineBasicBlock::iterator MII = Inst;
2743   DebugLoc DL = Inst.getDebugLoc();
2744 
2745   MachineOperand &Dest = Inst.getOperand(0);
2746   MachineOperand &Src = Inst.getOperand(1);
2747   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2748   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2749 
2750   BuildMI(MBB, MII, DL, get(AMDGPU::V_SUB_I32_e32), TmpReg)
2751     .addImm(0)
2752     .addReg(Src.getReg());
2753 
2754   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
2755     .addReg(Src.getReg())
2756     .addReg(TmpReg);
2757 
2758   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2759   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2760 }
2761 
2762 void SIInstrInfo::splitScalar64BitUnaryOp(
2763     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
2764     unsigned Opcode) const {
2765   MachineBasicBlock &MBB = *Inst.getParent();
2766   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2767 
2768   MachineOperand &Dest = Inst.getOperand(0);
2769   MachineOperand &Src0 = Inst.getOperand(1);
2770   DebugLoc DL = Inst.getDebugLoc();
2771 
2772   MachineBasicBlock::iterator MII = Inst;
2773 
2774   const MCInstrDesc &InstDesc = get(Opcode);
2775   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2776     MRI.getRegClass(Src0.getReg()) :
2777     &AMDGPU::SGPR_32RegClass;
2778 
2779   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2780 
2781   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2782                                                        AMDGPU::sub0, Src0SubRC);
2783 
2784   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2785   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
2786   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
2787 
2788   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
2789   BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2790     .addOperand(SrcReg0Sub0);
2791 
2792   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2793                                                        AMDGPU::sub1, Src0SubRC);
2794 
2795   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
2796   BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2797     .addOperand(SrcReg0Sub1);
2798 
2799   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
2800   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2801     .addReg(DestSub0)
2802     .addImm(AMDGPU::sub0)
2803     .addReg(DestSub1)
2804     .addImm(AMDGPU::sub1);
2805 
2806   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2807 
2808   // We don't need to legalizeOperands here because for a single operand, src0
2809   // will support any kind of input.
2810 
2811   // Move all users of this moved value.
2812   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
2813 }
2814 
2815 void SIInstrInfo::splitScalar64BitBinaryOp(
2816     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
2817     unsigned Opcode) const {
2818   MachineBasicBlock &MBB = *Inst.getParent();
2819   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2820 
2821   MachineOperand &Dest = Inst.getOperand(0);
2822   MachineOperand &Src0 = Inst.getOperand(1);
2823   MachineOperand &Src1 = Inst.getOperand(2);
2824   DebugLoc DL = Inst.getDebugLoc();
2825 
2826   MachineBasicBlock::iterator MII = Inst;
2827 
2828   const MCInstrDesc &InstDesc = get(Opcode);
2829   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2830     MRI.getRegClass(Src0.getReg()) :
2831     &AMDGPU::SGPR_32RegClass;
2832 
2833   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2834   const TargetRegisterClass *Src1RC = Src1.isReg() ?
2835     MRI.getRegClass(Src1.getReg()) :
2836     &AMDGPU::SGPR_32RegClass;
2837 
2838   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
2839 
2840   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2841                                                        AMDGPU::sub0, Src0SubRC);
2842   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2843                                                        AMDGPU::sub0, Src1SubRC);
2844 
2845   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2846   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
2847   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
2848 
2849   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
2850   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2851                               .addOperand(SrcReg0Sub0)
2852                               .addOperand(SrcReg1Sub0);
2853 
2854   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2855                                                        AMDGPU::sub1, Src0SubRC);
2856   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2857                                                        AMDGPU::sub1, Src1SubRC);
2858 
2859   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
2860   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2861                               .addOperand(SrcReg0Sub1)
2862                               .addOperand(SrcReg1Sub1);
2863 
2864   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
2865   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2866     .addReg(DestSub0)
2867     .addImm(AMDGPU::sub0)
2868     .addReg(DestSub1)
2869     .addImm(AMDGPU::sub1);
2870 
2871   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2872 
2873   // Try to legalize the operands in case we need to swap the order to keep it
2874   // valid.
2875   legalizeOperands(LoHalf);
2876   legalizeOperands(HiHalf);
2877 
2878   // Move all users of this moved vlaue.
2879   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
2880 }
2881 
2882 void SIInstrInfo::splitScalar64BitBCNT(
2883     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst) const {
2884   MachineBasicBlock &MBB = *Inst.getParent();
2885   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2886 
2887   MachineBasicBlock::iterator MII = Inst;
2888   DebugLoc DL = Inst.getDebugLoc();
2889 
2890   MachineOperand &Dest = Inst.getOperand(0);
2891   MachineOperand &Src = Inst.getOperand(1);
2892 
2893   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
2894   const TargetRegisterClass *SrcRC = Src.isReg() ?
2895     MRI.getRegClass(Src.getReg()) :
2896     &AMDGPU::SGPR_32RegClass;
2897 
2898   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2899   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2900 
2901   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
2902 
2903   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2904                                                       AMDGPU::sub0, SrcSubRC);
2905   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2906                                                       AMDGPU::sub1, SrcSubRC);
2907 
2908   BuildMI(MBB, MII, DL, InstDesc, MidReg)
2909     .addOperand(SrcRegSub0)
2910     .addImm(0);
2911 
2912   BuildMI(MBB, MII, DL, InstDesc, ResultReg)
2913     .addOperand(SrcRegSub1)
2914     .addReg(MidReg);
2915 
2916   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2917 
2918   // We don't need to legalize operands here. src0 for etiher instruction can be
2919   // an SGPR, and the second input is unused or determined here.
2920   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2921 }
2922 
2923 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
2924                                       MachineInstr &Inst) const {
2925   MachineBasicBlock &MBB = *Inst.getParent();
2926   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2927   MachineBasicBlock::iterator MII = Inst;
2928   DebugLoc DL = Inst.getDebugLoc();
2929 
2930   MachineOperand &Dest = Inst.getOperand(0);
2931   uint32_t Imm = Inst.getOperand(2).getImm();
2932   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2933   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2934 
2935   (void) Offset;
2936 
2937   // Only sext_inreg cases handled.
2938   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
2939          Offset == 0 && "Not implemented");
2940 
2941   if (BitWidth < 32) {
2942     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2943     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2944     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2945 
2946     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
2947         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
2948         .addImm(0)
2949         .addImm(BitWidth);
2950 
2951     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
2952       .addImm(31)
2953       .addReg(MidRegLo);
2954 
2955     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2956       .addReg(MidRegLo)
2957       .addImm(AMDGPU::sub0)
2958       .addReg(MidRegHi)
2959       .addImm(AMDGPU::sub1);
2960 
2961     MRI.replaceRegWith(Dest.getReg(), ResultReg);
2962     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2963     return;
2964   }
2965 
2966   MachineOperand &Src = Inst.getOperand(1);
2967   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2968   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2969 
2970   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
2971     .addImm(31)
2972     .addReg(Src.getReg(), 0, AMDGPU::sub0);
2973 
2974   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2975     .addReg(Src.getReg(), 0, AMDGPU::sub0)
2976     .addImm(AMDGPU::sub0)
2977     .addReg(TmpReg)
2978     .addImm(AMDGPU::sub1);
2979 
2980   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2981   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
2982 }
2983 
2984 void SIInstrInfo::addUsersToMoveToVALUWorklist(
2985   unsigned DstReg,
2986   MachineRegisterInfo &MRI,
2987   SmallVectorImpl<MachineInstr *> &Worklist) const {
2988   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
2989          E = MRI.use_end(); I != E; ++I) {
2990     MachineInstr &UseMI = *I->getParent();
2991     if (!canReadVGPR(UseMI, I.getOperandNo())) {
2992       Worklist.push_back(&UseMI);
2993     }
2994   }
2995 }
2996 
2997 void SIInstrInfo::addSCCDefUsersToVALUWorklist(
2998     MachineInstr &SCCDefInst, SmallVectorImpl<MachineInstr *> &Worklist) const {
2999   // This assumes that all the users of SCC are in the same block
3000   // as the SCC def.
3001   for (MachineInstr &MI :
3002        llvm::make_range(MachineBasicBlock::iterator(SCCDefInst),
3003                         SCCDefInst.getParent()->end())) {
3004     // Exit if we find another SCC def.
3005     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC) != -1)
3006       return;
3007 
3008     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC) != -1)
3009       Worklist.push_back(&MI);
3010   }
3011 }
3012 
3013 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
3014   const MachineInstr &Inst) const {
3015   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
3016 
3017   switch (Inst.getOpcode()) {
3018   // For target instructions, getOpRegClass just returns the virtual register
3019   // class associated with the operand, so we need to find an equivalent VGPR
3020   // register class in order to move the instruction to the VALU.
3021   case AMDGPU::COPY:
3022   case AMDGPU::PHI:
3023   case AMDGPU::REG_SEQUENCE:
3024   case AMDGPU::INSERT_SUBREG:
3025     if (RI.hasVGPRs(NewDstRC))
3026       return nullptr;
3027 
3028     NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
3029     if (!NewDstRC)
3030       return nullptr;
3031     return NewDstRC;
3032   default:
3033     return NewDstRC;
3034   }
3035 }
3036 
3037 // Find the one SGPR operand we are allowed to use.
3038 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
3039                                    int OpIndices[3]) const {
3040   const MCInstrDesc &Desc = MI.getDesc();
3041 
3042   // Find the one SGPR operand we are allowed to use.
3043   //
3044   // First we need to consider the instruction's operand requirements before
3045   // legalizing. Some operands are required to be SGPRs, such as implicit uses
3046   // of VCC, but we are still bound by the constant bus requirement to only use
3047   // one.
3048   //
3049   // If the operand's class is an SGPR, we can never move it.
3050 
3051   unsigned SGPRReg = findImplicitSGPRRead(MI);
3052   if (SGPRReg != AMDGPU::NoRegister)
3053     return SGPRReg;
3054 
3055   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
3056   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3057 
3058   for (unsigned i = 0; i < 3; ++i) {
3059     int Idx = OpIndices[i];
3060     if (Idx == -1)
3061       break;
3062 
3063     const MachineOperand &MO = MI.getOperand(Idx);
3064     if (!MO.isReg())
3065       continue;
3066 
3067     // Is this operand statically required to be an SGPR based on the operand
3068     // constraints?
3069     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
3070     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
3071     if (IsRequiredSGPR)
3072       return MO.getReg();
3073 
3074     // If this could be a VGPR or an SGPR, Check the dynamic register class.
3075     unsigned Reg = MO.getReg();
3076     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
3077     if (RI.isSGPRClass(RegRC))
3078       UsedSGPRs[i] = Reg;
3079   }
3080 
3081   // We don't have a required SGPR operand, so we have a bit more freedom in
3082   // selecting operands to move.
3083 
3084   // Try to select the most used SGPR. If an SGPR is equal to one of the
3085   // others, we choose that.
3086   //
3087   // e.g.
3088   // V_FMA_F32 v0, s0, s0, s0 -> No moves
3089   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
3090 
3091   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
3092   // prefer those.
3093 
3094   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
3095     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
3096       SGPRReg = UsedSGPRs[0];
3097   }
3098 
3099   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
3100     if (UsedSGPRs[1] == UsedSGPRs[2])
3101       SGPRReg = UsedSGPRs[1];
3102   }
3103 
3104   return SGPRReg;
3105 }
3106 
3107 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
3108                                              unsigned OperandName) const {
3109   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
3110   if (Idx == -1)
3111     return nullptr;
3112 
3113   return &MI.getOperand(Idx);
3114 }
3115 
3116 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
3117   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
3118   if (ST.isAmdHsaOS()) {
3119     RsrcDataFormat |= (1ULL << 56);
3120 
3121     if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3122       // Set MTYPE = 2
3123       RsrcDataFormat |= (2ULL << 59);
3124   }
3125 
3126   return RsrcDataFormat;
3127 }
3128 
3129 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
3130   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
3131                     AMDGPU::RSRC_TID_ENABLE |
3132                     0xffffffff; // Size;
3133 
3134   uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
3135 
3136   Rsrc23 |= (EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT) |
3137             // IndexStride = 64
3138             (UINT64_C(3) << AMDGPU::RSRC_INDEX_STRIDE_SHIFT);
3139 
3140   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
3141   // Clear them unless we want a huge stride.
3142   if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3143     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
3144 
3145   return Rsrc23;
3146 }
3147 
3148 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
3149   unsigned Opc = MI.getOpcode();
3150 
3151   return isSMRD(Opc);
3152 }
3153 
3154 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
3155   unsigned Opc = MI.getOpcode();
3156 
3157   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
3158 }
3159 
3160 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
3161   unsigned Opc = MI.getOpcode();
3162   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
3163   unsigned DescSize = Desc.getSize();
3164 
3165   // If we have a definitive size, we can use it. Otherwise we need to inspect
3166   // the operands to know the size.
3167   if (DescSize == 8 || DescSize == 4)
3168     return DescSize;
3169 
3170   assert(DescSize == 0);
3171 
3172   // 4-byte instructions may have a 32-bit literal encoded after them. Check
3173   // operands that coud ever be literals.
3174   if (isVALU(MI) || isSALU(MI)) {
3175     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3176     if (Src0Idx == -1)
3177       return 4; // No operands.
3178 
3179     if (isLiteralConstantLike(MI.getOperand(Src0Idx), getOpSize(MI, Src0Idx)))
3180       return 8;
3181 
3182     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3183     if (Src1Idx == -1)
3184       return 4;
3185 
3186     if (isLiteralConstantLike(MI.getOperand(Src1Idx), getOpSize(MI, Src1Idx)))
3187       return 8;
3188 
3189     return 4;
3190   }
3191 
3192   switch (Opc) {
3193   case TargetOpcode::IMPLICIT_DEF:
3194   case TargetOpcode::KILL:
3195   case TargetOpcode::DBG_VALUE:
3196   case TargetOpcode::BUNDLE:
3197   case TargetOpcode::EH_LABEL:
3198     return 0;
3199   case TargetOpcode::INLINEASM: {
3200     const MachineFunction *MF = MI.getParent()->getParent();
3201     const char *AsmStr = MI.getOperand(0).getSymbolName();
3202     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
3203   }
3204   default:
3205     llvm_unreachable("unable to find instruction size");
3206   }
3207 }
3208 
3209 ArrayRef<std::pair<int, const char *>>
3210 SIInstrInfo::getSerializableTargetIndices() const {
3211   static const std::pair<int, const char *> TargetIndices[] = {
3212       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
3213       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
3214       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
3215       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
3216       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
3217   return makeArrayRef(TargetIndices);
3218 }
3219 
3220 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
3221 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
3222 ScheduleHazardRecognizer *
3223 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
3224                                             const ScheduleDAG *DAG) const {
3225   return new GCNHazardRecognizer(DAG->MF);
3226 }
3227 
3228 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
3229 /// pass.
3230 ScheduleHazardRecognizer *
3231 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
3232   return new GCNHazardRecognizer(MF);
3233 }
3234