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