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