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