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   if (Src2) {
3660     switch (MI.getOpcode()) {
3661       default: return false;
3662 
3663       case AMDGPU::V_ADDC_U32_e64:
3664       case AMDGPU::V_SUBB_U32_e64:
3665       case AMDGPU::V_SUBBREV_U32_e64: {
3666         const MachineOperand *Src1
3667           = getNamedOperand(MI, AMDGPU::OpName::src1);
3668         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
3669           return false;
3670         // Additional verification is needed for sdst/src2.
3671         return true;
3672       }
3673       case AMDGPU::V_MAC_F16_e64:
3674       case AMDGPU::V_MAC_F32_e64:
3675       case AMDGPU::V_MAC_LEGACY_F32_e64:
3676       case AMDGPU::V_FMAC_F16_e64:
3677       case AMDGPU::V_FMAC_F32_e64:
3678       case AMDGPU::V_FMAC_F64_e64:
3679       case AMDGPU::V_FMAC_LEGACY_F32_e64:
3680         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
3681             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
3682           return false;
3683         break;
3684 
3685       case AMDGPU::V_CNDMASK_B32_e64:
3686         break;
3687     }
3688   }
3689 
3690   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3691   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
3692                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
3693     return false;
3694 
3695   // We don't need to check src0, all input types are legal, so just make sure
3696   // src0 isn't using any modifiers.
3697   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
3698     return false;
3699 
3700   // Can it be shrunk to a valid 32 bit opcode?
3701   if (!hasVALU32BitEncoding(MI.getOpcode()))
3702     return false;
3703 
3704   // Check output modifiers
3705   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
3706          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
3707 }
3708 
3709 // Set VCC operand with all flags from \p Orig, except for setting it as
3710 // implicit.
3711 static void copyFlagsToImplicitVCC(MachineInstr &MI,
3712                                    const MachineOperand &Orig) {
3713 
3714   for (MachineOperand &Use : MI.implicit_operands()) {
3715     if (Use.isUse() &&
3716         (Use.getReg() == AMDGPU::VCC || Use.getReg() == AMDGPU::VCC_LO)) {
3717       Use.setIsUndef(Orig.isUndef());
3718       Use.setIsKill(Orig.isKill());
3719       return;
3720     }
3721   }
3722 }
3723 
3724 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
3725                                            unsigned Op32) const {
3726   MachineBasicBlock *MBB = MI.getParent();;
3727   MachineInstrBuilder Inst32 =
3728     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32))
3729     .setMIFlags(MI.getFlags());
3730 
3731   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
3732   // For VOPC instructions, this is replaced by an implicit def of vcc.
3733   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
3734   if (Op32DstIdx != -1) {
3735     // dst
3736     Inst32.add(MI.getOperand(0));
3737   } else {
3738     assert(((MI.getOperand(0).getReg() == AMDGPU::VCC) ||
3739             (MI.getOperand(0).getReg() == AMDGPU::VCC_LO)) &&
3740            "Unexpected case");
3741   }
3742 
3743   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
3744 
3745   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3746   if (Src1)
3747     Inst32.add(*Src1);
3748 
3749   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3750 
3751   if (Src2) {
3752     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
3753     if (Op32Src2Idx != -1) {
3754       Inst32.add(*Src2);
3755     } else {
3756       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
3757       // replaced with an implicit read of vcc or vcc_lo. The implicit read
3758       // of vcc was already added during the initial BuildMI, but we
3759       // 1) may need to change vcc to vcc_lo to preserve the original register
3760       // 2) have to preserve the original flags.
3761       fixImplicitOperands(*Inst32);
3762       copyFlagsToImplicitVCC(*Inst32, *Src2);
3763     }
3764   }
3765 
3766   return Inst32;
3767 }
3768 
3769 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
3770                                   const MachineOperand &MO,
3771                                   const MCOperandInfo &OpInfo) const {
3772   // Literal constants use the constant bus.
3773   //if (isLiteralConstantLike(MO, OpInfo))
3774   // return true;
3775   if (MO.isImm())
3776     return !isInlineConstant(MO, OpInfo);
3777 
3778   if (!MO.isReg())
3779     return true; // Misc other operands like FrameIndex
3780 
3781   if (!MO.isUse())
3782     return false;
3783 
3784   if (MO.getReg().isVirtual())
3785     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
3786 
3787   // Null is free
3788   if (MO.getReg() == AMDGPU::SGPR_NULL)
3789     return false;
3790 
3791   // SGPRs use the constant bus
3792   if (MO.isImplicit()) {
3793     return MO.getReg() == AMDGPU::M0 ||
3794            MO.getReg() == AMDGPU::VCC ||
3795            MO.getReg() == AMDGPU::VCC_LO;
3796   } else {
3797     return AMDGPU::SReg_32RegClass.contains(MO.getReg()) ||
3798            AMDGPU::SReg_64RegClass.contains(MO.getReg());
3799   }
3800 }
3801 
3802 static Register findImplicitSGPRRead(const MachineInstr &MI) {
3803   for (const MachineOperand &MO : MI.implicit_operands()) {
3804     // We only care about reads.
3805     if (MO.isDef())
3806       continue;
3807 
3808     switch (MO.getReg()) {
3809     case AMDGPU::VCC:
3810     case AMDGPU::VCC_LO:
3811     case AMDGPU::VCC_HI:
3812     case AMDGPU::M0:
3813     case AMDGPU::FLAT_SCR:
3814       return MO.getReg();
3815 
3816     default:
3817       break;
3818     }
3819   }
3820 
3821   return AMDGPU::NoRegister;
3822 }
3823 
3824 static bool shouldReadExec(const MachineInstr &MI) {
3825   if (SIInstrInfo::isVALU(MI)) {
3826     switch (MI.getOpcode()) {
3827     case AMDGPU::V_READLANE_B32:
3828     case AMDGPU::V_WRITELANE_B32:
3829       return false;
3830     }
3831 
3832     return true;
3833   }
3834 
3835   if (MI.isPreISelOpcode() ||
3836       SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
3837       SIInstrInfo::isSALU(MI) ||
3838       SIInstrInfo::isSMRD(MI))
3839     return false;
3840 
3841   return true;
3842 }
3843 
3844 static bool isSubRegOf(const SIRegisterInfo &TRI,
3845                        const MachineOperand &SuperVec,
3846                        const MachineOperand &SubReg) {
3847   if (SubReg.getReg().isPhysical())
3848     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
3849 
3850   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
3851          SubReg.getReg() == SuperVec.getReg();
3852 }
3853 
3854 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
3855                                     StringRef &ErrInfo) const {
3856   uint16_t Opcode = MI.getOpcode();
3857   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
3858     return true;
3859 
3860   const MachineFunction *MF = MI.getParent()->getParent();
3861   const MachineRegisterInfo &MRI = MF->getRegInfo();
3862 
3863   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
3864   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
3865   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
3866 
3867   // Make sure the number of operands is correct.
3868   const MCInstrDesc &Desc = get(Opcode);
3869   if (!Desc.isVariadic() &&
3870       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
3871     ErrInfo = "Instruction has wrong number of operands.";
3872     return false;
3873   }
3874 
3875   if (MI.isInlineAsm()) {
3876     // Verify register classes for inlineasm constraints.
3877     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
3878          I != E; ++I) {
3879       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
3880       if (!RC)
3881         continue;
3882 
3883       const MachineOperand &Op = MI.getOperand(I);
3884       if (!Op.isReg())
3885         continue;
3886 
3887       Register Reg = Op.getReg();
3888       if (!Reg.isVirtual() && !RC->contains(Reg)) {
3889         ErrInfo = "inlineasm operand has incorrect register class.";
3890         return false;
3891       }
3892     }
3893 
3894     return true;
3895   }
3896 
3897   if (isMIMG(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
3898     ErrInfo = "missing memory operand from MIMG instruction.";
3899     return false;
3900   }
3901 
3902   // Make sure the register classes are correct.
3903   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
3904     const MachineOperand &MO = MI.getOperand(i);
3905     if (MO.isFPImm()) {
3906       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
3907                 "all fp values to integers.";
3908       return false;
3909     }
3910 
3911     int RegClass = Desc.OpInfo[i].RegClass;
3912 
3913     switch (Desc.OpInfo[i].OperandType) {
3914     case MCOI::OPERAND_REGISTER:
3915       if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
3916         ErrInfo = "Illegal immediate value for operand.";
3917         return false;
3918       }
3919       break;
3920     case AMDGPU::OPERAND_REG_IMM_INT32:
3921     case AMDGPU::OPERAND_REG_IMM_FP32:
3922     case AMDGPU::OPERAND_REG_IMM_FP32_DEFERRED:
3923       break;
3924     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3925     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3926     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3927     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3928     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3929     case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3930     case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3931     case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
3932     case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3933     case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
3934     case AMDGPU::OPERAND_REG_INLINE_AC_FP64: {
3935       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
3936         ErrInfo = "Illegal immediate value for operand.";
3937         return false;
3938       }
3939       break;
3940     }
3941     case MCOI::OPERAND_IMMEDIATE:
3942     case AMDGPU::OPERAND_KIMM32:
3943       // Check if this operand is an immediate.
3944       // FrameIndex operands will be replaced by immediates, so they are
3945       // allowed.
3946       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
3947         ErrInfo = "Expected immediate, but got non-immediate";
3948         return false;
3949       }
3950       LLVM_FALLTHROUGH;
3951     default:
3952       continue;
3953     }
3954 
3955     if (!MO.isReg())
3956       continue;
3957     Register Reg = MO.getReg();
3958     if (!Reg)
3959       continue;
3960 
3961     // FIXME: Ideally we would have separate instruction definitions with the
3962     // aligned register constraint.
3963     // FIXME: We do not verify inline asm operands, but custom inline asm
3964     // verification is broken anyway
3965     if (ST.needsAlignedVGPRs()) {
3966       const TargetRegisterClass *RC = RI.getRegClassForReg(MRI, Reg);
3967       if (RI.hasVectorRegisters(RC) && MO.getSubReg()) {
3968         const TargetRegisterClass *SubRC =
3969             RI.getSubRegClass(RC, MO.getSubReg());
3970         RC = RI.getCompatibleSubRegClass(RC, SubRC, MO.getSubReg());
3971         if (RC)
3972           RC = SubRC;
3973       }
3974 
3975       // Check that this is the aligned version of the class.
3976       if (!RC || !RI.isProperlyAlignedRC(*RC)) {
3977         ErrInfo = "Subtarget requires even aligned vector registers";
3978         return false;
3979       }
3980     }
3981 
3982     if (RegClass != -1) {
3983       if (Reg.isVirtual())
3984         continue;
3985 
3986       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
3987       if (!RC->contains(Reg)) {
3988         ErrInfo = "Operand has incorrect register class.";
3989         return false;
3990       }
3991     }
3992   }
3993 
3994   // Verify SDWA
3995   if (isSDWA(MI)) {
3996     if (!ST.hasSDWA()) {
3997       ErrInfo = "SDWA is not supported on this target";
3998       return false;
3999     }
4000 
4001     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4002 
4003     const int OpIndicies[] = { DstIdx, Src0Idx, Src1Idx, Src2Idx };
4004 
4005     for (int OpIdx: OpIndicies) {
4006       if (OpIdx == -1)
4007         continue;
4008       const MachineOperand &MO = MI.getOperand(OpIdx);
4009 
4010       if (!ST.hasSDWAScalar()) {
4011         // Only VGPRS on VI
4012         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
4013           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
4014           return false;
4015         }
4016       } else {
4017         // No immediates on GFX9
4018         if (!MO.isReg()) {
4019           ErrInfo =
4020             "Only reg allowed as operands in SDWA instructions on GFX9+";
4021           return false;
4022         }
4023       }
4024     }
4025 
4026     if (!ST.hasSDWAOmod()) {
4027       // No omod allowed on VI
4028       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
4029       if (OMod != nullptr &&
4030         (!OMod->isImm() || OMod->getImm() != 0)) {
4031         ErrInfo = "OMod not allowed in SDWA instructions on VI";
4032         return false;
4033       }
4034     }
4035 
4036     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
4037     if (isVOPC(BasicOpcode)) {
4038       if (!ST.hasSDWASdst() && DstIdx != -1) {
4039         // Only vcc allowed as dst on VI for VOPC
4040         const MachineOperand &Dst = MI.getOperand(DstIdx);
4041         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
4042           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
4043           return false;
4044         }
4045       } else if (!ST.hasSDWAOutModsVOPC()) {
4046         // No clamp allowed on GFX9 for VOPC
4047         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
4048         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
4049           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
4050           return false;
4051         }
4052 
4053         // No omod allowed on GFX9 for VOPC
4054         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
4055         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
4056           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
4057           return false;
4058         }
4059       }
4060     }
4061 
4062     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
4063     if (DstUnused && DstUnused->isImm() &&
4064         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
4065       const MachineOperand &Dst = MI.getOperand(DstIdx);
4066       if (!Dst.isReg() || !Dst.isTied()) {
4067         ErrInfo = "Dst register should have tied register";
4068         return false;
4069       }
4070 
4071       const MachineOperand &TiedMO =
4072           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
4073       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
4074         ErrInfo =
4075             "Dst register should be tied to implicit use of preserved register";
4076         return false;
4077       } else if (TiedMO.getReg().isPhysical() &&
4078                  Dst.getReg() != TiedMO.getReg()) {
4079         ErrInfo = "Dst register should use same physical register as preserved";
4080         return false;
4081       }
4082     }
4083   }
4084 
4085   // Verify MIMG
4086   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
4087     // Ensure that the return type used is large enough for all the options
4088     // being used TFE/LWE require an extra result register.
4089     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
4090     if (DMask) {
4091       uint64_t DMaskImm = DMask->getImm();
4092       uint32_t RegCount =
4093           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
4094       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
4095       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
4096       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
4097 
4098       // Adjust for packed 16 bit values
4099       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
4100         RegCount >>= 1;
4101 
4102       // Adjust if using LWE or TFE
4103       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
4104         RegCount += 1;
4105 
4106       const uint32_t DstIdx =
4107           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
4108       const MachineOperand &Dst = MI.getOperand(DstIdx);
4109       if (Dst.isReg()) {
4110         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
4111         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
4112         if (RegCount > DstSize) {
4113           ErrInfo = "MIMG instruction returns too many registers for dst "
4114                     "register class";
4115           return false;
4116         }
4117       }
4118     }
4119   }
4120 
4121   // Verify VOP*. Ignore multiple sgpr operands on writelane.
4122   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
4123       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
4124     // Only look at the true operands. Only a real operand can use the constant
4125     // bus, and we don't want to check pseudo-operands like the source modifier
4126     // flags.
4127     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
4128 
4129     unsigned ConstantBusCount = 0;
4130     bool UsesLiteral = false;
4131     const MachineOperand *LiteralVal = nullptr;
4132 
4133     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
4134       ++ConstantBusCount;
4135 
4136     SmallVector<Register, 2> SGPRsUsed;
4137     Register SGPRUsed;
4138 
4139     for (int OpIdx : OpIndices) {
4140       if (OpIdx == -1)
4141         break;
4142       const MachineOperand &MO = MI.getOperand(OpIdx);
4143       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4144         if (MO.isReg()) {
4145           SGPRUsed = MO.getReg();
4146           if (llvm::all_of(SGPRsUsed, [SGPRUsed](unsigned SGPR) {
4147                 return SGPRUsed != SGPR;
4148               })) {
4149             ++ConstantBusCount;
4150             SGPRsUsed.push_back(SGPRUsed);
4151           }
4152         } else {
4153           if (!UsesLiteral) {
4154             ++ConstantBusCount;
4155             UsesLiteral = true;
4156             LiteralVal = &MO;
4157           } else if (!MO.isIdenticalTo(*LiteralVal)) {
4158             assert(isVOP3(MI));
4159             ErrInfo = "VOP3 instruction uses more than one literal";
4160             return false;
4161           }
4162         }
4163       }
4164     }
4165 
4166     SGPRUsed = findImplicitSGPRRead(MI);
4167     if (SGPRUsed != AMDGPU::NoRegister) {
4168       // Implicit uses may safely overlap true overands
4169       if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
4170             return !RI.regsOverlap(SGPRUsed, SGPR);
4171           })) {
4172         ++ConstantBusCount;
4173         SGPRsUsed.push_back(SGPRUsed);
4174       }
4175     }
4176 
4177     // v_writelane_b32 is an exception from constant bus restriction:
4178     // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
4179     if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
4180         Opcode != AMDGPU::V_WRITELANE_B32) {
4181       ErrInfo = "VOP* instruction violates constant bus restriction";
4182       return false;
4183     }
4184 
4185     if (isVOP3(MI) && UsesLiteral && !ST.hasVOP3Literal()) {
4186       ErrInfo = "VOP3 instruction uses literal";
4187       return false;
4188     }
4189   }
4190 
4191   // Special case for writelane - this can break the multiple constant bus rule,
4192   // but still can't use more than one SGPR register
4193   if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
4194     unsigned SGPRCount = 0;
4195     Register SGPRUsed = AMDGPU::NoRegister;
4196 
4197     for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx}) {
4198       if (OpIdx == -1)
4199         break;
4200 
4201       const MachineOperand &MO = MI.getOperand(OpIdx);
4202 
4203       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4204         if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
4205           if (MO.getReg() != SGPRUsed)
4206             ++SGPRCount;
4207           SGPRUsed = MO.getReg();
4208         }
4209       }
4210       if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
4211         ErrInfo = "WRITELANE instruction violates constant bus restriction";
4212         return false;
4213       }
4214     }
4215   }
4216 
4217   // Verify misc. restrictions on specific instructions.
4218   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
4219       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
4220     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4221     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4222     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
4223     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
4224       if (!compareMachineOp(Src0, Src1) &&
4225           !compareMachineOp(Src0, Src2)) {
4226         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
4227         return false;
4228       }
4229     }
4230     if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
4231          SISrcMods::ABS) ||
4232         (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
4233          SISrcMods::ABS) ||
4234         (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
4235          SISrcMods::ABS)) {
4236       ErrInfo = "ABS not allowed in VOP3B instructions";
4237       return false;
4238     }
4239   }
4240 
4241   if (isSOP2(MI) || isSOPC(MI)) {
4242     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4243     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4244     unsigned Immediates = 0;
4245 
4246     if (!Src0.isReg() &&
4247         !isInlineConstant(Src0, Desc.OpInfo[Src0Idx].OperandType))
4248       Immediates++;
4249     if (!Src1.isReg() &&
4250         !isInlineConstant(Src1, Desc.OpInfo[Src1Idx].OperandType))
4251       Immediates++;
4252 
4253     if (Immediates > 1) {
4254       ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
4255       return false;
4256     }
4257   }
4258 
4259   if (isSOPK(MI)) {
4260     auto Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
4261     if (Desc.isBranch()) {
4262       if (!Op->isMBB()) {
4263         ErrInfo = "invalid branch target for SOPK instruction";
4264         return false;
4265       }
4266     } else {
4267       uint64_t Imm = Op->getImm();
4268       if (sopkIsZext(MI)) {
4269         if (!isUInt<16>(Imm)) {
4270           ErrInfo = "invalid immediate for SOPK instruction";
4271           return false;
4272         }
4273       } else {
4274         if (!isInt<16>(Imm)) {
4275           ErrInfo = "invalid immediate for SOPK instruction";
4276           return false;
4277         }
4278       }
4279     }
4280   }
4281 
4282   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
4283       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
4284       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4285       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
4286     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4287                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
4288 
4289     const unsigned StaticNumOps = Desc.getNumOperands() +
4290       Desc.getNumImplicitUses();
4291     const unsigned NumImplicitOps = IsDst ? 2 : 1;
4292 
4293     // Allow additional implicit operands. This allows a fixup done by the post
4294     // RA scheduler where the main implicit operand is killed and implicit-defs
4295     // are added for sub-registers that remain live after this instruction.
4296     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
4297       ErrInfo = "missing implicit register operands";
4298       return false;
4299     }
4300 
4301     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4302     if (IsDst) {
4303       if (!Dst->isUse()) {
4304         ErrInfo = "v_movreld_b32 vdst should be a use operand";
4305         return false;
4306       }
4307 
4308       unsigned UseOpIdx;
4309       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
4310           UseOpIdx != StaticNumOps + 1) {
4311         ErrInfo = "movrel implicit operands should be tied";
4312         return false;
4313       }
4314     }
4315 
4316     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4317     const MachineOperand &ImpUse
4318       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
4319     if (!ImpUse.isReg() || !ImpUse.isUse() ||
4320         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
4321       ErrInfo = "src0 should be subreg of implicit vector use";
4322       return false;
4323     }
4324   }
4325 
4326   // Make sure we aren't losing exec uses in the td files. This mostly requires
4327   // being careful when using let Uses to try to add other use registers.
4328   if (shouldReadExec(MI)) {
4329     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
4330       ErrInfo = "VALU instruction does not implicitly read exec mask";
4331       return false;
4332     }
4333   }
4334 
4335   if (isSMRD(MI)) {
4336     if (MI.mayStore()) {
4337       // The register offset form of scalar stores may only use m0 as the
4338       // soffset register.
4339       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
4340       if (Soff && Soff->getReg() != AMDGPU::M0) {
4341         ErrInfo = "scalar stores must use m0 as offset register";
4342         return false;
4343       }
4344     }
4345   }
4346 
4347   if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
4348     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4349     if (Offset->getImm() != 0) {
4350       ErrInfo = "subtarget does not support offsets in flat instructions";
4351       return false;
4352     }
4353   }
4354 
4355   if (isMIMG(MI)) {
4356     const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
4357     if (DimOp) {
4358       int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
4359                                                  AMDGPU::OpName::vaddr0);
4360       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
4361       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
4362       const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4363           AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
4364       const AMDGPU::MIMGDimInfo *Dim =
4365           AMDGPU::getMIMGDimInfoByEncoding(DimOp->getImm());
4366 
4367       if (!Dim) {
4368         ErrInfo = "dim is out of range";
4369         return false;
4370       }
4371 
4372       bool IsA16 = false;
4373       if (ST.hasR128A16()) {
4374         const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
4375         IsA16 = R128A16->getImm() != 0;
4376       } else if (ST.hasGFX10A16()) {
4377         const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
4378         IsA16 = A16->getImm() != 0;
4379       }
4380 
4381       bool IsNSA = SRsrcIdx - VAddr0Idx > 1;
4382 
4383       unsigned AddrWords =
4384           AMDGPU::getAddrSizeMIMGOp(BaseOpcode, Dim, IsA16, ST.hasG16());
4385 
4386       unsigned VAddrWords;
4387       if (IsNSA) {
4388         VAddrWords = SRsrcIdx - VAddr0Idx;
4389       } else {
4390         const TargetRegisterClass *RC = getOpRegClass(MI, VAddr0Idx);
4391         VAddrWords = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 32;
4392         if (AddrWords > 8)
4393           AddrWords = 16;
4394       }
4395 
4396       if (VAddrWords != AddrWords) {
4397         LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
4398                           << " but got " << VAddrWords << "\n");
4399         ErrInfo = "bad vaddr size";
4400         return false;
4401       }
4402     }
4403   }
4404 
4405   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
4406   if (DppCt) {
4407     using namespace AMDGPU::DPP;
4408 
4409     unsigned DC = DppCt->getImm();
4410     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
4411         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
4412         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
4413         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
4414         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
4415         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
4416         (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
4417       ErrInfo = "Invalid dpp_ctrl value";
4418       return false;
4419     }
4420     if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
4421         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4422       ErrInfo = "Invalid dpp_ctrl value: "
4423                 "wavefront shifts are not supported on GFX10+";
4424       return false;
4425     }
4426     if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
4427         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4428       ErrInfo = "Invalid dpp_ctrl value: "
4429                 "broadcasts are not supported on GFX10+";
4430       return false;
4431     }
4432     if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
4433         ST.getGeneration() < AMDGPUSubtarget::GFX10) {
4434       if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
4435           DC <= DppCtrl::ROW_NEWBCAST_LAST &&
4436           !ST.hasGFX90AInsts()) {
4437         ErrInfo = "Invalid dpp_ctrl value: "
4438                   "row_newbroadcast/row_share is not supported before "
4439                   "GFX90A/GFX10";
4440         return false;
4441       } else if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
4442         ErrInfo = "Invalid dpp_ctrl value: "
4443                   "row_share and row_xmask are not supported before GFX10";
4444         return false;
4445       }
4446     }
4447 
4448     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4449     int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
4450 
4451     if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
4452         ((DstIdx >= 0 &&
4453           (Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64RegClassID ||
4454            Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64_Align2RegClassID)) ||
4455          ((Src0Idx >= 0 &&
4456            (Desc.OpInfo[Src0Idx].RegClass == AMDGPU::VReg_64RegClassID ||
4457             Desc.OpInfo[Src0Idx].RegClass ==
4458                 AMDGPU::VReg_64_Align2RegClassID)))) &&
4459         !AMDGPU::isLegal64BitDPPControl(DC)) {
4460       ErrInfo = "Invalid dpp_ctrl value: "
4461                 "64 bit dpp only support row_newbcast";
4462       return false;
4463     }
4464   }
4465 
4466   if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
4467     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4468     uint16_t DataNameIdx = isDS(Opcode) ? AMDGPU::OpName::data0
4469                                         : AMDGPU::OpName::vdata;
4470     const MachineOperand *Data = getNamedOperand(MI, DataNameIdx);
4471     const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
4472     if (Data && !Data->isReg())
4473       Data = nullptr;
4474 
4475     if (ST.hasGFX90AInsts()) {
4476       if (Dst && Data &&
4477           (RI.isAGPR(MRI, Dst->getReg()) != RI.isAGPR(MRI, Data->getReg()))) {
4478         ErrInfo = "Invalid register class: "
4479                   "vdata and vdst should be both VGPR or AGPR";
4480         return false;
4481       }
4482       if (Data && Data2 &&
4483           (RI.isAGPR(MRI, Data->getReg()) != RI.isAGPR(MRI, Data2->getReg()))) {
4484         ErrInfo = "Invalid register class: "
4485                   "both data operands should be VGPR or AGPR";
4486         return false;
4487       }
4488     } else {
4489       if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
4490           (Data && RI.isAGPR(MRI, Data->getReg())) ||
4491           (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
4492         ErrInfo = "Invalid register class: "
4493                   "agpr loads and stores not supported on this GPU";
4494         return false;
4495       }
4496     }
4497   }
4498 
4499   if (ST.needsAlignedVGPRs() &&
4500       (MI.getOpcode() == AMDGPU::DS_GWS_INIT ||
4501        MI.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
4502        MI.getOpcode() == AMDGPU::DS_GWS_BARRIER)) {
4503     const MachineOperand *Op = getNamedOperand(MI, AMDGPU::OpName::data0);
4504     Register Reg = Op->getReg();
4505     bool Aligned = true;
4506     if (Reg.isPhysical()) {
4507       Aligned = !(RI.getHWRegIndex(Reg) & 1);
4508     } else {
4509       const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
4510       Aligned = RI.getRegSizeInBits(RC) > 32 && RI.isProperlyAlignedRC(RC) &&
4511                 !(RI.getChannelFromSubReg(Op->getSubReg()) & 1);
4512     }
4513 
4514     if (!Aligned) {
4515       ErrInfo = "Subtarget requires even aligned vector registers "
4516                 "for DS_GWS instructions";
4517       return false;
4518     }
4519   }
4520 
4521   return true;
4522 }
4523 
4524 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
4525   switch (MI.getOpcode()) {
4526   default: return AMDGPU::INSTRUCTION_LIST_END;
4527   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
4528   case AMDGPU::COPY: return AMDGPU::COPY;
4529   case AMDGPU::PHI: return AMDGPU::PHI;
4530   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
4531   case AMDGPU::WQM: return AMDGPU::WQM;
4532   case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
4533   case AMDGPU::STRICT_WWM: return AMDGPU::STRICT_WWM;
4534   case AMDGPU::STRICT_WQM: return AMDGPU::STRICT_WQM;
4535   case AMDGPU::S_MOV_B32: {
4536     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4537     return MI.getOperand(1).isReg() ||
4538            RI.isAGPR(MRI, MI.getOperand(0).getReg()) ?
4539            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
4540   }
4541   case AMDGPU::S_ADD_I32:
4542     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
4543   case AMDGPU::S_ADDC_U32:
4544     return AMDGPU::V_ADDC_U32_e32;
4545   case AMDGPU::S_SUB_I32:
4546     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
4547     // FIXME: These are not consistently handled, and selected when the carry is
4548     // used.
4549   case AMDGPU::S_ADD_U32:
4550     return AMDGPU::V_ADD_CO_U32_e32;
4551   case AMDGPU::S_SUB_U32:
4552     return AMDGPU::V_SUB_CO_U32_e32;
4553   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
4554   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
4555   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
4556   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
4557   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
4558   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
4559   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
4560   case AMDGPU::S_XNOR_B32:
4561     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
4562   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
4563   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
4564   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
4565   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
4566   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
4567   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
4568   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
4569   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
4570   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
4571   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
4572   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
4573   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
4574   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
4575   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
4576   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
4577   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
4578   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
4579   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
4580   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e64;
4581   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e64;
4582   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e64;
4583   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e64;
4584   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e64;
4585   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e64;
4586   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e64;
4587   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e64;
4588   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e64;
4589   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e64;
4590   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e64;
4591   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e64;
4592   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e64;
4593   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e64;
4594   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
4595   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
4596   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
4597   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
4598   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
4599   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
4600   }
4601   llvm_unreachable(
4602       "Unexpected scalar opcode without corresponding vector one!");
4603 }
4604 
4605 static unsigned adjustAllocatableRegClass(const GCNSubtarget &ST,
4606                                           const MachineRegisterInfo &MRI,
4607                                           const MCInstrDesc &TID,
4608                                           unsigned RCID,
4609                                           bool IsAllocatable) {
4610   if ((IsAllocatable || !ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4611       (((TID.mayLoad() || TID.mayStore()) &&
4612         !(TID.TSFlags & SIInstrFlags::VGPRSpill)) ||
4613        (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::MIMG)))) {
4614     switch (RCID) {
4615     case AMDGPU::AV_32RegClassID: return AMDGPU::VGPR_32RegClassID;
4616     case AMDGPU::AV_64RegClassID: return AMDGPU::VReg_64RegClassID;
4617     case AMDGPU::AV_96RegClassID: return AMDGPU::VReg_96RegClassID;
4618     case AMDGPU::AV_128RegClassID: return AMDGPU::VReg_128RegClassID;
4619     case AMDGPU::AV_160RegClassID: return AMDGPU::VReg_160RegClassID;
4620     default:
4621       break;
4622     }
4623   }
4624   return RCID;
4625 }
4626 
4627 const TargetRegisterClass *SIInstrInfo::getRegClass(const MCInstrDesc &TID,
4628     unsigned OpNum, const TargetRegisterInfo *TRI,
4629     const MachineFunction &MF)
4630   const {
4631   if (OpNum >= TID.getNumOperands())
4632     return nullptr;
4633   auto RegClass = TID.OpInfo[OpNum].RegClass;
4634   bool IsAllocatable = false;
4635   if (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::FLAT)) {
4636     // vdst and vdata should be both VGPR or AGPR, same for the DS instructions
4637     // with two data operands. Request register class constainted to VGPR only
4638     // of both operands present as Machine Copy Propagation can not check this
4639     // constraint and possibly other passes too.
4640     //
4641     // The check is limited to FLAT and DS because atomics in non-flat encoding
4642     // have their vdst and vdata tied to be the same register.
4643     const int VDstIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4644                                                    AMDGPU::OpName::vdst);
4645     const int DataIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4646         (TID.TSFlags & SIInstrFlags::DS) ? AMDGPU::OpName::data0
4647                                          : AMDGPU::OpName::vdata);
4648     if (DataIdx != -1) {
4649       IsAllocatable = VDstIdx != -1 ||
4650                       AMDGPU::getNamedOperandIdx(TID.Opcode,
4651                                                  AMDGPU::OpName::data1) != -1;
4652     }
4653   }
4654   RegClass = adjustAllocatableRegClass(ST, MF.getRegInfo(), TID, RegClass,
4655                                        IsAllocatable);
4656   return RI.getRegClass(RegClass);
4657 }
4658 
4659 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
4660                                                       unsigned OpNo) const {
4661   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4662   const MCInstrDesc &Desc = get(MI.getOpcode());
4663   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
4664       Desc.OpInfo[OpNo].RegClass == -1) {
4665     Register Reg = MI.getOperand(OpNo).getReg();
4666 
4667     if (Reg.isVirtual())
4668       return MRI.getRegClass(Reg);
4669     return RI.getPhysRegClass(Reg);
4670   }
4671 
4672   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
4673   RCID = adjustAllocatableRegClass(ST, MRI, Desc, RCID, true);
4674   return RI.getRegClass(RCID);
4675 }
4676 
4677 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
4678   MachineBasicBlock::iterator I = MI;
4679   MachineBasicBlock *MBB = MI.getParent();
4680   MachineOperand &MO = MI.getOperand(OpIdx);
4681   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4682   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
4683   const TargetRegisterClass *RC = RI.getRegClass(RCID);
4684   unsigned Size = RI.getRegSizeInBits(*RC);
4685   unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO : AMDGPU::V_MOV_B32_e32;
4686   if (MO.isReg())
4687     Opcode = AMDGPU::COPY;
4688   else if (RI.isSGPRClass(RC))
4689     Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
4690 
4691   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
4692   const TargetRegisterClass *VRC64 = RI.getVGPR64Class();
4693   if (RI.getCommonSubClass(VRC64, VRC))
4694     VRC = VRC64;
4695   else
4696     VRC = &AMDGPU::VGPR_32RegClass;
4697 
4698   Register Reg = MRI.createVirtualRegister(VRC);
4699   DebugLoc DL = MBB->findDebugLoc(I);
4700   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
4701   MO.ChangeToRegister(Reg, false);
4702 }
4703 
4704 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
4705                                          MachineRegisterInfo &MRI,
4706                                          MachineOperand &SuperReg,
4707                                          const TargetRegisterClass *SuperRC,
4708                                          unsigned SubIdx,
4709                                          const TargetRegisterClass *SubRC)
4710                                          const {
4711   MachineBasicBlock *MBB = MI->getParent();
4712   DebugLoc DL = MI->getDebugLoc();
4713   Register SubReg = MRI.createVirtualRegister(SubRC);
4714 
4715   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
4716     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4717       .addReg(SuperReg.getReg(), 0, SubIdx);
4718     return SubReg;
4719   }
4720 
4721   // Just in case the super register is itself a sub-register, copy it to a new
4722   // value so we don't need to worry about merging its subreg index with the
4723   // SubIdx passed to this function. The register coalescer should be able to
4724   // eliminate this extra copy.
4725   Register NewSuperReg = MRI.createVirtualRegister(SuperRC);
4726 
4727   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
4728     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
4729 
4730   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4731     .addReg(NewSuperReg, 0, SubIdx);
4732 
4733   return SubReg;
4734 }
4735 
4736 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
4737   MachineBasicBlock::iterator MII,
4738   MachineRegisterInfo &MRI,
4739   MachineOperand &Op,
4740   const TargetRegisterClass *SuperRC,
4741   unsigned SubIdx,
4742   const TargetRegisterClass *SubRC) const {
4743   if (Op.isImm()) {
4744     if (SubIdx == AMDGPU::sub0)
4745       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
4746     if (SubIdx == AMDGPU::sub1)
4747       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
4748 
4749     llvm_unreachable("Unhandled register index for immediate");
4750   }
4751 
4752   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
4753                                        SubIdx, SubRC);
4754   return MachineOperand::CreateReg(SubReg, false);
4755 }
4756 
4757 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
4758 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
4759   assert(Inst.getNumExplicitOperands() == 3);
4760   MachineOperand Op1 = Inst.getOperand(1);
4761   Inst.RemoveOperand(1);
4762   Inst.addOperand(Op1);
4763 }
4764 
4765 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
4766                                     const MCOperandInfo &OpInfo,
4767                                     const MachineOperand &MO) const {
4768   if (!MO.isReg())
4769     return false;
4770 
4771   Register Reg = MO.getReg();
4772 
4773   const TargetRegisterClass *DRC = RI.getRegClass(OpInfo.RegClass);
4774   if (Reg.isPhysical())
4775     return DRC->contains(Reg);
4776 
4777   const TargetRegisterClass *RC = MRI.getRegClass(Reg);
4778 
4779   if (MO.getSubReg()) {
4780     const MachineFunction *MF = MO.getParent()->getParent()->getParent();
4781     const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
4782     if (!SuperRC)
4783       return false;
4784 
4785     DRC = RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg());
4786     if (!DRC)
4787       return false;
4788   }
4789   return RC->hasSuperClassEq(DRC);
4790 }
4791 
4792 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
4793                                      const MCOperandInfo &OpInfo,
4794                                      const MachineOperand &MO) const {
4795   if (MO.isReg())
4796     return isLegalRegOperand(MRI, OpInfo, MO);
4797 
4798   // Handle non-register types that are treated like immediates.
4799   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
4800   return true;
4801 }
4802 
4803 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
4804                                  const MachineOperand *MO) const {
4805   const MachineFunction &MF = *MI.getParent()->getParent();
4806   const MachineRegisterInfo &MRI = MF.getRegInfo();
4807   const MCInstrDesc &InstDesc = MI.getDesc();
4808   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
4809   const TargetRegisterClass *DefinedRC =
4810       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
4811   if (!MO)
4812     MO = &MI.getOperand(OpIdx);
4813 
4814   int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
4815   int VOP3LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4816   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
4817     if (isVOP3(MI) && isLiteralConstantLike(*MO, OpInfo) && !VOP3LiteralLimit--)
4818       return false;
4819 
4820     SmallDenseSet<RegSubRegPair> SGPRsUsed;
4821     if (MO->isReg())
4822       SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
4823 
4824     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4825       if (i == OpIdx)
4826         continue;
4827       const MachineOperand &Op = MI.getOperand(i);
4828       if (Op.isReg()) {
4829         RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
4830         if (!SGPRsUsed.count(SGPR) &&
4831             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
4832           if (--ConstantBusLimit <= 0)
4833             return false;
4834           SGPRsUsed.insert(SGPR);
4835         }
4836       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
4837         if (--ConstantBusLimit <= 0)
4838           return false;
4839       } else if (isVOP3(MI) && AMDGPU::isSISrcOperand(InstDesc, i) &&
4840                  isLiteralConstantLike(Op, InstDesc.OpInfo[i])) {
4841         if (!VOP3LiteralLimit--)
4842           return false;
4843         if (--ConstantBusLimit <= 0)
4844           return false;
4845       }
4846     }
4847   }
4848 
4849   if (MO->isReg()) {
4850     assert(DefinedRC);
4851     if (!isLegalRegOperand(MRI, OpInfo, *MO))
4852       return false;
4853     bool IsAGPR = RI.isAGPR(MRI, MO->getReg());
4854     if (IsAGPR && !ST.hasMAIInsts())
4855       return false;
4856     unsigned Opc = MI.getOpcode();
4857     if (IsAGPR &&
4858         (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4859         (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
4860       return false;
4861     // Atomics should have both vdst and vdata either vgpr or agpr.
4862     const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
4863     const int DataIdx = AMDGPU::getNamedOperandIdx(Opc,
4864         isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
4865     if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
4866         MI.getOperand(DataIdx).isReg() &&
4867         RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
4868       return false;
4869     if ((int)OpIdx == DataIdx) {
4870       if (VDstIdx != -1 &&
4871           RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
4872         return false;
4873       // DS instructions with 2 src operands also must have tied RC.
4874       const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc,
4875                                                       AMDGPU::OpName::data1);
4876       if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
4877           RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
4878         return false;
4879     }
4880     if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 &&
4881         (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
4882         RI.isSGPRReg(MRI, MO->getReg()))
4883       return false;
4884     return true;
4885   }
4886 
4887   // Handle non-register types that are treated like immediates.
4888   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
4889 
4890   if (!DefinedRC) {
4891     // This operand expects an immediate.
4892     return true;
4893   }
4894 
4895   return isImmOperandLegal(MI, OpIdx, *MO);
4896 }
4897 
4898 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
4899                                        MachineInstr &MI) const {
4900   unsigned Opc = MI.getOpcode();
4901   const MCInstrDesc &InstrDesc = get(Opc);
4902 
4903   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4904   MachineOperand &Src0 = MI.getOperand(Src0Idx);
4905 
4906   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4907   MachineOperand &Src1 = MI.getOperand(Src1Idx);
4908 
4909   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
4910   // we need to only have one constant bus use before GFX10.
4911   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
4912   if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 &&
4913       Src0.isReg() && (RI.isSGPRReg(MRI, Src0.getReg()) ||
4914        isLiteralConstantLike(Src0, InstrDesc.OpInfo[Src0Idx])))
4915     legalizeOpWithMove(MI, Src0Idx);
4916 
4917   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
4918   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
4919   // src0/src1 with V_READFIRSTLANE.
4920   if (Opc == AMDGPU::V_WRITELANE_B32) {
4921     const DebugLoc &DL = MI.getDebugLoc();
4922     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
4923       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4924       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4925           .add(Src0);
4926       Src0.ChangeToRegister(Reg, false);
4927     }
4928     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
4929       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4930       const DebugLoc &DL = MI.getDebugLoc();
4931       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4932           .add(Src1);
4933       Src1.ChangeToRegister(Reg, false);
4934     }
4935     return;
4936   }
4937 
4938   // No VOP2 instructions support AGPRs.
4939   if (Src0.isReg() && RI.isAGPR(MRI, Src0.getReg()))
4940     legalizeOpWithMove(MI, Src0Idx);
4941 
4942   if (Src1.isReg() && RI.isAGPR(MRI, Src1.getReg()))
4943     legalizeOpWithMove(MI, Src1Idx);
4944 
4945   // VOP2 src0 instructions support all operand types, so we don't need to check
4946   // their legality. If src1 is already legal, we don't need to do anything.
4947   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
4948     return;
4949 
4950   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
4951   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
4952   // select is uniform.
4953   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
4954       RI.isVGPR(MRI, Src1.getReg())) {
4955     Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4956     const DebugLoc &DL = MI.getDebugLoc();
4957     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4958         .add(Src1);
4959     Src1.ChangeToRegister(Reg, false);
4960     return;
4961   }
4962 
4963   // We do not use commuteInstruction here because it is too aggressive and will
4964   // commute if it is possible. We only want to commute here if it improves
4965   // legality. This can be called a fairly large number of times so don't waste
4966   // compile time pointlessly swapping and checking legality again.
4967   if (HasImplicitSGPR || !MI.isCommutable()) {
4968     legalizeOpWithMove(MI, Src1Idx);
4969     return;
4970   }
4971 
4972   // If src0 can be used as src1, commuting will make the operands legal.
4973   // Otherwise we have to give up and insert a move.
4974   //
4975   // TODO: Other immediate-like operand kinds could be commuted if there was a
4976   // MachineOperand::ChangeTo* for them.
4977   if ((!Src1.isImm() && !Src1.isReg()) ||
4978       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
4979     legalizeOpWithMove(MI, Src1Idx);
4980     return;
4981   }
4982 
4983   int CommutedOpc = commuteOpcode(MI);
4984   if (CommutedOpc == -1) {
4985     legalizeOpWithMove(MI, Src1Idx);
4986     return;
4987   }
4988 
4989   MI.setDesc(get(CommutedOpc));
4990 
4991   Register Src0Reg = Src0.getReg();
4992   unsigned Src0SubReg = Src0.getSubReg();
4993   bool Src0Kill = Src0.isKill();
4994 
4995   if (Src1.isImm())
4996     Src0.ChangeToImmediate(Src1.getImm());
4997   else if (Src1.isReg()) {
4998     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
4999     Src0.setSubReg(Src1.getSubReg());
5000   } else
5001     llvm_unreachable("Should only have register or immediate operands");
5002 
5003   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
5004   Src1.setSubReg(Src0SubReg);
5005   fixImplicitOperands(MI);
5006 }
5007 
5008 // Legalize VOP3 operands. All operand types are supported for any operand
5009 // but only one literal constant and only starting from GFX10.
5010 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
5011                                        MachineInstr &MI) const {
5012   unsigned Opc = MI.getOpcode();
5013 
5014   int VOP3Idx[3] = {
5015     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
5016     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
5017     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
5018   };
5019 
5020   if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
5021       Opc == AMDGPU::V_PERMLANEX16_B32_e64) {
5022     // src1 and src2 must be scalar
5023     MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
5024     MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
5025     const DebugLoc &DL = MI.getDebugLoc();
5026     if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
5027       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5028       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5029         .add(Src1);
5030       Src1.ChangeToRegister(Reg, false);
5031     }
5032     if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
5033       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5034       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5035         .add(Src2);
5036       Src2.ChangeToRegister(Reg, false);
5037     }
5038   }
5039 
5040   // Find the one SGPR operand we are allowed to use.
5041   int ConstantBusLimit = ST.getConstantBusLimit(Opc);
5042   int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
5043   SmallDenseSet<unsigned> SGPRsUsed;
5044   Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
5045   if (SGPRReg != AMDGPU::NoRegister) {
5046     SGPRsUsed.insert(SGPRReg);
5047     --ConstantBusLimit;
5048   }
5049 
5050   for (unsigned i = 0; i < 3; ++i) {
5051     int Idx = VOP3Idx[i];
5052     if (Idx == -1)
5053       break;
5054     MachineOperand &MO = MI.getOperand(Idx);
5055 
5056     if (!MO.isReg()) {
5057       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
5058         continue;
5059 
5060       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
5061         --LiteralLimit;
5062         --ConstantBusLimit;
5063         continue;
5064       }
5065 
5066       --LiteralLimit;
5067       --ConstantBusLimit;
5068       legalizeOpWithMove(MI, Idx);
5069       continue;
5070     }
5071 
5072     if (RI.hasAGPRs(RI.getRegClassForReg(MRI, MO.getReg())) &&
5073         !isOperandLegal(MI, Idx, &MO)) {
5074       legalizeOpWithMove(MI, Idx);
5075       continue;
5076     }
5077 
5078     if (!RI.isSGPRClass(RI.getRegClassForReg(MRI, MO.getReg())))
5079       continue; // VGPRs are legal
5080 
5081     // We can use one SGPR in each VOP3 instruction prior to GFX10
5082     // and two starting from GFX10.
5083     if (SGPRsUsed.count(MO.getReg()))
5084       continue;
5085     if (ConstantBusLimit > 0) {
5086       SGPRsUsed.insert(MO.getReg());
5087       --ConstantBusLimit;
5088       continue;
5089     }
5090 
5091     // If we make it this far, then the operand is not legal and we must
5092     // legalize it.
5093     legalizeOpWithMove(MI, Idx);
5094   }
5095 }
5096 
5097 Register SIInstrInfo::readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI,
5098                                          MachineRegisterInfo &MRI) const {
5099   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
5100   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
5101   Register DstReg = MRI.createVirtualRegister(SRC);
5102   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
5103 
5104   if (RI.hasAGPRs(VRC)) {
5105     VRC = RI.getEquivalentVGPRClass(VRC);
5106     Register NewSrcReg = MRI.createVirtualRegister(VRC);
5107     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5108             get(TargetOpcode::COPY), NewSrcReg)
5109         .addReg(SrcReg);
5110     SrcReg = NewSrcReg;
5111   }
5112 
5113   if (SubRegs == 1) {
5114     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5115             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
5116         .addReg(SrcReg);
5117     return DstReg;
5118   }
5119 
5120   SmallVector<unsigned, 8> SRegs;
5121   for (unsigned i = 0; i < SubRegs; ++i) {
5122     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5123     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5124             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
5125         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
5126     SRegs.push_back(SGPR);
5127   }
5128 
5129   MachineInstrBuilder MIB =
5130       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5131               get(AMDGPU::REG_SEQUENCE), DstReg);
5132   for (unsigned i = 0; i < SubRegs; ++i) {
5133     MIB.addReg(SRegs[i]);
5134     MIB.addImm(RI.getSubRegFromChannel(i));
5135   }
5136   return DstReg;
5137 }
5138 
5139 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
5140                                        MachineInstr &MI) const {
5141 
5142   // If the pointer is store in VGPRs, then we need to move them to
5143   // SGPRs using v_readfirstlane.  This is safe because we only select
5144   // loads with uniform pointers to SMRD instruction so we know the
5145   // pointer value is uniform.
5146   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
5147   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
5148     Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
5149     SBase->setReg(SGPR);
5150   }
5151   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
5152   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
5153     Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
5154     SOff->setReg(SGPR);
5155   }
5156 }
5157 
5158 bool SIInstrInfo::moveFlatAddrToVGPR(MachineInstr &Inst) const {
5159   unsigned Opc = Inst.getOpcode();
5160   int OldSAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
5161   if (OldSAddrIdx < 0)
5162     return false;
5163 
5164   assert(isSegmentSpecificFLAT(Inst));
5165 
5166   int NewOpc = AMDGPU::getGlobalVaddrOp(Opc);
5167   if (NewOpc < 0)
5168     NewOpc = AMDGPU::getFlatScratchInstSVfromSS(Opc);
5169   if (NewOpc < 0)
5170     return false;
5171 
5172   MachineRegisterInfo &MRI = Inst.getMF()->getRegInfo();
5173   MachineOperand &SAddr = Inst.getOperand(OldSAddrIdx);
5174   if (RI.isSGPRReg(MRI, SAddr.getReg()))
5175     return false;
5176 
5177   int NewVAddrIdx = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vaddr);
5178   if (NewVAddrIdx < 0)
5179     return false;
5180 
5181   int OldVAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
5182 
5183   // Check vaddr, it shall be zero or absent.
5184   MachineInstr *VAddrDef = nullptr;
5185   if (OldVAddrIdx >= 0) {
5186     MachineOperand &VAddr = Inst.getOperand(OldVAddrIdx);
5187     VAddrDef = MRI.getUniqueVRegDef(VAddr.getReg());
5188     if (!VAddrDef || VAddrDef->getOpcode() != AMDGPU::V_MOV_B32_e32 ||
5189         !VAddrDef->getOperand(1).isImm() ||
5190         VAddrDef->getOperand(1).getImm() != 0)
5191       return false;
5192   }
5193 
5194   const MCInstrDesc &NewDesc = get(NewOpc);
5195   Inst.setDesc(NewDesc);
5196 
5197   // Callers expect interator to be valid after this call, so modify the
5198   // instruction in place.
5199   if (OldVAddrIdx == NewVAddrIdx) {
5200     MachineOperand &NewVAddr = Inst.getOperand(NewVAddrIdx);
5201     // Clear use list from the old vaddr holding a zero register.
5202     MRI.removeRegOperandFromUseList(&NewVAddr);
5203     MRI.moveOperands(&NewVAddr, &SAddr, 1);
5204     Inst.RemoveOperand(OldSAddrIdx);
5205     // Update the use list with the pointer we have just moved from vaddr to
5206     // saddr poisition. Otherwise new vaddr will be missing from the use list.
5207     MRI.removeRegOperandFromUseList(&NewVAddr);
5208     MRI.addRegOperandToUseList(&NewVAddr);
5209   } else {
5210     assert(OldSAddrIdx == NewVAddrIdx);
5211 
5212     if (OldVAddrIdx >= 0) {
5213       int NewVDstIn = AMDGPU::getNamedOperandIdx(NewOpc,
5214                                                  AMDGPU::OpName::vdst_in);
5215 
5216       // RemoveOperand doesn't try to fixup tied operand indexes at it goes, so
5217       // it asserts. Untie the operands for now and retie them afterwards.
5218       if (NewVDstIn != -1) {
5219         int OldVDstIn = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
5220         Inst.untieRegOperand(OldVDstIn);
5221       }
5222 
5223       Inst.RemoveOperand(OldVAddrIdx);
5224 
5225       if (NewVDstIn != -1) {
5226         int NewVDst = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vdst);
5227         Inst.tieOperands(NewVDst, NewVDstIn);
5228       }
5229     }
5230   }
5231 
5232   if (VAddrDef && MRI.use_nodbg_empty(VAddrDef->getOperand(0).getReg()))
5233     VAddrDef->eraseFromParent();
5234 
5235   return true;
5236 }
5237 
5238 // FIXME: Remove this when SelectionDAG is obsoleted.
5239 void SIInstrInfo::legalizeOperandsFLAT(MachineRegisterInfo &MRI,
5240                                        MachineInstr &MI) const {
5241   if (!isSegmentSpecificFLAT(MI))
5242     return;
5243 
5244   // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
5245   // thinks they are uniform, so a readfirstlane should be valid.
5246   MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
5247   if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
5248     return;
5249 
5250   if (moveFlatAddrToVGPR(MI))
5251     return;
5252 
5253   Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI);
5254   SAddr->setReg(ToSGPR);
5255 }
5256 
5257 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
5258                                          MachineBasicBlock::iterator I,
5259                                          const TargetRegisterClass *DstRC,
5260                                          MachineOperand &Op,
5261                                          MachineRegisterInfo &MRI,
5262                                          const DebugLoc &DL) const {
5263   Register OpReg = Op.getReg();
5264   unsigned OpSubReg = Op.getSubReg();
5265 
5266   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
5267       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
5268 
5269   // Check if operand is already the correct register class.
5270   if (DstRC == OpRC)
5271     return;
5272 
5273   Register DstReg = MRI.createVirtualRegister(DstRC);
5274   auto Copy = BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
5275 
5276   Op.setReg(DstReg);
5277   Op.setSubReg(0);
5278 
5279   MachineInstr *Def = MRI.getVRegDef(OpReg);
5280   if (!Def)
5281     return;
5282 
5283   // Try to eliminate the copy if it is copying an immediate value.
5284   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
5285     FoldImmediate(*Copy, *Def, OpReg, &MRI);
5286 
5287   bool ImpDef = Def->isImplicitDef();
5288   while (!ImpDef && Def && Def->isCopy()) {
5289     if (Def->getOperand(1).getReg().isPhysical())
5290       break;
5291     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
5292     ImpDef = Def && Def->isImplicitDef();
5293   }
5294   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
5295       !ImpDef)
5296     Copy.addReg(AMDGPU::EXEC, RegState::Implicit);
5297 }
5298 
5299 // Emit the actual waterfall loop, executing the wrapped instruction for each
5300 // unique value of \p Rsrc across all lanes. In the best case we execute 1
5301 // iteration, in the worst case we execute 64 (once per lane).
5302 static void
5303 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
5304                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5305                           const DebugLoc &DL, MachineOperand &Rsrc) {
5306   MachineFunction &MF = *OrigBB.getParent();
5307   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5308   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5309   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5310   unsigned SaveExecOpc =
5311       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
5312   unsigned XorTermOpc =
5313       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
5314   unsigned AndOpc =
5315       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
5316   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5317 
5318   MachineBasicBlock::iterator I = LoopBB.begin();
5319 
5320   SmallVector<Register, 8> ReadlanePieces;
5321   Register CondReg = AMDGPU::NoRegister;
5322 
5323   Register VRsrc = Rsrc.getReg();
5324   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
5325 
5326   unsigned RegSize = TRI->getRegSizeInBits(Rsrc.getReg(), MRI);
5327   unsigned NumSubRegs =  RegSize / 32;
5328   assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 && "Unhandled register size");
5329 
5330   for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
5331 
5332     Register CurRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5333     Register CurRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5334 
5335     // Read the next variant <- also loop target.
5336     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
5337             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx));
5338 
5339     // Read the next variant <- also loop target.
5340     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
5341             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx + 1));
5342 
5343     ReadlanePieces.push_back(CurRegLo);
5344     ReadlanePieces.push_back(CurRegHi);
5345 
5346     // Comparison is to be done as 64-bit.
5347     Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
5348     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
5349             .addReg(CurRegLo)
5350             .addImm(AMDGPU::sub0)
5351             .addReg(CurRegHi)
5352             .addImm(AMDGPU::sub1);
5353 
5354     Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
5355     auto Cmp =
5356         BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
5357             .addReg(CurReg);
5358     if (NumSubRegs <= 2)
5359       Cmp.addReg(VRsrc);
5360     else
5361       Cmp.addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx, 2));
5362 
5363     // Combine the comparision results with AND.
5364     if (CondReg == AMDGPU::NoRegister) // First.
5365       CondReg = NewCondReg;
5366     else { // If not the first, we create an AND.
5367       Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
5368       BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndReg)
5369               .addReg(CondReg)
5370               .addReg(NewCondReg);
5371       CondReg = AndReg;
5372     }
5373   } // End for loop.
5374 
5375   auto SRsrcRC = TRI->getEquivalentSGPRClass(MRI.getRegClass(VRsrc));
5376   Register SRsrc = MRI.createVirtualRegister(SRsrcRC);
5377 
5378   // Build scalar Rsrc.
5379   auto Merge = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc);
5380   unsigned Channel = 0;
5381   for (Register Piece : ReadlanePieces) {
5382     Merge.addReg(Piece)
5383          .addImm(TRI->getSubRegFromChannel(Channel++));
5384   }
5385 
5386   // Update Rsrc operand to use the SGPR Rsrc.
5387   Rsrc.setReg(SRsrc);
5388   Rsrc.setIsKill(true);
5389 
5390   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5391   MRI.setSimpleHint(SaveExec, CondReg);
5392 
5393   // Update EXEC to matching lanes, saving original to SaveExec.
5394   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
5395       .addReg(CondReg, RegState::Kill);
5396 
5397   // The original instruction is here; we insert the terminators after it.
5398   I = LoopBB.end();
5399 
5400   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5401   BuildMI(LoopBB, I, DL, TII.get(XorTermOpc), Exec)
5402       .addReg(Exec)
5403       .addReg(SaveExec);
5404 
5405   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::SI_WATERFALL_LOOP)).addMBB(&LoopBB);
5406 }
5407 
5408 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
5409 // with SGPRs by iterating over all unique values across all lanes.
5410 // Returns the loop basic block that now contains \p MI.
5411 static MachineBasicBlock *
5412 loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
5413                   MachineOperand &Rsrc, MachineDominatorTree *MDT,
5414                   MachineBasicBlock::iterator Begin = nullptr,
5415                   MachineBasicBlock::iterator End = nullptr) {
5416   MachineBasicBlock &MBB = *MI.getParent();
5417   MachineFunction &MF = *MBB.getParent();
5418   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5419   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5420   MachineRegisterInfo &MRI = MF.getRegInfo();
5421   if (!Begin.isValid())
5422     Begin = &MI;
5423   if (!End.isValid()) {
5424     End = &MI;
5425     ++End;
5426   }
5427   const DebugLoc &DL = MI.getDebugLoc();
5428   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5429   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
5430   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5431 
5432   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5433 
5434   // Save the EXEC mask
5435   BuildMI(MBB, Begin, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
5436 
5437   // Killed uses in the instruction we are waterfalling around will be
5438   // incorrect due to the added control-flow.
5439   MachineBasicBlock::iterator AfterMI = MI;
5440   ++AfterMI;
5441   for (auto I = Begin; I != AfterMI; I++) {
5442     for (auto &MO : I->uses()) {
5443       if (MO.isReg() && MO.isUse()) {
5444         MRI.clearKillFlags(MO.getReg());
5445       }
5446     }
5447   }
5448 
5449   // To insert the loop we need to split the block. Move everything after this
5450   // point to a new block, and insert a new empty block between the two.
5451   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
5452   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
5453   MachineFunction::iterator MBBI(MBB);
5454   ++MBBI;
5455 
5456   MF.insert(MBBI, LoopBB);
5457   MF.insert(MBBI, RemainderBB);
5458 
5459   LoopBB->addSuccessor(LoopBB);
5460   LoopBB->addSuccessor(RemainderBB);
5461 
5462   // Move Begin to MI to the LoopBB, and the remainder of the block to
5463   // RemainderBB.
5464   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5465   RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
5466   LoopBB->splice(LoopBB->begin(), &MBB, Begin, MBB.end());
5467 
5468   MBB.addSuccessor(LoopBB);
5469 
5470   // Update dominators. We know that MBB immediately dominates LoopBB, that
5471   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
5472   // dominates all of the successors transferred to it from MBB that MBB used
5473   // to properly dominate.
5474   if (MDT) {
5475     MDT->addNewBlock(LoopBB, &MBB);
5476     MDT->addNewBlock(RemainderBB, LoopBB);
5477     for (auto &Succ : RemainderBB->successors()) {
5478       if (MDT->properlyDominates(&MBB, Succ)) {
5479         MDT->changeImmediateDominator(Succ, RemainderBB);
5480       }
5481     }
5482   }
5483 
5484   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
5485 
5486   // Restore the EXEC mask
5487   MachineBasicBlock::iterator First = RemainderBB->begin();
5488   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
5489   return LoopBB;
5490 }
5491 
5492 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
5493 static std::tuple<unsigned, unsigned>
5494 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
5495   MachineBasicBlock &MBB = *MI.getParent();
5496   MachineFunction &MF = *MBB.getParent();
5497   MachineRegisterInfo &MRI = MF.getRegInfo();
5498 
5499   // Extract the ptr from the resource descriptor.
5500   unsigned RsrcPtr =
5501       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
5502                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
5503 
5504   // Create an empty resource descriptor
5505   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5506   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5507   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5508   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
5509   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
5510 
5511   // Zero64 = 0
5512   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
5513       .addImm(0);
5514 
5515   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
5516   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
5517       .addImm(RsrcDataFormat & 0xFFFFFFFF);
5518 
5519   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
5520   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
5521       .addImm(RsrcDataFormat >> 32);
5522 
5523   // NewSRsrc = {Zero64, SRsrcFormat}
5524   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
5525       .addReg(Zero64)
5526       .addImm(AMDGPU::sub0_sub1)
5527       .addReg(SRsrcFormatLo)
5528       .addImm(AMDGPU::sub2)
5529       .addReg(SRsrcFormatHi)
5530       .addImm(AMDGPU::sub3);
5531 
5532   return std::make_tuple(RsrcPtr, NewSRsrc);
5533 }
5534 
5535 MachineBasicBlock *
5536 SIInstrInfo::legalizeOperands(MachineInstr &MI,
5537                               MachineDominatorTree *MDT) const {
5538   MachineFunction &MF = *MI.getParent()->getParent();
5539   MachineRegisterInfo &MRI = MF.getRegInfo();
5540   MachineBasicBlock *CreatedBB = nullptr;
5541 
5542   // Legalize VOP2
5543   if (isVOP2(MI) || isVOPC(MI)) {
5544     legalizeOperandsVOP2(MRI, MI);
5545     return CreatedBB;
5546   }
5547 
5548   // Legalize VOP3
5549   if (isVOP3(MI)) {
5550     legalizeOperandsVOP3(MRI, MI);
5551     return CreatedBB;
5552   }
5553 
5554   // Legalize SMRD
5555   if (isSMRD(MI)) {
5556     legalizeOperandsSMRD(MRI, MI);
5557     return CreatedBB;
5558   }
5559 
5560   // Legalize FLAT
5561   if (isFLAT(MI)) {
5562     legalizeOperandsFLAT(MRI, MI);
5563     return CreatedBB;
5564   }
5565 
5566   // Legalize REG_SEQUENCE and PHI
5567   // The register class of the operands much be the same type as the register
5568   // class of the output.
5569   if (MI.getOpcode() == AMDGPU::PHI) {
5570     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
5571     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
5572       if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
5573         continue;
5574       const TargetRegisterClass *OpRC =
5575           MRI.getRegClass(MI.getOperand(i).getReg());
5576       if (RI.hasVectorRegisters(OpRC)) {
5577         VRC = OpRC;
5578       } else {
5579         SRC = OpRC;
5580       }
5581     }
5582 
5583     // If any of the operands are VGPR registers, then they all most be
5584     // otherwise we will create illegal VGPR->SGPR copies when legalizing
5585     // them.
5586     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
5587       if (!VRC) {
5588         assert(SRC);
5589         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
5590           VRC = &AMDGPU::VReg_1RegClass;
5591         } else
5592           VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5593                     ? RI.getEquivalentAGPRClass(SRC)
5594                     : RI.getEquivalentVGPRClass(SRC);
5595       } else {
5596         VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5597                   ? RI.getEquivalentAGPRClass(VRC)
5598                   : RI.getEquivalentVGPRClass(VRC);
5599       }
5600       RC = VRC;
5601     } else {
5602       RC = SRC;
5603     }
5604 
5605     // Update all the operands so they have the same type.
5606     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5607       MachineOperand &Op = MI.getOperand(I);
5608       if (!Op.isReg() || !Op.getReg().isVirtual())
5609         continue;
5610 
5611       // MI is a PHI instruction.
5612       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
5613       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
5614 
5615       // Avoid creating no-op copies with the same src and dst reg class.  These
5616       // confuse some of the machine passes.
5617       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
5618     }
5619   }
5620 
5621   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
5622   // VGPR dest type and SGPR sources, insert copies so all operands are
5623   // VGPRs. This seems to help operand folding / the register coalescer.
5624   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
5625     MachineBasicBlock *MBB = MI.getParent();
5626     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
5627     if (RI.hasVGPRs(DstRC)) {
5628       // Update all the operands so they are VGPR register classes. These may
5629       // not be the same register class because REG_SEQUENCE supports mixing
5630       // subregister index types e.g. sub0_sub1 + sub2 + sub3
5631       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5632         MachineOperand &Op = MI.getOperand(I);
5633         if (!Op.isReg() || !Op.getReg().isVirtual())
5634           continue;
5635 
5636         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
5637         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
5638         if (VRC == OpRC)
5639           continue;
5640 
5641         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
5642         Op.setIsKill();
5643       }
5644     }
5645 
5646     return CreatedBB;
5647   }
5648 
5649   // Legalize INSERT_SUBREG
5650   // src0 must have the same register class as dst
5651   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
5652     Register Dst = MI.getOperand(0).getReg();
5653     Register Src0 = MI.getOperand(1).getReg();
5654     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
5655     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
5656     if (DstRC != Src0RC) {
5657       MachineBasicBlock *MBB = MI.getParent();
5658       MachineOperand &Op = MI.getOperand(1);
5659       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
5660     }
5661     return CreatedBB;
5662   }
5663 
5664   // Legalize SI_INIT_M0
5665   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
5666     MachineOperand &Src = MI.getOperand(0);
5667     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
5668       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
5669     return CreatedBB;
5670   }
5671 
5672   // Legalize MIMG and MUBUF/MTBUF for shaders.
5673   //
5674   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
5675   // scratch memory access. In both cases, the legalization never involves
5676   // conversion to the addr64 form.
5677   if (isMIMG(MI) || (AMDGPU::isGraphics(MF.getFunction().getCallingConv()) &&
5678                      (isMUBUF(MI) || isMTBUF(MI)))) {
5679     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
5680     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
5681       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SRsrc, MDT);
5682 
5683     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
5684     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
5685       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SSamp, MDT);
5686 
5687     return CreatedBB;
5688   }
5689 
5690   // Legalize SI_CALL
5691   if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
5692     MachineOperand *Dest = &MI.getOperand(0);
5693     if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
5694       // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
5695       // following copies, we also need to move copies from and to physical
5696       // registers into the loop block.
5697       unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
5698       unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
5699 
5700       // Also move the copies to physical registers into the loop block
5701       MachineBasicBlock &MBB = *MI.getParent();
5702       MachineBasicBlock::iterator Start(&MI);
5703       while (Start->getOpcode() != FrameSetupOpcode)
5704         --Start;
5705       MachineBasicBlock::iterator End(&MI);
5706       while (End->getOpcode() != FrameDestroyOpcode)
5707         ++End;
5708       // Also include following copies of the return value
5709       ++End;
5710       while (End != MBB.end() && End->isCopy() && End->getOperand(1).isReg() &&
5711              MI.definesRegister(End->getOperand(1).getReg()))
5712         ++End;
5713       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Dest, MDT, Start, End);
5714     }
5715   }
5716 
5717   // Legalize MUBUF* instructions.
5718   int RsrcIdx =
5719       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
5720   if (RsrcIdx != -1) {
5721     // We have an MUBUF instruction
5722     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
5723     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
5724     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
5725                              RI.getRegClass(RsrcRC))) {
5726       // The operands are legal.
5727       // FIXME: We may need to legalize operands besided srsrc.
5728       return CreatedBB;
5729     }
5730 
5731     // Legalize a VGPR Rsrc.
5732     //
5733     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
5734     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
5735     // a zero-value SRsrc.
5736     //
5737     // If the instruction is _OFFSET (both idxen and offen disabled), and we
5738     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
5739     // above.
5740     //
5741     // Otherwise we are on non-ADDR64 hardware, and/or we have
5742     // idxen/offen/bothen and we fall back to a waterfall loop.
5743 
5744     MachineBasicBlock &MBB = *MI.getParent();
5745 
5746     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5747     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
5748       // This is already an ADDR64 instruction so we need to add the pointer
5749       // extracted from the resource descriptor to the current value of VAddr.
5750       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5751       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5752       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5753 
5754       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5755       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
5756       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
5757 
5758       unsigned RsrcPtr, NewSRsrc;
5759       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5760 
5761       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
5762       const DebugLoc &DL = MI.getDebugLoc();
5763       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
5764         .addDef(CondReg0)
5765         .addReg(RsrcPtr, 0, AMDGPU::sub0)
5766         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
5767         .addImm(0);
5768 
5769       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
5770       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
5771         .addDef(CondReg1, RegState::Dead)
5772         .addReg(RsrcPtr, 0, AMDGPU::sub1)
5773         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
5774         .addReg(CondReg0, RegState::Kill)
5775         .addImm(0);
5776 
5777       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5778       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
5779           .addReg(NewVAddrLo)
5780           .addImm(AMDGPU::sub0)
5781           .addReg(NewVAddrHi)
5782           .addImm(AMDGPU::sub1);
5783 
5784       VAddr->setReg(NewVAddr);
5785       Rsrc->setReg(NewSRsrc);
5786     } else if (!VAddr && ST.hasAddr64()) {
5787       // This instructions is the _OFFSET variant, so we need to convert it to
5788       // ADDR64.
5789       assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5790              "FIXME: Need to emit flat atomics here");
5791 
5792       unsigned RsrcPtr, NewSRsrc;
5793       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5794 
5795       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5796       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
5797       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5798       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
5799       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
5800 
5801       // Atomics rith return have have an additional tied operand and are
5802       // missing some of the special bits.
5803       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
5804       MachineInstr *Addr64;
5805 
5806       if (!VDataIn) {
5807         // Regular buffer load / store.
5808         MachineInstrBuilder MIB =
5809             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5810                 .add(*VData)
5811                 .addReg(NewVAddr)
5812                 .addReg(NewSRsrc)
5813                 .add(*SOffset)
5814                 .add(*Offset);
5815 
5816         if (const MachineOperand *CPol =
5817                 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
5818           MIB.addImm(CPol->getImm());
5819         }
5820 
5821         if (const MachineOperand *TFE =
5822                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
5823           MIB.addImm(TFE->getImm());
5824         }
5825 
5826         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
5827 
5828         MIB.cloneMemRefs(MI);
5829         Addr64 = MIB;
5830       } else {
5831         // Atomics with return.
5832         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5833                      .add(*VData)
5834                      .add(*VDataIn)
5835                      .addReg(NewVAddr)
5836                      .addReg(NewSRsrc)
5837                      .add(*SOffset)
5838                      .add(*Offset)
5839                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
5840                      .cloneMemRefs(MI);
5841       }
5842 
5843       MI.removeFromParent();
5844 
5845       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5846       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
5847               NewVAddr)
5848           .addReg(RsrcPtr, 0, AMDGPU::sub0)
5849           .addImm(AMDGPU::sub0)
5850           .addReg(RsrcPtr, 0, AMDGPU::sub1)
5851           .addImm(AMDGPU::sub1);
5852     } else {
5853       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
5854       // to SGPRs.
5855       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
5856       return CreatedBB;
5857     }
5858   }
5859   return CreatedBB;
5860 }
5861 
5862 MachineBasicBlock *SIInstrInfo::moveToVALU(MachineInstr &TopInst,
5863                                            MachineDominatorTree *MDT) const {
5864   SetVectorType Worklist;
5865   Worklist.insert(&TopInst);
5866   MachineBasicBlock *CreatedBB = nullptr;
5867   MachineBasicBlock *CreatedBBTmp = nullptr;
5868 
5869   while (!Worklist.empty()) {
5870     MachineInstr &Inst = *Worklist.pop_back_val();
5871     MachineBasicBlock *MBB = Inst.getParent();
5872     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
5873 
5874     unsigned Opcode = Inst.getOpcode();
5875     unsigned NewOpcode = getVALUOp(Inst);
5876 
5877     // Handle some special cases
5878     switch (Opcode) {
5879     default:
5880       break;
5881     case AMDGPU::S_ADD_U64_PSEUDO:
5882     case AMDGPU::S_SUB_U64_PSEUDO:
5883       splitScalar64BitAddSub(Worklist, Inst, MDT);
5884       Inst.eraseFromParent();
5885       continue;
5886     case AMDGPU::S_ADD_I32:
5887     case AMDGPU::S_SUB_I32: {
5888       // FIXME: The u32 versions currently selected use the carry.
5889       bool Changed;
5890       std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
5891       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5892         CreatedBB = CreatedBBTmp;
5893       if (Changed)
5894         continue;
5895 
5896       // Default handling
5897       break;
5898     }
5899     case AMDGPU::S_AND_B64:
5900       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
5901       Inst.eraseFromParent();
5902       continue;
5903 
5904     case AMDGPU::S_OR_B64:
5905       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
5906       Inst.eraseFromParent();
5907       continue;
5908 
5909     case AMDGPU::S_XOR_B64:
5910       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
5911       Inst.eraseFromParent();
5912       continue;
5913 
5914     case AMDGPU::S_NAND_B64:
5915       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
5916       Inst.eraseFromParent();
5917       continue;
5918 
5919     case AMDGPU::S_NOR_B64:
5920       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
5921       Inst.eraseFromParent();
5922       continue;
5923 
5924     case AMDGPU::S_XNOR_B64:
5925       if (ST.hasDLInsts())
5926         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
5927       else
5928         splitScalar64BitXnor(Worklist, Inst, MDT);
5929       Inst.eraseFromParent();
5930       continue;
5931 
5932     case AMDGPU::S_ANDN2_B64:
5933       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
5934       Inst.eraseFromParent();
5935       continue;
5936 
5937     case AMDGPU::S_ORN2_B64:
5938       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
5939       Inst.eraseFromParent();
5940       continue;
5941 
5942     case AMDGPU::S_BREV_B64:
5943       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
5944       Inst.eraseFromParent();
5945       continue;
5946 
5947     case AMDGPU::S_NOT_B64:
5948       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
5949       Inst.eraseFromParent();
5950       continue;
5951 
5952     case AMDGPU::S_BCNT1_I32_B64:
5953       splitScalar64BitBCNT(Worklist, Inst);
5954       Inst.eraseFromParent();
5955       continue;
5956 
5957     case AMDGPU::S_BFE_I64:
5958       splitScalar64BitBFE(Worklist, Inst);
5959       Inst.eraseFromParent();
5960       continue;
5961 
5962     case AMDGPU::S_LSHL_B32:
5963       if (ST.hasOnlyRevVALUShifts()) {
5964         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
5965         swapOperands(Inst);
5966       }
5967       break;
5968     case AMDGPU::S_ASHR_I32:
5969       if (ST.hasOnlyRevVALUShifts()) {
5970         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
5971         swapOperands(Inst);
5972       }
5973       break;
5974     case AMDGPU::S_LSHR_B32:
5975       if (ST.hasOnlyRevVALUShifts()) {
5976         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
5977         swapOperands(Inst);
5978       }
5979       break;
5980     case AMDGPU::S_LSHL_B64:
5981       if (ST.hasOnlyRevVALUShifts()) {
5982         NewOpcode = AMDGPU::V_LSHLREV_B64_e64;
5983         swapOperands(Inst);
5984       }
5985       break;
5986     case AMDGPU::S_ASHR_I64:
5987       if (ST.hasOnlyRevVALUShifts()) {
5988         NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
5989         swapOperands(Inst);
5990       }
5991       break;
5992     case AMDGPU::S_LSHR_B64:
5993       if (ST.hasOnlyRevVALUShifts()) {
5994         NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
5995         swapOperands(Inst);
5996       }
5997       break;
5998 
5999     case AMDGPU::S_ABS_I32:
6000       lowerScalarAbs(Worklist, Inst);
6001       Inst.eraseFromParent();
6002       continue;
6003 
6004     case AMDGPU::S_CBRANCH_SCC0:
6005     case AMDGPU::S_CBRANCH_SCC1: {
6006         // Clear unused bits of vcc
6007         Register CondReg = Inst.getOperand(1).getReg();
6008         bool IsSCC = CondReg == AMDGPU::SCC;
6009         Register VCC = RI.getVCC();
6010         Register EXEC = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6011         unsigned Opc = ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6012         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(Opc), VCC)
6013             .addReg(EXEC)
6014             .addReg(IsSCC ? VCC : CondReg);
6015         Inst.RemoveOperand(1);
6016       }
6017       break;
6018 
6019     case AMDGPU::S_BFE_U64:
6020     case AMDGPU::S_BFM_B64:
6021       llvm_unreachable("Moving this op to VALU not implemented");
6022 
6023     case AMDGPU::S_PACK_LL_B32_B16:
6024     case AMDGPU::S_PACK_LH_B32_B16:
6025     case AMDGPU::S_PACK_HH_B32_B16:
6026       movePackToVALU(Worklist, MRI, Inst);
6027       Inst.eraseFromParent();
6028       continue;
6029 
6030     case AMDGPU::S_XNOR_B32:
6031       lowerScalarXnor(Worklist, Inst);
6032       Inst.eraseFromParent();
6033       continue;
6034 
6035     case AMDGPU::S_NAND_B32:
6036       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
6037       Inst.eraseFromParent();
6038       continue;
6039 
6040     case AMDGPU::S_NOR_B32:
6041       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
6042       Inst.eraseFromParent();
6043       continue;
6044 
6045     case AMDGPU::S_ANDN2_B32:
6046       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
6047       Inst.eraseFromParent();
6048       continue;
6049 
6050     case AMDGPU::S_ORN2_B32:
6051       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
6052       Inst.eraseFromParent();
6053       continue;
6054 
6055     // TODO: remove as soon as everything is ready
6056     // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
6057     // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
6058     // can only be selected from the uniform SDNode.
6059     case AMDGPU::S_ADD_CO_PSEUDO:
6060     case AMDGPU::S_SUB_CO_PSEUDO: {
6061       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
6062                          ? AMDGPU::V_ADDC_U32_e64
6063                          : AMDGPU::V_SUBB_U32_e64;
6064       const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6065 
6066       Register CarryInReg = Inst.getOperand(4).getReg();
6067       if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
6068         Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
6069         BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
6070             .addReg(CarryInReg);
6071       }
6072 
6073       Register CarryOutReg = Inst.getOperand(1).getReg();
6074 
6075       Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
6076           MRI.getRegClass(Inst.getOperand(0).getReg())));
6077       MachineInstr *CarryOp =
6078           BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
6079               .addReg(CarryOutReg, RegState::Define)
6080               .add(Inst.getOperand(2))
6081               .add(Inst.getOperand(3))
6082               .addReg(CarryInReg)
6083               .addImm(0);
6084       CreatedBBTmp = legalizeOperands(*CarryOp);
6085       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6086         CreatedBB = CreatedBBTmp;
6087       MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
6088       addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
6089       Inst.eraseFromParent();
6090     }
6091       continue;
6092     case AMDGPU::S_UADDO_PSEUDO:
6093     case AMDGPU::S_USUBO_PSEUDO: {
6094       const DebugLoc &DL = Inst.getDebugLoc();
6095       MachineOperand &Dest0 = Inst.getOperand(0);
6096       MachineOperand &Dest1 = Inst.getOperand(1);
6097       MachineOperand &Src0 = Inst.getOperand(2);
6098       MachineOperand &Src1 = Inst.getOperand(3);
6099 
6100       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
6101                          ? AMDGPU::V_ADD_CO_U32_e64
6102                          : AMDGPU::V_SUB_CO_U32_e64;
6103       const TargetRegisterClass *NewRC =
6104           RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
6105       Register DestReg = MRI.createVirtualRegister(NewRC);
6106       MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
6107                                    .addReg(Dest1.getReg(), RegState::Define)
6108                                    .add(Src0)
6109                                    .add(Src1)
6110                                    .addImm(0); // clamp bit
6111 
6112       CreatedBBTmp = legalizeOperands(*NewInstr, MDT);
6113       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6114         CreatedBB = CreatedBBTmp;
6115 
6116       MRI.replaceRegWith(Dest0.getReg(), DestReg);
6117       addUsersToMoveToVALUWorklist(NewInstr->getOperand(0).getReg(), MRI,
6118                                    Worklist);
6119       Inst.eraseFromParent();
6120     }
6121       continue;
6122 
6123     case AMDGPU::S_CSELECT_B32:
6124       lowerSelect32(Worklist, Inst, MDT);
6125       Inst.eraseFromParent();
6126       continue;
6127     case AMDGPU::S_CSELECT_B64:
6128       splitSelect64(Worklist, Inst, MDT);
6129       Inst.eraseFromParent();
6130       continue;
6131     case AMDGPU::S_CMP_EQ_I32:
6132     case AMDGPU::S_CMP_LG_I32:
6133     case AMDGPU::S_CMP_GT_I32:
6134     case AMDGPU::S_CMP_GE_I32:
6135     case AMDGPU::S_CMP_LT_I32:
6136     case AMDGPU::S_CMP_LE_I32:
6137     case AMDGPU::S_CMP_EQ_U32:
6138     case AMDGPU::S_CMP_LG_U32:
6139     case AMDGPU::S_CMP_GT_U32:
6140     case AMDGPU::S_CMP_GE_U32:
6141     case AMDGPU::S_CMP_LT_U32:
6142     case AMDGPU::S_CMP_LE_U32:
6143     case AMDGPU::S_CMP_EQ_U64:
6144     case AMDGPU::S_CMP_LG_U64: {
6145         const MCInstrDesc &NewDesc = get(NewOpcode);
6146         Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
6147         MachineInstr *NewInstr =
6148             BuildMI(*MBB, Inst, Inst.getDebugLoc(), NewDesc, CondReg)
6149                 .add(Inst.getOperand(0))
6150                 .add(Inst.getOperand(1));
6151         legalizeOperands(*NewInstr, MDT);
6152         int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC);
6153         MachineOperand SCCOp = Inst.getOperand(SCCIdx);
6154         addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
6155         Inst.eraseFromParent();
6156       }
6157       continue;
6158     }
6159 
6160 
6161     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
6162       // We cannot move this instruction to the VALU, so we should try to
6163       // legalize its operands instead.
6164       CreatedBBTmp = legalizeOperands(Inst, MDT);
6165       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6166         CreatedBB = CreatedBBTmp;
6167       continue;
6168     }
6169 
6170     // Use the new VALU Opcode.
6171     const MCInstrDesc &NewDesc = get(NewOpcode);
6172     Inst.setDesc(NewDesc);
6173 
6174     // Remove any references to SCC. Vector instructions can't read from it, and
6175     // We're just about to add the implicit use / defs of VCC, and we don't want
6176     // both.
6177     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
6178       MachineOperand &Op = Inst.getOperand(i);
6179       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
6180         // Only propagate through live-def of SCC.
6181         if (Op.isDef() && !Op.isDead())
6182           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
6183         if (Op.isUse())
6184           addSCCDefsToVALUWorklist(Op, Worklist);
6185         Inst.RemoveOperand(i);
6186       }
6187     }
6188 
6189     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
6190       // We are converting these to a BFE, so we need to add the missing
6191       // operands for the size and offset.
6192       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
6193       Inst.addOperand(MachineOperand::CreateImm(0));
6194       Inst.addOperand(MachineOperand::CreateImm(Size));
6195 
6196     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
6197       // The VALU version adds the second operand to the result, so insert an
6198       // extra 0 operand.
6199       Inst.addOperand(MachineOperand::CreateImm(0));
6200     }
6201 
6202     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
6203     fixImplicitOperands(Inst);
6204 
6205     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
6206       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
6207       // If we need to move this to VGPRs, we need to unpack the second operand
6208       // back into the 2 separate ones for bit offset and width.
6209       assert(OffsetWidthOp.isImm() &&
6210              "Scalar BFE is only implemented for constant width and offset");
6211       uint32_t Imm = OffsetWidthOp.getImm();
6212 
6213       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6214       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6215       Inst.RemoveOperand(2);                     // Remove old immediate.
6216       Inst.addOperand(MachineOperand::CreateImm(Offset));
6217       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
6218     }
6219 
6220     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
6221     unsigned NewDstReg = AMDGPU::NoRegister;
6222     if (HasDst) {
6223       Register DstReg = Inst.getOperand(0).getReg();
6224       if (DstReg.isPhysical())
6225         continue;
6226 
6227       // Update the destination register class.
6228       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
6229       if (!NewDstRC)
6230         continue;
6231 
6232       if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual() &&
6233           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
6234         // Instead of creating a copy where src and dst are the same register
6235         // class, we just replace all uses of dst with src.  These kinds of
6236         // copies interfere with the heuristics MachineSink uses to decide
6237         // whether or not to split a critical edge.  Since the pass assumes
6238         // that copies will end up as machine instructions and not be
6239         // eliminated.
6240         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
6241         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
6242         MRI.clearKillFlags(Inst.getOperand(1).getReg());
6243         Inst.getOperand(0).setReg(DstReg);
6244 
6245         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
6246         // these are deleted later, but at -O0 it would leave a suspicious
6247         // looking illegal copy of an undef register.
6248         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
6249           Inst.RemoveOperand(I);
6250         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
6251         continue;
6252       }
6253 
6254       NewDstReg = MRI.createVirtualRegister(NewDstRC);
6255       MRI.replaceRegWith(DstReg, NewDstReg);
6256     }
6257 
6258     // Legalize the operands
6259     CreatedBBTmp = legalizeOperands(Inst, MDT);
6260     if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6261       CreatedBB = CreatedBBTmp;
6262 
6263     if (HasDst)
6264      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
6265   }
6266   return CreatedBB;
6267 }
6268 
6269 // Add/sub require special handling to deal with carry outs.
6270 std::pair<bool, MachineBasicBlock *>
6271 SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
6272                               MachineDominatorTree *MDT) const {
6273   if (ST.hasAddNoCarry()) {
6274     // Assume there is no user of scc since we don't select this in that case.
6275     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
6276     // is used.
6277 
6278     MachineBasicBlock &MBB = *Inst.getParent();
6279     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6280 
6281     Register OldDstReg = Inst.getOperand(0).getReg();
6282     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6283 
6284     unsigned Opc = Inst.getOpcode();
6285     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
6286 
6287     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
6288       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
6289 
6290     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
6291     Inst.RemoveOperand(3);
6292 
6293     Inst.setDesc(get(NewOpc));
6294     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
6295     Inst.addImplicitDefUseOperands(*MBB.getParent());
6296     MRI.replaceRegWith(OldDstReg, ResultReg);
6297     MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
6298 
6299     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6300     return std::make_pair(true, NewBB);
6301   }
6302 
6303   return std::make_pair(false, nullptr);
6304 }
6305 
6306 void SIInstrInfo::lowerSelect32(SetVectorType &Worklist, MachineInstr &Inst,
6307                                 MachineDominatorTree *MDT) const {
6308 
6309   MachineBasicBlock &MBB = *Inst.getParent();
6310   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6311   MachineBasicBlock::iterator MII = Inst;
6312   DebugLoc DL = Inst.getDebugLoc();
6313 
6314   MachineOperand &Dest = Inst.getOperand(0);
6315   MachineOperand &Src0 = Inst.getOperand(1);
6316   MachineOperand &Src1 = Inst.getOperand(2);
6317   MachineOperand &Cond = Inst.getOperand(3);
6318 
6319   Register SCCSource = Cond.getReg();
6320   bool IsSCC = (SCCSource == AMDGPU::SCC);
6321 
6322   // If this is a trivial select where the condition is effectively not SCC
6323   // (SCCSource is a source of copy to SCC), then the select is semantically
6324   // equivalent to copying SCCSource. Hence, there is no need to create
6325   // V_CNDMASK, we can just use that and bail out.
6326   if (!IsSCC && Src0.isImm() && (Src0.getImm() == -1) && Src1.isImm() &&
6327       (Src1.getImm() == 0)) {
6328     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6329     return;
6330   }
6331 
6332   const TargetRegisterClass *TC =
6333       RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6334 
6335   Register CopySCC = MRI.createVirtualRegister(TC);
6336 
6337   if (IsSCC) {
6338     // Now look for the closest SCC def if it is a copy
6339     // replacing the SCCSource with the COPY source register
6340     bool CopyFound = false;
6341     for (MachineInstr &CandI :
6342          make_range(std::next(MachineBasicBlock::reverse_iterator(Inst)),
6343                     Inst.getParent()->rend())) {
6344       if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) !=
6345           -1) {
6346         if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
6347           BuildMI(MBB, MII, DL, get(AMDGPU::COPY), CopySCC)
6348               .addReg(CandI.getOperand(1).getReg());
6349           CopyFound = true;
6350         }
6351         break;
6352       }
6353     }
6354     if (!CopyFound) {
6355       // SCC def is not a copy
6356       // Insert a trivial select instead of creating a copy, because a copy from
6357       // SCC would semantically mean just copying a single bit, but we may need
6358       // the result to be a vector condition mask that needs preserving.
6359       unsigned Opcode = (ST.getWavefrontSize() == 64) ? AMDGPU::S_CSELECT_B64
6360                                                       : AMDGPU::S_CSELECT_B32;
6361       auto NewSelect =
6362           BuildMI(MBB, MII, DL, get(Opcode), CopySCC).addImm(-1).addImm(0);
6363       NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
6364     }
6365   }
6366 
6367   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6368 
6369   auto UpdatedInst =
6370       BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), ResultReg)
6371           .addImm(0)
6372           .add(Src1) // False
6373           .addImm(0)
6374           .add(Src0) // True
6375           .addReg(IsSCC ? CopySCC : SCCSource);
6376 
6377   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6378   legalizeOperands(*UpdatedInst, MDT);
6379   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6380 }
6381 
6382 void SIInstrInfo::splitSelect64(SetVectorType &Worklist, MachineInstr &Inst,
6383                                 MachineDominatorTree *MDT) const {
6384   // Split S_CSELECT_B64 into a pair of S_CSELECT_B32 and lower them
6385   // further.
6386   const DebugLoc &DL = Inst.getDebugLoc();
6387   MachineBasicBlock::iterator MII = Inst;
6388   MachineBasicBlock &MBB = *Inst.getParent();
6389   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6390 
6391   // Get the original operands.
6392   MachineOperand &Dest = Inst.getOperand(0);
6393   MachineOperand &Src0 = Inst.getOperand(1);
6394   MachineOperand &Src1 = Inst.getOperand(2);
6395   MachineOperand &Cond = Inst.getOperand(3);
6396 
6397   Register SCCSource = Cond.getReg();
6398   bool IsSCC = (SCCSource == AMDGPU::SCC);
6399 
6400   // If this is a trivial select where the condition is effectively not SCC
6401   // (SCCSource is a source of copy to SCC), then the select is semantically
6402   // equivalent to copying SCCSource. Hence, there is no need to create
6403   // V_CNDMASK, we can just use that and bail out.
6404   if (!IsSCC && (Src0.isImm() && Src0.getImm() == -1) &&
6405       (Src1.isImm() && Src1.getImm() == 0)) {
6406     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6407     return;
6408   }
6409 
6410   // Prepare the split destination.
6411   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6412   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6413   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6414 
6415   // Split the source operands.
6416   const TargetRegisterClass *Src0RC = nullptr;
6417   const TargetRegisterClass *Src0SubRC = nullptr;
6418   if (Src0.isReg()) {
6419     Src0RC = MRI.getRegClass(Src0.getReg());
6420     Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6421   }
6422   const TargetRegisterClass *Src1RC = nullptr;
6423   const TargetRegisterClass *Src1SubRC = nullptr;
6424   if (Src1.isReg()) {
6425     Src1RC = MRI.getRegClass(Src1.getReg());
6426     Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6427   }
6428   // Split lo.
6429   MachineOperand SrcReg0Sub0 =
6430       buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
6431   MachineOperand SrcReg1Sub0 =
6432       buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
6433   // Split hi.
6434   MachineOperand SrcReg0Sub1 =
6435       buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
6436   MachineOperand SrcReg1Sub1 =
6437       buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
6438   // Select the lo part.
6439   MachineInstr *LoHalf =
6440       BuildMI(MBB, MII, DL, get(AMDGPU::S_CSELECT_B32), DestSub0)
6441           .add(SrcReg0Sub0)
6442           .add(SrcReg1Sub0);
6443   // Replace the condition operand with the original one.
6444   LoHalf->getOperand(3).setReg(SCCSource);
6445   Worklist.insert(LoHalf);
6446   // Select the hi part.
6447   MachineInstr *HiHalf =
6448       BuildMI(MBB, MII, DL, get(AMDGPU::S_CSELECT_B32), DestSub1)
6449           .add(SrcReg0Sub1)
6450           .add(SrcReg1Sub1);
6451   // Replace the condition operand with the original one.
6452   HiHalf->getOperand(3).setReg(SCCSource);
6453   Worklist.insert(HiHalf);
6454   // Merge them back to the original 64-bit one.
6455   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6456       .addReg(DestSub0)
6457       .addImm(AMDGPU::sub0)
6458       .addReg(DestSub1)
6459       .addImm(AMDGPU::sub1);
6460   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6461 
6462   // Try to legalize the operands in case we need to swap the order to keep
6463   // it valid.
6464   legalizeOperands(*LoHalf, MDT);
6465   legalizeOperands(*HiHalf, MDT);
6466 
6467   // Move all users of this moved value.
6468   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6469 }
6470 
6471 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
6472                                  MachineInstr &Inst) const {
6473   MachineBasicBlock &MBB = *Inst.getParent();
6474   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6475   MachineBasicBlock::iterator MII = Inst;
6476   DebugLoc DL = Inst.getDebugLoc();
6477 
6478   MachineOperand &Dest = Inst.getOperand(0);
6479   MachineOperand &Src = Inst.getOperand(1);
6480   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6481   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6482 
6483   unsigned SubOp = ST.hasAddNoCarry() ?
6484     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_CO_U32_e32;
6485 
6486   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
6487     .addImm(0)
6488     .addReg(Src.getReg());
6489 
6490   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
6491     .addReg(Src.getReg())
6492     .addReg(TmpReg);
6493 
6494   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6495   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6496 }
6497 
6498 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
6499                                   MachineInstr &Inst) const {
6500   MachineBasicBlock &MBB = *Inst.getParent();
6501   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6502   MachineBasicBlock::iterator MII = Inst;
6503   const DebugLoc &DL = Inst.getDebugLoc();
6504 
6505   MachineOperand &Dest = Inst.getOperand(0);
6506   MachineOperand &Src0 = Inst.getOperand(1);
6507   MachineOperand &Src1 = Inst.getOperand(2);
6508 
6509   if (ST.hasDLInsts()) {
6510     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6511     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
6512     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
6513 
6514     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
6515       .add(Src0)
6516       .add(Src1);
6517 
6518     MRI.replaceRegWith(Dest.getReg(), NewDest);
6519     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6520   } else {
6521     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
6522     // invert either source and then perform the XOR. If either source is a
6523     // scalar register, then we can leave the inversion on the scalar unit to
6524     // acheive a better distrubution of scalar and vector instructions.
6525     bool Src0IsSGPR = Src0.isReg() &&
6526                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
6527     bool Src1IsSGPR = Src1.isReg() &&
6528                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
6529     MachineInstr *Xor;
6530     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6531     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6532 
6533     // Build a pair of scalar instructions and add them to the work list.
6534     // The next iteration over the work list will lower these to the vector
6535     // unit as necessary.
6536     if (Src0IsSGPR) {
6537       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
6538       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6539       .addReg(Temp)
6540       .add(Src1);
6541     } else if (Src1IsSGPR) {
6542       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
6543       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6544       .add(Src0)
6545       .addReg(Temp);
6546     } else {
6547       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
6548         .add(Src0)
6549         .add(Src1);
6550       MachineInstr *Not =
6551           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
6552       Worklist.insert(Not);
6553     }
6554 
6555     MRI.replaceRegWith(Dest.getReg(), NewDest);
6556 
6557     Worklist.insert(Xor);
6558 
6559     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6560   }
6561 }
6562 
6563 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
6564                                       MachineInstr &Inst,
6565                                       unsigned Opcode) const {
6566   MachineBasicBlock &MBB = *Inst.getParent();
6567   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6568   MachineBasicBlock::iterator MII = Inst;
6569   const DebugLoc &DL = Inst.getDebugLoc();
6570 
6571   MachineOperand &Dest = Inst.getOperand(0);
6572   MachineOperand &Src0 = Inst.getOperand(1);
6573   MachineOperand &Src1 = Inst.getOperand(2);
6574 
6575   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6576   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6577 
6578   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
6579     .add(Src0)
6580     .add(Src1);
6581 
6582   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
6583     .addReg(Interm);
6584 
6585   Worklist.insert(&Op);
6586   Worklist.insert(&Not);
6587 
6588   MRI.replaceRegWith(Dest.getReg(), NewDest);
6589   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6590 }
6591 
6592 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
6593                                      MachineInstr &Inst,
6594                                      unsigned Opcode) const {
6595   MachineBasicBlock &MBB = *Inst.getParent();
6596   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6597   MachineBasicBlock::iterator MII = Inst;
6598   const DebugLoc &DL = Inst.getDebugLoc();
6599 
6600   MachineOperand &Dest = Inst.getOperand(0);
6601   MachineOperand &Src0 = Inst.getOperand(1);
6602   MachineOperand &Src1 = Inst.getOperand(2);
6603 
6604   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6605   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6606 
6607   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
6608     .add(Src1);
6609 
6610   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
6611     .add(Src0)
6612     .addReg(Interm);
6613 
6614   Worklist.insert(&Not);
6615   Worklist.insert(&Op);
6616 
6617   MRI.replaceRegWith(Dest.getReg(), NewDest);
6618   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6619 }
6620 
6621 void SIInstrInfo::splitScalar64BitUnaryOp(
6622     SetVectorType &Worklist, MachineInstr &Inst,
6623     unsigned Opcode, bool Swap) const {
6624   MachineBasicBlock &MBB = *Inst.getParent();
6625   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6626 
6627   MachineOperand &Dest = Inst.getOperand(0);
6628   MachineOperand &Src0 = Inst.getOperand(1);
6629   DebugLoc DL = Inst.getDebugLoc();
6630 
6631   MachineBasicBlock::iterator MII = Inst;
6632 
6633   const MCInstrDesc &InstDesc = get(Opcode);
6634   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6635     MRI.getRegClass(Src0.getReg()) :
6636     &AMDGPU::SGPR_32RegClass;
6637 
6638   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6639 
6640   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6641                                                        AMDGPU::sub0, Src0SubRC);
6642 
6643   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6644   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6645   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6646 
6647   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6648   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
6649 
6650   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6651                                                        AMDGPU::sub1, Src0SubRC);
6652 
6653   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6654   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
6655 
6656   if (Swap)
6657     std::swap(DestSub0, DestSub1);
6658 
6659   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6660   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6661     .addReg(DestSub0)
6662     .addImm(AMDGPU::sub0)
6663     .addReg(DestSub1)
6664     .addImm(AMDGPU::sub1);
6665 
6666   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6667 
6668   Worklist.insert(&LoHalf);
6669   Worklist.insert(&HiHalf);
6670 
6671   // We don't need to legalizeOperands here because for a single operand, src0
6672   // will support any kind of input.
6673 
6674   // Move all users of this moved value.
6675   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6676 }
6677 
6678 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
6679                                          MachineInstr &Inst,
6680                                          MachineDominatorTree *MDT) const {
6681   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
6682 
6683   MachineBasicBlock &MBB = *Inst.getParent();
6684   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6685   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6686 
6687   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6688   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6689   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6690 
6691   Register CarryReg = MRI.createVirtualRegister(CarryRC);
6692   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
6693 
6694   MachineOperand &Dest = Inst.getOperand(0);
6695   MachineOperand &Src0 = Inst.getOperand(1);
6696   MachineOperand &Src1 = Inst.getOperand(2);
6697   const DebugLoc &DL = Inst.getDebugLoc();
6698   MachineBasicBlock::iterator MII = Inst;
6699 
6700   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
6701   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
6702   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6703   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6704 
6705   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6706                                                        AMDGPU::sub0, Src0SubRC);
6707   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6708                                                        AMDGPU::sub0, Src1SubRC);
6709 
6710 
6711   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6712                                                        AMDGPU::sub1, Src0SubRC);
6713   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6714                                                        AMDGPU::sub1, Src1SubRC);
6715 
6716   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
6717   MachineInstr *LoHalf =
6718     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
6719     .addReg(CarryReg, RegState::Define)
6720     .add(SrcReg0Sub0)
6721     .add(SrcReg1Sub0)
6722     .addImm(0); // clamp bit
6723 
6724   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
6725   MachineInstr *HiHalf =
6726     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
6727     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
6728     .add(SrcReg0Sub1)
6729     .add(SrcReg1Sub1)
6730     .addReg(CarryReg, RegState::Kill)
6731     .addImm(0); // clamp bit
6732 
6733   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6734     .addReg(DestSub0)
6735     .addImm(AMDGPU::sub0)
6736     .addReg(DestSub1)
6737     .addImm(AMDGPU::sub1);
6738 
6739   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6740 
6741   // Try to legalize the operands in case we need to swap the order to keep it
6742   // valid.
6743   legalizeOperands(*LoHalf, MDT);
6744   legalizeOperands(*HiHalf, MDT);
6745 
6746   // Move all users of this moved vlaue.
6747   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6748 }
6749 
6750 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
6751                                            MachineInstr &Inst, unsigned Opcode,
6752                                            MachineDominatorTree *MDT) const {
6753   MachineBasicBlock &MBB = *Inst.getParent();
6754   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6755 
6756   MachineOperand &Dest = Inst.getOperand(0);
6757   MachineOperand &Src0 = Inst.getOperand(1);
6758   MachineOperand &Src1 = Inst.getOperand(2);
6759   DebugLoc DL = Inst.getDebugLoc();
6760 
6761   MachineBasicBlock::iterator MII = Inst;
6762 
6763   const MCInstrDesc &InstDesc = get(Opcode);
6764   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6765     MRI.getRegClass(Src0.getReg()) :
6766     &AMDGPU::SGPR_32RegClass;
6767 
6768   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6769   const TargetRegisterClass *Src1RC = Src1.isReg() ?
6770     MRI.getRegClass(Src1.getReg()) :
6771     &AMDGPU::SGPR_32RegClass;
6772 
6773   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6774 
6775   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6776                                                        AMDGPU::sub0, Src0SubRC);
6777   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6778                                                        AMDGPU::sub0, Src1SubRC);
6779   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6780                                                        AMDGPU::sub1, Src0SubRC);
6781   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6782                                                        AMDGPU::sub1, Src1SubRC);
6783 
6784   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6785   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6786   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6787 
6788   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6789   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
6790                               .add(SrcReg0Sub0)
6791                               .add(SrcReg1Sub0);
6792 
6793   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6794   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
6795                               .add(SrcReg0Sub1)
6796                               .add(SrcReg1Sub1);
6797 
6798   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6799   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6800     .addReg(DestSub0)
6801     .addImm(AMDGPU::sub0)
6802     .addReg(DestSub1)
6803     .addImm(AMDGPU::sub1);
6804 
6805   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6806 
6807   Worklist.insert(&LoHalf);
6808   Worklist.insert(&HiHalf);
6809 
6810   // Move all users of this moved vlaue.
6811   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6812 }
6813 
6814 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
6815                                        MachineInstr &Inst,
6816                                        MachineDominatorTree *MDT) const {
6817   MachineBasicBlock &MBB = *Inst.getParent();
6818   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6819 
6820   MachineOperand &Dest = Inst.getOperand(0);
6821   MachineOperand &Src0 = Inst.getOperand(1);
6822   MachineOperand &Src1 = Inst.getOperand(2);
6823   const DebugLoc &DL = Inst.getDebugLoc();
6824 
6825   MachineBasicBlock::iterator MII = Inst;
6826 
6827   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6828 
6829   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6830 
6831   MachineOperand* Op0;
6832   MachineOperand* Op1;
6833 
6834   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
6835     Op0 = &Src0;
6836     Op1 = &Src1;
6837   } else {
6838     Op0 = &Src1;
6839     Op1 = &Src0;
6840   }
6841 
6842   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
6843     .add(*Op0);
6844 
6845   Register NewDest = MRI.createVirtualRegister(DestRC);
6846 
6847   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
6848     .addReg(Interm)
6849     .add(*Op1);
6850 
6851   MRI.replaceRegWith(Dest.getReg(), NewDest);
6852 
6853   Worklist.insert(&Xor);
6854 }
6855 
6856 void SIInstrInfo::splitScalar64BitBCNT(
6857     SetVectorType &Worklist, MachineInstr &Inst) const {
6858   MachineBasicBlock &MBB = *Inst.getParent();
6859   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6860 
6861   MachineBasicBlock::iterator MII = Inst;
6862   const DebugLoc &DL = Inst.getDebugLoc();
6863 
6864   MachineOperand &Dest = Inst.getOperand(0);
6865   MachineOperand &Src = Inst.getOperand(1);
6866 
6867   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
6868   const TargetRegisterClass *SrcRC = Src.isReg() ?
6869     MRI.getRegClass(Src.getReg()) :
6870     &AMDGPU::SGPR_32RegClass;
6871 
6872   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6873   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6874 
6875   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
6876 
6877   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6878                                                       AMDGPU::sub0, SrcSubRC);
6879   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6880                                                       AMDGPU::sub1, SrcSubRC);
6881 
6882   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
6883 
6884   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
6885 
6886   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6887 
6888   // We don't need to legalize operands here. src0 for etiher instruction can be
6889   // an SGPR, and the second input is unused or determined here.
6890   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6891 }
6892 
6893 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
6894                                       MachineInstr &Inst) const {
6895   MachineBasicBlock &MBB = *Inst.getParent();
6896   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6897   MachineBasicBlock::iterator MII = Inst;
6898   const DebugLoc &DL = Inst.getDebugLoc();
6899 
6900   MachineOperand &Dest = Inst.getOperand(0);
6901   uint32_t Imm = Inst.getOperand(2).getImm();
6902   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6903   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6904 
6905   (void) Offset;
6906 
6907   // Only sext_inreg cases handled.
6908   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
6909          Offset == 0 && "Not implemented");
6910 
6911   if (BitWidth < 32) {
6912     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6913     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6914     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6915 
6916     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
6917         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
6918         .addImm(0)
6919         .addImm(BitWidth);
6920 
6921     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
6922       .addImm(31)
6923       .addReg(MidRegLo);
6924 
6925     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6926       .addReg(MidRegLo)
6927       .addImm(AMDGPU::sub0)
6928       .addReg(MidRegHi)
6929       .addImm(AMDGPU::sub1);
6930 
6931     MRI.replaceRegWith(Dest.getReg(), ResultReg);
6932     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6933     return;
6934   }
6935 
6936   MachineOperand &Src = Inst.getOperand(1);
6937   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6938   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6939 
6940   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
6941     .addImm(31)
6942     .addReg(Src.getReg(), 0, AMDGPU::sub0);
6943 
6944   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6945     .addReg(Src.getReg(), 0, AMDGPU::sub0)
6946     .addImm(AMDGPU::sub0)
6947     .addReg(TmpReg)
6948     .addImm(AMDGPU::sub1);
6949 
6950   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6951   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6952 }
6953 
6954 void SIInstrInfo::addUsersToMoveToVALUWorklist(
6955   Register DstReg,
6956   MachineRegisterInfo &MRI,
6957   SetVectorType &Worklist) const {
6958   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
6959          E = MRI.use_end(); I != E;) {
6960     MachineInstr &UseMI = *I->getParent();
6961 
6962     unsigned OpNo = 0;
6963 
6964     switch (UseMI.getOpcode()) {
6965     case AMDGPU::COPY:
6966     case AMDGPU::WQM:
6967     case AMDGPU::SOFT_WQM:
6968     case AMDGPU::STRICT_WWM:
6969     case AMDGPU::STRICT_WQM:
6970     case AMDGPU::REG_SEQUENCE:
6971     case AMDGPU::PHI:
6972     case AMDGPU::INSERT_SUBREG:
6973       break;
6974     default:
6975       OpNo = I.getOperandNo();
6976       break;
6977     }
6978 
6979     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
6980       Worklist.insert(&UseMI);
6981 
6982       do {
6983         ++I;
6984       } while (I != E && I->getParent() == &UseMI);
6985     } else {
6986       ++I;
6987     }
6988   }
6989 }
6990 
6991 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
6992                                  MachineRegisterInfo &MRI,
6993                                  MachineInstr &Inst) const {
6994   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6995   MachineBasicBlock *MBB = Inst.getParent();
6996   MachineOperand &Src0 = Inst.getOperand(1);
6997   MachineOperand &Src1 = Inst.getOperand(2);
6998   const DebugLoc &DL = Inst.getDebugLoc();
6999 
7000   switch (Inst.getOpcode()) {
7001   case AMDGPU::S_PACK_LL_B32_B16: {
7002     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7003     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7004 
7005     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
7006     // 0.
7007     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7008       .addImm(0xffff);
7009 
7010     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
7011       .addReg(ImmReg, RegState::Kill)
7012       .add(Src0);
7013 
7014     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
7015       .add(Src1)
7016       .addImm(16)
7017       .addReg(TmpReg, RegState::Kill);
7018     break;
7019   }
7020   case AMDGPU::S_PACK_LH_B32_B16: {
7021     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7022     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7023       .addImm(0xffff);
7024     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
7025       .addReg(ImmReg, RegState::Kill)
7026       .add(Src0)
7027       .add(Src1);
7028     break;
7029   }
7030   case AMDGPU::S_PACK_HH_B32_B16: {
7031     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7032     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7033     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
7034       .addImm(16)
7035       .add(Src0);
7036     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7037       .addImm(0xffff0000);
7038     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
7039       .add(Src1)
7040       .addReg(ImmReg, RegState::Kill)
7041       .addReg(TmpReg, RegState::Kill);
7042     break;
7043   }
7044   default:
7045     llvm_unreachable("unhandled s_pack_* instruction");
7046   }
7047 
7048   MachineOperand &Dest = Inst.getOperand(0);
7049   MRI.replaceRegWith(Dest.getReg(), ResultReg);
7050   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
7051 }
7052 
7053 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
7054                                                MachineInstr &SCCDefInst,
7055                                                SetVectorType &Worklist,
7056                                                Register NewCond) const {
7057 
7058   // Ensure that def inst defines SCC, which is still live.
7059   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
7060          !Op.isDead() && Op.getParent() == &SCCDefInst);
7061   SmallVector<MachineInstr *, 4> CopyToDelete;
7062   // This assumes that all the users of SCC are in the same block
7063   // as the SCC def.
7064   for (MachineInstr &MI : // Skip the def inst itself.
7065        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
7066                   SCCDefInst.getParent()->end())) {
7067     // Check if SCC is used first.
7068     int SCCIdx = MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI);
7069     if (SCCIdx != -1) {
7070       if (MI.isCopy()) {
7071         MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7072         Register DestReg = MI.getOperand(0).getReg();
7073 
7074         MRI.replaceRegWith(DestReg, NewCond);
7075         CopyToDelete.push_back(&MI);
7076       } else {
7077 
7078         if (NewCond.isValid())
7079           MI.getOperand(SCCIdx).setReg(NewCond);
7080 
7081         Worklist.insert(&MI);
7082       }
7083     }
7084     // Exit if we find another SCC def.
7085     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
7086       break;
7087   }
7088   for (auto &Copy : CopyToDelete)
7089     Copy->eraseFromParent();
7090 }
7091 
7092 // Instructions that use SCC may be converted to VALU instructions. When that
7093 // happens, the SCC register is changed to VCC_LO. The instruction that defines
7094 // SCC must be changed to an instruction that defines VCC. This function makes
7095 // sure that the instruction that defines SCC is added to the moveToVALU
7096 // worklist.
7097 void SIInstrInfo::addSCCDefsToVALUWorklist(MachineOperand &Op,
7098                                            SetVectorType &Worklist) const {
7099   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isUse());
7100 
7101   MachineInstr *SCCUseInst = Op.getParent();
7102   // Look for a preceeding instruction that either defines VCC or SCC. If VCC
7103   // then there is nothing to do because the defining instruction has been
7104   // converted to a VALU already. If SCC then that instruction needs to be
7105   // converted to a VALU.
7106   for (MachineInstr &MI :
7107        make_range(std::next(MachineBasicBlock::reverse_iterator(SCCUseInst)),
7108                   SCCUseInst->getParent()->rend())) {
7109     if (MI.modifiesRegister(AMDGPU::VCC, &RI))
7110       break;
7111     if (MI.definesRegister(AMDGPU::SCC, &RI)) {
7112       Worklist.insert(&MI);
7113       break;
7114     }
7115   }
7116 }
7117 
7118 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
7119   const MachineInstr &Inst) const {
7120   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
7121 
7122   switch (Inst.getOpcode()) {
7123   // For target instructions, getOpRegClass just returns the virtual register
7124   // class associated with the operand, so we need to find an equivalent VGPR
7125   // register class in order to move the instruction to the VALU.
7126   case AMDGPU::COPY:
7127   case AMDGPU::PHI:
7128   case AMDGPU::REG_SEQUENCE:
7129   case AMDGPU::INSERT_SUBREG:
7130   case AMDGPU::WQM:
7131   case AMDGPU::SOFT_WQM:
7132   case AMDGPU::STRICT_WWM:
7133   case AMDGPU::STRICT_WQM: {
7134     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
7135     if (RI.isAGPRClass(SrcRC)) {
7136       if (RI.isAGPRClass(NewDstRC))
7137         return nullptr;
7138 
7139       switch (Inst.getOpcode()) {
7140       case AMDGPU::PHI:
7141       case AMDGPU::REG_SEQUENCE:
7142       case AMDGPU::INSERT_SUBREG:
7143         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
7144         break;
7145       default:
7146         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7147       }
7148 
7149       if (!NewDstRC)
7150         return nullptr;
7151     } else {
7152       if (RI.isVGPRClass(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
7153         return nullptr;
7154 
7155       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7156       if (!NewDstRC)
7157         return nullptr;
7158     }
7159 
7160     return NewDstRC;
7161   }
7162   default:
7163     return NewDstRC;
7164   }
7165 }
7166 
7167 // Find the one SGPR operand we are allowed to use.
7168 Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
7169                                    int OpIndices[3]) const {
7170   const MCInstrDesc &Desc = MI.getDesc();
7171 
7172   // Find the one SGPR operand we are allowed to use.
7173   //
7174   // First we need to consider the instruction's operand requirements before
7175   // legalizing. Some operands are required to be SGPRs, such as implicit uses
7176   // of VCC, but we are still bound by the constant bus requirement to only use
7177   // one.
7178   //
7179   // If the operand's class is an SGPR, we can never move it.
7180 
7181   Register SGPRReg = findImplicitSGPRRead(MI);
7182   if (SGPRReg != AMDGPU::NoRegister)
7183     return SGPRReg;
7184 
7185   Register UsedSGPRs[3] = { AMDGPU::NoRegister };
7186   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7187 
7188   for (unsigned i = 0; i < 3; ++i) {
7189     int Idx = OpIndices[i];
7190     if (Idx == -1)
7191       break;
7192 
7193     const MachineOperand &MO = MI.getOperand(Idx);
7194     if (!MO.isReg())
7195       continue;
7196 
7197     // Is this operand statically required to be an SGPR based on the operand
7198     // constraints?
7199     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
7200     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
7201     if (IsRequiredSGPR)
7202       return MO.getReg();
7203 
7204     // If this could be a VGPR or an SGPR, Check the dynamic register class.
7205     Register Reg = MO.getReg();
7206     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
7207     if (RI.isSGPRClass(RegRC))
7208       UsedSGPRs[i] = Reg;
7209   }
7210 
7211   // We don't have a required SGPR operand, so we have a bit more freedom in
7212   // selecting operands to move.
7213 
7214   // Try to select the most used SGPR. If an SGPR is equal to one of the
7215   // others, we choose that.
7216   //
7217   // e.g.
7218   // V_FMA_F32 v0, s0, s0, s0 -> No moves
7219   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
7220 
7221   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
7222   // prefer those.
7223 
7224   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
7225     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
7226       SGPRReg = UsedSGPRs[0];
7227   }
7228 
7229   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
7230     if (UsedSGPRs[1] == UsedSGPRs[2])
7231       SGPRReg = UsedSGPRs[1];
7232   }
7233 
7234   return SGPRReg;
7235 }
7236 
7237 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
7238                                              unsigned OperandName) const {
7239   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
7240   if (Idx == -1)
7241     return nullptr;
7242 
7243   return &MI.getOperand(Idx);
7244 }
7245 
7246 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
7247   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
7248     return (AMDGPU::MTBUFFormat::UFMT_32_FLOAT << 44) |
7249            (1ULL << 56) | // RESOURCE_LEVEL = 1
7250            (3ULL << 60); // OOB_SELECT = 3
7251   }
7252 
7253   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
7254   if (ST.isAmdHsaOS()) {
7255     // Set ATC = 1. GFX9 doesn't have this bit.
7256     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7257       RsrcDataFormat |= (1ULL << 56);
7258 
7259     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
7260     // BTW, it disables TC L2 and therefore decreases performance.
7261     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
7262       RsrcDataFormat |= (2ULL << 59);
7263   }
7264 
7265   return RsrcDataFormat;
7266 }
7267 
7268 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
7269   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
7270                     AMDGPU::RSRC_TID_ENABLE |
7271                     0xffffffff; // Size;
7272 
7273   // GFX9 doesn't have ELEMENT_SIZE.
7274   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
7275     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
7276     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
7277   }
7278 
7279   // IndexStride = 64 / 32.
7280   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
7281   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
7282 
7283   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
7284   // Clear them unless we want a huge stride.
7285   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
7286       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
7287     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
7288 
7289   return Rsrc23;
7290 }
7291 
7292 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
7293   unsigned Opc = MI.getOpcode();
7294 
7295   return isSMRD(Opc);
7296 }
7297 
7298 bool SIInstrInfo::isHighLatencyDef(int Opc) const {
7299   return get(Opc).mayLoad() &&
7300          (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
7301 }
7302 
7303 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
7304                                     int &FrameIndex) const {
7305   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
7306   if (!Addr || !Addr->isFI())
7307     return AMDGPU::NoRegister;
7308 
7309   assert(!MI.memoperands_empty() &&
7310          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
7311 
7312   FrameIndex = Addr->getIndex();
7313   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
7314 }
7315 
7316 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
7317                                         int &FrameIndex) const {
7318   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
7319   assert(Addr && Addr->isFI());
7320   FrameIndex = Addr->getIndex();
7321   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
7322 }
7323 
7324 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
7325                                           int &FrameIndex) const {
7326   if (!MI.mayLoad())
7327     return AMDGPU::NoRegister;
7328 
7329   if (isMUBUF(MI) || isVGPRSpill(MI))
7330     return isStackAccess(MI, FrameIndex);
7331 
7332   if (isSGPRSpill(MI))
7333     return isSGPRStackAccess(MI, FrameIndex);
7334 
7335   return AMDGPU::NoRegister;
7336 }
7337 
7338 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
7339                                          int &FrameIndex) const {
7340   if (!MI.mayStore())
7341     return AMDGPU::NoRegister;
7342 
7343   if (isMUBUF(MI) || isVGPRSpill(MI))
7344     return isStackAccess(MI, FrameIndex);
7345 
7346   if (isSGPRSpill(MI))
7347     return isSGPRStackAccess(MI, FrameIndex);
7348 
7349   return AMDGPU::NoRegister;
7350 }
7351 
7352 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
7353   unsigned Size = 0;
7354   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
7355   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
7356   while (++I != E && I->isInsideBundle()) {
7357     assert(!I->isBundle() && "No nested bundle!");
7358     Size += getInstSizeInBytes(*I);
7359   }
7360 
7361   return Size;
7362 }
7363 
7364 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
7365   unsigned Opc = MI.getOpcode();
7366   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
7367   unsigned DescSize = Desc.getSize();
7368 
7369   // If we have a definitive size, we can use it. Otherwise we need to inspect
7370   // the operands to know the size.
7371   if (isFixedSize(MI)) {
7372     unsigned Size = DescSize;
7373 
7374     // If we hit the buggy offset, an extra nop will be inserted in MC so
7375     // estimate the worst case.
7376     if (MI.isBranch() && ST.hasOffset3fBug())
7377       Size += 4;
7378 
7379     return Size;
7380   }
7381 
7382   // Instructions may have a 32-bit literal encoded after them. Check
7383   // operands that could ever be literals.
7384   if (isVALU(MI) || isSALU(MI)) {
7385     if (isDPP(MI))
7386       return DescSize;
7387     bool HasLiteral = false;
7388     for (int I = 0, E = MI.getNumExplicitOperands(); I != E; ++I) {
7389       if (isLiteralConstant(MI, I)) {
7390         HasLiteral = true;
7391         break;
7392       }
7393     }
7394     return HasLiteral ? DescSize + 4 : DescSize;
7395   }
7396 
7397   // Check whether we have extra NSA words.
7398   if (isMIMG(MI)) {
7399     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
7400     if (VAddr0Idx < 0)
7401       return 8;
7402 
7403     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
7404     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
7405   }
7406 
7407   switch (Opc) {
7408   case TargetOpcode::BUNDLE:
7409     return getInstBundleSize(MI);
7410   case TargetOpcode::INLINEASM:
7411   case TargetOpcode::INLINEASM_BR: {
7412     const MachineFunction *MF = MI.getParent()->getParent();
7413     const char *AsmStr = MI.getOperand(0).getSymbolName();
7414     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(), &ST);
7415   }
7416   default:
7417     if (MI.isMetaInstruction())
7418       return 0;
7419     return DescSize;
7420   }
7421 }
7422 
7423 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
7424   if (!isFLAT(MI))
7425     return false;
7426 
7427   if (MI.memoperands_empty())
7428     return true;
7429 
7430   for (const MachineMemOperand *MMO : MI.memoperands()) {
7431     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
7432       return true;
7433   }
7434   return false;
7435 }
7436 
7437 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
7438   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
7439 }
7440 
7441 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
7442                                             MachineBasicBlock *IfEnd) const {
7443   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
7444   assert(TI != IfEntry->end());
7445 
7446   MachineInstr *Branch = &(*TI);
7447   MachineFunction *MF = IfEntry->getParent();
7448   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
7449 
7450   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7451     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7452     MachineInstr *SIIF =
7453         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
7454             .add(Branch->getOperand(0))
7455             .add(Branch->getOperand(1));
7456     MachineInstr *SIEND =
7457         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
7458             .addReg(DstReg);
7459 
7460     IfEntry->erase(TI);
7461     IfEntry->insert(IfEntry->end(), SIIF);
7462     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
7463   }
7464 }
7465 
7466 void SIInstrInfo::convertNonUniformLoopRegion(
7467     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
7468   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
7469   // We expect 2 terminators, one conditional and one unconditional.
7470   assert(TI != LoopEnd->end());
7471 
7472   MachineInstr *Branch = &(*TI);
7473   MachineFunction *MF = LoopEnd->getParent();
7474   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
7475 
7476   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7477 
7478     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7479     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
7480     MachineInstrBuilder HeaderPHIBuilder =
7481         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
7482     for (MachineBasicBlock *PMBB : LoopEntry->predecessors()) {
7483       if (PMBB == LoopEnd) {
7484         HeaderPHIBuilder.addReg(BackEdgeReg);
7485       } else {
7486         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
7487         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
7488                              ZeroReg, 0);
7489         HeaderPHIBuilder.addReg(ZeroReg);
7490       }
7491       HeaderPHIBuilder.addMBB(PMBB);
7492     }
7493     MachineInstr *HeaderPhi = HeaderPHIBuilder;
7494     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
7495                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
7496                                   .addReg(DstReg)
7497                                   .add(Branch->getOperand(0));
7498     MachineInstr *SILOOP =
7499         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
7500             .addReg(BackEdgeReg)
7501             .addMBB(LoopEntry);
7502 
7503     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
7504     LoopEnd->erase(TI);
7505     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
7506     LoopEnd->insert(LoopEnd->end(), SILOOP);
7507   }
7508 }
7509 
7510 ArrayRef<std::pair<int, const char *>>
7511 SIInstrInfo::getSerializableTargetIndices() const {
7512   static const std::pair<int, const char *> TargetIndices[] = {
7513       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
7514       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
7515       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
7516       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
7517       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
7518   return makeArrayRef(TargetIndices);
7519 }
7520 
7521 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
7522 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
7523 ScheduleHazardRecognizer *
7524 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
7525                                             const ScheduleDAG *DAG) const {
7526   return new GCNHazardRecognizer(DAG->MF);
7527 }
7528 
7529 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
7530 /// pass.
7531 ScheduleHazardRecognizer *
7532 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
7533   return new GCNHazardRecognizer(MF);
7534 }
7535 
7536 // Called during:
7537 // - pre-RA scheduling and post-RA scheduling
7538 ScheduleHazardRecognizer *
7539 SIInstrInfo::CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
7540                                             const ScheduleDAGMI *DAG) const {
7541   // Borrowed from Arm Target
7542   // We would like to restrict this hazard recognizer to only
7543   // post-RA scheduling; we can tell that we're post-RA because we don't
7544   // track VRegLiveness.
7545   if (!DAG->hasVRegLiveness())
7546     return new GCNHazardRecognizer(DAG->MF);
7547   return TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
7548 }
7549 
7550 std::pair<unsigned, unsigned>
7551 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7552   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
7553 }
7554 
7555 ArrayRef<std::pair<unsigned, const char *>>
7556 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7557   static const std::pair<unsigned, const char *> TargetFlags[] = {
7558     { MO_GOTPCREL, "amdgpu-gotprel" },
7559     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
7560     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
7561     { MO_REL32_LO, "amdgpu-rel32-lo" },
7562     { MO_REL32_HI, "amdgpu-rel32-hi" },
7563     { MO_ABS32_LO, "amdgpu-abs32-lo" },
7564     { MO_ABS32_HI, "amdgpu-abs32-hi" },
7565   };
7566 
7567   return makeArrayRef(TargetFlags);
7568 }
7569 
7570 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
7571   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
7572          MI.modifiesRegister(AMDGPU::EXEC, &RI);
7573 }
7574 
7575 MachineInstrBuilder
7576 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7577                            MachineBasicBlock::iterator I,
7578                            const DebugLoc &DL,
7579                            Register DestReg) const {
7580   if (ST.hasAddNoCarry())
7581     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
7582 
7583   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7584   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
7585   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
7586 
7587   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7588            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7589 }
7590 
7591 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7592                                                MachineBasicBlock::iterator I,
7593                                                const DebugLoc &DL,
7594                                                Register DestReg,
7595                                                RegScavenger &RS) const {
7596   if (ST.hasAddNoCarry())
7597     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
7598 
7599   // If available, prefer to use vcc.
7600   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
7601                              ? Register(RI.getVCC())
7602                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
7603 
7604   // TODO: Users need to deal with this.
7605   if (!UnusedCarry.isValid())
7606     return MachineInstrBuilder();
7607 
7608   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7609            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7610 }
7611 
7612 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
7613   switch (Opcode) {
7614   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
7615   case AMDGPU::SI_KILL_I1_TERMINATOR:
7616     return true;
7617   default:
7618     return false;
7619   }
7620 }
7621 
7622 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
7623   switch (Opcode) {
7624   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7625     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
7626   case AMDGPU::SI_KILL_I1_PSEUDO:
7627     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
7628   default:
7629     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
7630   }
7631 }
7632 
7633 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
7634   if (!ST.isWave32())
7635     return;
7636 
7637   for (auto &Op : MI.implicit_operands()) {
7638     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
7639       Op.setReg(AMDGPU::VCC_LO);
7640   }
7641 }
7642 
7643 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
7644   if (!isSMRD(MI))
7645     return false;
7646 
7647   // Check that it is using a buffer resource.
7648   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
7649   if (Idx == -1) // e.g. s_memtime
7650     return false;
7651 
7652   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
7653   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
7654 }
7655 
7656 // Depending on the used address space and instructions, some immediate offsets
7657 // are allowed and some are not.
7658 // In general, flat instruction offsets can only be non-negative, global and
7659 // scratch instruction offsets can also be negative.
7660 //
7661 // There are several bugs related to these offsets:
7662 // On gfx10.1, flat instructions that go into the global address space cannot
7663 // use an offset.
7664 //
7665 // For scratch instructions, the address can be either an SGPR or a VGPR.
7666 // The following offsets can be used, depending on the architecture (x means
7667 // cannot be used):
7668 // +----------------------------+------+------+
7669 // | Address-Mode               | SGPR | VGPR |
7670 // +----------------------------+------+------+
7671 // | gfx9                       |      |      |
7672 // | negative, 4-aligned offset | x    | ok   |
7673 // | negative, unaligned offset | x    | ok   |
7674 // +----------------------------+------+------+
7675 // | gfx10                      |      |      |
7676 // | negative, 4-aligned offset | ok   | ok   |
7677 // | negative, unaligned offset | ok   | x    |
7678 // +----------------------------+------+------+
7679 // | gfx10.3                    |      |      |
7680 // | negative, 4-aligned offset | ok   | ok   |
7681 // | negative, unaligned offset | ok   | ok   |
7682 // +----------------------------+------+------+
7683 //
7684 // This function ignores the addressing mode, so if an offset cannot be used in
7685 // one addressing mode, it is considered illegal.
7686 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
7687                                     uint64_t FlatVariant) const {
7688   // TODO: Should 0 be special cased?
7689   if (!ST.hasFlatInstOffsets())
7690     return false;
7691 
7692   if (ST.hasFlatSegmentOffsetBug() && FlatVariant == SIInstrFlags::FLAT &&
7693       (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
7694        AddrSpace == AMDGPUAS::GLOBAL_ADDRESS))
7695     return false;
7696 
7697   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7698   if (ST.hasNegativeScratchOffsetBug() &&
7699       FlatVariant == SIInstrFlags::FlatScratch)
7700     Signed = false;
7701   if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7702       FlatVariant == SIInstrFlags::FlatScratch && Offset < 0 &&
7703       (Offset % 4) != 0) {
7704     return false;
7705   }
7706 
7707   unsigned N = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7708   return Signed ? isIntN(N, Offset) : isUIntN(N, Offset);
7709 }
7710 
7711 // See comment on SIInstrInfo::isLegalFLATOffset for what is legal and what not.
7712 std::pair<int64_t, int64_t>
7713 SIInstrInfo::splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace,
7714                              uint64_t FlatVariant) const {
7715   int64_t RemainderOffset = COffsetVal;
7716   int64_t ImmField = 0;
7717   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7718   if (ST.hasNegativeScratchOffsetBug() &&
7719       FlatVariant == SIInstrFlags::FlatScratch)
7720     Signed = false;
7721 
7722   const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7723   if (Signed) {
7724     // Use signed division by a power of two to truncate towards 0.
7725     int64_t D = 1LL << (NumBits - 1);
7726     RemainderOffset = (COffsetVal / D) * D;
7727     ImmField = COffsetVal - RemainderOffset;
7728 
7729     if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7730         FlatVariant == SIInstrFlags::FlatScratch && ImmField < 0 &&
7731         (ImmField % 4) != 0) {
7732       // Make ImmField a multiple of 4
7733       RemainderOffset += ImmField % 4;
7734       ImmField -= ImmField % 4;
7735     }
7736   } else if (COffsetVal >= 0) {
7737     ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
7738     RemainderOffset = COffsetVal - ImmField;
7739   }
7740 
7741   assert(isLegalFLATOffset(ImmField, AddrSpace, FlatVariant));
7742   assert(RemainderOffset + ImmField == COffsetVal);
7743   return {ImmField, RemainderOffset};
7744 }
7745 
7746 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
7747 enum SIEncodingFamily {
7748   SI = 0,
7749   VI = 1,
7750   SDWA = 2,
7751   SDWA9 = 3,
7752   GFX80 = 4,
7753   GFX9 = 5,
7754   GFX10 = 6,
7755   SDWA10 = 7,
7756   GFX90A = 8
7757 };
7758 
7759 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
7760   switch (ST.getGeneration()) {
7761   default:
7762     break;
7763   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
7764   case AMDGPUSubtarget::SEA_ISLANDS:
7765     return SIEncodingFamily::SI;
7766   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
7767   case AMDGPUSubtarget::GFX9:
7768     return SIEncodingFamily::VI;
7769   case AMDGPUSubtarget::GFX10:
7770     return SIEncodingFamily::GFX10;
7771   }
7772   llvm_unreachable("Unknown subtarget generation!");
7773 }
7774 
7775 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
7776   switch(MCOp) {
7777   // These opcodes use indirect register addressing so
7778   // they need special handling by codegen (currently missing).
7779   // Therefore it is too risky to allow these opcodes
7780   // to be selected by dpp combiner or sdwa peepholer.
7781   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
7782   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
7783   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
7784   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
7785   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
7786   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
7787   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
7788   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
7789     return true;
7790   default:
7791     return false;
7792   }
7793 }
7794 
7795 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
7796   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
7797 
7798   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
7799     ST.getGeneration() == AMDGPUSubtarget::GFX9)
7800     Gen = SIEncodingFamily::GFX9;
7801 
7802   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
7803   // subtarget has UnpackedD16VMem feature.
7804   // TODO: remove this when we discard GFX80 encoding.
7805   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
7806     Gen = SIEncodingFamily::GFX80;
7807 
7808   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
7809     switch (ST.getGeneration()) {
7810     default:
7811       Gen = SIEncodingFamily::SDWA;
7812       break;
7813     case AMDGPUSubtarget::GFX9:
7814       Gen = SIEncodingFamily::SDWA9;
7815       break;
7816     case AMDGPUSubtarget::GFX10:
7817       Gen = SIEncodingFamily::SDWA10;
7818       break;
7819     }
7820   }
7821 
7822   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
7823 
7824   // -1 means that Opcode is already a native instruction.
7825   if (MCOp == -1)
7826     return Opcode;
7827 
7828   if (ST.hasGFX90AInsts()) {
7829     uint16_t NMCOp = (uint16_t)-1;
7830       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX90A);
7831     if (NMCOp == (uint16_t)-1)
7832       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX9);
7833     if (NMCOp != (uint16_t)-1)
7834       MCOp = NMCOp;
7835   }
7836 
7837   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
7838   // no encoding in the given subtarget generation.
7839   if (MCOp == (uint16_t)-1)
7840     return -1;
7841 
7842   if (isAsmOnlyOpcode(MCOp))
7843     return -1;
7844 
7845   return MCOp;
7846 }
7847 
7848 static
7849 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
7850   assert(RegOpnd.isReg());
7851   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
7852                              getRegSubRegPair(RegOpnd);
7853 }
7854 
7855 TargetInstrInfo::RegSubRegPair
7856 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
7857   assert(MI.isRegSequence());
7858   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
7859     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
7860       auto &RegOp = MI.getOperand(1 + 2 * I);
7861       return getRegOrUndef(RegOp);
7862     }
7863   return TargetInstrInfo::RegSubRegPair();
7864 }
7865 
7866 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
7867 // Following a subreg of reg:subreg isn't supported
7868 static bool followSubRegDef(MachineInstr &MI,
7869                             TargetInstrInfo::RegSubRegPair &RSR) {
7870   if (!RSR.SubReg)
7871     return false;
7872   switch (MI.getOpcode()) {
7873   default: break;
7874   case AMDGPU::REG_SEQUENCE:
7875     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
7876     return true;
7877   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
7878   case AMDGPU::INSERT_SUBREG:
7879     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
7880       // inserted the subreg we're looking for
7881       RSR = getRegOrUndef(MI.getOperand(2));
7882     else { // the subreg in the rest of the reg
7883       auto R1 = getRegOrUndef(MI.getOperand(1));
7884       if (R1.SubReg) // subreg of subreg isn't supported
7885         return false;
7886       RSR.Reg = R1.Reg;
7887     }
7888     return true;
7889   }
7890   return false;
7891 }
7892 
7893 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
7894                                      MachineRegisterInfo &MRI) {
7895   assert(MRI.isSSA());
7896   if (!P.Reg.isVirtual())
7897     return nullptr;
7898 
7899   auto RSR = P;
7900   auto *DefInst = MRI.getVRegDef(RSR.Reg);
7901   while (auto *MI = DefInst) {
7902     DefInst = nullptr;
7903     switch (MI->getOpcode()) {
7904     case AMDGPU::COPY:
7905     case AMDGPU::V_MOV_B32_e32: {
7906       auto &Op1 = MI->getOperand(1);
7907       if (Op1.isReg() && Op1.getReg().isVirtual()) {
7908         if (Op1.isUndef())
7909           return nullptr;
7910         RSR = getRegSubRegPair(Op1);
7911         DefInst = MRI.getVRegDef(RSR.Reg);
7912       }
7913       break;
7914     }
7915     default:
7916       if (followSubRegDef(*MI, RSR)) {
7917         if (!RSR.Reg)
7918           return nullptr;
7919         DefInst = MRI.getVRegDef(RSR.Reg);
7920       }
7921     }
7922     if (!DefInst)
7923       return MI;
7924   }
7925   return nullptr;
7926 }
7927 
7928 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
7929                                       Register VReg,
7930                                       const MachineInstr &DefMI,
7931                                       const MachineInstr &UseMI) {
7932   assert(MRI.isSSA() && "Must be run on SSA");
7933 
7934   auto *TRI = MRI.getTargetRegisterInfo();
7935   auto *DefBB = DefMI.getParent();
7936 
7937   // Don't bother searching between blocks, although it is possible this block
7938   // doesn't modify exec.
7939   if (UseMI.getParent() != DefBB)
7940     return true;
7941 
7942   const int MaxInstScan = 20;
7943   int NumInst = 0;
7944 
7945   // Stop scan at the use.
7946   auto E = UseMI.getIterator();
7947   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
7948     if (I->isDebugInstr())
7949       continue;
7950 
7951     if (++NumInst > MaxInstScan)
7952       return true;
7953 
7954     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
7955       return true;
7956   }
7957 
7958   return false;
7959 }
7960 
7961 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
7962                                          Register VReg,
7963                                          const MachineInstr &DefMI) {
7964   assert(MRI.isSSA() && "Must be run on SSA");
7965 
7966   auto *TRI = MRI.getTargetRegisterInfo();
7967   auto *DefBB = DefMI.getParent();
7968 
7969   const int MaxUseScan = 10;
7970   int NumUse = 0;
7971 
7972   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
7973     auto &UseInst = *Use.getParent();
7974     // Don't bother searching between blocks, although it is possible this block
7975     // doesn't modify exec.
7976     if (UseInst.getParent() != DefBB)
7977       return true;
7978 
7979     if (++NumUse > MaxUseScan)
7980       return true;
7981   }
7982 
7983   if (NumUse == 0)
7984     return false;
7985 
7986   const int MaxInstScan = 20;
7987   int NumInst = 0;
7988 
7989   // Stop scan when we have seen all the uses.
7990   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
7991     assert(I != DefBB->end());
7992 
7993     if (I->isDebugInstr())
7994       continue;
7995 
7996     if (++NumInst > MaxInstScan)
7997       return true;
7998 
7999     for (const MachineOperand &Op : I->operands()) {
8000       // We don't check reg masks here as they're used only on calls:
8001       // 1. EXEC is only considered const within one BB
8002       // 2. Call should be a terminator instruction if present in a BB
8003 
8004       if (!Op.isReg())
8005         continue;
8006 
8007       Register Reg = Op.getReg();
8008       if (Op.isUse()) {
8009         if (Reg == VReg && --NumUse == 0)
8010           return false;
8011       } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
8012         return true;
8013     }
8014   }
8015 }
8016 
8017 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
8018     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
8019     const DebugLoc &DL, Register Src, Register Dst) const {
8020   auto Cur = MBB.begin();
8021   if (Cur != MBB.end())
8022     do {
8023       if (!Cur->isPHI() && Cur->readsRegister(Dst))
8024         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
8025       ++Cur;
8026     } while (Cur != MBB.end() && Cur != LastPHIIt);
8027 
8028   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
8029                                                    Dst);
8030 }
8031 
8032 MachineInstr *SIInstrInfo::createPHISourceCopy(
8033     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
8034     const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
8035   if (InsPt != MBB.end() &&
8036       (InsPt->getOpcode() == AMDGPU::SI_IF ||
8037        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
8038        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
8039       InsPt->definesRegister(Src)) {
8040     InsPt++;
8041     return BuildMI(MBB, InsPt, DL,
8042                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
8043                                      : AMDGPU::S_MOV_B64_term),
8044                    Dst)
8045         .addReg(Src, 0, SrcSubReg)
8046         .addReg(AMDGPU::EXEC, RegState::Implicit);
8047   }
8048   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
8049                                               Dst);
8050 }
8051 
8052 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
8053 
8054 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
8055     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
8056     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
8057     VirtRegMap *VRM) const {
8058   // This is a bit of a hack (copied from AArch64). Consider this instruction:
8059   //
8060   //   %0:sreg_32 = COPY $m0
8061   //
8062   // We explicitly chose SReg_32 for the virtual register so such a copy might
8063   // be eliminated by RegisterCoalescer. However, that may not be possible, and
8064   // %0 may even spill. We can't spill $m0 normally (it would require copying to
8065   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
8066   // TargetInstrInfo::foldMemoryOperand() is going to try.
8067   // A similar issue also exists with spilling and reloading $exec registers.
8068   //
8069   // To prevent that, constrain the %0 register class here.
8070   if (MI.isFullCopy()) {
8071     Register DstReg = MI.getOperand(0).getReg();
8072     Register SrcReg = MI.getOperand(1).getReg();
8073     if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
8074         (DstReg.isVirtual() != SrcReg.isVirtual())) {
8075       MachineRegisterInfo &MRI = MF.getRegInfo();
8076       Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
8077       const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
8078       if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
8079         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
8080         return nullptr;
8081       } else if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
8082         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
8083         return nullptr;
8084       }
8085     }
8086   }
8087 
8088   return nullptr;
8089 }
8090 
8091 unsigned SIInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
8092                                       const MachineInstr &MI,
8093                                       unsigned *PredCost) const {
8094   if (MI.isBundle()) {
8095     MachineBasicBlock::const_instr_iterator I(MI.getIterator());
8096     MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
8097     unsigned Lat = 0, Count = 0;
8098     for (++I; I != E && I->isBundledWithPred(); ++I) {
8099       ++Count;
8100       Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
8101     }
8102     return Lat + Count - 1;
8103   }
8104 
8105   return SchedModel.computeInstrLatency(&MI);
8106 }
8107 
8108 unsigned SIInstrInfo::getDSShaderTypeValue(const MachineFunction &MF) {
8109   switch (MF.getFunction().getCallingConv()) {
8110   case CallingConv::AMDGPU_PS:
8111     return 1;
8112   case CallingConv::AMDGPU_VS:
8113     return 2;
8114   case CallingConv::AMDGPU_GS:
8115     return 3;
8116   case CallingConv::AMDGPU_HS:
8117   case CallingConv::AMDGPU_LS:
8118   case CallingConv::AMDGPU_ES:
8119     report_fatal_error("ds_ordered_count unsupported for this calling conv");
8120   case CallingConv::AMDGPU_CS:
8121   case CallingConv::AMDGPU_KERNEL:
8122   case CallingConv::C:
8123   case CallingConv::Fast:
8124   default:
8125     // Assume other calling conventions are various compute callable functions
8126     return 0;
8127   }
8128 }
8129 
8130 bool SIInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
8131                                  Register &SrcReg2, int64_t &CmpMask,
8132                                  int64_t &CmpValue) const {
8133   if (!MI.getOperand(0).isReg() || MI.getOperand(0).getSubReg())
8134     return false;
8135 
8136   switch (MI.getOpcode()) {
8137   default:
8138     break;
8139   case AMDGPU::S_CMP_EQ_U32:
8140   case AMDGPU::S_CMP_EQ_I32:
8141   case AMDGPU::S_CMP_LG_U32:
8142   case AMDGPU::S_CMP_LG_I32:
8143   case AMDGPU::S_CMP_LT_U32:
8144   case AMDGPU::S_CMP_LT_I32:
8145   case AMDGPU::S_CMP_GT_U32:
8146   case AMDGPU::S_CMP_GT_I32:
8147   case AMDGPU::S_CMP_LE_U32:
8148   case AMDGPU::S_CMP_LE_I32:
8149   case AMDGPU::S_CMP_GE_U32:
8150   case AMDGPU::S_CMP_GE_I32:
8151   case AMDGPU::S_CMP_EQ_U64:
8152   case AMDGPU::S_CMP_LG_U64:
8153     SrcReg = MI.getOperand(0).getReg();
8154     if (MI.getOperand(1).isReg()) {
8155       if (MI.getOperand(1).getSubReg())
8156         return false;
8157       SrcReg2 = MI.getOperand(1).getReg();
8158       CmpValue = 0;
8159     } else if (MI.getOperand(1).isImm()) {
8160       SrcReg2 = Register();
8161       CmpValue = MI.getOperand(1).getImm();
8162     } else {
8163       return false;
8164     }
8165     CmpMask = ~0;
8166     return true;
8167   case AMDGPU::S_CMPK_EQ_U32:
8168   case AMDGPU::S_CMPK_EQ_I32:
8169   case AMDGPU::S_CMPK_LG_U32:
8170   case AMDGPU::S_CMPK_LG_I32:
8171   case AMDGPU::S_CMPK_LT_U32:
8172   case AMDGPU::S_CMPK_LT_I32:
8173   case AMDGPU::S_CMPK_GT_U32:
8174   case AMDGPU::S_CMPK_GT_I32:
8175   case AMDGPU::S_CMPK_LE_U32:
8176   case AMDGPU::S_CMPK_LE_I32:
8177   case AMDGPU::S_CMPK_GE_U32:
8178   case AMDGPU::S_CMPK_GE_I32:
8179     SrcReg = MI.getOperand(0).getReg();
8180     SrcReg2 = Register();
8181     CmpValue = MI.getOperand(1).getImm();
8182     CmpMask = ~0;
8183     return true;
8184   }
8185 
8186   return false;
8187 }
8188 
8189 bool SIInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
8190                                        Register SrcReg2, int64_t CmpMask,
8191                                        int64_t CmpValue,
8192                                        const MachineRegisterInfo *MRI) const {
8193   if (!SrcReg || SrcReg.isPhysical())
8194     return false;
8195 
8196   if (SrcReg2 && !getFoldableImm(SrcReg2, *MRI, CmpValue))
8197     return false;
8198 
8199   const auto optimizeCmpAnd = [&CmpInstr, SrcReg, CmpValue, MRI,
8200                                this](int64_t ExpectedValue, unsigned SrcSize,
8201                                      bool IsReversable, bool IsSigned) -> bool {
8202     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8203     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8204     // s_cmp_ge_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8205     // s_cmp_ge_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8206     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 1 << n => s_and_b64 $src, 1 << n
8207     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8208     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8209     // s_cmp_gt_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8210     // s_cmp_gt_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8211     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 0 => s_and_b64 $src, 1 << n
8212     //
8213     // Signed ge/gt are not used for the sign bit.
8214     //
8215     // If result of the AND is unused except in the compare:
8216     // s_and_b(32|64) $src, 1 << n => s_bitcmp1_b(32|64) $src, n
8217     //
8218     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8219     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8220     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 0 => s_bitcmp0_b64 $src, n
8221     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8222     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8223     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 1 << n => s_bitcmp0_b64 $src, n
8224 
8225     MachineInstr *Def = MRI->getUniqueVRegDef(SrcReg);
8226     if (!Def || Def->getParent() != CmpInstr.getParent())
8227       return false;
8228 
8229     if (Def->getOpcode() != AMDGPU::S_AND_B32 &&
8230         Def->getOpcode() != AMDGPU::S_AND_B64)
8231       return false;
8232 
8233     int64_t Mask;
8234     const auto isMask = [&Mask, SrcSize](const MachineOperand *MO) -> bool {
8235       if (MO->isImm())
8236         Mask = MO->getImm();
8237       else if (!getFoldableImm(MO, Mask))
8238         return false;
8239       Mask &= maxUIntN(SrcSize);
8240       return isPowerOf2_64(Mask);
8241     };
8242 
8243     MachineOperand *SrcOp = &Def->getOperand(1);
8244     if (isMask(SrcOp))
8245       SrcOp = &Def->getOperand(2);
8246     else if (isMask(&Def->getOperand(2)))
8247       SrcOp = &Def->getOperand(1);
8248     else
8249       return false;
8250 
8251     unsigned BitNo = countTrailingZeros((uint64_t)Mask);
8252     if (IsSigned && BitNo == SrcSize - 1)
8253       return false;
8254 
8255     ExpectedValue <<= BitNo;
8256 
8257     bool IsReversedCC = false;
8258     if (CmpValue != ExpectedValue) {
8259       if (!IsReversable)
8260         return false;
8261       IsReversedCC = CmpValue == (ExpectedValue ^ Mask);
8262       if (!IsReversedCC)
8263         return false;
8264     }
8265 
8266     Register DefReg = Def->getOperand(0).getReg();
8267     if (IsReversedCC && !MRI->hasOneNonDBGUse(DefReg))
8268       return false;
8269 
8270     for (auto I = std::next(Def->getIterator()), E = CmpInstr.getIterator();
8271          I != E; ++I) {
8272       if (I->modifiesRegister(AMDGPU::SCC, &RI) ||
8273           I->killsRegister(AMDGPU::SCC, &RI))
8274         return false;
8275     }
8276 
8277     MachineOperand *SccDef = Def->findRegisterDefOperand(AMDGPU::SCC);
8278     SccDef->setIsDead(false);
8279     CmpInstr.eraseFromParent();
8280 
8281     if (!MRI->use_nodbg_empty(DefReg)) {
8282       assert(!IsReversedCC);
8283       return true;
8284     }
8285 
8286     // Replace AND with unused result with a S_BITCMP.
8287     MachineBasicBlock *MBB = Def->getParent();
8288 
8289     unsigned NewOpc = (SrcSize == 32) ? IsReversedCC ? AMDGPU::S_BITCMP0_B32
8290                                                      : AMDGPU::S_BITCMP1_B32
8291                                       : IsReversedCC ? AMDGPU::S_BITCMP0_B64
8292                                                      : AMDGPU::S_BITCMP1_B64;
8293 
8294     BuildMI(*MBB, Def, Def->getDebugLoc(), get(NewOpc))
8295       .add(*SrcOp)
8296       .addImm(BitNo);
8297     Def->eraseFromParent();
8298 
8299     return true;
8300   };
8301 
8302   switch (CmpInstr.getOpcode()) {
8303   default:
8304     break;
8305   case AMDGPU::S_CMP_EQ_U32:
8306   case AMDGPU::S_CMP_EQ_I32:
8307   case AMDGPU::S_CMPK_EQ_U32:
8308   case AMDGPU::S_CMPK_EQ_I32:
8309     return optimizeCmpAnd(1, 32, true, false);
8310   case AMDGPU::S_CMP_GE_U32:
8311   case AMDGPU::S_CMPK_GE_U32:
8312     return optimizeCmpAnd(1, 32, false, false);
8313   case AMDGPU::S_CMP_GE_I32:
8314   case AMDGPU::S_CMPK_GE_I32:
8315     return optimizeCmpAnd(1, 32, false, true);
8316   case AMDGPU::S_CMP_EQ_U64:
8317     return optimizeCmpAnd(1, 64, true, false);
8318   case AMDGPU::S_CMP_LG_U32:
8319   case AMDGPU::S_CMP_LG_I32:
8320   case AMDGPU::S_CMPK_LG_U32:
8321   case AMDGPU::S_CMPK_LG_I32:
8322     return optimizeCmpAnd(0, 32, true, false);
8323   case AMDGPU::S_CMP_GT_U32:
8324   case AMDGPU::S_CMPK_GT_U32:
8325     return optimizeCmpAnd(0, 32, false, false);
8326   case AMDGPU::S_CMP_GT_I32:
8327   case AMDGPU::S_CMPK_GT_I32:
8328     return optimizeCmpAnd(0, 32, false, true);
8329   case AMDGPU::S_CMP_LG_U64:
8330     return optimizeCmpAnd(0, 64, true, false);
8331   }
8332 
8333   return false;
8334 }
8335