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