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