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