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