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