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