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