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 
3986   // Make sure the number of operands is correct.
3987   const MCInstrDesc &Desc = get(Opcode);
3988   if (!Desc.isVariadic() &&
3989       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
3990     ErrInfo = "Instruction has wrong number of operands.";
3991     return false;
3992   }
3993 
3994   if (MI.isInlineAsm()) {
3995     // Verify register classes for inlineasm constraints.
3996     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
3997          I != E; ++I) {
3998       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
3999       if (!RC)
4000         continue;
4001 
4002       const MachineOperand &Op = MI.getOperand(I);
4003       if (!Op.isReg())
4004         continue;
4005 
4006       Register Reg = Op.getReg();
4007       if (!Reg.isVirtual() && !RC->contains(Reg)) {
4008         ErrInfo = "inlineasm operand has incorrect register class.";
4009         return false;
4010       }
4011     }
4012 
4013     return true;
4014   }
4015 
4016   if (isMIMG(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
4017     ErrInfo = "missing memory operand from MIMG instruction.";
4018     return false;
4019   }
4020 
4021   // Make sure the register classes are correct.
4022   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
4023     const MachineOperand &MO = MI.getOperand(i);
4024     if (MO.isFPImm()) {
4025       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
4026                 "all fp values to integers.";
4027       return false;
4028     }
4029 
4030     int RegClass = Desc.OpInfo[i].RegClass;
4031 
4032     switch (Desc.OpInfo[i].OperandType) {
4033     case MCOI::OPERAND_REGISTER:
4034       if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
4035         ErrInfo = "Illegal immediate value for operand.";
4036         return false;
4037       }
4038       break;
4039     case AMDGPU::OPERAND_REG_IMM_INT32:
4040     case AMDGPU::OPERAND_REG_IMM_FP32:
4041     case AMDGPU::OPERAND_REG_IMM_FP32_DEFERRED:
4042     case AMDGPU::OPERAND_REG_IMM_V2FP32:
4043       break;
4044     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
4045     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
4046     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
4047     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
4048     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
4049     case AMDGPU::OPERAND_REG_INLINE_C_FP16:
4050     case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
4051     case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
4052     case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
4053     case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
4054     case AMDGPU::OPERAND_REG_INLINE_AC_FP64: {
4055       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
4056         ErrInfo = "Illegal immediate value for operand.";
4057         return false;
4058       }
4059       break;
4060     }
4061     case MCOI::OPERAND_IMMEDIATE:
4062     case AMDGPU::OPERAND_KIMM32:
4063       // Check if this operand is an immediate.
4064       // FrameIndex operands will be replaced by immediates, so they are
4065       // allowed.
4066       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
4067         ErrInfo = "Expected immediate, but got non-immediate";
4068         return false;
4069       }
4070       LLVM_FALLTHROUGH;
4071     default:
4072       continue;
4073     }
4074 
4075     if (!MO.isReg())
4076       continue;
4077     Register Reg = MO.getReg();
4078     if (!Reg)
4079       continue;
4080 
4081     // FIXME: Ideally we would have separate instruction definitions with the
4082     // aligned register constraint.
4083     // FIXME: We do not verify inline asm operands, but custom inline asm
4084     // verification is broken anyway
4085     if (ST.needsAlignedVGPRs()) {
4086       const TargetRegisterClass *RC = RI.getRegClassForReg(MRI, Reg);
4087       if (RI.hasVectorRegisters(RC) && MO.getSubReg()) {
4088         const TargetRegisterClass *SubRC =
4089             RI.getSubRegClass(RC, MO.getSubReg());
4090         RC = RI.getCompatibleSubRegClass(RC, SubRC, MO.getSubReg());
4091         if (RC)
4092           RC = SubRC;
4093       }
4094 
4095       // Check that this is the aligned version of the class.
4096       if (!RC || !RI.isProperlyAlignedRC(*RC)) {
4097         ErrInfo = "Subtarget requires even aligned vector registers";
4098         return false;
4099       }
4100     }
4101 
4102     if (RegClass != -1) {
4103       if (Reg.isVirtual())
4104         continue;
4105 
4106       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
4107       if (!RC->contains(Reg)) {
4108         ErrInfo = "Operand has incorrect register class.";
4109         return false;
4110       }
4111     }
4112   }
4113 
4114   // Verify SDWA
4115   if (isSDWA(MI)) {
4116     if (!ST.hasSDWA()) {
4117       ErrInfo = "SDWA is not supported on this target";
4118       return false;
4119     }
4120 
4121     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4122 
4123     for (int OpIdx : {DstIdx, Src0Idx, Src1Idx, Src2Idx}) {
4124       if (OpIdx == -1)
4125         continue;
4126       const MachineOperand &MO = MI.getOperand(OpIdx);
4127 
4128       if (!ST.hasSDWAScalar()) {
4129         // Only VGPRS on VI
4130         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
4131           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
4132           return false;
4133         }
4134       } else {
4135         // No immediates on GFX9
4136         if (!MO.isReg()) {
4137           ErrInfo =
4138             "Only reg allowed as operands in SDWA instructions on GFX9+";
4139           return false;
4140         }
4141       }
4142     }
4143 
4144     if (!ST.hasSDWAOmod()) {
4145       // No omod allowed on VI
4146       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
4147       if (OMod != nullptr &&
4148         (!OMod->isImm() || OMod->getImm() != 0)) {
4149         ErrInfo = "OMod not allowed in SDWA instructions on VI";
4150         return false;
4151       }
4152     }
4153 
4154     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
4155     if (isVOPC(BasicOpcode)) {
4156       if (!ST.hasSDWASdst() && DstIdx != -1) {
4157         // Only vcc allowed as dst on VI for VOPC
4158         const MachineOperand &Dst = MI.getOperand(DstIdx);
4159         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
4160           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
4161           return false;
4162         }
4163       } else if (!ST.hasSDWAOutModsVOPC()) {
4164         // No clamp allowed on GFX9 for VOPC
4165         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
4166         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
4167           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
4168           return false;
4169         }
4170 
4171         // No omod allowed on GFX9 for VOPC
4172         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
4173         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
4174           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
4175           return false;
4176         }
4177       }
4178     }
4179 
4180     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
4181     if (DstUnused && DstUnused->isImm() &&
4182         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
4183       const MachineOperand &Dst = MI.getOperand(DstIdx);
4184       if (!Dst.isReg() || !Dst.isTied()) {
4185         ErrInfo = "Dst register should have tied register";
4186         return false;
4187       }
4188 
4189       const MachineOperand &TiedMO =
4190           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
4191       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
4192         ErrInfo =
4193             "Dst register should be tied to implicit use of preserved register";
4194         return false;
4195       } else if (TiedMO.getReg().isPhysical() &&
4196                  Dst.getReg() != TiedMO.getReg()) {
4197         ErrInfo = "Dst register should use same physical register as preserved";
4198         return false;
4199       }
4200     }
4201   }
4202 
4203   // Verify MIMG
4204   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
4205     // Ensure that the return type used is large enough for all the options
4206     // being used TFE/LWE require an extra result register.
4207     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
4208     if (DMask) {
4209       uint64_t DMaskImm = DMask->getImm();
4210       uint32_t RegCount =
4211           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
4212       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
4213       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
4214       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
4215 
4216       // Adjust for packed 16 bit values
4217       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
4218         RegCount >>= 1;
4219 
4220       // Adjust if using LWE or TFE
4221       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
4222         RegCount += 1;
4223 
4224       const uint32_t DstIdx =
4225           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
4226       const MachineOperand &Dst = MI.getOperand(DstIdx);
4227       if (Dst.isReg()) {
4228         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
4229         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
4230         if (RegCount > DstSize) {
4231           ErrInfo = "MIMG instruction returns too many registers for dst "
4232                     "register class";
4233           return false;
4234         }
4235       }
4236     }
4237   }
4238 
4239   // Verify VOP*. Ignore multiple sgpr operands on writelane.
4240   if (isVALU(MI) && Desc.getOpcode() != AMDGPU::V_WRITELANE_B32) {
4241     unsigned ConstantBusCount = 0;
4242     bool UsesLiteral = false;
4243     const MachineOperand *LiteralVal = nullptr;
4244 
4245     int ImmIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm);
4246     if (ImmIdx != -1) {
4247       ++ConstantBusCount;
4248       UsesLiteral = true;
4249       LiteralVal = &MI.getOperand(ImmIdx);
4250     }
4251 
4252     SmallVector<Register, 2> SGPRsUsed;
4253     Register SGPRUsed;
4254 
4255     // Only look at the true operands. Only a real operand can use the constant
4256     // bus, and we don't want to check pseudo-operands like the source modifier
4257     // flags.
4258     for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx}) {
4259       if (OpIdx == -1)
4260         break;
4261       const MachineOperand &MO = MI.getOperand(OpIdx);
4262       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4263         if (MO.isReg()) {
4264           SGPRUsed = MO.getReg();
4265           if (llvm::all_of(SGPRsUsed, [SGPRUsed](unsigned SGPR) {
4266                 return SGPRUsed != SGPR;
4267               })) {
4268             ++ConstantBusCount;
4269             SGPRsUsed.push_back(SGPRUsed);
4270           }
4271         } else {
4272           if (!UsesLiteral) {
4273             ++ConstantBusCount;
4274             UsesLiteral = true;
4275             LiteralVal = &MO;
4276           } else if (!MO.isIdenticalTo(*LiteralVal)) {
4277             assert(isVOP2(MI) || isVOP3(MI));
4278             ErrInfo = "VOP2/VOP3 instruction uses more than one literal";
4279             return false;
4280           }
4281         }
4282       }
4283     }
4284 
4285     SGPRUsed = findImplicitSGPRRead(MI);
4286     if (SGPRUsed != AMDGPU::NoRegister) {
4287       // Implicit uses may safely overlap true operands
4288       if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
4289             return !RI.regsOverlap(SGPRUsed, SGPR);
4290           })) {
4291         ++ConstantBusCount;
4292         SGPRsUsed.push_back(SGPRUsed);
4293       }
4294     }
4295 
4296     // v_writelane_b32 is an exception from constant bus restriction:
4297     // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
4298     if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
4299         Opcode != AMDGPU::V_WRITELANE_B32) {
4300       ErrInfo = "VOP* instruction violates constant bus restriction";
4301       return false;
4302     }
4303 
4304     if (isVOP3(MI) && UsesLiteral && !ST.hasVOP3Literal()) {
4305       ErrInfo = "VOP3 instruction uses literal";
4306       return false;
4307     }
4308   }
4309 
4310   // Special case for writelane - this can break the multiple constant bus rule,
4311   // but still can't use more than one SGPR register
4312   if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
4313     unsigned SGPRCount = 0;
4314     Register SGPRUsed = AMDGPU::NoRegister;
4315 
4316     for (int OpIdx : {Src0Idx, Src1Idx}) {
4317       if (OpIdx == -1)
4318         break;
4319 
4320       const MachineOperand &MO = MI.getOperand(OpIdx);
4321 
4322       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4323         if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
4324           if (MO.getReg() != SGPRUsed)
4325             ++SGPRCount;
4326           SGPRUsed = MO.getReg();
4327         }
4328       }
4329       if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
4330         ErrInfo = "WRITELANE instruction violates constant bus restriction";
4331         return false;
4332       }
4333     }
4334   }
4335 
4336   // Verify misc. restrictions on specific instructions.
4337   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
4338       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
4339     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4340     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4341     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
4342     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
4343       if (!compareMachineOp(Src0, Src1) &&
4344           !compareMachineOp(Src0, Src2)) {
4345         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
4346         return false;
4347       }
4348     }
4349     if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
4350          SISrcMods::ABS) ||
4351         (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
4352          SISrcMods::ABS) ||
4353         (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
4354          SISrcMods::ABS)) {
4355       ErrInfo = "ABS not allowed in VOP3B instructions";
4356       return false;
4357     }
4358   }
4359 
4360   if (isSOP2(MI) || isSOPC(MI)) {
4361     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4362     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4363 
4364     if (!Src0.isReg() && !Src1.isReg() &&
4365         !isInlineConstant(Src0, Desc.OpInfo[Src0Idx].OperandType) &&
4366         !isInlineConstant(Src1, Desc.OpInfo[Src1Idx].OperandType) &&
4367         !Src0.isIdenticalTo(Src1)) {
4368       ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
4369       return false;
4370     }
4371   }
4372 
4373   if (isSOPK(MI)) {
4374     auto Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
4375     if (Desc.isBranch()) {
4376       if (!Op->isMBB()) {
4377         ErrInfo = "invalid branch target for SOPK instruction";
4378         return false;
4379       }
4380     } else {
4381       uint64_t Imm = Op->getImm();
4382       if (sopkIsZext(MI)) {
4383         if (!isUInt<16>(Imm)) {
4384           ErrInfo = "invalid immediate for SOPK instruction";
4385           return false;
4386         }
4387       } else {
4388         if (!isInt<16>(Imm)) {
4389           ErrInfo = "invalid immediate for SOPK instruction";
4390           return false;
4391         }
4392       }
4393     }
4394   }
4395 
4396   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
4397       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
4398       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4399       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
4400     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4401                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
4402 
4403     const unsigned StaticNumOps = Desc.getNumOperands() +
4404       Desc.getNumImplicitUses();
4405     const unsigned NumImplicitOps = IsDst ? 2 : 1;
4406 
4407     // Allow additional implicit operands. This allows a fixup done by the post
4408     // RA scheduler where the main implicit operand is killed and implicit-defs
4409     // are added for sub-registers that remain live after this instruction.
4410     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
4411       ErrInfo = "missing implicit register operands";
4412       return false;
4413     }
4414 
4415     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4416     if (IsDst) {
4417       if (!Dst->isUse()) {
4418         ErrInfo = "v_movreld_b32 vdst should be a use operand";
4419         return false;
4420       }
4421 
4422       unsigned UseOpIdx;
4423       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
4424           UseOpIdx != StaticNumOps + 1) {
4425         ErrInfo = "movrel implicit operands should be tied";
4426         return false;
4427       }
4428     }
4429 
4430     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4431     const MachineOperand &ImpUse
4432       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
4433     if (!ImpUse.isReg() || !ImpUse.isUse() ||
4434         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
4435       ErrInfo = "src0 should be subreg of implicit vector use";
4436       return false;
4437     }
4438   }
4439 
4440   // Make sure we aren't losing exec uses in the td files. This mostly requires
4441   // being careful when using let Uses to try to add other use registers.
4442   if (shouldReadExec(MI)) {
4443     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
4444       ErrInfo = "VALU instruction does not implicitly read exec mask";
4445       return false;
4446     }
4447   }
4448 
4449   if (isSMRD(MI)) {
4450     if (MI.mayStore() &&
4451         ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4452       // The register offset form of scalar stores may only use m0 as the
4453       // soffset register.
4454       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soffset);
4455       if (Soff && Soff->getReg() != AMDGPU::M0) {
4456         ErrInfo = "scalar stores must use m0 as offset register";
4457         return false;
4458       }
4459     }
4460   }
4461 
4462   if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
4463     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4464     if (Offset->getImm() != 0) {
4465       ErrInfo = "subtarget does not support offsets in flat instructions";
4466       return false;
4467     }
4468   }
4469 
4470   if (isMIMG(MI)) {
4471     const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
4472     if (DimOp) {
4473       int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
4474                                                  AMDGPU::OpName::vaddr0);
4475       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
4476       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
4477       const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4478           AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
4479       const AMDGPU::MIMGDimInfo *Dim =
4480           AMDGPU::getMIMGDimInfoByEncoding(DimOp->getImm());
4481 
4482       if (!Dim) {
4483         ErrInfo = "dim is out of range";
4484         return false;
4485       }
4486 
4487       bool IsA16 = false;
4488       if (ST.hasR128A16()) {
4489         const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
4490         IsA16 = R128A16->getImm() != 0;
4491       } else if (ST.hasGFX10A16()) {
4492         const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
4493         IsA16 = A16->getImm() != 0;
4494       }
4495 
4496       bool IsNSA = SRsrcIdx - VAddr0Idx > 1;
4497 
4498       unsigned AddrWords =
4499           AMDGPU::getAddrSizeMIMGOp(BaseOpcode, Dim, IsA16, ST.hasG16());
4500 
4501       unsigned VAddrWords;
4502       if (IsNSA) {
4503         VAddrWords = SRsrcIdx - VAddr0Idx;
4504       } else {
4505         const TargetRegisterClass *RC = getOpRegClass(MI, VAddr0Idx);
4506         VAddrWords = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 32;
4507         if (AddrWords > 8)
4508           AddrWords = 16;
4509       }
4510 
4511       if (VAddrWords != AddrWords) {
4512         LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
4513                           << " but got " << VAddrWords << "\n");
4514         ErrInfo = "bad vaddr size";
4515         return false;
4516       }
4517     }
4518   }
4519 
4520   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
4521   if (DppCt) {
4522     using namespace AMDGPU::DPP;
4523 
4524     unsigned DC = DppCt->getImm();
4525     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
4526         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
4527         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
4528         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
4529         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
4530         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
4531         (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
4532       ErrInfo = "Invalid dpp_ctrl value";
4533       return false;
4534     }
4535     if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
4536         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4537       ErrInfo = "Invalid dpp_ctrl value: "
4538                 "wavefront shifts are not supported on GFX10+";
4539       return false;
4540     }
4541     if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
4542         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4543       ErrInfo = "Invalid dpp_ctrl value: "
4544                 "broadcasts are not supported on GFX10+";
4545       return false;
4546     }
4547     if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
4548         ST.getGeneration() < AMDGPUSubtarget::GFX10) {
4549       if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
4550           DC <= DppCtrl::ROW_NEWBCAST_LAST &&
4551           !ST.hasGFX90AInsts()) {
4552         ErrInfo = "Invalid dpp_ctrl value: "
4553                   "row_newbroadcast/row_share is not supported before "
4554                   "GFX90A/GFX10";
4555         return false;
4556       } else if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
4557         ErrInfo = "Invalid dpp_ctrl value: "
4558                   "row_share and row_xmask are not supported before GFX10";
4559         return false;
4560       }
4561     }
4562 
4563     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4564 
4565     if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
4566         ((DstIdx >= 0 &&
4567           (Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64RegClassID ||
4568            Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64_Align2RegClassID)) ||
4569          ((Src0Idx >= 0 &&
4570            (Desc.OpInfo[Src0Idx].RegClass == AMDGPU::VReg_64RegClassID ||
4571             Desc.OpInfo[Src0Idx].RegClass ==
4572                 AMDGPU::VReg_64_Align2RegClassID)))) &&
4573         !AMDGPU::isLegal64BitDPPControl(DC)) {
4574       ErrInfo = "Invalid dpp_ctrl value: "
4575                 "64 bit dpp only support row_newbcast";
4576       return false;
4577     }
4578   }
4579 
4580   if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
4581     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4582     uint16_t DataNameIdx = isDS(Opcode) ? AMDGPU::OpName::data0
4583                                         : AMDGPU::OpName::vdata;
4584     const MachineOperand *Data = getNamedOperand(MI, DataNameIdx);
4585     const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
4586     if (Data && !Data->isReg())
4587       Data = nullptr;
4588 
4589     if (ST.hasGFX90AInsts()) {
4590       if (Dst && Data &&
4591           (RI.isAGPR(MRI, Dst->getReg()) != RI.isAGPR(MRI, Data->getReg()))) {
4592         ErrInfo = "Invalid register class: "
4593                   "vdata and vdst should be both VGPR or AGPR";
4594         return false;
4595       }
4596       if (Data && Data2 &&
4597           (RI.isAGPR(MRI, Data->getReg()) != RI.isAGPR(MRI, Data2->getReg()))) {
4598         ErrInfo = "Invalid register class: "
4599                   "both data operands should be VGPR or AGPR";
4600         return false;
4601       }
4602     } else {
4603       if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
4604           (Data && RI.isAGPR(MRI, Data->getReg())) ||
4605           (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
4606         ErrInfo = "Invalid register class: "
4607                   "agpr loads and stores not supported on this GPU";
4608         return false;
4609       }
4610     }
4611   }
4612 
4613   if (ST.needsAlignedVGPRs()) {
4614     const auto isAlignedReg = [&MI, &MRI, this](unsigned OpName) -> bool {
4615       const MachineOperand *Op = getNamedOperand(MI, OpName);
4616       if (!Op)
4617         return true;
4618       Register Reg = Op->getReg();
4619       if (Reg.isPhysical())
4620         return !(RI.getHWRegIndex(Reg) & 1);
4621       const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
4622       return RI.getRegSizeInBits(RC) > 32 && RI.isProperlyAlignedRC(RC) &&
4623              !(RI.getChannelFromSubReg(Op->getSubReg()) & 1);
4624     };
4625 
4626     if (MI.getOpcode() == AMDGPU::DS_GWS_INIT ||
4627         MI.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
4628         MI.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
4629 
4630       if (!isAlignedReg(AMDGPU::OpName::data0)) {
4631         ErrInfo = "Subtarget requires even aligned vector registers "
4632                   "for DS_GWS instructions";
4633         return false;
4634       }
4635     }
4636 
4637     if (isMIMG(MI)) {
4638       if (!isAlignedReg(AMDGPU::OpName::vaddr)) {
4639         ErrInfo = "Subtarget requires even aligned vector registers "
4640                   "for vaddr operand of image instructions";
4641         return false;
4642       }
4643     }
4644   }
4645 
4646   if (MI.getOpcode() == AMDGPU::V_ACCVGPR_WRITE_B32_e64 &&
4647       !ST.hasGFX90AInsts()) {
4648     const MachineOperand *Src = getNamedOperand(MI, AMDGPU::OpName::src0);
4649     if (Src->isReg() && RI.isSGPRReg(MRI, Src->getReg())) {
4650       ErrInfo = "Invalid register class: "
4651                 "v_accvgpr_write with an SGPR is not supported on this GPU";
4652       return false;
4653     }
4654   }
4655 
4656   if (Desc.getOpcode() == AMDGPU::G_AMDGPU_WAVE_ADDRESS) {
4657     const MachineOperand &SrcOp = MI.getOperand(1);
4658     if (!SrcOp.isReg() || SrcOp.getReg().isVirtual()) {
4659       ErrInfo = "pseudo expects only physical SGPRs";
4660       return false;
4661     }
4662   }
4663 
4664   return true;
4665 }
4666 
4667 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
4668   switch (MI.getOpcode()) {
4669   default: return AMDGPU::INSTRUCTION_LIST_END;
4670   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
4671   case AMDGPU::COPY: return AMDGPU::COPY;
4672   case AMDGPU::PHI: return AMDGPU::PHI;
4673   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
4674   case AMDGPU::WQM: return AMDGPU::WQM;
4675   case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
4676   case AMDGPU::STRICT_WWM: return AMDGPU::STRICT_WWM;
4677   case AMDGPU::STRICT_WQM: return AMDGPU::STRICT_WQM;
4678   case AMDGPU::S_MOV_B32: {
4679     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4680     return MI.getOperand(1).isReg() ||
4681            RI.isAGPR(MRI, MI.getOperand(0).getReg()) ?
4682            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
4683   }
4684   case AMDGPU::S_ADD_I32:
4685     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
4686   case AMDGPU::S_ADDC_U32:
4687     return AMDGPU::V_ADDC_U32_e32;
4688   case AMDGPU::S_SUB_I32:
4689     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
4690     // FIXME: These are not consistently handled, and selected when the carry is
4691     // used.
4692   case AMDGPU::S_ADD_U32:
4693     return AMDGPU::V_ADD_CO_U32_e32;
4694   case AMDGPU::S_SUB_U32:
4695     return AMDGPU::V_SUB_CO_U32_e32;
4696   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
4697   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
4698   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
4699   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
4700   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
4701   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
4702   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
4703   case AMDGPU::S_XNOR_B32:
4704     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
4705   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
4706   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
4707   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
4708   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
4709   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
4710   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
4711   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
4712   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
4713   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
4714   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
4715   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
4716   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
4717   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
4718   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
4719   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
4720   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
4721   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
4722   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
4723   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e64;
4724   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e64;
4725   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e64;
4726   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e64;
4727   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e64;
4728   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e64;
4729   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e64;
4730   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e64;
4731   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e64;
4732   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e64;
4733   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e64;
4734   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e64;
4735   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e64;
4736   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e64;
4737   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
4738   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
4739   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
4740   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
4741   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
4742   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
4743   }
4744   llvm_unreachable(
4745       "Unexpected scalar opcode without corresponding vector one!");
4746 }
4747 
4748 static const TargetRegisterClass *
4749 adjustAllocatableRegClass(const GCNSubtarget &ST, const SIRegisterInfo &RI,
4750                           const MachineRegisterInfo &MRI,
4751                           const MCInstrDesc &TID, unsigned RCID,
4752                           bool IsAllocatable) {
4753   if ((IsAllocatable || !ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4754       (((TID.mayLoad() || TID.mayStore()) &&
4755         !(TID.TSFlags & SIInstrFlags::VGPRSpill)) ||
4756        (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::MIMG)))) {
4757     switch (RCID) {
4758     case AMDGPU::AV_32RegClassID:
4759       RCID = AMDGPU::VGPR_32RegClassID;
4760       break;
4761     case AMDGPU::AV_64RegClassID:
4762       RCID = AMDGPU::VReg_64RegClassID;
4763       break;
4764     case AMDGPU::AV_96RegClassID:
4765       RCID = AMDGPU::VReg_96RegClassID;
4766       break;
4767     case AMDGPU::AV_128RegClassID:
4768       RCID = AMDGPU::VReg_128RegClassID;
4769       break;
4770     case AMDGPU::AV_160RegClassID:
4771       RCID = AMDGPU::VReg_160RegClassID;
4772       break;
4773     case AMDGPU::AV_512RegClassID:
4774       RCID = AMDGPU::VReg_512RegClassID;
4775       break;
4776     default:
4777       break;
4778     }
4779   }
4780 
4781   return RI.getProperlyAlignedRC(RI.getRegClass(RCID));
4782 }
4783 
4784 const TargetRegisterClass *SIInstrInfo::getRegClass(const MCInstrDesc &TID,
4785     unsigned OpNum, const TargetRegisterInfo *TRI,
4786     const MachineFunction &MF)
4787   const {
4788   if (OpNum >= TID.getNumOperands())
4789     return nullptr;
4790   auto RegClass = TID.OpInfo[OpNum].RegClass;
4791   bool IsAllocatable = false;
4792   if (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::FLAT)) {
4793     // vdst and vdata should be both VGPR or AGPR, same for the DS instructions
4794     // with two data operands. Request register class constrained to VGPR only
4795     // of both operands present as Machine Copy Propagation can not check this
4796     // constraint and possibly other passes too.
4797     //
4798     // The check is limited to FLAT and DS because atomics in non-flat encoding
4799     // have their vdst and vdata tied to be the same register.
4800     const int VDstIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4801                                                    AMDGPU::OpName::vdst);
4802     const int DataIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4803         (TID.TSFlags & SIInstrFlags::DS) ? AMDGPU::OpName::data0
4804                                          : AMDGPU::OpName::vdata);
4805     if (DataIdx != -1) {
4806       IsAllocatable = VDstIdx != -1 ||
4807                       AMDGPU::getNamedOperandIdx(TID.Opcode,
4808                                                  AMDGPU::OpName::data1) != -1;
4809     }
4810   }
4811   return adjustAllocatableRegClass(ST, RI, MF.getRegInfo(), TID, RegClass,
4812                                    IsAllocatable);
4813 }
4814 
4815 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
4816                                                       unsigned OpNo) const {
4817   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4818   const MCInstrDesc &Desc = get(MI.getOpcode());
4819   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
4820       Desc.OpInfo[OpNo].RegClass == -1) {
4821     Register Reg = MI.getOperand(OpNo).getReg();
4822 
4823     if (Reg.isVirtual())
4824       return MRI.getRegClass(Reg);
4825     return RI.getPhysRegClass(Reg);
4826   }
4827 
4828   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
4829   return adjustAllocatableRegClass(ST, RI, MRI, Desc, RCID, true);
4830 }
4831 
4832 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
4833   MachineBasicBlock::iterator I = MI;
4834   MachineBasicBlock *MBB = MI.getParent();
4835   MachineOperand &MO = MI.getOperand(OpIdx);
4836   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4837   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
4838   const TargetRegisterClass *RC = RI.getRegClass(RCID);
4839   unsigned Size = RI.getRegSizeInBits(*RC);
4840   unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO : AMDGPU::V_MOV_B32_e32;
4841   if (MO.isReg())
4842     Opcode = AMDGPU::COPY;
4843   else if (RI.isSGPRClass(RC))
4844     Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
4845 
4846   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
4847   const TargetRegisterClass *VRC64 = RI.getVGPR64Class();
4848   if (RI.getCommonSubClass(VRC64, VRC))
4849     VRC = VRC64;
4850   else
4851     VRC = &AMDGPU::VGPR_32RegClass;
4852 
4853   Register Reg = MRI.createVirtualRegister(VRC);
4854   DebugLoc DL = MBB->findDebugLoc(I);
4855   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
4856   MO.ChangeToRegister(Reg, false);
4857 }
4858 
4859 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
4860                                          MachineRegisterInfo &MRI,
4861                                          MachineOperand &SuperReg,
4862                                          const TargetRegisterClass *SuperRC,
4863                                          unsigned SubIdx,
4864                                          const TargetRegisterClass *SubRC)
4865                                          const {
4866   MachineBasicBlock *MBB = MI->getParent();
4867   DebugLoc DL = MI->getDebugLoc();
4868   Register SubReg = MRI.createVirtualRegister(SubRC);
4869 
4870   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
4871     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4872       .addReg(SuperReg.getReg(), 0, SubIdx);
4873     return SubReg;
4874   }
4875 
4876   // Just in case the super register is itself a sub-register, copy it to a new
4877   // value so we don't need to worry about merging its subreg index with the
4878   // SubIdx passed to this function. The register coalescer should be able to
4879   // eliminate this extra copy.
4880   Register NewSuperReg = MRI.createVirtualRegister(SuperRC);
4881 
4882   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
4883     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
4884 
4885   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4886     .addReg(NewSuperReg, 0, SubIdx);
4887 
4888   return SubReg;
4889 }
4890 
4891 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
4892   MachineBasicBlock::iterator MII,
4893   MachineRegisterInfo &MRI,
4894   MachineOperand &Op,
4895   const TargetRegisterClass *SuperRC,
4896   unsigned SubIdx,
4897   const TargetRegisterClass *SubRC) const {
4898   if (Op.isImm()) {
4899     if (SubIdx == AMDGPU::sub0)
4900       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
4901     if (SubIdx == AMDGPU::sub1)
4902       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
4903 
4904     llvm_unreachable("Unhandled register index for immediate");
4905   }
4906 
4907   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
4908                                        SubIdx, SubRC);
4909   return MachineOperand::CreateReg(SubReg, false);
4910 }
4911 
4912 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
4913 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
4914   assert(Inst.getNumExplicitOperands() == 3);
4915   MachineOperand Op1 = Inst.getOperand(1);
4916   Inst.removeOperand(1);
4917   Inst.addOperand(Op1);
4918 }
4919 
4920 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
4921                                     const MCOperandInfo &OpInfo,
4922                                     const MachineOperand &MO) const {
4923   if (!MO.isReg())
4924     return false;
4925 
4926   Register Reg = MO.getReg();
4927 
4928   const TargetRegisterClass *DRC = RI.getRegClass(OpInfo.RegClass);
4929   if (Reg.isPhysical())
4930     return DRC->contains(Reg);
4931 
4932   const TargetRegisterClass *RC = MRI.getRegClass(Reg);
4933 
4934   if (MO.getSubReg()) {
4935     const MachineFunction *MF = MO.getParent()->getParent()->getParent();
4936     const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
4937     if (!SuperRC)
4938       return false;
4939 
4940     DRC = RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg());
4941     if (!DRC)
4942       return false;
4943   }
4944   return RC->hasSuperClassEq(DRC);
4945 }
4946 
4947 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
4948                                      const MCOperandInfo &OpInfo,
4949                                      const MachineOperand &MO) const {
4950   if (MO.isReg())
4951     return isLegalRegOperand(MRI, OpInfo, MO);
4952 
4953   // Handle non-register types that are treated like immediates.
4954   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
4955   return true;
4956 }
4957 
4958 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
4959                                  const MachineOperand *MO) const {
4960   const MachineFunction &MF = *MI.getParent()->getParent();
4961   const MachineRegisterInfo &MRI = MF.getRegInfo();
4962   const MCInstrDesc &InstDesc = MI.getDesc();
4963   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
4964   const TargetRegisterClass *DefinedRC =
4965       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
4966   if (!MO)
4967     MO = &MI.getOperand(OpIdx);
4968 
4969   int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
4970   int LiteralLimit = !isVOP3(MI) || ST.hasVOP3Literal() ? 1 : 0;
4971   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
4972     if (isLiteralConstantLike(*MO, OpInfo) && !LiteralLimit--)
4973       return false;
4974 
4975     SmallDenseSet<RegSubRegPair> SGPRsUsed;
4976     if (MO->isReg())
4977       SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
4978 
4979     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4980       if (i == OpIdx)
4981         continue;
4982       const MachineOperand &Op = MI.getOperand(i);
4983       if (Op.isReg()) {
4984         RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
4985         if (!SGPRsUsed.count(SGPR) &&
4986             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
4987           if (--ConstantBusLimit <= 0)
4988             return false;
4989           SGPRsUsed.insert(SGPR);
4990         }
4991       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32 ||
4992                  (AMDGPU::isSISrcOperand(InstDesc, i) &&
4993                   isLiteralConstantLike(Op, InstDesc.OpInfo[i]))) {
4994         if (!LiteralLimit--)
4995           return false;
4996         if (--ConstantBusLimit <= 0)
4997           return false;
4998       }
4999     }
5000   }
5001 
5002   if (MO->isReg()) {
5003     if (!DefinedRC) {
5004       // This operand allows any register.
5005       return true;
5006     }
5007     if (!isLegalRegOperand(MRI, OpInfo, *MO))
5008       return false;
5009     bool IsAGPR = RI.isAGPR(MRI, MO->getReg());
5010     if (IsAGPR && !ST.hasMAIInsts())
5011       return false;
5012     unsigned Opc = MI.getOpcode();
5013     if (IsAGPR &&
5014         (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
5015         (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
5016       return false;
5017     // Atomics should have both vdst and vdata either vgpr or agpr.
5018     const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
5019     const int DataIdx = AMDGPU::getNamedOperandIdx(Opc,
5020         isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
5021     if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
5022         MI.getOperand(DataIdx).isReg() &&
5023         RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
5024       return false;
5025     if ((int)OpIdx == DataIdx) {
5026       if (VDstIdx != -1 &&
5027           RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
5028         return false;
5029       // DS instructions with 2 src operands also must have tied RC.
5030       const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc,
5031                                                       AMDGPU::OpName::data1);
5032       if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
5033           RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
5034         return false;
5035     }
5036     if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 && !ST.hasGFX90AInsts() &&
5037         (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
5038         RI.isSGPRReg(MRI, MO->getReg()))
5039       return false;
5040     return true;
5041   }
5042 
5043   // Handle non-register types that are treated like immediates.
5044   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
5045 
5046   if (!DefinedRC) {
5047     // This operand expects an immediate.
5048     return true;
5049   }
5050 
5051   return isImmOperandLegal(MI, OpIdx, *MO);
5052 }
5053 
5054 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
5055                                        MachineInstr &MI) const {
5056   unsigned Opc = MI.getOpcode();
5057   const MCInstrDesc &InstrDesc = get(Opc);
5058 
5059   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
5060   MachineOperand &Src0 = MI.getOperand(Src0Idx);
5061 
5062   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5063   MachineOperand &Src1 = MI.getOperand(Src1Idx);
5064 
5065   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
5066   // we need to only have one constant bus use before GFX10.
5067   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
5068   if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 &&
5069       Src0.isReg() && (RI.isSGPRReg(MRI, Src0.getReg()) ||
5070        isLiteralConstantLike(Src0, InstrDesc.OpInfo[Src0Idx])))
5071     legalizeOpWithMove(MI, Src0Idx);
5072 
5073   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
5074   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
5075   // src0/src1 with V_READFIRSTLANE.
5076   if (Opc == AMDGPU::V_WRITELANE_B32) {
5077     const DebugLoc &DL = MI.getDebugLoc();
5078     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
5079       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5080       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5081           .add(Src0);
5082       Src0.ChangeToRegister(Reg, false);
5083     }
5084     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
5085       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5086       const DebugLoc &DL = MI.getDebugLoc();
5087       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5088           .add(Src1);
5089       Src1.ChangeToRegister(Reg, false);
5090     }
5091     return;
5092   }
5093 
5094   // No VOP2 instructions support AGPRs.
5095   if (Src0.isReg() && RI.isAGPR(MRI, Src0.getReg()))
5096     legalizeOpWithMove(MI, Src0Idx);
5097 
5098   if (Src1.isReg() && RI.isAGPR(MRI, Src1.getReg()))
5099     legalizeOpWithMove(MI, Src1Idx);
5100 
5101   // VOP2 src0 instructions support all operand types, so we don't need to check
5102   // their legality. If src1 is already legal, we don't need to do anything.
5103   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
5104     return;
5105 
5106   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
5107   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
5108   // select is uniform.
5109   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
5110       RI.isVGPR(MRI, Src1.getReg())) {
5111     Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5112     const DebugLoc &DL = MI.getDebugLoc();
5113     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5114         .add(Src1);
5115     Src1.ChangeToRegister(Reg, false);
5116     return;
5117   }
5118 
5119   // We do not use commuteInstruction here because it is too aggressive and will
5120   // commute if it is possible. We only want to commute here if it improves
5121   // legality. This can be called a fairly large number of times so don't waste
5122   // compile time pointlessly swapping and checking legality again.
5123   if (HasImplicitSGPR || !MI.isCommutable()) {
5124     legalizeOpWithMove(MI, Src1Idx);
5125     return;
5126   }
5127 
5128   // If src0 can be used as src1, commuting will make the operands legal.
5129   // Otherwise we have to give up and insert a move.
5130   //
5131   // TODO: Other immediate-like operand kinds could be commuted if there was a
5132   // MachineOperand::ChangeTo* for them.
5133   if ((!Src1.isImm() && !Src1.isReg()) ||
5134       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
5135     legalizeOpWithMove(MI, Src1Idx);
5136     return;
5137   }
5138 
5139   int CommutedOpc = commuteOpcode(MI);
5140   if (CommutedOpc == -1) {
5141     legalizeOpWithMove(MI, Src1Idx);
5142     return;
5143   }
5144 
5145   MI.setDesc(get(CommutedOpc));
5146 
5147   Register Src0Reg = Src0.getReg();
5148   unsigned Src0SubReg = Src0.getSubReg();
5149   bool Src0Kill = Src0.isKill();
5150 
5151   if (Src1.isImm())
5152     Src0.ChangeToImmediate(Src1.getImm());
5153   else if (Src1.isReg()) {
5154     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
5155     Src0.setSubReg(Src1.getSubReg());
5156   } else
5157     llvm_unreachable("Should only have register or immediate operands");
5158 
5159   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
5160   Src1.setSubReg(Src0SubReg);
5161   fixImplicitOperands(MI);
5162 }
5163 
5164 // Legalize VOP3 operands. All operand types are supported for any operand
5165 // but only one literal constant and only starting from GFX10.
5166 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
5167                                        MachineInstr &MI) const {
5168   unsigned Opc = MI.getOpcode();
5169 
5170   int VOP3Idx[3] = {
5171     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
5172     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
5173     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
5174   };
5175 
5176   if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
5177       Opc == AMDGPU::V_PERMLANEX16_B32_e64) {
5178     // src1 and src2 must be scalar
5179     MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
5180     MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
5181     const DebugLoc &DL = MI.getDebugLoc();
5182     if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
5183       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5184       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5185         .add(Src1);
5186       Src1.ChangeToRegister(Reg, false);
5187     }
5188     if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
5189       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5190       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5191         .add(Src2);
5192       Src2.ChangeToRegister(Reg, false);
5193     }
5194   }
5195 
5196   // Find the one SGPR operand we are allowed to use.
5197   int ConstantBusLimit = ST.getConstantBusLimit(Opc);
5198   int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
5199   SmallDenseSet<unsigned> SGPRsUsed;
5200   Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
5201   if (SGPRReg != AMDGPU::NoRegister) {
5202     SGPRsUsed.insert(SGPRReg);
5203     --ConstantBusLimit;
5204   }
5205 
5206   for (int Idx : VOP3Idx) {
5207     if (Idx == -1)
5208       break;
5209     MachineOperand &MO = MI.getOperand(Idx);
5210 
5211     if (!MO.isReg()) {
5212       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
5213         continue;
5214 
5215       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
5216         --LiteralLimit;
5217         --ConstantBusLimit;
5218         continue;
5219       }
5220 
5221       --LiteralLimit;
5222       --ConstantBusLimit;
5223       legalizeOpWithMove(MI, Idx);
5224       continue;
5225     }
5226 
5227     if (RI.hasAGPRs(RI.getRegClassForReg(MRI, MO.getReg())) &&
5228         !isOperandLegal(MI, Idx, &MO)) {
5229       legalizeOpWithMove(MI, Idx);
5230       continue;
5231     }
5232 
5233     if (!RI.isSGPRClass(RI.getRegClassForReg(MRI, MO.getReg())))
5234       continue; // VGPRs are legal
5235 
5236     // We can use one SGPR in each VOP3 instruction prior to GFX10
5237     // and two starting from GFX10.
5238     if (SGPRsUsed.count(MO.getReg()))
5239       continue;
5240     if (ConstantBusLimit > 0) {
5241       SGPRsUsed.insert(MO.getReg());
5242       --ConstantBusLimit;
5243       continue;
5244     }
5245 
5246     // If we make it this far, then the operand is not legal and we must
5247     // legalize it.
5248     legalizeOpWithMove(MI, Idx);
5249   }
5250 }
5251 
5252 Register SIInstrInfo::readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI,
5253                                          MachineRegisterInfo &MRI) const {
5254   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
5255   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
5256   Register DstReg = MRI.createVirtualRegister(SRC);
5257   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
5258 
5259   if (RI.hasAGPRs(VRC)) {
5260     VRC = RI.getEquivalentVGPRClass(VRC);
5261     Register NewSrcReg = MRI.createVirtualRegister(VRC);
5262     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5263             get(TargetOpcode::COPY), NewSrcReg)
5264         .addReg(SrcReg);
5265     SrcReg = NewSrcReg;
5266   }
5267 
5268   if (SubRegs == 1) {
5269     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5270             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
5271         .addReg(SrcReg);
5272     return DstReg;
5273   }
5274 
5275   SmallVector<unsigned, 8> SRegs;
5276   for (unsigned i = 0; i < SubRegs; ++i) {
5277     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5278     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5279             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
5280         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
5281     SRegs.push_back(SGPR);
5282   }
5283 
5284   MachineInstrBuilder MIB =
5285       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5286               get(AMDGPU::REG_SEQUENCE), DstReg);
5287   for (unsigned i = 0; i < SubRegs; ++i) {
5288     MIB.addReg(SRegs[i]);
5289     MIB.addImm(RI.getSubRegFromChannel(i));
5290   }
5291   return DstReg;
5292 }
5293 
5294 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
5295                                        MachineInstr &MI) const {
5296 
5297   // If the pointer is store in VGPRs, then we need to move them to
5298   // SGPRs using v_readfirstlane.  This is safe because we only select
5299   // loads with uniform pointers to SMRD instruction so we know the
5300   // pointer value is uniform.
5301   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
5302   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
5303     Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
5304     SBase->setReg(SGPR);
5305   }
5306   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soffset);
5307   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
5308     Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
5309     SOff->setReg(SGPR);
5310   }
5311 }
5312 
5313 bool SIInstrInfo::moveFlatAddrToVGPR(MachineInstr &Inst) const {
5314   unsigned Opc = Inst.getOpcode();
5315   int OldSAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
5316   if (OldSAddrIdx < 0)
5317     return false;
5318 
5319   assert(isSegmentSpecificFLAT(Inst));
5320 
5321   int NewOpc = AMDGPU::getGlobalVaddrOp(Opc);
5322   if (NewOpc < 0)
5323     NewOpc = AMDGPU::getFlatScratchInstSVfromSS(Opc);
5324   if (NewOpc < 0)
5325     return false;
5326 
5327   MachineRegisterInfo &MRI = Inst.getMF()->getRegInfo();
5328   MachineOperand &SAddr = Inst.getOperand(OldSAddrIdx);
5329   if (RI.isSGPRReg(MRI, SAddr.getReg()))
5330     return false;
5331 
5332   int NewVAddrIdx = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vaddr);
5333   if (NewVAddrIdx < 0)
5334     return false;
5335 
5336   int OldVAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
5337 
5338   // Check vaddr, it shall be zero or absent.
5339   MachineInstr *VAddrDef = nullptr;
5340   if (OldVAddrIdx >= 0) {
5341     MachineOperand &VAddr = Inst.getOperand(OldVAddrIdx);
5342     VAddrDef = MRI.getUniqueVRegDef(VAddr.getReg());
5343     if (!VAddrDef || VAddrDef->getOpcode() != AMDGPU::V_MOV_B32_e32 ||
5344         !VAddrDef->getOperand(1).isImm() ||
5345         VAddrDef->getOperand(1).getImm() != 0)
5346       return false;
5347   }
5348 
5349   const MCInstrDesc &NewDesc = get(NewOpc);
5350   Inst.setDesc(NewDesc);
5351 
5352   // Callers expect iterator to be valid after this call, so modify the
5353   // instruction in place.
5354   if (OldVAddrIdx == NewVAddrIdx) {
5355     MachineOperand &NewVAddr = Inst.getOperand(NewVAddrIdx);
5356     // Clear use list from the old vaddr holding a zero register.
5357     MRI.removeRegOperandFromUseList(&NewVAddr);
5358     MRI.moveOperands(&NewVAddr, &SAddr, 1);
5359     Inst.removeOperand(OldSAddrIdx);
5360     // Update the use list with the pointer we have just moved from vaddr to
5361     // saddr position. Otherwise new vaddr will be missing from the use list.
5362     MRI.removeRegOperandFromUseList(&NewVAddr);
5363     MRI.addRegOperandToUseList(&NewVAddr);
5364   } else {
5365     assert(OldSAddrIdx == NewVAddrIdx);
5366 
5367     if (OldVAddrIdx >= 0) {
5368       int NewVDstIn = AMDGPU::getNamedOperandIdx(NewOpc,
5369                                                  AMDGPU::OpName::vdst_in);
5370 
5371       // removeOperand doesn't try to fixup tied operand indexes at it goes, so
5372       // it asserts. Untie the operands for now and retie them afterwards.
5373       if (NewVDstIn != -1) {
5374         int OldVDstIn = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
5375         Inst.untieRegOperand(OldVDstIn);
5376       }
5377 
5378       Inst.removeOperand(OldVAddrIdx);
5379 
5380       if (NewVDstIn != -1) {
5381         int NewVDst = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vdst);
5382         Inst.tieOperands(NewVDst, NewVDstIn);
5383       }
5384     }
5385   }
5386 
5387   if (VAddrDef && MRI.use_nodbg_empty(VAddrDef->getOperand(0).getReg()))
5388     VAddrDef->eraseFromParent();
5389 
5390   return true;
5391 }
5392 
5393 // FIXME: Remove this when SelectionDAG is obsoleted.
5394 void SIInstrInfo::legalizeOperandsFLAT(MachineRegisterInfo &MRI,
5395                                        MachineInstr &MI) const {
5396   if (!isSegmentSpecificFLAT(MI))
5397     return;
5398 
5399   // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
5400   // thinks they are uniform, so a readfirstlane should be valid.
5401   MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
5402   if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
5403     return;
5404 
5405   if (moveFlatAddrToVGPR(MI))
5406     return;
5407 
5408   Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI);
5409   SAddr->setReg(ToSGPR);
5410 }
5411 
5412 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
5413                                          MachineBasicBlock::iterator I,
5414                                          const TargetRegisterClass *DstRC,
5415                                          MachineOperand &Op,
5416                                          MachineRegisterInfo &MRI,
5417                                          const DebugLoc &DL) const {
5418   Register OpReg = Op.getReg();
5419   unsigned OpSubReg = Op.getSubReg();
5420 
5421   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
5422       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
5423 
5424   // Check if operand is already the correct register class.
5425   if (DstRC == OpRC)
5426     return;
5427 
5428   Register DstReg = MRI.createVirtualRegister(DstRC);
5429   auto Copy = BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
5430 
5431   Op.setReg(DstReg);
5432   Op.setSubReg(0);
5433 
5434   MachineInstr *Def = MRI.getVRegDef(OpReg);
5435   if (!Def)
5436     return;
5437 
5438   // Try to eliminate the copy if it is copying an immediate value.
5439   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
5440     FoldImmediate(*Copy, *Def, OpReg, &MRI);
5441 
5442   bool ImpDef = Def->isImplicitDef();
5443   while (!ImpDef && Def && Def->isCopy()) {
5444     if (Def->getOperand(1).getReg().isPhysical())
5445       break;
5446     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
5447     ImpDef = Def && Def->isImplicitDef();
5448   }
5449   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
5450       !ImpDef)
5451     Copy.addReg(AMDGPU::EXEC, RegState::Implicit);
5452 }
5453 
5454 // Emit the actual waterfall loop, executing the wrapped instruction for each
5455 // unique value of \p Rsrc across all lanes. In the best case we execute 1
5456 // iteration, in the worst case we execute 64 (once per lane).
5457 static void
5458 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
5459                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5460                           MachineBasicBlock &BodyBB, const DebugLoc &DL,
5461                           MachineOperand &Rsrc) {
5462   MachineFunction &MF = *OrigBB.getParent();
5463   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5464   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5465   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5466   unsigned SaveExecOpc =
5467       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
5468   unsigned XorTermOpc =
5469       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
5470   unsigned AndOpc =
5471       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
5472   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5473 
5474   MachineBasicBlock::iterator I = LoopBB.begin();
5475 
5476   SmallVector<Register, 8> ReadlanePieces;
5477   Register CondReg = AMDGPU::NoRegister;
5478 
5479   Register VRsrc = Rsrc.getReg();
5480   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
5481 
5482   unsigned RegSize = TRI->getRegSizeInBits(Rsrc.getReg(), MRI);
5483   unsigned NumSubRegs =  RegSize / 32;
5484   assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 && "Unhandled register size");
5485 
5486   for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
5487 
5488     Register CurRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5489     Register CurRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5490 
5491     // Read the next variant <- also loop target.
5492     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
5493             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx));
5494 
5495     // Read the next variant <- also loop target.
5496     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
5497             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx + 1));
5498 
5499     ReadlanePieces.push_back(CurRegLo);
5500     ReadlanePieces.push_back(CurRegHi);
5501 
5502     // Comparison is to be done as 64-bit.
5503     Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
5504     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
5505             .addReg(CurRegLo)
5506             .addImm(AMDGPU::sub0)
5507             .addReg(CurRegHi)
5508             .addImm(AMDGPU::sub1);
5509 
5510     Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
5511     auto Cmp =
5512         BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
5513             .addReg(CurReg);
5514     if (NumSubRegs <= 2)
5515       Cmp.addReg(VRsrc);
5516     else
5517       Cmp.addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx, 2));
5518 
5519     // Combine the comparison results with AND.
5520     if (CondReg == AMDGPU::NoRegister) // First.
5521       CondReg = NewCondReg;
5522     else { // If not the first, we create an AND.
5523       Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
5524       BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndReg)
5525               .addReg(CondReg)
5526               .addReg(NewCondReg);
5527       CondReg = AndReg;
5528     }
5529   } // End for loop.
5530 
5531   auto SRsrcRC = TRI->getEquivalentSGPRClass(MRI.getRegClass(VRsrc));
5532   Register SRsrc = MRI.createVirtualRegister(SRsrcRC);
5533 
5534   // Build scalar Rsrc.
5535   auto Merge = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc);
5536   unsigned Channel = 0;
5537   for (Register Piece : ReadlanePieces) {
5538     Merge.addReg(Piece)
5539          .addImm(TRI->getSubRegFromChannel(Channel++));
5540   }
5541 
5542   // Update Rsrc operand to use the SGPR Rsrc.
5543   Rsrc.setReg(SRsrc);
5544   Rsrc.setIsKill(true);
5545 
5546   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5547   MRI.setSimpleHint(SaveExec, CondReg);
5548 
5549   // Update EXEC to matching lanes, saving original to SaveExec.
5550   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
5551       .addReg(CondReg, RegState::Kill);
5552 
5553   // The original instruction is here; we insert the terminators after it.
5554   I = BodyBB.end();
5555 
5556   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5557   BuildMI(BodyBB, I, DL, TII.get(XorTermOpc), Exec)
5558       .addReg(Exec)
5559       .addReg(SaveExec);
5560 
5561   BuildMI(BodyBB, I, DL, TII.get(AMDGPU::SI_WATERFALL_LOOP)).addMBB(&LoopBB);
5562 }
5563 
5564 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
5565 // with SGPRs by iterating over all unique values across all lanes.
5566 // Returns the loop basic block that now contains \p MI.
5567 static MachineBasicBlock *
5568 loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
5569                   MachineOperand &Rsrc, MachineDominatorTree *MDT,
5570                   MachineBasicBlock::iterator Begin = nullptr,
5571                   MachineBasicBlock::iterator End = nullptr) {
5572   MachineBasicBlock &MBB = *MI.getParent();
5573   MachineFunction &MF = *MBB.getParent();
5574   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5575   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5576   MachineRegisterInfo &MRI = MF.getRegInfo();
5577   if (!Begin.isValid())
5578     Begin = &MI;
5579   if (!End.isValid()) {
5580     End = &MI;
5581     ++End;
5582   }
5583   const DebugLoc &DL = MI.getDebugLoc();
5584   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5585   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
5586   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5587 
5588   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5589 
5590   // Save the EXEC mask
5591   BuildMI(MBB, Begin, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
5592 
5593   // Killed uses in the instruction we are waterfalling around will be
5594   // incorrect due to the added control-flow.
5595   MachineBasicBlock::iterator AfterMI = MI;
5596   ++AfterMI;
5597   for (auto I = Begin; I != AfterMI; I++) {
5598     for (auto &MO : I->uses()) {
5599       if (MO.isReg() && MO.isUse()) {
5600         MRI.clearKillFlags(MO.getReg());
5601       }
5602     }
5603   }
5604 
5605   // To insert the loop we need to split the block. Move everything after this
5606   // point to a new block, and insert a new empty block between the two.
5607   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
5608   MachineBasicBlock *BodyBB = MF.CreateMachineBasicBlock();
5609   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
5610   MachineFunction::iterator MBBI(MBB);
5611   ++MBBI;
5612 
5613   MF.insert(MBBI, LoopBB);
5614   MF.insert(MBBI, BodyBB);
5615   MF.insert(MBBI, RemainderBB);
5616 
5617   LoopBB->addSuccessor(BodyBB);
5618   BodyBB->addSuccessor(LoopBB);
5619   BodyBB->addSuccessor(RemainderBB);
5620 
5621   // Move Begin to MI to the BodyBB, and the remainder of the block to
5622   // RemainderBB.
5623   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5624   RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
5625   BodyBB->splice(BodyBB->begin(), &MBB, Begin, MBB.end());
5626 
5627   MBB.addSuccessor(LoopBB);
5628 
5629   // Update dominators. We know that MBB immediately dominates LoopBB, that
5630   // LoopBB immediately dominates BodyBB, and BodyBB immediately dominates
5631   // RemainderBB. RemainderBB immediately dominates all of the successors
5632   // transferred to it from MBB that MBB used to properly dominate.
5633   if (MDT) {
5634     MDT->addNewBlock(LoopBB, &MBB);
5635     MDT->addNewBlock(BodyBB, LoopBB);
5636     MDT->addNewBlock(RemainderBB, BodyBB);
5637     for (auto &Succ : RemainderBB->successors()) {
5638       if (MDT->properlyDominates(&MBB, Succ)) {
5639         MDT->changeImmediateDominator(Succ, RemainderBB);
5640       }
5641     }
5642   }
5643 
5644   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, *BodyBB, DL, Rsrc);
5645 
5646   // Restore the EXEC mask
5647   MachineBasicBlock::iterator First = RemainderBB->begin();
5648   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
5649   return BodyBB;
5650 }
5651 
5652 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
5653 static std::tuple<unsigned, unsigned>
5654 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
5655   MachineBasicBlock &MBB = *MI.getParent();
5656   MachineFunction &MF = *MBB.getParent();
5657   MachineRegisterInfo &MRI = MF.getRegInfo();
5658 
5659   // Extract the ptr from the resource descriptor.
5660   unsigned RsrcPtr =
5661       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
5662                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
5663 
5664   // Create an empty resource descriptor
5665   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5666   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5667   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5668   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
5669   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
5670 
5671   // Zero64 = 0
5672   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
5673       .addImm(0);
5674 
5675   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
5676   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
5677       .addImm(RsrcDataFormat & 0xFFFFFFFF);
5678 
5679   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
5680   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
5681       .addImm(RsrcDataFormat >> 32);
5682 
5683   // NewSRsrc = {Zero64, SRsrcFormat}
5684   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
5685       .addReg(Zero64)
5686       .addImm(AMDGPU::sub0_sub1)
5687       .addReg(SRsrcFormatLo)
5688       .addImm(AMDGPU::sub2)
5689       .addReg(SRsrcFormatHi)
5690       .addImm(AMDGPU::sub3);
5691 
5692   return std::make_tuple(RsrcPtr, NewSRsrc);
5693 }
5694 
5695 MachineBasicBlock *
5696 SIInstrInfo::legalizeOperands(MachineInstr &MI,
5697                               MachineDominatorTree *MDT) const {
5698   MachineFunction &MF = *MI.getParent()->getParent();
5699   MachineRegisterInfo &MRI = MF.getRegInfo();
5700   MachineBasicBlock *CreatedBB = nullptr;
5701 
5702   // Legalize VOP2
5703   if (isVOP2(MI) || isVOPC(MI)) {
5704     legalizeOperandsVOP2(MRI, MI);
5705     return CreatedBB;
5706   }
5707 
5708   // Legalize VOP3
5709   if (isVOP3(MI)) {
5710     legalizeOperandsVOP3(MRI, MI);
5711     return CreatedBB;
5712   }
5713 
5714   // Legalize SMRD
5715   if (isSMRD(MI)) {
5716     legalizeOperandsSMRD(MRI, MI);
5717     return CreatedBB;
5718   }
5719 
5720   // Legalize FLAT
5721   if (isFLAT(MI)) {
5722     legalizeOperandsFLAT(MRI, MI);
5723     return CreatedBB;
5724   }
5725 
5726   // Legalize REG_SEQUENCE and PHI
5727   // The register class of the operands much be the same type as the register
5728   // class of the output.
5729   if (MI.getOpcode() == AMDGPU::PHI) {
5730     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
5731     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
5732       if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
5733         continue;
5734       const TargetRegisterClass *OpRC =
5735           MRI.getRegClass(MI.getOperand(i).getReg());
5736       if (RI.hasVectorRegisters(OpRC)) {
5737         VRC = OpRC;
5738       } else {
5739         SRC = OpRC;
5740       }
5741     }
5742 
5743     // If any of the operands are VGPR registers, then they all most be
5744     // otherwise we will create illegal VGPR->SGPR copies when legalizing
5745     // them.
5746     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
5747       if (!VRC) {
5748         assert(SRC);
5749         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
5750           VRC = &AMDGPU::VReg_1RegClass;
5751         } else
5752           VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5753                     ? RI.getEquivalentAGPRClass(SRC)
5754                     : RI.getEquivalentVGPRClass(SRC);
5755       } else {
5756         VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5757                   ? RI.getEquivalentAGPRClass(VRC)
5758                   : RI.getEquivalentVGPRClass(VRC);
5759       }
5760       RC = VRC;
5761     } else {
5762       RC = SRC;
5763     }
5764 
5765     // Update all the operands so they have the same type.
5766     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5767       MachineOperand &Op = MI.getOperand(I);
5768       if (!Op.isReg() || !Op.getReg().isVirtual())
5769         continue;
5770 
5771       // MI is a PHI instruction.
5772       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
5773       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
5774 
5775       // Avoid creating no-op copies with the same src and dst reg class.  These
5776       // confuse some of the machine passes.
5777       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
5778     }
5779   }
5780 
5781   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
5782   // VGPR dest type and SGPR sources, insert copies so all operands are
5783   // VGPRs. This seems to help operand folding / the register coalescer.
5784   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
5785     MachineBasicBlock *MBB = MI.getParent();
5786     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
5787     if (RI.hasVGPRs(DstRC)) {
5788       // Update all the operands so they are VGPR register classes. These may
5789       // not be the same register class because REG_SEQUENCE supports mixing
5790       // subregister index types e.g. sub0_sub1 + sub2 + sub3
5791       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5792         MachineOperand &Op = MI.getOperand(I);
5793         if (!Op.isReg() || !Op.getReg().isVirtual())
5794           continue;
5795 
5796         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
5797         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
5798         if (VRC == OpRC)
5799           continue;
5800 
5801         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
5802         Op.setIsKill();
5803       }
5804     }
5805 
5806     return CreatedBB;
5807   }
5808 
5809   // Legalize INSERT_SUBREG
5810   // src0 must have the same register class as dst
5811   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
5812     Register Dst = MI.getOperand(0).getReg();
5813     Register Src0 = MI.getOperand(1).getReg();
5814     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
5815     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
5816     if (DstRC != Src0RC) {
5817       MachineBasicBlock *MBB = MI.getParent();
5818       MachineOperand &Op = MI.getOperand(1);
5819       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
5820     }
5821     return CreatedBB;
5822   }
5823 
5824   // Legalize SI_INIT_M0
5825   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
5826     MachineOperand &Src = MI.getOperand(0);
5827     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
5828       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
5829     return CreatedBB;
5830   }
5831 
5832   // Legalize MIMG and MUBUF/MTBUF for shaders.
5833   //
5834   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
5835   // scratch memory access. In both cases, the legalization never involves
5836   // conversion to the addr64 form.
5837   if (isMIMG(MI) || (AMDGPU::isGraphics(MF.getFunction().getCallingConv()) &&
5838                      (isMUBUF(MI) || isMTBUF(MI)))) {
5839     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
5840     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
5841       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SRsrc, MDT);
5842 
5843     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
5844     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
5845       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SSamp, MDT);
5846 
5847     return CreatedBB;
5848   }
5849 
5850   // Legalize SI_CALL
5851   if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
5852     MachineOperand *Dest = &MI.getOperand(0);
5853     if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
5854       // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
5855       // following copies, we also need to move copies from and to physical
5856       // registers into the loop block.
5857       unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
5858       unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
5859 
5860       // Also move the copies to physical registers into the loop block
5861       MachineBasicBlock &MBB = *MI.getParent();
5862       MachineBasicBlock::iterator Start(&MI);
5863       while (Start->getOpcode() != FrameSetupOpcode)
5864         --Start;
5865       MachineBasicBlock::iterator End(&MI);
5866       while (End->getOpcode() != FrameDestroyOpcode)
5867         ++End;
5868       // Also include following copies of the return value
5869       ++End;
5870       while (End != MBB.end() && End->isCopy() && End->getOperand(1).isReg() &&
5871              MI.definesRegister(End->getOperand(1).getReg()))
5872         ++End;
5873       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Dest, MDT, Start, End);
5874     }
5875   }
5876 
5877   // Legalize MUBUF* instructions.
5878   int RsrcIdx =
5879       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
5880   if (RsrcIdx != -1) {
5881     // We have an MUBUF instruction
5882     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
5883     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
5884     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
5885                              RI.getRegClass(RsrcRC))) {
5886       // The operands are legal.
5887       // FIXME: We may need to legalize operands besides srsrc.
5888       return CreatedBB;
5889     }
5890 
5891     // Legalize a VGPR Rsrc.
5892     //
5893     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
5894     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
5895     // a zero-value SRsrc.
5896     //
5897     // If the instruction is _OFFSET (both idxen and offen disabled), and we
5898     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
5899     // above.
5900     //
5901     // Otherwise we are on non-ADDR64 hardware, and/or we have
5902     // idxen/offen/bothen and we fall back to a waterfall loop.
5903 
5904     MachineBasicBlock &MBB = *MI.getParent();
5905 
5906     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5907     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
5908       // This is already an ADDR64 instruction so we need to add the pointer
5909       // extracted from the resource descriptor to the current value of VAddr.
5910       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5911       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5912       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5913 
5914       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5915       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
5916       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
5917 
5918       unsigned RsrcPtr, NewSRsrc;
5919       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5920 
5921       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
5922       const DebugLoc &DL = MI.getDebugLoc();
5923       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
5924         .addDef(CondReg0)
5925         .addReg(RsrcPtr, 0, AMDGPU::sub0)
5926         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
5927         .addImm(0);
5928 
5929       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
5930       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
5931         .addDef(CondReg1, RegState::Dead)
5932         .addReg(RsrcPtr, 0, AMDGPU::sub1)
5933         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
5934         .addReg(CondReg0, RegState::Kill)
5935         .addImm(0);
5936 
5937       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5938       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
5939           .addReg(NewVAddrLo)
5940           .addImm(AMDGPU::sub0)
5941           .addReg(NewVAddrHi)
5942           .addImm(AMDGPU::sub1);
5943 
5944       VAddr->setReg(NewVAddr);
5945       Rsrc->setReg(NewSRsrc);
5946     } else if (!VAddr && ST.hasAddr64()) {
5947       // This instructions is the _OFFSET variant, so we need to convert it to
5948       // ADDR64.
5949       assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5950              "FIXME: Need to emit flat atomics here");
5951 
5952       unsigned RsrcPtr, NewSRsrc;
5953       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5954 
5955       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5956       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
5957       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5958       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
5959       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
5960 
5961       // Atomics with return have an additional tied operand and are
5962       // missing some of the special bits.
5963       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
5964       MachineInstr *Addr64;
5965 
5966       if (!VDataIn) {
5967         // Regular buffer load / store.
5968         MachineInstrBuilder MIB =
5969             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5970                 .add(*VData)
5971                 .addReg(NewVAddr)
5972                 .addReg(NewSRsrc)
5973                 .add(*SOffset)
5974                 .add(*Offset);
5975 
5976         if (const MachineOperand *CPol =
5977                 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
5978           MIB.addImm(CPol->getImm());
5979         }
5980 
5981         if (const MachineOperand *TFE =
5982                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
5983           MIB.addImm(TFE->getImm());
5984         }
5985 
5986         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
5987 
5988         MIB.cloneMemRefs(MI);
5989         Addr64 = MIB;
5990       } else {
5991         // Atomics with return.
5992         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5993                      .add(*VData)
5994                      .add(*VDataIn)
5995                      .addReg(NewVAddr)
5996                      .addReg(NewSRsrc)
5997                      .add(*SOffset)
5998                      .add(*Offset)
5999                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
6000                      .cloneMemRefs(MI);
6001       }
6002 
6003       MI.removeFromParent();
6004 
6005       // NewVaddr = {NewVaddrHi, NewVaddrLo}
6006       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
6007               NewVAddr)
6008           .addReg(RsrcPtr, 0, AMDGPU::sub0)
6009           .addImm(AMDGPU::sub0)
6010           .addReg(RsrcPtr, 0, AMDGPU::sub1)
6011           .addImm(AMDGPU::sub1);
6012     } else {
6013       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
6014       // to SGPRs.
6015       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
6016       return CreatedBB;
6017     }
6018   }
6019   return CreatedBB;
6020 }
6021 
6022 MachineBasicBlock *SIInstrInfo::moveToVALU(MachineInstr &TopInst,
6023                                            MachineDominatorTree *MDT) const {
6024   SetVectorType Worklist;
6025   Worklist.insert(&TopInst);
6026   MachineBasicBlock *CreatedBB = nullptr;
6027   MachineBasicBlock *CreatedBBTmp = nullptr;
6028 
6029   while (!Worklist.empty()) {
6030     MachineInstr &Inst = *Worklist.pop_back_val();
6031     MachineBasicBlock *MBB = Inst.getParent();
6032     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
6033 
6034     unsigned Opcode = Inst.getOpcode();
6035     unsigned NewOpcode = getVALUOp(Inst);
6036 
6037     // Handle some special cases
6038     switch (Opcode) {
6039     default:
6040       break;
6041     case AMDGPU::S_ADD_U64_PSEUDO:
6042     case AMDGPU::S_SUB_U64_PSEUDO:
6043       splitScalar64BitAddSub(Worklist, Inst, MDT);
6044       Inst.eraseFromParent();
6045       continue;
6046     case AMDGPU::S_ADD_I32:
6047     case AMDGPU::S_SUB_I32: {
6048       // FIXME: The u32 versions currently selected use the carry.
6049       bool Changed;
6050       std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
6051       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6052         CreatedBB = CreatedBBTmp;
6053       if (Changed)
6054         continue;
6055 
6056       // Default handling
6057       break;
6058     }
6059     case AMDGPU::S_AND_B64:
6060       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
6061       Inst.eraseFromParent();
6062       continue;
6063 
6064     case AMDGPU::S_OR_B64:
6065       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
6066       Inst.eraseFromParent();
6067       continue;
6068 
6069     case AMDGPU::S_XOR_B64:
6070       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
6071       Inst.eraseFromParent();
6072       continue;
6073 
6074     case AMDGPU::S_NAND_B64:
6075       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
6076       Inst.eraseFromParent();
6077       continue;
6078 
6079     case AMDGPU::S_NOR_B64:
6080       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
6081       Inst.eraseFromParent();
6082       continue;
6083 
6084     case AMDGPU::S_XNOR_B64:
6085       if (ST.hasDLInsts())
6086         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
6087       else
6088         splitScalar64BitXnor(Worklist, Inst, MDT);
6089       Inst.eraseFromParent();
6090       continue;
6091 
6092     case AMDGPU::S_ANDN2_B64:
6093       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
6094       Inst.eraseFromParent();
6095       continue;
6096 
6097     case AMDGPU::S_ORN2_B64:
6098       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
6099       Inst.eraseFromParent();
6100       continue;
6101 
6102     case AMDGPU::S_BREV_B64:
6103       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
6104       Inst.eraseFromParent();
6105       continue;
6106 
6107     case AMDGPU::S_NOT_B64:
6108       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
6109       Inst.eraseFromParent();
6110       continue;
6111 
6112     case AMDGPU::S_BCNT1_I32_B64:
6113       splitScalar64BitBCNT(Worklist, Inst);
6114       Inst.eraseFromParent();
6115       continue;
6116 
6117     case AMDGPU::S_BFE_I64:
6118       splitScalar64BitBFE(Worklist, Inst);
6119       Inst.eraseFromParent();
6120       continue;
6121 
6122     case AMDGPU::S_LSHL_B32:
6123       if (ST.hasOnlyRevVALUShifts()) {
6124         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
6125         swapOperands(Inst);
6126       }
6127       break;
6128     case AMDGPU::S_ASHR_I32:
6129       if (ST.hasOnlyRevVALUShifts()) {
6130         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
6131         swapOperands(Inst);
6132       }
6133       break;
6134     case AMDGPU::S_LSHR_B32:
6135       if (ST.hasOnlyRevVALUShifts()) {
6136         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
6137         swapOperands(Inst);
6138       }
6139       break;
6140     case AMDGPU::S_LSHL_B64:
6141       if (ST.hasOnlyRevVALUShifts()) {
6142         NewOpcode = AMDGPU::V_LSHLREV_B64_e64;
6143         swapOperands(Inst);
6144       }
6145       break;
6146     case AMDGPU::S_ASHR_I64:
6147       if (ST.hasOnlyRevVALUShifts()) {
6148         NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
6149         swapOperands(Inst);
6150       }
6151       break;
6152     case AMDGPU::S_LSHR_B64:
6153       if (ST.hasOnlyRevVALUShifts()) {
6154         NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
6155         swapOperands(Inst);
6156       }
6157       break;
6158 
6159     case AMDGPU::S_ABS_I32:
6160       lowerScalarAbs(Worklist, Inst);
6161       Inst.eraseFromParent();
6162       continue;
6163 
6164     case AMDGPU::S_CBRANCH_SCC0:
6165     case AMDGPU::S_CBRANCH_SCC1: {
6166         // Clear unused bits of vcc
6167         Register CondReg = Inst.getOperand(1).getReg();
6168         bool IsSCC = CondReg == AMDGPU::SCC;
6169         Register VCC = RI.getVCC();
6170         Register EXEC = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6171         unsigned Opc = ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6172         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(Opc), VCC)
6173             .addReg(EXEC)
6174             .addReg(IsSCC ? VCC : CondReg);
6175         Inst.removeOperand(1);
6176       }
6177       break;
6178 
6179     case AMDGPU::S_BFE_U64:
6180     case AMDGPU::S_BFM_B64:
6181       llvm_unreachable("Moving this op to VALU not implemented");
6182 
6183     case AMDGPU::S_PACK_LL_B32_B16:
6184     case AMDGPU::S_PACK_LH_B32_B16:
6185     case AMDGPU::S_PACK_HL_B32_B16:
6186     case AMDGPU::S_PACK_HH_B32_B16:
6187       movePackToVALU(Worklist, MRI, Inst);
6188       Inst.eraseFromParent();
6189       continue;
6190 
6191     case AMDGPU::S_XNOR_B32:
6192       lowerScalarXnor(Worklist, Inst);
6193       Inst.eraseFromParent();
6194       continue;
6195 
6196     case AMDGPU::S_NAND_B32:
6197       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
6198       Inst.eraseFromParent();
6199       continue;
6200 
6201     case AMDGPU::S_NOR_B32:
6202       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
6203       Inst.eraseFromParent();
6204       continue;
6205 
6206     case AMDGPU::S_ANDN2_B32:
6207       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
6208       Inst.eraseFromParent();
6209       continue;
6210 
6211     case AMDGPU::S_ORN2_B32:
6212       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
6213       Inst.eraseFromParent();
6214       continue;
6215 
6216     // TODO: remove as soon as everything is ready
6217     // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
6218     // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
6219     // can only be selected from the uniform SDNode.
6220     case AMDGPU::S_ADD_CO_PSEUDO:
6221     case AMDGPU::S_SUB_CO_PSEUDO: {
6222       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
6223                          ? AMDGPU::V_ADDC_U32_e64
6224                          : AMDGPU::V_SUBB_U32_e64;
6225       const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6226 
6227       Register CarryInReg = Inst.getOperand(4).getReg();
6228       if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
6229         Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
6230         BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
6231             .addReg(CarryInReg);
6232       }
6233 
6234       Register CarryOutReg = Inst.getOperand(1).getReg();
6235 
6236       Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
6237           MRI.getRegClass(Inst.getOperand(0).getReg())));
6238       MachineInstr *CarryOp =
6239           BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
6240               .addReg(CarryOutReg, RegState::Define)
6241               .add(Inst.getOperand(2))
6242               .add(Inst.getOperand(3))
6243               .addReg(CarryInReg)
6244               .addImm(0);
6245       CreatedBBTmp = legalizeOperands(*CarryOp);
6246       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6247         CreatedBB = CreatedBBTmp;
6248       MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
6249       addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
6250       Inst.eraseFromParent();
6251     }
6252       continue;
6253     case AMDGPU::S_UADDO_PSEUDO:
6254     case AMDGPU::S_USUBO_PSEUDO: {
6255       const DebugLoc &DL = Inst.getDebugLoc();
6256       MachineOperand &Dest0 = Inst.getOperand(0);
6257       MachineOperand &Dest1 = Inst.getOperand(1);
6258       MachineOperand &Src0 = Inst.getOperand(2);
6259       MachineOperand &Src1 = Inst.getOperand(3);
6260 
6261       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
6262                          ? AMDGPU::V_ADD_CO_U32_e64
6263                          : AMDGPU::V_SUB_CO_U32_e64;
6264       const TargetRegisterClass *NewRC =
6265           RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
6266       Register DestReg = MRI.createVirtualRegister(NewRC);
6267       MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
6268                                    .addReg(Dest1.getReg(), RegState::Define)
6269                                    .add(Src0)
6270                                    .add(Src1)
6271                                    .addImm(0); // clamp bit
6272 
6273       CreatedBBTmp = legalizeOperands(*NewInstr, MDT);
6274       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6275         CreatedBB = CreatedBBTmp;
6276 
6277       MRI.replaceRegWith(Dest0.getReg(), DestReg);
6278       addUsersToMoveToVALUWorklist(NewInstr->getOperand(0).getReg(), MRI,
6279                                    Worklist);
6280       Inst.eraseFromParent();
6281     }
6282       continue;
6283 
6284     case AMDGPU::S_CSELECT_B32:
6285     case AMDGPU::S_CSELECT_B64:
6286       lowerSelect(Worklist, Inst, MDT);
6287       Inst.eraseFromParent();
6288       continue;
6289     case AMDGPU::S_CMP_EQ_I32:
6290     case AMDGPU::S_CMP_LG_I32:
6291     case AMDGPU::S_CMP_GT_I32:
6292     case AMDGPU::S_CMP_GE_I32:
6293     case AMDGPU::S_CMP_LT_I32:
6294     case AMDGPU::S_CMP_LE_I32:
6295     case AMDGPU::S_CMP_EQ_U32:
6296     case AMDGPU::S_CMP_LG_U32:
6297     case AMDGPU::S_CMP_GT_U32:
6298     case AMDGPU::S_CMP_GE_U32:
6299     case AMDGPU::S_CMP_LT_U32:
6300     case AMDGPU::S_CMP_LE_U32:
6301     case AMDGPU::S_CMP_EQ_U64:
6302     case AMDGPU::S_CMP_LG_U64: {
6303         const MCInstrDesc &NewDesc = get(NewOpcode);
6304         Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
6305         MachineInstr *NewInstr =
6306             BuildMI(*MBB, Inst, Inst.getDebugLoc(), NewDesc, CondReg)
6307                 .add(Inst.getOperand(0))
6308                 .add(Inst.getOperand(1));
6309         legalizeOperands(*NewInstr, MDT);
6310         int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC);
6311         MachineOperand SCCOp = Inst.getOperand(SCCIdx);
6312         addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
6313         Inst.eraseFromParent();
6314       }
6315       continue;
6316     }
6317 
6318 
6319     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
6320       // We cannot move this instruction to the VALU, so we should try to
6321       // legalize its operands instead.
6322       CreatedBBTmp = legalizeOperands(Inst, MDT);
6323       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6324         CreatedBB = CreatedBBTmp;
6325       continue;
6326     }
6327 
6328     // Use the new VALU Opcode.
6329     const MCInstrDesc &NewDesc = get(NewOpcode);
6330     Inst.setDesc(NewDesc);
6331 
6332     // Remove any references to SCC. Vector instructions can't read from it, and
6333     // We're just about to add the implicit use / defs of VCC, and we don't want
6334     // both.
6335     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
6336       MachineOperand &Op = Inst.getOperand(i);
6337       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
6338         // Only propagate through live-def of SCC.
6339         if (Op.isDef() && !Op.isDead())
6340           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
6341         if (Op.isUse())
6342           addSCCDefsToVALUWorklist(Op, Worklist);
6343         Inst.removeOperand(i);
6344       }
6345     }
6346 
6347     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
6348       // We are converting these to a BFE, so we need to add the missing
6349       // operands for the size and offset.
6350       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
6351       Inst.addOperand(MachineOperand::CreateImm(0));
6352       Inst.addOperand(MachineOperand::CreateImm(Size));
6353 
6354     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
6355       // The VALU version adds the second operand to the result, so insert an
6356       // extra 0 operand.
6357       Inst.addOperand(MachineOperand::CreateImm(0));
6358     }
6359 
6360     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
6361     fixImplicitOperands(Inst);
6362 
6363     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
6364       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
6365       // If we need to move this to VGPRs, we need to unpack the second operand
6366       // back into the 2 separate ones for bit offset and width.
6367       assert(OffsetWidthOp.isImm() &&
6368              "Scalar BFE is only implemented for constant width and offset");
6369       uint32_t Imm = OffsetWidthOp.getImm();
6370 
6371       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6372       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6373       Inst.removeOperand(2);                     // Remove old immediate.
6374       Inst.addOperand(MachineOperand::CreateImm(Offset));
6375       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
6376     }
6377 
6378     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
6379     unsigned NewDstReg = AMDGPU::NoRegister;
6380     if (HasDst) {
6381       Register DstReg = Inst.getOperand(0).getReg();
6382       if (DstReg.isPhysical())
6383         continue;
6384 
6385       // Update the destination register class.
6386       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
6387       if (!NewDstRC)
6388         continue;
6389 
6390       if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual() &&
6391           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
6392         // Instead of creating a copy where src and dst are the same register
6393         // class, we just replace all uses of dst with src.  These kinds of
6394         // copies interfere with the heuristics MachineSink uses to decide
6395         // whether or not to split a critical edge.  Since the pass assumes
6396         // that copies will end up as machine instructions and not be
6397         // eliminated.
6398         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
6399         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
6400         MRI.clearKillFlags(Inst.getOperand(1).getReg());
6401         Inst.getOperand(0).setReg(DstReg);
6402 
6403         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
6404         // these are deleted later, but at -O0 it would leave a suspicious
6405         // looking illegal copy of an undef register.
6406         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
6407           Inst.removeOperand(I);
6408         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
6409         continue;
6410       }
6411 
6412       NewDstReg = MRI.createVirtualRegister(NewDstRC);
6413       MRI.replaceRegWith(DstReg, NewDstReg);
6414     }
6415 
6416     // Legalize the operands
6417     CreatedBBTmp = legalizeOperands(Inst, MDT);
6418     if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6419       CreatedBB = CreatedBBTmp;
6420 
6421     if (HasDst)
6422      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
6423   }
6424   return CreatedBB;
6425 }
6426 
6427 // Add/sub require special handling to deal with carry outs.
6428 std::pair<bool, MachineBasicBlock *>
6429 SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
6430                               MachineDominatorTree *MDT) const {
6431   if (ST.hasAddNoCarry()) {
6432     // Assume there is no user of scc since we don't select this in that case.
6433     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
6434     // is used.
6435 
6436     MachineBasicBlock &MBB = *Inst.getParent();
6437     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6438 
6439     Register OldDstReg = Inst.getOperand(0).getReg();
6440     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6441 
6442     unsigned Opc = Inst.getOpcode();
6443     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
6444 
6445     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
6446       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
6447 
6448     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
6449     Inst.removeOperand(3);
6450 
6451     Inst.setDesc(get(NewOpc));
6452     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
6453     Inst.addImplicitDefUseOperands(*MBB.getParent());
6454     MRI.replaceRegWith(OldDstReg, ResultReg);
6455     MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
6456 
6457     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6458     return std::make_pair(true, NewBB);
6459   }
6460 
6461   return std::make_pair(false, nullptr);
6462 }
6463 
6464 void SIInstrInfo::lowerSelect(SetVectorType &Worklist, MachineInstr &Inst,
6465                               MachineDominatorTree *MDT) const {
6466 
6467   MachineBasicBlock &MBB = *Inst.getParent();
6468   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6469   MachineBasicBlock::iterator MII = Inst;
6470   DebugLoc DL = Inst.getDebugLoc();
6471 
6472   MachineOperand &Dest = Inst.getOperand(0);
6473   MachineOperand &Src0 = Inst.getOperand(1);
6474   MachineOperand &Src1 = Inst.getOperand(2);
6475   MachineOperand &Cond = Inst.getOperand(3);
6476 
6477   Register SCCSource = Cond.getReg();
6478   bool IsSCC = (SCCSource == AMDGPU::SCC);
6479 
6480   // If this is a trivial select where the condition is effectively not SCC
6481   // (SCCSource is a source of copy to SCC), then the select is semantically
6482   // equivalent to copying SCCSource. Hence, there is no need to create
6483   // V_CNDMASK, we can just use that and bail out.
6484   if (!IsSCC && Src0.isImm() && (Src0.getImm() == -1) && Src1.isImm() &&
6485       (Src1.getImm() == 0)) {
6486     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6487     return;
6488   }
6489 
6490   const TargetRegisterClass *TC =
6491       RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6492 
6493   Register CopySCC = MRI.createVirtualRegister(TC);
6494 
6495   if (IsSCC) {
6496     // Now look for the closest SCC def if it is a copy
6497     // replacing the SCCSource with the COPY source register
6498     bool CopyFound = false;
6499     for (MachineInstr &CandI :
6500          make_range(std::next(MachineBasicBlock::reverse_iterator(Inst)),
6501                     Inst.getParent()->rend())) {
6502       if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) !=
6503           -1) {
6504         if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
6505           BuildMI(MBB, MII, DL, get(AMDGPU::COPY), CopySCC)
6506               .addReg(CandI.getOperand(1).getReg());
6507           CopyFound = true;
6508         }
6509         break;
6510       }
6511     }
6512     if (!CopyFound) {
6513       // SCC def is not a copy
6514       // Insert a trivial select instead of creating a copy, because a copy from
6515       // SCC would semantically mean just copying a single bit, but we may need
6516       // the result to be a vector condition mask that needs preserving.
6517       unsigned Opcode = (ST.getWavefrontSize() == 64) ? AMDGPU::S_CSELECT_B64
6518                                                       : AMDGPU::S_CSELECT_B32;
6519       auto NewSelect =
6520           BuildMI(MBB, MII, DL, get(Opcode), CopySCC).addImm(-1).addImm(0);
6521       NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
6522     }
6523   }
6524 
6525   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6526 
6527   auto UpdatedInst =
6528       BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), ResultReg)
6529           .addImm(0)
6530           .add(Src1) // False
6531           .addImm(0)
6532           .add(Src0) // True
6533           .addReg(IsSCC ? CopySCC : SCCSource);
6534 
6535   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6536   legalizeOperands(*UpdatedInst, MDT);
6537   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6538 }
6539 
6540 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
6541                                  MachineInstr &Inst) const {
6542   MachineBasicBlock &MBB = *Inst.getParent();
6543   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6544   MachineBasicBlock::iterator MII = Inst;
6545   DebugLoc DL = Inst.getDebugLoc();
6546 
6547   MachineOperand &Dest = Inst.getOperand(0);
6548   MachineOperand &Src = Inst.getOperand(1);
6549   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6550   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6551 
6552   unsigned SubOp = ST.hasAddNoCarry() ?
6553     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_CO_U32_e32;
6554 
6555   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
6556     .addImm(0)
6557     .addReg(Src.getReg());
6558 
6559   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
6560     .addReg(Src.getReg())
6561     .addReg(TmpReg);
6562 
6563   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6564   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6565 }
6566 
6567 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
6568                                   MachineInstr &Inst) const {
6569   MachineBasicBlock &MBB = *Inst.getParent();
6570   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6571   MachineBasicBlock::iterator MII = Inst;
6572   const DebugLoc &DL = Inst.getDebugLoc();
6573 
6574   MachineOperand &Dest = Inst.getOperand(0);
6575   MachineOperand &Src0 = Inst.getOperand(1);
6576   MachineOperand &Src1 = Inst.getOperand(2);
6577 
6578   if (ST.hasDLInsts()) {
6579     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6580     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
6581     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
6582 
6583     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
6584       .add(Src0)
6585       .add(Src1);
6586 
6587     MRI.replaceRegWith(Dest.getReg(), NewDest);
6588     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6589   } else {
6590     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
6591     // invert either source and then perform the XOR. If either source is a
6592     // scalar register, then we can leave the inversion on the scalar unit to
6593     // achieve a better distribution of scalar and vector instructions.
6594     bool Src0IsSGPR = Src0.isReg() &&
6595                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
6596     bool Src1IsSGPR = Src1.isReg() &&
6597                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
6598     MachineInstr *Xor;
6599     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6600     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6601 
6602     // Build a pair of scalar instructions and add them to the work list.
6603     // The next iteration over the work list will lower these to the vector
6604     // unit as necessary.
6605     if (Src0IsSGPR) {
6606       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
6607       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6608       .addReg(Temp)
6609       .add(Src1);
6610     } else if (Src1IsSGPR) {
6611       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
6612       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6613       .add(Src0)
6614       .addReg(Temp);
6615     } else {
6616       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
6617         .add(Src0)
6618         .add(Src1);
6619       MachineInstr *Not =
6620           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
6621       Worklist.insert(Not);
6622     }
6623 
6624     MRI.replaceRegWith(Dest.getReg(), NewDest);
6625 
6626     Worklist.insert(Xor);
6627 
6628     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6629   }
6630 }
6631 
6632 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
6633                                       MachineInstr &Inst,
6634                                       unsigned Opcode) const {
6635   MachineBasicBlock &MBB = *Inst.getParent();
6636   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6637   MachineBasicBlock::iterator MII = Inst;
6638   const DebugLoc &DL = Inst.getDebugLoc();
6639 
6640   MachineOperand &Dest = Inst.getOperand(0);
6641   MachineOperand &Src0 = Inst.getOperand(1);
6642   MachineOperand &Src1 = Inst.getOperand(2);
6643 
6644   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6645   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6646 
6647   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
6648     .add(Src0)
6649     .add(Src1);
6650 
6651   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
6652     .addReg(Interm);
6653 
6654   Worklist.insert(&Op);
6655   Worklist.insert(&Not);
6656 
6657   MRI.replaceRegWith(Dest.getReg(), NewDest);
6658   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6659 }
6660 
6661 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
6662                                      MachineInstr &Inst,
6663                                      unsigned Opcode) const {
6664   MachineBasicBlock &MBB = *Inst.getParent();
6665   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6666   MachineBasicBlock::iterator MII = Inst;
6667   const DebugLoc &DL = Inst.getDebugLoc();
6668 
6669   MachineOperand &Dest = Inst.getOperand(0);
6670   MachineOperand &Src0 = Inst.getOperand(1);
6671   MachineOperand &Src1 = Inst.getOperand(2);
6672 
6673   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6674   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6675 
6676   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
6677     .add(Src1);
6678 
6679   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
6680     .add(Src0)
6681     .addReg(Interm);
6682 
6683   Worklist.insert(&Not);
6684   Worklist.insert(&Op);
6685 
6686   MRI.replaceRegWith(Dest.getReg(), NewDest);
6687   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6688 }
6689 
6690 void SIInstrInfo::splitScalar64BitUnaryOp(
6691     SetVectorType &Worklist, MachineInstr &Inst,
6692     unsigned Opcode, bool Swap) const {
6693   MachineBasicBlock &MBB = *Inst.getParent();
6694   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6695 
6696   MachineOperand &Dest = Inst.getOperand(0);
6697   MachineOperand &Src0 = Inst.getOperand(1);
6698   DebugLoc DL = Inst.getDebugLoc();
6699 
6700   MachineBasicBlock::iterator MII = Inst;
6701 
6702   const MCInstrDesc &InstDesc = get(Opcode);
6703   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6704     MRI.getRegClass(Src0.getReg()) :
6705     &AMDGPU::SGPR_32RegClass;
6706 
6707   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6708 
6709   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6710                                                        AMDGPU::sub0, Src0SubRC);
6711 
6712   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6713   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6714   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6715 
6716   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6717   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
6718 
6719   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6720                                                        AMDGPU::sub1, Src0SubRC);
6721 
6722   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6723   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
6724 
6725   if (Swap)
6726     std::swap(DestSub0, DestSub1);
6727 
6728   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6729   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6730     .addReg(DestSub0)
6731     .addImm(AMDGPU::sub0)
6732     .addReg(DestSub1)
6733     .addImm(AMDGPU::sub1);
6734 
6735   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6736 
6737   Worklist.insert(&LoHalf);
6738   Worklist.insert(&HiHalf);
6739 
6740   // We don't need to legalizeOperands here because for a single operand, src0
6741   // will support any kind of input.
6742 
6743   // Move all users of this moved value.
6744   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6745 }
6746 
6747 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
6748                                          MachineInstr &Inst,
6749                                          MachineDominatorTree *MDT) const {
6750   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
6751 
6752   MachineBasicBlock &MBB = *Inst.getParent();
6753   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6754   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6755 
6756   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6757   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6758   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6759 
6760   Register CarryReg = MRI.createVirtualRegister(CarryRC);
6761   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
6762 
6763   MachineOperand &Dest = Inst.getOperand(0);
6764   MachineOperand &Src0 = Inst.getOperand(1);
6765   MachineOperand &Src1 = Inst.getOperand(2);
6766   const DebugLoc &DL = Inst.getDebugLoc();
6767   MachineBasicBlock::iterator MII = Inst;
6768 
6769   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
6770   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
6771   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6772   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6773 
6774   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6775                                                        AMDGPU::sub0, Src0SubRC);
6776   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6777                                                        AMDGPU::sub0, Src1SubRC);
6778 
6779 
6780   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6781                                                        AMDGPU::sub1, Src0SubRC);
6782   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6783                                                        AMDGPU::sub1, Src1SubRC);
6784 
6785   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
6786   MachineInstr *LoHalf =
6787     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
6788     .addReg(CarryReg, RegState::Define)
6789     .add(SrcReg0Sub0)
6790     .add(SrcReg1Sub0)
6791     .addImm(0); // clamp bit
6792 
6793   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
6794   MachineInstr *HiHalf =
6795     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
6796     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
6797     .add(SrcReg0Sub1)
6798     .add(SrcReg1Sub1)
6799     .addReg(CarryReg, RegState::Kill)
6800     .addImm(0); // clamp bit
6801 
6802   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6803     .addReg(DestSub0)
6804     .addImm(AMDGPU::sub0)
6805     .addReg(DestSub1)
6806     .addImm(AMDGPU::sub1);
6807 
6808   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6809 
6810   // Try to legalize the operands in case we need to swap the order to keep it
6811   // valid.
6812   legalizeOperands(*LoHalf, MDT);
6813   legalizeOperands(*HiHalf, MDT);
6814 
6815   // Move all users of this moved value.
6816   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6817 }
6818 
6819 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
6820                                            MachineInstr &Inst, unsigned Opcode,
6821                                            MachineDominatorTree *MDT) const {
6822   MachineBasicBlock &MBB = *Inst.getParent();
6823   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6824 
6825   MachineOperand &Dest = Inst.getOperand(0);
6826   MachineOperand &Src0 = Inst.getOperand(1);
6827   MachineOperand &Src1 = Inst.getOperand(2);
6828   DebugLoc DL = Inst.getDebugLoc();
6829 
6830   MachineBasicBlock::iterator MII = Inst;
6831 
6832   const MCInstrDesc &InstDesc = get(Opcode);
6833   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6834     MRI.getRegClass(Src0.getReg()) :
6835     &AMDGPU::SGPR_32RegClass;
6836 
6837   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6838   const TargetRegisterClass *Src1RC = Src1.isReg() ?
6839     MRI.getRegClass(Src1.getReg()) :
6840     &AMDGPU::SGPR_32RegClass;
6841 
6842   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6843 
6844   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6845                                                        AMDGPU::sub0, Src0SubRC);
6846   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6847                                                        AMDGPU::sub0, Src1SubRC);
6848   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6849                                                        AMDGPU::sub1, Src0SubRC);
6850   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6851                                                        AMDGPU::sub1, Src1SubRC);
6852 
6853   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6854   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6855   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6856 
6857   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6858   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
6859                               .add(SrcReg0Sub0)
6860                               .add(SrcReg1Sub0);
6861 
6862   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6863   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
6864                               .add(SrcReg0Sub1)
6865                               .add(SrcReg1Sub1);
6866 
6867   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6868   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6869     .addReg(DestSub0)
6870     .addImm(AMDGPU::sub0)
6871     .addReg(DestSub1)
6872     .addImm(AMDGPU::sub1);
6873 
6874   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6875 
6876   Worklist.insert(&LoHalf);
6877   Worklist.insert(&HiHalf);
6878 
6879   // Move all users of this moved value.
6880   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6881 }
6882 
6883 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
6884                                        MachineInstr &Inst,
6885                                        MachineDominatorTree *MDT) const {
6886   MachineBasicBlock &MBB = *Inst.getParent();
6887   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6888 
6889   MachineOperand &Dest = Inst.getOperand(0);
6890   MachineOperand &Src0 = Inst.getOperand(1);
6891   MachineOperand &Src1 = Inst.getOperand(2);
6892   const DebugLoc &DL = Inst.getDebugLoc();
6893 
6894   MachineBasicBlock::iterator MII = Inst;
6895 
6896   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6897 
6898   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6899 
6900   MachineOperand* Op0;
6901   MachineOperand* Op1;
6902 
6903   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
6904     Op0 = &Src0;
6905     Op1 = &Src1;
6906   } else {
6907     Op0 = &Src1;
6908     Op1 = &Src0;
6909   }
6910 
6911   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
6912     .add(*Op0);
6913 
6914   Register NewDest = MRI.createVirtualRegister(DestRC);
6915 
6916   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
6917     .addReg(Interm)
6918     .add(*Op1);
6919 
6920   MRI.replaceRegWith(Dest.getReg(), NewDest);
6921 
6922   Worklist.insert(&Xor);
6923 }
6924 
6925 void SIInstrInfo::splitScalar64BitBCNT(
6926     SetVectorType &Worklist, MachineInstr &Inst) const {
6927   MachineBasicBlock &MBB = *Inst.getParent();
6928   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6929 
6930   MachineBasicBlock::iterator MII = Inst;
6931   const DebugLoc &DL = Inst.getDebugLoc();
6932 
6933   MachineOperand &Dest = Inst.getOperand(0);
6934   MachineOperand &Src = Inst.getOperand(1);
6935 
6936   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
6937   const TargetRegisterClass *SrcRC = Src.isReg() ?
6938     MRI.getRegClass(Src.getReg()) :
6939     &AMDGPU::SGPR_32RegClass;
6940 
6941   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6942   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6943 
6944   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
6945 
6946   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6947                                                       AMDGPU::sub0, SrcSubRC);
6948   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6949                                                       AMDGPU::sub1, SrcSubRC);
6950 
6951   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
6952 
6953   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
6954 
6955   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6956 
6957   // We don't need to legalize operands here. src0 for either instruction can be
6958   // an SGPR, and the second input is unused or determined here.
6959   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6960 }
6961 
6962 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
6963                                       MachineInstr &Inst) const {
6964   MachineBasicBlock &MBB = *Inst.getParent();
6965   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6966   MachineBasicBlock::iterator MII = Inst;
6967   const DebugLoc &DL = Inst.getDebugLoc();
6968 
6969   MachineOperand &Dest = Inst.getOperand(0);
6970   uint32_t Imm = Inst.getOperand(2).getImm();
6971   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6972   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6973 
6974   (void) Offset;
6975 
6976   // Only sext_inreg cases handled.
6977   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
6978          Offset == 0 && "Not implemented");
6979 
6980   if (BitWidth < 32) {
6981     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6982     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6983     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6984 
6985     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
6986         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
6987         .addImm(0)
6988         .addImm(BitWidth);
6989 
6990     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
6991       .addImm(31)
6992       .addReg(MidRegLo);
6993 
6994     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6995       .addReg(MidRegLo)
6996       .addImm(AMDGPU::sub0)
6997       .addReg(MidRegHi)
6998       .addImm(AMDGPU::sub1);
6999 
7000     MRI.replaceRegWith(Dest.getReg(), ResultReg);
7001     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
7002     return;
7003   }
7004 
7005   MachineOperand &Src = Inst.getOperand(1);
7006   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7007   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
7008 
7009   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
7010     .addImm(31)
7011     .addReg(Src.getReg(), 0, AMDGPU::sub0);
7012 
7013   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
7014     .addReg(Src.getReg(), 0, AMDGPU::sub0)
7015     .addImm(AMDGPU::sub0)
7016     .addReg(TmpReg)
7017     .addImm(AMDGPU::sub1);
7018 
7019   MRI.replaceRegWith(Dest.getReg(), ResultReg);
7020   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
7021 }
7022 
7023 void SIInstrInfo::addUsersToMoveToVALUWorklist(
7024   Register DstReg,
7025   MachineRegisterInfo &MRI,
7026   SetVectorType &Worklist) const {
7027   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
7028          E = MRI.use_end(); I != E;) {
7029     MachineInstr &UseMI = *I->getParent();
7030 
7031     unsigned OpNo = 0;
7032 
7033     switch (UseMI.getOpcode()) {
7034     case AMDGPU::COPY:
7035     case AMDGPU::WQM:
7036     case AMDGPU::SOFT_WQM:
7037     case AMDGPU::STRICT_WWM:
7038     case AMDGPU::STRICT_WQM:
7039     case AMDGPU::REG_SEQUENCE:
7040     case AMDGPU::PHI:
7041     case AMDGPU::INSERT_SUBREG:
7042       break;
7043     default:
7044       OpNo = I.getOperandNo();
7045       break;
7046     }
7047 
7048     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
7049       Worklist.insert(&UseMI);
7050 
7051       do {
7052         ++I;
7053       } while (I != E && I->getParent() == &UseMI);
7054     } else {
7055       ++I;
7056     }
7057   }
7058 }
7059 
7060 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
7061                                  MachineRegisterInfo &MRI,
7062                                  MachineInstr &Inst) const {
7063   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7064   MachineBasicBlock *MBB = Inst.getParent();
7065   MachineOperand &Src0 = Inst.getOperand(1);
7066   MachineOperand &Src1 = Inst.getOperand(2);
7067   const DebugLoc &DL = Inst.getDebugLoc();
7068 
7069   switch (Inst.getOpcode()) {
7070   case AMDGPU::S_PACK_LL_B32_B16: {
7071     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7072     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7073 
7074     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
7075     // 0.
7076     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7077       .addImm(0xffff);
7078 
7079     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
7080       .addReg(ImmReg, RegState::Kill)
7081       .add(Src0);
7082 
7083     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
7084       .add(Src1)
7085       .addImm(16)
7086       .addReg(TmpReg, RegState::Kill);
7087     break;
7088   }
7089   case AMDGPU::S_PACK_LH_B32_B16: {
7090     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7091     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7092       .addImm(0xffff);
7093     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
7094       .addReg(ImmReg, RegState::Kill)
7095       .add(Src0)
7096       .add(Src1);
7097     break;
7098   }
7099   case AMDGPU::S_PACK_HL_B32_B16: {
7100     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7101     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
7102         .addImm(16)
7103         .add(Src0);
7104     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
7105         .add(Src1)
7106         .addImm(16)
7107         .addReg(TmpReg, RegState::Kill);
7108     break;
7109   }
7110   case AMDGPU::S_PACK_HH_B32_B16: {
7111     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7112     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7113     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
7114       .addImm(16)
7115       .add(Src0);
7116     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7117       .addImm(0xffff0000);
7118     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
7119       .add(Src1)
7120       .addReg(ImmReg, RegState::Kill)
7121       .addReg(TmpReg, RegState::Kill);
7122     break;
7123   }
7124   default:
7125     llvm_unreachable("unhandled s_pack_* instruction");
7126   }
7127 
7128   MachineOperand &Dest = Inst.getOperand(0);
7129   MRI.replaceRegWith(Dest.getReg(), ResultReg);
7130   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
7131 }
7132 
7133 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
7134                                                MachineInstr &SCCDefInst,
7135                                                SetVectorType &Worklist,
7136                                                Register NewCond) const {
7137 
7138   // Ensure that def inst defines SCC, which is still live.
7139   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
7140          !Op.isDead() && Op.getParent() == &SCCDefInst);
7141   SmallVector<MachineInstr *, 4> CopyToDelete;
7142   // This assumes that all the users of SCC are in the same block
7143   // as the SCC def.
7144   for (MachineInstr &MI : // Skip the def inst itself.
7145        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
7146                   SCCDefInst.getParent()->end())) {
7147     // Check if SCC is used first.
7148     int SCCIdx = MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI);
7149     if (SCCIdx != -1) {
7150       if (MI.isCopy()) {
7151         MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7152         Register DestReg = MI.getOperand(0).getReg();
7153 
7154         MRI.replaceRegWith(DestReg, NewCond);
7155         CopyToDelete.push_back(&MI);
7156       } else {
7157 
7158         if (NewCond.isValid())
7159           MI.getOperand(SCCIdx).setReg(NewCond);
7160 
7161         Worklist.insert(&MI);
7162       }
7163     }
7164     // Exit if we find another SCC def.
7165     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
7166       break;
7167   }
7168   for (auto &Copy : CopyToDelete)
7169     Copy->eraseFromParent();
7170 }
7171 
7172 // Instructions that use SCC may be converted to VALU instructions. When that
7173 // happens, the SCC register is changed to VCC_LO. The instruction that defines
7174 // SCC must be changed to an instruction that defines VCC. This function makes
7175 // sure that the instruction that defines SCC is added to the moveToVALU
7176 // worklist.
7177 void SIInstrInfo::addSCCDefsToVALUWorklist(MachineOperand &Op,
7178                                            SetVectorType &Worklist) const {
7179   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isUse());
7180 
7181   MachineInstr *SCCUseInst = Op.getParent();
7182   // Look for a preceding instruction that either defines VCC or SCC. If VCC
7183   // then there is nothing to do because the defining instruction has been
7184   // converted to a VALU already. If SCC then that instruction needs to be
7185   // converted to a VALU.
7186   for (MachineInstr &MI :
7187        make_range(std::next(MachineBasicBlock::reverse_iterator(SCCUseInst)),
7188                   SCCUseInst->getParent()->rend())) {
7189     if (MI.modifiesRegister(AMDGPU::VCC, &RI))
7190       break;
7191     if (MI.definesRegister(AMDGPU::SCC, &RI)) {
7192       Worklist.insert(&MI);
7193       break;
7194     }
7195   }
7196 }
7197 
7198 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
7199   const MachineInstr &Inst) const {
7200   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
7201 
7202   switch (Inst.getOpcode()) {
7203   // For target instructions, getOpRegClass just returns the virtual register
7204   // class associated with the operand, so we need to find an equivalent VGPR
7205   // register class in order to move the instruction to the VALU.
7206   case AMDGPU::COPY:
7207   case AMDGPU::PHI:
7208   case AMDGPU::REG_SEQUENCE:
7209   case AMDGPU::INSERT_SUBREG:
7210   case AMDGPU::WQM:
7211   case AMDGPU::SOFT_WQM:
7212   case AMDGPU::STRICT_WWM:
7213   case AMDGPU::STRICT_WQM: {
7214     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
7215     if (RI.isAGPRClass(SrcRC)) {
7216       if (RI.isAGPRClass(NewDstRC))
7217         return nullptr;
7218 
7219       switch (Inst.getOpcode()) {
7220       case AMDGPU::PHI:
7221       case AMDGPU::REG_SEQUENCE:
7222       case AMDGPU::INSERT_SUBREG:
7223         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
7224         break;
7225       default:
7226         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7227       }
7228 
7229       if (!NewDstRC)
7230         return nullptr;
7231     } else {
7232       if (RI.isVGPRClass(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
7233         return nullptr;
7234 
7235       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7236       if (!NewDstRC)
7237         return nullptr;
7238     }
7239 
7240     return NewDstRC;
7241   }
7242   default:
7243     return NewDstRC;
7244   }
7245 }
7246 
7247 // Find the one SGPR operand we are allowed to use.
7248 Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
7249                                    int OpIndices[3]) const {
7250   const MCInstrDesc &Desc = MI.getDesc();
7251 
7252   // Find the one SGPR operand we are allowed to use.
7253   //
7254   // First we need to consider the instruction's operand requirements before
7255   // legalizing. Some operands are required to be SGPRs, such as implicit uses
7256   // of VCC, but we are still bound by the constant bus requirement to only use
7257   // one.
7258   //
7259   // If the operand's class is an SGPR, we can never move it.
7260 
7261   Register SGPRReg = findImplicitSGPRRead(MI);
7262   if (SGPRReg != AMDGPU::NoRegister)
7263     return SGPRReg;
7264 
7265   Register UsedSGPRs[3] = { AMDGPU::NoRegister };
7266   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7267 
7268   for (unsigned i = 0; i < 3; ++i) {
7269     int Idx = OpIndices[i];
7270     if (Idx == -1)
7271       break;
7272 
7273     const MachineOperand &MO = MI.getOperand(Idx);
7274     if (!MO.isReg())
7275       continue;
7276 
7277     // Is this operand statically required to be an SGPR based on the operand
7278     // constraints?
7279     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
7280     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
7281     if (IsRequiredSGPR)
7282       return MO.getReg();
7283 
7284     // If this could be a VGPR or an SGPR, Check the dynamic register class.
7285     Register Reg = MO.getReg();
7286     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
7287     if (RI.isSGPRClass(RegRC))
7288       UsedSGPRs[i] = Reg;
7289   }
7290 
7291   // We don't have a required SGPR operand, so we have a bit more freedom in
7292   // selecting operands to move.
7293 
7294   // Try to select the most used SGPR. If an SGPR is equal to one of the
7295   // others, we choose that.
7296   //
7297   // e.g.
7298   // V_FMA_F32 v0, s0, s0, s0 -> No moves
7299   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
7300 
7301   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
7302   // prefer those.
7303 
7304   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
7305     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
7306       SGPRReg = UsedSGPRs[0];
7307   }
7308 
7309   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
7310     if (UsedSGPRs[1] == UsedSGPRs[2])
7311       SGPRReg = UsedSGPRs[1];
7312   }
7313 
7314   return SGPRReg;
7315 }
7316 
7317 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
7318                                              unsigned OperandName) const {
7319   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
7320   if (Idx == -1)
7321     return nullptr;
7322 
7323   return &MI.getOperand(Idx);
7324 }
7325 
7326 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
7327   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
7328     int64_t Format = ST.getGeneration() >= AMDGPUSubtarget::GFX11 ?
7329                          AMDGPU::UfmtGFX11::UFMT_32_FLOAT :
7330                          AMDGPU::UfmtGFX10::UFMT_32_FLOAT;
7331     return (Format << 44) |
7332            (1ULL << 56) | // RESOURCE_LEVEL = 1
7333            (3ULL << 60); // OOB_SELECT = 3
7334   }
7335 
7336   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
7337   if (ST.isAmdHsaOS()) {
7338     // Set ATC = 1. GFX9 doesn't have this bit.
7339     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7340       RsrcDataFormat |= (1ULL << 56);
7341 
7342     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
7343     // BTW, it disables TC L2 and therefore decreases performance.
7344     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
7345       RsrcDataFormat |= (2ULL << 59);
7346   }
7347 
7348   return RsrcDataFormat;
7349 }
7350 
7351 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
7352   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
7353                     AMDGPU::RSRC_TID_ENABLE |
7354                     0xffffffff; // Size;
7355 
7356   // GFX9 doesn't have ELEMENT_SIZE.
7357   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
7358     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
7359     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
7360   }
7361 
7362   // IndexStride = 64 / 32.
7363   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
7364   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
7365 
7366   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
7367   // Clear them unless we want a huge stride.
7368   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
7369       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
7370     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
7371 
7372   return Rsrc23;
7373 }
7374 
7375 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
7376   unsigned Opc = MI.getOpcode();
7377 
7378   return isSMRD(Opc);
7379 }
7380 
7381 bool SIInstrInfo::isHighLatencyDef(int Opc) const {
7382   return get(Opc).mayLoad() &&
7383          (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
7384 }
7385 
7386 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
7387                                     int &FrameIndex) const {
7388   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
7389   if (!Addr || !Addr->isFI())
7390     return AMDGPU::NoRegister;
7391 
7392   assert(!MI.memoperands_empty() &&
7393          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
7394 
7395   FrameIndex = Addr->getIndex();
7396   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
7397 }
7398 
7399 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
7400                                         int &FrameIndex) const {
7401   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
7402   assert(Addr && Addr->isFI());
7403   FrameIndex = Addr->getIndex();
7404   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
7405 }
7406 
7407 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
7408                                           int &FrameIndex) const {
7409   if (!MI.mayLoad())
7410     return AMDGPU::NoRegister;
7411 
7412   if (isMUBUF(MI) || isVGPRSpill(MI))
7413     return isStackAccess(MI, FrameIndex);
7414 
7415   if (isSGPRSpill(MI))
7416     return isSGPRStackAccess(MI, FrameIndex);
7417 
7418   return AMDGPU::NoRegister;
7419 }
7420 
7421 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
7422                                          int &FrameIndex) const {
7423   if (!MI.mayStore())
7424     return AMDGPU::NoRegister;
7425 
7426   if (isMUBUF(MI) || isVGPRSpill(MI))
7427     return isStackAccess(MI, FrameIndex);
7428 
7429   if (isSGPRSpill(MI))
7430     return isSGPRStackAccess(MI, FrameIndex);
7431 
7432   return AMDGPU::NoRegister;
7433 }
7434 
7435 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
7436   unsigned Size = 0;
7437   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
7438   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
7439   while (++I != E && I->isInsideBundle()) {
7440     assert(!I->isBundle() && "No nested bundle!");
7441     Size += getInstSizeInBytes(*I);
7442   }
7443 
7444   return Size;
7445 }
7446 
7447 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
7448   unsigned Opc = MI.getOpcode();
7449   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
7450   unsigned DescSize = Desc.getSize();
7451 
7452   // If we have a definitive size, we can use it. Otherwise we need to inspect
7453   // the operands to know the size.
7454   if (isFixedSize(MI)) {
7455     unsigned Size = DescSize;
7456 
7457     // If we hit the buggy offset, an extra nop will be inserted in MC so
7458     // estimate the worst case.
7459     if (MI.isBranch() && ST.hasOffset3fBug())
7460       Size += 4;
7461 
7462     return Size;
7463   }
7464 
7465   // Instructions may have a 32-bit literal encoded after them. Check
7466   // operands that could ever be literals.
7467   if (isVALU(MI) || isSALU(MI)) {
7468     if (isDPP(MI))
7469       return DescSize;
7470     bool HasLiteral = false;
7471     for (int I = 0, E = MI.getNumExplicitOperands(); I != E; ++I) {
7472       const MachineOperand &Op = MI.getOperand(I);
7473       const MCOperandInfo &OpInfo = Desc.OpInfo[I];
7474       if (isLiteralConstantLike(Op, OpInfo)) {
7475         HasLiteral = true;
7476         break;
7477       }
7478     }
7479     return HasLiteral ? DescSize + 4 : DescSize;
7480   }
7481 
7482   // Check whether we have extra NSA words.
7483   if (isMIMG(MI)) {
7484     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
7485     if (VAddr0Idx < 0)
7486       return 8;
7487 
7488     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
7489     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
7490   }
7491 
7492   switch (Opc) {
7493   case TargetOpcode::BUNDLE:
7494     return getInstBundleSize(MI);
7495   case TargetOpcode::INLINEASM:
7496   case TargetOpcode::INLINEASM_BR: {
7497     const MachineFunction *MF = MI.getParent()->getParent();
7498     const char *AsmStr = MI.getOperand(0).getSymbolName();
7499     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(), &ST);
7500   }
7501   default:
7502     if (MI.isMetaInstruction())
7503       return 0;
7504     return DescSize;
7505   }
7506 }
7507 
7508 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
7509   if (!isFLAT(MI))
7510     return false;
7511 
7512   if (MI.memoperands_empty())
7513     return true;
7514 
7515   for (const MachineMemOperand *MMO : MI.memoperands()) {
7516     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
7517       return true;
7518   }
7519   return false;
7520 }
7521 
7522 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
7523   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
7524 }
7525 
7526 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
7527                                             MachineBasicBlock *IfEnd) const {
7528   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
7529   assert(TI != IfEntry->end());
7530 
7531   MachineInstr *Branch = &(*TI);
7532   MachineFunction *MF = IfEntry->getParent();
7533   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
7534 
7535   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7536     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7537     MachineInstr *SIIF =
7538         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
7539             .add(Branch->getOperand(0))
7540             .add(Branch->getOperand(1));
7541     MachineInstr *SIEND =
7542         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
7543             .addReg(DstReg);
7544 
7545     IfEntry->erase(TI);
7546     IfEntry->insert(IfEntry->end(), SIIF);
7547     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
7548   }
7549 }
7550 
7551 void SIInstrInfo::convertNonUniformLoopRegion(
7552     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
7553   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
7554   // We expect 2 terminators, one conditional and one unconditional.
7555   assert(TI != LoopEnd->end());
7556 
7557   MachineInstr *Branch = &(*TI);
7558   MachineFunction *MF = LoopEnd->getParent();
7559   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
7560 
7561   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7562 
7563     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7564     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
7565     MachineInstrBuilder HeaderPHIBuilder =
7566         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
7567     for (MachineBasicBlock *PMBB : LoopEntry->predecessors()) {
7568       if (PMBB == LoopEnd) {
7569         HeaderPHIBuilder.addReg(BackEdgeReg);
7570       } else {
7571         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
7572         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
7573                              ZeroReg, 0);
7574         HeaderPHIBuilder.addReg(ZeroReg);
7575       }
7576       HeaderPHIBuilder.addMBB(PMBB);
7577     }
7578     MachineInstr *HeaderPhi = HeaderPHIBuilder;
7579     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
7580                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
7581                                   .addReg(DstReg)
7582                                   .add(Branch->getOperand(0));
7583     MachineInstr *SILOOP =
7584         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
7585             .addReg(BackEdgeReg)
7586             .addMBB(LoopEntry);
7587 
7588     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
7589     LoopEnd->erase(TI);
7590     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
7591     LoopEnd->insert(LoopEnd->end(), SILOOP);
7592   }
7593 }
7594 
7595 ArrayRef<std::pair<int, const char *>>
7596 SIInstrInfo::getSerializableTargetIndices() const {
7597   static const std::pair<int, const char *> TargetIndices[] = {
7598       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
7599       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
7600       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
7601       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
7602       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
7603   return makeArrayRef(TargetIndices);
7604 }
7605 
7606 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
7607 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
7608 ScheduleHazardRecognizer *
7609 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
7610                                             const ScheduleDAG *DAG) const {
7611   return new GCNHazardRecognizer(DAG->MF);
7612 }
7613 
7614 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
7615 /// pass.
7616 ScheduleHazardRecognizer *
7617 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
7618   return new GCNHazardRecognizer(MF);
7619 }
7620 
7621 // Called during:
7622 // - pre-RA scheduling and post-RA scheduling
7623 ScheduleHazardRecognizer *
7624 SIInstrInfo::CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
7625                                             const ScheduleDAGMI *DAG) const {
7626   // Borrowed from Arm Target
7627   // We would like to restrict this hazard recognizer to only
7628   // post-RA scheduling; we can tell that we're post-RA because we don't
7629   // track VRegLiveness.
7630   if (!DAG->hasVRegLiveness())
7631     return new GCNHazardRecognizer(DAG->MF);
7632   return TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
7633 }
7634 
7635 std::pair<unsigned, unsigned>
7636 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7637   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
7638 }
7639 
7640 ArrayRef<std::pair<unsigned, const char *>>
7641 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7642   static const std::pair<unsigned, const char *> TargetFlags[] = {
7643     { MO_GOTPCREL, "amdgpu-gotprel" },
7644     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
7645     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
7646     { MO_REL32_LO, "amdgpu-rel32-lo" },
7647     { MO_REL32_HI, "amdgpu-rel32-hi" },
7648     { MO_ABS32_LO, "amdgpu-abs32-lo" },
7649     { MO_ABS32_HI, "amdgpu-abs32-hi" },
7650   };
7651 
7652   return makeArrayRef(TargetFlags);
7653 }
7654 
7655 ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
7656 SIInstrInfo::getSerializableMachineMemOperandTargetFlags() const {
7657   static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
7658       {
7659           {MONoClobber, "amdgpu-noclobber"},
7660       };
7661 
7662   return makeArrayRef(TargetFlags);
7663 }
7664 
7665 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
7666   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
7667          MI.modifiesRegister(AMDGPU::EXEC, &RI);
7668 }
7669 
7670 MachineInstrBuilder
7671 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7672                            MachineBasicBlock::iterator I,
7673                            const DebugLoc &DL,
7674                            Register DestReg) const {
7675   if (ST.hasAddNoCarry())
7676     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
7677 
7678   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7679   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
7680   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
7681 
7682   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7683            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7684 }
7685 
7686 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7687                                                MachineBasicBlock::iterator I,
7688                                                const DebugLoc &DL,
7689                                                Register DestReg,
7690                                                RegScavenger &RS) const {
7691   if (ST.hasAddNoCarry())
7692     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
7693 
7694   // If available, prefer to use vcc.
7695   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
7696                              ? Register(RI.getVCC())
7697                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
7698 
7699   // TODO: Users need to deal with this.
7700   if (!UnusedCarry.isValid())
7701     return MachineInstrBuilder();
7702 
7703   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7704            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7705 }
7706 
7707 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
7708   switch (Opcode) {
7709   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
7710   case AMDGPU::SI_KILL_I1_TERMINATOR:
7711     return true;
7712   default:
7713     return false;
7714   }
7715 }
7716 
7717 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
7718   switch (Opcode) {
7719   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7720     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
7721   case AMDGPU::SI_KILL_I1_PSEUDO:
7722     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
7723   default:
7724     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
7725   }
7726 }
7727 
7728 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
7729   if (!ST.isWave32())
7730     return;
7731 
7732   for (auto &Op : MI.implicit_operands()) {
7733     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
7734       Op.setReg(AMDGPU::VCC_LO);
7735   }
7736 }
7737 
7738 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
7739   if (!isSMRD(MI))
7740     return false;
7741 
7742   // Check that it is using a buffer resource.
7743   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
7744   if (Idx == -1) // e.g. s_memtime
7745     return false;
7746 
7747   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
7748   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
7749 }
7750 
7751 // Depending on the used address space and instructions, some immediate offsets
7752 // are allowed and some are not.
7753 // In general, flat instruction offsets can only be non-negative, global and
7754 // scratch instruction offsets can also be negative.
7755 //
7756 // There are several bugs related to these offsets:
7757 // On gfx10.1, flat instructions that go into the global address space cannot
7758 // use an offset.
7759 //
7760 // For scratch instructions, the address can be either an SGPR or a VGPR.
7761 // The following offsets can be used, depending on the architecture (x means
7762 // cannot be used):
7763 // +----------------------------+------+------+
7764 // | Address-Mode               | SGPR | VGPR |
7765 // +----------------------------+------+------+
7766 // | gfx9                       |      |      |
7767 // | negative, 4-aligned offset | x    | ok   |
7768 // | negative, unaligned offset | x    | ok   |
7769 // +----------------------------+------+------+
7770 // | gfx10                      |      |      |
7771 // | negative, 4-aligned offset | ok   | ok   |
7772 // | negative, unaligned offset | ok   | x    |
7773 // +----------------------------+------+------+
7774 // | gfx10.3                    |      |      |
7775 // | negative, 4-aligned offset | ok   | ok   |
7776 // | negative, unaligned offset | ok   | ok   |
7777 // +----------------------------+------+------+
7778 //
7779 // This function ignores the addressing mode, so if an offset cannot be used in
7780 // one addressing mode, it is considered illegal.
7781 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
7782                                     uint64_t FlatVariant) const {
7783   // TODO: Should 0 be special cased?
7784   if (!ST.hasFlatInstOffsets())
7785     return false;
7786 
7787   if (ST.hasFlatSegmentOffsetBug() && FlatVariant == SIInstrFlags::FLAT &&
7788       (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
7789        AddrSpace == AMDGPUAS::GLOBAL_ADDRESS))
7790     return false;
7791 
7792   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7793   if (ST.hasNegativeScratchOffsetBug() &&
7794       FlatVariant == SIInstrFlags::FlatScratch)
7795     Signed = false;
7796   if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7797       FlatVariant == SIInstrFlags::FlatScratch && Offset < 0 &&
7798       (Offset % 4) != 0) {
7799     return false;
7800   }
7801 
7802   unsigned N = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7803   return Signed ? isIntN(N, Offset) : isUIntN(N, Offset);
7804 }
7805 
7806 // See comment on SIInstrInfo::isLegalFLATOffset for what is legal and what not.
7807 std::pair<int64_t, int64_t>
7808 SIInstrInfo::splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace,
7809                              uint64_t FlatVariant) const {
7810   int64_t RemainderOffset = COffsetVal;
7811   int64_t ImmField = 0;
7812   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7813   if (ST.hasNegativeScratchOffsetBug() &&
7814       FlatVariant == SIInstrFlags::FlatScratch)
7815     Signed = false;
7816 
7817   const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7818   if (Signed) {
7819     // Use signed division by a power of two to truncate towards 0.
7820     int64_t D = 1LL << (NumBits - 1);
7821     RemainderOffset = (COffsetVal / D) * D;
7822     ImmField = COffsetVal - RemainderOffset;
7823 
7824     if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7825         FlatVariant == SIInstrFlags::FlatScratch && ImmField < 0 &&
7826         (ImmField % 4) != 0) {
7827       // Make ImmField a multiple of 4
7828       RemainderOffset += ImmField % 4;
7829       ImmField -= ImmField % 4;
7830     }
7831   } else if (COffsetVal >= 0) {
7832     ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
7833     RemainderOffset = COffsetVal - ImmField;
7834   }
7835 
7836   assert(isLegalFLATOffset(ImmField, AddrSpace, FlatVariant));
7837   assert(RemainderOffset + ImmField == COffsetVal);
7838   return {ImmField, RemainderOffset};
7839 }
7840 
7841 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
7842 // and the columns of the getMCOpcodeGen table.
7843 enum SIEncodingFamily {
7844   SI = 0,
7845   VI = 1,
7846   SDWA = 2,
7847   SDWA9 = 3,
7848   GFX80 = 4,
7849   GFX9 = 5,
7850   GFX10 = 6,
7851   SDWA10 = 7,
7852   GFX90A = 8,
7853   GFX940 = 9,
7854   GFX11 = 10,
7855 };
7856 
7857 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
7858   switch (ST.getGeneration()) {
7859   default:
7860     break;
7861   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
7862   case AMDGPUSubtarget::SEA_ISLANDS:
7863     return SIEncodingFamily::SI;
7864   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
7865   case AMDGPUSubtarget::GFX9:
7866     return SIEncodingFamily::VI;
7867   case AMDGPUSubtarget::GFX10:
7868     return SIEncodingFamily::GFX10;
7869   case AMDGPUSubtarget::GFX11:
7870     return SIEncodingFamily::GFX11;
7871   }
7872   llvm_unreachable("Unknown subtarget generation!");
7873 }
7874 
7875 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
7876   switch(MCOp) {
7877   // These opcodes use indirect register addressing so
7878   // they need special handling by codegen (currently missing).
7879   // Therefore it is too risky to allow these opcodes
7880   // to be selected by dpp combiner or sdwa peepholer.
7881   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
7882   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
7883   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
7884   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
7885   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
7886   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
7887   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
7888   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
7889     return true;
7890   default:
7891     return false;
7892   }
7893 }
7894 
7895 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
7896   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
7897 
7898   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
7899     ST.getGeneration() == AMDGPUSubtarget::GFX9)
7900     Gen = SIEncodingFamily::GFX9;
7901 
7902   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
7903   // subtarget has UnpackedD16VMem feature.
7904   // TODO: remove this when we discard GFX80 encoding.
7905   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
7906     Gen = SIEncodingFamily::GFX80;
7907 
7908   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
7909     switch (ST.getGeneration()) {
7910     default:
7911       Gen = SIEncodingFamily::SDWA;
7912       break;
7913     case AMDGPUSubtarget::GFX9:
7914       Gen = SIEncodingFamily::SDWA9;
7915       break;
7916     case AMDGPUSubtarget::GFX10:
7917       Gen = SIEncodingFamily::SDWA10;
7918       break;
7919     }
7920   }
7921 
7922   if (isMAI(Opcode)) {
7923     int MFMAOp = AMDGPU::getMFMAEarlyClobberOp(Opcode);
7924     if (MFMAOp != -1)
7925       Opcode = MFMAOp;
7926   }
7927 
7928   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
7929 
7930   // -1 means that Opcode is already a native instruction.
7931   if (MCOp == -1)
7932     return Opcode;
7933 
7934   if (ST.hasGFX90AInsts()) {
7935     uint16_t NMCOp = (uint16_t)-1;
7936     if (ST.hasGFX940Insts())
7937       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX940);
7938     if (NMCOp == (uint16_t)-1)
7939       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX90A);
7940     if (NMCOp == (uint16_t)-1)
7941       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX9);
7942     if (NMCOp != (uint16_t)-1)
7943       MCOp = NMCOp;
7944   }
7945 
7946   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
7947   // no encoding in the given subtarget generation.
7948   if (MCOp == (uint16_t)-1)
7949     return -1;
7950 
7951   if (isAsmOnlyOpcode(MCOp))
7952     return -1;
7953 
7954   return MCOp;
7955 }
7956 
7957 static
7958 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
7959   assert(RegOpnd.isReg());
7960   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
7961                              getRegSubRegPair(RegOpnd);
7962 }
7963 
7964 TargetInstrInfo::RegSubRegPair
7965 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
7966   assert(MI.isRegSequence());
7967   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
7968     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
7969       auto &RegOp = MI.getOperand(1 + 2 * I);
7970       return getRegOrUndef(RegOp);
7971     }
7972   return TargetInstrInfo::RegSubRegPair();
7973 }
7974 
7975 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
7976 // Following a subreg of reg:subreg isn't supported
7977 static bool followSubRegDef(MachineInstr &MI,
7978                             TargetInstrInfo::RegSubRegPair &RSR) {
7979   if (!RSR.SubReg)
7980     return false;
7981   switch (MI.getOpcode()) {
7982   default: break;
7983   case AMDGPU::REG_SEQUENCE:
7984     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
7985     return true;
7986   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
7987   case AMDGPU::INSERT_SUBREG:
7988     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
7989       // inserted the subreg we're looking for
7990       RSR = getRegOrUndef(MI.getOperand(2));
7991     else { // the subreg in the rest of the reg
7992       auto R1 = getRegOrUndef(MI.getOperand(1));
7993       if (R1.SubReg) // subreg of subreg isn't supported
7994         return false;
7995       RSR.Reg = R1.Reg;
7996     }
7997     return true;
7998   }
7999   return false;
8000 }
8001 
8002 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
8003                                      MachineRegisterInfo &MRI) {
8004   assert(MRI.isSSA());
8005   if (!P.Reg.isVirtual())
8006     return nullptr;
8007 
8008   auto RSR = P;
8009   auto *DefInst = MRI.getVRegDef(RSR.Reg);
8010   while (auto *MI = DefInst) {
8011     DefInst = nullptr;
8012     switch (MI->getOpcode()) {
8013     case AMDGPU::COPY:
8014     case AMDGPU::V_MOV_B32_e32: {
8015       auto &Op1 = MI->getOperand(1);
8016       if (Op1.isReg() && Op1.getReg().isVirtual()) {
8017         if (Op1.isUndef())
8018           return nullptr;
8019         RSR = getRegSubRegPair(Op1);
8020         DefInst = MRI.getVRegDef(RSR.Reg);
8021       }
8022       break;
8023     }
8024     default:
8025       if (followSubRegDef(*MI, RSR)) {
8026         if (!RSR.Reg)
8027           return nullptr;
8028         DefInst = MRI.getVRegDef(RSR.Reg);
8029       }
8030     }
8031     if (!DefInst)
8032       return MI;
8033   }
8034   return nullptr;
8035 }
8036 
8037 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
8038                                       Register VReg,
8039                                       const MachineInstr &DefMI,
8040                                       const MachineInstr &UseMI) {
8041   assert(MRI.isSSA() && "Must be run on SSA");
8042 
8043   auto *TRI = MRI.getTargetRegisterInfo();
8044   auto *DefBB = DefMI.getParent();
8045 
8046   // Don't bother searching between blocks, although it is possible this block
8047   // doesn't modify exec.
8048   if (UseMI.getParent() != DefBB)
8049     return true;
8050 
8051   const int MaxInstScan = 20;
8052   int NumInst = 0;
8053 
8054   // Stop scan at the use.
8055   auto E = UseMI.getIterator();
8056   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
8057     if (I->isDebugInstr())
8058       continue;
8059 
8060     if (++NumInst > MaxInstScan)
8061       return true;
8062 
8063     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
8064       return true;
8065   }
8066 
8067   return false;
8068 }
8069 
8070 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
8071                                          Register VReg,
8072                                          const MachineInstr &DefMI) {
8073   assert(MRI.isSSA() && "Must be run on SSA");
8074 
8075   auto *TRI = MRI.getTargetRegisterInfo();
8076   auto *DefBB = DefMI.getParent();
8077 
8078   const int MaxUseScan = 10;
8079   int NumUse = 0;
8080 
8081   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
8082     auto &UseInst = *Use.getParent();
8083     // Don't bother searching between blocks, although it is possible this block
8084     // doesn't modify exec.
8085     if (UseInst.getParent() != DefBB || UseInst.isPHI())
8086       return true;
8087 
8088     if (++NumUse > MaxUseScan)
8089       return true;
8090   }
8091 
8092   if (NumUse == 0)
8093     return false;
8094 
8095   const int MaxInstScan = 20;
8096   int NumInst = 0;
8097 
8098   // Stop scan when we have seen all the uses.
8099   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
8100     assert(I != DefBB->end());
8101 
8102     if (I->isDebugInstr())
8103       continue;
8104 
8105     if (++NumInst > MaxInstScan)
8106       return true;
8107 
8108     for (const MachineOperand &Op : I->operands()) {
8109       // We don't check reg masks here as they're used only on calls:
8110       // 1. EXEC is only considered const within one BB
8111       // 2. Call should be a terminator instruction if present in a BB
8112 
8113       if (!Op.isReg())
8114         continue;
8115 
8116       Register Reg = Op.getReg();
8117       if (Op.isUse()) {
8118         if (Reg == VReg && --NumUse == 0)
8119           return false;
8120       } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
8121         return true;
8122     }
8123   }
8124 }
8125 
8126 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
8127     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
8128     const DebugLoc &DL, Register Src, Register Dst) const {
8129   auto Cur = MBB.begin();
8130   if (Cur != MBB.end())
8131     do {
8132       if (!Cur->isPHI() && Cur->readsRegister(Dst))
8133         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
8134       ++Cur;
8135     } while (Cur != MBB.end() && Cur != LastPHIIt);
8136 
8137   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
8138                                                    Dst);
8139 }
8140 
8141 MachineInstr *SIInstrInfo::createPHISourceCopy(
8142     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
8143     const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
8144   if (InsPt != MBB.end() &&
8145       (InsPt->getOpcode() == AMDGPU::SI_IF ||
8146        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
8147        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
8148       InsPt->definesRegister(Src)) {
8149     InsPt++;
8150     return BuildMI(MBB, InsPt, DL,
8151                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
8152                                      : AMDGPU::S_MOV_B64_term),
8153                    Dst)
8154         .addReg(Src, 0, SrcSubReg)
8155         .addReg(AMDGPU::EXEC, RegState::Implicit);
8156   }
8157   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
8158                                               Dst);
8159 }
8160 
8161 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
8162 
8163 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
8164     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
8165     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
8166     VirtRegMap *VRM) const {
8167   // This is a bit of a hack (copied from AArch64). Consider this instruction:
8168   //
8169   //   %0:sreg_32 = COPY $m0
8170   //
8171   // We explicitly chose SReg_32 for the virtual register so such a copy might
8172   // be eliminated by RegisterCoalescer. However, that may not be possible, and
8173   // %0 may even spill. We can't spill $m0 normally (it would require copying to
8174   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
8175   // TargetInstrInfo::foldMemoryOperand() is going to try.
8176   // A similar issue also exists with spilling and reloading $exec registers.
8177   //
8178   // To prevent that, constrain the %0 register class here.
8179   if (MI.isFullCopy()) {
8180     Register DstReg = MI.getOperand(0).getReg();
8181     Register SrcReg = MI.getOperand(1).getReg();
8182     if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
8183         (DstReg.isVirtual() != SrcReg.isVirtual())) {
8184       MachineRegisterInfo &MRI = MF.getRegInfo();
8185       Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
8186       const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
8187       if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
8188         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
8189         return nullptr;
8190       } else if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
8191         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
8192         return nullptr;
8193       }
8194     }
8195   }
8196 
8197   return nullptr;
8198 }
8199 
8200 unsigned SIInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
8201                                       const MachineInstr &MI,
8202                                       unsigned *PredCost) const {
8203   if (MI.isBundle()) {
8204     MachineBasicBlock::const_instr_iterator I(MI.getIterator());
8205     MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
8206     unsigned Lat = 0, Count = 0;
8207     for (++I; I != E && I->isBundledWithPred(); ++I) {
8208       ++Count;
8209       Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
8210     }
8211     return Lat + Count - 1;
8212   }
8213 
8214   return SchedModel.computeInstrLatency(&MI);
8215 }
8216 
8217 unsigned SIInstrInfo::getDSShaderTypeValue(const MachineFunction &MF) {
8218   switch (MF.getFunction().getCallingConv()) {
8219   case CallingConv::AMDGPU_PS:
8220     return 1;
8221   case CallingConv::AMDGPU_VS:
8222     return 2;
8223   case CallingConv::AMDGPU_GS:
8224     return 3;
8225   case CallingConv::AMDGPU_HS:
8226   case CallingConv::AMDGPU_LS:
8227   case CallingConv::AMDGPU_ES:
8228     report_fatal_error("ds_ordered_count unsupported for this calling conv");
8229   case CallingConv::AMDGPU_CS:
8230   case CallingConv::AMDGPU_KERNEL:
8231   case CallingConv::C:
8232   case CallingConv::Fast:
8233   default:
8234     // Assume other calling conventions are various compute callable functions
8235     return 0;
8236   }
8237 }
8238 
8239 bool SIInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
8240                                  Register &SrcReg2, int64_t &CmpMask,
8241                                  int64_t &CmpValue) const {
8242   if (!MI.getOperand(0).isReg() || MI.getOperand(0).getSubReg())
8243     return false;
8244 
8245   switch (MI.getOpcode()) {
8246   default:
8247     break;
8248   case AMDGPU::S_CMP_EQ_U32:
8249   case AMDGPU::S_CMP_EQ_I32:
8250   case AMDGPU::S_CMP_LG_U32:
8251   case AMDGPU::S_CMP_LG_I32:
8252   case AMDGPU::S_CMP_LT_U32:
8253   case AMDGPU::S_CMP_LT_I32:
8254   case AMDGPU::S_CMP_GT_U32:
8255   case AMDGPU::S_CMP_GT_I32:
8256   case AMDGPU::S_CMP_LE_U32:
8257   case AMDGPU::S_CMP_LE_I32:
8258   case AMDGPU::S_CMP_GE_U32:
8259   case AMDGPU::S_CMP_GE_I32:
8260   case AMDGPU::S_CMP_EQ_U64:
8261   case AMDGPU::S_CMP_LG_U64:
8262     SrcReg = MI.getOperand(0).getReg();
8263     if (MI.getOperand(1).isReg()) {
8264       if (MI.getOperand(1).getSubReg())
8265         return false;
8266       SrcReg2 = MI.getOperand(1).getReg();
8267       CmpValue = 0;
8268     } else if (MI.getOperand(1).isImm()) {
8269       SrcReg2 = Register();
8270       CmpValue = MI.getOperand(1).getImm();
8271     } else {
8272       return false;
8273     }
8274     CmpMask = ~0;
8275     return true;
8276   case AMDGPU::S_CMPK_EQ_U32:
8277   case AMDGPU::S_CMPK_EQ_I32:
8278   case AMDGPU::S_CMPK_LG_U32:
8279   case AMDGPU::S_CMPK_LG_I32:
8280   case AMDGPU::S_CMPK_LT_U32:
8281   case AMDGPU::S_CMPK_LT_I32:
8282   case AMDGPU::S_CMPK_GT_U32:
8283   case AMDGPU::S_CMPK_GT_I32:
8284   case AMDGPU::S_CMPK_LE_U32:
8285   case AMDGPU::S_CMPK_LE_I32:
8286   case AMDGPU::S_CMPK_GE_U32:
8287   case AMDGPU::S_CMPK_GE_I32:
8288     SrcReg = MI.getOperand(0).getReg();
8289     SrcReg2 = Register();
8290     CmpValue = MI.getOperand(1).getImm();
8291     CmpMask = ~0;
8292     return true;
8293   }
8294 
8295   return false;
8296 }
8297 
8298 bool SIInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
8299                                        Register SrcReg2, int64_t CmpMask,
8300                                        int64_t CmpValue,
8301                                        const MachineRegisterInfo *MRI) const {
8302   if (!SrcReg || SrcReg.isPhysical())
8303     return false;
8304 
8305   if (SrcReg2 && !getFoldableImm(SrcReg2, *MRI, CmpValue))
8306     return false;
8307 
8308   const auto optimizeCmpAnd = [&CmpInstr, SrcReg, CmpValue, MRI,
8309                                this](int64_t ExpectedValue, unsigned SrcSize,
8310                                      bool IsReversible, bool IsSigned) -> bool {
8311     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8312     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8313     // s_cmp_ge_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8314     // s_cmp_ge_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8315     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 1 << n => s_and_b64 $src, 1 << n
8316     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8317     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8318     // s_cmp_gt_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8319     // s_cmp_gt_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8320     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 0 => s_and_b64 $src, 1 << n
8321     //
8322     // Signed ge/gt are not used for the sign bit.
8323     //
8324     // If result of the AND is unused except in the compare:
8325     // s_and_b(32|64) $src, 1 << n => s_bitcmp1_b(32|64) $src, n
8326     //
8327     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8328     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8329     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 0 => s_bitcmp0_b64 $src, n
8330     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8331     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8332     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 1 << n => s_bitcmp0_b64 $src, n
8333 
8334     MachineInstr *Def = MRI->getUniqueVRegDef(SrcReg);
8335     if (!Def || Def->getParent() != CmpInstr.getParent())
8336       return false;
8337 
8338     if (Def->getOpcode() != AMDGPU::S_AND_B32 &&
8339         Def->getOpcode() != AMDGPU::S_AND_B64)
8340       return false;
8341 
8342     int64_t Mask;
8343     const auto isMask = [&Mask, SrcSize](const MachineOperand *MO) -> bool {
8344       if (MO->isImm())
8345         Mask = MO->getImm();
8346       else if (!getFoldableImm(MO, Mask))
8347         return false;
8348       Mask &= maxUIntN(SrcSize);
8349       return isPowerOf2_64(Mask);
8350     };
8351 
8352     MachineOperand *SrcOp = &Def->getOperand(1);
8353     if (isMask(SrcOp))
8354       SrcOp = &Def->getOperand(2);
8355     else if (isMask(&Def->getOperand(2)))
8356       SrcOp = &Def->getOperand(1);
8357     else
8358       return false;
8359 
8360     unsigned BitNo = countTrailingZeros((uint64_t)Mask);
8361     if (IsSigned && BitNo == SrcSize - 1)
8362       return false;
8363 
8364     ExpectedValue <<= BitNo;
8365 
8366     bool IsReversedCC = false;
8367     if (CmpValue != ExpectedValue) {
8368       if (!IsReversible)
8369         return false;
8370       IsReversedCC = CmpValue == (ExpectedValue ^ Mask);
8371       if (!IsReversedCC)
8372         return false;
8373     }
8374 
8375     Register DefReg = Def->getOperand(0).getReg();
8376     if (IsReversedCC && !MRI->hasOneNonDBGUse(DefReg))
8377       return false;
8378 
8379     for (auto I = std::next(Def->getIterator()), E = CmpInstr.getIterator();
8380          I != E; ++I) {
8381       if (I->modifiesRegister(AMDGPU::SCC, &RI) ||
8382           I->killsRegister(AMDGPU::SCC, &RI))
8383         return false;
8384     }
8385 
8386     MachineOperand *SccDef = Def->findRegisterDefOperand(AMDGPU::SCC);
8387     SccDef->setIsDead(false);
8388     CmpInstr.eraseFromParent();
8389 
8390     if (!MRI->use_nodbg_empty(DefReg)) {
8391       assert(!IsReversedCC);
8392       return true;
8393     }
8394 
8395     // Replace AND with unused result with a S_BITCMP.
8396     MachineBasicBlock *MBB = Def->getParent();
8397 
8398     unsigned NewOpc = (SrcSize == 32) ? IsReversedCC ? AMDGPU::S_BITCMP0_B32
8399                                                      : AMDGPU::S_BITCMP1_B32
8400                                       : IsReversedCC ? AMDGPU::S_BITCMP0_B64
8401                                                      : AMDGPU::S_BITCMP1_B64;
8402 
8403     BuildMI(*MBB, Def, Def->getDebugLoc(), get(NewOpc))
8404       .add(*SrcOp)
8405       .addImm(BitNo);
8406     Def->eraseFromParent();
8407 
8408     return true;
8409   };
8410 
8411   switch (CmpInstr.getOpcode()) {
8412   default:
8413     break;
8414   case AMDGPU::S_CMP_EQ_U32:
8415   case AMDGPU::S_CMP_EQ_I32:
8416   case AMDGPU::S_CMPK_EQ_U32:
8417   case AMDGPU::S_CMPK_EQ_I32:
8418     return optimizeCmpAnd(1, 32, true, false);
8419   case AMDGPU::S_CMP_GE_U32:
8420   case AMDGPU::S_CMPK_GE_U32:
8421     return optimizeCmpAnd(1, 32, false, false);
8422   case AMDGPU::S_CMP_GE_I32:
8423   case AMDGPU::S_CMPK_GE_I32:
8424     return optimizeCmpAnd(1, 32, false, true);
8425   case AMDGPU::S_CMP_EQ_U64:
8426     return optimizeCmpAnd(1, 64, true, false);
8427   case AMDGPU::S_CMP_LG_U32:
8428   case AMDGPU::S_CMP_LG_I32:
8429   case AMDGPU::S_CMPK_LG_U32:
8430   case AMDGPU::S_CMPK_LG_I32:
8431     return optimizeCmpAnd(0, 32, true, false);
8432   case AMDGPU::S_CMP_GT_U32:
8433   case AMDGPU::S_CMPK_GT_U32:
8434     return optimizeCmpAnd(0, 32, false, false);
8435   case AMDGPU::S_CMP_GT_I32:
8436   case AMDGPU::S_CMPK_GT_I32:
8437     return optimizeCmpAnd(0, 32, false, true);
8438   case AMDGPU::S_CMP_LG_U64:
8439     return optimizeCmpAnd(0, 64, true, false);
8440   }
8441 
8442   return false;
8443 }
8444 
8445 void SIInstrInfo::enforceOperandRCAlignment(MachineInstr &MI,
8446                                             unsigned OpName) const {
8447   if (!ST.needsAlignedVGPRs())
8448     return;
8449 
8450   int OpNo = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
8451   if (OpNo < 0)
8452     return;
8453   MachineOperand &Op = MI.getOperand(OpNo);
8454   if (getOpSize(MI, OpNo) > 4)
8455     return;
8456 
8457   // Add implicit aligned super-reg to force alignment on the data operand.
8458   const DebugLoc &DL = MI.getDebugLoc();
8459   MachineBasicBlock *BB = MI.getParent();
8460   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8461   Register DataReg = Op.getReg();
8462   bool IsAGPR = RI.isAGPR(MRI, DataReg);
8463   Register Undef = MRI.createVirtualRegister(
8464       IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
8465   BuildMI(*BB, MI, DL, get(AMDGPU::IMPLICIT_DEF), Undef);
8466   Register NewVR =
8467       MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
8468                                        : &AMDGPU::VReg_64_Align2RegClass);
8469   BuildMI(*BB, MI, DL, get(AMDGPU::REG_SEQUENCE), NewVR)
8470       .addReg(DataReg, 0, Op.getSubReg())
8471       .addImm(AMDGPU::sub0)
8472       .addReg(Undef)
8473       .addImm(AMDGPU::sub1);
8474   Op.setReg(NewVR);
8475   Op.setSubReg(AMDGPU::sub0);
8476   MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
8477 }
8478