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 (int Idx : VOP3Idx) {
5055     if (Idx == -1)
5056       break;
5057     MachineOperand &MO = MI.getOperand(Idx);
5058 
5059     if (!MO.isReg()) {
5060       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
5061         continue;
5062 
5063       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
5064         --LiteralLimit;
5065         --ConstantBusLimit;
5066         continue;
5067       }
5068 
5069       --LiteralLimit;
5070       --ConstantBusLimit;
5071       legalizeOpWithMove(MI, Idx);
5072       continue;
5073     }
5074 
5075     if (RI.hasAGPRs(RI.getRegClassForReg(MRI, MO.getReg())) &&
5076         !isOperandLegal(MI, Idx, &MO)) {
5077       legalizeOpWithMove(MI, Idx);
5078       continue;
5079     }
5080 
5081     if (!RI.isSGPRClass(RI.getRegClassForReg(MRI, MO.getReg())))
5082       continue; // VGPRs are legal
5083 
5084     // We can use one SGPR in each VOP3 instruction prior to GFX10
5085     // and two starting from GFX10.
5086     if (SGPRsUsed.count(MO.getReg()))
5087       continue;
5088     if (ConstantBusLimit > 0) {
5089       SGPRsUsed.insert(MO.getReg());
5090       --ConstantBusLimit;
5091       continue;
5092     }
5093 
5094     // If we make it this far, then the operand is not legal and we must
5095     // legalize it.
5096     legalizeOpWithMove(MI, Idx);
5097   }
5098 }
5099 
5100 Register SIInstrInfo::readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI,
5101                                          MachineRegisterInfo &MRI) const {
5102   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
5103   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
5104   Register DstReg = MRI.createVirtualRegister(SRC);
5105   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
5106 
5107   if (RI.hasAGPRs(VRC)) {
5108     VRC = RI.getEquivalentVGPRClass(VRC);
5109     Register NewSrcReg = MRI.createVirtualRegister(VRC);
5110     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5111             get(TargetOpcode::COPY), NewSrcReg)
5112         .addReg(SrcReg);
5113     SrcReg = NewSrcReg;
5114   }
5115 
5116   if (SubRegs == 1) {
5117     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5118             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
5119         .addReg(SrcReg);
5120     return DstReg;
5121   }
5122 
5123   SmallVector<unsigned, 8> SRegs;
5124   for (unsigned i = 0; i < SubRegs; ++i) {
5125     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5126     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5127             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
5128         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
5129     SRegs.push_back(SGPR);
5130   }
5131 
5132   MachineInstrBuilder MIB =
5133       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5134               get(AMDGPU::REG_SEQUENCE), DstReg);
5135   for (unsigned i = 0; i < SubRegs; ++i) {
5136     MIB.addReg(SRegs[i]);
5137     MIB.addImm(RI.getSubRegFromChannel(i));
5138   }
5139   return DstReg;
5140 }
5141 
5142 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
5143                                        MachineInstr &MI) const {
5144 
5145   // If the pointer is store in VGPRs, then we need to move them to
5146   // SGPRs using v_readfirstlane.  This is safe because we only select
5147   // loads with uniform pointers to SMRD instruction so we know the
5148   // pointer value is uniform.
5149   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
5150   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
5151     Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
5152     SBase->setReg(SGPR);
5153   }
5154   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
5155   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
5156     Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
5157     SOff->setReg(SGPR);
5158   }
5159 }
5160 
5161 bool SIInstrInfo::moveFlatAddrToVGPR(MachineInstr &Inst) const {
5162   unsigned Opc = Inst.getOpcode();
5163   int OldSAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
5164   if (OldSAddrIdx < 0)
5165     return false;
5166 
5167   assert(isSegmentSpecificFLAT(Inst));
5168 
5169   int NewOpc = AMDGPU::getGlobalVaddrOp(Opc);
5170   if (NewOpc < 0)
5171     NewOpc = AMDGPU::getFlatScratchInstSVfromSS(Opc);
5172   if (NewOpc < 0)
5173     return false;
5174 
5175   MachineRegisterInfo &MRI = Inst.getMF()->getRegInfo();
5176   MachineOperand &SAddr = Inst.getOperand(OldSAddrIdx);
5177   if (RI.isSGPRReg(MRI, SAddr.getReg()))
5178     return false;
5179 
5180   int NewVAddrIdx = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vaddr);
5181   if (NewVAddrIdx < 0)
5182     return false;
5183 
5184   int OldVAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
5185 
5186   // Check vaddr, it shall be zero or absent.
5187   MachineInstr *VAddrDef = nullptr;
5188   if (OldVAddrIdx >= 0) {
5189     MachineOperand &VAddr = Inst.getOperand(OldVAddrIdx);
5190     VAddrDef = MRI.getUniqueVRegDef(VAddr.getReg());
5191     if (!VAddrDef || VAddrDef->getOpcode() != AMDGPU::V_MOV_B32_e32 ||
5192         !VAddrDef->getOperand(1).isImm() ||
5193         VAddrDef->getOperand(1).getImm() != 0)
5194       return false;
5195   }
5196 
5197   const MCInstrDesc &NewDesc = get(NewOpc);
5198   Inst.setDesc(NewDesc);
5199 
5200   // Callers expect interator to be valid after this call, so modify the
5201   // instruction in place.
5202   if (OldVAddrIdx == NewVAddrIdx) {
5203     MachineOperand &NewVAddr = Inst.getOperand(NewVAddrIdx);
5204     // Clear use list from the old vaddr holding a zero register.
5205     MRI.removeRegOperandFromUseList(&NewVAddr);
5206     MRI.moveOperands(&NewVAddr, &SAddr, 1);
5207     Inst.RemoveOperand(OldSAddrIdx);
5208     // Update the use list with the pointer we have just moved from vaddr to
5209     // saddr poisition. Otherwise new vaddr will be missing from the use list.
5210     MRI.removeRegOperandFromUseList(&NewVAddr);
5211     MRI.addRegOperandToUseList(&NewVAddr);
5212   } else {
5213     assert(OldSAddrIdx == NewVAddrIdx);
5214 
5215     if (OldVAddrIdx >= 0) {
5216       int NewVDstIn = AMDGPU::getNamedOperandIdx(NewOpc,
5217                                                  AMDGPU::OpName::vdst_in);
5218 
5219       // RemoveOperand doesn't try to fixup tied operand indexes at it goes, so
5220       // it asserts. Untie the operands for now and retie them afterwards.
5221       if (NewVDstIn != -1) {
5222         int OldVDstIn = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
5223         Inst.untieRegOperand(OldVDstIn);
5224       }
5225 
5226       Inst.RemoveOperand(OldVAddrIdx);
5227 
5228       if (NewVDstIn != -1) {
5229         int NewVDst = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vdst);
5230         Inst.tieOperands(NewVDst, NewVDstIn);
5231       }
5232     }
5233   }
5234 
5235   if (VAddrDef && MRI.use_nodbg_empty(VAddrDef->getOperand(0).getReg()))
5236     VAddrDef->eraseFromParent();
5237 
5238   return true;
5239 }
5240 
5241 // FIXME: Remove this when SelectionDAG is obsoleted.
5242 void SIInstrInfo::legalizeOperandsFLAT(MachineRegisterInfo &MRI,
5243                                        MachineInstr &MI) const {
5244   if (!isSegmentSpecificFLAT(MI))
5245     return;
5246 
5247   // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
5248   // thinks they are uniform, so a readfirstlane should be valid.
5249   MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
5250   if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
5251     return;
5252 
5253   if (moveFlatAddrToVGPR(MI))
5254     return;
5255 
5256   Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI);
5257   SAddr->setReg(ToSGPR);
5258 }
5259 
5260 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
5261                                          MachineBasicBlock::iterator I,
5262                                          const TargetRegisterClass *DstRC,
5263                                          MachineOperand &Op,
5264                                          MachineRegisterInfo &MRI,
5265                                          const DebugLoc &DL) const {
5266   Register OpReg = Op.getReg();
5267   unsigned OpSubReg = Op.getSubReg();
5268 
5269   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
5270       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
5271 
5272   // Check if operand is already the correct register class.
5273   if (DstRC == OpRC)
5274     return;
5275 
5276   Register DstReg = MRI.createVirtualRegister(DstRC);
5277   auto Copy = BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
5278 
5279   Op.setReg(DstReg);
5280   Op.setSubReg(0);
5281 
5282   MachineInstr *Def = MRI.getVRegDef(OpReg);
5283   if (!Def)
5284     return;
5285 
5286   // Try to eliminate the copy if it is copying an immediate value.
5287   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
5288     FoldImmediate(*Copy, *Def, OpReg, &MRI);
5289 
5290   bool ImpDef = Def->isImplicitDef();
5291   while (!ImpDef && Def && Def->isCopy()) {
5292     if (Def->getOperand(1).getReg().isPhysical())
5293       break;
5294     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
5295     ImpDef = Def && Def->isImplicitDef();
5296   }
5297   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
5298       !ImpDef)
5299     Copy.addReg(AMDGPU::EXEC, RegState::Implicit);
5300 }
5301 
5302 // Emit the actual waterfall loop, executing the wrapped instruction for each
5303 // unique value of \p Rsrc across all lanes. In the best case we execute 1
5304 // iteration, in the worst case we execute 64 (once per lane).
5305 static void
5306 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
5307                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5308                           const DebugLoc &DL, MachineOperand &Rsrc) {
5309   MachineFunction &MF = *OrigBB.getParent();
5310   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5311   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5312   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5313   unsigned SaveExecOpc =
5314       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
5315   unsigned XorTermOpc =
5316       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
5317   unsigned AndOpc =
5318       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
5319   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5320 
5321   MachineBasicBlock::iterator I = LoopBB.begin();
5322 
5323   SmallVector<Register, 8> ReadlanePieces;
5324   Register CondReg = AMDGPU::NoRegister;
5325 
5326   Register VRsrc = Rsrc.getReg();
5327   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
5328 
5329   unsigned RegSize = TRI->getRegSizeInBits(Rsrc.getReg(), MRI);
5330   unsigned NumSubRegs =  RegSize / 32;
5331   assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 && "Unhandled register size");
5332 
5333   for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
5334 
5335     Register CurRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5336     Register CurRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5337 
5338     // Read the next variant <- also loop target.
5339     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
5340             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx));
5341 
5342     // Read the next variant <- also loop target.
5343     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
5344             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx + 1));
5345 
5346     ReadlanePieces.push_back(CurRegLo);
5347     ReadlanePieces.push_back(CurRegHi);
5348 
5349     // Comparison is to be done as 64-bit.
5350     Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
5351     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
5352             .addReg(CurRegLo)
5353             .addImm(AMDGPU::sub0)
5354             .addReg(CurRegHi)
5355             .addImm(AMDGPU::sub1);
5356 
5357     Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
5358     auto Cmp =
5359         BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
5360             .addReg(CurReg);
5361     if (NumSubRegs <= 2)
5362       Cmp.addReg(VRsrc);
5363     else
5364       Cmp.addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx, 2));
5365 
5366     // Combine the comparision results with AND.
5367     if (CondReg == AMDGPU::NoRegister) // First.
5368       CondReg = NewCondReg;
5369     else { // If not the first, we create an AND.
5370       Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
5371       BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndReg)
5372               .addReg(CondReg)
5373               .addReg(NewCondReg);
5374       CondReg = AndReg;
5375     }
5376   } // End for loop.
5377 
5378   auto SRsrcRC = TRI->getEquivalentSGPRClass(MRI.getRegClass(VRsrc));
5379   Register SRsrc = MRI.createVirtualRegister(SRsrcRC);
5380 
5381   // Build scalar Rsrc.
5382   auto Merge = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc);
5383   unsigned Channel = 0;
5384   for (Register Piece : ReadlanePieces) {
5385     Merge.addReg(Piece)
5386          .addImm(TRI->getSubRegFromChannel(Channel++));
5387   }
5388 
5389   // Update Rsrc operand to use the SGPR Rsrc.
5390   Rsrc.setReg(SRsrc);
5391   Rsrc.setIsKill(true);
5392 
5393   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5394   MRI.setSimpleHint(SaveExec, CondReg);
5395 
5396   // Update EXEC to matching lanes, saving original to SaveExec.
5397   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
5398       .addReg(CondReg, RegState::Kill);
5399 
5400   // The original instruction is here; we insert the terminators after it.
5401   I = LoopBB.end();
5402 
5403   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5404   BuildMI(LoopBB, I, DL, TII.get(XorTermOpc), Exec)
5405       .addReg(Exec)
5406       .addReg(SaveExec);
5407 
5408   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::SI_WATERFALL_LOOP)).addMBB(&LoopBB);
5409 }
5410 
5411 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
5412 // with SGPRs by iterating over all unique values across all lanes.
5413 // Returns the loop basic block that now contains \p MI.
5414 static MachineBasicBlock *
5415 loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
5416                   MachineOperand &Rsrc, MachineDominatorTree *MDT,
5417                   MachineBasicBlock::iterator Begin = nullptr,
5418                   MachineBasicBlock::iterator End = nullptr) {
5419   MachineBasicBlock &MBB = *MI.getParent();
5420   MachineFunction &MF = *MBB.getParent();
5421   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5422   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5423   MachineRegisterInfo &MRI = MF.getRegInfo();
5424   if (!Begin.isValid())
5425     Begin = &MI;
5426   if (!End.isValid()) {
5427     End = &MI;
5428     ++End;
5429   }
5430   const DebugLoc &DL = MI.getDebugLoc();
5431   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5432   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
5433   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5434 
5435   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5436 
5437   // Save the EXEC mask
5438   BuildMI(MBB, Begin, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
5439 
5440   // Killed uses in the instruction we are waterfalling around will be
5441   // incorrect due to the added control-flow.
5442   MachineBasicBlock::iterator AfterMI = MI;
5443   ++AfterMI;
5444   for (auto I = Begin; I != AfterMI; I++) {
5445     for (auto &MO : I->uses()) {
5446       if (MO.isReg() && MO.isUse()) {
5447         MRI.clearKillFlags(MO.getReg());
5448       }
5449     }
5450   }
5451 
5452   // To insert the loop we need to split the block. Move everything after this
5453   // point to a new block, and insert a new empty block between the two.
5454   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
5455   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
5456   MachineFunction::iterator MBBI(MBB);
5457   ++MBBI;
5458 
5459   MF.insert(MBBI, LoopBB);
5460   MF.insert(MBBI, RemainderBB);
5461 
5462   LoopBB->addSuccessor(LoopBB);
5463   LoopBB->addSuccessor(RemainderBB);
5464 
5465   // Move Begin to MI to the LoopBB, and the remainder of the block to
5466   // RemainderBB.
5467   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5468   RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
5469   LoopBB->splice(LoopBB->begin(), &MBB, Begin, MBB.end());
5470 
5471   MBB.addSuccessor(LoopBB);
5472 
5473   // Update dominators. We know that MBB immediately dominates LoopBB, that
5474   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
5475   // dominates all of the successors transferred to it from MBB that MBB used
5476   // to properly dominate.
5477   if (MDT) {
5478     MDT->addNewBlock(LoopBB, &MBB);
5479     MDT->addNewBlock(RemainderBB, LoopBB);
5480     for (auto &Succ : RemainderBB->successors()) {
5481       if (MDT->properlyDominates(&MBB, Succ)) {
5482         MDT->changeImmediateDominator(Succ, RemainderBB);
5483       }
5484     }
5485   }
5486 
5487   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
5488 
5489   // Restore the EXEC mask
5490   MachineBasicBlock::iterator First = RemainderBB->begin();
5491   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
5492   return LoopBB;
5493 }
5494 
5495 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
5496 static std::tuple<unsigned, unsigned>
5497 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
5498   MachineBasicBlock &MBB = *MI.getParent();
5499   MachineFunction &MF = *MBB.getParent();
5500   MachineRegisterInfo &MRI = MF.getRegInfo();
5501 
5502   // Extract the ptr from the resource descriptor.
5503   unsigned RsrcPtr =
5504       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
5505                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
5506 
5507   // Create an empty resource descriptor
5508   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5509   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5510   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5511   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
5512   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
5513 
5514   // Zero64 = 0
5515   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
5516       .addImm(0);
5517 
5518   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
5519   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
5520       .addImm(RsrcDataFormat & 0xFFFFFFFF);
5521 
5522   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
5523   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
5524       .addImm(RsrcDataFormat >> 32);
5525 
5526   // NewSRsrc = {Zero64, SRsrcFormat}
5527   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
5528       .addReg(Zero64)
5529       .addImm(AMDGPU::sub0_sub1)
5530       .addReg(SRsrcFormatLo)
5531       .addImm(AMDGPU::sub2)
5532       .addReg(SRsrcFormatHi)
5533       .addImm(AMDGPU::sub3);
5534 
5535   return std::make_tuple(RsrcPtr, NewSRsrc);
5536 }
5537 
5538 MachineBasicBlock *
5539 SIInstrInfo::legalizeOperands(MachineInstr &MI,
5540                               MachineDominatorTree *MDT) const {
5541   MachineFunction &MF = *MI.getParent()->getParent();
5542   MachineRegisterInfo &MRI = MF.getRegInfo();
5543   MachineBasicBlock *CreatedBB = nullptr;
5544 
5545   // Legalize VOP2
5546   if (isVOP2(MI) || isVOPC(MI)) {
5547     legalizeOperandsVOP2(MRI, MI);
5548     return CreatedBB;
5549   }
5550 
5551   // Legalize VOP3
5552   if (isVOP3(MI)) {
5553     legalizeOperandsVOP3(MRI, MI);
5554     return CreatedBB;
5555   }
5556 
5557   // Legalize SMRD
5558   if (isSMRD(MI)) {
5559     legalizeOperandsSMRD(MRI, MI);
5560     return CreatedBB;
5561   }
5562 
5563   // Legalize FLAT
5564   if (isFLAT(MI)) {
5565     legalizeOperandsFLAT(MRI, MI);
5566     return CreatedBB;
5567   }
5568 
5569   // Legalize REG_SEQUENCE and PHI
5570   // The register class of the operands much be the same type as the register
5571   // class of the output.
5572   if (MI.getOpcode() == AMDGPU::PHI) {
5573     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
5574     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
5575       if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
5576         continue;
5577       const TargetRegisterClass *OpRC =
5578           MRI.getRegClass(MI.getOperand(i).getReg());
5579       if (RI.hasVectorRegisters(OpRC)) {
5580         VRC = OpRC;
5581       } else {
5582         SRC = OpRC;
5583       }
5584     }
5585 
5586     // If any of the operands are VGPR registers, then they all most be
5587     // otherwise we will create illegal VGPR->SGPR copies when legalizing
5588     // them.
5589     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
5590       if (!VRC) {
5591         assert(SRC);
5592         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
5593           VRC = &AMDGPU::VReg_1RegClass;
5594         } else
5595           VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5596                     ? RI.getEquivalentAGPRClass(SRC)
5597                     : RI.getEquivalentVGPRClass(SRC);
5598       } else {
5599         VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5600                   ? RI.getEquivalentAGPRClass(VRC)
5601                   : RI.getEquivalentVGPRClass(VRC);
5602       }
5603       RC = VRC;
5604     } else {
5605       RC = SRC;
5606     }
5607 
5608     // Update all the operands so they have the same type.
5609     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5610       MachineOperand &Op = MI.getOperand(I);
5611       if (!Op.isReg() || !Op.getReg().isVirtual())
5612         continue;
5613 
5614       // MI is a PHI instruction.
5615       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
5616       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
5617 
5618       // Avoid creating no-op copies with the same src and dst reg class.  These
5619       // confuse some of the machine passes.
5620       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
5621     }
5622   }
5623 
5624   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
5625   // VGPR dest type and SGPR sources, insert copies so all operands are
5626   // VGPRs. This seems to help operand folding / the register coalescer.
5627   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
5628     MachineBasicBlock *MBB = MI.getParent();
5629     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
5630     if (RI.hasVGPRs(DstRC)) {
5631       // Update all the operands so they are VGPR register classes. These may
5632       // not be the same register class because REG_SEQUENCE supports mixing
5633       // subregister index types e.g. sub0_sub1 + sub2 + sub3
5634       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5635         MachineOperand &Op = MI.getOperand(I);
5636         if (!Op.isReg() || !Op.getReg().isVirtual())
5637           continue;
5638 
5639         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
5640         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
5641         if (VRC == OpRC)
5642           continue;
5643 
5644         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
5645         Op.setIsKill();
5646       }
5647     }
5648 
5649     return CreatedBB;
5650   }
5651 
5652   // Legalize INSERT_SUBREG
5653   // src0 must have the same register class as dst
5654   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
5655     Register Dst = MI.getOperand(0).getReg();
5656     Register Src0 = MI.getOperand(1).getReg();
5657     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
5658     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
5659     if (DstRC != Src0RC) {
5660       MachineBasicBlock *MBB = MI.getParent();
5661       MachineOperand &Op = MI.getOperand(1);
5662       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
5663     }
5664     return CreatedBB;
5665   }
5666 
5667   // Legalize SI_INIT_M0
5668   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
5669     MachineOperand &Src = MI.getOperand(0);
5670     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
5671       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
5672     return CreatedBB;
5673   }
5674 
5675   // Legalize MIMG and MUBUF/MTBUF for shaders.
5676   //
5677   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
5678   // scratch memory access. In both cases, the legalization never involves
5679   // conversion to the addr64 form.
5680   if (isMIMG(MI) || (AMDGPU::isGraphics(MF.getFunction().getCallingConv()) &&
5681                      (isMUBUF(MI) || isMTBUF(MI)))) {
5682     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
5683     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
5684       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SRsrc, MDT);
5685 
5686     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
5687     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
5688       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SSamp, MDT);
5689 
5690     return CreatedBB;
5691   }
5692 
5693   // Legalize SI_CALL
5694   if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
5695     MachineOperand *Dest = &MI.getOperand(0);
5696     if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
5697       // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
5698       // following copies, we also need to move copies from and to physical
5699       // registers into the loop block.
5700       unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
5701       unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
5702 
5703       // Also move the copies to physical registers into the loop block
5704       MachineBasicBlock &MBB = *MI.getParent();
5705       MachineBasicBlock::iterator Start(&MI);
5706       while (Start->getOpcode() != FrameSetupOpcode)
5707         --Start;
5708       MachineBasicBlock::iterator End(&MI);
5709       while (End->getOpcode() != FrameDestroyOpcode)
5710         ++End;
5711       // Also include following copies of the return value
5712       ++End;
5713       while (End != MBB.end() && End->isCopy() && End->getOperand(1).isReg() &&
5714              MI.definesRegister(End->getOperand(1).getReg()))
5715         ++End;
5716       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Dest, MDT, Start, End);
5717     }
5718   }
5719 
5720   // Legalize MUBUF* instructions.
5721   int RsrcIdx =
5722       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
5723   if (RsrcIdx != -1) {
5724     // We have an MUBUF instruction
5725     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
5726     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
5727     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
5728                              RI.getRegClass(RsrcRC))) {
5729       // The operands are legal.
5730       // FIXME: We may need to legalize operands besided srsrc.
5731       return CreatedBB;
5732     }
5733 
5734     // Legalize a VGPR Rsrc.
5735     //
5736     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
5737     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
5738     // a zero-value SRsrc.
5739     //
5740     // If the instruction is _OFFSET (both idxen and offen disabled), and we
5741     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
5742     // above.
5743     //
5744     // Otherwise we are on non-ADDR64 hardware, and/or we have
5745     // idxen/offen/bothen and we fall back to a waterfall loop.
5746 
5747     MachineBasicBlock &MBB = *MI.getParent();
5748 
5749     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5750     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
5751       // This is already an ADDR64 instruction so we need to add the pointer
5752       // extracted from the resource descriptor to the current value of VAddr.
5753       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5754       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5755       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5756 
5757       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5758       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
5759       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
5760 
5761       unsigned RsrcPtr, NewSRsrc;
5762       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5763 
5764       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
5765       const DebugLoc &DL = MI.getDebugLoc();
5766       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
5767         .addDef(CondReg0)
5768         .addReg(RsrcPtr, 0, AMDGPU::sub0)
5769         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
5770         .addImm(0);
5771 
5772       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
5773       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
5774         .addDef(CondReg1, RegState::Dead)
5775         .addReg(RsrcPtr, 0, AMDGPU::sub1)
5776         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
5777         .addReg(CondReg0, RegState::Kill)
5778         .addImm(0);
5779 
5780       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5781       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
5782           .addReg(NewVAddrLo)
5783           .addImm(AMDGPU::sub0)
5784           .addReg(NewVAddrHi)
5785           .addImm(AMDGPU::sub1);
5786 
5787       VAddr->setReg(NewVAddr);
5788       Rsrc->setReg(NewSRsrc);
5789     } else if (!VAddr && ST.hasAddr64()) {
5790       // This instructions is the _OFFSET variant, so we need to convert it to
5791       // ADDR64.
5792       assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5793              "FIXME: Need to emit flat atomics here");
5794 
5795       unsigned RsrcPtr, NewSRsrc;
5796       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5797 
5798       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5799       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
5800       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5801       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
5802       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
5803 
5804       // Atomics rith return have have an additional tied operand and are
5805       // missing some of the special bits.
5806       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
5807       MachineInstr *Addr64;
5808 
5809       if (!VDataIn) {
5810         // Regular buffer load / store.
5811         MachineInstrBuilder MIB =
5812             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5813                 .add(*VData)
5814                 .addReg(NewVAddr)
5815                 .addReg(NewSRsrc)
5816                 .add(*SOffset)
5817                 .add(*Offset);
5818 
5819         if (const MachineOperand *CPol =
5820                 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
5821           MIB.addImm(CPol->getImm());
5822         }
5823 
5824         if (const MachineOperand *TFE =
5825                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
5826           MIB.addImm(TFE->getImm());
5827         }
5828 
5829         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
5830 
5831         MIB.cloneMemRefs(MI);
5832         Addr64 = MIB;
5833       } else {
5834         // Atomics with return.
5835         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5836                      .add(*VData)
5837                      .add(*VDataIn)
5838                      .addReg(NewVAddr)
5839                      .addReg(NewSRsrc)
5840                      .add(*SOffset)
5841                      .add(*Offset)
5842                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
5843                      .cloneMemRefs(MI);
5844       }
5845 
5846       MI.removeFromParent();
5847 
5848       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5849       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
5850               NewVAddr)
5851           .addReg(RsrcPtr, 0, AMDGPU::sub0)
5852           .addImm(AMDGPU::sub0)
5853           .addReg(RsrcPtr, 0, AMDGPU::sub1)
5854           .addImm(AMDGPU::sub1);
5855     } else {
5856       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
5857       // to SGPRs.
5858       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
5859       return CreatedBB;
5860     }
5861   }
5862   return CreatedBB;
5863 }
5864 
5865 MachineBasicBlock *SIInstrInfo::moveToVALU(MachineInstr &TopInst,
5866                                            MachineDominatorTree *MDT) const {
5867   SetVectorType Worklist;
5868   Worklist.insert(&TopInst);
5869   MachineBasicBlock *CreatedBB = nullptr;
5870   MachineBasicBlock *CreatedBBTmp = nullptr;
5871 
5872   while (!Worklist.empty()) {
5873     MachineInstr &Inst = *Worklist.pop_back_val();
5874     MachineBasicBlock *MBB = Inst.getParent();
5875     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
5876 
5877     unsigned Opcode = Inst.getOpcode();
5878     unsigned NewOpcode = getVALUOp(Inst);
5879 
5880     // Handle some special cases
5881     switch (Opcode) {
5882     default:
5883       break;
5884     case AMDGPU::S_ADD_U64_PSEUDO:
5885     case AMDGPU::S_SUB_U64_PSEUDO:
5886       splitScalar64BitAddSub(Worklist, Inst, MDT);
5887       Inst.eraseFromParent();
5888       continue;
5889     case AMDGPU::S_ADD_I32:
5890     case AMDGPU::S_SUB_I32: {
5891       // FIXME: The u32 versions currently selected use the carry.
5892       bool Changed;
5893       std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
5894       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5895         CreatedBB = CreatedBBTmp;
5896       if (Changed)
5897         continue;
5898 
5899       // Default handling
5900       break;
5901     }
5902     case AMDGPU::S_AND_B64:
5903       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
5904       Inst.eraseFromParent();
5905       continue;
5906 
5907     case AMDGPU::S_OR_B64:
5908       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
5909       Inst.eraseFromParent();
5910       continue;
5911 
5912     case AMDGPU::S_XOR_B64:
5913       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
5914       Inst.eraseFromParent();
5915       continue;
5916 
5917     case AMDGPU::S_NAND_B64:
5918       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
5919       Inst.eraseFromParent();
5920       continue;
5921 
5922     case AMDGPU::S_NOR_B64:
5923       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
5924       Inst.eraseFromParent();
5925       continue;
5926 
5927     case AMDGPU::S_XNOR_B64:
5928       if (ST.hasDLInsts())
5929         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
5930       else
5931         splitScalar64BitXnor(Worklist, Inst, MDT);
5932       Inst.eraseFromParent();
5933       continue;
5934 
5935     case AMDGPU::S_ANDN2_B64:
5936       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
5937       Inst.eraseFromParent();
5938       continue;
5939 
5940     case AMDGPU::S_ORN2_B64:
5941       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
5942       Inst.eraseFromParent();
5943       continue;
5944 
5945     case AMDGPU::S_BREV_B64:
5946       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
5947       Inst.eraseFromParent();
5948       continue;
5949 
5950     case AMDGPU::S_NOT_B64:
5951       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
5952       Inst.eraseFromParent();
5953       continue;
5954 
5955     case AMDGPU::S_BCNT1_I32_B64:
5956       splitScalar64BitBCNT(Worklist, Inst);
5957       Inst.eraseFromParent();
5958       continue;
5959 
5960     case AMDGPU::S_BFE_I64:
5961       splitScalar64BitBFE(Worklist, Inst);
5962       Inst.eraseFromParent();
5963       continue;
5964 
5965     case AMDGPU::S_LSHL_B32:
5966       if (ST.hasOnlyRevVALUShifts()) {
5967         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
5968         swapOperands(Inst);
5969       }
5970       break;
5971     case AMDGPU::S_ASHR_I32:
5972       if (ST.hasOnlyRevVALUShifts()) {
5973         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
5974         swapOperands(Inst);
5975       }
5976       break;
5977     case AMDGPU::S_LSHR_B32:
5978       if (ST.hasOnlyRevVALUShifts()) {
5979         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
5980         swapOperands(Inst);
5981       }
5982       break;
5983     case AMDGPU::S_LSHL_B64:
5984       if (ST.hasOnlyRevVALUShifts()) {
5985         NewOpcode = AMDGPU::V_LSHLREV_B64_e64;
5986         swapOperands(Inst);
5987       }
5988       break;
5989     case AMDGPU::S_ASHR_I64:
5990       if (ST.hasOnlyRevVALUShifts()) {
5991         NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
5992         swapOperands(Inst);
5993       }
5994       break;
5995     case AMDGPU::S_LSHR_B64:
5996       if (ST.hasOnlyRevVALUShifts()) {
5997         NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
5998         swapOperands(Inst);
5999       }
6000       break;
6001 
6002     case AMDGPU::S_ABS_I32:
6003       lowerScalarAbs(Worklist, Inst);
6004       Inst.eraseFromParent();
6005       continue;
6006 
6007     case AMDGPU::S_CBRANCH_SCC0:
6008     case AMDGPU::S_CBRANCH_SCC1: {
6009         // Clear unused bits of vcc
6010         Register CondReg = Inst.getOperand(1).getReg();
6011         bool IsSCC = CondReg == AMDGPU::SCC;
6012         Register VCC = RI.getVCC();
6013         Register EXEC = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6014         unsigned Opc = ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6015         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(Opc), VCC)
6016             .addReg(EXEC)
6017             .addReg(IsSCC ? VCC : CondReg);
6018         Inst.RemoveOperand(1);
6019       }
6020       break;
6021 
6022     case AMDGPU::S_BFE_U64:
6023     case AMDGPU::S_BFM_B64:
6024       llvm_unreachable("Moving this op to VALU not implemented");
6025 
6026     case AMDGPU::S_PACK_LL_B32_B16:
6027     case AMDGPU::S_PACK_LH_B32_B16:
6028     case AMDGPU::S_PACK_HH_B32_B16:
6029       movePackToVALU(Worklist, MRI, Inst);
6030       Inst.eraseFromParent();
6031       continue;
6032 
6033     case AMDGPU::S_XNOR_B32:
6034       lowerScalarXnor(Worklist, Inst);
6035       Inst.eraseFromParent();
6036       continue;
6037 
6038     case AMDGPU::S_NAND_B32:
6039       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
6040       Inst.eraseFromParent();
6041       continue;
6042 
6043     case AMDGPU::S_NOR_B32:
6044       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
6045       Inst.eraseFromParent();
6046       continue;
6047 
6048     case AMDGPU::S_ANDN2_B32:
6049       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
6050       Inst.eraseFromParent();
6051       continue;
6052 
6053     case AMDGPU::S_ORN2_B32:
6054       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
6055       Inst.eraseFromParent();
6056       continue;
6057 
6058     // TODO: remove as soon as everything is ready
6059     // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
6060     // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
6061     // can only be selected from the uniform SDNode.
6062     case AMDGPU::S_ADD_CO_PSEUDO:
6063     case AMDGPU::S_SUB_CO_PSEUDO: {
6064       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
6065                          ? AMDGPU::V_ADDC_U32_e64
6066                          : AMDGPU::V_SUBB_U32_e64;
6067       const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6068 
6069       Register CarryInReg = Inst.getOperand(4).getReg();
6070       if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
6071         Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
6072         BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
6073             .addReg(CarryInReg);
6074       }
6075 
6076       Register CarryOutReg = Inst.getOperand(1).getReg();
6077 
6078       Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
6079           MRI.getRegClass(Inst.getOperand(0).getReg())));
6080       MachineInstr *CarryOp =
6081           BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
6082               .addReg(CarryOutReg, RegState::Define)
6083               .add(Inst.getOperand(2))
6084               .add(Inst.getOperand(3))
6085               .addReg(CarryInReg)
6086               .addImm(0);
6087       CreatedBBTmp = legalizeOperands(*CarryOp);
6088       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6089         CreatedBB = CreatedBBTmp;
6090       MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
6091       addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
6092       Inst.eraseFromParent();
6093     }
6094       continue;
6095     case AMDGPU::S_UADDO_PSEUDO:
6096     case AMDGPU::S_USUBO_PSEUDO: {
6097       const DebugLoc &DL = Inst.getDebugLoc();
6098       MachineOperand &Dest0 = Inst.getOperand(0);
6099       MachineOperand &Dest1 = Inst.getOperand(1);
6100       MachineOperand &Src0 = Inst.getOperand(2);
6101       MachineOperand &Src1 = Inst.getOperand(3);
6102 
6103       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
6104                          ? AMDGPU::V_ADD_CO_U32_e64
6105                          : AMDGPU::V_SUB_CO_U32_e64;
6106       const TargetRegisterClass *NewRC =
6107           RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
6108       Register DestReg = MRI.createVirtualRegister(NewRC);
6109       MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
6110                                    .addReg(Dest1.getReg(), RegState::Define)
6111                                    .add(Src0)
6112                                    .add(Src1)
6113                                    .addImm(0); // clamp bit
6114 
6115       CreatedBBTmp = legalizeOperands(*NewInstr, MDT);
6116       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6117         CreatedBB = CreatedBBTmp;
6118 
6119       MRI.replaceRegWith(Dest0.getReg(), DestReg);
6120       addUsersToMoveToVALUWorklist(NewInstr->getOperand(0).getReg(), MRI,
6121                                    Worklist);
6122       Inst.eraseFromParent();
6123     }
6124       continue;
6125 
6126     case AMDGPU::S_CSELECT_B32:
6127       lowerSelect32(Worklist, Inst, MDT);
6128       Inst.eraseFromParent();
6129       continue;
6130     case AMDGPU::S_CSELECT_B64:
6131       splitSelect64(Worklist, Inst, MDT);
6132       Inst.eraseFromParent();
6133       continue;
6134     case AMDGPU::S_CMP_EQ_I32:
6135     case AMDGPU::S_CMP_LG_I32:
6136     case AMDGPU::S_CMP_GT_I32:
6137     case AMDGPU::S_CMP_GE_I32:
6138     case AMDGPU::S_CMP_LT_I32:
6139     case AMDGPU::S_CMP_LE_I32:
6140     case AMDGPU::S_CMP_EQ_U32:
6141     case AMDGPU::S_CMP_LG_U32:
6142     case AMDGPU::S_CMP_GT_U32:
6143     case AMDGPU::S_CMP_GE_U32:
6144     case AMDGPU::S_CMP_LT_U32:
6145     case AMDGPU::S_CMP_LE_U32:
6146     case AMDGPU::S_CMP_EQ_U64:
6147     case AMDGPU::S_CMP_LG_U64: {
6148         const MCInstrDesc &NewDesc = get(NewOpcode);
6149         Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
6150         MachineInstr *NewInstr =
6151             BuildMI(*MBB, Inst, Inst.getDebugLoc(), NewDesc, CondReg)
6152                 .add(Inst.getOperand(0))
6153                 .add(Inst.getOperand(1));
6154         legalizeOperands(*NewInstr, MDT);
6155         int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC);
6156         MachineOperand SCCOp = Inst.getOperand(SCCIdx);
6157         addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
6158         Inst.eraseFromParent();
6159       }
6160       continue;
6161     }
6162 
6163 
6164     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
6165       // We cannot move this instruction to the VALU, so we should try to
6166       // legalize its operands instead.
6167       CreatedBBTmp = legalizeOperands(Inst, MDT);
6168       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6169         CreatedBB = CreatedBBTmp;
6170       continue;
6171     }
6172 
6173     // Use the new VALU Opcode.
6174     const MCInstrDesc &NewDesc = get(NewOpcode);
6175     Inst.setDesc(NewDesc);
6176 
6177     // Remove any references to SCC. Vector instructions can't read from it, and
6178     // We're just about to add the implicit use / defs of VCC, and we don't want
6179     // both.
6180     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
6181       MachineOperand &Op = Inst.getOperand(i);
6182       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
6183         // Only propagate through live-def of SCC.
6184         if (Op.isDef() && !Op.isDead())
6185           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
6186         if (Op.isUse())
6187           addSCCDefsToVALUWorklist(Op, Worklist);
6188         Inst.RemoveOperand(i);
6189       }
6190     }
6191 
6192     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
6193       // We are converting these to a BFE, so we need to add the missing
6194       // operands for the size and offset.
6195       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
6196       Inst.addOperand(MachineOperand::CreateImm(0));
6197       Inst.addOperand(MachineOperand::CreateImm(Size));
6198 
6199     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
6200       // The VALU version adds the second operand to the result, so insert an
6201       // extra 0 operand.
6202       Inst.addOperand(MachineOperand::CreateImm(0));
6203     }
6204 
6205     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
6206     fixImplicitOperands(Inst);
6207 
6208     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
6209       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
6210       // If we need to move this to VGPRs, we need to unpack the second operand
6211       // back into the 2 separate ones for bit offset and width.
6212       assert(OffsetWidthOp.isImm() &&
6213              "Scalar BFE is only implemented for constant width and offset");
6214       uint32_t Imm = OffsetWidthOp.getImm();
6215 
6216       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6217       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6218       Inst.RemoveOperand(2);                     // Remove old immediate.
6219       Inst.addOperand(MachineOperand::CreateImm(Offset));
6220       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
6221     }
6222 
6223     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
6224     unsigned NewDstReg = AMDGPU::NoRegister;
6225     if (HasDst) {
6226       Register DstReg = Inst.getOperand(0).getReg();
6227       if (DstReg.isPhysical())
6228         continue;
6229 
6230       // Update the destination register class.
6231       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
6232       if (!NewDstRC)
6233         continue;
6234 
6235       if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual() &&
6236           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
6237         // Instead of creating a copy where src and dst are the same register
6238         // class, we just replace all uses of dst with src.  These kinds of
6239         // copies interfere with the heuristics MachineSink uses to decide
6240         // whether or not to split a critical edge.  Since the pass assumes
6241         // that copies will end up as machine instructions and not be
6242         // eliminated.
6243         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
6244         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
6245         MRI.clearKillFlags(Inst.getOperand(1).getReg());
6246         Inst.getOperand(0).setReg(DstReg);
6247 
6248         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
6249         // these are deleted later, but at -O0 it would leave a suspicious
6250         // looking illegal copy of an undef register.
6251         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
6252           Inst.RemoveOperand(I);
6253         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
6254         continue;
6255       }
6256 
6257       NewDstReg = MRI.createVirtualRegister(NewDstRC);
6258       MRI.replaceRegWith(DstReg, NewDstReg);
6259     }
6260 
6261     // Legalize the operands
6262     CreatedBBTmp = legalizeOperands(Inst, MDT);
6263     if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6264       CreatedBB = CreatedBBTmp;
6265 
6266     if (HasDst)
6267      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
6268   }
6269   return CreatedBB;
6270 }
6271 
6272 // Add/sub require special handling to deal with carry outs.
6273 std::pair<bool, MachineBasicBlock *>
6274 SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
6275                               MachineDominatorTree *MDT) const {
6276   if (ST.hasAddNoCarry()) {
6277     // Assume there is no user of scc since we don't select this in that case.
6278     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
6279     // is used.
6280 
6281     MachineBasicBlock &MBB = *Inst.getParent();
6282     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6283 
6284     Register OldDstReg = Inst.getOperand(0).getReg();
6285     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6286 
6287     unsigned Opc = Inst.getOpcode();
6288     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
6289 
6290     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
6291       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
6292 
6293     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
6294     Inst.RemoveOperand(3);
6295 
6296     Inst.setDesc(get(NewOpc));
6297     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
6298     Inst.addImplicitDefUseOperands(*MBB.getParent());
6299     MRI.replaceRegWith(OldDstReg, ResultReg);
6300     MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
6301 
6302     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6303     return std::make_pair(true, NewBB);
6304   }
6305 
6306   return std::make_pair(false, nullptr);
6307 }
6308 
6309 void SIInstrInfo::lowerSelect32(SetVectorType &Worklist, MachineInstr &Inst,
6310                                 MachineDominatorTree *MDT) const {
6311 
6312   MachineBasicBlock &MBB = *Inst.getParent();
6313   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6314   MachineBasicBlock::iterator MII = Inst;
6315   DebugLoc DL = Inst.getDebugLoc();
6316 
6317   MachineOperand &Dest = Inst.getOperand(0);
6318   MachineOperand &Src0 = Inst.getOperand(1);
6319   MachineOperand &Src1 = Inst.getOperand(2);
6320   MachineOperand &Cond = Inst.getOperand(3);
6321 
6322   Register SCCSource = Cond.getReg();
6323   bool IsSCC = (SCCSource == AMDGPU::SCC);
6324 
6325   // If this is a trivial select where the condition is effectively not SCC
6326   // (SCCSource is a source of copy to SCC), then the select is semantically
6327   // equivalent to copying SCCSource. Hence, there is no need to create
6328   // V_CNDMASK, we can just use that and bail out.
6329   if (!IsSCC && Src0.isImm() && (Src0.getImm() == -1) && Src1.isImm() &&
6330       (Src1.getImm() == 0)) {
6331     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6332     return;
6333   }
6334 
6335   const TargetRegisterClass *TC =
6336       RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6337 
6338   Register CopySCC = MRI.createVirtualRegister(TC);
6339 
6340   if (IsSCC) {
6341     // Now look for the closest SCC def if it is a copy
6342     // replacing the SCCSource with the COPY source register
6343     bool CopyFound = false;
6344     for (MachineInstr &CandI :
6345          make_range(std::next(MachineBasicBlock::reverse_iterator(Inst)),
6346                     Inst.getParent()->rend())) {
6347       if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) !=
6348           -1) {
6349         if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
6350           BuildMI(MBB, MII, DL, get(AMDGPU::COPY), CopySCC)
6351               .addReg(CandI.getOperand(1).getReg());
6352           CopyFound = true;
6353         }
6354         break;
6355       }
6356     }
6357     if (!CopyFound) {
6358       // SCC def is not a copy
6359       // Insert a trivial select instead of creating a copy, because a copy from
6360       // SCC would semantically mean just copying a single bit, but we may need
6361       // the result to be a vector condition mask that needs preserving.
6362       unsigned Opcode = (ST.getWavefrontSize() == 64) ? AMDGPU::S_CSELECT_B64
6363                                                       : AMDGPU::S_CSELECT_B32;
6364       auto NewSelect =
6365           BuildMI(MBB, MII, DL, get(Opcode), CopySCC).addImm(-1).addImm(0);
6366       NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
6367     }
6368   }
6369 
6370   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6371 
6372   auto UpdatedInst =
6373       BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), ResultReg)
6374           .addImm(0)
6375           .add(Src1) // False
6376           .addImm(0)
6377           .add(Src0) // True
6378           .addReg(IsSCC ? CopySCC : SCCSource);
6379 
6380   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6381   legalizeOperands(*UpdatedInst, MDT);
6382   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6383 }
6384 
6385 void SIInstrInfo::splitSelect64(SetVectorType &Worklist, MachineInstr &Inst,
6386                                 MachineDominatorTree *MDT) const {
6387   // Split S_CSELECT_B64 into a pair of S_CSELECT_B32 and lower them
6388   // further.
6389   const DebugLoc &DL = Inst.getDebugLoc();
6390   MachineBasicBlock::iterator MII = Inst;
6391   MachineBasicBlock &MBB = *Inst.getParent();
6392   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6393 
6394   // Get the original operands.
6395   MachineOperand &Dest = Inst.getOperand(0);
6396   MachineOperand &Src0 = Inst.getOperand(1);
6397   MachineOperand &Src1 = Inst.getOperand(2);
6398   MachineOperand &Cond = Inst.getOperand(3);
6399 
6400   Register SCCSource = Cond.getReg();
6401   bool IsSCC = (SCCSource == AMDGPU::SCC);
6402 
6403   // If this is a trivial select where the condition is effectively not SCC
6404   // (SCCSource is a source of copy to SCC), then the select is semantically
6405   // equivalent to copying SCCSource. Hence, there is no need to create
6406   // V_CNDMASK, we can just use that and bail out.
6407   if (!IsSCC && (Src0.isImm() && Src0.getImm() == -1) &&
6408       (Src1.isImm() && Src1.getImm() == 0)) {
6409     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6410     return;
6411   }
6412 
6413   // Prepare the split destination.
6414   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6415   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6416   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6417 
6418   // Split the source operands.
6419   const TargetRegisterClass *Src0RC = nullptr;
6420   const TargetRegisterClass *Src0SubRC = nullptr;
6421   if (Src0.isReg()) {
6422     Src0RC = MRI.getRegClass(Src0.getReg());
6423     Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6424   }
6425   const TargetRegisterClass *Src1RC = nullptr;
6426   const TargetRegisterClass *Src1SubRC = nullptr;
6427   if (Src1.isReg()) {
6428     Src1RC = MRI.getRegClass(Src1.getReg());
6429     Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6430   }
6431   // Split lo.
6432   MachineOperand SrcReg0Sub0 =
6433       buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
6434   MachineOperand SrcReg1Sub0 =
6435       buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
6436   // Split hi.
6437   MachineOperand SrcReg0Sub1 =
6438       buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
6439   MachineOperand SrcReg1Sub1 =
6440       buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
6441   // Select the lo part.
6442   MachineInstr *LoHalf =
6443       BuildMI(MBB, MII, DL, get(AMDGPU::S_CSELECT_B32), DestSub0)
6444           .add(SrcReg0Sub0)
6445           .add(SrcReg1Sub0);
6446   // Replace the condition operand with the original one.
6447   LoHalf->getOperand(3).setReg(SCCSource);
6448   Worklist.insert(LoHalf);
6449   // Select the hi part.
6450   MachineInstr *HiHalf =
6451       BuildMI(MBB, MII, DL, get(AMDGPU::S_CSELECT_B32), DestSub1)
6452           .add(SrcReg0Sub1)
6453           .add(SrcReg1Sub1);
6454   // Replace the condition operand with the original one.
6455   HiHalf->getOperand(3).setReg(SCCSource);
6456   Worklist.insert(HiHalf);
6457   // Merge them back to the original 64-bit one.
6458   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6459       .addReg(DestSub0)
6460       .addImm(AMDGPU::sub0)
6461       .addReg(DestSub1)
6462       .addImm(AMDGPU::sub1);
6463   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6464 
6465   // Try to legalize the operands in case we need to swap the order to keep
6466   // it valid.
6467   legalizeOperands(*LoHalf, MDT);
6468   legalizeOperands(*HiHalf, MDT);
6469 
6470   // Move all users of this moved value.
6471   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6472 }
6473 
6474 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
6475                                  MachineInstr &Inst) const {
6476   MachineBasicBlock &MBB = *Inst.getParent();
6477   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6478   MachineBasicBlock::iterator MII = Inst;
6479   DebugLoc DL = Inst.getDebugLoc();
6480 
6481   MachineOperand &Dest = Inst.getOperand(0);
6482   MachineOperand &Src = Inst.getOperand(1);
6483   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6484   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6485 
6486   unsigned SubOp = ST.hasAddNoCarry() ?
6487     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_CO_U32_e32;
6488 
6489   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
6490     .addImm(0)
6491     .addReg(Src.getReg());
6492 
6493   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
6494     .addReg(Src.getReg())
6495     .addReg(TmpReg);
6496 
6497   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6498   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6499 }
6500 
6501 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
6502                                   MachineInstr &Inst) const {
6503   MachineBasicBlock &MBB = *Inst.getParent();
6504   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6505   MachineBasicBlock::iterator MII = Inst;
6506   const DebugLoc &DL = Inst.getDebugLoc();
6507 
6508   MachineOperand &Dest = Inst.getOperand(0);
6509   MachineOperand &Src0 = Inst.getOperand(1);
6510   MachineOperand &Src1 = Inst.getOperand(2);
6511 
6512   if (ST.hasDLInsts()) {
6513     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6514     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
6515     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
6516 
6517     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
6518       .add(Src0)
6519       .add(Src1);
6520 
6521     MRI.replaceRegWith(Dest.getReg(), NewDest);
6522     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6523   } else {
6524     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
6525     // invert either source and then perform the XOR. If either source is a
6526     // scalar register, then we can leave the inversion on the scalar unit to
6527     // acheive a better distrubution of scalar and vector instructions.
6528     bool Src0IsSGPR = Src0.isReg() &&
6529                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
6530     bool Src1IsSGPR = Src1.isReg() &&
6531                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
6532     MachineInstr *Xor;
6533     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6534     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6535 
6536     // Build a pair of scalar instructions and add them to the work list.
6537     // The next iteration over the work list will lower these to the vector
6538     // unit as necessary.
6539     if (Src0IsSGPR) {
6540       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
6541       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6542       .addReg(Temp)
6543       .add(Src1);
6544     } else if (Src1IsSGPR) {
6545       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
6546       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6547       .add(Src0)
6548       .addReg(Temp);
6549     } else {
6550       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
6551         .add(Src0)
6552         .add(Src1);
6553       MachineInstr *Not =
6554           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
6555       Worklist.insert(Not);
6556     }
6557 
6558     MRI.replaceRegWith(Dest.getReg(), NewDest);
6559 
6560     Worklist.insert(Xor);
6561 
6562     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6563   }
6564 }
6565 
6566 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
6567                                       MachineInstr &Inst,
6568                                       unsigned Opcode) const {
6569   MachineBasicBlock &MBB = *Inst.getParent();
6570   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6571   MachineBasicBlock::iterator MII = Inst;
6572   const DebugLoc &DL = Inst.getDebugLoc();
6573 
6574   MachineOperand &Dest = Inst.getOperand(0);
6575   MachineOperand &Src0 = Inst.getOperand(1);
6576   MachineOperand &Src1 = Inst.getOperand(2);
6577 
6578   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6579   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6580 
6581   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
6582     .add(Src0)
6583     .add(Src1);
6584 
6585   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
6586     .addReg(Interm);
6587 
6588   Worklist.insert(&Op);
6589   Worklist.insert(&Not);
6590 
6591   MRI.replaceRegWith(Dest.getReg(), NewDest);
6592   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6593 }
6594 
6595 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
6596                                      MachineInstr &Inst,
6597                                      unsigned Opcode) const {
6598   MachineBasicBlock &MBB = *Inst.getParent();
6599   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6600   MachineBasicBlock::iterator MII = Inst;
6601   const DebugLoc &DL = Inst.getDebugLoc();
6602 
6603   MachineOperand &Dest = Inst.getOperand(0);
6604   MachineOperand &Src0 = Inst.getOperand(1);
6605   MachineOperand &Src1 = Inst.getOperand(2);
6606 
6607   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6608   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6609 
6610   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
6611     .add(Src1);
6612 
6613   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
6614     .add(Src0)
6615     .addReg(Interm);
6616 
6617   Worklist.insert(&Not);
6618   Worklist.insert(&Op);
6619 
6620   MRI.replaceRegWith(Dest.getReg(), NewDest);
6621   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6622 }
6623 
6624 void SIInstrInfo::splitScalar64BitUnaryOp(
6625     SetVectorType &Worklist, MachineInstr &Inst,
6626     unsigned Opcode, bool Swap) const {
6627   MachineBasicBlock &MBB = *Inst.getParent();
6628   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6629 
6630   MachineOperand &Dest = Inst.getOperand(0);
6631   MachineOperand &Src0 = Inst.getOperand(1);
6632   DebugLoc DL = Inst.getDebugLoc();
6633 
6634   MachineBasicBlock::iterator MII = Inst;
6635 
6636   const MCInstrDesc &InstDesc = get(Opcode);
6637   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6638     MRI.getRegClass(Src0.getReg()) :
6639     &AMDGPU::SGPR_32RegClass;
6640 
6641   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6642 
6643   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6644                                                        AMDGPU::sub0, Src0SubRC);
6645 
6646   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6647   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6648   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6649 
6650   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6651   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
6652 
6653   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6654                                                        AMDGPU::sub1, Src0SubRC);
6655 
6656   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6657   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
6658 
6659   if (Swap)
6660     std::swap(DestSub0, DestSub1);
6661 
6662   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6663   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6664     .addReg(DestSub0)
6665     .addImm(AMDGPU::sub0)
6666     .addReg(DestSub1)
6667     .addImm(AMDGPU::sub1);
6668 
6669   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6670 
6671   Worklist.insert(&LoHalf);
6672   Worklist.insert(&HiHalf);
6673 
6674   // We don't need to legalizeOperands here because for a single operand, src0
6675   // will support any kind of input.
6676 
6677   // Move all users of this moved value.
6678   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6679 }
6680 
6681 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
6682                                          MachineInstr &Inst,
6683                                          MachineDominatorTree *MDT) const {
6684   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
6685 
6686   MachineBasicBlock &MBB = *Inst.getParent();
6687   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6688   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6689 
6690   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6691   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6692   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6693 
6694   Register CarryReg = MRI.createVirtualRegister(CarryRC);
6695   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
6696 
6697   MachineOperand &Dest = Inst.getOperand(0);
6698   MachineOperand &Src0 = Inst.getOperand(1);
6699   MachineOperand &Src1 = Inst.getOperand(2);
6700   const DebugLoc &DL = Inst.getDebugLoc();
6701   MachineBasicBlock::iterator MII = Inst;
6702 
6703   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
6704   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
6705   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6706   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6707 
6708   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6709                                                        AMDGPU::sub0, Src0SubRC);
6710   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6711                                                        AMDGPU::sub0, Src1SubRC);
6712 
6713 
6714   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6715                                                        AMDGPU::sub1, Src0SubRC);
6716   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6717                                                        AMDGPU::sub1, Src1SubRC);
6718 
6719   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
6720   MachineInstr *LoHalf =
6721     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
6722     .addReg(CarryReg, RegState::Define)
6723     .add(SrcReg0Sub0)
6724     .add(SrcReg1Sub0)
6725     .addImm(0); // clamp bit
6726 
6727   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
6728   MachineInstr *HiHalf =
6729     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
6730     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
6731     .add(SrcReg0Sub1)
6732     .add(SrcReg1Sub1)
6733     .addReg(CarryReg, RegState::Kill)
6734     .addImm(0); // clamp bit
6735 
6736   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6737     .addReg(DestSub0)
6738     .addImm(AMDGPU::sub0)
6739     .addReg(DestSub1)
6740     .addImm(AMDGPU::sub1);
6741 
6742   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6743 
6744   // Try to legalize the operands in case we need to swap the order to keep it
6745   // valid.
6746   legalizeOperands(*LoHalf, MDT);
6747   legalizeOperands(*HiHalf, MDT);
6748 
6749   // Move all users of this moved vlaue.
6750   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6751 }
6752 
6753 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
6754                                            MachineInstr &Inst, unsigned Opcode,
6755                                            MachineDominatorTree *MDT) const {
6756   MachineBasicBlock &MBB = *Inst.getParent();
6757   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6758 
6759   MachineOperand &Dest = Inst.getOperand(0);
6760   MachineOperand &Src0 = Inst.getOperand(1);
6761   MachineOperand &Src1 = Inst.getOperand(2);
6762   DebugLoc DL = Inst.getDebugLoc();
6763 
6764   MachineBasicBlock::iterator MII = Inst;
6765 
6766   const MCInstrDesc &InstDesc = get(Opcode);
6767   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6768     MRI.getRegClass(Src0.getReg()) :
6769     &AMDGPU::SGPR_32RegClass;
6770 
6771   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6772   const TargetRegisterClass *Src1RC = Src1.isReg() ?
6773     MRI.getRegClass(Src1.getReg()) :
6774     &AMDGPU::SGPR_32RegClass;
6775 
6776   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6777 
6778   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6779                                                        AMDGPU::sub0, Src0SubRC);
6780   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6781                                                        AMDGPU::sub0, Src1SubRC);
6782   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6783                                                        AMDGPU::sub1, Src0SubRC);
6784   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6785                                                        AMDGPU::sub1, Src1SubRC);
6786 
6787   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6788   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6789   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6790 
6791   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6792   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
6793                               .add(SrcReg0Sub0)
6794                               .add(SrcReg1Sub0);
6795 
6796   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6797   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
6798                               .add(SrcReg0Sub1)
6799                               .add(SrcReg1Sub1);
6800 
6801   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6802   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6803     .addReg(DestSub0)
6804     .addImm(AMDGPU::sub0)
6805     .addReg(DestSub1)
6806     .addImm(AMDGPU::sub1);
6807 
6808   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6809 
6810   Worklist.insert(&LoHalf);
6811   Worklist.insert(&HiHalf);
6812 
6813   // Move all users of this moved vlaue.
6814   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6815 }
6816 
6817 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
6818                                        MachineInstr &Inst,
6819                                        MachineDominatorTree *MDT) const {
6820   MachineBasicBlock &MBB = *Inst.getParent();
6821   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6822 
6823   MachineOperand &Dest = Inst.getOperand(0);
6824   MachineOperand &Src0 = Inst.getOperand(1);
6825   MachineOperand &Src1 = Inst.getOperand(2);
6826   const DebugLoc &DL = Inst.getDebugLoc();
6827 
6828   MachineBasicBlock::iterator MII = Inst;
6829 
6830   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6831 
6832   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6833 
6834   MachineOperand* Op0;
6835   MachineOperand* Op1;
6836 
6837   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
6838     Op0 = &Src0;
6839     Op1 = &Src1;
6840   } else {
6841     Op0 = &Src1;
6842     Op1 = &Src0;
6843   }
6844 
6845   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
6846     .add(*Op0);
6847 
6848   Register NewDest = MRI.createVirtualRegister(DestRC);
6849 
6850   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
6851     .addReg(Interm)
6852     .add(*Op1);
6853 
6854   MRI.replaceRegWith(Dest.getReg(), NewDest);
6855 
6856   Worklist.insert(&Xor);
6857 }
6858 
6859 void SIInstrInfo::splitScalar64BitBCNT(
6860     SetVectorType &Worklist, MachineInstr &Inst) const {
6861   MachineBasicBlock &MBB = *Inst.getParent();
6862   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6863 
6864   MachineBasicBlock::iterator MII = Inst;
6865   const DebugLoc &DL = Inst.getDebugLoc();
6866 
6867   MachineOperand &Dest = Inst.getOperand(0);
6868   MachineOperand &Src = Inst.getOperand(1);
6869 
6870   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
6871   const TargetRegisterClass *SrcRC = Src.isReg() ?
6872     MRI.getRegClass(Src.getReg()) :
6873     &AMDGPU::SGPR_32RegClass;
6874 
6875   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6876   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6877 
6878   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
6879 
6880   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6881                                                       AMDGPU::sub0, SrcSubRC);
6882   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6883                                                       AMDGPU::sub1, SrcSubRC);
6884 
6885   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
6886 
6887   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
6888 
6889   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6890 
6891   // We don't need to legalize operands here. src0 for etiher instruction can be
6892   // an SGPR, and the second input is unused or determined here.
6893   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6894 }
6895 
6896 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
6897                                       MachineInstr &Inst) const {
6898   MachineBasicBlock &MBB = *Inst.getParent();
6899   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6900   MachineBasicBlock::iterator MII = Inst;
6901   const DebugLoc &DL = Inst.getDebugLoc();
6902 
6903   MachineOperand &Dest = Inst.getOperand(0);
6904   uint32_t Imm = Inst.getOperand(2).getImm();
6905   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6906   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6907 
6908   (void) Offset;
6909 
6910   // Only sext_inreg cases handled.
6911   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
6912          Offset == 0 && "Not implemented");
6913 
6914   if (BitWidth < 32) {
6915     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6916     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6917     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6918 
6919     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
6920         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
6921         .addImm(0)
6922         .addImm(BitWidth);
6923 
6924     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
6925       .addImm(31)
6926       .addReg(MidRegLo);
6927 
6928     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6929       .addReg(MidRegLo)
6930       .addImm(AMDGPU::sub0)
6931       .addReg(MidRegHi)
6932       .addImm(AMDGPU::sub1);
6933 
6934     MRI.replaceRegWith(Dest.getReg(), ResultReg);
6935     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6936     return;
6937   }
6938 
6939   MachineOperand &Src = Inst.getOperand(1);
6940   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6941   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6942 
6943   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
6944     .addImm(31)
6945     .addReg(Src.getReg(), 0, AMDGPU::sub0);
6946 
6947   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6948     .addReg(Src.getReg(), 0, AMDGPU::sub0)
6949     .addImm(AMDGPU::sub0)
6950     .addReg(TmpReg)
6951     .addImm(AMDGPU::sub1);
6952 
6953   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6954   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6955 }
6956 
6957 void SIInstrInfo::addUsersToMoveToVALUWorklist(
6958   Register DstReg,
6959   MachineRegisterInfo &MRI,
6960   SetVectorType &Worklist) const {
6961   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
6962          E = MRI.use_end(); I != E;) {
6963     MachineInstr &UseMI = *I->getParent();
6964 
6965     unsigned OpNo = 0;
6966 
6967     switch (UseMI.getOpcode()) {
6968     case AMDGPU::COPY:
6969     case AMDGPU::WQM:
6970     case AMDGPU::SOFT_WQM:
6971     case AMDGPU::STRICT_WWM:
6972     case AMDGPU::STRICT_WQM:
6973     case AMDGPU::REG_SEQUENCE:
6974     case AMDGPU::PHI:
6975     case AMDGPU::INSERT_SUBREG:
6976       break;
6977     default:
6978       OpNo = I.getOperandNo();
6979       break;
6980     }
6981 
6982     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
6983       Worklist.insert(&UseMI);
6984 
6985       do {
6986         ++I;
6987       } while (I != E && I->getParent() == &UseMI);
6988     } else {
6989       ++I;
6990     }
6991   }
6992 }
6993 
6994 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
6995                                  MachineRegisterInfo &MRI,
6996                                  MachineInstr &Inst) const {
6997   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6998   MachineBasicBlock *MBB = Inst.getParent();
6999   MachineOperand &Src0 = Inst.getOperand(1);
7000   MachineOperand &Src1 = Inst.getOperand(2);
7001   const DebugLoc &DL = Inst.getDebugLoc();
7002 
7003   switch (Inst.getOpcode()) {
7004   case AMDGPU::S_PACK_LL_B32_B16: {
7005     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7006     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7007 
7008     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
7009     // 0.
7010     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7011       .addImm(0xffff);
7012 
7013     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
7014       .addReg(ImmReg, RegState::Kill)
7015       .add(Src0);
7016 
7017     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
7018       .add(Src1)
7019       .addImm(16)
7020       .addReg(TmpReg, RegState::Kill);
7021     break;
7022   }
7023   case AMDGPU::S_PACK_LH_B32_B16: {
7024     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7025     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7026       .addImm(0xffff);
7027     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
7028       .addReg(ImmReg, RegState::Kill)
7029       .add(Src0)
7030       .add(Src1);
7031     break;
7032   }
7033   case AMDGPU::S_PACK_HH_B32_B16: {
7034     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7035     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7036     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
7037       .addImm(16)
7038       .add(Src0);
7039     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7040       .addImm(0xffff0000);
7041     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
7042       .add(Src1)
7043       .addReg(ImmReg, RegState::Kill)
7044       .addReg(TmpReg, RegState::Kill);
7045     break;
7046   }
7047   default:
7048     llvm_unreachable("unhandled s_pack_* instruction");
7049   }
7050 
7051   MachineOperand &Dest = Inst.getOperand(0);
7052   MRI.replaceRegWith(Dest.getReg(), ResultReg);
7053   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
7054 }
7055 
7056 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
7057                                                MachineInstr &SCCDefInst,
7058                                                SetVectorType &Worklist,
7059                                                Register NewCond) const {
7060 
7061   // Ensure that def inst defines SCC, which is still live.
7062   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
7063          !Op.isDead() && Op.getParent() == &SCCDefInst);
7064   SmallVector<MachineInstr *, 4> CopyToDelete;
7065   // This assumes that all the users of SCC are in the same block
7066   // as the SCC def.
7067   for (MachineInstr &MI : // Skip the def inst itself.
7068        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
7069                   SCCDefInst.getParent()->end())) {
7070     // Check if SCC is used first.
7071     int SCCIdx = MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI);
7072     if (SCCIdx != -1) {
7073       if (MI.isCopy()) {
7074         MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7075         Register DestReg = MI.getOperand(0).getReg();
7076 
7077         MRI.replaceRegWith(DestReg, NewCond);
7078         CopyToDelete.push_back(&MI);
7079       } else {
7080 
7081         if (NewCond.isValid())
7082           MI.getOperand(SCCIdx).setReg(NewCond);
7083 
7084         Worklist.insert(&MI);
7085       }
7086     }
7087     // Exit if we find another SCC def.
7088     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
7089       break;
7090   }
7091   for (auto &Copy : CopyToDelete)
7092     Copy->eraseFromParent();
7093 }
7094 
7095 // Instructions that use SCC may be converted to VALU instructions. When that
7096 // happens, the SCC register is changed to VCC_LO. The instruction that defines
7097 // SCC must be changed to an instruction that defines VCC. This function makes
7098 // sure that the instruction that defines SCC is added to the moveToVALU
7099 // worklist.
7100 void SIInstrInfo::addSCCDefsToVALUWorklist(MachineOperand &Op,
7101                                            SetVectorType &Worklist) const {
7102   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isUse());
7103 
7104   MachineInstr *SCCUseInst = Op.getParent();
7105   // Look for a preceeding instruction that either defines VCC or SCC. If VCC
7106   // then there is nothing to do because the defining instruction has been
7107   // converted to a VALU already. If SCC then that instruction needs to be
7108   // converted to a VALU.
7109   for (MachineInstr &MI :
7110        make_range(std::next(MachineBasicBlock::reverse_iterator(SCCUseInst)),
7111                   SCCUseInst->getParent()->rend())) {
7112     if (MI.modifiesRegister(AMDGPU::VCC, &RI))
7113       break;
7114     if (MI.definesRegister(AMDGPU::SCC, &RI)) {
7115       Worklist.insert(&MI);
7116       break;
7117     }
7118   }
7119 }
7120 
7121 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
7122   const MachineInstr &Inst) const {
7123   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
7124 
7125   switch (Inst.getOpcode()) {
7126   // For target instructions, getOpRegClass just returns the virtual register
7127   // class associated with the operand, so we need to find an equivalent VGPR
7128   // register class in order to move the instruction to the VALU.
7129   case AMDGPU::COPY:
7130   case AMDGPU::PHI:
7131   case AMDGPU::REG_SEQUENCE:
7132   case AMDGPU::INSERT_SUBREG:
7133   case AMDGPU::WQM:
7134   case AMDGPU::SOFT_WQM:
7135   case AMDGPU::STRICT_WWM:
7136   case AMDGPU::STRICT_WQM: {
7137     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
7138     if (RI.isAGPRClass(SrcRC)) {
7139       if (RI.isAGPRClass(NewDstRC))
7140         return nullptr;
7141 
7142       switch (Inst.getOpcode()) {
7143       case AMDGPU::PHI:
7144       case AMDGPU::REG_SEQUENCE:
7145       case AMDGPU::INSERT_SUBREG:
7146         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
7147         break;
7148       default:
7149         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7150       }
7151 
7152       if (!NewDstRC)
7153         return nullptr;
7154     } else {
7155       if (RI.isVGPRClass(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
7156         return nullptr;
7157 
7158       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7159       if (!NewDstRC)
7160         return nullptr;
7161     }
7162 
7163     return NewDstRC;
7164   }
7165   default:
7166     return NewDstRC;
7167   }
7168 }
7169 
7170 // Find the one SGPR operand we are allowed to use.
7171 Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
7172                                    int OpIndices[3]) const {
7173   const MCInstrDesc &Desc = MI.getDesc();
7174 
7175   // Find the one SGPR operand we are allowed to use.
7176   //
7177   // First we need to consider the instruction's operand requirements before
7178   // legalizing. Some operands are required to be SGPRs, such as implicit uses
7179   // of VCC, but we are still bound by the constant bus requirement to only use
7180   // one.
7181   //
7182   // If the operand's class is an SGPR, we can never move it.
7183 
7184   Register SGPRReg = findImplicitSGPRRead(MI);
7185   if (SGPRReg != AMDGPU::NoRegister)
7186     return SGPRReg;
7187 
7188   Register UsedSGPRs[3] = { AMDGPU::NoRegister };
7189   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7190 
7191   for (unsigned i = 0; i < 3; ++i) {
7192     int Idx = OpIndices[i];
7193     if (Idx == -1)
7194       break;
7195 
7196     const MachineOperand &MO = MI.getOperand(Idx);
7197     if (!MO.isReg())
7198       continue;
7199 
7200     // Is this operand statically required to be an SGPR based on the operand
7201     // constraints?
7202     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
7203     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
7204     if (IsRequiredSGPR)
7205       return MO.getReg();
7206 
7207     // If this could be a VGPR or an SGPR, Check the dynamic register class.
7208     Register Reg = MO.getReg();
7209     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
7210     if (RI.isSGPRClass(RegRC))
7211       UsedSGPRs[i] = Reg;
7212   }
7213 
7214   // We don't have a required SGPR operand, so we have a bit more freedom in
7215   // selecting operands to move.
7216 
7217   // Try to select the most used SGPR. If an SGPR is equal to one of the
7218   // others, we choose that.
7219   //
7220   // e.g.
7221   // V_FMA_F32 v0, s0, s0, s0 -> No moves
7222   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
7223 
7224   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
7225   // prefer those.
7226 
7227   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
7228     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
7229       SGPRReg = UsedSGPRs[0];
7230   }
7231 
7232   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
7233     if (UsedSGPRs[1] == UsedSGPRs[2])
7234       SGPRReg = UsedSGPRs[1];
7235   }
7236 
7237   return SGPRReg;
7238 }
7239 
7240 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
7241                                              unsigned OperandName) const {
7242   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
7243   if (Idx == -1)
7244     return nullptr;
7245 
7246   return &MI.getOperand(Idx);
7247 }
7248 
7249 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
7250   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
7251     return (AMDGPU::MTBUFFormat::UFMT_32_FLOAT << 44) |
7252            (1ULL << 56) | // RESOURCE_LEVEL = 1
7253            (3ULL << 60); // OOB_SELECT = 3
7254   }
7255 
7256   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
7257   if (ST.isAmdHsaOS()) {
7258     // Set ATC = 1. GFX9 doesn't have this bit.
7259     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7260       RsrcDataFormat |= (1ULL << 56);
7261 
7262     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
7263     // BTW, it disables TC L2 and therefore decreases performance.
7264     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
7265       RsrcDataFormat |= (2ULL << 59);
7266   }
7267 
7268   return RsrcDataFormat;
7269 }
7270 
7271 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
7272   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
7273                     AMDGPU::RSRC_TID_ENABLE |
7274                     0xffffffff; // Size;
7275 
7276   // GFX9 doesn't have ELEMENT_SIZE.
7277   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
7278     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
7279     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
7280   }
7281 
7282   // IndexStride = 64 / 32.
7283   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
7284   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
7285 
7286   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
7287   // Clear them unless we want a huge stride.
7288   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
7289       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
7290     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
7291 
7292   return Rsrc23;
7293 }
7294 
7295 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
7296   unsigned Opc = MI.getOpcode();
7297 
7298   return isSMRD(Opc);
7299 }
7300 
7301 bool SIInstrInfo::isHighLatencyDef(int Opc) const {
7302   return get(Opc).mayLoad() &&
7303          (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
7304 }
7305 
7306 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
7307                                     int &FrameIndex) const {
7308   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
7309   if (!Addr || !Addr->isFI())
7310     return AMDGPU::NoRegister;
7311 
7312   assert(!MI.memoperands_empty() &&
7313          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
7314 
7315   FrameIndex = Addr->getIndex();
7316   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
7317 }
7318 
7319 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
7320                                         int &FrameIndex) const {
7321   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
7322   assert(Addr && Addr->isFI());
7323   FrameIndex = Addr->getIndex();
7324   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
7325 }
7326 
7327 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
7328                                           int &FrameIndex) const {
7329   if (!MI.mayLoad())
7330     return AMDGPU::NoRegister;
7331 
7332   if (isMUBUF(MI) || isVGPRSpill(MI))
7333     return isStackAccess(MI, FrameIndex);
7334 
7335   if (isSGPRSpill(MI))
7336     return isSGPRStackAccess(MI, FrameIndex);
7337 
7338   return AMDGPU::NoRegister;
7339 }
7340 
7341 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
7342                                          int &FrameIndex) const {
7343   if (!MI.mayStore())
7344     return AMDGPU::NoRegister;
7345 
7346   if (isMUBUF(MI) || isVGPRSpill(MI))
7347     return isStackAccess(MI, FrameIndex);
7348 
7349   if (isSGPRSpill(MI))
7350     return isSGPRStackAccess(MI, FrameIndex);
7351 
7352   return AMDGPU::NoRegister;
7353 }
7354 
7355 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
7356   unsigned Size = 0;
7357   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
7358   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
7359   while (++I != E && I->isInsideBundle()) {
7360     assert(!I->isBundle() && "No nested bundle!");
7361     Size += getInstSizeInBytes(*I);
7362   }
7363 
7364   return Size;
7365 }
7366 
7367 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
7368   unsigned Opc = MI.getOpcode();
7369   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
7370   unsigned DescSize = Desc.getSize();
7371 
7372   // If we have a definitive size, we can use it. Otherwise we need to inspect
7373   // the operands to know the size.
7374   if (isFixedSize(MI)) {
7375     unsigned Size = DescSize;
7376 
7377     // If we hit the buggy offset, an extra nop will be inserted in MC so
7378     // estimate the worst case.
7379     if (MI.isBranch() && ST.hasOffset3fBug())
7380       Size += 4;
7381 
7382     return Size;
7383   }
7384 
7385   // Instructions may have a 32-bit literal encoded after them. Check
7386   // operands that could ever be literals.
7387   if (isVALU(MI) || isSALU(MI)) {
7388     if (isDPP(MI))
7389       return DescSize;
7390     bool HasLiteral = false;
7391     for (int I = 0, E = MI.getNumExplicitOperands(); I != E; ++I) {
7392       if (isLiteralConstant(MI, I)) {
7393         HasLiteral = true;
7394         break;
7395       }
7396     }
7397     return HasLiteral ? DescSize + 4 : DescSize;
7398   }
7399 
7400   // Check whether we have extra NSA words.
7401   if (isMIMG(MI)) {
7402     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
7403     if (VAddr0Idx < 0)
7404       return 8;
7405 
7406     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
7407     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
7408   }
7409 
7410   switch (Opc) {
7411   case TargetOpcode::BUNDLE:
7412     return getInstBundleSize(MI);
7413   case TargetOpcode::INLINEASM:
7414   case TargetOpcode::INLINEASM_BR: {
7415     const MachineFunction *MF = MI.getParent()->getParent();
7416     const char *AsmStr = MI.getOperand(0).getSymbolName();
7417     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(), &ST);
7418   }
7419   default:
7420     if (MI.isMetaInstruction())
7421       return 0;
7422     return DescSize;
7423   }
7424 }
7425 
7426 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
7427   if (!isFLAT(MI))
7428     return false;
7429 
7430   if (MI.memoperands_empty())
7431     return true;
7432 
7433   for (const MachineMemOperand *MMO : MI.memoperands()) {
7434     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
7435       return true;
7436   }
7437   return false;
7438 }
7439 
7440 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
7441   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
7442 }
7443 
7444 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
7445                                             MachineBasicBlock *IfEnd) const {
7446   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
7447   assert(TI != IfEntry->end());
7448 
7449   MachineInstr *Branch = &(*TI);
7450   MachineFunction *MF = IfEntry->getParent();
7451   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
7452 
7453   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7454     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7455     MachineInstr *SIIF =
7456         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
7457             .add(Branch->getOperand(0))
7458             .add(Branch->getOperand(1));
7459     MachineInstr *SIEND =
7460         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
7461             .addReg(DstReg);
7462 
7463     IfEntry->erase(TI);
7464     IfEntry->insert(IfEntry->end(), SIIF);
7465     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
7466   }
7467 }
7468 
7469 void SIInstrInfo::convertNonUniformLoopRegion(
7470     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
7471   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
7472   // We expect 2 terminators, one conditional and one unconditional.
7473   assert(TI != LoopEnd->end());
7474 
7475   MachineInstr *Branch = &(*TI);
7476   MachineFunction *MF = LoopEnd->getParent();
7477   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
7478 
7479   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7480 
7481     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7482     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
7483     MachineInstrBuilder HeaderPHIBuilder =
7484         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
7485     for (MachineBasicBlock *PMBB : LoopEntry->predecessors()) {
7486       if (PMBB == LoopEnd) {
7487         HeaderPHIBuilder.addReg(BackEdgeReg);
7488       } else {
7489         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
7490         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
7491                              ZeroReg, 0);
7492         HeaderPHIBuilder.addReg(ZeroReg);
7493       }
7494       HeaderPHIBuilder.addMBB(PMBB);
7495     }
7496     MachineInstr *HeaderPhi = HeaderPHIBuilder;
7497     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
7498                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
7499                                   .addReg(DstReg)
7500                                   .add(Branch->getOperand(0));
7501     MachineInstr *SILOOP =
7502         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
7503             .addReg(BackEdgeReg)
7504             .addMBB(LoopEntry);
7505 
7506     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
7507     LoopEnd->erase(TI);
7508     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
7509     LoopEnd->insert(LoopEnd->end(), SILOOP);
7510   }
7511 }
7512 
7513 ArrayRef<std::pair<int, const char *>>
7514 SIInstrInfo::getSerializableTargetIndices() const {
7515   static const std::pair<int, const char *> TargetIndices[] = {
7516       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
7517       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
7518       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
7519       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
7520       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
7521   return makeArrayRef(TargetIndices);
7522 }
7523 
7524 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
7525 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
7526 ScheduleHazardRecognizer *
7527 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
7528                                             const ScheduleDAG *DAG) const {
7529   return new GCNHazardRecognizer(DAG->MF);
7530 }
7531 
7532 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
7533 /// pass.
7534 ScheduleHazardRecognizer *
7535 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
7536   return new GCNHazardRecognizer(MF);
7537 }
7538 
7539 // Called during:
7540 // - pre-RA scheduling and post-RA scheduling
7541 ScheduleHazardRecognizer *
7542 SIInstrInfo::CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
7543                                             const ScheduleDAGMI *DAG) const {
7544   // Borrowed from Arm Target
7545   // We would like to restrict this hazard recognizer to only
7546   // post-RA scheduling; we can tell that we're post-RA because we don't
7547   // track VRegLiveness.
7548   if (!DAG->hasVRegLiveness())
7549     return new GCNHazardRecognizer(DAG->MF);
7550   return TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
7551 }
7552 
7553 std::pair<unsigned, unsigned>
7554 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7555   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
7556 }
7557 
7558 ArrayRef<std::pair<unsigned, const char *>>
7559 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7560   static const std::pair<unsigned, const char *> TargetFlags[] = {
7561     { MO_GOTPCREL, "amdgpu-gotprel" },
7562     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
7563     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
7564     { MO_REL32_LO, "amdgpu-rel32-lo" },
7565     { MO_REL32_HI, "amdgpu-rel32-hi" },
7566     { MO_ABS32_LO, "amdgpu-abs32-lo" },
7567     { MO_ABS32_HI, "amdgpu-abs32-hi" },
7568   };
7569 
7570   return makeArrayRef(TargetFlags);
7571 }
7572 
7573 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
7574   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
7575          MI.modifiesRegister(AMDGPU::EXEC, &RI);
7576 }
7577 
7578 MachineInstrBuilder
7579 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7580                            MachineBasicBlock::iterator I,
7581                            const DebugLoc &DL,
7582                            Register DestReg) const {
7583   if (ST.hasAddNoCarry())
7584     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
7585 
7586   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7587   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
7588   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
7589 
7590   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7591            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7592 }
7593 
7594 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7595                                                MachineBasicBlock::iterator I,
7596                                                const DebugLoc &DL,
7597                                                Register DestReg,
7598                                                RegScavenger &RS) const {
7599   if (ST.hasAddNoCarry())
7600     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
7601 
7602   // If available, prefer to use vcc.
7603   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
7604                              ? Register(RI.getVCC())
7605                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
7606 
7607   // TODO: Users need to deal with this.
7608   if (!UnusedCarry.isValid())
7609     return MachineInstrBuilder();
7610 
7611   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7612            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7613 }
7614 
7615 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
7616   switch (Opcode) {
7617   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
7618   case AMDGPU::SI_KILL_I1_TERMINATOR:
7619     return true;
7620   default:
7621     return false;
7622   }
7623 }
7624 
7625 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
7626   switch (Opcode) {
7627   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7628     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
7629   case AMDGPU::SI_KILL_I1_PSEUDO:
7630     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
7631   default:
7632     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
7633   }
7634 }
7635 
7636 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
7637   if (!ST.isWave32())
7638     return;
7639 
7640   for (auto &Op : MI.implicit_operands()) {
7641     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
7642       Op.setReg(AMDGPU::VCC_LO);
7643   }
7644 }
7645 
7646 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
7647   if (!isSMRD(MI))
7648     return false;
7649 
7650   // Check that it is using a buffer resource.
7651   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
7652   if (Idx == -1) // e.g. s_memtime
7653     return false;
7654 
7655   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
7656   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
7657 }
7658 
7659 // Depending on the used address space and instructions, some immediate offsets
7660 // are allowed and some are not.
7661 // In general, flat instruction offsets can only be non-negative, global and
7662 // scratch instruction offsets can also be negative.
7663 //
7664 // There are several bugs related to these offsets:
7665 // On gfx10.1, flat instructions that go into the global address space cannot
7666 // use an offset.
7667 //
7668 // For scratch instructions, the address can be either an SGPR or a VGPR.
7669 // The following offsets can be used, depending on the architecture (x means
7670 // cannot be used):
7671 // +----------------------------+------+------+
7672 // | Address-Mode               | SGPR | VGPR |
7673 // +----------------------------+------+------+
7674 // | gfx9                       |      |      |
7675 // | negative, 4-aligned offset | x    | ok   |
7676 // | negative, unaligned offset | x    | ok   |
7677 // +----------------------------+------+------+
7678 // | gfx10                      |      |      |
7679 // | negative, 4-aligned offset | ok   | ok   |
7680 // | negative, unaligned offset | ok   | x    |
7681 // +----------------------------+------+------+
7682 // | gfx10.3                    |      |      |
7683 // | negative, 4-aligned offset | ok   | ok   |
7684 // | negative, unaligned offset | ok   | ok   |
7685 // +----------------------------+------+------+
7686 //
7687 // This function ignores the addressing mode, so if an offset cannot be used in
7688 // one addressing mode, it is considered illegal.
7689 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
7690                                     uint64_t FlatVariant) const {
7691   // TODO: Should 0 be special cased?
7692   if (!ST.hasFlatInstOffsets())
7693     return false;
7694 
7695   if (ST.hasFlatSegmentOffsetBug() && FlatVariant == SIInstrFlags::FLAT &&
7696       (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
7697        AddrSpace == AMDGPUAS::GLOBAL_ADDRESS))
7698     return false;
7699 
7700   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7701   if (ST.hasNegativeScratchOffsetBug() &&
7702       FlatVariant == SIInstrFlags::FlatScratch)
7703     Signed = false;
7704   if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7705       FlatVariant == SIInstrFlags::FlatScratch && Offset < 0 &&
7706       (Offset % 4) != 0) {
7707     return false;
7708   }
7709 
7710   unsigned N = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7711   return Signed ? isIntN(N, Offset) : isUIntN(N, Offset);
7712 }
7713 
7714 // See comment on SIInstrInfo::isLegalFLATOffset for what is legal and what not.
7715 std::pair<int64_t, int64_t>
7716 SIInstrInfo::splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace,
7717                              uint64_t FlatVariant) const {
7718   int64_t RemainderOffset = COffsetVal;
7719   int64_t ImmField = 0;
7720   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7721   if (ST.hasNegativeScratchOffsetBug() &&
7722       FlatVariant == SIInstrFlags::FlatScratch)
7723     Signed = false;
7724 
7725   const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7726   if (Signed) {
7727     // Use signed division by a power of two to truncate towards 0.
7728     int64_t D = 1LL << (NumBits - 1);
7729     RemainderOffset = (COffsetVal / D) * D;
7730     ImmField = COffsetVal - RemainderOffset;
7731 
7732     if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7733         FlatVariant == SIInstrFlags::FlatScratch && ImmField < 0 &&
7734         (ImmField % 4) != 0) {
7735       // Make ImmField a multiple of 4
7736       RemainderOffset += ImmField % 4;
7737       ImmField -= ImmField % 4;
7738     }
7739   } else if (COffsetVal >= 0) {
7740     ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
7741     RemainderOffset = COffsetVal - ImmField;
7742   }
7743 
7744   assert(isLegalFLATOffset(ImmField, AddrSpace, FlatVariant));
7745   assert(RemainderOffset + ImmField == COffsetVal);
7746   return {ImmField, RemainderOffset};
7747 }
7748 
7749 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
7750 enum SIEncodingFamily {
7751   SI = 0,
7752   VI = 1,
7753   SDWA = 2,
7754   SDWA9 = 3,
7755   GFX80 = 4,
7756   GFX9 = 5,
7757   GFX10 = 6,
7758   SDWA10 = 7,
7759   GFX90A = 8
7760 };
7761 
7762 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
7763   switch (ST.getGeneration()) {
7764   default:
7765     break;
7766   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
7767   case AMDGPUSubtarget::SEA_ISLANDS:
7768     return SIEncodingFamily::SI;
7769   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
7770   case AMDGPUSubtarget::GFX9:
7771     return SIEncodingFamily::VI;
7772   case AMDGPUSubtarget::GFX10:
7773     return SIEncodingFamily::GFX10;
7774   }
7775   llvm_unreachable("Unknown subtarget generation!");
7776 }
7777 
7778 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
7779   switch(MCOp) {
7780   // These opcodes use indirect register addressing so
7781   // they need special handling by codegen (currently missing).
7782   // Therefore it is too risky to allow these opcodes
7783   // to be selected by dpp combiner or sdwa peepholer.
7784   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
7785   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
7786   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
7787   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
7788   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
7789   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
7790   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
7791   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
7792     return true;
7793   default:
7794     return false;
7795   }
7796 }
7797 
7798 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
7799   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
7800 
7801   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
7802     ST.getGeneration() == AMDGPUSubtarget::GFX9)
7803     Gen = SIEncodingFamily::GFX9;
7804 
7805   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
7806   // subtarget has UnpackedD16VMem feature.
7807   // TODO: remove this when we discard GFX80 encoding.
7808   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
7809     Gen = SIEncodingFamily::GFX80;
7810 
7811   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
7812     switch (ST.getGeneration()) {
7813     default:
7814       Gen = SIEncodingFamily::SDWA;
7815       break;
7816     case AMDGPUSubtarget::GFX9:
7817       Gen = SIEncodingFamily::SDWA9;
7818       break;
7819     case AMDGPUSubtarget::GFX10:
7820       Gen = SIEncodingFamily::SDWA10;
7821       break;
7822     }
7823   }
7824 
7825   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
7826 
7827   // -1 means that Opcode is already a native instruction.
7828   if (MCOp == -1)
7829     return Opcode;
7830 
7831   if (ST.hasGFX90AInsts()) {
7832     uint16_t NMCOp = (uint16_t)-1;
7833       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX90A);
7834     if (NMCOp == (uint16_t)-1)
7835       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX9);
7836     if (NMCOp != (uint16_t)-1)
7837       MCOp = NMCOp;
7838   }
7839 
7840   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
7841   // no encoding in the given subtarget generation.
7842   if (MCOp == (uint16_t)-1)
7843     return -1;
7844 
7845   if (isAsmOnlyOpcode(MCOp))
7846     return -1;
7847 
7848   return MCOp;
7849 }
7850 
7851 static
7852 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
7853   assert(RegOpnd.isReg());
7854   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
7855                              getRegSubRegPair(RegOpnd);
7856 }
7857 
7858 TargetInstrInfo::RegSubRegPair
7859 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
7860   assert(MI.isRegSequence());
7861   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
7862     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
7863       auto &RegOp = MI.getOperand(1 + 2 * I);
7864       return getRegOrUndef(RegOp);
7865     }
7866   return TargetInstrInfo::RegSubRegPair();
7867 }
7868 
7869 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
7870 // Following a subreg of reg:subreg isn't supported
7871 static bool followSubRegDef(MachineInstr &MI,
7872                             TargetInstrInfo::RegSubRegPair &RSR) {
7873   if (!RSR.SubReg)
7874     return false;
7875   switch (MI.getOpcode()) {
7876   default: break;
7877   case AMDGPU::REG_SEQUENCE:
7878     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
7879     return true;
7880   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
7881   case AMDGPU::INSERT_SUBREG:
7882     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
7883       // inserted the subreg we're looking for
7884       RSR = getRegOrUndef(MI.getOperand(2));
7885     else { // the subreg in the rest of the reg
7886       auto R1 = getRegOrUndef(MI.getOperand(1));
7887       if (R1.SubReg) // subreg of subreg isn't supported
7888         return false;
7889       RSR.Reg = R1.Reg;
7890     }
7891     return true;
7892   }
7893   return false;
7894 }
7895 
7896 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
7897                                      MachineRegisterInfo &MRI) {
7898   assert(MRI.isSSA());
7899   if (!P.Reg.isVirtual())
7900     return nullptr;
7901 
7902   auto RSR = P;
7903   auto *DefInst = MRI.getVRegDef(RSR.Reg);
7904   while (auto *MI = DefInst) {
7905     DefInst = nullptr;
7906     switch (MI->getOpcode()) {
7907     case AMDGPU::COPY:
7908     case AMDGPU::V_MOV_B32_e32: {
7909       auto &Op1 = MI->getOperand(1);
7910       if (Op1.isReg() && Op1.getReg().isVirtual()) {
7911         if (Op1.isUndef())
7912           return nullptr;
7913         RSR = getRegSubRegPair(Op1);
7914         DefInst = MRI.getVRegDef(RSR.Reg);
7915       }
7916       break;
7917     }
7918     default:
7919       if (followSubRegDef(*MI, RSR)) {
7920         if (!RSR.Reg)
7921           return nullptr;
7922         DefInst = MRI.getVRegDef(RSR.Reg);
7923       }
7924     }
7925     if (!DefInst)
7926       return MI;
7927   }
7928   return nullptr;
7929 }
7930 
7931 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
7932                                       Register VReg,
7933                                       const MachineInstr &DefMI,
7934                                       const MachineInstr &UseMI) {
7935   assert(MRI.isSSA() && "Must be run on SSA");
7936 
7937   auto *TRI = MRI.getTargetRegisterInfo();
7938   auto *DefBB = DefMI.getParent();
7939 
7940   // Don't bother searching between blocks, although it is possible this block
7941   // doesn't modify exec.
7942   if (UseMI.getParent() != DefBB)
7943     return true;
7944 
7945   const int MaxInstScan = 20;
7946   int NumInst = 0;
7947 
7948   // Stop scan at the use.
7949   auto E = UseMI.getIterator();
7950   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
7951     if (I->isDebugInstr())
7952       continue;
7953 
7954     if (++NumInst > MaxInstScan)
7955       return true;
7956 
7957     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
7958       return true;
7959   }
7960 
7961   return false;
7962 }
7963 
7964 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
7965                                          Register VReg,
7966                                          const MachineInstr &DefMI) {
7967   assert(MRI.isSSA() && "Must be run on SSA");
7968 
7969   auto *TRI = MRI.getTargetRegisterInfo();
7970   auto *DefBB = DefMI.getParent();
7971 
7972   const int MaxUseScan = 10;
7973   int NumUse = 0;
7974 
7975   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
7976     auto &UseInst = *Use.getParent();
7977     // Don't bother searching between blocks, although it is possible this block
7978     // doesn't modify exec.
7979     if (UseInst.getParent() != DefBB)
7980       return true;
7981 
7982     if (++NumUse > MaxUseScan)
7983       return true;
7984   }
7985 
7986   if (NumUse == 0)
7987     return false;
7988 
7989   const int MaxInstScan = 20;
7990   int NumInst = 0;
7991 
7992   // Stop scan when we have seen all the uses.
7993   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
7994     assert(I != DefBB->end());
7995 
7996     if (I->isDebugInstr())
7997       continue;
7998 
7999     if (++NumInst > MaxInstScan)
8000       return true;
8001 
8002     for (const MachineOperand &Op : I->operands()) {
8003       // We don't check reg masks here as they're used only on calls:
8004       // 1. EXEC is only considered const within one BB
8005       // 2. Call should be a terminator instruction if present in a BB
8006 
8007       if (!Op.isReg())
8008         continue;
8009 
8010       Register Reg = Op.getReg();
8011       if (Op.isUse()) {
8012         if (Reg == VReg && --NumUse == 0)
8013           return false;
8014       } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
8015         return true;
8016     }
8017   }
8018 }
8019 
8020 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
8021     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
8022     const DebugLoc &DL, Register Src, Register Dst) const {
8023   auto Cur = MBB.begin();
8024   if (Cur != MBB.end())
8025     do {
8026       if (!Cur->isPHI() && Cur->readsRegister(Dst))
8027         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
8028       ++Cur;
8029     } while (Cur != MBB.end() && Cur != LastPHIIt);
8030 
8031   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
8032                                                    Dst);
8033 }
8034 
8035 MachineInstr *SIInstrInfo::createPHISourceCopy(
8036     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
8037     const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
8038   if (InsPt != MBB.end() &&
8039       (InsPt->getOpcode() == AMDGPU::SI_IF ||
8040        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
8041        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
8042       InsPt->definesRegister(Src)) {
8043     InsPt++;
8044     return BuildMI(MBB, InsPt, DL,
8045                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
8046                                      : AMDGPU::S_MOV_B64_term),
8047                    Dst)
8048         .addReg(Src, 0, SrcSubReg)
8049         .addReg(AMDGPU::EXEC, RegState::Implicit);
8050   }
8051   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
8052                                               Dst);
8053 }
8054 
8055 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
8056 
8057 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
8058     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
8059     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
8060     VirtRegMap *VRM) const {
8061   // This is a bit of a hack (copied from AArch64). Consider this instruction:
8062   //
8063   //   %0:sreg_32 = COPY $m0
8064   //
8065   // We explicitly chose SReg_32 for the virtual register so such a copy might
8066   // be eliminated by RegisterCoalescer. However, that may not be possible, and
8067   // %0 may even spill. We can't spill $m0 normally (it would require copying to
8068   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
8069   // TargetInstrInfo::foldMemoryOperand() is going to try.
8070   // A similar issue also exists with spilling and reloading $exec registers.
8071   //
8072   // To prevent that, constrain the %0 register class here.
8073   if (MI.isFullCopy()) {
8074     Register DstReg = MI.getOperand(0).getReg();
8075     Register SrcReg = MI.getOperand(1).getReg();
8076     if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
8077         (DstReg.isVirtual() != SrcReg.isVirtual())) {
8078       MachineRegisterInfo &MRI = MF.getRegInfo();
8079       Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
8080       const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
8081       if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
8082         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
8083         return nullptr;
8084       } else if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
8085         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
8086         return nullptr;
8087       }
8088     }
8089   }
8090 
8091   return nullptr;
8092 }
8093 
8094 unsigned SIInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
8095                                       const MachineInstr &MI,
8096                                       unsigned *PredCost) const {
8097   if (MI.isBundle()) {
8098     MachineBasicBlock::const_instr_iterator I(MI.getIterator());
8099     MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
8100     unsigned Lat = 0, Count = 0;
8101     for (++I; I != E && I->isBundledWithPred(); ++I) {
8102       ++Count;
8103       Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
8104     }
8105     return Lat + Count - 1;
8106   }
8107 
8108   return SchedModel.computeInstrLatency(&MI);
8109 }
8110 
8111 unsigned SIInstrInfo::getDSShaderTypeValue(const MachineFunction &MF) {
8112   switch (MF.getFunction().getCallingConv()) {
8113   case CallingConv::AMDGPU_PS:
8114     return 1;
8115   case CallingConv::AMDGPU_VS:
8116     return 2;
8117   case CallingConv::AMDGPU_GS:
8118     return 3;
8119   case CallingConv::AMDGPU_HS:
8120   case CallingConv::AMDGPU_LS:
8121   case CallingConv::AMDGPU_ES:
8122     report_fatal_error("ds_ordered_count unsupported for this calling conv");
8123   case CallingConv::AMDGPU_CS:
8124   case CallingConv::AMDGPU_KERNEL:
8125   case CallingConv::C:
8126   case CallingConv::Fast:
8127   default:
8128     // Assume other calling conventions are various compute callable functions
8129     return 0;
8130   }
8131 }
8132 
8133 bool SIInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
8134                                  Register &SrcReg2, int64_t &CmpMask,
8135                                  int64_t &CmpValue) const {
8136   if (!MI.getOperand(0).isReg() || MI.getOperand(0).getSubReg())
8137     return false;
8138 
8139   switch (MI.getOpcode()) {
8140   default:
8141     break;
8142   case AMDGPU::S_CMP_EQ_U32:
8143   case AMDGPU::S_CMP_EQ_I32:
8144   case AMDGPU::S_CMP_LG_U32:
8145   case AMDGPU::S_CMP_LG_I32:
8146   case AMDGPU::S_CMP_LT_U32:
8147   case AMDGPU::S_CMP_LT_I32:
8148   case AMDGPU::S_CMP_GT_U32:
8149   case AMDGPU::S_CMP_GT_I32:
8150   case AMDGPU::S_CMP_LE_U32:
8151   case AMDGPU::S_CMP_LE_I32:
8152   case AMDGPU::S_CMP_GE_U32:
8153   case AMDGPU::S_CMP_GE_I32:
8154   case AMDGPU::S_CMP_EQ_U64:
8155   case AMDGPU::S_CMP_LG_U64:
8156     SrcReg = MI.getOperand(0).getReg();
8157     if (MI.getOperand(1).isReg()) {
8158       if (MI.getOperand(1).getSubReg())
8159         return false;
8160       SrcReg2 = MI.getOperand(1).getReg();
8161       CmpValue = 0;
8162     } else if (MI.getOperand(1).isImm()) {
8163       SrcReg2 = Register();
8164       CmpValue = MI.getOperand(1).getImm();
8165     } else {
8166       return false;
8167     }
8168     CmpMask = ~0;
8169     return true;
8170   case AMDGPU::S_CMPK_EQ_U32:
8171   case AMDGPU::S_CMPK_EQ_I32:
8172   case AMDGPU::S_CMPK_LG_U32:
8173   case AMDGPU::S_CMPK_LG_I32:
8174   case AMDGPU::S_CMPK_LT_U32:
8175   case AMDGPU::S_CMPK_LT_I32:
8176   case AMDGPU::S_CMPK_GT_U32:
8177   case AMDGPU::S_CMPK_GT_I32:
8178   case AMDGPU::S_CMPK_LE_U32:
8179   case AMDGPU::S_CMPK_LE_I32:
8180   case AMDGPU::S_CMPK_GE_U32:
8181   case AMDGPU::S_CMPK_GE_I32:
8182     SrcReg = MI.getOperand(0).getReg();
8183     SrcReg2 = Register();
8184     CmpValue = MI.getOperand(1).getImm();
8185     CmpMask = ~0;
8186     return true;
8187   }
8188 
8189   return false;
8190 }
8191 
8192 bool SIInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
8193                                        Register SrcReg2, int64_t CmpMask,
8194                                        int64_t CmpValue,
8195                                        const MachineRegisterInfo *MRI) const {
8196   if (!SrcReg || SrcReg.isPhysical())
8197     return false;
8198 
8199   if (SrcReg2 && !getFoldableImm(SrcReg2, *MRI, CmpValue))
8200     return false;
8201 
8202   const auto optimizeCmpAnd = [&CmpInstr, SrcReg, CmpValue, MRI,
8203                                this](int64_t ExpectedValue, unsigned SrcSize,
8204                                      bool IsReversable, bool IsSigned) -> bool {
8205     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8206     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8207     // s_cmp_ge_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8208     // s_cmp_ge_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8209     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 1 << n => s_and_b64 $src, 1 << n
8210     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8211     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8212     // s_cmp_gt_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8213     // s_cmp_gt_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8214     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 0 => s_and_b64 $src, 1 << n
8215     //
8216     // Signed ge/gt are not used for the sign bit.
8217     //
8218     // If result of the AND is unused except in the compare:
8219     // s_and_b(32|64) $src, 1 << n => s_bitcmp1_b(32|64) $src, n
8220     //
8221     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8222     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8223     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 0 => s_bitcmp0_b64 $src, n
8224     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8225     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8226     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 1 << n => s_bitcmp0_b64 $src, n
8227 
8228     MachineInstr *Def = MRI->getUniqueVRegDef(SrcReg);
8229     if (!Def || Def->getParent() != CmpInstr.getParent())
8230       return false;
8231 
8232     if (Def->getOpcode() != AMDGPU::S_AND_B32 &&
8233         Def->getOpcode() != AMDGPU::S_AND_B64)
8234       return false;
8235 
8236     int64_t Mask;
8237     const auto isMask = [&Mask, SrcSize](const MachineOperand *MO) -> bool {
8238       if (MO->isImm())
8239         Mask = MO->getImm();
8240       else if (!getFoldableImm(MO, Mask))
8241         return false;
8242       Mask &= maxUIntN(SrcSize);
8243       return isPowerOf2_64(Mask);
8244     };
8245 
8246     MachineOperand *SrcOp = &Def->getOperand(1);
8247     if (isMask(SrcOp))
8248       SrcOp = &Def->getOperand(2);
8249     else if (isMask(&Def->getOperand(2)))
8250       SrcOp = &Def->getOperand(1);
8251     else
8252       return false;
8253 
8254     unsigned BitNo = countTrailingZeros((uint64_t)Mask);
8255     if (IsSigned && BitNo == SrcSize - 1)
8256       return false;
8257 
8258     ExpectedValue <<= BitNo;
8259 
8260     bool IsReversedCC = false;
8261     if (CmpValue != ExpectedValue) {
8262       if (!IsReversable)
8263         return false;
8264       IsReversedCC = CmpValue == (ExpectedValue ^ Mask);
8265       if (!IsReversedCC)
8266         return false;
8267     }
8268 
8269     Register DefReg = Def->getOperand(0).getReg();
8270     if (IsReversedCC && !MRI->hasOneNonDBGUse(DefReg))
8271       return false;
8272 
8273     for (auto I = std::next(Def->getIterator()), E = CmpInstr.getIterator();
8274          I != E; ++I) {
8275       if (I->modifiesRegister(AMDGPU::SCC, &RI) ||
8276           I->killsRegister(AMDGPU::SCC, &RI))
8277         return false;
8278     }
8279 
8280     MachineOperand *SccDef = Def->findRegisterDefOperand(AMDGPU::SCC);
8281     SccDef->setIsDead(false);
8282     CmpInstr.eraseFromParent();
8283 
8284     if (!MRI->use_nodbg_empty(DefReg)) {
8285       assert(!IsReversedCC);
8286       return true;
8287     }
8288 
8289     // Replace AND with unused result with a S_BITCMP.
8290     MachineBasicBlock *MBB = Def->getParent();
8291 
8292     unsigned NewOpc = (SrcSize == 32) ? IsReversedCC ? AMDGPU::S_BITCMP0_B32
8293                                                      : AMDGPU::S_BITCMP1_B32
8294                                       : IsReversedCC ? AMDGPU::S_BITCMP0_B64
8295                                                      : AMDGPU::S_BITCMP1_B64;
8296 
8297     BuildMI(*MBB, Def, Def->getDebugLoc(), get(NewOpc))
8298       .add(*SrcOp)
8299       .addImm(BitNo);
8300     Def->eraseFromParent();
8301 
8302     return true;
8303   };
8304 
8305   switch (CmpInstr.getOpcode()) {
8306   default:
8307     break;
8308   case AMDGPU::S_CMP_EQ_U32:
8309   case AMDGPU::S_CMP_EQ_I32:
8310   case AMDGPU::S_CMPK_EQ_U32:
8311   case AMDGPU::S_CMPK_EQ_I32:
8312     return optimizeCmpAnd(1, 32, true, false);
8313   case AMDGPU::S_CMP_GE_U32:
8314   case AMDGPU::S_CMPK_GE_U32:
8315     return optimizeCmpAnd(1, 32, false, false);
8316   case AMDGPU::S_CMP_GE_I32:
8317   case AMDGPU::S_CMPK_GE_I32:
8318     return optimizeCmpAnd(1, 32, false, true);
8319   case AMDGPU::S_CMP_EQ_U64:
8320     return optimizeCmpAnd(1, 64, true, false);
8321   case AMDGPU::S_CMP_LG_U32:
8322   case AMDGPU::S_CMP_LG_I32:
8323   case AMDGPU::S_CMPK_LG_U32:
8324   case AMDGPU::S_CMPK_LG_I32:
8325     return optimizeCmpAnd(0, 32, true, false);
8326   case AMDGPU::S_CMP_GT_U32:
8327   case AMDGPU::S_CMPK_GT_U32:
8328     return optimizeCmpAnd(0, 32, false, false);
8329   case AMDGPU::S_CMP_GT_I32:
8330   case AMDGPU::S_CMPK_GT_I32:
8331     return optimizeCmpAnd(0, 32, false, true);
8332   case AMDGPU::S_CMP_LG_U64:
8333     return optimizeCmpAnd(0, 64, true, false);
8334   }
8335 
8336   return false;
8337 }
8338