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