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