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