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