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