1 //===- SIInstrInfo.cpp - SI Instruction Information  ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// SI Implementation of TargetInstrInfo.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIInstrInfo.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "GCNHazardRecognizer.h"
18 #include "GCNSubtarget.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/CodeGen/ScheduleDAG.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetMachine.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "si-instr-info"
34 
35 #define GET_INSTRINFO_CTOR_DTOR
36 #include "AMDGPUGenInstrInfo.inc"
37 
38 namespace llvm {
39 
40 class AAResults;
41 
42 namespace AMDGPU {
43 #define GET_D16ImageDimIntrinsics_IMPL
44 #define GET_ImageDimIntrinsicTable_IMPL
45 #define GET_RsrcIntrinsics_IMPL
46 #include "AMDGPUGenSearchableTables.inc"
47 }
48 }
49 
50 
51 // Must be at least 4 to be able to branch over minimum unconditional branch
52 // code. This is only for making it possible to write reasonably small tests for
53 // long branches.
54 static cl::opt<unsigned>
55 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
56                  cl::desc("Restrict range of branch instructions (DEBUG)"));
57 
58 static cl::opt<bool> Fix16BitCopies(
59   "amdgpu-fix-16-bit-physreg-copies",
60   cl::desc("Fix copies between 32 and 16 bit registers by extending to 32 bit"),
61   cl::init(true),
62   cl::ReallyHidden);
63 
64 SIInstrInfo::SIInstrInfo(const GCNSubtarget &ST)
65   : AMDGPUGenInstrInfo(AMDGPU::ADJCALLSTACKUP, AMDGPU::ADJCALLSTACKDOWN),
66     RI(ST), ST(ST) {
67   SchedModel.init(&ST);
68 }
69 
70 //===----------------------------------------------------------------------===//
71 // TargetInstrInfo callbacks
72 //===----------------------------------------------------------------------===//
73 
74 static unsigned getNumOperandsNoGlue(SDNode *Node) {
75   unsigned N = Node->getNumOperands();
76   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
77     --N;
78   return N;
79 }
80 
81 /// Returns true if both nodes have the same value for the given
82 ///        operand \p Op, or if both nodes do not have this operand.
83 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
84   unsigned Opc0 = N0->getMachineOpcode();
85   unsigned Opc1 = N1->getMachineOpcode();
86 
87   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
88   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
89 
90   if (Op0Idx == -1 && Op1Idx == -1)
91     return true;
92 
93 
94   if ((Op0Idx == -1 && Op1Idx != -1) ||
95       (Op1Idx == -1 && Op0Idx != -1))
96     return false;
97 
98   // getNamedOperandIdx returns the index for the MachineInstr's operands,
99   // which includes the result as the first operand. We are indexing into the
100   // MachineSDNode's operands, so we need to skip the result operand to get
101   // the real index.
102   --Op0Idx;
103   --Op1Idx;
104 
105   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
106 }
107 
108 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
109                                                     AAResults *AA) const {
110   // TODO: The generic check fails for VALU instructions that should be
111   // rematerializable due to implicit reads of exec. We really want all of the
112   // generic logic for this except for this.
113   switch (MI.getOpcode()) {
114   case AMDGPU::V_MOV_B32_e32:
115   case AMDGPU::V_MOV_B32_e64:
116   case AMDGPU::V_MOV_B64_PSEUDO:
117   case AMDGPU::V_ACCVGPR_READ_B32_e64:
118   case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
119     // No implicit operands.
120     return MI.getNumOperands() == MI.getDesc().getNumOperands();
121   default:
122     return false;
123   }
124 }
125 
126 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
127                                           int64_t &Offset0,
128                                           int64_t &Offset1) const {
129   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
130     return false;
131 
132   unsigned Opc0 = Load0->getMachineOpcode();
133   unsigned Opc1 = Load1->getMachineOpcode();
134 
135   // Make sure both are actually loads.
136   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
137     return false;
138 
139   if (isDS(Opc0) && isDS(Opc1)) {
140 
141     // FIXME: Handle this case:
142     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
143       return false;
144 
145     // Check base reg.
146     if (Load0->getOperand(0) != Load1->getOperand(0))
147       return false;
148 
149     // Skip read2 / write2 variants for simplicity.
150     // TODO: We should report true if the used offsets are adjacent (excluded
151     // st64 versions).
152     int Offset0Idx = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
153     int Offset1Idx = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
154     if (Offset0Idx == -1 || Offset1Idx == -1)
155       return false;
156 
157     // XXX - be careful of datalesss loads
158     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
159     // include the output in the operand list, but SDNodes don't, we need to
160     // subtract the index by one.
161     Offset0Idx -= get(Opc0).NumDefs;
162     Offset1Idx -= get(Opc1).NumDefs;
163     Offset0 = cast<ConstantSDNode>(Load0->getOperand(Offset0Idx))->getZExtValue();
164     Offset1 = cast<ConstantSDNode>(Load1->getOperand(Offset1Idx))->getZExtValue();
165     return true;
166   }
167 
168   if (isSMRD(Opc0) && isSMRD(Opc1)) {
169     // Skip time and cache invalidation instructions.
170     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::sbase) == -1 ||
171         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::sbase) == -1)
172       return false;
173 
174     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
175 
176     // Check base reg.
177     if (Load0->getOperand(0) != Load1->getOperand(0))
178       return false;
179 
180     const ConstantSDNode *Load0Offset =
181         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
182     const ConstantSDNode *Load1Offset =
183         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
184 
185     if (!Load0Offset || !Load1Offset)
186       return false;
187 
188     Offset0 = Load0Offset->getZExtValue();
189     Offset1 = Load1Offset->getZExtValue();
190     return true;
191   }
192 
193   // MUBUF and MTBUF can access the same addresses.
194   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
195 
196     // MUBUF and MTBUF have vaddr at different indices.
197     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
198         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
199         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
200       return false;
201 
202     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
203     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
204 
205     if (OffIdx0 == -1 || OffIdx1 == -1)
206       return false;
207 
208     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
209     // include the output in the operand list, but SDNodes don't, we need to
210     // subtract the index by one.
211     OffIdx0 -= get(Opc0).NumDefs;
212     OffIdx1 -= get(Opc1).NumDefs;
213 
214     SDValue Off0 = Load0->getOperand(OffIdx0);
215     SDValue Off1 = Load1->getOperand(OffIdx1);
216 
217     // The offset might be a FrameIndexSDNode.
218     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
219       return false;
220 
221     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
222     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
223     return true;
224   }
225 
226   return false;
227 }
228 
229 static bool isStride64(unsigned Opc) {
230   switch (Opc) {
231   case AMDGPU::DS_READ2ST64_B32:
232   case AMDGPU::DS_READ2ST64_B64:
233   case AMDGPU::DS_WRITE2ST64_B32:
234   case AMDGPU::DS_WRITE2ST64_B64:
235     return true;
236   default:
237     return false;
238   }
239 }
240 
241 bool SIInstrInfo::getMemOperandsWithOffsetWidth(
242     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
243     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
244     const TargetRegisterInfo *TRI) const {
245   if (!LdSt.mayLoadOrStore())
246     return false;
247 
248   unsigned Opc = LdSt.getOpcode();
249   OffsetIsScalable = false;
250   const MachineOperand *BaseOp, *OffsetOp;
251   int DataOpIdx;
252 
253   if (isDS(LdSt)) {
254     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
255     OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
256     if (OffsetOp) {
257       // Normal, single offset LDS instruction.
258       if (!BaseOp) {
259         // DS_CONSUME/DS_APPEND use M0 for the base address.
260         // TODO: find the implicit use operand for M0 and use that as BaseOp?
261         return false;
262       }
263       BaseOps.push_back(BaseOp);
264       Offset = OffsetOp->getImm();
265       // Get appropriate operand, and compute width accordingly.
266       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
267       if (DataOpIdx == -1)
268         DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
269       Width = getOpSize(LdSt, DataOpIdx);
270     } else {
271       // The 2 offset instructions use offset0 and offset1 instead. We can treat
272       // these as a load with a single offset if the 2 offsets are consecutive.
273       // We will use this for some partially aligned loads.
274       const MachineOperand *Offset0Op =
275           getNamedOperand(LdSt, AMDGPU::OpName::offset0);
276       const MachineOperand *Offset1Op =
277           getNamedOperand(LdSt, AMDGPU::OpName::offset1);
278 
279       unsigned Offset0 = Offset0Op->getImm();
280       unsigned Offset1 = Offset1Op->getImm();
281       if (Offset0 + 1 != Offset1)
282         return false;
283 
284       // Each of these offsets is in element sized units, so we need to convert
285       // to bytes of the individual reads.
286 
287       unsigned EltSize;
288       if (LdSt.mayLoad())
289         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, 0)) / 16;
290       else {
291         assert(LdSt.mayStore());
292         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
293         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, Data0Idx)) / 8;
294       }
295 
296       if (isStride64(Opc))
297         EltSize *= 64;
298 
299       BaseOps.push_back(BaseOp);
300       Offset = EltSize * Offset0;
301       // Get appropriate operand(s), and compute width accordingly.
302       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
303       if (DataOpIdx == -1) {
304         DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
305         Width = getOpSize(LdSt, DataOpIdx);
306         DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
307         Width += getOpSize(LdSt, DataOpIdx);
308       } else {
309         Width = getOpSize(LdSt, DataOpIdx);
310       }
311     }
312     return true;
313   }
314 
315   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
316     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
317     if (SOffset && SOffset->isReg()) {
318       // We can only handle this if it's a stack access, as any other resource
319       // would require reporting multiple base registers.
320       const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
321       if (AddrReg && !AddrReg->isFI())
322         return false;
323 
324       const MachineOperand *RSrc = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
325       const SIMachineFunctionInfo *MFI
326         = LdSt.getParent()->getParent()->getInfo<SIMachineFunctionInfo>();
327       if (RSrc->getReg() != MFI->getScratchRSrcReg())
328         return false;
329 
330       const MachineOperand *OffsetImm =
331         getNamedOperand(LdSt, AMDGPU::OpName::offset);
332       BaseOps.push_back(RSrc);
333       BaseOps.push_back(SOffset);
334       Offset = OffsetImm->getImm();
335     } else {
336       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
337       if (!BaseOp) // e.g. BUFFER_WBINVL1_VOL
338         return false;
339       BaseOps.push_back(BaseOp);
340 
341       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
342       if (BaseOp)
343         BaseOps.push_back(BaseOp);
344 
345       const MachineOperand *OffsetImm =
346           getNamedOperand(LdSt, AMDGPU::OpName::offset);
347       Offset = OffsetImm->getImm();
348       if (SOffset) // soffset can be an inline immediate.
349         Offset += SOffset->getImm();
350     }
351     // Get appropriate operand, and compute width accordingly.
352     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
353     if (DataOpIdx == -1)
354       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
355     Width = getOpSize(LdSt, DataOpIdx);
356     return true;
357   }
358 
359   if (isMIMG(LdSt)) {
360     int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
361     BaseOps.push_back(&LdSt.getOperand(SRsrcIdx));
362     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
363     if (VAddr0Idx >= 0) {
364       // GFX10 possible NSA encoding.
365       for (int I = VAddr0Idx; I < SRsrcIdx; ++I)
366         BaseOps.push_back(&LdSt.getOperand(I));
367     } else {
368       BaseOps.push_back(getNamedOperand(LdSt, AMDGPU::OpName::vaddr));
369     }
370     Offset = 0;
371     // Get appropriate operand, and compute width accordingly.
372     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
373     Width = getOpSize(LdSt, DataOpIdx);
374     return true;
375   }
376 
377   if (isSMRD(LdSt)) {
378     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::sbase);
379     if (!BaseOp) // e.g. S_MEMTIME
380       return false;
381     BaseOps.push_back(BaseOp);
382     OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
383     Offset = OffsetOp ? OffsetOp->getImm() : 0;
384     // Get appropriate operand, and compute width accordingly.
385     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sdst);
386     Width = getOpSize(LdSt, DataOpIdx);
387     return true;
388   }
389 
390   if (isFLAT(LdSt)) {
391     // Instructions have either vaddr or saddr or both or none.
392     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
393     if (BaseOp)
394       BaseOps.push_back(BaseOp);
395     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::saddr);
396     if (BaseOp)
397       BaseOps.push_back(BaseOp);
398     Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
399     // Get appropriate operand, and compute width accordingly.
400     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
401     if (DataOpIdx == -1)
402       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
403     Width = getOpSize(LdSt, DataOpIdx);
404     return true;
405   }
406 
407   return false;
408 }
409 
410 static bool memOpsHaveSameBasePtr(const MachineInstr &MI1,
411                                   ArrayRef<const MachineOperand *> BaseOps1,
412                                   const MachineInstr &MI2,
413                                   ArrayRef<const MachineOperand *> BaseOps2) {
414   // Only examine the first "base" operand of each instruction, on the
415   // assumption that it represents the real base address of the memory access.
416   // Other operands are typically offsets or indices from this base address.
417   if (BaseOps1.front()->isIdenticalTo(*BaseOps2.front()))
418     return true;
419 
420   if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
421     return false;
422 
423   auto MO1 = *MI1.memoperands_begin();
424   auto MO2 = *MI2.memoperands_begin();
425   if (MO1->getAddrSpace() != MO2->getAddrSpace())
426     return false;
427 
428   auto Base1 = MO1->getValue();
429   auto Base2 = MO2->getValue();
430   if (!Base1 || !Base2)
431     return false;
432   Base1 = getUnderlyingObject(Base1);
433   Base2 = getUnderlyingObject(Base2);
434 
435   if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
436     return false;
437 
438   return Base1 == Base2;
439 }
440 
441 bool SIInstrInfo::shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
442                                       ArrayRef<const MachineOperand *> BaseOps2,
443                                       unsigned NumLoads,
444                                       unsigned NumBytes) const {
445   // If the mem ops (to be clustered) do not have the same base ptr, then they
446   // should not be clustered
447   if (!BaseOps1.empty() && !BaseOps2.empty()) {
448     const MachineInstr &FirstLdSt = *BaseOps1.front()->getParent();
449     const MachineInstr &SecondLdSt = *BaseOps2.front()->getParent();
450     if (!memOpsHaveSameBasePtr(FirstLdSt, BaseOps1, SecondLdSt, BaseOps2))
451       return false;
452   } else if (!BaseOps1.empty() || !BaseOps2.empty()) {
453     // If only one base op is empty, they do not have the same base ptr
454     return false;
455   }
456 
457   // In order to avoid regester pressure, on an average, the number of DWORDS
458   // loaded together by all clustered mem ops should not exceed 8. This is an
459   // empirical value based on certain observations and performance related
460   // experiments.
461   // The good thing about this heuristic is - it avoids clustering of too many
462   // sub-word loads, and also avoids clustering of wide loads. Below is the
463   // brief summary of how the heuristic behaves for various `LoadSize`.
464   // (1) 1 <= LoadSize <= 4: cluster at max 8 mem ops
465   // (2) 5 <= LoadSize <= 8: cluster at max 4 mem ops
466   // (3) 9 <= LoadSize <= 12: cluster at max 2 mem ops
467   // (4) 13 <= LoadSize <= 16: cluster at max 2 mem ops
468   // (5) LoadSize >= 17: do not cluster
469   const unsigned LoadSize = NumBytes / NumLoads;
470   const unsigned NumDWORDs = ((LoadSize + 3) / 4) * NumLoads;
471   return NumDWORDs <= 8;
472 }
473 
474 // FIXME: This behaves strangely. If, for example, you have 32 load + stores,
475 // the first 16 loads will be interleaved with the stores, and the next 16 will
476 // be clustered as expected. It should really split into 2 16 store batches.
477 //
478 // Loads are clustered until this returns false, rather than trying to schedule
479 // groups of stores. This also means we have to deal with saying different
480 // address space loads should be clustered, and ones which might cause bank
481 // conflicts.
482 //
483 // This might be deprecated so it might not be worth that much effort to fix.
484 bool SIInstrInfo::shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1,
485                                           int64_t Offset0, int64_t Offset1,
486                                           unsigned NumLoads) const {
487   assert(Offset1 > Offset0 &&
488          "Second offset should be larger than first offset!");
489   // If we have less than 16 loads in a row, and the offsets are within 64
490   // bytes, then schedule together.
491 
492   // A cacheline is 64 bytes (for global memory).
493   return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
494 }
495 
496 static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB,
497                               MachineBasicBlock::iterator MI,
498                               const DebugLoc &DL, MCRegister DestReg,
499                               MCRegister SrcReg, bool KillSrc,
500                               const char *Msg = "illegal SGPR to VGPR copy") {
501   MachineFunction *MF = MBB.getParent();
502   DiagnosticInfoUnsupported IllegalCopy(MF->getFunction(), Msg, DL, DS_Error);
503   LLVMContext &C = MF->getFunction().getContext();
504   C.diagnose(IllegalCopy);
505 
506   BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
507     .addReg(SrcReg, getKillRegState(KillSrc));
508 }
509 
510 /// Handle copying from SGPR to AGPR, or from AGPR to AGPR. It is not possible
511 /// to directly copy, so an intermediate VGPR needs to be used.
512 static void indirectCopyToAGPR(const SIInstrInfo &TII,
513                                MachineBasicBlock &MBB,
514                                MachineBasicBlock::iterator MI,
515                                const DebugLoc &DL, MCRegister DestReg,
516                                MCRegister SrcReg, bool KillSrc,
517                                RegScavenger &RS,
518                                Register ImpDefSuperReg = Register(),
519                                Register ImpUseSuperReg = Register()) {
520   const SIRegisterInfo &RI = TII.getRegisterInfo();
521 
522   assert(AMDGPU::SReg_32RegClass.contains(SrcReg) ||
523          AMDGPU::AGPR_32RegClass.contains(SrcReg));
524 
525   // First try to find defining accvgpr_write to avoid temporary registers.
526   for (auto Def = MI, E = MBB.begin(); Def != E; ) {
527     --Def;
528     if (!Def->definesRegister(SrcReg, &RI))
529       continue;
530     if (Def->getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
531       break;
532 
533     MachineOperand &DefOp = Def->getOperand(1);
534     assert(DefOp.isReg() || DefOp.isImm());
535 
536     if (DefOp.isReg()) {
537       // Check that register source operand if not clobbered before MI.
538       // Immediate operands are always safe to propagate.
539       bool SafeToPropagate = true;
540       for (auto I = Def; I != MI && SafeToPropagate; ++I)
541         if (I->modifiesRegister(DefOp.getReg(), &RI))
542           SafeToPropagate = false;
543 
544       if (!SafeToPropagate)
545         break;
546 
547       DefOp.setIsKill(false);
548     }
549 
550     MachineInstrBuilder Builder =
551       BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
552       .add(DefOp);
553     if (ImpDefSuperReg)
554       Builder.addReg(ImpDefSuperReg, RegState::Define | RegState::Implicit);
555 
556     if (ImpUseSuperReg) {
557       Builder.addReg(ImpUseSuperReg,
558                      getKillRegState(KillSrc) | RegState::Implicit);
559     }
560 
561     return;
562   }
563 
564   RS.enterBasicBlock(MBB);
565   RS.forward(MI);
566 
567   // Ideally we want to have three registers for a long reg_sequence copy
568   // to hide 2 waitstates between v_mov_b32 and accvgpr_write.
569   unsigned MaxVGPRs = RI.getRegPressureLimit(&AMDGPU::VGPR_32RegClass,
570                                              *MBB.getParent());
571 
572   // Registers in the sequence are allocated contiguously so we can just
573   // use register number to pick one of three round-robin temps.
574   unsigned RegNo = DestReg % 3;
575   Register Tmp = RS.scavengeRegister(&AMDGPU::VGPR_32RegClass, 0);
576   if (!Tmp)
577     report_fatal_error("Cannot scavenge VGPR to copy to AGPR");
578   RS.setRegUsed(Tmp);
579 
580   if (!TII.getSubtarget().hasGFX90AInsts()) {
581     // Only loop through if there are any free registers left, otherwise
582     // scavenger may report a fatal error without emergency spill slot
583     // or spill with the slot.
584     while (RegNo-- && RS.FindUnusedReg(&AMDGPU::VGPR_32RegClass)) {
585       Register Tmp2 = RS.scavengeRegister(&AMDGPU::VGPR_32RegClass, 0);
586       if (!Tmp2 || RI.getHWRegIndex(Tmp2) >= MaxVGPRs)
587         break;
588       Tmp = Tmp2;
589       RS.setRegUsed(Tmp);
590     }
591   }
592 
593   // Insert copy to temporary VGPR.
594   unsigned TmpCopyOp = AMDGPU::V_MOV_B32_e32;
595   if (AMDGPU::AGPR_32RegClass.contains(SrcReg)) {
596     TmpCopyOp = AMDGPU::V_ACCVGPR_READ_B32_e64;
597   } else {
598     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
599   }
600 
601   MachineInstrBuilder UseBuilder = BuildMI(MBB, MI, DL, TII.get(TmpCopyOp), Tmp)
602     .addReg(SrcReg, getKillRegState(KillSrc));
603   if (ImpUseSuperReg) {
604     UseBuilder.addReg(ImpUseSuperReg,
605                       getKillRegState(KillSrc) | RegState::Implicit);
606   }
607 
608   MachineInstrBuilder DefBuilder
609     = BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
610     .addReg(Tmp, RegState::Kill);
611 
612   if (ImpDefSuperReg)
613     DefBuilder.addReg(ImpDefSuperReg, RegState::Define | RegState::Implicit);
614 }
615 
616 static void expandSGPRCopy(const SIInstrInfo &TII, MachineBasicBlock &MBB,
617                            MachineBasicBlock::iterator MI, const DebugLoc &DL,
618                            MCRegister DestReg, MCRegister SrcReg, bool KillSrc,
619                            const TargetRegisterClass *RC, bool Forward) {
620   const SIRegisterInfo &RI = TII.getRegisterInfo();
621   ArrayRef<int16_t> BaseIndices = RI.getRegSplitParts(RC, 4);
622   MachineBasicBlock::iterator I = MI;
623   MachineInstr *FirstMI = nullptr, *LastMI = nullptr;
624 
625   for (unsigned Idx = 0; Idx < BaseIndices.size(); ++Idx) {
626     int16_t SubIdx = BaseIndices[Idx];
627     Register Reg = RI.getSubReg(DestReg, SubIdx);
628     unsigned Opcode = AMDGPU::S_MOV_B32;
629 
630     // Is SGPR aligned? If so try to combine with next.
631     Register Src = RI.getSubReg(SrcReg, SubIdx);
632     bool AlignedDest = ((Reg - AMDGPU::SGPR0) % 2) == 0;
633     bool AlignedSrc = ((Src - AMDGPU::SGPR0) % 2) == 0;
634     if (AlignedDest && AlignedSrc && (Idx + 1 < BaseIndices.size())) {
635       // Can use SGPR64 copy
636       unsigned Channel = RI.getChannelFromSubReg(SubIdx);
637       SubIdx = RI.getSubRegFromChannel(Channel, 2);
638       Opcode = AMDGPU::S_MOV_B64;
639       Idx++;
640     }
641 
642     LastMI = BuildMI(MBB, I, DL, TII.get(Opcode), RI.getSubReg(DestReg, SubIdx))
643                  .addReg(RI.getSubReg(SrcReg, SubIdx))
644                  .addReg(SrcReg, RegState::Implicit);
645 
646     if (!FirstMI)
647       FirstMI = LastMI;
648 
649     if (!Forward)
650       I--;
651   }
652 
653   assert(FirstMI && LastMI);
654   if (!Forward)
655     std::swap(FirstMI, LastMI);
656 
657   FirstMI->addOperand(
658       MachineOperand::CreateReg(DestReg, true /*IsDef*/, true /*IsImp*/));
659 
660   if (KillSrc)
661     LastMI->addRegisterKilled(SrcReg, &RI);
662 }
663 
664 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
665                               MachineBasicBlock::iterator MI,
666                               const DebugLoc &DL, MCRegister DestReg,
667                               MCRegister SrcReg, bool KillSrc) const {
668   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
669 
670   // FIXME: This is hack to resolve copies between 16 bit and 32 bit
671   // registers until all patterns are fixed.
672   if (Fix16BitCopies &&
673       ((RI.getRegSizeInBits(*RC) == 16) ^
674        (RI.getRegSizeInBits(*RI.getPhysRegClass(SrcReg)) == 16))) {
675     MCRegister &RegToFix = (RI.getRegSizeInBits(*RC) == 16) ? DestReg : SrcReg;
676     MCRegister Super = RI.get32BitRegister(RegToFix);
677     assert(RI.getSubReg(Super, AMDGPU::lo16) == RegToFix);
678     RegToFix = Super;
679 
680     if (DestReg == SrcReg) {
681       // Insert empty bundle since ExpandPostRA expects an instruction here.
682       BuildMI(MBB, MI, DL, get(AMDGPU::BUNDLE));
683       return;
684     }
685 
686     RC = RI.getPhysRegClass(DestReg);
687   }
688 
689   if (RC == &AMDGPU::VGPR_32RegClass) {
690     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
691            AMDGPU::SReg_32RegClass.contains(SrcReg) ||
692            AMDGPU::AGPR_32RegClass.contains(SrcReg));
693     unsigned Opc = AMDGPU::AGPR_32RegClass.contains(SrcReg) ?
694                      AMDGPU::V_ACCVGPR_READ_B32_e64 : AMDGPU::V_MOV_B32_e32;
695     BuildMI(MBB, MI, DL, get(Opc), DestReg)
696       .addReg(SrcReg, getKillRegState(KillSrc));
697     return;
698   }
699 
700   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
701       RC == &AMDGPU::SReg_32RegClass) {
702     if (SrcReg == AMDGPU::SCC) {
703       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
704           .addImm(1)
705           .addImm(0);
706       return;
707     }
708 
709     if (DestReg == AMDGPU::VCC_LO) {
710       if (AMDGPU::SReg_32RegClass.contains(SrcReg)) {
711         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), AMDGPU::VCC_LO)
712           .addReg(SrcReg, getKillRegState(KillSrc));
713       } else {
714         // FIXME: Hack until VReg_1 removed.
715         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
716         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
717           .addImm(0)
718           .addReg(SrcReg, getKillRegState(KillSrc));
719       }
720 
721       return;
722     }
723 
724     if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
725       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
726       return;
727     }
728 
729     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
730             .addReg(SrcReg, getKillRegState(KillSrc));
731     return;
732   }
733 
734   if (RC == &AMDGPU::SReg_64RegClass) {
735     if (SrcReg == AMDGPU::SCC) {
736       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B64), DestReg)
737           .addImm(1)
738           .addImm(0);
739       return;
740     }
741 
742     if (DestReg == AMDGPU::VCC) {
743       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
744         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
745           .addReg(SrcReg, getKillRegState(KillSrc));
746       } else {
747         // FIXME: Hack until VReg_1 removed.
748         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
749         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
750           .addImm(0)
751           .addReg(SrcReg, getKillRegState(KillSrc));
752       }
753 
754       return;
755     }
756 
757     if (!AMDGPU::SReg_64RegClass.contains(SrcReg)) {
758       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
759       return;
760     }
761 
762     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
763             .addReg(SrcReg, getKillRegState(KillSrc));
764     return;
765   }
766 
767   if (DestReg == AMDGPU::SCC) {
768     // Copying 64-bit or 32-bit sources to SCC barely makes sense,
769     // but SelectionDAG emits such copies for i1 sources.
770     if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
771       // This copy can only be produced by patterns
772       // with explicit SCC, which are known to be enabled
773       // only for subtargets with S_CMP_LG_U64 present.
774       assert(ST.hasScalarCompareEq64());
775       BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U64))
776           .addReg(SrcReg, getKillRegState(KillSrc))
777           .addImm(0);
778     } else {
779       assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
780       BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
781           .addReg(SrcReg, getKillRegState(KillSrc))
782           .addImm(0);
783     }
784 
785     return;
786   }
787 
788   if (RC == &AMDGPU::AGPR_32RegClass) {
789     if (AMDGPU::VGPR_32RegClass.contains(SrcReg)) {
790       BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
791         .addReg(SrcReg, getKillRegState(KillSrc));
792       return;
793     }
794 
795     if (AMDGPU::AGPR_32RegClass.contains(SrcReg) && ST.hasGFX90AInsts()) {
796       BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_MOV_B32), DestReg)
797         .addReg(SrcReg, getKillRegState(KillSrc));
798       return;
799     }
800 
801     // FIXME: Pass should maintain scavenger to avoid scan through the block on
802     // every AGPR spill.
803     RegScavenger RS;
804     indirectCopyToAGPR(*this, MBB, MI, DL, DestReg, SrcReg, KillSrc, RS);
805     return;
806   }
807 
808   const unsigned Size = RI.getRegSizeInBits(*RC);
809   if (Size == 16) {
810     assert(AMDGPU::VGPR_LO16RegClass.contains(SrcReg) ||
811            AMDGPU::VGPR_HI16RegClass.contains(SrcReg) ||
812            AMDGPU::SReg_LO16RegClass.contains(SrcReg) ||
813            AMDGPU::AGPR_LO16RegClass.contains(SrcReg));
814 
815     bool IsSGPRDst = AMDGPU::SReg_LO16RegClass.contains(DestReg);
816     bool IsSGPRSrc = AMDGPU::SReg_LO16RegClass.contains(SrcReg);
817     bool IsAGPRDst = AMDGPU::AGPR_LO16RegClass.contains(DestReg);
818     bool IsAGPRSrc = AMDGPU::AGPR_LO16RegClass.contains(SrcReg);
819     bool DstLow = AMDGPU::VGPR_LO16RegClass.contains(DestReg) ||
820                   AMDGPU::SReg_LO16RegClass.contains(DestReg) ||
821                   AMDGPU::AGPR_LO16RegClass.contains(DestReg);
822     bool SrcLow = AMDGPU::VGPR_LO16RegClass.contains(SrcReg) ||
823                   AMDGPU::SReg_LO16RegClass.contains(SrcReg) ||
824                   AMDGPU::AGPR_LO16RegClass.contains(SrcReg);
825     MCRegister NewDestReg = RI.get32BitRegister(DestReg);
826     MCRegister NewSrcReg = RI.get32BitRegister(SrcReg);
827 
828     if (IsSGPRDst) {
829       if (!IsSGPRSrc) {
830         reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
831         return;
832       }
833 
834       BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), NewDestReg)
835         .addReg(NewSrcReg, getKillRegState(KillSrc));
836       return;
837     }
838 
839     if (IsAGPRDst || IsAGPRSrc) {
840       if (!DstLow || !SrcLow) {
841         reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
842                           "Cannot use hi16 subreg with an AGPR!");
843       }
844 
845       copyPhysReg(MBB, MI, DL, NewDestReg, NewSrcReg, KillSrc);
846       return;
847     }
848 
849     if (IsSGPRSrc && !ST.hasSDWAScalar()) {
850       if (!DstLow || !SrcLow) {
851         reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
852                           "Cannot use hi16 subreg on VI!");
853       }
854 
855       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), NewDestReg)
856         .addReg(NewSrcReg, getKillRegState(KillSrc));
857       return;
858     }
859 
860     auto MIB = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_sdwa), NewDestReg)
861       .addImm(0) // src0_modifiers
862       .addReg(NewSrcReg)
863       .addImm(0) // clamp
864       .addImm(DstLow ? AMDGPU::SDWA::SdwaSel::WORD_0
865                      : AMDGPU::SDWA::SdwaSel::WORD_1)
866       .addImm(AMDGPU::SDWA::DstUnused::UNUSED_PRESERVE)
867       .addImm(SrcLow ? AMDGPU::SDWA::SdwaSel::WORD_0
868                      : AMDGPU::SDWA::SdwaSel::WORD_1)
869       .addReg(NewDestReg, RegState::Implicit | RegState::Undef);
870     // First implicit operand is $exec.
871     MIB->tieOperands(0, MIB->getNumOperands() - 1);
872     return;
873   }
874 
875   if (RC == &AMDGPU::VReg_64RegClass &&
876       !RI.hasAGPRs(RI.getPhysRegClass(SrcReg))) {
877     if (ST.hasPackedFP32Ops()) {
878       BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DestReg)
879         .addImm(SISrcMods::OP_SEL_1)
880         .addReg(SrcReg)
881         .addImm(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1)
882         .addReg(SrcReg)
883         .addImm(0) // op_sel_lo
884         .addImm(0) // op_sel_hi
885         .addImm(0) // neg_lo
886         .addImm(0) // neg_hi
887         .addImm(0) // clamp
888         .addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
889       return;
890     }
891   }
892 
893   const bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
894   if (RI.isSGPRClass(RC)) {
895     if (!RI.isSGPRClass(RI.getPhysRegClass(SrcReg))) {
896       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
897       return;
898     }
899     expandSGPRCopy(*this, MBB, MI, DL, DestReg, SrcReg, KillSrc, RC, Forward);
900     return;
901   }
902 
903   unsigned EltSize = 4;
904   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
905   if (RI.hasAGPRs(RC)) {
906     Opcode = (RI.hasVGPRs(RI.getPhysRegClass(SrcReg))) ?
907       AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
908   } else if (RI.hasVGPRs(RC) && RI.hasAGPRs(RI.getPhysRegClass(SrcReg))) {
909     Opcode = AMDGPU::V_ACCVGPR_READ_B32_e64;
910   } else if ((Size % 64 == 0) && RI.hasVGPRs(RC) &&
911              !RI.hasAGPRs(RI.getPhysRegClass(SrcReg))) {
912     // TODO: In 96-bit case, could do a 64-bit mov and then a 32-bit mov.
913     if (ST.hasPackedFP32Ops()) {
914       Opcode = AMDGPU::V_PK_MOV_B32;
915       EltSize = 8;
916     }
917   }
918 
919   // For the cases where we need an intermediate instruction/temporary register
920   // (destination is an AGPR), we need a scavenger.
921   //
922   // FIXME: The pass should maintain this for us so we don't have to re-scan the
923   // whole block for every handled copy.
924   std::unique_ptr<RegScavenger> RS;
925   if (Opcode == AMDGPU::INSTRUCTION_LIST_END)
926     RS.reset(new RegScavenger());
927 
928   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
929 
930   // If there is an overlap, we can't kill the super-register on the last
931   // instruction, since it will also kill the components made live by this def.
932   const bool CanKillSuperReg = KillSrc && !RI.regsOverlap(SrcReg, DestReg);
933 
934   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
935     unsigned SubIdx;
936     if (Forward)
937       SubIdx = SubIndices[Idx];
938     else
939       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
940 
941     bool UseKill = CanKillSuperReg && Idx == SubIndices.size() - 1;
942 
943     if (Opcode == AMDGPU::INSTRUCTION_LIST_END) {
944       Register ImpDefSuper = Idx == 0 ? Register(DestReg) : Register();
945       Register ImpUseSuper = SrcReg;
946       indirectCopyToAGPR(*this, MBB, MI, DL, RI.getSubReg(DestReg, SubIdx),
947                          RI.getSubReg(SrcReg, SubIdx), UseKill, *RS,
948                          ImpDefSuper, ImpUseSuper);
949     } else if (Opcode == AMDGPU::V_PK_MOV_B32) {
950       Register DstSubReg = RI.getSubReg(DestReg, SubIdx);
951       Register SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
952       MachineInstrBuilder MIB =
953         BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DstSubReg)
954         .addImm(SISrcMods::OP_SEL_1)
955         .addReg(SrcSubReg)
956         .addImm(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1)
957         .addReg(SrcSubReg)
958         .addImm(0) // op_sel_lo
959         .addImm(0) // op_sel_hi
960         .addImm(0) // neg_lo
961         .addImm(0) // neg_hi
962         .addImm(0) // clamp
963         .addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
964       if (Idx == 0)
965         MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
966     } else {
967       MachineInstrBuilder Builder =
968         BuildMI(MBB, MI, DL, get(Opcode), RI.getSubReg(DestReg, SubIdx))
969         .addReg(RI.getSubReg(SrcReg, SubIdx));
970       if (Idx == 0)
971         Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
972 
973       Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
974     }
975   }
976 }
977 
978 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
979   int NewOpc;
980 
981   // Try to map original to commuted opcode
982   NewOpc = AMDGPU::getCommuteRev(Opcode);
983   if (NewOpc != -1)
984     // Check if the commuted (REV) opcode exists on the target.
985     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
986 
987   // Try to map commuted to original opcode
988   NewOpc = AMDGPU::getCommuteOrig(Opcode);
989   if (NewOpc != -1)
990     // Check if the original (non-REV) opcode exists on the target.
991     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
992 
993   return Opcode;
994 }
995 
996 void SIInstrInfo::materializeImmediate(MachineBasicBlock &MBB,
997                                        MachineBasicBlock::iterator MI,
998                                        const DebugLoc &DL, unsigned DestReg,
999                                        int64_t Value) const {
1000   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1001   const TargetRegisterClass *RegClass = MRI.getRegClass(DestReg);
1002   if (RegClass == &AMDGPU::SReg_32RegClass ||
1003       RegClass == &AMDGPU::SGPR_32RegClass ||
1004       RegClass == &AMDGPU::SReg_32_XM0RegClass ||
1005       RegClass == &AMDGPU::SReg_32_XM0_XEXECRegClass) {
1006     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
1007       .addImm(Value);
1008     return;
1009   }
1010 
1011   if (RegClass == &AMDGPU::SReg_64RegClass ||
1012       RegClass == &AMDGPU::SGPR_64RegClass ||
1013       RegClass == &AMDGPU::SReg_64_XEXECRegClass) {
1014     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
1015       .addImm(Value);
1016     return;
1017   }
1018 
1019   if (RegClass == &AMDGPU::VGPR_32RegClass) {
1020     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
1021       .addImm(Value);
1022     return;
1023   }
1024   if (RegClass == &AMDGPU::VReg_64RegClass) {
1025     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO), DestReg)
1026       .addImm(Value);
1027     return;
1028   }
1029 
1030   unsigned EltSize = 4;
1031   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1032   if (RI.isSGPRClass(RegClass)) {
1033     if (RI.getRegSizeInBits(*RegClass) > 32) {
1034       Opcode =  AMDGPU::S_MOV_B64;
1035       EltSize = 8;
1036     } else {
1037       Opcode = AMDGPU::S_MOV_B32;
1038       EltSize = 4;
1039     }
1040   }
1041 
1042   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RegClass, EltSize);
1043   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
1044     int64_t IdxValue = Idx == 0 ? Value : 0;
1045 
1046     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
1047       get(Opcode), RI.getSubReg(DestReg, SubIndices[Idx]));
1048     Builder.addImm(IdxValue);
1049   }
1050 }
1051 
1052 const TargetRegisterClass *
1053 SIInstrInfo::getPreferredSelectRegClass(unsigned Size) const {
1054   return &AMDGPU::VGPR_32RegClass;
1055 }
1056 
1057 void SIInstrInfo::insertVectorSelect(MachineBasicBlock &MBB,
1058                                      MachineBasicBlock::iterator I,
1059                                      const DebugLoc &DL, Register DstReg,
1060                                      ArrayRef<MachineOperand> Cond,
1061                                      Register TrueReg,
1062                                      Register FalseReg) const {
1063   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1064   const TargetRegisterClass *BoolXExecRC =
1065     RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
1066   assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass &&
1067          "Not a VGPR32 reg");
1068 
1069   if (Cond.size() == 1) {
1070     Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1071     BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1072       .add(Cond[0]);
1073     BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1074       .addImm(0)
1075       .addReg(FalseReg)
1076       .addImm(0)
1077       .addReg(TrueReg)
1078       .addReg(SReg);
1079   } else if (Cond.size() == 2) {
1080     assert(Cond[0].isImm() && "Cond[0] is not an immediate");
1081     switch (Cond[0].getImm()) {
1082     case SIInstrInfo::SCC_TRUE: {
1083       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1084       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1085                                             : AMDGPU::S_CSELECT_B64), SReg)
1086         .addImm(1)
1087         .addImm(0);
1088       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1089         .addImm(0)
1090         .addReg(FalseReg)
1091         .addImm(0)
1092         .addReg(TrueReg)
1093         .addReg(SReg);
1094       break;
1095     }
1096     case SIInstrInfo::SCC_FALSE: {
1097       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1098       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1099                                             : AMDGPU::S_CSELECT_B64), SReg)
1100         .addImm(0)
1101         .addImm(1);
1102       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1103         .addImm(0)
1104         .addReg(FalseReg)
1105         .addImm(0)
1106         .addReg(TrueReg)
1107         .addReg(SReg);
1108       break;
1109     }
1110     case SIInstrInfo::VCCNZ: {
1111       MachineOperand RegOp = Cond[1];
1112       RegOp.setImplicit(false);
1113       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1114       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1115         .add(RegOp);
1116       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1117           .addImm(0)
1118           .addReg(FalseReg)
1119           .addImm(0)
1120           .addReg(TrueReg)
1121           .addReg(SReg);
1122       break;
1123     }
1124     case SIInstrInfo::VCCZ: {
1125       MachineOperand RegOp = Cond[1];
1126       RegOp.setImplicit(false);
1127       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1128       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1129         .add(RegOp);
1130       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1131           .addImm(0)
1132           .addReg(TrueReg)
1133           .addImm(0)
1134           .addReg(FalseReg)
1135           .addReg(SReg);
1136       break;
1137     }
1138     case SIInstrInfo::EXECNZ: {
1139       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1140       Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
1141       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1142                                             : AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
1143         .addImm(0);
1144       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1145                                             : AMDGPU::S_CSELECT_B64), SReg)
1146         .addImm(1)
1147         .addImm(0);
1148       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1149         .addImm(0)
1150         .addReg(FalseReg)
1151         .addImm(0)
1152         .addReg(TrueReg)
1153         .addReg(SReg);
1154       break;
1155     }
1156     case SIInstrInfo::EXECZ: {
1157       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1158       Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
1159       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1160                                             : AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
1161         .addImm(0);
1162       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1163                                             : AMDGPU::S_CSELECT_B64), SReg)
1164         .addImm(0)
1165         .addImm(1);
1166       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1167         .addImm(0)
1168         .addReg(FalseReg)
1169         .addImm(0)
1170         .addReg(TrueReg)
1171         .addReg(SReg);
1172       llvm_unreachable("Unhandled branch predicate EXECZ");
1173       break;
1174     }
1175     default:
1176       llvm_unreachable("invalid branch predicate");
1177     }
1178   } else {
1179     llvm_unreachable("Can only handle Cond size 1 or 2");
1180   }
1181 }
1182 
1183 Register SIInstrInfo::insertEQ(MachineBasicBlock *MBB,
1184                                MachineBasicBlock::iterator I,
1185                                const DebugLoc &DL,
1186                                Register SrcReg, int Value) const {
1187   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1188   Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
1189   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg)
1190     .addImm(Value)
1191     .addReg(SrcReg);
1192 
1193   return Reg;
1194 }
1195 
1196 Register SIInstrInfo::insertNE(MachineBasicBlock *MBB,
1197                                MachineBasicBlock::iterator I,
1198                                const DebugLoc &DL,
1199                                Register SrcReg, int Value) const {
1200   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1201   Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
1202   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg)
1203     .addImm(Value)
1204     .addReg(SrcReg);
1205 
1206   return Reg;
1207 }
1208 
1209 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
1210 
1211   if (RI.hasAGPRs(DstRC))
1212     return AMDGPU::COPY;
1213   if (RI.getRegSizeInBits(*DstRC) == 32) {
1214     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1215   } else if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC)) {
1216     return AMDGPU::S_MOV_B64;
1217   } else if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC)) {
1218     return  AMDGPU::V_MOV_B64_PSEUDO;
1219   }
1220   return AMDGPU::COPY;
1221 }
1222 
1223 const MCInstrDesc &
1224 SIInstrInfo::getIndirectGPRIDXPseudo(unsigned VecSize,
1225                                      bool IsIndirectSrc) const {
1226   if (IsIndirectSrc) {
1227     if (VecSize <= 32) // 4 bytes
1228       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1);
1229     if (VecSize <= 64) // 8 bytes
1230       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2);
1231     if (VecSize <= 96) // 12 bytes
1232       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3);
1233     if (VecSize <= 128) // 16 bytes
1234       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4);
1235     if (VecSize <= 160) // 20 bytes
1236       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5);
1237     if (VecSize <= 256) // 32 bytes
1238       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8);
1239     if (VecSize <= 512) // 64 bytes
1240       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16);
1241     if (VecSize <= 1024) // 128 bytes
1242       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32);
1243 
1244     llvm_unreachable("unsupported size for IndirectRegReadGPRIDX pseudos");
1245   }
1246 
1247   if (VecSize <= 32) // 4 bytes
1248     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1);
1249   if (VecSize <= 64) // 8 bytes
1250     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2);
1251   if (VecSize <= 96) // 12 bytes
1252     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3);
1253   if (VecSize <= 128) // 16 bytes
1254     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4);
1255   if (VecSize <= 160) // 20 bytes
1256     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5);
1257   if (VecSize <= 256) // 32 bytes
1258     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8);
1259   if (VecSize <= 512) // 64 bytes
1260     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16);
1261   if (VecSize <= 1024) // 128 bytes
1262     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32);
1263 
1264   llvm_unreachable("unsupported size for IndirectRegWriteGPRIDX pseudos");
1265 }
1266 
1267 static unsigned getIndirectVGPRWriteMovRelPseudoOpc(unsigned VecSize) {
1268   if (VecSize <= 32) // 4 bytes
1269     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1270   if (VecSize <= 64) // 8 bytes
1271     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1272   if (VecSize <= 96) // 12 bytes
1273     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1274   if (VecSize <= 128) // 16 bytes
1275     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1276   if (VecSize <= 160) // 20 bytes
1277     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1278   if (VecSize <= 256) // 32 bytes
1279     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1280   if (VecSize <= 512) // 64 bytes
1281     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1282   if (VecSize <= 1024) // 128 bytes
1283     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1284 
1285   llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1286 }
1287 
1288 static unsigned getIndirectSGPRWriteMovRelPseudo32(unsigned VecSize) {
1289   if (VecSize <= 32) // 4 bytes
1290     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1291   if (VecSize <= 64) // 8 bytes
1292     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1293   if (VecSize <= 96) // 12 bytes
1294     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1295   if (VecSize <= 128) // 16 bytes
1296     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1297   if (VecSize <= 160) // 20 bytes
1298     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1299   if (VecSize <= 256) // 32 bytes
1300     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1301   if (VecSize <= 512) // 64 bytes
1302     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1303   if (VecSize <= 1024) // 128 bytes
1304     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1305 
1306   llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1307 }
1308 
1309 static unsigned getIndirectSGPRWriteMovRelPseudo64(unsigned VecSize) {
1310   if (VecSize <= 64) // 8 bytes
1311     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1;
1312   if (VecSize <= 128) // 16 bytes
1313     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2;
1314   if (VecSize <= 256) // 32 bytes
1315     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4;
1316   if (VecSize <= 512) // 64 bytes
1317     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8;
1318   if (VecSize <= 1024) // 128 bytes
1319     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16;
1320 
1321   llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1322 }
1323 
1324 const MCInstrDesc &
1325 SIInstrInfo::getIndirectRegWriteMovRelPseudo(unsigned VecSize, unsigned EltSize,
1326                                              bool IsSGPR) const {
1327   if (IsSGPR) {
1328     switch (EltSize) {
1329     case 32:
1330       return get(getIndirectSGPRWriteMovRelPseudo32(VecSize));
1331     case 64:
1332       return get(getIndirectSGPRWriteMovRelPseudo64(VecSize));
1333     default:
1334       llvm_unreachable("invalid reg indexing elt size");
1335     }
1336   }
1337 
1338   assert(EltSize == 32 && "invalid reg indexing elt size");
1339   return get(getIndirectVGPRWriteMovRelPseudoOpc(VecSize));
1340 }
1341 
1342 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
1343   switch (Size) {
1344   case 4:
1345     return AMDGPU::SI_SPILL_S32_SAVE;
1346   case 8:
1347     return AMDGPU::SI_SPILL_S64_SAVE;
1348   case 12:
1349     return AMDGPU::SI_SPILL_S96_SAVE;
1350   case 16:
1351     return AMDGPU::SI_SPILL_S128_SAVE;
1352   case 20:
1353     return AMDGPU::SI_SPILL_S160_SAVE;
1354   case 24:
1355     return AMDGPU::SI_SPILL_S192_SAVE;
1356   case 32:
1357     return AMDGPU::SI_SPILL_S256_SAVE;
1358   case 64:
1359     return AMDGPU::SI_SPILL_S512_SAVE;
1360   case 128:
1361     return AMDGPU::SI_SPILL_S1024_SAVE;
1362   default:
1363     llvm_unreachable("unknown register size");
1364   }
1365 }
1366 
1367 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
1368   switch (Size) {
1369   case 4:
1370     return AMDGPU::SI_SPILL_V32_SAVE;
1371   case 8:
1372     return AMDGPU::SI_SPILL_V64_SAVE;
1373   case 12:
1374     return AMDGPU::SI_SPILL_V96_SAVE;
1375   case 16:
1376     return AMDGPU::SI_SPILL_V128_SAVE;
1377   case 20:
1378     return AMDGPU::SI_SPILL_V160_SAVE;
1379   case 24:
1380     return AMDGPU::SI_SPILL_V192_SAVE;
1381   case 32:
1382     return AMDGPU::SI_SPILL_V256_SAVE;
1383   case 64:
1384     return AMDGPU::SI_SPILL_V512_SAVE;
1385   case 128:
1386     return AMDGPU::SI_SPILL_V1024_SAVE;
1387   default:
1388     llvm_unreachable("unknown register size");
1389   }
1390 }
1391 
1392 static unsigned getAGPRSpillSaveOpcode(unsigned Size) {
1393   switch (Size) {
1394   case 4:
1395     return AMDGPU::SI_SPILL_A32_SAVE;
1396   case 8:
1397     return AMDGPU::SI_SPILL_A64_SAVE;
1398   case 12:
1399     return AMDGPU::SI_SPILL_A96_SAVE;
1400   case 16:
1401     return AMDGPU::SI_SPILL_A128_SAVE;
1402   case 20:
1403     return AMDGPU::SI_SPILL_A160_SAVE;
1404   case 24:
1405     return AMDGPU::SI_SPILL_A192_SAVE;
1406   case 32:
1407     return AMDGPU::SI_SPILL_A256_SAVE;
1408   case 64:
1409     return AMDGPU::SI_SPILL_A512_SAVE;
1410   case 128:
1411     return AMDGPU::SI_SPILL_A1024_SAVE;
1412   default:
1413     llvm_unreachable("unknown register size");
1414   }
1415 }
1416 
1417 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1418                                       MachineBasicBlock::iterator MI,
1419                                       Register SrcReg, bool isKill,
1420                                       int FrameIndex,
1421                                       const TargetRegisterClass *RC,
1422                                       const TargetRegisterInfo *TRI) const {
1423   MachineFunction *MF = MBB.getParent();
1424   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1425   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1426   const DebugLoc &DL = MBB.findDebugLoc(MI);
1427 
1428   MachinePointerInfo PtrInfo
1429     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1430   MachineMemOperand *MMO = MF->getMachineMemOperand(
1431       PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FrameIndex),
1432       FrameInfo.getObjectAlign(FrameIndex));
1433   unsigned SpillSize = TRI->getSpillSize(*RC);
1434 
1435   if (RI.isSGPRClass(RC)) {
1436     MFI->setHasSpilledSGPRs();
1437     assert(SrcReg != AMDGPU::M0 && "m0 should not be spilled");
1438     assert(SrcReg != AMDGPU::EXEC_LO && SrcReg != AMDGPU::EXEC_HI &&
1439            SrcReg != AMDGPU::EXEC && "exec should not be spilled");
1440 
1441     // We are only allowed to create one new instruction when spilling
1442     // registers, so we need to use pseudo instruction for spilling SGPRs.
1443     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(SpillSize));
1444 
1445     // The SGPR spill/restore instructions only work on number sgprs, so we need
1446     // to make sure we are using the correct register class.
1447     if (SrcReg.isVirtual() && SpillSize == 4) {
1448       MachineRegisterInfo &MRI = MF->getRegInfo();
1449       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1450     }
1451 
1452     BuildMI(MBB, MI, DL, OpDesc)
1453       .addReg(SrcReg, getKillRegState(isKill)) // data
1454       .addFrameIndex(FrameIndex)               // addr
1455       .addMemOperand(MMO)
1456       .addReg(MFI->getStackPtrOffsetReg(), RegState::Implicit);
1457 
1458     if (RI.spillSGPRToVGPR())
1459       FrameInfo.setStackID(FrameIndex, TargetStackID::SGPRSpill);
1460     return;
1461   }
1462 
1463   unsigned Opcode = RI.hasAGPRs(RC) ? getAGPRSpillSaveOpcode(SpillSize)
1464                                     : getVGPRSpillSaveOpcode(SpillSize);
1465   MFI->setHasSpilledVGPRs();
1466 
1467   BuildMI(MBB, MI, DL, get(Opcode))
1468     .addReg(SrcReg, getKillRegState(isKill)) // data
1469     .addFrameIndex(FrameIndex)               // addr
1470     .addReg(MFI->getStackPtrOffsetReg())     // scratch_offset
1471     .addImm(0)                               // offset
1472     .addMemOperand(MMO);
1473 }
1474 
1475 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
1476   switch (Size) {
1477   case 4:
1478     return AMDGPU::SI_SPILL_S32_RESTORE;
1479   case 8:
1480     return AMDGPU::SI_SPILL_S64_RESTORE;
1481   case 12:
1482     return AMDGPU::SI_SPILL_S96_RESTORE;
1483   case 16:
1484     return AMDGPU::SI_SPILL_S128_RESTORE;
1485   case 20:
1486     return AMDGPU::SI_SPILL_S160_RESTORE;
1487   case 24:
1488     return AMDGPU::SI_SPILL_S192_RESTORE;
1489   case 32:
1490     return AMDGPU::SI_SPILL_S256_RESTORE;
1491   case 64:
1492     return AMDGPU::SI_SPILL_S512_RESTORE;
1493   case 128:
1494     return AMDGPU::SI_SPILL_S1024_RESTORE;
1495   default:
1496     llvm_unreachable("unknown register size");
1497   }
1498 }
1499 
1500 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
1501   switch (Size) {
1502   case 4:
1503     return AMDGPU::SI_SPILL_V32_RESTORE;
1504   case 8:
1505     return AMDGPU::SI_SPILL_V64_RESTORE;
1506   case 12:
1507     return AMDGPU::SI_SPILL_V96_RESTORE;
1508   case 16:
1509     return AMDGPU::SI_SPILL_V128_RESTORE;
1510   case 20:
1511     return AMDGPU::SI_SPILL_V160_RESTORE;
1512   case 24:
1513     return AMDGPU::SI_SPILL_V192_RESTORE;
1514   case 32:
1515     return AMDGPU::SI_SPILL_V256_RESTORE;
1516   case 64:
1517     return AMDGPU::SI_SPILL_V512_RESTORE;
1518   case 128:
1519     return AMDGPU::SI_SPILL_V1024_RESTORE;
1520   default:
1521     llvm_unreachable("unknown register size");
1522   }
1523 }
1524 
1525 static unsigned getAGPRSpillRestoreOpcode(unsigned Size) {
1526   switch (Size) {
1527   case 4:
1528     return AMDGPU::SI_SPILL_A32_RESTORE;
1529   case 8:
1530     return AMDGPU::SI_SPILL_A64_RESTORE;
1531   case 12:
1532     return AMDGPU::SI_SPILL_A96_RESTORE;
1533   case 16:
1534     return AMDGPU::SI_SPILL_A128_RESTORE;
1535   case 20:
1536     return AMDGPU::SI_SPILL_A160_RESTORE;
1537   case 24:
1538     return AMDGPU::SI_SPILL_A192_RESTORE;
1539   case 32:
1540     return AMDGPU::SI_SPILL_A256_RESTORE;
1541   case 64:
1542     return AMDGPU::SI_SPILL_A512_RESTORE;
1543   case 128:
1544     return AMDGPU::SI_SPILL_A1024_RESTORE;
1545   default:
1546     llvm_unreachable("unknown register size");
1547   }
1548 }
1549 
1550 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1551                                        MachineBasicBlock::iterator MI,
1552                                        Register DestReg, int FrameIndex,
1553                                        const TargetRegisterClass *RC,
1554                                        const TargetRegisterInfo *TRI) const {
1555   MachineFunction *MF = MBB.getParent();
1556   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1557   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1558   const DebugLoc &DL = MBB.findDebugLoc(MI);
1559   unsigned SpillSize = TRI->getSpillSize(*RC);
1560 
1561   MachinePointerInfo PtrInfo
1562     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1563 
1564   MachineMemOperand *MMO = MF->getMachineMemOperand(
1565       PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FrameIndex),
1566       FrameInfo.getObjectAlign(FrameIndex));
1567 
1568   if (RI.isSGPRClass(RC)) {
1569     MFI->setHasSpilledSGPRs();
1570     assert(DestReg != AMDGPU::M0 && "m0 should not be reloaded into");
1571     assert(DestReg != AMDGPU::EXEC_LO && DestReg != AMDGPU::EXEC_HI &&
1572            DestReg != AMDGPU::EXEC && "exec should not be spilled");
1573 
1574     // FIXME: Maybe this should not include a memoperand because it will be
1575     // lowered to non-memory instructions.
1576     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
1577     if (DestReg.isVirtual() && SpillSize == 4) {
1578       MachineRegisterInfo &MRI = MF->getRegInfo();
1579       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1580     }
1581 
1582     if (RI.spillSGPRToVGPR())
1583       FrameInfo.setStackID(FrameIndex, TargetStackID::SGPRSpill);
1584     BuildMI(MBB, MI, DL, OpDesc, DestReg)
1585       .addFrameIndex(FrameIndex) // addr
1586       .addMemOperand(MMO)
1587       .addReg(MFI->getStackPtrOffsetReg(), RegState::Implicit);
1588 
1589     return;
1590   }
1591 
1592   unsigned Opcode = RI.hasAGPRs(RC) ? getAGPRSpillRestoreOpcode(SpillSize)
1593                                     : getVGPRSpillRestoreOpcode(SpillSize);
1594   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
1595     .addFrameIndex(FrameIndex)        // vaddr
1596     .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
1597     .addImm(0)                           // offset
1598     .addMemOperand(MMO);
1599 }
1600 
1601 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
1602                              MachineBasicBlock::iterator MI) const {
1603   insertNoops(MBB, MI, 1);
1604 }
1605 
1606 void SIInstrInfo::insertNoops(MachineBasicBlock &MBB,
1607                               MachineBasicBlock::iterator MI,
1608                               unsigned Quantity) const {
1609   DebugLoc DL = MBB.findDebugLoc(MI);
1610   while (Quantity > 0) {
1611     unsigned Arg = std::min(Quantity, 8u);
1612     Quantity -= Arg;
1613     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP)).addImm(Arg - 1);
1614   }
1615 }
1616 
1617 void SIInstrInfo::insertReturn(MachineBasicBlock &MBB) const {
1618   auto MF = MBB.getParent();
1619   SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1620 
1621   assert(Info->isEntryFunction());
1622 
1623   if (MBB.succ_empty()) {
1624     bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end();
1625     if (HasNoTerminator) {
1626       if (Info->returnsVoid()) {
1627         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::S_ENDPGM)).addImm(0);
1628       } else {
1629         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::SI_RETURN_TO_EPILOG));
1630       }
1631     }
1632   }
1633 }
1634 
1635 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) {
1636   switch (MI.getOpcode()) {
1637   default: return 1; // FIXME: Do wait states equal cycles?
1638 
1639   case AMDGPU::S_NOP:
1640     return MI.getOperand(0).getImm() + 1;
1641   }
1642 }
1643 
1644 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1645   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1646   MachineBasicBlock &MBB = *MI.getParent();
1647   DebugLoc DL = MBB.findDebugLoc(MI);
1648   switch (MI.getOpcode()) {
1649   default: return TargetInstrInfo::expandPostRAPseudo(MI);
1650   case AMDGPU::S_MOV_B64_term:
1651     // This is only a terminator to get the correct spill code placement during
1652     // register allocation.
1653     MI.setDesc(get(AMDGPU::S_MOV_B64));
1654     break;
1655 
1656   case AMDGPU::S_MOV_B32_term:
1657     // This is only a terminator to get the correct spill code placement during
1658     // register allocation.
1659     MI.setDesc(get(AMDGPU::S_MOV_B32));
1660     break;
1661 
1662   case AMDGPU::S_XOR_B64_term:
1663     // This is only a terminator to get the correct spill code placement during
1664     // register allocation.
1665     MI.setDesc(get(AMDGPU::S_XOR_B64));
1666     break;
1667 
1668   case AMDGPU::S_XOR_B32_term:
1669     // This is only a terminator to get the correct spill code placement during
1670     // register allocation.
1671     MI.setDesc(get(AMDGPU::S_XOR_B32));
1672     break;
1673   case AMDGPU::S_OR_B64_term:
1674     // This is only a terminator to get the correct spill code placement during
1675     // register allocation.
1676     MI.setDesc(get(AMDGPU::S_OR_B64));
1677     break;
1678   case AMDGPU::S_OR_B32_term:
1679     // This is only a terminator to get the correct spill code placement during
1680     // register allocation.
1681     MI.setDesc(get(AMDGPU::S_OR_B32));
1682     break;
1683 
1684   case AMDGPU::S_ANDN2_B64_term:
1685     // This is only a terminator to get the correct spill code placement during
1686     // register allocation.
1687     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
1688     break;
1689 
1690   case AMDGPU::S_ANDN2_B32_term:
1691     // This is only a terminator to get the correct spill code placement during
1692     // register allocation.
1693     MI.setDesc(get(AMDGPU::S_ANDN2_B32));
1694     break;
1695 
1696   case AMDGPU::S_AND_B64_term:
1697     // This is only a terminator to get the correct spill code placement during
1698     // register allocation.
1699     MI.setDesc(get(AMDGPU::S_AND_B64));
1700     break;
1701 
1702   case AMDGPU::S_AND_B32_term:
1703     // This is only a terminator to get the correct spill code placement during
1704     // register allocation.
1705     MI.setDesc(get(AMDGPU::S_AND_B32));
1706     break;
1707 
1708   case AMDGPU::V_MOV_B64_PSEUDO: {
1709     Register Dst = MI.getOperand(0).getReg();
1710     Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
1711     Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
1712 
1713     const MachineOperand &SrcOp = MI.getOperand(1);
1714     // FIXME: Will this work for 64-bit floating point immediates?
1715     assert(!SrcOp.isFPImm());
1716     if (SrcOp.isImm()) {
1717       APInt Imm(64, SrcOp.getImm());
1718       APInt Lo(32, Imm.getLoBits(32).getZExtValue());
1719       APInt Hi(32, Imm.getHiBits(32).getZExtValue());
1720       if (ST.hasPackedFP32Ops() && Lo == Hi && isInlineConstant(Lo)) {
1721         BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), Dst)
1722           .addImm(SISrcMods::OP_SEL_1)
1723           .addImm(Lo.getSExtValue())
1724           .addImm(SISrcMods::OP_SEL_1)
1725           .addImm(Lo.getSExtValue())
1726           .addImm(0)  // op_sel_lo
1727           .addImm(0)  // op_sel_hi
1728           .addImm(0)  // neg_lo
1729           .addImm(0)  // neg_hi
1730           .addImm(0); // clamp
1731       } else {
1732         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1733           .addImm(Lo.getZExtValue())
1734           .addReg(Dst, RegState::Implicit | RegState::Define);
1735         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1736           .addImm(Hi.getZExtValue())
1737           .addReg(Dst, RegState::Implicit | RegState::Define);
1738       }
1739     } else {
1740       assert(SrcOp.isReg());
1741       if (ST.hasPackedFP32Ops() &&
1742           !RI.isAGPR(MBB.getParent()->getRegInfo(), SrcOp.getReg())) {
1743         BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), Dst)
1744           .addImm(SISrcMods::OP_SEL_1) // src0_mod
1745           .addReg(SrcOp.getReg())
1746           .addImm(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1) // src1_mod
1747           .addReg(SrcOp.getReg())
1748           .addImm(0)  // op_sel_lo
1749           .addImm(0)  // op_sel_hi
1750           .addImm(0)  // neg_lo
1751           .addImm(0)  // neg_hi
1752           .addImm(0); // clamp
1753       } else {
1754         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1755           .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
1756           .addReg(Dst, RegState::Implicit | RegState::Define);
1757         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1758           .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
1759           .addReg(Dst, RegState::Implicit | RegState::Define);
1760       }
1761     }
1762     MI.eraseFromParent();
1763     break;
1764   }
1765   case AMDGPU::V_MOV_B64_DPP_PSEUDO: {
1766     expandMovDPP64(MI);
1767     break;
1768   }
1769   case AMDGPU::V_SET_INACTIVE_B32: {
1770     unsigned NotOpc = ST.isWave32() ? AMDGPU::S_NOT_B32 : AMDGPU::S_NOT_B64;
1771     unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1772     auto FirstNot = BuildMI(MBB, MI, DL, get(NotOpc), Exec).addReg(Exec);
1773     FirstNot->addRegisterDead(AMDGPU::SCC, TRI); // SCC is overwritten
1774     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), MI.getOperand(0).getReg())
1775       .add(MI.getOperand(2));
1776     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1777       .addReg(Exec);
1778     MI.eraseFromParent();
1779     break;
1780   }
1781   case AMDGPU::V_SET_INACTIVE_B64: {
1782     unsigned NotOpc = ST.isWave32() ? AMDGPU::S_NOT_B32 : AMDGPU::S_NOT_B64;
1783     unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1784     auto FirstNot = BuildMI(MBB, MI, DL, get(NotOpc), Exec).addReg(Exec);
1785     FirstNot->addRegisterDead(AMDGPU::SCC, TRI); // SCC is overwritten
1786     MachineInstr *Copy = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO),
1787                                  MI.getOperand(0).getReg())
1788       .add(MI.getOperand(2));
1789     expandPostRAPseudo(*Copy);
1790     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1791       .addReg(Exec);
1792     MI.eraseFromParent();
1793     break;
1794   }
1795   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1:
1796   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2:
1797   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3:
1798   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4:
1799   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5:
1800   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8:
1801   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16:
1802   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32:
1803   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1:
1804   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2:
1805   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3:
1806   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4:
1807   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5:
1808   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8:
1809   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16:
1810   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32:
1811   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1:
1812   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2:
1813   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4:
1814   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8:
1815   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16: {
1816     const TargetRegisterClass *EltRC = getOpRegClass(MI, 2);
1817 
1818     unsigned Opc;
1819     if (RI.hasVGPRs(EltRC)) {
1820       Opc = AMDGPU::V_MOVRELD_B32_e32;
1821     } else {
1822       Opc = RI.getRegSizeInBits(*EltRC) == 64 ? AMDGPU::S_MOVRELD_B64
1823                                               : AMDGPU::S_MOVRELD_B32;
1824     }
1825 
1826     const MCInstrDesc &OpDesc = get(Opc);
1827     Register VecReg = MI.getOperand(0).getReg();
1828     bool IsUndef = MI.getOperand(1).isUndef();
1829     unsigned SubReg = MI.getOperand(3).getImm();
1830     assert(VecReg == MI.getOperand(1).getReg());
1831 
1832     MachineInstrBuilder MIB =
1833       BuildMI(MBB, MI, DL, OpDesc)
1834         .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1835         .add(MI.getOperand(2))
1836         .addReg(VecReg, RegState::ImplicitDefine)
1837         .addReg(VecReg, RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1838 
1839     const int ImpDefIdx =
1840       OpDesc.getNumOperands() + OpDesc.getNumImplicitUses();
1841     const int ImpUseIdx = ImpDefIdx + 1;
1842     MIB->tieOperands(ImpDefIdx, ImpUseIdx);
1843     MI.eraseFromParent();
1844     break;
1845   }
1846   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1:
1847   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2:
1848   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3:
1849   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4:
1850   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5:
1851   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8:
1852   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16:
1853   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32: {
1854     assert(ST.useVGPRIndexMode());
1855     Register VecReg = MI.getOperand(0).getReg();
1856     bool IsUndef = MI.getOperand(1).isUndef();
1857     Register Idx = MI.getOperand(3).getReg();
1858     Register SubReg = MI.getOperand(4).getImm();
1859 
1860     MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
1861                               .addReg(Idx)
1862                               .addImm(AMDGPU::VGPRIndexMode::DST_ENABLE);
1863     SetOn->getOperand(3).setIsUndef();
1864 
1865     const MCInstrDesc &OpDesc = get(AMDGPU::V_MOV_B32_indirect);
1866     MachineInstrBuilder MIB =
1867         BuildMI(MBB, MI, DL, OpDesc)
1868             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1869             .add(MI.getOperand(2))
1870             .addReg(VecReg, RegState::ImplicitDefine)
1871             .addReg(VecReg,
1872                     RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1873 
1874     const int ImpDefIdx = OpDesc.getNumOperands() + OpDesc.getNumImplicitUses();
1875     const int ImpUseIdx = ImpDefIdx + 1;
1876     MIB->tieOperands(ImpDefIdx, ImpUseIdx);
1877 
1878     MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
1879 
1880     finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
1881 
1882     MI.eraseFromParent();
1883     break;
1884   }
1885   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1:
1886   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2:
1887   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3:
1888   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4:
1889   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5:
1890   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8:
1891   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16:
1892   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32: {
1893     assert(ST.useVGPRIndexMode());
1894     Register Dst = MI.getOperand(0).getReg();
1895     Register VecReg = MI.getOperand(1).getReg();
1896     bool IsUndef = MI.getOperand(1).isUndef();
1897     Register Idx = MI.getOperand(2).getReg();
1898     Register SubReg = MI.getOperand(3).getImm();
1899 
1900     MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
1901                               .addReg(Idx)
1902                               .addImm(AMDGPU::VGPRIndexMode::SRC0_ENABLE);
1903     SetOn->getOperand(3).setIsUndef();
1904 
1905     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32))
1906         .addDef(Dst)
1907         .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1908         .addReg(VecReg, RegState::Implicit | (IsUndef ? RegState::Undef : 0))
1909         .addReg(AMDGPU::M0, RegState::Implicit);
1910 
1911     MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
1912 
1913     finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
1914 
1915     MI.eraseFromParent();
1916     break;
1917   }
1918   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
1919     MachineFunction &MF = *MBB.getParent();
1920     Register Reg = MI.getOperand(0).getReg();
1921     Register RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
1922     Register RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
1923 
1924     // Create a bundle so these instructions won't be re-ordered by the
1925     // post-RA scheduler.
1926     MIBundleBuilder Bundler(MBB, MI);
1927     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
1928 
1929     // Add 32-bit offset from this instruction to the start of the
1930     // constant data.
1931     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
1932                        .addReg(RegLo)
1933                        .add(MI.getOperand(1)));
1934 
1935     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
1936                                   .addReg(RegHi);
1937     MIB.add(MI.getOperand(2));
1938 
1939     Bundler.append(MIB);
1940     finalizeBundle(MBB, Bundler.begin());
1941 
1942     MI.eraseFromParent();
1943     break;
1944   }
1945   case AMDGPU::ENTER_WWM: {
1946     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1947     // WWM is entered.
1948     MI.setDesc(get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1949                                  : AMDGPU::S_OR_SAVEEXEC_B64));
1950     break;
1951   }
1952   case AMDGPU::EXIT_WWM: {
1953     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1954     // WWM is exited.
1955     MI.setDesc(get(ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64));
1956     break;
1957   }
1958   }
1959   return true;
1960 }
1961 
1962 std::pair<MachineInstr*, MachineInstr*>
1963 SIInstrInfo::expandMovDPP64(MachineInstr &MI) const {
1964   assert (MI.getOpcode() == AMDGPU::V_MOV_B64_DPP_PSEUDO);
1965 
1966   MachineBasicBlock &MBB = *MI.getParent();
1967   DebugLoc DL = MBB.findDebugLoc(MI);
1968   MachineFunction *MF = MBB.getParent();
1969   MachineRegisterInfo &MRI = MF->getRegInfo();
1970   Register Dst = MI.getOperand(0).getReg();
1971   unsigned Part = 0;
1972   MachineInstr *Split[2];
1973 
1974   for (auto Sub : { AMDGPU::sub0, AMDGPU::sub1 }) {
1975     auto MovDPP = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_dpp));
1976     if (Dst.isPhysical()) {
1977       MovDPP.addDef(RI.getSubReg(Dst, Sub));
1978     } else {
1979       assert(MRI.isSSA());
1980       auto Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1981       MovDPP.addDef(Tmp);
1982     }
1983 
1984     for (unsigned I = 1; I <= 2; ++I) { // old and src operands.
1985       const MachineOperand &SrcOp = MI.getOperand(I);
1986       assert(!SrcOp.isFPImm());
1987       if (SrcOp.isImm()) {
1988         APInt Imm(64, SrcOp.getImm());
1989         Imm.ashrInPlace(Part * 32);
1990         MovDPP.addImm(Imm.getLoBits(32).getZExtValue());
1991       } else {
1992         assert(SrcOp.isReg());
1993         Register Src = SrcOp.getReg();
1994         if (Src.isPhysical())
1995           MovDPP.addReg(RI.getSubReg(Src, Sub));
1996         else
1997           MovDPP.addReg(Src, SrcOp.isUndef() ? RegState::Undef : 0, Sub);
1998       }
1999     }
2000 
2001     for (unsigned I = 3; I < MI.getNumExplicitOperands(); ++I)
2002       MovDPP.addImm(MI.getOperand(I).getImm());
2003 
2004     Split[Part] = MovDPP;
2005     ++Part;
2006   }
2007 
2008   if (Dst.isVirtual())
2009     BuildMI(MBB, MI, DL, get(AMDGPU::REG_SEQUENCE), Dst)
2010       .addReg(Split[0]->getOperand(0).getReg())
2011       .addImm(AMDGPU::sub0)
2012       .addReg(Split[1]->getOperand(0).getReg())
2013       .addImm(AMDGPU::sub1);
2014 
2015   MI.eraseFromParent();
2016   return std::make_pair(Split[0], Split[1]);
2017 }
2018 
2019 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
2020                                       MachineOperand &Src0,
2021                                       unsigned Src0OpName,
2022                                       MachineOperand &Src1,
2023                                       unsigned Src1OpName) const {
2024   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
2025   if (!Src0Mods)
2026     return false;
2027 
2028   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
2029   assert(Src1Mods &&
2030          "All commutable instructions have both src0 and src1 modifiers");
2031 
2032   int Src0ModsVal = Src0Mods->getImm();
2033   int Src1ModsVal = Src1Mods->getImm();
2034 
2035   Src1Mods->setImm(Src0ModsVal);
2036   Src0Mods->setImm(Src1ModsVal);
2037   return true;
2038 }
2039 
2040 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
2041                                              MachineOperand &RegOp,
2042                                              MachineOperand &NonRegOp) {
2043   Register Reg = RegOp.getReg();
2044   unsigned SubReg = RegOp.getSubReg();
2045   bool IsKill = RegOp.isKill();
2046   bool IsDead = RegOp.isDead();
2047   bool IsUndef = RegOp.isUndef();
2048   bool IsDebug = RegOp.isDebug();
2049 
2050   if (NonRegOp.isImm())
2051     RegOp.ChangeToImmediate(NonRegOp.getImm());
2052   else if (NonRegOp.isFI())
2053     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
2054   else if (NonRegOp.isGlobal()) {
2055     RegOp.ChangeToGA(NonRegOp.getGlobal(), NonRegOp.getOffset(),
2056                      NonRegOp.getTargetFlags());
2057   } else
2058     return nullptr;
2059 
2060   // Make sure we don't reinterpret a subreg index in the target flags.
2061   RegOp.setTargetFlags(NonRegOp.getTargetFlags());
2062 
2063   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
2064   NonRegOp.setSubReg(SubReg);
2065 
2066   return &MI;
2067 }
2068 
2069 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
2070                                                   unsigned Src0Idx,
2071                                                   unsigned Src1Idx) const {
2072   assert(!NewMI && "this should never be used");
2073 
2074   unsigned Opc = MI.getOpcode();
2075   int CommutedOpcode = commuteOpcode(Opc);
2076   if (CommutedOpcode == -1)
2077     return nullptr;
2078 
2079   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
2080            static_cast<int>(Src0Idx) &&
2081          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
2082            static_cast<int>(Src1Idx) &&
2083          "inconsistency with findCommutedOpIndices");
2084 
2085   MachineOperand &Src0 = MI.getOperand(Src0Idx);
2086   MachineOperand &Src1 = MI.getOperand(Src1Idx);
2087 
2088   MachineInstr *CommutedMI = nullptr;
2089   if (Src0.isReg() && Src1.isReg()) {
2090     if (isOperandLegal(MI, Src1Idx, &Src0)) {
2091       // Be sure to copy the source modifiers to the right place.
2092       CommutedMI
2093         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
2094     }
2095 
2096   } else if (Src0.isReg() && !Src1.isReg()) {
2097     // src0 should always be able to support any operand type, so no need to
2098     // check operand legality.
2099     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
2100   } else if (!Src0.isReg() && Src1.isReg()) {
2101     if (isOperandLegal(MI, Src1Idx, &Src0))
2102       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
2103   } else {
2104     // FIXME: Found two non registers to commute. This does happen.
2105     return nullptr;
2106   }
2107 
2108   if (CommutedMI) {
2109     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
2110                         Src1, AMDGPU::OpName::src1_modifiers);
2111 
2112     CommutedMI->setDesc(get(CommutedOpcode));
2113   }
2114 
2115   return CommutedMI;
2116 }
2117 
2118 // This needs to be implemented because the source modifiers may be inserted
2119 // between the true commutable operands, and the base
2120 // TargetInstrInfo::commuteInstruction uses it.
2121 bool SIInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
2122                                         unsigned &SrcOpIdx0,
2123                                         unsigned &SrcOpIdx1) const {
2124   return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
2125 }
2126 
2127 bool SIInstrInfo::findCommutedOpIndices(MCInstrDesc Desc, unsigned &SrcOpIdx0,
2128                                         unsigned &SrcOpIdx1) const {
2129   if (!Desc.isCommutable())
2130     return false;
2131 
2132   unsigned Opc = Desc.getOpcode();
2133   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2134   if (Src0Idx == -1)
2135     return false;
2136 
2137   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2138   if (Src1Idx == -1)
2139     return false;
2140 
2141   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
2142 }
2143 
2144 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
2145                                         int64_t BrOffset) const {
2146   // BranchRelaxation should never have to check s_setpc_b64 because its dest
2147   // block is unanalyzable.
2148   assert(BranchOp != AMDGPU::S_SETPC_B64);
2149 
2150   // Convert to dwords.
2151   BrOffset /= 4;
2152 
2153   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
2154   // from the next instruction.
2155   BrOffset -= 1;
2156 
2157   return isIntN(BranchOffsetBits, BrOffset);
2158 }
2159 
2160 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
2161   const MachineInstr &MI) const {
2162   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
2163     // This would be a difficult analysis to perform, but can always be legal so
2164     // there's no need to analyze it.
2165     return nullptr;
2166   }
2167 
2168   return MI.getOperand(0).getMBB();
2169 }
2170 
2171 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
2172                                            MachineBasicBlock &DestBB,
2173                                            const DebugLoc &DL,
2174                                            int64_t BrOffset,
2175                                            RegScavenger *RS) const {
2176   assert(RS && "RegScavenger required for long branching");
2177   assert(MBB.empty() &&
2178          "new block should be inserted for expanding unconditional branch");
2179   assert(MBB.pred_size() == 1);
2180 
2181   MachineFunction *MF = MBB.getParent();
2182   MachineRegisterInfo &MRI = MF->getRegInfo();
2183 
2184   // FIXME: Virtual register workaround for RegScavenger not working with empty
2185   // blocks.
2186   Register PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2187 
2188   auto I = MBB.end();
2189 
2190   // We need to compute the offset relative to the instruction immediately after
2191   // s_getpc_b64. Insert pc arithmetic code before last terminator.
2192   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
2193 
2194   // TODO: Handle > 32-bit block address.
2195   if (BrOffset >= 0) {
2196     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
2197       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
2198       .addReg(PCReg, 0, AMDGPU::sub0)
2199       .addMBB(&DestBB, MO_LONG_BRANCH_FORWARD);
2200     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
2201       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
2202       .addReg(PCReg, 0, AMDGPU::sub1)
2203       .addImm(0);
2204   } else {
2205     // Backwards branch.
2206     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
2207       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
2208       .addReg(PCReg, 0, AMDGPU::sub0)
2209       .addMBB(&DestBB, MO_LONG_BRANCH_BACKWARD);
2210     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
2211       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
2212       .addReg(PCReg, 0, AMDGPU::sub1)
2213       .addImm(0);
2214   }
2215 
2216   // Insert the indirect branch after the other terminator.
2217   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
2218     .addReg(PCReg);
2219 
2220   // FIXME: If spilling is necessary, this will fail because this scavenger has
2221   // no emergency stack slots. It is non-trivial to spill in this situation,
2222   // because the restore code needs to be specially placed after the
2223   // jump. BranchRelaxation then needs to be made aware of the newly inserted
2224   // block.
2225   //
2226   // If a spill is needed for the pc register pair, we need to insert a spill
2227   // restore block right before the destination block, and insert a short branch
2228   // into the old destination block's fallthrough predecessor.
2229   // e.g.:
2230   //
2231   // s_cbranch_scc0 skip_long_branch:
2232   //
2233   // long_branch_bb:
2234   //   spill s[8:9]
2235   //   s_getpc_b64 s[8:9]
2236   //   s_add_u32 s8, s8, restore_bb
2237   //   s_addc_u32 s9, s9, 0
2238   //   s_setpc_b64 s[8:9]
2239   //
2240   // skip_long_branch:
2241   //   foo;
2242   //
2243   // .....
2244   //
2245   // dest_bb_fallthrough_predecessor:
2246   // bar;
2247   // s_branch dest_bb
2248   //
2249   // restore_bb:
2250   //  restore s[8:9]
2251   //  fallthrough dest_bb
2252   ///
2253   // dest_bb:
2254   //   buzz;
2255 
2256   RS->enterBasicBlockEnd(MBB);
2257   Register Scav = RS->scavengeRegisterBackwards(
2258     AMDGPU::SReg_64RegClass,
2259     MachineBasicBlock::iterator(GetPC), false, 0);
2260   MRI.replaceRegWith(PCReg, Scav);
2261   MRI.clearVirtRegs();
2262   RS->setRegUsed(Scav);
2263 
2264   return 4 + 8 + 4 + 4;
2265 }
2266 
2267 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
2268   switch (Cond) {
2269   case SIInstrInfo::SCC_TRUE:
2270     return AMDGPU::S_CBRANCH_SCC1;
2271   case SIInstrInfo::SCC_FALSE:
2272     return AMDGPU::S_CBRANCH_SCC0;
2273   case SIInstrInfo::VCCNZ:
2274     return AMDGPU::S_CBRANCH_VCCNZ;
2275   case SIInstrInfo::VCCZ:
2276     return AMDGPU::S_CBRANCH_VCCZ;
2277   case SIInstrInfo::EXECNZ:
2278     return AMDGPU::S_CBRANCH_EXECNZ;
2279   case SIInstrInfo::EXECZ:
2280     return AMDGPU::S_CBRANCH_EXECZ;
2281   default:
2282     llvm_unreachable("invalid branch predicate");
2283   }
2284 }
2285 
2286 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
2287   switch (Opcode) {
2288   case AMDGPU::S_CBRANCH_SCC0:
2289     return SCC_FALSE;
2290   case AMDGPU::S_CBRANCH_SCC1:
2291     return SCC_TRUE;
2292   case AMDGPU::S_CBRANCH_VCCNZ:
2293     return VCCNZ;
2294   case AMDGPU::S_CBRANCH_VCCZ:
2295     return VCCZ;
2296   case AMDGPU::S_CBRANCH_EXECNZ:
2297     return EXECNZ;
2298   case AMDGPU::S_CBRANCH_EXECZ:
2299     return EXECZ;
2300   default:
2301     return INVALID_BR;
2302   }
2303 }
2304 
2305 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
2306                                     MachineBasicBlock::iterator I,
2307                                     MachineBasicBlock *&TBB,
2308                                     MachineBasicBlock *&FBB,
2309                                     SmallVectorImpl<MachineOperand> &Cond,
2310                                     bool AllowModify) const {
2311   if (I->getOpcode() == AMDGPU::S_BRANCH) {
2312     // Unconditional Branch
2313     TBB = I->getOperand(0).getMBB();
2314     return false;
2315   }
2316 
2317   MachineBasicBlock *CondBB = nullptr;
2318 
2319   if (I->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
2320     CondBB = I->getOperand(1).getMBB();
2321     Cond.push_back(I->getOperand(0));
2322   } else {
2323     BranchPredicate Pred = getBranchPredicate(I->getOpcode());
2324     if (Pred == INVALID_BR)
2325       return true;
2326 
2327     CondBB = I->getOperand(0).getMBB();
2328     Cond.push_back(MachineOperand::CreateImm(Pred));
2329     Cond.push_back(I->getOperand(1)); // Save the branch register.
2330   }
2331   ++I;
2332 
2333   if (I == MBB.end()) {
2334     // Conditional branch followed by fall-through.
2335     TBB = CondBB;
2336     return false;
2337   }
2338 
2339   if (I->getOpcode() == AMDGPU::S_BRANCH) {
2340     TBB = CondBB;
2341     FBB = I->getOperand(0).getMBB();
2342     return false;
2343   }
2344 
2345   return true;
2346 }
2347 
2348 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
2349                                 MachineBasicBlock *&FBB,
2350                                 SmallVectorImpl<MachineOperand> &Cond,
2351                                 bool AllowModify) const {
2352   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
2353   auto E = MBB.end();
2354   if (I == E)
2355     return false;
2356 
2357   // Skip over the instructions that are artificially terminators for special
2358   // exec management.
2359   while (I != E && !I->isBranch() && !I->isReturn() &&
2360          I->getOpcode() != AMDGPU::SI_MASK_BRANCH) {
2361     switch (I->getOpcode()) {
2362     case AMDGPU::SI_MASK_BRANCH:
2363     case AMDGPU::S_MOV_B64_term:
2364     case AMDGPU::S_XOR_B64_term:
2365     case AMDGPU::S_OR_B64_term:
2366     case AMDGPU::S_ANDN2_B64_term:
2367     case AMDGPU::S_AND_B64_term:
2368     case AMDGPU::S_MOV_B32_term:
2369     case AMDGPU::S_XOR_B32_term:
2370     case AMDGPU::S_OR_B32_term:
2371     case AMDGPU::S_ANDN2_B32_term:
2372     case AMDGPU::S_AND_B32_term:
2373       break;
2374     case AMDGPU::SI_IF:
2375     case AMDGPU::SI_ELSE:
2376     case AMDGPU::SI_KILL_I1_TERMINATOR:
2377     case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
2378       // FIXME: It's messy that these need to be considered here at all.
2379       return true;
2380     default:
2381       llvm_unreachable("unexpected non-branch terminator inst");
2382     }
2383 
2384     ++I;
2385   }
2386 
2387   if (I == E)
2388     return false;
2389 
2390   if (I->getOpcode() != AMDGPU::SI_MASK_BRANCH)
2391     return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
2392 
2393   ++I;
2394 
2395   // TODO: Should be able to treat as fallthrough?
2396   if (I == MBB.end())
2397     return true;
2398 
2399   if (analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify))
2400     return true;
2401 
2402   MachineBasicBlock *MaskBrDest = I->getOperand(0).getMBB();
2403 
2404   // Specifically handle the case where the conditional branch is to the same
2405   // destination as the mask branch. e.g.
2406   //
2407   // si_mask_branch BB8
2408   // s_cbranch_execz BB8
2409   // s_cbranch BB9
2410   //
2411   // This is required to understand divergent loops which may need the branches
2412   // to be relaxed.
2413   if (TBB != MaskBrDest || Cond.empty())
2414     return true;
2415 
2416   auto Pred = Cond[0].getImm();
2417   return (Pred != EXECZ && Pred != EXECNZ);
2418 }
2419 
2420 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
2421                                    int *BytesRemoved) const {
2422   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
2423 
2424   unsigned Count = 0;
2425   unsigned RemovedSize = 0;
2426   while (I != MBB.end()) {
2427     MachineBasicBlock::iterator Next = std::next(I);
2428     if (I->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
2429       I = Next;
2430       continue;
2431     }
2432 
2433     RemovedSize += getInstSizeInBytes(*I);
2434     I->eraseFromParent();
2435     ++Count;
2436     I = Next;
2437   }
2438 
2439   if (BytesRemoved)
2440     *BytesRemoved = RemovedSize;
2441 
2442   return Count;
2443 }
2444 
2445 // Copy the flags onto the implicit condition register operand.
2446 static void preserveCondRegFlags(MachineOperand &CondReg,
2447                                  const MachineOperand &OrigCond) {
2448   CondReg.setIsUndef(OrigCond.isUndef());
2449   CondReg.setIsKill(OrigCond.isKill());
2450 }
2451 
2452 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
2453                                    MachineBasicBlock *TBB,
2454                                    MachineBasicBlock *FBB,
2455                                    ArrayRef<MachineOperand> Cond,
2456                                    const DebugLoc &DL,
2457                                    int *BytesAdded) const {
2458   if (!FBB && Cond.empty()) {
2459     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
2460       .addMBB(TBB);
2461     if (BytesAdded)
2462       *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
2463     return 1;
2464   }
2465 
2466   if(Cond.size() == 1 && Cond[0].isReg()) {
2467      BuildMI(&MBB, DL, get(AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO))
2468        .add(Cond[0])
2469        .addMBB(TBB);
2470      return 1;
2471   }
2472 
2473   assert(TBB && Cond[0].isImm());
2474 
2475   unsigned Opcode
2476     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
2477 
2478   if (!FBB) {
2479     Cond[1].isUndef();
2480     MachineInstr *CondBr =
2481       BuildMI(&MBB, DL, get(Opcode))
2482       .addMBB(TBB);
2483 
2484     // Copy the flags onto the implicit condition register operand.
2485     preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
2486     fixImplicitOperands(*CondBr);
2487 
2488     if (BytesAdded)
2489       *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
2490     return 1;
2491   }
2492 
2493   assert(TBB && FBB);
2494 
2495   MachineInstr *CondBr =
2496     BuildMI(&MBB, DL, get(Opcode))
2497     .addMBB(TBB);
2498   fixImplicitOperands(*CondBr);
2499   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
2500     .addMBB(FBB);
2501 
2502   MachineOperand &CondReg = CondBr->getOperand(1);
2503   CondReg.setIsUndef(Cond[1].isUndef());
2504   CondReg.setIsKill(Cond[1].isKill());
2505 
2506   if (BytesAdded)
2507     *BytesAdded = ST.hasOffset3fBug() ? 16 : 8;
2508 
2509   return 2;
2510 }
2511 
2512 bool SIInstrInfo::reverseBranchCondition(
2513   SmallVectorImpl<MachineOperand> &Cond) const {
2514   if (Cond.size() != 2) {
2515     return true;
2516   }
2517 
2518   if (Cond[0].isImm()) {
2519     Cond[0].setImm(-Cond[0].getImm());
2520     return false;
2521   }
2522 
2523   return true;
2524 }
2525 
2526 bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
2527                                   ArrayRef<MachineOperand> Cond,
2528                                   Register DstReg, Register TrueReg,
2529                                   Register FalseReg, int &CondCycles,
2530                                   int &TrueCycles, int &FalseCycles) const {
2531   switch (Cond[0].getImm()) {
2532   case VCCNZ:
2533   case VCCZ: {
2534     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2535     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
2536     if (MRI.getRegClass(FalseReg) != RC)
2537       return false;
2538 
2539     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
2540     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
2541 
2542     // Limit to equal cost for branch vs. N v_cndmask_b32s.
2543     return RI.hasVGPRs(RC) && NumInsts <= 6;
2544   }
2545   case SCC_TRUE:
2546   case SCC_FALSE: {
2547     // FIXME: We could insert for VGPRs if we could replace the original compare
2548     // with a vector one.
2549     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2550     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
2551     if (MRI.getRegClass(FalseReg) != RC)
2552       return false;
2553 
2554     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
2555 
2556     // Multiples of 8 can do s_cselect_b64
2557     if (NumInsts % 2 == 0)
2558       NumInsts /= 2;
2559 
2560     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
2561     return RI.isSGPRClass(RC);
2562   }
2563   default:
2564     return false;
2565   }
2566 }
2567 
2568 void SIInstrInfo::insertSelect(MachineBasicBlock &MBB,
2569                                MachineBasicBlock::iterator I, const DebugLoc &DL,
2570                                Register DstReg, ArrayRef<MachineOperand> Cond,
2571                                Register TrueReg, Register FalseReg) const {
2572   BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
2573   if (Pred == VCCZ || Pred == SCC_FALSE) {
2574     Pred = static_cast<BranchPredicate>(-Pred);
2575     std::swap(TrueReg, FalseReg);
2576   }
2577 
2578   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2579   const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
2580   unsigned DstSize = RI.getRegSizeInBits(*DstRC);
2581 
2582   if (DstSize == 32) {
2583     MachineInstr *Select;
2584     if (Pred == SCC_TRUE) {
2585       Select = BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B32), DstReg)
2586         .addReg(TrueReg)
2587         .addReg(FalseReg);
2588     } else {
2589       // Instruction's operands are backwards from what is expected.
2590       Select = BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e32), DstReg)
2591         .addReg(FalseReg)
2592         .addReg(TrueReg);
2593     }
2594 
2595     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2596     return;
2597   }
2598 
2599   if (DstSize == 64 && Pred == SCC_TRUE) {
2600     MachineInstr *Select =
2601       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
2602       .addReg(TrueReg)
2603       .addReg(FalseReg);
2604 
2605     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2606     return;
2607   }
2608 
2609   static const int16_t Sub0_15[] = {
2610     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
2611     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
2612     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
2613     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
2614   };
2615 
2616   static const int16_t Sub0_15_64[] = {
2617     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
2618     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
2619     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
2620     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
2621   };
2622 
2623   unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
2624   const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
2625   const int16_t *SubIndices = Sub0_15;
2626   int NElts = DstSize / 32;
2627 
2628   // 64-bit select is only available for SALU.
2629   // TODO: Split 96-bit into 64-bit and 32-bit, not 3x 32-bit.
2630   if (Pred == SCC_TRUE) {
2631     if (NElts % 2) {
2632       SelOp = AMDGPU::S_CSELECT_B32;
2633       EltRC = &AMDGPU::SGPR_32RegClass;
2634     } else {
2635       SelOp = AMDGPU::S_CSELECT_B64;
2636       EltRC = &AMDGPU::SGPR_64RegClass;
2637       SubIndices = Sub0_15_64;
2638       NElts /= 2;
2639     }
2640   }
2641 
2642   MachineInstrBuilder MIB = BuildMI(
2643     MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
2644 
2645   I = MIB->getIterator();
2646 
2647   SmallVector<Register, 8> Regs;
2648   for (int Idx = 0; Idx != NElts; ++Idx) {
2649     Register DstElt = MRI.createVirtualRegister(EltRC);
2650     Regs.push_back(DstElt);
2651 
2652     unsigned SubIdx = SubIndices[Idx];
2653 
2654     MachineInstr *Select;
2655     if (SelOp == AMDGPU::V_CNDMASK_B32_e32) {
2656       Select =
2657         BuildMI(MBB, I, DL, get(SelOp), DstElt)
2658         .addReg(FalseReg, 0, SubIdx)
2659         .addReg(TrueReg, 0, SubIdx);
2660     } else {
2661       Select =
2662         BuildMI(MBB, I, DL, get(SelOp), DstElt)
2663         .addReg(TrueReg, 0, SubIdx)
2664         .addReg(FalseReg, 0, SubIdx);
2665     }
2666 
2667     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2668     fixImplicitOperands(*Select);
2669 
2670     MIB.addReg(DstElt)
2671        .addImm(SubIdx);
2672   }
2673 }
2674 
2675 bool SIInstrInfo::isFoldableCopy(const MachineInstr &MI) const {
2676   switch (MI.getOpcode()) {
2677   case AMDGPU::V_MOV_B32_e32:
2678   case AMDGPU::V_MOV_B32_e64:
2679   case AMDGPU::V_MOV_B64_PSEUDO: {
2680     // If there are additional implicit register operands, this may be used for
2681     // register indexing so the source register operand isn't simply copied.
2682     unsigned NumOps = MI.getDesc().getNumOperands() +
2683       MI.getDesc().getNumImplicitUses();
2684 
2685     return MI.getNumOperands() == NumOps;
2686   }
2687   case AMDGPU::S_MOV_B32:
2688   case AMDGPU::S_MOV_B64:
2689   case AMDGPU::COPY:
2690   case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
2691   case AMDGPU::V_ACCVGPR_READ_B32_e64:
2692   case AMDGPU::V_ACCVGPR_MOV_B32:
2693     return true;
2694   default:
2695     return false;
2696   }
2697 }
2698 
2699 unsigned SIInstrInfo::getAddressSpaceForPseudoSourceKind(
2700     unsigned Kind) const {
2701   switch(Kind) {
2702   case PseudoSourceValue::Stack:
2703   case PseudoSourceValue::FixedStack:
2704     return AMDGPUAS::PRIVATE_ADDRESS;
2705   case PseudoSourceValue::ConstantPool:
2706   case PseudoSourceValue::GOT:
2707   case PseudoSourceValue::JumpTable:
2708   case PseudoSourceValue::GlobalValueCallEntry:
2709   case PseudoSourceValue::ExternalSymbolCallEntry:
2710   case PseudoSourceValue::TargetCustom:
2711     return AMDGPUAS::CONSTANT_ADDRESS;
2712   }
2713   return AMDGPUAS::FLAT_ADDRESS;
2714 }
2715 
2716 static void removeModOperands(MachineInstr &MI) {
2717   unsigned Opc = MI.getOpcode();
2718   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2719                                               AMDGPU::OpName::src0_modifiers);
2720   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2721                                               AMDGPU::OpName::src1_modifiers);
2722   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2723                                               AMDGPU::OpName::src2_modifiers);
2724 
2725   MI.RemoveOperand(Src2ModIdx);
2726   MI.RemoveOperand(Src1ModIdx);
2727   MI.RemoveOperand(Src0ModIdx);
2728 }
2729 
2730 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2731                                 Register Reg, MachineRegisterInfo *MRI) const {
2732   if (!MRI->hasOneNonDBGUse(Reg))
2733     return false;
2734 
2735   switch (DefMI.getOpcode()) {
2736   default:
2737     return false;
2738   case AMDGPU::S_MOV_B64:
2739     // TODO: We could fold 64-bit immediates, but this get compilicated
2740     // when there are sub-registers.
2741     return false;
2742 
2743   case AMDGPU::V_MOV_B32_e32:
2744   case AMDGPU::S_MOV_B32:
2745   case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
2746     break;
2747   }
2748 
2749   const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
2750   assert(ImmOp);
2751   // FIXME: We could handle FrameIndex values here.
2752   if (!ImmOp->isImm())
2753     return false;
2754 
2755   unsigned Opc = UseMI.getOpcode();
2756   if (Opc == AMDGPU::COPY) {
2757     Register DstReg = UseMI.getOperand(0).getReg();
2758     bool Is16Bit = getOpSize(UseMI, 0) == 2;
2759     bool isVGPRCopy = RI.isVGPR(*MRI, DstReg);
2760     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
2761     APInt Imm(32, ImmOp->getImm());
2762 
2763     if (UseMI.getOperand(1).getSubReg() == AMDGPU::hi16)
2764       Imm = Imm.ashr(16);
2765 
2766     if (RI.isAGPR(*MRI, DstReg)) {
2767       if (!isInlineConstant(Imm))
2768         return false;
2769       NewOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
2770     }
2771 
2772     if (Is16Bit) {
2773        if (isVGPRCopy)
2774          return false; // Do not clobber vgpr_hi16
2775 
2776        if (DstReg.isVirtual() &&
2777            UseMI.getOperand(0).getSubReg() != AMDGPU::lo16)
2778          return false;
2779 
2780       UseMI.getOperand(0).setSubReg(0);
2781       if (DstReg.isPhysical()) {
2782         DstReg = RI.get32BitRegister(DstReg);
2783         UseMI.getOperand(0).setReg(DstReg);
2784       }
2785       assert(UseMI.getOperand(1).getReg().isVirtual());
2786     }
2787 
2788     UseMI.setDesc(get(NewOpc));
2789     UseMI.getOperand(1).ChangeToImmediate(Imm.getSExtValue());
2790     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
2791     return true;
2792   }
2793 
2794   if (Opc == AMDGPU::V_MAD_F32_e64 || Opc == AMDGPU::V_MAC_F32_e64 ||
2795       Opc == AMDGPU::V_MAD_F16_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
2796       Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2797       Opc == AMDGPU::V_FMA_F16_e64 || Opc == AMDGPU::V_FMAC_F16_e64) {
2798     // Don't fold if we are using source or output modifiers. The new VOP2
2799     // instructions don't have them.
2800     if (hasAnyModifiersSet(UseMI))
2801       return false;
2802 
2803     // If this is a free constant, there's no reason to do this.
2804     // TODO: We could fold this here instead of letting SIFoldOperands do it
2805     // later.
2806     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
2807 
2808     // Any src operand can be used for the legality check.
2809     if (isInlineConstant(UseMI, *Src0, *ImmOp))
2810       return false;
2811 
2812     bool IsF32 = Opc == AMDGPU::V_MAD_F32_e64 || Opc == AMDGPU::V_MAC_F32_e64 ||
2813                  Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64;
2814     bool IsFMA = Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2815                  Opc == AMDGPU::V_FMA_F16_e64 || Opc == AMDGPU::V_FMAC_F16_e64;
2816     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
2817     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
2818 
2819     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
2820     // We should only expect these to be on src0 due to canonicalizations.
2821     if (Src0->isReg() && Src0->getReg() == Reg) {
2822       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
2823         return false;
2824 
2825       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
2826         return false;
2827 
2828       unsigned NewOpc =
2829         IsFMA ? (IsF32 ? AMDGPU::V_FMAMK_F32 : AMDGPU::V_FMAMK_F16)
2830               : (IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16);
2831       if (pseudoToMCOpcode(NewOpc) == -1)
2832         return false;
2833 
2834       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
2835 
2836       const int64_t Imm = ImmOp->getImm();
2837 
2838       // FIXME: This would be a lot easier if we could return a new instruction
2839       // instead of having to modify in place.
2840 
2841       // Remove these first since they are at the end.
2842       UseMI.RemoveOperand(
2843           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2844       UseMI.RemoveOperand(
2845           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2846 
2847       Register Src1Reg = Src1->getReg();
2848       unsigned Src1SubReg = Src1->getSubReg();
2849       Src0->setReg(Src1Reg);
2850       Src0->setSubReg(Src1SubReg);
2851       Src0->setIsKill(Src1->isKill());
2852 
2853       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2854           Opc == AMDGPU::V_MAC_F16_e64 ||
2855           Opc == AMDGPU::V_FMAC_F32_e64 ||
2856           Opc == AMDGPU::V_FMAC_F16_e64)
2857         UseMI.untieRegOperand(
2858             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2859 
2860       Src1->ChangeToImmediate(Imm);
2861 
2862       removeModOperands(UseMI);
2863       UseMI.setDesc(get(NewOpc));
2864 
2865       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2866       if (DeleteDef)
2867         DefMI.eraseFromParent();
2868 
2869       return true;
2870     }
2871 
2872     // Added part is the constant: Use v_madak_{f16, f32}.
2873     if (Src2->isReg() && Src2->getReg() == Reg) {
2874       // Not allowed to use constant bus for another operand.
2875       // We can however allow an inline immediate as src0.
2876       bool Src0Inlined = false;
2877       if (Src0->isReg()) {
2878         // Try to inline constant if possible.
2879         // If the Def moves immediate and the use is single
2880         // We are saving VGPR here.
2881         MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
2882         if (Def && Def->isMoveImmediate() &&
2883           isInlineConstant(Def->getOperand(1)) &&
2884           MRI->hasOneUse(Src0->getReg())) {
2885           Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2886           Src0Inlined = true;
2887         } else if ((Src0->getReg().isPhysical() &&
2888                     (ST.getConstantBusLimit(Opc) <= 1 &&
2889                      RI.isSGPRClass(RI.getPhysRegClass(Src0->getReg())))) ||
2890                    (Src0->getReg().isVirtual() &&
2891                     (ST.getConstantBusLimit(Opc) <= 1 &&
2892                      RI.isSGPRClass(MRI->getRegClass(Src0->getReg())))))
2893           return false;
2894           // VGPR is okay as Src0 - fallthrough
2895       }
2896 
2897       if (Src1->isReg() && !Src0Inlined ) {
2898         // We have one slot for inlinable constant so far - try to fill it
2899         MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
2900         if (Def && Def->isMoveImmediate() &&
2901             isInlineConstant(Def->getOperand(1)) &&
2902             MRI->hasOneUse(Src1->getReg()) &&
2903             commuteInstruction(UseMI)) {
2904             Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2905         } else if ((Src1->getReg().isPhysical() &&
2906                     RI.isSGPRClass(RI.getPhysRegClass(Src1->getReg()))) ||
2907                    (Src1->getReg().isVirtual() &&
2908                     RI.isSGPRClass(MRI->getRegClass(Src1->getReg()))))
2909           return false;
2910           // VGPR is okay as Src1 - fallthrough
2911       }
2912 
2913       unsigned NewOpc =
2914         IsFMA ? (IsF32 ? AMDGPU::V_FMAAK_F32 : AMDGPU::V_FMAAK_F16)
2915               : (IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16);
2916       if (pseudoToMCOpcode(NewOpc) == -1)
2917         return false;
2918 
2919       const int64_t Imm = ImmOp->getImm();
2920 
2921       // FIXME: This would be a lot easier if we could return a new instruction
2922       // instead of having to modify in place.
2923 
2924       // Remove these first since they are at the end.
2925       UseMI.RemoveOperand(
2926           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2927       UseMI.RemoveOperand(
2928           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2929 
2930       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2931           Opc == AMDGPU::V_MAC_F16_e64 ||
2932           Opc == AMDGPU::V_FMAC_F32_e64 ||
2933           Opc == AMDGPU::V_FMAC_F16_e64)
2934         UseMI.untieRegOperand(
2935             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2936 
2937       // ChangingToImmediate adds Src2 back to the instruction.
2938       Src2->ChangeToImmediate(Imm);
2939 
2940       // These come before src2.
2941       removeModOperands(UseMI);
2942       UseMI.setDesc(get(NewOpc));
2943       // It might happen that UseMI was commuted
2944       // and we now have SGPR as SRC1. If so 2 inlined
2945       // constant and SGPR are illegal.
2946       legalizeOperands(UseMI);
2947 
2948       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2949       if (DeleteDef)
2950         DefMI.eraseFromParent();
2951 
2952       return true;
2953     }
2954   }
2955 
2956   return false;
2957 }
2958 
2959 static bool
2960 memOpsHaveSameBaseOperands(ArrayRef<const MachineOperand *> BaseOps1,
2961                            ArrayRef<const MachineOperand *> BaseOps2) {
2962   if (BaseOps1.size() != BaseOps2.size())
2963     return false;
2964   for (size_t I = 0, E = BaseOps1.size(); I < E; ++I) {
2965     if (!BaseOps1[I]->isIdenticalTo(*BaseOps2[I]))
2966       return false;
2967   }
2968   return true;
2969 }
2970 
2971 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
2972                                 int WidthB, int OffsetB) {
2973   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
2974   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
2975   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
2976   return LowOffset + LowWidth <= HighOffset;
2977 }
2978 
2979 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(const MachineInstr &MIa,
2980                                                const MachineInstr &MIb) const {
2981   SmallVector<const MachineOperand *, 4> BaseOps0, BaseOps1;
2982   int64_t Offset0, Offset1;
2983   unsigned Dummy0, Dummy1;
2984   bool Offset0IsScalable, Offset1IsScalable;
2985   if (!getMemOperandsWithOffsetWidth(MIa, BaseOps0, Offset0, Offset0IsScalable,
2986                                      Dummy0, &RI) ||
2987       !getMemOperandsWithOffsetWidth(MIb, BaseOps1, Offset1, Offset1IsScalable,
2988                                      Dummy1, &RI))
2989     return false;
2990 
2991   if (!memOpsHaveSameBaseOperands(BaseOps0, BaseOps1))
2992     return false;
2993 
2994   if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
2995     // FIXME: Handle ds_read2 / ds_write2.
2996     return false;
2997   }
2998   unsigned Width0 = MIa.memoperands().front()->getSize();
2999   unsigned Width1 = MIb.memoperands().front()->getSize();
3000   return offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1);
3001 }
3002 
3003 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
3004                                                   const MachineInstr &MIb) const {
3005   assert(MIa.mayLoadOrStore() &&
3006          "MIa must load from or modify a memory location");
3007   assert(MIb.mayLoadOrStore() &&
3008          "MIb must load from or modify a memory location");
3009 
3010   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
3011     return false;
3012 
3013   // XXX - Can we relax this between address spaces?
3014   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
3015     return false;
3016 
3017   // TODO: Should we check the address space from the MachineMemOperand? That
3018   // would allow us to distinguish objects we know don't alias based on the
3019   // underlying address space, even if it was lowered to a different one,
3020   // e.g. private accesses lowered to use MUBUF instructions on a scratch
3021   // buffer.
3022   if (isDS(MIa)) {
3023     if (isDS(MIb))
3024       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3025 
3026     return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
3027   }
3028 
3029   if (isMUBUF(MIa) || isMTBUF(MIa)) {
3030     if (isMUBUF(MIb) || isMTBUF(MIb))
3031       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3032 
3033     return !isFLAT(MIb) && !isSMRD(MIb);
3034   }
3035 
3036   if (isSMRD(MIa)) {
3037     if (isSMRD(MIb))
3038       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3039 
3040     return !isFLAT(MIb) && !isMUBUF(MIb) && !isMTBUF(MIb);
3041   }
3042 
3043   if (isFLAT(MIa)) {
3044     if (isFLAT(MIb))
3045       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3046 
3047     return false;
3048   }
3049 
3050   return false;
3051 }
3052 
3053 static int64_t getFoldableImm(const MachineOperand* MO) {
3054   if (!MO->isReg())
3055     return false;
3056   const MachineFunction *MF = MO->getParent()->getParent()->getParent();
3057   const MachineRegisterInfo &MRI = MF->getRegInfo();
3058   auto Def = MRI.getUniqueVRegDef(MO->getReg());
3059   if (Def && Def->getOpcode() == AMDGPU::V_MOV_B32_e32 &&
3060       Def->getOperand(1).isImm())
3061     return Def->getOperand(1).getImm();
3062   return AMDGPU::NoRegister;
3063 }
3064 
3065 static void updateLiveVariables(LiveVariables *LV, MachineInstr &MI,
3066                                 MachineInstr &NewMI) {
3067   if (LV) {
3068     unsigned NumOps = MI.getNumOperands();
3069     for (unsigned I = 1; I < NumOps; ++I) {
3070       MachineOperand &Op = MI.getOperand(I);
3071       if (Op.isReg() && Op.isKill())
3072         LV->replaceKillInstruction(Op.getReg(), MI, NewMI);
3073     }
3074   }
3075 }
3076 
3077 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
3078                                                  MachineInstr &MI,
3079                                                  LiveVariables *LV) const {
3080   unsigned Opc = MI.getOpcode();
3081   bool IsF16 = false;
3082   bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F32_e64 ||
3083                Opc == AMDGPU::V_FMAC_F16_e32 || Opc == AMDGPU::V_FMAC_F16_e64 ||
3084                Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64;
3085   bool IsF64 = Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64;
3086 
3087   switch (Opc) {
3088   default:
3089     return nullptr;
3090   case AMDGPU::V_MAC_F16_e64:
3091   case AMDGPU::V_FMAC_F16_e64:
3092     IsF16 = true;
3093     LLVM_FALLTHROUGH;
3094   case AMDGPU::V_MAC_F32_e64:
3095   case AMDGPU::V_FMAC_F32_e64:
3096   case AMDGPU::V_FMAC_F64_e64:
3097     break;
3098   case AMDGPU::V_MAC_F16_e32:
3099   case AMDGPU::V_FMAC_F16_e32:
3100     IsF16 = true;
3101     LLVM_FALLTHROUGH;
3102   case AMDGPU::V_MAC_F32_e32:
3103   case AMDGPU::V_FMAC_F32_e32:
3104   case AMDGPU::V_FMAC_F64_e32: {
3105     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
3106                                              AMDGPU::OpName::src0);
3107     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
3108     if (!Src0->isReg() && !Src0->isImm())
3109       return nullptr;
3110 
3111     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
3112       return nullptr;
3113 
3114     break;
3115   }
3116   }
3117 
3118   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
3119   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
3120   const MachineOperand *Src0Mods =
3121     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
3122   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3123   const MachineOperand *Src1Mods =
3124     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
3125   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3126   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
3127   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
3128   MachineInstrBuilder MIB;
3129 
3130   if (!Src0Mods && !Src1Mods && !Clamp && !Omod && !IsF64 &&
3131       // If we have an SGPR input, we will violate the constant bus restriction.
3132       (ST.getConstantBusLimit(Opc) > 1 || !Src0->isReg() ||
3133        !RI.isSGPRReg(MBB->getParent()->getRegInfo(), Src0->getReg()))) {
3134     if (auto Imm = getFoldableImm(Src2)) {
3135       unsigned NewOpc =
3136           IsFMA ? (IsF16 ? AMDGPU::V_FMAAK_F16 : AMDGPU::V_FMAAK_F32)
3137                 : (IsF16 ? AMDGPU::V_MADAK_F16 : AMDGPU::V_MADAK_F32);
3138       if (pseudoToMCOpcode(NewOpc) != -1) {
3139         MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3140                   .add(*Dst)
3141                   .add(*Src0)
3142                   .add(*Src1)
3143                   .addImm(Imm);
3144         updateLiveVariables(LV, MI, *MIB);
3145         return MIB;
3146       }
3147     }
3148     unsigned NewOpc = IsFMA
3149                           ? (IsF16 ? AMDGPU::V_FMAMK_F16 : AMDGPU::V_FMAMK_F32)
3150                           : (IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32);
3151     if (auto Imm = getFoldableImm(Src1)) {
3152       if (pseudoToMCOpcode(NewOpc) != -1) {
3153         MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3154                   .add(*Dst)
3155                   .add(*Src0)
3156                   .addImm(Imm)
3157                   .add(*Src2);
3158         updateLiveVariables(LV, MI, *MIB);
3159         return MIB;
3160       }
3161     }
3162     if (auto Imm = getFoldableImm(Src0)) {
3163       if (pseudoToMCOpcode(NewOpc) != -1 &&
3164           isOperandLegal(
3165               MI, AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::src0),
3166               Src1)) {
3167         MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3168                   .add(*Dst)
3169                   .add(*Src1)
3170                   .addImm(Imm)
3171                   .add(*Src2);
3172         updateLiveVariables(LV, MI, *MIB);
3173         return MIB;
3174       }
3175     }
3176   }
3177 
3178   unsigned NewOpc = IsFMA ? (IsF16 ? AMDGPU::V_FMA_F16_e64
3179                                    : IsF64 ? AMDGPU::V_FMA_F64_e64
3180                                            : AMDGPU::V_FMA_F32_e64)
3181                           : (IsF16 ? AMDGPU::V_MAD_F16_e64 : AMDGPU::V_MAD_F32_e64);
3182   if (pseudoToMCOpcode(NewOpc) == -1)
3183     return nullptr;
3184 
3185   MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3186             .add(*Dst)
3187             .addImm(Src0Mods ? Src0Mods->getImm() : 0)
3188             .add(*Src0)
3189             .addImm(Src1Mods ? Src1Mods->getImm() : 0)
3190             .add(*Src1)
3191             .addImm(0) // Src mods
3192             .add(*Src2)
3193             .addImm(Clamp ? Clamp->getImm() : 0)
3194             .addImm(Omod ? Omod->getImm() : 0);
3195   updateLiveVariables(LV, MI, *MIB);
3196   return MIB;
3197 }
3198 
3199 // It's not generally safe to move VALU instructions across these since it will
3200 // start using the register as a base index rather than directly.
3201 // XXX - Why isn't hasSideEffects sufficient for these?
3202 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
3203   switch (MI.getOpcode()) {
3204   case AMDGPU::S_SET_GPR_IDX_ON:
3205   case AMDGPU::S_SET_GPR_IDX_MODE:
3206   case AMDGPU::S_SET_GPR_IDX_OFF:
3207     return true;
3208   default:
3209     return false;
3210   }
3211 }
3212 
3213 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
3214                                        const MachineBasicBlock *MBB,
3215                                        const MachineFunction &MF) const {
3216   // Skipping the check for SP writes in the base implementation. The reason it
3217   // was added was apparently due to compile time concerns.
3218   //
3219   // TODO: Do we really want this barrier? It triggers unnecessary hazard nops
3220   // but is probably avoidable.
3221 
3222   // Copied from base implementation.
3223   // Terminators and labels can't be scheduled around.
3224   if (MI.isTerminator() || MI.isPosition())
3225     return true;
3226 
3227   // INLINEASM_BR can jump to another block
3228   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
3229     return true;
3230 
3231   // Target-independent instructions do not have an implicit-use of EXEC, even
3232   // when they operate on VGPRs. Treating EXEC modifications as scheduling
3233   // boundaries prevents incorrect movements of such instructions.
3234   return MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
3235          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
3236          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
3237          changesVGPRIndexingMode(MI);
3238 }
3239 
3240 bool SIInstrInfo::isAlwaysGDS(uint16_t Opcode) const {
3241   return Opcode == AMDGPU::DS_ORDERED_COUNT ||
3242          Opcode == AMDGPU::DS_GWS_INIT ||
3243          Opcode == AMDGPU::DS_GWS_SEMA_V ||
3244          Opcode == AMDGPU::DS_GWS_SEMA_BR ||
3245          Opcode == AMDGPU::DS_GWS_SEMA_P ||
3246          Opcode == AMDGPU::DS_GWS_SEMA_RELEASE_ALL ||
3247          Opcode == AMDGPU::DS_GWS_BARRIER;
3248 }
3249 
3250 bool SIInstrInfo::modifiesModeRegister(const MachineInstr &MI) {
3251   // Skip the full operand and register alias search modifiesRegister
3252   // does. There's only a handful of instructions that touch this, it's only an
3253   // implicit def, and doesn't alias any other registers.
3254   if (const MCPhysReg *ImpDef = MI.getDesc().getImplicitDefs()) {
3255     for (; ImpDef && *ImpDef; ++ImpDef) {
3256       if (*ImpDef == AMDGPU::MODE)
3257         return true;
3258     }
3259   }
3260 
3261   return false;
3262 }
3263 
3264 bool SIInstrInfo::hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const {
3265   unsigned Opcode = MI.getOpcode();
3266 
3267   if (MI.mayStore() && isSMRD(MI))
3268     return true; // scalar store or atomic
3269 
3270   // This will terminate the function when other lanes may need to continue.
3271   if (MI.isReturn())
3272     return true;
3273 
3274   // These instructions cause shader I/O that may cause hardware lockups
3275   // when executed with an empty EXEC mask.
3276   //
3277   // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
3278   //       EXEC = 0, but checking for that case here seems not worth it
3279   //       given the typical code patterns.
3280   if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
3281       isEXP(Opcode) ||
3282       Opcode == AMDGPU::DS_ORDERED_COUNT || Opcode == AMDGPU::S_TRAP ||
3283       Opcode == AMDGPU::DS_GWS_INIT || Opcode == AMDGPU::DS_GWS_BARRIER)
3284     return true;
3285 
3286   if (MI.isCall() || MI.isInlineAsm())
3287     return true; // conservative assumption
3288 
3289   // A mode change is a scalar operation that influences vector instructions.
3290   if (modifiesModeRegister(MI))
3291     return true;
3292 
3293   // These are like SALU instructions in terms of effects, so it's questionable
3294   // whether we should return true for those.
3295   //
3296   // However, executing them with EXEC = 0 causes them to operate on undefined
3297   // data, which we avoid by returning true here.
3298   if (Opcode == AMDGPU::V_READFIRSTLANE_B32 ||
3299       Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32)
3300     return true;
3301 
3302   return false;
3303 }
3304 
3305 bool SIInstrInfo::mayReadEXEC(const MachineRegisterInfo &MRI,
3306                               const MachineInstr &MI) const {
3307   if (MI.isMetaInstruction())
3308     return false;
3309 
3310   // This won't read exec if this is an SGPR->SGPR copy.
3311   if (MI.isCopyLike()) {
3312     if (!RI.isSGPRReg(MRI, MI.getOperand(0).getReg()))
3313       return true;
3314 
3315     // Make sure this isn't copying exec as a normal operand
3316     return MI.readsRegister(AMDGPU::EXEC, &RI);
3317   }
3318 
3319   // Make a conservative assumption about the callee.
3320   if (MI.isCall())
3321     return true;
3322 
3323   // Be conservative with any unhandled generic opcodes.
3324   if (!isTargetSpecificOpcode(MI.getOpcode()))
3325     return true;
3326 
3327   return !isSALU(MI) || MI.readsRegister(AMDGPU::EXEC, &RI);
3328 }
3329 
3330 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
3331   switch (Imm.getBitWidth()) {
3332   case 1: // This likely will be a condition code mask.
3333     return true;
3334 
3335   case 32:
3336     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
3337                                         ST.hasInv2PiInlineImm());
3338   case 64:
3339     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
3340                                         ST.hasInv2PiInlineImm());
3341   case 16:
3342     return ST.has16BitInsts() &&
3343            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
3344                                         ST.hasInv2PiInlineImm());
3345   default:
3346     llvm_unreachable("invalid bitwidth");
3347   }
3348 }
3349 
3350 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
3351                                    uint8_t OperandType) const {
3352   if (!MO.isImm() ||
3353       OperandType < AMDGPU::OPERAND_SRC_FIRST ||
3354       OperandType > AMDGPU::OPERAND_SRC_LAST)
3355     return false;
3356 
3357   // MachineOperand provides no way to tell the true operand size, since it only
3358   // records a 64-bit value. We need to know the size to determine if a 32-bit
3359   // floating point immediate bit pattern is legal for an integer immediate. It
3360   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
3361 
3362   int64_t Imm = MO.getImm();
3363   switch (OperandType) {
3364   case AMDGPU::OPERAND_REG_IMM_INT32:
3365   case AMDGPU::OPERAND_REG_IMM_FP32:
3366   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3367   case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3368   case AMDGPU::OPERAND_REG_IMM_V2FP32:
3369   case AMDGPU::OPERAND_REG_INLINE_C_V2FP32:
3370   case AMDGPU::OPERAND_REG_IMM_V2INT32:
3371   case AMDGPU::OPERAND_REG_INLINE_C_V2INT32:
3372   case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3373   case AMDGPU::OPERAND_REG_INLINE_AC_FP32: {
3374     int32_t Trunc = static_cast<int32_t>(Imm);
3375     return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
3376   }
3377   case AMDGPU::OPERAND_REG_IMM_INT64:
3378   case AMDGPU::OPERAND_REG_IMM_FP64:
3379   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3380   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3381   case AMDGPU::OPERAND_REG_INLINE_AC_FP64:
3382     return AMDGPU::isInlinableLiteral64(MO.getImm(),
3383                                         ST.hasInv2PiInlineImm());
3384   case AMDGPU::OPERAND_REG_IMM_INT16:
3385   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3386   case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3387     // We would expect inline immediates to not be concerned with an integer/fp
3388     // distinction. However, in the case of 16-bit integer operations, the
3389     // "floating point" values appear to not work. It seems read the low 16-bits
3390     // of 32-bit immediates, which happens to always work for the integer
3391     // values.
3392     //
3393     // See llvm bugzilla 46302.
3394     //
3395     // TODO: Theoretically we could use op-sel to use the high bits of the
3396     // 32-bit FP values.
3397     return AMDGPU::isInlinableIntLiteral(Imm);
3398   case AMDGPU::OPERAND_REG_IMM_V2INT16:
3399   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
3400   case AMDGPU::OPERAND_REG_INLINE_AC_V2INT16:
3401     // This suffers the same problem as the scalar 16-bit cases.
3402     return AMDGPU::isInlinableIntLiteralV216(Imm);
3403   case AMDGPU::OPERAND_REG_IMM_FP16:
3404   case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3405   case AMDGPU::OPERAND_REG_INLINE_AC_FP16: {
3406     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
3407       // A few special case instructions have 16-bit operands on subtargets
3408       // where 16-bit instructions are not legal.
3409       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
3410       // constants in these cases
3411       int16_t Trunc = static_cast<int16_t>(Imm);
3412       return ST.has16BitInsts() &&
3413              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
3414     }
3415 
3416     return false;
3417   }
3418   case AMDGPU::OPERAND_REG_IMM_V2FP16:
3419   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
3420   case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: {
3421     uint32_t Trunc = static_cast<uint32_t>(Imm);
3422     return AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
3423   }
3424   default:
3425     llvm_unreachable("invalid bitwidth");
3426   }
3427 }
3428 
3429 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
3430                                         const MCOperandInfo &OpInfo) const {
3431   switch (MO.getType()) {
3432   case MachineOperand::MO_Register:
3433     return false;
3434   case MachineOperand::MO_Immediate:
3435     return !isInlineConstant(MO, OpInfo);
3436   case MachineOperand::MO_FrameIndex:
3437   case MachineOperand::MO_MachineBasicBlock:
3438   case MachineOperand::MO_ExternalSymbol:
3439   case MachineOperand::MO_GlobalAddress:
3440   case MachineOperand::MO_MCSymbol:
3441     return true;
3442   default:
3443     llvm_unreachable("unexpected operand type");
3444   }
3445 }
3446 
3447 static bool compareMachineOp(const MachineOperand &Op0,
3448                              const MachineOperand &Op1) {
3449   if (Op0.getType() != Op1.getType())
3450     return false;
3451 
3452   switch (Op0.getType()) {
3453   case MachineOperand::MO_Register:
3454     return Op0.getReg() == Op1.getReg();
3455   case MachineOperand::MO_Immediate:
3456     return Op0.getImm() == Op1.getImm();
3457   default:
3458     llvm_unreachable("Didn't expect to be comparing these operand types");
3459   }
3460 }
3461 
3462 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
3463                                     const MachineOperand &MO) const {
3464   const MCInstrDesc &InstDesc = MI.getDesc();
3465   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo];
3466 
3467   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
3468 
3469   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
3470     return true;
3471 
3472   if (OpInfo.RegClass < 0)
3473     return false;
3474 
3475   if (MO.isImm() && isInlineConstant(MO, OpInfo)) {
3476     if (isMAI(MI) && ST.hasMFMAInlineLiteralBug() &&
3477         OpNo ==(unsigned)AMDGPU::getNamedOperandIdx(MI.getOpcode(),
3478                                                     AMDGPU::OpName::src2))
3479       return false;
3480     return RI.opCanUseInlineConstant(OpInfo.OperandType);
3481   }
3482 
3483   if (!RI.opCanUseLiteralConstant(OpInfo.OperandType))
3484     return false;
3485 
3486   if (!isVOP3(MI) || !AMDGPU::isSISrcOperand(InstDesc, OpNo))
3487     return true;
3488 
3489   return ST.hasVOP3Literal();
3490 }
3491 
3492 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
3493   // GFX90A does not have V_MUL_LEGACY_F32_e32.
3494   if (Opcode == AMDGPU::V_MUL_LEGACY_F32_e64 && ST.hasGFX90AInsts())
3495     return false;
3496 
3497   int Op32 = AMDGPU::getVOPe32(Opcode);
3498   if (Op32 == -1)
3499     return false;
3500 
3501   return pseudoToMCOpcode(Op32) != -1;
3502 }
3503 
3504 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
3505   // The src0_modifier operand is present on all instructions
3506   // that have modifiers.
3507 
3508   return AMDGPU::getNamedOperandIdx(Opcode,
3509                                     AMDGPU::OpName::src0_modifiers) != -1;
3510 }
3511 
3512 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
3513                                   unsigned OpName) const {
3514   const MachineOperand *Mods = getNamedOperand(MI, OpName);
3515   return Mods && Mods->getImm();
3516 }
3517 
3518 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
3519   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
3520          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
3521          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
3522          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
3523          hasModifiersSet(MI, AMDGPU::OpName::omod);
3524 }
3525 
3526 bool SIInstrInfo::canShrink(const MachineInstr &MI,
3527                             const MachineRegisterInfo &MRI) const {
3528   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3529   // Can't shrink instruction with three operands.
3530   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
3531   // a special case for it.  It can only be shrunk if the third operand
3532   // is vcc, and src0_modifiers and src1_modifiers are not set.
3533   // We should handle this the same way we handle vopc, by addding
3534   // a register allocation hint pre-regalloc and then do the shrinking
3535   // post-regalloc.
3536   if (Src2) {
3537     switch (MI.getOpcode()) {
3538       default: return false;
3539 
3540       case AMDGPU::V_ADDC_U32_e64:
3541       case AMDGPU::V_SUBB_U32_e64:
3542       case AMDGPU::V_SUBBREV_U32_e64: {
3543         const MachineOperand *Src1
3544           = getNamedOperand(MI, AMDGPU::OpName::src1);
3545         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
3546           return false;
3547         // Additional verification is needed for sdst/src2.
3548         return true;
3549       }
3550       case AMDGPU::V_MAC_F32_e64:
3551       case AMDGPU::V_MAC_F16_e64:
3552       case AMDGPU::V_FMAC_F32_e64:
3553       case AMDGPU::V_FMAC_F16_e64:
3554       case AMDGPU::V_FMAC_F64_e64:
3555         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
3556             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
3557           return false;
3558         break;
3559 
3560       case AMDGPU::V_CNDMASK_B32_e64:
3561         break;
3562     }
3563   }
3564 
3565   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3566   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
3567                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
3568     return false;
3569 
3570   // We don't need to check src0, all input types are legal, so just make sure
3571   // src0 isn't using any modifiers.
3572   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
3573     return false;
3574 
3575   // Can it be shrunk to a valid 32 bit opcode?
3576   if (!hasVALU32BitEncoding(MI.getOpcode()))
3577     return false;
3578 
3579   // Check output modifiers
3580   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
3581          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
3582 }
3583 
3584 // Set VCC operand with all flags from \p Orig, except for setting it as
3585 // implicit.
3586 static void copyFlagsToImplicitVCC(MachineInstr &MI,
3587                                    const MachineOperand &Orig) {
3588 
3589   for (MachineOperand &Use : MI.implicit_operands()) {
3590     if (Use.isUse() &&
3591         (Use.getReg() == AMDGPU::VCC || Use.getReg() == AMDGPU::VCC_LO)) {
3592       Use.setIsUndef(Orig.isUndef());
3593       Use.setIsKill(Orig.isKill());
3594       return;
3595     }
3596   }
3597 }
3598 
3599 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
3600                                            unsigned Op32) const {
3601   MachineBasicBlock *MBB = MI.getParent();;
3602   MachineInstrBuilder Inst32 =
3603     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32))
3604     .setMIFlags(MI.getFlags());
3605 
3606   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
3607   // For VOPC instructions, this is replaced by an implicit def of vcc.
3608   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
3609   if (Op32DstIdx != -1) {
3610     // dst
3611     Inst32.add(MI.getOperand(0));
3612   } else {
3613     assert(((MI.getOperand(0).getReg() == AMDGPU::VCC) ||
3614             (MI.getOperand(0).getReg() == AMDGPU::VCC_LO)) &&
3615            "Unexpected case");
3616   }
3617 
3618   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
3619 
3620   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3621   if (Src1)
3622     Inst32.add(*Src1);
3623 
3624   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3625 
3626   if (Src2) {
3627     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
3628     if (Op32Src2Idx != -1) {
3629       Inst32.add(*Src2);
3630     } else {
3631       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
3632       // replaced with an implicit read of vcc or vcc_lo. The implicit read
3633       // of vcc was already added during the initial BuildMI, but we
3634       // 1) may need to change vcc to vcc_lo to preserve the original register
3635       // 2) have to preserve the original flags.
3636       fixImplicitOperands(*Inst32);
3637       copyFlagsToImplicitVCC(*Inst32, *Src2);
3638     }
3639   }
3640 
3641   return Inst32;
3642 }
3643 
3644 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
3645                                   const MachineOperand &MO,
3646                                   const MCOperandInfo &OpInfo) const {
3647   // Literal constants use the constant bus.
3648   //if (isLiteralConstantLike(MO, OpInfo))
3649   // return true;
3650   if (MO.isImm())
3651     return !isInlineConstant(MO, OpInfo);
3652 
3653   if (!MO.isReg())
3654     return true; // Misc other operands like FrameIndex
3655 
3656   if (!MO.isUse())
3657     return false;
3658 
3659   if (MO.getReg().isVirtual())
3660     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
3661 
3662   // Null is free
3663   if (MO.getReg() == AMDGPU::SGPR_NULL)
3664     return false;
3665 
3666   // SGPRs use the constant bus
3667   if (MO.isImplicit()) {
3668     return MO.getReg() == AMDGPU::M0 ||
3669            MO.getReg() == AMDGPU::VCC ||
3670            MO.getReg() == AMDGPU::VCC_LO;
3671   } else {
3672     return AMDGPU::SReg_32RegClass.contains(MO.getReg()) ||
3673            AMDGPU::SReg_64RegClass.contains(MO.getReg());
3674   }
3675 }
3676 
3677 static Register findImplicitSGPRRead(const MachineInstr &MI) {
3678   for (const MachineOperand &MO : MI.implicit_operands()) {
3679     // We only care about reads.
3680     if (MO.isDef())
3681       continue;
3682 
3683     switch (MO.getReg()) {
3684     case AMDGPU::VCC:
3685     case AMDGPU::VCC_LO:
3686     case AMDGPU::VCC_HI:
3687     case AMDGPU::M0:
3688     case AMDGPU::FLAT_SCR:
3689       return MO.getReg();
3690 
3691     default:
3692       break;
3693     }
3694   }
3695 
3696   return AMDGPU::NoRegister;
3697 }
3698 
3699 static bool shouldReadExec(const MachineInstr &MI) {
3700   if (SIInstrInfo::isVALU(MI)) {
3701     switch (MI.getOpcode()) {
3702     case AMDGPU::V_READLANE_B32:
3703     case AMDGPU::V_WRITELANE_B32:
3704       return false;
3705     }
3706 
3707     return true;
3708   }
3709 
3710   if (MI.isPreISelOpcode() ||
3711       SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
3712       SIInstrInfo::isSALU(MI) ||
3713       SIInstrInfo::isSMRD(MI))
3714     return false;
3715 
3716   return true;
3717 }
3718 
3719 static bool isSubRegOf(const SIRegisterInfo &TRI,
3720                        const MachineOperand &SuperVec,
3721                        const MachineOperand &SubReg) {
3722   if (SubReg.getReg().isPhysical())
3723     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
3724 
3725   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
3726          SubReg.getReg() == SuperVec.getReg();
3727 }
3728 
3729 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
3730                                     StringRef &ErrInfo) const {
3731   uint16_t Opcode = MI.getOpcode();
3732   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
3733     return true;
3734 
3735   const MachineFunction *MF = MI.getParent()->getParent();
3736   const MachineRegisterInfo &MRI = MF->getRegInfo();
3737 
3738   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
3739   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
3740   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
3741 
3742   // Make sure the number of operands is correct.
3743   const MCInstrDesc &Desc = get(Opcode);
3744   if (!Desc.isVariadic() &&
3745       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
3746     ErrInfo = "Instruction has wrong number of operands.";
3747     return false;
3748   }
3749 
3750   if (MI.isInlineAsm()) {
3751     // Verify register classes for inlineasm constraints.
3752     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
3753          I != E; ++I) {
3754       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
3755       if (!RC)
3756         continue;
3757 
3758       const MachineOperand &Op = MI.getOperand(I);
3759       if (!Op.isReg())
3760         continue;
3761 
3762       Register Reg = Op.getReg();
3763       if (!Reg.isVirtual() && !RC->contains(Reg)) {
3764         ErrInfo = "inlineasm operand has incorrect register class.";
3765         return false;
3766       }
3767     }
3768 
3769     return true;
3770   }
3771 
3772   if (isMIMG(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
3773     ErrInfo = "missing memory operand from MIMG instruction.";
3774     return false;
3775   }
3776 
3777   // Make sure the register classes are correct.
3778   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
3779     if (MI.getOperand(i).isFPImm()) {
3780       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
3781                 "all fp values to integers.";
3782       return false;
3783     }
3784 
3785     int RegClass = Desc.OpInfo[i].RegClass;
3786 
3787     switch (Desc.OpInfo[i].OperandType) {
3788     case MCOI::OPERAND_REGISTER:
3789       if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
3790         ErrInfo = "Illegal immediate value for operand.";
3791         return false;
3792       }
3793       break;
3794     case AMDGPU::OPERAND_REG_IMM_INT32:
3795     case AMDGPU::OPERAND_REG_IMM_FP32:
3796       break;
3797     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3798     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3799     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3800     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3801     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3802     case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3803     case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3804     case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
3805     case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3806     case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
3807     case AMDGPU::OPERAND_REG_INLINE_AC_FP64: {
3808       const MachineOperand &MO = MI.getOperand(i);
3809       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
3810         ErrInfo = "Illegal immediate value for operand.";
3811         return false;
3812       }
3813       break;
3814     }
3815     case MCOI::OPERAND_IMMEDIATE:
3816     case AMDGPU::OPERAND_KIMM32:
3817       // Check if this operand is an immediate.
3818       // FrameIndex operands will be replaced by immediates, so they are
3819       // allowed.
3820       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
3821         ErrInfo = "Expected immediate, but got non-immediate";
3822         return false;
3823       }
3824       LLVM_FALLTHROUGH;
3825     default:
3826       continue;
3827     }
3828 
3829     if (!MI.getOperand(i).isReg())
3830       continue;
3831 
3832     if (RegClass != -1) {
3833       Register Reg = MI.getOperand(i).getReg();
3834       if (Reg == AMDGPU::NoRegister || Reg.isVirtual())
3835         continue;
3836 
3837       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
3838       if (!RC->contains(Reg)) {
3839         ErrInfo = "Operand has incorrect register class.";
3840         return false;
3841       }
3842     }
3843   }
3844 
3845   // Verify SDWA
3846   if (isSDWA(MI)) {
3847     if (!ST.hasSDWA()) {
3848       ErrInfo = "SDWA is not supported on this target";
3849       return false;
3850     }
3851 
3852     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
3853 
3854     const int OpIndicies[] = { DstIdx, Src0Idx, Src1Idx, Src2Idx };
3855 
3856     for (int OpIdx: OpIndicies) {
3857       if (OpIdx == -1)
3858         continue;
3859       const MachineOperand &MO = MI.getOperand(OpIdx);
3860 
3861       if (!ST.hasSDWAScalar()) {
3862         // Only VGPRS on VI
3863         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
3864           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
3865           return false;
3866         }
3867       } else {
3868         // No immediates on GFX9
3869         if (!MO.isReg()) {
3870           ErrInfo =
3871             "Only reg allowed as operands in SDWA instructions on GFX9+";
3872           return false;
3873         }
3874       }
3875     }
3876 
3877     if (!ST.hasSDWAOmod()) {
3878       // No omod allowed on VI
3879       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
3880       if (OMod != nullptr &&
3881         (!OMod->isImm() || OMod->getImm() != 0)) {
3882         ErrInfo = "OMod not allowed in SDWA instructions on VI";
3883         return false;
3884       }
3885     }
3886 
3887     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
3888     if (isVOPC(BasicOpcode)) {
3889       if (!ST.hasSDWASdst() && DstIdx != -1) {
3890         // Only vcc allowed as dst on VI for VOPC
3891         const MachineOperand &Dst = MI.getOperand(DstIdx);
3892         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
3893           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
3894           return false;
3895         }
3896       } else if (!ST.hasSDWAOutModsVOPC()) {
3897         // No clamp allowed on GFX9 for VOPC
3898         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
3899         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
3900           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
3901           return false;
3902         }
3903 
3904         // No omod allowed on GFX9 for VOPC
3905         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
3906         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
3907           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
3908           return false;
3909         }
3910       }
3911     }
3912 
3913     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
3914     if (DstUnused && DstUnused->isImm() &&
3915         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
3916       const MachineOperand &Dst = MI.getOperand(DstIdx);
3917       if (!Dst.isReg() || !Dst.isTied()) {
3918         ErrInfo = "Dst register should have tied register";
3919         return false;
3920       }
3921 
3922       const MachineOperand &TiedMO =
3923           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
3924       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
3925         ErrInfo =
3926             "Dst register should be tied to implicit use of preserved register";
3927         return false;
3928       } else if (TiedMO.getReg().isPhysical() &&
3929                  Dst.getReg() != TiedMO.getReg()) {
3930         ErrInfo = "Dst register should use same physical register as preserved";
3931         return false;
3932       }
3933     }
3934   }
3935 
3936   // Verify MIMG
3937   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
3938     // Ensure that the return type used is large enough for all the options
3939     // being used TFE/LWE require an extra result register.
3940     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
3941     if (DMask) {
3942       uint64_t DMaskImm = DMask->getImm();
3943       uint32_t RegCount =
3944           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
3945       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
3946       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
3947       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
3948 
3949       // Adjust for packed 16 bit values
3950       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
3951         RegCount >>= 1;
3952 
3953       // Adjust if using LWE or TFE
3954       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
3955         RegCount += 1;
3956 
3957       const uint32_t DstIdx =
3958           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
3959       const MachineOperand &Dst = MI.getOperand(DstIdx);
3960       if (Dst.isReg()) {
3961         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
3962         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
3963         if (RegCount > DstSize) {
3964           ErrInfo = "MIMG instruction returns too many registers for dst "
3965                     "register class";
3966           return false;
3967         }
3968       }
3969     }
3970   }
3971 
3972   // Verify VOP*. Ignore multiple sgpr operands on writelane.
3973   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
3974       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
3975     // Only look at the true operands. Only a real operand can use the constant
3976     // bus, and we don't want to check pseudo-operands like the source modifier
3977     // flags.
3978     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
3979 
3980     unsigned ConstantBusCount = 0;
3981     unsigned LiteralCount = 0;
3982 
3983     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
3984       ++ConstantBusCount;
3985 
3986     SmallVector<Register, 2> SGPRsUsed;
3987     Register SGPRUsed;
3988 
3989     for (int OpIdx : OpIndices) {
3990       if (OpIdx == -1)
3991         break;
3992       const MachineOperand &MO = MI.getOperand(OpIdx);
3993       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
3994         if (MO.isReg()) {
3995           SGPRUsed = MO.getReg();
3996           if (llvm::all_of(SGPRsUsed, [SGPRUsed](unsigned SGPR) {
3997                 return SGPRUsed != SGPR;
3998               })) {
3999             ++ConstantBusCount;
4000             SGPRsUsed.push_back(SGPRUsed);
4001           }
4002         } else {
4003           ++ConstantBusCount;
4004           ++LiteralCount;
4005         }
4006       }
4007     }
4008 
4009     SGPRUsed = findImplicitSGPRRead(MI);
4010     if (SGPRUsed != AMDGPU::NoRegister) {
4011       // Implicit uses may safely overlap true overands
4012       if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
4013             return !RI.regsOverlap(SGPRUsed, SGPR);
4014           })) {
4015         ++ConstantBusCount;
4016         SGPRsUsed.push_back(SGPRUsed);
4017       }
4018     }
4019 
4020     // v_writelane_b32 is an exception from constant bus restriction:
4021     // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
4022     if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
4023         Opcode != AMDGPU::V_WRITELANE_B32) {
4024       ErrInfo = "VOP* instruction violates constant bus restriction";
4025       return false;
4026     }
4027 
4028     if (isVOP3(MI) && LiteralCount) {
4029       if (!ST.hasVOP3Literal()) {
4030         ErrInfo = "VOP3 instruction uses literal";
4031         return false;
4032       }
4033       if (LiteralCount > 1) {
4034         ErrInfo = "VOP3 instruction uses more than one literal";
4035         return false;
4036       }
4037     }
4038   }
4039 
4040   // Special case for writelane - this can break the multiple constant bus rule,
4041   // but still can't use more than one SGPR register
4042   if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
4043     unsigned SGPRCount = 0;
4044     Register SGPRUsed = AMDGPU::NoRegister;
4045 
4046     for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx}) {
4047       if (OpIdx == -1)
4048         break;
4049 
4050       const MachineOperand &MO = MI.getOperand(OpIdx);
4051 
4052       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4053         if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
4054           if (MO.getReg() != SGPRUsed)
4055             ++SGPRCount;
4056           SGPRUsed = MO.getReg();
4057         }
4058       }
4059       if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
4060         ErrInfo = "WRITELANE instruction violates constant bus restriction";
4061         return false;
4062       }
4063     }
4064   }
4065 
4066   // Verify misc. restrictions on specific instructions.
4067   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
4068       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
4069     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4070     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4071     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
4072     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
4073       if (!compareMachineOp(Src0, Src1) &&
4074           !compareMachineOp(Src0, Src2)) {
4075         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
4076         return false;
4077       }
4078     }
4079     if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
4080          SISrcMods::ABS) ||
4081         (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
4082          SISrcMods::ABS) ||
4083         (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
4084          SISrcMods::ABS)) {
4085       ErrInfo = "ABS not allowed in VOP3B instructions";
4086       return false;
4087     }
4088   }
4089 
4090   if (isSOP2(MI) || isSOPC(MI)) {
4091     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4092     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4093     unsigned Immediates = 0;
4094 
4095     if (!Src0.isReg() &&
4096         !isInlineConstant(Src0, Desc.OpInfo[Src0Idx].OperandType))
4097       Immediates++;
4098     if (!Src1.isReg() &&
4099         !isInlineConstant(Src1, Desc.OpInfo[Src1Idx].OperandType))
4100       Immediates++;
4101 
4102     if (Immediates > 1) {
4103       ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
4104       return false;
4105     }
4106   }
4107 
4108   if (isSOPK(MI)) {
4109     auto Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
4110     if (Desc.isBranch()) {
4111       if (!Op->isMBB()) {
4112         ErrInfo = "invalid branch target for SOPK instruction";
4113         return false;
4114       }
4115     } else {
4116       uint64_t Imm = Op->getImm();
4117       if (sopkIsZext(MI)) {
4118         if (!isUInt<16>(Imm)) {
4119           ErrInfo = "invalid immediate for SOPK instruction";
4120           return false;
4121         }
4122       } else {
4123         if (!isInt<16>(Imm)) {
4124           ErrInfo = "invalid immediate for SOPK instruction";
4125           return false;
4126         }
4127       }
4128     }
4129   }
4130 
4131   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
4132       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
4133       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4134       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
4135     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4136                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
4137 
4138     const unsigned StaticNumOps = Desc.getNumOperands() +
4139       Desc.getNumImplicitUses();
4140     const unsigned NumImplicitOps = IsDst ? 2 : 1;
4141 
4142     // Allow additional implicit operands. This allows a fixup done by the post
4143     // RA scheduler where the main implicit operand is killed and implicit-defs
4144     // are added for sub-registers that remain live after this instruction.
4145     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
4146       ErrInfo = "missing implicit register operands";
4147       return false;
4148     }
4149 
4150     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4151     if (IsDst) {
4152       if (!Dst->isUse()) {
4153         ErrInfo = "v_movreld_b32 vdst should be a use operand";
4154         return false;
4155       }
4156 
4157       unsigned UseOpIdx;
4158       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
4159           UseOpIdx != StaticNumOps + 1) {
4160         ErrInfo = "movrel implicit operands should be tied";
4161         return false;
4162       }
4163     }
4164 
4165     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4166     const MachineOperand &ImpUse
4167       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
4168     if (!ImpUse.isReg() || !ImpUse.isUse() ||
4169         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
4170       ErrInfo = "src0 should be subreg of implicit vector use";
4171       return false;
4172     }
4173   }
4174 
4175   // Make sure we aren't losing exec uses in the td files. This mostly requires
4176   // being careful when using let Uses to try to add other use registers.
4177   if (shouldReadExec(MI)) {
4178     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
4179       ErrInfo = "VALU instruction does not implicitly read exec mask";
4180       return false;
4181     }
4182   }
4183 
4184   if (isSMRD(MI)) {
4185     if (MI.mayStore()) {
4186       // The register offset form of scalar stores may only use m0 as the
4187       // soffset register.
4188       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
4189       if (Soff && Soff->getReg() != AMDGPU::M0) {
4190         ErrInfo = "scalar stores must use m0 as offset register";
4191         return false;
4192       }
4193     }
4194   }
4195 
4196   if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
4197     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4198     if (Offset->getImm() != 0) {
4199       ErrInfo = "subtarget does not support offsets in flat instructions";
4200       return false;
4201     }
4202   }
4203 
4204   if (isMIMG(MI)) {
4205     const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
4206     if (DimOp) {
4207       int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
4208                                                  AMDGPU::OpName::vaddr0);
4209       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
4210       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
4211       const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4212           AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
4213       const AMDGPU::MIMGDimInfo *Dim =
4214           AMDGPU::getMIMGDimInfoByEncoding(DimOp->getImm());
4215 
4216       if (!Dim) {
4217         ErrInfo = "dim is out of range";
4218         return false;
4219       }
4220 
4221       bool IsA16 = false;
4222       if (ST.hasR128A16()) {
4223         const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
4224         IsA16 = R128A16->getImm() != 0;
4225       } else if (ST.hasGFX10A16()) {
4226         const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
4227         IsA16 = A16->getImm() != 0;
4228       }
4229 
4230       bool PackDerivatives = IsA16 || BaseOpcode->G16;
4231       bool IsNSA = SRsrcIdx - VAddr0Idx > 1;
4232 
4233       unsigned AddrWords = BaseOpcode->NumExtraArgs;
4234       unsigned AddrComponents = (BaseOpcode->Coordinates ? Dim->NumCoords : 0) +
4235                                 (BaseOpcode->LodOrClampOrMip ? 1 : 0);
4236       if (IsA16)
4237         AddrWords += (AddrComponents + 1) / 2;
4238       else
4239         AddrWords += AddrComponents;
4240 
4241       if (BaseOpcode->Gradients) {
4242         if (PackDerivatives)
4243           // There are two gradients per coordinate, we pack them separately.
4244           // For the 3d case, we get (dy/du, dx/du) (-, dz/du) (dy/dv, dx/dv) (-, dz/dv)
4245           AddrWords += (Dim->NumGradients / 2 + 1) / 2 * 2;
4246         else
4247           AddrWords += Dim->NumGradients;
4248       }
4249 
4250       unsigned VAddrWords;
4251       if (IsNSA) {
4252         VAddrWords = SRsrcIdx - VAddr0Idx;
4253       } else {
4254         const TargetRegisterClass *RC = getOpRegClass(MI, VAddr0Idx);
4255         VAddrWords = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 32;
4256         if (AddrWords > 8)
4257           AddrWords = 16;
4258         else if (AddrWords > 4)
4259           AddrWords = 8;
4260         else if (AddrWords == 4)
4261           AddrWords = 4;
4262         else if (AddrWords == 3)
4263           AddrWords = 3;
4264       }
4265 
4266       if (VAddrWords != AddrWords) {
4267         LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
4268                           << " but got " << VAddrWords << "\n");
4269         ErrInfo = "bad vaddr size";
4270         return false;
4271       }
4272     }
4273   }
4274 
4275   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
4276   if (DppCt) {
4277     using namespace AMDGPU::DPP;
4278 
4279     unsigned DC = DppCt->getImm();
4280     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
4281         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
4282         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
4283         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
4284         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
4285         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
4286         (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
4287       ErrInfo = "Invalid dpp_ctrl value";
4288       return false;
4289     }
4290     if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
4291         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4292       ErrInfo = "Invalid dpp_ctrl value: "
4293                 "wavefront shifts are not supported on GFX10+";
4294       return false;
4295     }
4296     if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
4297         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4298       ErrInfo = "Invalid dpp_ctrl value: "
4299                 "broadcasts are not supported on GFX10+";
4300       return false;
4301     }
4302     if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
4303         ST.getGeneration() < AMDGPUSubtarget::GFX10) {
4304       if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
4305           DC <= DppCtrl::ROW_NEWBCAST_LAST &&
4306           !ST.hasGFX90AInsts()) {
4307         ErrInfo = "Invalid dpp_ctrl value: "
4308                   "row_newbroadcast/row_share is not supported before "
4309                   "GFX90A/GFX10";
4310         return false;
4311       } else if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
4312         ErrInfo = "Invalid dpp_ctrl value: "
4313                   "row_share and row_xmask are not supported before GFX10";
4314         return false;
4315       }
4316     }
4317 
4318     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4319     int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
4320 
4321     if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
4322         ((DstIdx >= 0 &&
4323           Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64RegClassID) ||
4324         ((Src0Idx >= 0 &&
4325           Desc.OpInfo[Src0Idx].RegClass == AMDGPU::VReg_64RegClassID))) &&
4326         !AMDGPU::isLegal64BitDPPControl(DC)) {
4327       ErrInfo = "Invalid dpp_ctrl value: "
4328                 "64 bit dpp only support row_newbcast";
4329       return false;
4330     }
4331   }
4332 
4333   if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
4334     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4335     uint16_t DataNameIdx = isDS(Opcode) ? AMDGPU::OpName::data0
4336                                         : AMDGPU::OpName::vdata;
4337     const MachineOperand *Data = getNamedOperand(MI, DataNameIdx);
4338     const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
4339     if (Data && !Data->isReg())
4340       Data = nullptr;
4341 
4342     if (ST.hasGFX90AInsts()) {
4343       if (Dst && Data &&
4344           (RI.isAGPR(MRI, Dst->getReg()) != RI.isAGPR(MRI, Data->getReg()))) {
4345         ErrInfo = "Invalid register class: "
4346                   "vdata and vdst should be both VGPR or AGPR";
4347         return false;
4348       }
4349       if (Data && Data2 &&
4350           (RI.isAGPR(MRI, Data->getReg()) != RI.isAGPR(MRI, Data2->getReg()))) {
4351         ErrInfo = "Invalid register class: "
4352                   "both data operands should be VGPR or AGPR";
4353         return false;
4354       }
4355     } else {
4356       if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
4357           (Data && RI.isAGPR(MRI, Data->getReg())) ||
4358           (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
4359         ErrInfo = "Invalid register class: "
4360                   "agpr loads and stores not supported on this GPU";
4361         return false;
4362       }
4363     }
4364   }
4365 
4366   return true;
4367 }
4368 
4369 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
4370   switch (MI.getOpcode()) {
4371   default: return AMDGPU::INSTRUCTION_LIST_END;
4372   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
4373   case AMDGPU::COPY: return AMDGPU::COPY;
4374   case AMDGPU::PHI: return AMDGPU::PHI;
4375   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
4376   case AMDGPU::WQM: return AMDGPU::WQM;
4377   case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
4378   case AMDGPU::WWM: return AMDGPU::WWM;
4379   case AMDGPU::S_MOV_B32: {
4380     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4381     return MI.getOperand(1).isReg() ||
4382            RI.isAGPR(MRI, MI.getOperand(0).getReg()) ?
4383            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
4384   }
4385   case AMDGPU::S_ADD_I32:
4386     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
4387   case AMDGPU::S_ADDC_U32:
4388     return AMDGPU::V_ADDC_U32_e32;
4389   case AMDGPU::S_SUB_I32:
4390     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
4391     // FIXME: These are not consistently handled, and selected when the carry is
4392     // used.
4393   case AMDGPU::S_ADD_U32:
4394     return AMDGPU::V_ADD_CO_U32_e32;
4395   case AMDGPU::S_SUB_U32:
4396     return AMDGPU::V_SUB_CO_U32_e32;
4397   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
4398   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
4399   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
4400   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
4401   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
4402   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
4403   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
4404   case AMDGPU::S_XNOR_B32:
4405     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
4406   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
4407   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
4408   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
4409   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
4410   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
4411   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
4412   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
4413   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
4414   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
4415   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
4416   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
4417   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
4418   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
4419   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
4420   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
4421   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
4422   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
4423   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
4424   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
4425   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
4426   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
4427   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
4428   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
4429   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
4430   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
4431   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
4432   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
4433   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
4434   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
4435   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
4436   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
4437   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
4438   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
4439   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
4440   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
4441   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
4442   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
4443   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
4444   }
4445   llvm_unreachable(
4446       "Unexpected scalar opcode without corresponding vector one!");
4447 }
4448 
4449 static unsigned adjustAllocatableRegClass(const GCNSubtarget &ST,
4450                                           const MachineRegisterInfo &MRI,
4451                                           const MCInstrDesc &TID,
4452                                           unsigned RCID,
4453                                           bool IsAllocatable) {
4454   if ((IsAllocatable || !ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4455       (TID.mayLoad() || TID.mayStore() ||
4456       (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::MIMG)))) {
4457     switch (RCID) {
4458     case AMDGPU::AV_32RegClassID: return AMDGPU::VGPR_32RegClassID;
4459     case AMDGPU::AV_64RegClassID: return AMDGPU::VReg_64RegClassID;
4460     case AMDGPU::AV_96RegClassID: return AMDGPU::VReg_96RegClassID;
4461     case AMDGPU::AV_128RegClassID: return AMDGPU::VReg_128RegClassID;
4462     case AMDGPU::AV_160RegClassID: return AMDGPU::VReg_160RegClassID;
4463     default:
4464       break;
4465     }
4466   }
4467   return RCID;
4468 }
4469 
4470 const TargetRegisterClass *SIInstrInfo::getRegClass(const MCInstrDesc &TID,
4471     unsigned OpNum, const TargetRegisterInfo *TRI,
4472     const MachineFunction &MF)
4473   const {
4474   if (OpNum >= TID.getNumOperands())
4475     return nullptr;
4476   auto RegClass = TID.OpInfo[OpNum].RegClass;
4477   bool IsAllocatable = false;
4478   if (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::FLAT)) {
4479     // vdst and vdata should be both VGPR or AGPR, same for the DS instructions
4480     // with two data operands. Request register class constainted to VGPR only
4481     // of both operands present as Machine Copy Propagation can not check this
4482     // constraint and possibly other passes too.
4483     //
4484     // The check is limited to FLAT and DS because atomics in non-flat encoding
4485     // have their vdst and vdata tied to be the same register.
4486     const int VDstIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4487                                                    AMDGPU::OpName::vdst);
4488     const int DataIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4489         (TID.TSFlags & SIInstrFlags::DS) ? AMDGPU::OpName::data0
4490                                          : AMDGPU::OpName::vdata);
4491     if (DataIdx != -1) {
4492       IsAllocatable = VDstIdx != -1 ||
4493                       AMDGPU::getNamedOperandIdx(TID.Opcode,
4494                                                  AMDGPU::OpName::data1) != -1;
4495     }
4496   }
4497   RegClass = adjustAllocatableRegClass(ST, MF.getRegInfo(), TID, RegClass,
4498                                        IsAllocatable);
4499   return RI.getRegClass(RegClass);
4500 }
4501 
4502 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
4503                                                       unsigned OpNo) const {
4504   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4505   const MCInstrDesc &Desc = get(MI.getOpcode());
4506   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
4507       Desc.OpInfo[OpNo].RegClass == -1) {
4508     Register Reg = MI.getOperand(OpNo).getReg();
4509 
4510     if (Reg.isVirtual())
4511       return MRI.getRegClass(Reg);
4512     return RI.getPhysRegClass(Reg);
4513   }
4514 
4515   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
4516   RCID = adjustAllocatableRegClass(ST, MRI, Desc, RCID, true);
4517   return RI.getRegClass(RCID);
4518 }
4519 
4520 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
4521   MachineBasicBlock::iterator I = MI;
4522   MachineBasicBlock *MBB = MI.getParent();
4523   MachineOperand &MO = MI.getOperand(OpIdx);
4524   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4525   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
4526   const TargetRegisterClass *RC = RI.getRegClass(RCID);
4527   unsigned Size = RI.getRegSizeInBits(*RC);
4528   unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO : AMDGPU::V_MOV_B32_e32;
4529   if (MO.isReg())
4530     Opcode = AMDGPU::COPY;
4531   else if (RI.isSGPRClass(RC))
4532     Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
4533 
4534   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
4535   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
4536     VRC = &AMDGPU::VReg_64RegClass;
4537   else
4538     VRC = &AMDGPU::VGPR_32RegClass;
4539 
4540   Register Reg = MRI.createVirtualRegister(VRC);
4541   DebugLoc DL = MBB->findDebugLoc(I);
4542   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
4543   MO.ChangeToRegister(Reg, false);
4544 }
4545 
4546 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
4547                                          MachineRegisterInfo &MRI,
4548                                          MachineOperand &SuperReg,
4549                                          const TargetRegisterClass *SuperRC,
4550                                          unsigned SubIdx,
4551                                          const TargetRegisterClass *SubRC)
4552                                          const {
4553   MachineBasicBlock *MBB = MI->getParent();
4554   DebugLoc DL = MI->getDebugLoc();
4555   Register SubReg = MRI.createVirtualRegister(SubRC);
4556 
4557   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
4558     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4559       .addReg(SuperReg.getReg(), 0, SubIdx);
4560     return SubReg;
4561   }
4562 
4563   // Just in case the super register is itself a sub-register, copy it to a new
4564   // value so we don't need to worry about merging its subreg index with the
4565   // SubIdx passed to this function. The register coalescer should be able to
4566   // eliminate this extra copy.
4567   Register NewSuperReg = MRI.createVirtualRegister(SuperRC);
4568 
4569   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
4570     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
4571 
4572   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4573     .addReg(NewSuperReg, 0, SubIdx);
4574 
4575   return SubReg;
4576 }
4577 
4578 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
4579   MachineBasicBlock::iterator MII,
4580   MachineRegisterInfo &MRI,
4581   MachineOperand &Op,
4582   const TargetRegisterClass *SuperRC,
4583   unsigned SubIdx,
4584   const TargetRegisterClass *SubRC) const {
4585   if (Op.isImm()) {
4586     if (SubIdx == AMDGPU::sub0)
4587       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
4588     if (SubIdx == AMDGPU::sub1)
4589       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
4590 
4591     llvm_unreachable("Unhandled register index for immediate");
4592   }
4593 
4594   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
4595                                        SubIdx, SubRC);
4596   return MachineOperand::CreateReg(SubReg, false);
4597 }
4598 
4599 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
4600 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
4601   assert(Inst.getNumExplicitOperands() == 3);
4602   MachineOperand Op1 = Inst.getOperand(1);
4603   Inst.RemoveOperand(1);
4604   Inst.addOperand(Op1);
4605 }
4606 
4607 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
4608                                     const MCOperandInfo &OpInfo,
4609                                     const MachineOperand &MO) const {
4610   if (!MO.isReg())
4611     return false;
4612 
4613   Register Reg = MO.getReg();
4614 
4615   const TargetRegisterClass *DRC = RI.getRegClass(OpInfo.RegClass);
4616   if (Reg.isPhysical())
4617     return DRC->contains(Reg);
4618 
4619   const TargetRegisterClass *RC = MRI.getRegClass(Reg);
4620 
4621   if (MO.getSubReg()) {
4622     const MachineFunction *MF = MO.getParent()->getParent()->getParent();
4623     const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
4624     if (!SuperRC)
4625       return false;
4626 
4627     DRC = RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg());
4628     if (!DRC)
4629       return false;
4630   }
4631   return RC->hasSuperClassEq(DRC);
4632 }
4633 
4634 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
4635                                      const MCOperandInfo &OpInfo,
4636                                      const MachineOperand &MO) const {
4637   if (MO.isReg())
4638     return isLegalRegOperand(MRI, OpInfo, MO);
4639 
4640   // Handle non-register types that are treated like immediates.
4641   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
4642   return true;
4643 }
4644 
4645 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
4646                                  const MachineOperand *MO) const {
4647   const MachineFunction &MF = *MI.getParent()->getParent();
4648   const MachineRegisterInfo &MRI = MF.getRegInfo();
4649   const MCInstrDesc &InstDesc = MI.getDesc();
4650   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
4651   const TargetRegisterClass *DefinedRC =
4652       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
4653   if (!MO)
4654     MO = &MI.getOperand(OpIdx);
4655 
4656   int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
4657   int VOP3LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4658   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
4659     if (isVOP3(MI) && isLiteralConstantLike(*MO, OpInfo) && !VOP3LiteralLimit--)
4660       return false;
4661 
4662     SmallDenseSet<RegSubRegPair> SGPRsUsed;
4663     if (MO->isReg())
4664       SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
4665 
4666     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4667       if (i == OpIdx)
4668         continue;
4669       const MachineOperand &Op = MI.getOperand(i);
4670       if (Op.isReg()) {
4671         RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
4672         if (!SGPRsUsed.count(SGPR) &&
4673             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
4674           if (--ConstantBusLimit <= 0)
4675             return false;
4676           SGPRsUsed.insert(SGPR);
4677         }
4678       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
4679         if (--ConstantBusLimit <= 0)
4680           return false;
4681       } else if (isVOP3(MI) && AMDGPU::isSISrcOperand(InstDesc, i) &&
4682                  isLiteralConstantLike(Op, InstDesc.OpInfo[i])) {
4683         if (!VOP3LiteralLimit--)
4684           return false;
4685         if (--ConstantBusLimit <= 0)
4686           return false;
4687       }
4688     }
4689   }
4690 
4691   if (MO->isReg()) {
4692     assert(DefinedRC);
4693     if (!isLegalRegOperand(MRI, OpInfo, *MO))
4694       return false;
4695     bool IsAGPR = RI.isAGPR(MRI, MO->getReg());
4696     if (IsAGPR && !ST.hasMAIInsts())
4697       return false;
4698     unsigned Opc = MI.getOpcode();
4699     if (IsAGPR &&
4700         (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4701         (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
4702       return false;
4703     // Atomics should have both vdst and vdata either vgpr or agpr.
4704     const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
4705     const int DataIdx = AMDGPU::getNamedOperandIdx(Opc,
4706         isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
4707     if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
4708         MI.getOperand(DataIdx).isReg() &&
4709         RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
4710       return false;
4711     if ((int)OpIdx == DataIdx) {
4712       if (VDstIdx != -1 &&
4713           RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
4714         return false;
4715       // DS instructions with 2 src operands also must have tied RC.
4716       const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc,
4717                                                       AMDGPU::OpName::data1);
4718       if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
4719           RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
4720         return false;
4721     }
4722     if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 &&
4723         (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
4724         RI.isSGPRReg(MRI, MO->getReg()))
4725       return false;
4726     return true;
4727   }
4728 
4729   // Handle non-register types that are treated like immediates.
4730   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
4731 
4732   if (!DefinedRC) {
4733     // This operand expects an immediate.
4734     return true;
4735   }
4736 
4737   return isImmOperandLegal(MI, OpIdx, *MO);
4738 }
4739 
4740 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
4741                                        MachineInstr &MI) const {
4742   unsigned Opc = MI.getOpcode();
4743   const MCInstrDesc &InstrDesc = get(Opc);
4744 
4745   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4746   MachineOperand &Src0 = MI.getOperand(Src0Idx);
4747 
4748   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4749   MachineOperand &Src1 = MI.getOperand(Src1Idx);
4750 
4751   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
4752   // we need to only have one constant bus use before GFX10.
4753   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
4754   if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 &&
4755       Src0.isReg() && (RI.isSGPRReg(MRI, Src0.getReg()) ||
4756        isLiteralConstantLike(Src0, InstrDesc.OpInfo[Src0Idx])))
4757     legalizeOpWithMove(MI, Src0Idx);
4758 
4759   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
4760   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
4761   // src0/src1 with V_READFIRSTLANE.
4762   if (Opc == AMDGPU::V_WRITELANE_B32) {
4763     const DebugLoc &DL = MI.getDebugLoc();
4764     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
4765       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4766       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4767           .add(Src0);
4768       Src0.ChangeToRegister(Reg, false);
4769     }
4770     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
4771       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4772       const DebugLoc &DL = MI.getDebugLoc();
4773       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4774           .add(Src1);
4775       Src1.ChangeToRegister(Reg, false);
4776     }
4777     return;
4778   }
4779 
4780   // No VOP2 instructions support AGPRs.
4781   if (Src0.isReg() && RI.isAGPR(MRI, Src0.getReg()))
4782     legalizeOpWithMove(MI, Src0Idx);
4783 
4784   if (Src1.isReg() && RI.isAGPR(MRI, Src1.getReg()))
4785     legalizeOpWithMove(MI, Src1Idx);
4786 
4787   // VOP2 src0 instructions support all operand types, so we don't need to check
4788   // their legality. If src1 is already legal, we don't need to do anything.
4789   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
4790     return;
4791 
4792   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
4793   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
4794   // select is uniform.
4795   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
4796       RI.isVGPR(MRI, Src1.getReg())) {
4797     Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4798     const DebugLoc &DL = MI.getDebugLoc();
4799     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4800         .add(Src1);
4801     Src1.ChangeToRegister(Reg, false);
4802     return;
4803   }
4804 
4805   // We do not use commuteInstruction here because it is too aggressive and will
4806   // commute if it is possible. We only want to commute here if it improves
4807   // legality. This can be called a fairly large number of times so don't waste
4808   // compile time pointlessly swapping and checking legality again.
4809   if (HasImplicitSGPR || !MI.isCommutable()) {
4810     legalizeOpWithMove(MI, Src1Idx);
4811     return;
4812   }
4813 
4814   // If src0 can be used as src1, commuting will make the operands legal.
4815   // Otherwise we have to give up and insert a move.
4816   //
4817   // TODO: Other immediate-like operand kinds could be commuted if there was a
4818   // MachineOperand::ChangeTo* for them.
4819   if ((!Src1.isImm() && !Src1.isReg()) ||
4820       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
4821     legalizeOpWithMove(MI, Src1Idx);
4822     return;
4823   }
4824 
4825   int CommutedOpc = commuteOpcode(MI);
4826   if (CommutedOpc == -1) {
4827     legalizeOpWithMove(MI, Src1Idx);
4828     return;
4829   }
4830 
4831   MI.setDesc(get(CommutedOpc));
4832 
4833   Register Src0Reg = Src0.getReg();
4834   unsigned Src0SubReg = Src0.getSubReg();
4835   bool Src0Kill = Src0.isKill();
4836 
4837   if (Src1.isImm())
4838     Src0.ChangeToImmediate(Src1.getImm());
4839   else if (Src1.isReg()) {
4840     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
4841     Src0.setSubReg(Src1.getSubReg());
4842   } else
4843     llvm_unreachable("Should only have register or immediate operands");
4844 
4845   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
4846   Src1.setSubReg(Src0SubReg);
4847   fixImplicitOperands(MI);
4848 }
4849 
4850 // Legalize VOP3 operands. All operand types are supported for any operand
4851 // but only one literal constant and only starting from GFX10.
4852 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
4853                                        MachineInstr &MI) const {
4854   unsigned Opc = MI.getOpcode();
4855 
4856   int VOP3Idx[3] = {
4857     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
4858     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
4859     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
4860   };
4861 
4862   if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
4863       Opc == AMDGPU::V_PERMLANEX16_B32_e64) {
4864     // src1 and src2 must be scalar
4865     MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
4866     MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
4867     const DebugLoc &DL = MI.getDebugLoc();
4868     if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
4869       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4870       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4871         .add(Src1);
4872       Src1.ChangeToRegister(Reg, false);
4873     }
4874     if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
4875       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4876       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4877         .add(Src2);
4878       Src2.ChangeToRegister(Reg, false);
4879     }
4880   }
4881 
4882   // Find the one SGPR operand we are allowed to use.
4883   int ConstantBusLimit = ST.getConstantBusLimit(Opc);
4884   int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4885   SmallDenseSet<unsigned> SGPRsUsed;
4886   Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
4887   if (SGPRReg != AMDGPU::NoRegister) {
4888     SGPRsUsed.insert(SGPRReg);
4889     --ConstantBusLimit;
4890   }
4891 
4892   for (unsigned i = 0; i < 3; ++i) {
4893     int Idx = VOP3Idx[i];
4894     if (Idx == -1)
4895       break;
4896     MachineOperand &MO = MI.getOperand(Idx);
4897 
4898     if (!MO.isReg()) {
4899       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
4900         continue;
4901 
4902       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
4903         --LiteralLimit;
4904         --ConstantBusLimit;
4905         continue;
4906       }
4907 
4908       --LiteralLimit;
4909       --ConstantBusLimit;
4910       legalizeOpWithMove(MI, Idx);
4911       continue;
4912     }
4913 
4914     if (RI.hasAGPRs(MRI.getRegClass(MO.getReg())) &&
4915         !isOperandLegal(MI, Idx, &MO)) {
4916       legalizeOpWithMove(MI, Idx);
4917       continue;
4918     }
4919 
4920     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
4921       continue; // VGPRs are legal
4922 
4923     // We can use one SGPR in each VOP3 instruction prior to GFX10
4924     // and two starting from GFX10.
4925     if (SGPRsUsed.count(MO.getReg()))
4926       continue;
4927     if (ConstantBusLimit > 0) {
4928       SGPRsUsed.insert(MO.getReg());
4929       --ConstantBusLimit;
4930       continue;
4931     }
4932 
4933     // If we make it this far, then the operand is not legal and we must
4934     // legalize it.
4935     legalizeOpWithMove(MI, Idx);
4936   }
4937 }
4938 
4939 Register SIInstrInfo::readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI,
4940                                          MachineRegisterInfo &MRI) const {
4941   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
4942   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
4943   Register DstReg = MRI.createVirtualRegister(SRC);
4944   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
4945 
4946   if (RI.hasAGPRs(VRC)) {
4947     VRC = RI.getEquivalentVGPRClass(VRC);
4948     Register NewSrcReg = MRI.createVirtualRegister(VRC);
4949     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4950             get(TargetOpcode::COPY), NewSrcReg)
4951         .addReg(SrcReg);
4952     SrcReg = NewSrcReg;
4953   }
4954 
4955   if (SubRegs == 1) {
4956     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4957             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
4958         .addReg(SrcReg);
4959     return DstReg;
4960   }
4961 
4962   SmallVector<unsigned, 8> SRegs;
4963   for (unsigned i = 0; i < SubRegs; ++i) {
4964     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4965     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4966             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
4967         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
4968     SRegs.push_back(SGPR);
4969   }
4970 
4971   MachineInstrBuilder MIB =
4972       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4973               get(AMDGPU::REG_SEQUENCE), DstReg);
4974   for (unsigned i = 0; i < SubRegs; ++i) {
4975     MIB.addReg(SRegs[i]);
4976     MIB.addImm(RI.getSubRegFromChannel(i));
4977   }
4978   return DstReg;
4979 }
4980 
4981 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
4982                                        MachineInstr &MI) const {
4983 
4984   // If the pointer is store in VGPRs, then we need to move them to
4985   // SGPRs using v_readfirstlane.  This is safe because we only select
4986   // loads with uniform pointers to SMRD instruction so we know the
4987   // pointer value is uniform.
4988   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
4989   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
4990     Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
4991     SBase->setReg(SGPR);
4992   }
4993   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
4994   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
4995     Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
4996     SOff->setReg(SGPR);
4997   }
4998 }
4999 
5000 // FIXME: Remove this when SelectionDAG is obsoleted.
5001 void SIInstrInfo::legalizeOperandsFLAT(MachineRegisterInfo &MRI,
5002                                        MachineInstr &MI) const {
5003   if (!isSegmentSpecificFLAT(MI))
5004     return;
5005 
5006   // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
5007   // thinks they are uniform, so a readfirstlane should be valid.
5008   MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
5009   if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
5010     return;
5011 
5012   Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI);
5013   SAddr->setReg(ToSGPR);
5014 }
5015 
5016 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
5017                                          MachineBasicBlock::iterator I,
5018                                          const TargetRegisterClass *DstRC,
5019                                          MachineOperand &Op,
5020                                          MachineRegisterInfo &MRI,
5021                                          const DebugLoc &DL) const {
5022   Register OpReg = Op.getReg();
5023   unsigned OpSubReg = Op.getSubReg();
5024 
5025   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
5026       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
5027 
5028   // Check if operand is already the correct register class.
5029   if (DstRC == OpRC)
5030     return;
5031 
5032   Register DstReg = MRI.createVirtualRegister(DstRC);
5033   MachineInstr *Copy =
5034       BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
5035 
5036   Op.setReg(DstReg);
5037   Op.setSubReg(0);
5038 
5039   MachineInstr *Def = MRI.getVRegDef(OpReg);
5040   if (!Def)
5041     return;
5042 
5043   // Try to eliminate the copy if it is copying an immediate value.
5044   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
5045     FoldImmediate(*Copy, *Def, OpReg, &MRI);
5046 
5047   bool ImpDef = Def->isImplicitDef();
5048   while (!ImpDef && Def && Def->isCopy()) {
5049     if (Def->getOperand(1).getReg().isPhysical())
5050       break;
5051     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
5052     ImpDef = Def && Def->isImplicitDef();
5053   }
5054   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
5055       !ImpDef)
5056     Copy->addOperand(MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
5057 }
5058 
5059 // Emit the actual waterfall loop, executing the wrapped instruction for each
5060 // unique value of \p Rsrc across all lanes. In the best case we execute 1
5061 // iteration, in the worst case we execute 64 (once per lane).
5062 static void
5063 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
5064                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5065                           const DebugLoc &DL, MachineOperand &Rsrc) {
5066   MachineFunction &MF = *OrigBB.getParent();
5067   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5068   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5069   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5070   unsigned SaveExecOpc =
5071       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
5072   unsigned XorTermOpc =
5073       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
5074   unsigned AndOpc =
5075       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
5076   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5077 
5078   MachineBasicBlock::iterator I = LoopBB.begin();
5079 
5080   SmallVector<Register, 8> ReadlanePieces;
5081   Register CondReg = AMDGPU::NoRegister;
5082 
5083   Register VRsrc = Rsrc.getReg();
5084   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
5085 
5086   unsigned RegSize = TRI->getRegSizeInBits(Rsrc.getReg(), MRI);
5087   unsigned NumSubRegs =  RegSize / 32;
5088   assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 && "Unhandled register size");
5089 
5090   for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
5091 
5092     Register CurRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5093     Register CurRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5094 
5095     // Read the next variant <- also loop target.
5096     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
5097             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx));
5098 
5099     // Read the next variant <- also loop target.
5100     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
5101             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx + 1));
5102 
5103     ReadlanePieces.push_back(CurRegLo);
5104     ReadlanePieces.push_back(CurRegHi);
5105 
5106     // Comparison is to be done as 64-bit.
5107     Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
5108     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
5109             .addReg(CurRegLo)
5110             .addImm(AMDGPU::sub0)
5111             .addReg(CurRegHi)
5112             .addImm(AMDGPU::sub1);
5113 
5114     Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
5115     auto Cmp =
5116         BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
5117             .addReg(CurReg);
5118     if (NumSubRegs <= 2)
5119       Cmp.addReg(VRsrc);
5120     else
5121       Cmp.addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx, 2));
5122 
5123     // Combine the comparision results with AND.
5124     if (CondReg == AMDGPU::NoRegister) // First.
5125       CondReg = NewCondReg;
5126     else { // If not the first, we create an AND.
5127       Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
5128       BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndReg)
5129               .addReg(CondReg)
5130               .addReg(NewCondReg);
5131       CondReg = AndReg;
5132     }
5133   } // End for loop.
5134 
5135   auto SRsrcRC = TRI->getEquivalentSGPRClass(MRI.getRegClass(VRsrc));
5136   Register SRsrc = MRI.createVirtualRegister(SRsrcRC);
5137 
5138   // Build scalar Rsrc.
5139   auto Merge = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc);
5140   unsigned Channel = 0;
5141   for (Register Piece : ReadlanePieces) {
5142     Merge.addReg(Piece)
5143          .addImm(TRI->getSubRegFromChannel(Channel++));
5144   }
5145 
5146   // Update Rsrc operand to use the SGPR Rsrc.
5147   Rsrc.setReg(SRsrc);
5148   Rsrc.setIsKill(true);
5149 
5150   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5151   MRI.setSimpleHint(SaveExec, CondReg);
5152 
5153   // Update EXEC to matching lanes, saving original to SaveExec.
5154   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
5155       .addReg(CondReg, RegState::Kill);
5156 
5157   // The original instruction is here; we insert the terminators after it.
5158   I = LoopBB.end();
5159 
5160   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5161   BuildMI(LoopBB, I, DL, TII.get(XorTermOpc), Exec)
5162       .addReg(Exec)
5163       .addReg(SaveExec);
5164 
5165   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(&LoopBB);
5166 }
5167 
5168 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
5169 // with SGPRs by iterating over all unique values across all lanes.
5170 // Returns the loop basic block that now contains \p MI.
5171 static MachineBasicBlock *
5172 loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
5173                   MachineOperand &Rsrc, MachineDominatorTree *MDT,
5174                   MachineBasicBlock::iterator Begin = nullptr,
5175                   MachineBasicBlock::iterator End = nullptr) {
5176   MachineBasicBlock &MBB = *MI.getParent();
5177   MachineFunction &MF = *MBB.getParent();
5178   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5179   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5180   MachineRegisterInfo &MRI = MF.getRegInfo();
5181   if (!Begin.isValid())
5182     Begin = &MI;
5183   if (!End.isValid()) {
5184     End = &MI;
5185     ++End;
5186   }
5187   const DebugLoc &DL = MI.getDebugLoc();
5188   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5189   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
5190   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5191 
5192   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5193 
5194   // Save the EXEC mask
5195   BuildMI(MBB, Begin, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
5196 
5197   // Killed uses in the instruction we are waterfalling around will be
5198   // incorrect due to the added control-flow.
5199   MachineBasicBlock::iterator AfterMI = MI;
5200   ++AfterMI;
5201   for (auto I = Begin; I != AfterMI; I++) {
5202     for (auto &MO : I->uses()) {
5203       if (MO.isReg() && MO.isUse()) {
5204         MRI.clearKillFlags(MO.getReg());
5205       }
5206     }
5207   }
5208 
5209   // To insert the loop we need to split the block. Move everything after this
5210   // point to a new block, and insert a new empty block between the two.
5211   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
5212   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
5213   MachineFunction::iterator MBBI(MBB);
5214   ++MBBI;
5215 
5216   MF.insert(MBBI, LoopBB);
5217   MF.insert(MBBI, RemainderBB);
5218 
5219   LoopBB->addSuccessor(LoopBB);
5220   LoopBB->addSuccessor(RemainderBB);
5221 
5222   // Move Begin to MI to the LoopBB, and the remainder of the block to
5223   // RemainderBB.
5224   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5225   RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
5226   LoopBB->splice(LoopBB->begin(), &MBB, Begin, MBB.end());
5227 
5228   MBB.addSuccessor(LoopBB);
5229 
5230   // Update dominators. We know that MBB immediately dominates LoopBB, that
5231   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
5232   // dominates all of the successors transferred to it from MBB that MBB used
5233   // to properly dominate.
5234   if (MDT) {
5235     MDT->addNewBlock(LoopBB, &MBB);
5236     MDT->addNewBlock(RemainderBB, LoopBB);
5237     for (auto &Succ : RemainderBB->successors()) {
5238       if (MDT->properlyDominates(&MBB, Succ)) {
5239         MDT->changeImmediateDominator(Succ, RemainderBB);
5240       }
5241     }
5242   }
5243 
5244   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
5245 
5246   // Restore the EXEC mask
5247   MachineBasicBlock::iterator First = RemainderBB->begin();
5248   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
5249   return LoopBB;
5250 }
5251 
5252 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
5253 static std::tuple<unsigned, unsigned>
5254 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
5255   MachineBasicBlock &MBB = *MI.getParent();
5256   MachineFunction &MF = *MBB.getParent();
5257   MachineRegisterInfo &MRI = MF.getRegInfo();
5258 
5259   // Extract the ptr from the resource descriptor.
5260   unsigned RsrcPtr =
5261       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
5262                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
5263 
5264   // Create an empty resource descriptor
5265   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5266   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5267   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5268   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
5269   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
5270 
5271   // Zero64 = 0
5272   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
5273       .addImm(0);
5274 
5275   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
5276   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
5277       .addImm(RsrcDataFormat & 0xFFFFFFFF);
5278 
5279   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
5280   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
5281       .addImm(RsrcDataFormat >> 32);
5282 
5283   // NewSRsrc = {Zero64, SRsrcFormat}
5284   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
5285       .addReg(Zero64)
5286       .addImm(AMDGPU::sub0_sub1)
5287       .addReg(SRsrcFormatLo)
5288       .addImm(AMDGPU::sub2)
5289       .addReg(SRsrcFormatHi)
5290       .addImm(AMDGPU::sub3);
5291 
5292   return std::make_tuple(RsrcPtr, NewSRsrc);
5293 }
5294 
5295 MachineBasicBlock *
5296 SIInstrInfo::legalizeOperands(MachineInstr &MI,
5297                               MachineDominatorTree *MDT) const {
5298   MachineFunction &MF = *MI.getParent()->getParent();
5299   MachineRegisterInfo &MRI = MF.getRegInfo();
5300   MachineBasicBlock *CreatedBB = nullptr;
5301 
5302   // Legalize VOP2
5303   if (isVOP2(MI) || isVOPC(MI)) {
5304     legalizeOperandsVOP2(MRI, MI);
5305     return CreatedBB;
5306   }
5307 
5308   // Legalize VOP3
5309   if (isVOP3(MI)) {
5310     legalizeOperandsVOP3(MRI, MI);
5311     return CreatedBB;
5312   }
5313 
5314   // Legalize SMRD
5315   if (isSMRD(MI)) {
5316     legalizeOperandsSMRD(MRI, MI);
5317     return CreatedBB;
5318   }
5319 
5320   // Legalize FLAT
5321   if (isFLAT(MI)) {
5322     legalizeOperandsFLAT(MRI, MI);
5323     return CreatedBB;
5324   }
5325 
5326   // Legalize REG_SEQUENCE and PHI
5327   // The register class of the operands much be the same type as the register
5328   // class of the output.
5329   if (MI.getOpcode() == AMDGPU::PHI) {
5330     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
5331     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
5332       if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
5333         continue;
5334       const TargetRegisterClass *OpRC =
5335           MRI.getRegClass(MI.getOperand(i).getReg());
5336       if (RI.hasVectorRegisters(OpRC)) {
5337         VRC = OpRC;
5338       } else {
5339         SRC = OpRC;
5340       }
5341     }
5342 
5343     // If any of the operands are VGPR registers, then they all most be
5344     // otherwise we will create illegal VGPR->SGPR copies when legalizing
5345     // them.
5346     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
5347       if (!VRC) {
5348         assert(SRC);
5349         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
5350           VRC = &AMDGPU::VReg_1RegClass;
5351         } else
5352           VRC = RI.hasAGPRs(getOpRegClass(MI, 0))
5353                     ? RI.getEquivalentAGPRClass(SRC)
5354                     : RI.getEquivalentVGPRClass(SRC);
5355       } else {
5356           VRC = RI.hasAGPRs(getOpRegClass(MI, 0))
5357                     ? RI.getEquivalentAGPRClass(VRC)
5358                     : RI.getEquivalentVGPRClass(VRC);
5359       }
5360       RC = VRC;
5361     } else {
5362       RC = SRC;
5363     }
5364 
5365     // Update all the operands so they have the same type.
5366     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5367       MachineOperand &Op = MI.getOperand(I);
5368       if (!Op.isReg() || !Op.getReg().isVirtual())
5369         continue;
5370 
5371       // MI is a PHI instruction.
5372       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
5373       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
5374 
5375       // Avoid creating no-op copies with the same src and dst reg class.  These
5376       // confuse some of the machine passes.
5377       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
5378     }
5379   }
5380 
5381   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
5382   // VGPR dest type and SGPR sources, insert copies so all operands are
5383   // VGPRs. This seems to help operand folding / the register coalescer.
5384   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
5385     MachineBasicBlock *MBB = MI.getParent();
5386     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
5387     if (RI.hasVGPRs(DstRC)) {
5388       // Update all the operands so they are VGPR register classes. These may
5389       // not be the same register class because REG_SEQUENCE supports mixing
5390       // subregister index types e.g. sub0_sub1 + sub2 + sub3
5391       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5392         MachineOperand &Op = MI.getOperand(I);
5393         if (!Op.isReg() || !Op.getReg().isVirtual())
5394           continue;
5395 
5396         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
5397         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
5398         if (VRC == OpRC)
5399           continue;
5400 
5401         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
5402         Op.setIsKill();
5403       }
5404     }
5405 
5406     return CreatedBB;
5407   }
5408 
5409   // Legalize INSERT_SUBREG
5410   // src0 must have the same register class as dst
5411   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
5412     Register Dst = MI.getOperand(0).getReg();
5413     Register Src0 = MI.getOperand(1).getReg();
5414     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
5415     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
5416     if (DstRC != Src0RC) {
5417       MachineBasicBlock *MBB = MI.getParent();
5418       MachineOperand &Op = MI.getOperand(1);
5419       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
5420     }
5421     return CreatedBB;
5422   }
5423 
5424   // Legalize SI_INIT_M0
5425   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
5426     MachineOperand &Src = MI.getOperand(0);
5427     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
5428       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
5429     return CreatedBB;
5430   }
5431 
5432   // Legalize MIMG and MUBUF/MTBUF for shaders.
5433   //
5434   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
5435   // scratch memory access. In both cases, the legalization never involves
5436   // conversion to the addr64 form.
5437   if (isMIMG(MI) || (AMDGPU::isGraphics(MF.getFunction().getCallingConv()) &&
5438                      (isMUBUF(MI) || isMTBUF(MI)))) {
5439     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
5440     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
5441       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SRsrc, MDT);
5442 
5443     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
5444     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
5445       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SSamp, MDT);
5446 
5447     return CreatedBB;
5448   }
5449 
5450   // Legalize SI_CALL
5451   if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
5452     MachineOperand *Dest = &MI.getOperand(0);
5453     if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
5454       // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
5455       // following copies, we also need to move copies from and to physical
5456       // registers into the loop block.
5457       unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
5458       unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
5459 
5460       // Also move the copies to physical registers into the loop block
5461       MachineBasicBlock &MBB = *MI.getParent();
5462       MachineBasicBlock::iterator Start(&MI);
5463       while (Start->getOpcode() != FrameSetupOpcode)
5464         --Start;
5465       MachineBasicBlock::iterator End(&MI);
5466       while (End->getOpcode() != FrameDestroyOpcode)
5467         ++End;
5468       // Also include following copies of the return value
5469       ++End;
5470       while (End != MBB.end() && End->isCopy() && End->getOperand(1).isReg() &&
5471              MI.definesRegister(End->getOperand(1).getReg()))
5472         ++End;
5473       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Dest, MDT, Start, End);
5474     }
5475   }
5476 
5477   // Legalize MUBUF* instructions.
5478   int RsrcIdx =
5479       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
5480   if (RsrcIdx != -1) {
5481     // We have an MUBUF instruction
5482     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
5483     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
5484     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
5485                              RI.getRegClass(RsrcRC))) {
5486       // The operands are legal.
5487       // FIXME: We may need to legalize operands besided srsrc.
5488       return CreatedBB;
5489     }
5490 
5491     // Legalize a VGPR Rsrc.
5492     //
5493     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
5494     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
5495     // a zero-value SRsrc.
5496     //
5497     // If the instruction is _OFFSET (both idxen and offen disabled), and we
5498     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
5499     // above.
5500     //
5501     // Otherwise we are on non-ADDR64 hardware, and/or we have
5502     // idxen/offen/bothen and we fall back to a waterfall loop.
5503 
5504     MachineBasicBlock &MBB = *MI.getParent();
5505 
5506     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5507     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
5508       // This is already an ADDR64 instruction so we need to add the pointer
5509       // extracted from the resource descriptor to the current value of VAddr.
5510       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5511       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5512       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5513 
5514       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5515       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
5516       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
5517 
5518       unsigned RsrcPtr, NewSRsrc;
5519       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5520 
5521       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
5522       const DebugLoc &DL = MI.getDebugLoc();
5523       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
5524         .addDef(CondReg0)
5525         .addReg(RsrcPtr, 0, AMDGPU::sub0)
5526         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
5527         .addImm(0);
5528 
5529       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
5530       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
5531         .addDef(CondReg1, RegState::Dead)
5532         .addReg(RsrcPtr, 0, AMDGPU::sub1)
5533         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
5534         .addReg(CondReg0, RegState::Kill)
5535         .addImm(0);
5536 
5537       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5538       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
5539           .addReg(NewVAddrLo)
5540           .addImm(AMDGPU::sub0)
5541           .addReg(NewVAddrHi)
5542           .addImm(AMDGPU::sub1);
5543 
5544       VAddr->setReg(NewVAddr);
5545       Rsrc->setReg(NewSRsrc);
5546     } else if (!VAddr && ST.hasAddr64()) {
5547       // This instructions is the _OFFSET variant, so we need to convert it to
5548       // ADDR64.
5549       assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5550              "FIXME: Need to emit flat atomics here");
5551 
5552       unsigned RsrcPtr, NewSRsrc;
5553       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5554 
5555       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5556       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
5557       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5558       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
5559       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
5560 
5561       // Atomics rith return have have an additional tied operand and are
5562       // missing some of the special bits.
5563       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
5564       MachineInstr *Addr64;
5565 
5566       if (!VDataIn) {
5567         // Regular buffer load / store.
5568         MachineInstrBuilder MIB =
5569             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5570                 .add(*VData)
5571                 .addReg(NewVAddr)
5572                 .addReg(NewSRsrc)
5573                 .add(*SOffset)
5574                 .add(*Offset);
5575 
5576         // Atomics do not have this operand.
5577         if (const MachineOperand *GLC =
5578                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
5579           MIB.addImm(GLC->getImm());
5580         }
5581         if (const MachineOperand *DLC =
5582                 getNamedOperand(MI, AMDGPU::OpName::dlc)) {
5583           MIB.addImm(DLC->getImm());
5584         }
5585         if (const MachineOperand *SCCB =
5586                 getNamedOperand(MI, AMDGPU::OpName::sccb)) {
5587           MIB.addImm(SCCB->getImm());
5588         }
5589 
5590         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
5591 
5592         if (const MachineOperand *TFE =
5593                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
5594           MIB.addImm(TFE->getImm());
5595         }
5596 
5597         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
5598 
5599         MIB.cloneMemRefs(MI);
5600         Addr64 = MIB;
5601       } else {
5602         // Atomics with return.
5603         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5604                      .add(*VData)
5605                      .add(*VDataIn)
5606                      .addReg(NewVAddr)
5607                      .addReg(NewSRsrc)
5608                      .add(*SOffset)
5609                      .add(*Offset)
5610                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
5611                      .cloneMemRefs(MI);
5612       }
5613 
5614       MI.removeFromParent();
5615 
5616       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5617       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
5618               NewVAddr)
5619           .addReg(RsrcPtr, 0, AMDGPU::sub0)
5620           .addImm(AMDGPU::sub0)
5621           .addReg(RsrcPtr, 0, AMDGPU::sub1)
5622           .addImm(AMDGPU::sub1);
5623     } else {
5624       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
5625       // to SGPRs.
5626       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
5627       return CreatedBB;
5628     }
5629   }
5630   return CreatedBB;
5631 }
5632 
5633 MachineBasicBlock *SIInstrInfo::moveToVALU(MachineInstr &TopInst,
5634                                            MachineDominatorTree *MDT) const {
5635   SetVectorType Worklist;
5636   Worklist.insert(&TopInst);
5637   MachineBasicBlock *CreatedBB = nullptr;
5638   MachineBasicBlock *CreatedBBTmp = nullptr;
5639 
5640   while (!Worklist.empty()) {
5641     MachineInstr &Inst = *Worklist.pop_back_val();
5642     MachineBasicBlock *MBB = Inst.getParent();
5643     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
5644 
5645     unsigned Opcode = Inst.getOpcode();
5646     unsigned NewOpcode = getVALUOp(Inst);
5647 
5648     // Handle some special cases
5649     switch (Opcode) {
5650     default:
5651       break;
5652     case AMDGPU::S_ADD_U64_PSEUDO:
5653     case AMDGPU::S_SUB_U64_PSEUDO:
5654       splitScalar64BitAddSub(Worklist, Inst, MDT);
5655       Inst.eraseFromParent();
5656       continue;
5657     case AMDGPU::S_ADD_I32:
5658     case AMDGPU::S_SUB_I32: {
5659       // FIXME: The u32 versions currently selected use the carry.
5660       bool Changed;
5661       std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
5662       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5663         CreatedBB = CreatedBBTmp;
5664       if (Changed)
5665         continue;
5666 
5667       // Default handling
5668       break;
5669     }
5670     case AMDGPU::S_AND_B64:
5671       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
5672       Inst.eraseFromParent();
5673       continue;
5674 
5675     case AMDGPU::S_OR_B64:
5676       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
5677       Inst.eraseFromParent();
5678       continue;
5679 
5680     case AMDGPU::S_XOR_B64:
5681       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
5682       Inst.eraseFromParent();
5683       continue;
5684 
5685     case AMDGPU::S_NAND_B64:
5686       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
5687       Inst.eraseFromParent();
5688       continue;
5689 
5690     case AMDGPU::S_NOR_B64:
5691       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
5692       Inst.eraseFromParent();
5693       continue;
5694 
5695     case AMDGPU::S_XNOR_B64:
5696       if (ST.hasDLInsts())
5697         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
5698       else
5699         splitScalar64BitXnor(Worklist, Inst, MDT);
5700       Inst.eraseFromParent();
5701       continue;
5702 
5703     case AMDGPU::S_ANDN2_B64:
5704       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
5705       Inst.eraseFromParent();
5706       continue;
5707 
5708     case AMDGPU::S_ORN2_B64:
5709       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
5710       Inst.eraseFromParent();
5711       continue;
5712 
5713     case AMDGPU::S_NOT_B64:
5714       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
5715       Inst.eraseFromParent();
5716       continue;
5717 
5718     case AMDGPU::S_BCNT1_I32_B64:
5719       splitScalar64BitBCNT(Worklist, Inst);
5720       Inst.eraseFromParent();
5721       continue;
5722 
5723     case AMDGPU::S_BFE_I64:
5724       splitScalar64BitBFE(Worklist, Inst);
5725       Inst.eraseFromParent();
5726       continue;
5727 
5728     case AMDGPU::S_LSHL_B32:
5729       if (ST.hasOnlyRevVALUShifts()) {
5730         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
5731         swapOperands(Inst);
5732       }
5733       break;
5734     case AMDGPU::S_ASHR_I32:
5735       if (ST.hasOnlyRevVALUShifts()) {
5736         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
5737         swapOperands(Inst);
5738       }
5739       break;
5740     case AMDGPU::S_LSHR_B32:
5741       if (ST.hasOnlyRevVALUShifts()) {
5742         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
5743         swapOperands(Inst);
5744       }
5745       break;
5746     case AMDGPU::S_LSHL_B64:
5747       if (ST.hasOnlyRevVALUShifts()) {
5748         NewOpcode = AMDGPU::V_LSHLREV_B64_e64;
5749         swapOperands(Inst);
5750       }
5751       break;
5752     case AMDGPU::S_ASHR_I64:
5753       if (ST.hasOnlyRevVALUShifts()) {
5754         NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
5755         swapOperands(Inst);
5756       }
5757       break;
5758     case AMDGPU::S_LSHR_B64:
5759       if (ST.hasOnlyRevVALUShifts()) {
5760         NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
5761         swapOperands(Inst);
5762       }
5763       break;
5764 
5765     case AMDGPU::S_ABS_I32:
5766       lowerScalarAbs(Worklist, Inst);
5767       Inst.eraseFromParent();
5768       continue;
5769 
5770     case AMDGPU::S_CBRANCH_SCC0:
5771     case AMDGPU::S_CBRANCH_SCC1:
5772       // Clear unused bits of vcc
5773       if (ST.isWave32())
5774         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B32),
5775                 AMDGPU::VCC_LO)
5776             .addReg(AMDGPU::EXEC_LO)
5777             .addReg(AMDGPU::VCC_LO);
5778       else
5779         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
5780                 AMDGPU::VCC)
5781             .addReg(AMDGPU::EXEC)
5782             .addReg(AMDGPU::VCC);
5783       break;
5784 
5785     case AMDGPU::S_BFE_U64:
5786     case AMDGPU::S_BFM_B64:
5787       llvm_unreachable("Moving this op to VALU not implemented");
5788 
5789     case AMDGPU::S_PACK_LL_B32_B16:
5790     case AMDGPU::S_PACK_LH_B32_B16:
5791     case AMDGPU::S_PACK_HH_B32_B16:
5792       movePackToVALU(Worklist, MRI, Inst);
5793       Inst.eraseFromParent();
5794       continue;
5795 
5796     case AMDGPU::S_XNOR_B32:
5797       lowerScalarXnor(Worklist, Inst);
5798       Inst.eraseFromParent();
5799       continue;
5800 
5801     case AMDGPU::S_NAND_B32:
5802       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
5803       Inst.eraseFromParent();
5804       continue;
5805 
5806     case AMDGPU::S_NOR_B32:
5807       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
5808       Inst.eraseFromParent();
5809       continue;
5810 
5811     case AMDGPU::S_ANDN2_B32:
5812       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
5813       Inst.eraseFromParent();
5814       continue;
5815 
5816     case AMDGPU::S_ORN2_B32:
5817       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
5818       Inst.eraseFromParent();
5819       continue;
5820 
5821     // TODO: remove as soon as everything is ready
5822     // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
5823     // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
5824     // can only be selected from the uniform SDNode.
5825     case AMDGPU::S_ADD_CO_PSEUDO:
5826     case AMDGPU::S_SUB_CO_PSEUDO: {
5827       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
5828                          ? AMDGPU::V_ADDC_U32_e64
5829                          : AMDGPU::V_SUBB_U32_e64;
5830       const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5831 
5832       Register CarryInReg = Inst.getOperand(4).getReg();
5833       if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
5834         Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
5835         BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
5836             .addReg(CarryInReg);
5837       }
5838 
5839       Register CarryOutReg = Inst.getOperand(1).getReg();
5840 
5841       Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
5842           MRI.getRegClass(Inst.getOperand(0).getReg())));
5843       MachineInstr *CarryOp =
5844           BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
5845               .addReg(CarryOutReg, RegState::Define)
5846               .add(Inst.getOperand(2))
5847               .add(Inst.getOperand(3))
5848               .addReg(CarryInReg)
5849               .addImm(0);
5850       CreatedBBTmp = legalizeOperands(*CarryOp);
5851       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5852         CreatedBB = CreatedBBTmp;
5853       MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
5854       addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
5855       Inst.eraseFromParent();
5856     }
5857       continue;
5858     case AMDGPU::S_UADDO_PSEUDO:
5859     case AMDGPU::S_USUBO_PSEUDO: {
5860       const DebugLoc &DL = Inst.getDebugLoc();
5861       MachineOperand &Dest0 = Inst.getOperand(0);
5862       MachineOperand &Dest1 = Inst.getOperand(1);
5863       MachineOperand &Src0 = Inst.getOperand(2);
5864       MachineOperand &Src1 = Inst.getOperand(3);
5865 
5866       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
5867                          ? AMDGPU::V_ADD_CO_U32_e64
5868                          : AMDGPU::V_SUB_CO_U32_e64;
5869       const TargetRegisterClass *NewRC =
5870           RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
5871       Register DestReg = MRI.createVirtualRegister(NewRC);
5872       MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
5873                                    .addReg(Dest1.getReg(), RegState::Define)
5874                                    .add(Src0)
5875                                    .add(Src1)
5876                                    .addImm(0); // clamp bit
5877 
5878       CreatedBBTmp = legalizeOperands(*NewInstr, MDT);
5879       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5880         CreatedBB = CreatedBBTmp;
5881 
5882       MRI.replaceRegWith(Dest0.getReg(), DestReg);
5883       addUsersToMoveToVALUWorklist(NewInstr->getOperand(0).getReg(), MRI,
5884                                    Worklist);
5885       Inst.eraseFromParent();
5886     }
5887       continue;
5888 
5889     case AMDGPU::S_CSELECT_B32:
5890     case AMDGPU::S_CSELECT_B64:
5891       lowerSelect(Worklist, Inst, MDT);
5892       Inst.eraseFromParent();
5893       continue;
5894     }
5895 
5896     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
5897       // We cannot move this instruction to the VALU, so we should try to
5898       // legalize its operands instead.
5899       CreatedBBTmp = legalizeOperands(Inst, MDT);
5900       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5901         CreatedBB = CreatedBBTmp;
5902       continue;
5903     }
5904 
5905     // Use the new VALU Opcode.
5906     const MCInstrDesc &NewDesc = get(NewOpcode);
5907     Inst.setDesc(NewDesc);
5908 
5909     // Remove any references to SCC. Vector instructions can't read from it, and
5910     // We're just about to add the implicit use / defs of VCC, and we don't want
5911     // both.
5912     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
5913       MachineOperand &Op = Inst.getOperand(i);
5914       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
5915         // Only propagate through live-def of SCC.
5916         if (Op.isDef() && !Op.isDead())
5917           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
5918         Inst.RemoveOperand(i);
5919       }
5920     }
5921 
5922     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
5923       // We are converting these to a BFE, so we need to add the missing
5924       // operands for the size and offset.
5925       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
5926       Inst.addOperand(MachineOperand::CreateImm(0));
5927       Inst.addOperand(MachineOperand::CreateImm(Size));
5928 
5929     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
5930       // The VALU version adds the second operand to the result, so insert an
5931       // extra 0 operand.
5932       Inst.addOperand(MachineOperand::CreateImm(0));
5933     }
5934 
5935     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
5936     fixImplicitOperands(Inst);
5937 
5938     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
5939       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
5940       // If we need to move this to VGPRs, we need to unpack the second operand
5941       // back into the 2 separate ones for bit offset and width.
5942       assert(OffsetWidthOp.isImm() &&
5943              "Scalar BFE is only implemented for constant width and offset");
5944       uint32_t Imm = OffsetWidthOp.getImm();
5945 
5946       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
5947       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
5948       Inst.RemoveOperand(2);                     // Remove old immediate.
5949       Inst.addOperand(MachineOperand::CreateImm(Offset));
5950       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
5951     }
5952 
5953     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
5954     unsigned NewDstReg = AMDGPU::NoRegister;
5955     if (HasDst) {
5956       Register DstReg = Inst.getOperand(0).getReg();
5957       if (DstReg.isPhysical())
5958         continue;
5959 
5960       // Update the destination register class.
5961       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
5962       if (!NewDstRC)
5963         continue;
5964 
5965       if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual() &&
5966           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
5967         // Instead of creating a copy where src and dst are the same register
5968         // class, we just replace all uses of dst with src.  These kinds of
5969         // copies interfere with the heuristics MachineSink uses to decide
5970         // whether or not to split a critical edge.  Since the pass assumes
5971         // that copies will end up as machine instructions and not be
5972         // eliminated.
5973         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
5974         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
5975         MRI.clearKillFlags(Inst.getOperand(1).getReg());
5976         Inst.getOperand(0).setReg(DstReg);
5977 
5978         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
5979         // these are deleted later, but at -O0 it would leave a suspicious
5980         // looking illegal copy of an undef register.
5981         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
5982           Inst.RemoveOperand(I);
5983         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
5984         continue;
5985       }
5986 
5987       NewDstReg = MRI.createVirtualRegister(NewDstRC);
5988       MRI.replaceRegWith(DstReg, NewDstReg);
5989     }
5990 
5991     // Legalize the operands
5992     CreatedBBTmp = legalizeOperands(Inst, MDT);
5993     if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5994       CreatedBB = CreatedBBTmp;
5995 
5996     if (HasDst)
5997      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
5998   }
5999   return CreatedBB;
6000 }
6001 
6002 // Add/sub require special handling to deal with carry outs.
6003 std::pair<bool, MachineBasicBlock *>
6004 SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
6005                               MachineDominatorTree *MDT) const {
6006   if (ST.hasAddNoCarry()) {
6007     // Assume there is no user of scc since we don't select this in that case.
6008     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
6009     // is used.
6010 
6011     MachineBasicBlock &MBB = *Inst.getParent();
6012     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6013 
6014     Register OldDstReg = Inst.getOperand(0).getReg();
6015     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6016 
6017     unsigned Opc = Inst.getOpcode();
6018     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
6019 
6020     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
6021       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
6022 
6023     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
6024     Inst.RemoveOperand(3);
6025 
6026     Inst.setDesc(get(NewOpc));
6027     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
6028     Inst.addImplicitDefUseOperands(*MBB.getParent());
6029     MRI.replaceRegWith(OldDstReg, ResultReg);
6030     MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
6031 
6032     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6033     return std::make_pair(true, NewBB);
6034   }
6035 
6036   return std::make_pair(false, nullptr);
6037 }
6038 
6039 void SIInstrInfo::lowerSelect(SetVectorType &Worklist, MachineInstr &Inst,
6040                               MachineDominatorTree *MDT) const {
6041 
6042   MachineBasicBlock &MBB = *Inst.getParent();
6043   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6044   MachineBasicBlock::iterator MII = Inst;
6045   DebugLoc DL = Inst.getDebugLoc();
6046 
6047   MachineOperand &Dest = Inst.getOperand(0);
6048   MachineOperand &Src0 = Inst.getOperand(1);
6049   MachineOperand &Src1 = Inst.getOperand(2);
6050   MachineOperand &Cond = Inst.getOperand(3);
6051 
6052   Register SCCSource = Cond.getReg();
6053   // Find SCC def, and if that is a copy (SCC = COPY reg) then use reg instead.
6054   if (!Cond.isUndef()) {
6055     for (MachineInstr &CandI :
6056          make_range(std::next(MachineBasicBlock::reverse_iterator(Inst)),
6057                     Inst.getParent()->rend())) {
6058       if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) !=
6059           -1) {
6060         if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
6061           SCCSource = CandI.getOperand(1).getReg();
6062         }
6063         break;
6064       }
6065     }
6066   }
6067 
6068   // If this is a trivial select where the condition is effectively not SCC
6069   // (SCCSource is a source of copy to SCC), then the select is semantically
6070   // equivalent to copying SCCSource. Hence, there is no need to create
6071   // V_CNDMASK, we can just use that and bail out.
6072   if ((SCCSource != AMDGPU::SCC) && Src0.isImm() && (Src0.getImm() == -1) &&
6073       Src1.isImm() && (Src1.getImm() == 0)) {
6074     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6075     return;
6076   }
6077 
6078   const TargetRegisterClass *TC = ST.getWavefrontSize() == 64
6079                                       ? &AMDGPU::SReg_64_XEXECRegClass
6080                                       : &AMDGPU::SReg_32_XM0_XEXECRegClass;
6081   Register CopySCC = MRI.createVirtualRegister(TC);
6082 
6083   if (SCCSource == AMDGPU::SCC) {
6084     // Insert a trivial select instead of creating a copy, because a copy from
6085     // SCC would semantically mean just copying a single bit, but we may need
6086     // the result to be a vector condition mask that needs preserving.
6087     unsigned Opcode = (ST.getWavefrontSize() == 64) ? AMDGPU::S_CSELECT_B64
6088                                                     : AMDGPU::S_CSELECT_B32;
6089     auto NewSelect =
6090         BuildMI(MBB, MII, DL, get(Opcode), CopySCC).addImm(-1).addImm(0);
6091     NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
6092   } else {
6093     BuildMI(MBB, MII, DL, get(AMDGPU::COPY), CopySCC).addReg(SCCSource);
6094   }
6095 
6096   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6097 
6098   auto UpdatedInst =
6099       BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), ResultReg)
6100           .addImm(0)
6101           .add(Src1) // False
6102           .addImm(0)
6103           .add(Src0) // True
6104           .addReg(CopySCC);
6105 
6106   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6107   legalizeOperands(*UpdatedInst, MDT);
6108   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6109 }
6110 
6111 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
6112                                  MachineInstr &Inst) const {
6113   MachineBasicBlock &MBB = *Inst.getParent();
6114   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6115   MachineBasicBlock::iterator MII = Inst;
6116   DebugLoc DL = Inst.getDebugLoc();
6117 
6118   MachineOperand &Dest = Inst.getOperand(0);
6119   MachineOperand &Src = Inst.getOperand(1);
6120   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6121   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6122 
6123   unsigned SubOp = ST.hasAddNoCarry() ?
6124     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_CO_U32_e32;
6125 
6126   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
6127     .addImm(0)
6128     .addReg(Src.getReg());
6129 
6130   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
6131     .addReg(Src.getReg())
6132     .addReg(TmpReg);
6133 
6134   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6135   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6136 }
6137 
6138 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
6139                                   MachineInstr &Inst) const {
6140   MachineBasicBlock &MBB = *Inst.getParent();
6141   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6142   MachineBasicBlock::iterator MII = Inst;
6143   const DebugLoc &DL = Inst.getDebugLoc();
6144 
6145   MachineOperand &Dest = Inst.getOperand(0);
6146   MachineOperand &Src0 = Inst.getOperand(1);
6147   MachineOperand &Src1 = Inst.getOperand(2);
6148 
6149   if (ST.hasDLInsts()) {
6150     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6151     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
6152     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
6153 
6154     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
6155       .add(Src0)
6156       .add(Src1);
6157 
6158     MRI.replaceRegWith(Dest.getReg(), NewDest);
6159     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6160   } else {
6161     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
6162     // invert either source and then perform the XOR. If either source is a
6163     // scalar register, then we can leave the inversion on the scalar unit to
6164     // acheive a better distrubution of scalar and vector instructions.
6165     bool Src0IsSGPR = Src0.isReg() &&
6166                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
6167     bool Src1IsSGPR = Src1.isReg() &&
6168                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
6169     MachineInstr *Xor;
6170     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6171     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6172 
6173     // Build a pair of scalar instructions and add them to the work list.
6174     // The next iteration over the work list will lower these to the vector
6175     // unit as necessary.
6176     if (Src0IsSGPR) {
6177       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
6178       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6179       .addReg(Temp)
6180       .add(Src1);
6181     } else if (Src1IsSGPR) {
6182       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
6183       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6184       .add(Src0)
6185       .addReg(Temp);
6186     } else {
6187       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
6188         .add(Src0)
6189         .add(Src1);
6190       MachineInstr *Not =
6191           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
6192       Worklist.insert(Not);
6193     }
6194 
6195     MRI.replaceRegWith(Dest.getReg(), NewDest);
6196 
6197     Worklist.insert(Xor);
6198 
6199     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6200   }
6201 }
6202 
6203 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
6204                                       MachineInstr &Inst,
6205                                       unsigned Opcode) const {
6206   MachineBasicBlock &MBB = *Inst.getParent();
6207   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6208   MachineBasicBlock::iterator MII = Inst;
6209   const DebugLoc &DL = Inst.getDebugLoc();
6210 
6211   MachineOperand &Dest = Inst.getOperand(0);
6212   MachineOperand &Src0 = Inst.getOperand(1);
6213   MachineOperand &Src1 = Inst.getOperand(2);
6214 
6215   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6216   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6217 
6218   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
6219     .add(Src0)
6220     .add(Src1);
6221 
6222   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
6223     .addReg(Interm);
6224 
6225   Worklist.insert(&Op);
6226   Worklist.insert(&Not);
6227 
6228   MRI.replaceRegWith(Dest.getReg(), NewDest);
6229   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6230 }
6231 
6232 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
6233                                      MachineInstr &Inst,
6234                                      unsigned Opcode) const {
6235   MachineBasicBlock &MBB = *Inst.getParent();
6236   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6237   MachineBasicBlock::iterator MII = Inst;
6238   const DebugLoc &DL = Inst.getDebugLoc();
6239 
6240   MachineOperand &Dest = Inst.getOperand(0);
6241   MachineOperand &Src0 = Inst.getOperand(1);
6242   MachineOperand &Src1 = Inst.getOperand(2);
6243 
6244   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6245   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6246 
6247   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
6248     .add(Src1);
6249 
6250   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
6251     .add(Src0)
6252     .addReg(Interm);
6253 
6254   Worklist.insert(&Not);
6255   Worklist.insert(&Op);
6256 
6257   MRI.replaceRegWith(Dest.getReg(), NewDest);
6258   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6259 }
6260 
6261 void SIInstrInfo::splitScalar64BitUnaryOp(
6262     SetVectorType &Worklist, MachineInstr &Inst,
6263     unsigned Opcode) const {
6264   MachineBasicBlock &MBB = *Inst.getParent();
6265   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6266 
6267   MachineOperand &Dest = Inst.getOperand(0);
6268   MachineOperand &Src0 = Inst.getOperand(1);
6269   DebugLoc DL = Inst.getDebugLoc();
6270 
6271   MachineBasicBlock::iterator MII = Inst;
6272 
6273   const MCInstrDesc &InstDesc = get(Opcode);
6274   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6275     MRI.getRegClass(Src0.getReg()) :
6276     &AMDGPU::SGPR_32RegClass;
6277 
6278   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6279 
6280   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6281                                                        AMDGPU::sub0, Src0SubRC);
6282 
6283   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6284   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6285   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6286 
6287   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6288   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
6289 
6290   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6291                                                        AMDGPU::sub1, Src0SubRC);
6292 
6293   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6294   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
6295 
6296   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6297   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6298     .addReg(DestSub0)
6299     .addImm(AMDGPU::sub0)
6300     .addReg(DestSub1)
6301     .addImm(AMDGPU::sub1);
6302 
6303   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6304 
6305   Worklist.insert(&LoHalf);
6306   Worklist.insert(&HiHalf);
6307 
6308   // We don't need to legalizeOperands here because for a single operand, src0
6309   // will support any kind of input.
6310 
6311   // Move all users of this moved value.
6312   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6313 }
6314 
6315 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
6316                                          MachineInstr &Inst,
6317                                          MachineDominatorTree *MDT) const {
6318   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
6319 
6320   MachineBasicBlock &MBB = *Inst.getParent();
6321   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6322   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6323 
6324   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6325   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6326   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6327 
6328   Register CarryReg = MRI.createVirtualRegister(CarryRC);
6329   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
6330 
6331   MachineOperand &Dest = Inst.getOperand(0);
6332   MachineOperand &Src0 = Inst.getOperand(1);
6333   MachineOperand &Src1 = Inst.getOperand(2);
6334   const DebugLoc &DL = Inst.getDebugLoc();
6335   MachineBasicBlock::iterator MII = Inst;
6336 
6337   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
6338   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
6339   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6340   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6341 
6342   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6343                                                        AMDGPU::sub0, Src0SubRC);
6344   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6345                                                        AMDGPU::sub0, Src1SubRC);
6346 
6347 
6348   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6349                                                        AMDGPU::sub1, Src0SubRC);
6350   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6351                                                        AMDGPU::sub1, Src1SubRC);
6352 
6353   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
6354   MachineInstr *LoHalf =
6355     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
6356     .addReg(CarryReg, RegState::Define)
6357     .add(SrcReg0Sub0)
6358     .add(SrcReg1Sub0)
6359     .addImm(0); // clamp bit
6360 
6361   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
6362   MachineInstr *HiHalf =
6363     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
6364     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
6365     .add(SrcReg0Sub1)
6366     .add(SrcReg1Sub1)
6367     .addReg(CarryReg, RegState::Kill)
6368     .addImm(0); // clamp bit
6369 
6370   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6371     .addReg(DestSub0)
6372     .addImm(AMDGPU::sub0)
6373     .addReg(DestSub1)
6374     .addImm(AMDGPU::sub1);
6375 
6376   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6377 
6378   // Try to legalize the operands in case we need to swap the order to keep it
6379   // valid.
6380   legalizeOperands(*LoHalf, MDT);
6381   legalizeOperands(*HiHalf, MDT);
6382 
6383   // Move all users of this moved vlaue.
6384   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6385 }
6386 
6387 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
6388                                            MachineInstr &Inst, unsigned Opcode,
6389                                            MachineDominatorTree *MDT) const {
6390   MachineBasicBlock &MBB = *Inst.getParent();
6391   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6392 
6393   MachineOperand &Dest = Inst.getOperand(0);
6394   MachineOperand &Src0 = Inst.getOperand(1);
6395   MachineOperand &Src1 = Inst.getOperand(2);
6396   DebugLoc DL = Inst.getDebugLoc();
6397 
6398   MachineBasicBlock::iterator MII = Inst;
6399 
6400   const MCInstrDesc &InstDesc = get(Opcode);
6401   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6402     MRI.getRegClass(Src0.getReg()) :
6403     &AMDGPU::SGPR_32RegClass;
6404 
6405   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6406   const TargetRegisterClass *Src1RC = Src1.isReg() ?
6407     MRI.getRegClass(Src1.getReg()) :
6408     &AMDGPU::SGPR_32RegClass;
6409 
6410   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6411 
6412   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6413                                                        AMDGPU::sub0, Src0SubRC);
6414   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6415                                                        AMDGPU::sub0, Src1SubRC);
6416   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6417                                                        AMDGPU::sub1, Src0SubRC);
6418   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6419                                                        AMDGPU::sub1, Src1SubRC);
6420 
6421   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6422   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6423   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6424 
6425   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6426   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
6427                               .add(SrcReg0Sub0)
6428                               .add(SrcReg1Sub0);
6429 
6430   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6431   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
6432                               .add(SrcReg0Sub1)
6433                               .add(SrcReg1Sub1);
6434 
6435   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6436   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6437     .addReg(DestSub0)
6438     .addImm(AMDGPU::sub0)
6439     .addReg(DestSub1)
6440     .addImm(AMDGPU::sub1);
6441 
6442   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6443 
6444   Worklist.insert(&LoHalf);
6445   Worklist.insert(&HiHalf);
6446 
6447   // Move all users of this moved vlaue.
6448   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6449 }
6450 
6451 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
6452                                        MachineInstr &Inst,
6453                                        MachineDominatorTree *MDT) const {
6454   MachineBasicBlock &MBB = *Inst.getParent();
6455   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6456 
6457   MachineOperand &Dest = Inst.getOperand(0);
6458   MachineOperand &Src0 = Inst.getOperand(1);
6459   MachineOperand &Src1 = Inst.getOperand(2);
6460   const DebugLoc &DL = Inst.getDebugLoc();
6461 
6462   MachineBasicBlock::iterator MII = Inst;
6463 
6464   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6465 
6466   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6467 
6468   MachineOperand* Op0;
6469   MachineOperand* Op1;
6470 
6471   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
6472     Op0 = &Src0;
6473     Op1 = &Src1;
6474   } else {
6475     Op0 = &Src1;
6476     Op1 = &Src0;
6477   }
6478 
6479   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
6480     .add(*Op0);
6481 
6482   Register NewDest = MRI.createVirtualRegister(DestRC);
6483 
6484   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
6485     .addReg(Interm)
6486     .add(*Op1);
6487 
6488   MRI.replaceRegWith(Dest.getReg(), NewDest);
6489 
6490   Worklist.insert(&Xor);
6491 }
6492 
6493 void SIInstrInfo::splitScalar64BitBCNT(
6494     SetVectorType &Worklist, MachineInstr &Inst) const {
6495   MachineBasicBlock &MBB = *Inst.getParent();
6496   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6497 
6498   MachineBasicBlock::iterator MII = Inst;
6499   const DebugLoc &DL = Inst.getDebugLoc();
6500 
6501   MachineOperand &Dest = Inst.getOperand(0);
6502   MachineOperand &Src = Inst.getOperand(1);
6503 
6504   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
6505   const TargetRegisterClass *SrcRC = Src.isReg() ?
6506     MRI.getRegClass(Src.getReg()) :
6507     &AMDGPU::SGPR_32RegClass;
6508 
6509   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6510   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6511 
6512   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
6513 
6514   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6515                                                       AMDGPU::sub0, SrcSubRC);
6516   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6517                                                       AMDGPU::sub1, SrcSubRC);
6518 
6519   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
6520 
6521   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
6522 
6523   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6524 
6525   // We don't need to legalize operands here. src0 for etiher instruction can be
6526   // an SGPR, and the second input is unused or determined here.
6527   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6528 }
6529 
6530 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
6531                                       MachineInstr &Inst) const {
6532   MachineBasicBlock &MBB = *Inst.getParent();
6533   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6534   MachineBasicBlock::iterator MII = Inst;
6535   const DebugLoc &DL = Inst.getDebugLoc();
6536 
6537   MachineOperand &Dest = Inst.getOperand(0);
6538   uint32_t Imm = Inst.getOperand(2).getImm();
6539   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6540   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6541 
6542   (void) Offset;
6543 
6544   // Only sext_inreg cases handled.
6545   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
6546          Offset == 0 && "Not implemented");
6547 
6548   if (BitWidth < 32) {
6549     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6550     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6551     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6552 
6553     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
6554         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
6555         .addImm(0)
6556         .addImm(BitWidth);
6557 
6558     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
6559       .addImm(31)
6560       .addReg(MidRegLo);
6561 
6562     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6563       .addReg(MidRegLo)
6564       .addImm(AMDGPU::sub0)
6565       .addReg(MidRegHi)
6566       .addImm(AMDGPU::sub1);
6567 
6568     MRI.replaceRegWith(Dest.getReg(), ResultReg);
6569     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6570     return;
6571   }
6572 
6573   MachineOperand &Src = Inst.getOperand(1);
6574   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6575   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6576 
6577   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
6578     .addImm(31)
6579     .addReg(Src.getReg(), 0, AMDGPU::sub0);
6580 
6581   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6582     .addReg(Src.getReg(), 0, AMDGPU::sub0)
6583     .addImm(AMDGPU::sub0)
6584     .addReg(TmpReg)
6585     .addImm(AMDGPU::sub1);
6586 
6587   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6588   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6589 }
6590 
6591 void SIInstrInfo::addUsersToMoveToVALUWorklist(
6592   Register DstReg,
6593   MachineRegisterInfo &MRI,
6594   SetVectorType &Worklist) const {
6595   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
6596          E = MRI.use_end(); I != E;) {
6597     MachineInstr &UseMI = *I->getParent();
6598 
6599     unsigned OpNo = 0;
6600 
6601     switch (UseMI.getOpcode()) {
6602     case AMDGPU::COPY:
6603     case AMDGPU::WQM:
6604     case AMDGPU::SOFT_WQM:
6605     case AMDGPU::WWM:
6606     case AMDGPU::REG_SEQUENCE:
6607     case AMDGPU::PHI:
6608     case AMDGPU::INSERT_SUBREG:
6609       break;
6610     default:
6611       OpNo = I.getOperandNo();
6612       break;
6613     }
6614 
6615     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
6616       Worklist.insert(&UseMI);
6617 
6618       do {
6619         ++I;
6620       } while (I != E && I->getParent() == &UseMI);
6621     } else {
6622       ++I;
6623     }
6624   }
6625 }
6626 
6627 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
6628                                  MachineRegisterInfo &MRI,
6629                                  MachineInstr &Inst) const {
6630   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6631   MachineBasicBlock *MBB = Inst.getParent();
6632   MachineOperand &Src0 = Inst.getOperand(1);
6633   MachineOperand &Src1 = Inst.getOperand(2);
6634   const DebugLoc &DL = Inst.getDebugLoc();
6635 
6636   switch (Inst.getOpcode()) {
6637   case AMDGPU::S_PACK_LL_B32_B16: {
6638     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6639     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6640 
6641     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
6642     // 0.
6643     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
6644       .addImm(0xffff);
6645 
6646     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
6647       .addReg(ImmReg, RegState::Kill)
6648       .add(Src0);
6649 
6650     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
6651       .add(Src1)
6652       .addImm(16)
6653       .addReg(TmpReg, RegState::Kill);
6654     break;
6655   }
6656   case AMDGPU::S_PACK_LH_B32_B16: {
6657     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6658     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
6659       .addImm(0xffff);
6660     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
6661       .addReg(ImmReg, RegState::Kill)
6662       .add(Src0)
6663       .add(Src1);
6664     break;
6665   }
6666   case AMDGPU::S_PACK_HH_B32_B16: {
6667     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6668     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6669     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
6670       .addImm(16)
6671       .add(Src0);
6672     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
6673       .addImm(0xffff0000);
6674     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
6675       .add(Src1)
6676       .addReg(ImmReg, RegState::Kill)
6677       .addReg(TmpReg, RegState::Kill);
6678     break;
6679   }
6680   default:
6681     llvm_unreachable("unhandled s_pack_* instruction");
6682   }
6683 
6684   MachineOperand &Dest = Inst.getOperand(0);
6685   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6686   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6687 }
6688 
6689 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
6690                                                MachineInstr &SCCDefInst,
6691                                                SetVectorType &Worklist) const {
6692   bool SCCUsedImplicitly = false;
6693 
6694   // Ensure that def inst defines SCC, which is still live.
6695   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
6696          !Op.isDead() && Op.getParent() == &SCCDefInst);
6697   SmallVector<MachineInstr *, 4> CopyToDelete;
6698   // This assumes that all the users of SCC are in the same block
6699   // as the SCC def.
6700   for (MachineInstr &MI : // Skip the def inst itself.
6701        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
6702                   SCCDefInst.getParent()->end())) {
6703     // Check if SCC is used first.
6704     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI) != -1) {
6705       if (MI.isCopy()) {
6706         MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6707         Register DestReg = MI.getOperand(0).getReg();
6708 
6709         for (auto &User : MRI.use_nodbg_instructions(DestReg)) {
6710           if ((User.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) ||
6711               (User.getOpcode() == AMDGPU::S_SUB_CO_PSEUDO)) {
6712             User.getOperand(4).setReg(RI.getVCC());
6713             Worklist.insert(&User);
6714           } else if (User.getOpcode() == AMDGPU::V_CNDMASK_B32_e64) {
6715             User.getOperand(5).setReg(RI.getVCC());
6716             // No need to add to Worklist.
6717           }
6718         }
6719         CopyToDelete.push_back(&MI);
6720       } else {
6721         if (MI.getOpcode() == AMDGPU::S_CSELECT_B32 ||
6722             MI.getOpcode() == AMDGPU::S_CSELECT_B64) {
6723           // This is an implicit use of SCC and it is really expected by
6724           // the SCC users to handle.
6725           // We cannot preserve the edge to the user so add the explicit
6726           // copy: SCC = COPY VCC.
6727           // The copy will be cleaned up during the processing of the user
6728           // in lowerSelect.
6729           SCCUsedImplicitly = true;
6730         }
6731 
6732         Worklist.insert(&MI);
6733       }
6734     }
6735     // Exit if we find another SCC def.
6736     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
6737       break;
6738   }
6739   for (auto &Copy : CopyToDelete)
6740     Copy->eraseFromParent();
6741 
6742   if (SCCUsedImplicitly) {
6743     BuildMI(*SCCDefInst.getParent(), std::next(SCCDefInst.getIterator()),
6744             SCCDefInst.getDebugLoc(), get(AMDGPU::COPY), AMDGPU::SCC)
6745         .addReg(RI.getVCC());
6746   }
6747 }
6748 
6749 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
6750   const MachineInstr &Inst) const {
6751   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
6752 
6753   switch (Inst.getOpcode()) {
6754   // For target instructions, getOpRegClass just returns the virtual register
6755   // class associated with the operand, so we need to find an equivalent VGPR
6756   // register class in order to move the instruction to the VALU.
6757   case AMDGPU::COPY:
6758   case AMDGPU::PHI:
6759   case AMDGPU::REG_SEQUENCE:
6760   case AMDGPU::INSERT_SUBREG:
6761   case AMDGPU::WQM:
6762   case AMDGPU::SOFT_WQM:
6763   case AMDGPU::WWM: {
6764     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
6765     if (RI.hasAGPRs(SrcRC)) {
6766       if (RI.hasAGPRs(NewDstRC))
6767         return nullptr;
6768 
6769       switch (Inst.getOpcode()) {
6770       case AMDGPU::PHI:
6771       case AMDGPU::REG_SEQUENCE:
6772       case AMDGPU::INSERT_SUBREG:
6773         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
6774         break;
6775       default:
6776         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
6777       }
6778 
6779       if (!NewDstRC)
6780         return nullptr;
6781     } else {
6782       if (RI.hasVGPRs(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
6783         return nullptr;
6784 
6785       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
6786       if (!NewDstRC)
6787         return nullptr;
6788     }
6789 
6790     return NewDstRC;
6791   }
6792   default:
6793     return NewDstRC;
6794   }
6795 }
6796 
6797 // Find the one SGPR operand we are allowed to use.
6798 Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
6799                                    int OpIndices[3]) const {
6800   const MCInstrDesc &Desc = MI.getDesc();
6801 
6802   // Find the one SGPR operand we are allowed to use.
6803   //
6804   // First we need to consider the instruction's operand requirements before
6805   // legalizing. Some operands are required to be SGPRs, such as implicit uses
6806   // of VCC, but we are still bound by the constant bus requirement to only use
6807   // one.
6808   //
6809   // If the operand's class is an SGPR, we can never move it.
6810 
6811   Register SGPRReg = findImplicitSGPRRead(MI);
6812   if (SGPRReg != AMDGPU::NoRegister)
6813     return SGPRReg;
6814 
6815   Register UsedSGPRs[3] = { AMDGPU::NoRegister };
6816   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6817 
6818   for (unsigned i = 0; i < 3; ++i) {
6819     int Idx = OpIndices[i];
6820     if (Idx == -1)
6821       break;
6822 
6823     const MachineOperand &MO = MI.getOperand(Idx);
6824     if (!MO.isReg())
6825       continue;
6826 
6827     // Is this operand statically required to be an SGPR based on the operand
6828     // constraints?
6829     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
6830     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
6831     if (IsRequiredSGPR)
6832       return MO.getReg();
6833 
6834     // If this could be a VGPR or an SGPR, Check the dynamic register class.
6835     Register Reg = MO.getReg();
6836     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
6837     if (RI.isSGPRClass(RegRC))
6838       UsedSGPRs[i] = Reg;
6839   }
6840 
6841   // We don't have a required SGPR operand, so we have a bit more freedom in
6842   // selecting operands to move.
6843 
6844   // Try to select the most used SGPR. If an SGPR is equal to one of the
6845   // others, we choose that.
6846   //
6847   // e.g.
6848   // V_FMA_F32 v0, s0, s0, s0 -> No moves
6849   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
6850 
6851   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
6852   // prefer those.
6853 
6854   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
6855     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
6856       SGPRReg = UsedSGPRs[0];
6857   }
6858 
6859   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
6860     if (UsedSGPRs[1] == UsedSGPRs[2])
6861       SGPRReg = UsedSGPRs[1];
6862   }
6863 
6864   return SGPRReg;
6865 }
6866 
6867 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
6868                                              unsigned OperandName) const {
6869   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
6870   if (Idx == -1)
6871     return nullptr;
6872 
6873   return &MI.getOperand(Idx);
6874 }
6875 
6876 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
6877   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
6878     return (AMDGPU::MTBUFFormat::UFMT_32_FLOAT << 44) |
6879            (1ULL << 56) | // RESOURCE_LEVEL = 1
6880            (3ULL << 60); // OOB_SELECT = 3
6881   }
6882 
6883   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
6884   if (ST.isAmdHsaOS()) {
6885     // Set ATC = 1. GFX9 doesn't have this bit.
6886     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6887       RsrcDataFormat |= (1ULL << 56);
6888 
6889     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
6890     // BTW, it disables TC L2 and therefore decreases performance.
6891     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
6892       RsrcDataFormat |= (2ULL << 59);
6893   }
6894 
6895   return RsrcDataFormat;
6896 }
6897 
6898 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
6899   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
6900                     AMDGPU::RSRC_TID_ENABLE |
6901                     0xffffffff; // Size;
6902 
6903   // GFX9 doesn't have ELEMENT_SIZE.
6904   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
6905     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
6906     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
6907   }
6908 
6909   // IndexStride = 64 / 32.
6910   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
6911   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
6912 
6913   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
6914   // Clear them unless we want a huge stride.
6915   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
6916       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
6917     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
6918 
6919   return Rsrc23;
6920 }
6921 
6922 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
6923   unsigned Opc = MI.getOpcode();
6924 
6925   return isSMRD(Opc);
6926 }
6927 
6928 bool SIInstrInfo::isHighLatencyDef(int Opc) const {
6929   return get(Opc).mayLoad() &&
6930          (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
6931 }
6932 
6933 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
6934                                     int &FrameIndex) const {
6935   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
6936   if (!Addr || !Addr->isFI())
6937     return AMDGPU::NoRegister;
6938 
6939   assert(!MI.memoperands_empty() &&
6940          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
6941 
6942   FrameIndex = Addr->getIndex();
6943   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
6944 }
6945 
6946 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
6947                                         int &FrameIndex) const {
6948   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
6949   assert(Addr && Addr->isFI());
6950   FrameIndex = Addr->getIndex();
6951   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
6952 }
6953 
6954 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
6955                                           int &FrameIndex) const {
6956   if (!MI.mayLoad())
6957     return AMDGPU::NoRegister;
6958 
6959   if (isMUBUF(MI) || isVGPRSpill(MI))
6960     return isStackAccess(MI, FrameIndex);
6961 
6962   if (isSGPRSpill(MI))
6963     return isSGPRStackAccess(MI, FrameIndex);
6964 
6965   return AMDGPU::NoRegister;
6966 }
6967 
6968 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
6969                                          int &FrameIndex) const {
6970   if (!MI.mayStore())
6971     return AMDGPU::NoRegister;
6972 
6973   if (isMUBUF(MI) || isVGPRSpill(MI))
6974     return isStackAccess(MI, FrameIndex);
6975 
6976   if (isSGPRSpill(MI))
6977     return isSGPRStackAccess(MI, FrameIndex);
6978 
6979   return AMDGPU::NoRegister;
6980 }
6981 
6982 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
6983   unsigned Size = 0;
6984   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
6985   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
6986   while (++I != E && I->isInsideBundle()) {
6987     assert(!I->isBundle() && "No nested bundle!");
6988     Size += getInstSizeInBytes(*I);
6989   }
6990 
6991   return Size;
6992 }
6993 
6994 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
6995   unsigned Opc = MI.getOpcode();
6996   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
6997   unsigned DescSize = Desc.getSize();
6998 
6999   // If we have a definitive size, we can use it. Otherwise we need to inspect
7000   // the operands to know the size.
7001   if (isFixedSize(MI)) {
7002     unsigned Size = DescSize;
7003 
7004     // If we hit the buggy offset, an extra nop will be inserted in MC so
7005     // estimate the worst case.
7006     if (MI.isBranch() && ST.hasOffset3fBug())
7007       Size += 4;
7008 
7009     return Size;
7010   }
7011 
7012   // 4-byte instructions may have a 32-bit literal encoded after them. Check
7013   // operands that coud ever be literals.
7014   if (isVALU(MI) || isSALU(MI)) {
7015     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
7016     if (Src0Idx == -1)
7017       return DescSize; // No operands.
7018 
7019     if (isLiteralConstantLike(MI.getOperand(Src0Idx), Desc.OpInfo[Src0Idx]))
7020       return isVOP3(MI) ? 12 : (DescSize + 4);
7021 
7022     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
7023     if (Src1Idx == -1)
7024       return DescSize;
7025 
7026     if (isLiteralConstantLike(MI.getOperand(Src1Idx), Desc.OpInfo[Src1Idx]))
7027       return isVOP3(MI) ? 12 : (DescSize + 4);
7028 
7029     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
7030     if (Src2Idx == -1)
7031       return DescSize;
7032 
7033     if (isLiteralConstantLike(MI.getOperand(Src2Idx), Desc.OpInfo[Src2Idx]))
7034       return isVOP3(MI) ? 12 : (DescSize + 4);
7035 
7036     return DescSize;
7037   }
7038 
7039   // Check whether we have extra NSA words.
7040   if (isMIMG(MI)) {
7041     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
7042     if (VAddr0Idx < 0)
7043       return 8;
7044 
7045     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
7046     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
7047   }
7048 
7049   switch (Opc) {
7050   case TargetOpcode::IMPLICIT_DEF:
7051   case TargetOpcode::KILL:
7052   case TargetOpcode::DBG_VALUE:
7053   case TargetOpcode::EH_LABEL:
7054     return 0;
7055   case TargetOpcode::BUNDLE:
7056     return getInstBundleSize(MI);
7057   case TargetOpcode::INLINEASM:
7058   case TargetOpcode::INLINEASM_BR: {
7059     const MachineFunction *MF = MI.getParent()->getParent();
7060     const char *AsmStr = MI.getOperand(0).getSymbolName();
7061     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(), &ST);
7062   }
7063   default:
7064     return DescSize;
7065   }
7066 }
7067 
7068 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
7069   if (!isFLAT(MI))
7070     return false;
7071 
7072   if (MI.memoperands_empty())
7073     return true;
7074 
7075   for (const MachineMemOperand *MMO : MI.memoperands()) {
7076     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
7077       return true;
7078   }
7079   return false;
7080 }
7081 
7082 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
7083   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
7084 }
7085 
7086 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
7087                                             MachineBasicBlock *IfEnd) const {
7088   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
7089   assert(TI != IfEntry->end());
7090 
7091   MachineInstr *Branch = &(*TI);
7092   MachineFunction *MF = IfEntry->getParent();
7093   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
7094 
7095   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7096     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7097     MachineInstr *SIIF =
7098         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
7099             .add(Branch->getOperand(0))
7100             .add(Branch->getOperand(1));
7101     MachineInstr *SIEND =
7102         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
7103             .addReg(DstReg);
7104 
7105     IfEntry->erase(TI);
7106     IfEntry->insert(IfEntry->end(), SIIF);
7107     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
7108   }
7109 }
7110 
7111 void SIInstrInfo::convertNonUniformLoopRegion(
7112     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
7113   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
7114   // We expect 2 terminators, one conditional and one unconditional.
7115   assert(TI != LoopEnd->end());
7116 
7117   MachineInstr *Branch = &(*TI);
7118   MachineFunction *MF = LoopEnd->getParent();
7119   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
7120 
7121   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7122 
7123     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7124     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
7125     MachineInstrBuilder HeaderPHIBuilder =
7126         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
7127     for (MachineBasicBlock::pred_iterator PI = LoopEntry->pred_begin(),
7128                                           E = LoopEntry->pred_end();
7129          PI != E; ++PI) {
7130       if (*PI == LoopEnd) {
7131         HeaderPHIBuilder.addReg(BackEdgeReg);
7132       } else {
7133         MachineBasicBlock *PMBB = *PI;
7134         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
7135         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
7136                              ZeroReg, 0);
7137         HeaderPHIBuilder.addReg(ZeroReg);
7138       }
7139       HeaderPHIBuilder.addMBB(*PI);
7140     }
7141     MachineInstr *HeaderPhi = HeaderPHIBuilder;
7142     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
7143                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
7144                                   .addReg(DstReg)
7145                                   .add(Branch->getOperand(0));
7146     MachineInstr *SILOOP =
7147         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
7148             .addReg(BackEdgeReg)
7149             .addMBB(LoopEntry);
7150 
7151     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
7152     LoopEnd->erase(TI);
7153     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
7154     LoopEnd->insert(LoopEnd->end(), SILOOP);
7155   }
7156 }
7157 
7158 ArrayRef<std::pair<int, const char *>>
7159 SIInstrInfo::getSerializableTargetIndices() const {
7160   static const std::pair<int, const char *> TargetIndices[] = {
7161       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
7162       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
7163       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
7164       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
7165       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
7166   return makeArrayRef(TargetIndices);
7167 }
7168 
7169 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
7170 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
7171 ScheduleHazardRecognizer *
7172 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
7173                                             const ScheduleDAG *DAG) const {
7174   return new GCNHazardRecognizer(DAG->MF);
7175 }
7176 
7177 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
7178 /// pass.
7179 ScheduleHazardRecognizer *
7180 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
7181   return new GCNHazardRecognizer(MF);
7182 }
7183 
7184 std::pair<unsigned, unsigned>
7185 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7186   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
7187 }
7188 
7189 ArrayRef<std::pair<unsigned, const char *>>
7190 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7191   static const std::pair<unsigned, const char *> TargetFlags[] = {
7192     { MO_GOTPCREL, "amdgpu-gotprel" },
7193     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
7194     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
7195     { MO_REL32_LO, "amdgpu-rel32-lo" },
7196     { MO_REL32_HI, "amdgpu-rel32-hi" },
7197     { MO_ABS32_LO, "amdgpu-abs32-lo" },
7198     { MO_ABS32_HI, "amdgpu-abs32-hi" },
7199   };
7200 
7201   return makeArrayRef(TargetFlags);
7202 }
7203 
7204 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
7205   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
7206          MI.modifiesRegister(AMDGPU::EXEC, &RI);
7207 }
7208 
7209 MachineInstrBuilder
7210 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7211                            MachineBasicBlock::iterator I,
7212                            const DebugLoc &DL,
7213                            Register DestReg) const {
7214   if (ST.hasAddNoCarry())
7215     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
7216 
7217   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7218   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
7219   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
7220 
7221   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7222            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7223 }
7224 
7225 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7226                                                MachineBasicBlock::iterator I,
7227                                                const DebugLoc &DL,
7228                                                Register DestReg,
7229                                                RegScavenger &RS) const {
7230   if (ST.hasAddNoCarry())
7231     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
7232 
7233   // If available, prefer to use vcc.
7234   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
7235                              ? Register(RI.getVCC())
7236                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
7237 
7238   // TODO: Users need to deal with this.
7239   if (!UnusedCarry.isValid())
7240     return MachineInstrBuilder();
7241 
7242   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7243            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7244 }
7245 
7246 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
7247   switch (Opcode) {
7248   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
7249   case AMDGPU::SI_KILL_I1_TERMINATOR:
7250     return true;
7251   default:
7252     return false;
7253   }
7254 }
7255 
7256 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
7257   switch (Opcode) {
7258   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7259     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
7260   case AMDGPU::SI_KILL_I1_PSEUDO:
7261     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
7262   default:
7263     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
7264   }
7265 }
7266 
7267 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
7268   if (!ST.isWave32())
7269     return;
7270 
7271   for (auto &Op : MI.implicit_operands()) {
7272     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
7273       Op.setReg(AMDGPU::VCC_LO);
7274   }
7275 }
7276 
7277 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
7278   if (!isSMRD(MI))
7279     return false;
7280 
7281   // Check that it is using a buffer resource.
7282   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
7283   if (Idx == -1) // e.g. s_memtime
7284     return false;
7285 
7286   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
7287   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
7288 }
7289 
7290 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
7291                                     bool Signed) const {
7292   // TODO: Should 0 be special cased?
7293   if (!ST.hasFlatInstOffsets())
7294     return false;
7295 
7296   if (ST.hasFlatSegmentOffsetBug() && AddrSpace == AMDGPUAS::FLAT_ADDRESS)
7297     return false;
7298 
7299   unsigned N = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7300   return Signed ? isIntN(N, Offset) : isUIntN(N, Offset);
7301 }
7302 
7303 std::pair<int64_t, int64_t> SIInstrInfo::splitFlatOffset(int64_t COffsetVal,
7304                                                          unsigned AddrSpace,
7305                                                          bool IsSigned) const {
7306   int64_t RemainderOffset = COffsetVal;
7307   int64_t ImmField = 0;
7308   const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST, IsSigned);
7309   if (IsSigned) {
7310     // Use signed division by a power of two to truncate towards 0.
7311     int64_t D = 1LL << (NumBits - 1);
7312     RemainderOffset = (COffsetVal / D) * D;
7313     ImmField = COffsetVal - RemainderOffset;
7314   } else if (COffsetVal >= 0) {
7315     ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
7316     RemainderOffset = COffsetVal - ImmField;
7317   }
7318 
7319   assert(isLegalFLATOffset(ImmField, AddrSpace, IsSigned));
7320   assert(RemainderOffset + ImmField == COffsetVal);
7321   return {ImmField, RemainderOffset};
7322 }
7323 
7324 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
7325 enum SIEncodingFamily {
7326   SI = 0,
7327   VI = 1,
7328   SDWA = 2,
7329   SDWA9 = 3,
7330   GFX80 = 4,
7331   GFX9 = 5,
7332   GFX10 = 6,
7333   SDWA10 = 7,
7334   GFX90A = 8
7335 };
7336 
7337 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
7338   switch (ST.getGeneration()) {
7339   default:
7340     break;
7341   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
7342   case AMDGPUSubtarget::SEA_ISLANDS:
7343     return SIEncodingFamily::SI;
7344   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
7345   case AMDGPUSubtarget::GFX9:
7346     return SIEncodingFamily::VI;
7347   case AMDGPUSubtarget::GFX10:
7348     return SIEncodingFamily::GFX10;
7349   }
7350   llvm_unreachable("Unknown subtarget generation!");
7351 }
7352 
7353 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
7354   switch(MCOp) {
7355   // These opcodes use indirect register addressing so
7356   // they need special handling by codegen (currently missing).
7357   // Therefore it is too risky to allow these opcodes
7358   // to be selected by dpp combiner or sdwa peepholer.
7359   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
7360   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
7361   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
7362   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
7363   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
7364   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
7365   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
7366   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
7367     return true;
7368   default:
7369     return false;
7370   }
7371 }
7372 
7373 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
7374   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
7375 
7376   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
7377     ST.getGeneration() == AMDGPUSubtarget::GFX9)
7378     Gen = SIEncodingFamily::GFX9;
7379 
7380   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
7381   // subtarget has UnpackedD16VMem feature.
7382   // TODO: remove this when we discard GFX80 encoding.
7383   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
7384     Gen = SIEncodingFamily::GFX80;
7385 
7386   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
7387     switch (ST.getGeneration()) {
7388     default:
7389       Gen = SIEncodingFamily::SDWA;
7390       break;
7391     case AMDGPUSubtarget::GFX9:
7392       Gen = SIEncodingFamily::SDWA9;
7393       break;
7394     case AMDGPUSubtarget::GFX10:
7395       Gen = SIEncodingFamily::SDWA10;
7396       break;
7397     }
7398   }
7399 
7400   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
7401 
7402   // -1 means that Opcode is already a native instruction.
7403   if (MCOp == -1)
7404     return Opcode;
7405 
7406   if (ST.hasGFX90AInsts()) {
7407     uint16_t NMCOp = (uint16_t)-1;
7408       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX90A);
7409     if (NMCOp == (uint16_t)-1)
7410       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX9);
7411     if (NMCOp != (uint16_t)-1)
7412       MCOp = NMCOp;
7413   }
7414 
7415   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
7416   // no encoding in the given subtarget generation.
7417   if (MCOp == (uint16_t)-1)
7418     return -1;
7419 
7420   if (isAsmOnlyOpcode(MCOp))
7421     return -1;
7422 
7423   return MCOp;
7424 }
7425 
7426 static
7427 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
7428   assert(RegOpnd.isReg());
7429   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
7430                              getRegSubRegPair(RegOpnd);
7431 }
7432 
7433 TargetInstrInfo::RegSubRegPair
7434 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
7435   assert(MI.isRegSequence());
7436   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
7437     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
7438       auto &RegOp = MI.getOperand(1 + 2 * I);
7439       return getRegOrUndef(RegOp);
7440     }
7441   return TargetInstrInfo::RegSubRegPair();
7442 }
7443 
7444 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
7445 // Following a subreg of reg:subreg isn't supported
7446 static bool followSubRegDef(MachineInstr &MI,
7447                             TargetInstrInfo::RegSubRegPair &RSR) {
7448   if (!RSR.SubReg)
7449     return false;
7450   switch (MI.getOpcode()) {
7451   default: break;
7452   case AMDGPU::REG_SEQUENCE:
7453     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
7454     return true;
7455   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
7456   case AMDGPU::INSERT_SUBREG:
7457     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
7458       // inserted the subreg we're looking for
7459       RSR = getRegOrUndef(MI.getOperand(2));
7460     else { // the subreg in the rest of the reg
7461       auto R1 = getRegOrUndef(MI.getOperand(1));
7462       if (R1.SubReg) // subreg of subreg isn't supported
7463         return false;
7464       RSR.Reg = R1.Reg;
7465     }
7466     return true;
7467   }
7468   return false;
7469 }
7470 
7471 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
7472                                      MachineRegisterInfo &MRI) {
7473   assert(MRI.isSSA());
7474   if (!P.Reg.isVirtual())
7475     return nullptr;
7476 
7477   auto RSR = P;
7478   auto *DefInst = MRI.getVRegDef(RSR.Reg);
7479   while (auto *MI = DefInst) {
7480     DefInst = nullptr;
7481     switch (MI->getOpcode()) {
7482     case AMDGPU::COPY:
7483     case AMDGPU::V_MOV_B32_e32: {
7484       auto &Op1 = MI->getOperand(1);
7485       if (Op1.isReg() && Op1.getReg().isVirtual()) {
7486         if (Op1.isUndef())
7487           return nullptr;
7488         RSR = getRegSubRegPair(Op1);
7489         DefInst = MRI.getVRegDef(RSR.Reg);
7490       }
7491       break;
7492     }
7493     default:
7494       if (followSubRegDef(*MI, RSR)) {
7495         if (!RSR.Reg)
7496           return nullptr;
7497         DefInst = MRI.getVRegDef(RSR.Reg);
7498       }
7499     }
7500     if (!DefInst)
7501       return MI;
7502   }
7503   return nullptr;
7504 }
7505 
7506 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
7507                                       Register VReg,
7508                                       const MachineInstr &DefMI,
7509                                       const MachineInstr &UseMI) {
7510   assert(MRI.isSSA() && "Must be run on SSA");
7511 
7512   auto *TRI = MRI.getTargetRegisterInfo();
7513   auto *DefBB = DefMI.getParent();
7514 
7515   // Don't bother searching between blocks, although it is possible this block
7516   // doesn't modify exec.
7517   if (UseMI.getParent() != DefBB)
7518     return true;
7519 
7520   const int MaxInstScan = 20;
7521   int NumInst = 0;
7522 
7523   // Stop scan at the use.
7524   auto E = UseMI.getIterator();
7525   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
7526     if (I->isDebugInstr())
7527       continue;
7528 
7529     if (++NumInst > MaxInstScan)
7530       return true;
7531 
7532     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
7533       return true;
7534   }
7535 
7536   return false;
7537 }
7538 
7539 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
7540                                          Register VReg,
7541                                          const MachineInstr &DefMI) {
7542   assert(MRI.isSSA() && "Must be run on SSA");
7543 
7544   auto *TRI = MRI.getTargetRegisterInfo();
7545   auto *DefBB = DefMI.getParent();
7546 
7547   const int MaxUseScan = 10;
7548   int NumUse = 0;
7549 
7550   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
7551     auto &UseInst = *Use.getParent();
7552     // Don't bother searching between blocks, although it is possible this block
7553     // doesn't modify exec.
7554     if (UseInst.getParent() != DefBB)
7555       return true;
7556 
7557     if (++NumUse > MaxUseScan)
7558       return true;
7559   }
7560 
7561   if (NumUse == 0)
7562     return false;
7563 
7564   const int MaxInstScan = 20;
7565   int NumInst = 0;
7566 
7567   // Stop scan when we have seen all the uses.
7568   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
7569     assert(I != DefBB->end());
7570 
7571     if (I->isDebugInstr())
7572       continue;
7573 
7574     if (++NumInst > MaxInstScan)
7575       return true;
7576 
7577     for (const MachineOperand &Op : I->operands()) {
7578       // We don't check reg masks here as they're used only on calls:
7579       // 1. EXEC is only considered const within one BB
7580       // 2. Call should be a terminator instruction if present in a BB
7581 
7582       if (!Op.isReg())
7583         continue;
7584 
7585       Register Reg = Op.getReg();
7586       if (Op.isUse()) {
7587         if (Reg == VReg && --NumUse == 0)
7588           return false;
7589       } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
7590         return true;
7591     }
7592   }
7593 }
7594 
7595 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
7596     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
7597     const DebugLoc &DL, Register Src, Register Dst) const {
7598   auto Cur = MBB.begin();
7599   if (Cur != MBB.end())
7600     do {
7601       if (!Cur->isPHI() && Cur->readsRegister(Dst))
7602         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
7603       ++Cur;
7604     } while (Cur != MBB.end() && Cur != LastPHIIt);
7605 
7606   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
7607                                                    Dst);
7608 }
7609 
7610 MachineInstr *SIInstrInfo::createPHISourceCopy(
7611     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
7612     const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
7613   if (InsPt != MBB.end() &&
7614       (InsPt->getOpcode() == AMDGPU::SI_IF ||
7615        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
7616        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
7617       InsPt->definesRegister(Src)) {
7618     InsPt++;
7619     return BuildMI(MBB, InsPt, DL,
7620                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
7621                                      : AMDGPU::S_MOV_B64_term),
7622                    Dst)
7623         .addReg(Src, 0, SrcSubReg)
7624         .addReg(AMDGPU::EXEC, RegState::Implicit);
7625   }
7626   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
7627                                               Dst);
7628 }
7629 
7630 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
7631 
7632 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
7633     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
7634     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
7635     VirtRegMap *VRM) const {
7636   // This is a bit of a hack (copied from AArch64). Consider this instruction:
7637   //
7638   //   %0:sreg_32 = COPY $m0
7639   //
7640   // We explicitly chose SReg_32 for the virtual register so such a copy might
7641   // be eliminated by RegisterCoalescer. However, that may not be possible, and
7642   // %0 may even spill. We can't spill $m0 normally (it would require copying to
7643   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
7644   // TargetInstrInfo::foldMemoryOperand() is going to try.
7645   // A similar issue also exists with spilling and reloading $exec registers.
7646   //
7647   // To prevent that, constrain the %0 register class here.
7648   if (MI.isFullCopy()) {
7649     Register DstReg = MI.getOperand(0).getReg();
7650     Register SrcReg = MI.getOperand(1).getReg();
7651     if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
7652         (DstReg.isVirtual() != SrcReg.isVirtual())) {
7653       MachineRegisterInfo &MRI = MF.getRegInfo();
7654       Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
7655       const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
7656       if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
7657         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
7658         return nullptr;
7659       } else if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
7660         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
7661         return nullptr;
7662       }
7663     }
7664   }
7665 
7666   return nullptr;
7667 }
7668 
7669 unsigned SIInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
7670                                       const MachineInstr &MI,
7671                                       unsigned *PredCost) const {
7672   if (MI.isBundle()) {
7673     MachineBasicBlock::const_instr_iterator I(MI.getIterator());
7674     MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
7675     unsigned Lat = 0, Count = 0;
7676     for (++I; I != E && I->isBundledWithPred(); ++I) {
7677       ++Count;
7678       Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
7679     }
7680     return Lat + Count - 1;
7681   }
7682 
7683   return SchedModel.computeInstrLatency(&MI);
7684 }
7685 
7686 unsigned SIInstrInfo::getDSShaderTypeValue(const MachineFunction &MF) {
7687   switch (MF.getFunction().getCallingConv()) {
7688   case CallingConv::AMDGPU_PS:
7689     return 1;
7690   case CallingConv::AMDGPU_VS:
7691     return 2;
7692   case CallingConv::AMDGPU_GS:
7693     return 3;
7694   case CallingConv::AMDGPU_HS:
7695   case CallingConv::AMDGPU_LS:
7696   case CallingConv::AMDGPU_ES:
7697     report_fatal_error("ds_ordered_count unsupported for this calling conv");
7698   case CallingConv::AMDGPU_CS:
7699   case CallingConv::AMDGPU_KERNEL:
7700   case CallingConv::C:
7701   case CallingConv::Fast:
7702   default:
7703     // Assume other calling conventions are various compute callable functions
7704     return 0;
7705   }
7706 }
7707