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