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