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