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 "AMDGPUSubtarget.h"
17 #include "GCNHazardRecognizer.h"
18 #include "SIDefines.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/MemoryLocation.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineInstrBundle.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RegisterScavenging.h"
42 #include "llvm/CodeGen/ScheduleDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetOpcodes.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DiagnosticInfo.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/MC/MCInstrDesc.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MachineValueType.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Target/TargetMachine.h"
59 #include <cassert>
60 #include <cstdint>
61 #include <iterator>
62 #include <utility>
63 
64 using namespace llvm;
65 
66 #define GET_INSTRINFO_CTOR_DTOR
67 #include "AMDGPUGenInstrInfo.inc"
68 
69 namespace llvm {
70 namespace AMDGPU {
71 #define GET_D16ImageDimIntrinsics_IMPL
72 #define GET_ImageDimIntrinsicTable_IMPL
73 #define GET_RsrcIntrinsics_IMPL
74 #include "AMDGPUGenSearchableTables.inc"
75 }
76 }
77 
78 
79 // Must be at least 4 to be able to branch over minimum unconditional branch
80 // code. This is only for making it possible to write reasonably small tests for
81 // long branches.
82 static cl::opt<unsigned>
83 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
84                  cl::desc("Restrict range of branch instructions (DEBUG)"));
85 
86 SIInstrInfo::SIInstrInfo(const GCNSubtarget &ST)
87   : AMDGPUGenInstrInfo(AMDGPU::ADJCALLSTACKUP, AMDGPU::ADJCALLSTACKDOWN),
88     RI(ST), ST(ST) {}
89 
90 //===----------------------------------------------------------------------===//
91 // TargetInstrInfo callbacks
92 //===----------------------------------------------------------------------===//
93 
94 static unsigned getNumOperandsNoGlue(SDNode *Node) {
95   unsigned N = Node->getNumOperands();
96   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
97     --N;
98   return N;
99 }
100 
101 /// Returns true if both nodes have the same value for the given
102 ///        operand \p Op, or if both nodes do not have this operand.
103 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
104   unsigned Opc0 = N0->getMachineOpcode();
105   unsigned Opc1 = N1->getMachineOpcode();
106 
107   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
108   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
109 
110   if (Op0Idx == -1 && Op1Idx == -1)
111     return true;
112 
113 
114   if ((Op0Idx == -1 && Op1Idx != -1) ||
115       (Op1Idx == -1 && Op0Idx != -1))
116     return false;
117 
118   // getNamedOperandIdx returns the index for the MachineInstr's operands,
119   // which includes the result as the first operand. We are indexing into the
120   // MachineSDNode's operands, so we need to skip the result operand to get
121   // the real index.
122   --Op0Idx;
123   --Op1Idx;
124 
125   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
126 }
127 
128 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
129                                                     AliasAnalysis *AA) const {
130   // TODO: The generic check fails for VALU instructions that should be
131   // rematerializable due to implicit reads of exec. We really want all of the
132   // generic logic for this except for this.
133   switch (MI.getOpcode()) {
134   case AMDGPU::V_MOV_B32_e32:
135   case AMDGPU::V_MOV_B32_e64:
136   case AMDGPU::V_MOV_B64_PSEUDO:
137     // No implicit operands.
138     return MI.getNumOperands() == MI.getDesc().getNumOperands();
139   default:
140     return false;
141   }
142 }
143 
144 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
145                                           int64_t &Offset0,
146                                           int64_t &Offset1) const {
147   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
148     return false;
149 
150   unsigned Opc0 = Load0->getMachineOpcode();
151   unsigned Opc1 = Load1->getMachineOpcode();
152 
153   // Make sure both are actually loads.
154   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
155     return false;
156 
157   if (isDS(Opc0) && isDS(Opc1)) {
158 
159     // FIXME: Handle this case:
160     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
161       return false;
162 
163     // Check base reg.
164     if (Load0->getOperand(0) != Load1->getOperand(0))
165       return false;
166 
167     // Skip read2 / write2 variants for simplicity.
168     // TODO: We should report true if the used offsets are adjacent (excluded
169     // st64 versions).
170     int Offset0Idx = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
171     int Offset1Idx = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
172     if (Offset0Idx == -1 || Offset1Idx == -1)
173       return false;
174 
175     // XXX - be careful of datalesss loads
176     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
177     // include the output in the operand list, but SDNodes don't, we need to
178     // subtract the index by one.
179     Offset0Idx -= get(Opc0).NumDefs;
180     Offset1Idx -= get(Opc1).NumDefs;
181     Offset0 = cast<ConstantSDNode>(Load0->getOperand(Offset0Idx))->getZExtValue();
182     Offset1 = cast<ConstantSDNode>(Load1->getOperand(Offset1Idx))->getZExtValue();
183     return true;
184   }
185 
186   if (isSMRD(Opc0) && isSMRD(Opc1)) {
187     // Skip time and cache invalidation instructions.
188     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::sbase) == -1 ||
189         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::sbase) == -1)
190       return false;
191 
192     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
193 
194     // Check base reg.
195     if (Load0->getOperand(0) != Load1->getOperand(0))
196       return false;
197 
198     const ConstantSDNode *Load0Offset =
199         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
200     const ConstantSDNode *Load1Offset =
201         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
202 
203     if (!Load0Offset || !Load1Offset)
204       return false;
205 
206     Offset0 = Load0Offset->getZExtValue();
207     Offset1 = Load1Offset->getZExtValue();
208     return true;
209   }
210 
211   // MUBUF and MTBUF can access the same addresses.
212   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
213 
214     // MUBUF and MTBUF have vaddr at different indices.
215     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
216         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
217         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
218       return false;
219 
220     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
221     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
222 
223     if (OffIdx0 == -1 || OffIdx1 == -1)
224       return false;
225 
226     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
227     // include the output in the operand list, but SDNodes don't, we need to
228     // subtract the index by one.
229     OffIdx0 -= get(Opc0).NumDefs;
230     OffIdx1 -= get(Opc1).NumDefs;
231 
232     SDValue Off0 = Load0->getOperand(OffIdx0);
233     SDValue Off1 = Load1->getOperand(OffIdx1);
234 
235     // The offset might be a FrameIndexSDNode.
236     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
237       return false;
238 
239     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
240     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
241     return true;
242   }
243 
244   return false;
245 }
246 
247 static bool isStride64(unsigned Opc) {
248   switch (Opc) {
249   case AMDGPU::DS_READ2ST64_B32:
250   case AMDGPU::DS_READ2ST64_B64:
251   case AMDGPU::DS_WRITE2ST64_B32:
252   case AMDGPU::DS_WRITE2ST64_B64:
253     return true;
254   default:
255     return false;
256   }
257 }
258 
259 bool SIInstrInfo::getMemOperandWithOffset(const MachineInstr &LdSt,
260                                           const MachineOperand *&BaseOp,
261                                           int64_t &Offset,
262                                           const TargetRegisterInfo *TRI) const {
263   if (!LdSt.mayLoadOrStore())
264     return false;
265 
266   unsigned Opc = LdSt.getOpcode();
267 
268   if (isDS(LdSt)) {
269     const MachineOperand *OffsetImm =
270         getNamedOperand(LdSt, AMDGPU::OpName::offset);
271     if (OffsetImm) {
272       // Normal, single offset LDS instruction.
273       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
274       // TODO: ds_consume/ds_append use M0 for the base address. Is it safe to
275       // report that here?
276       if (!BaseOp || !BaseOp->isReg())
277         return false;
278 
279       Offset = OffsetImm->getImm();
280 
281       return true;
282     }
283 
284     // The 2 offset instructions use offset0 and offset1 instead. We can treat
285     // these as a load with a single offset if the 2 offsets are consecutive. We
286     // will use this for some partially aligned loads.
287     const MachineOperand *Offset0Imm =
288         getNamedOperand(LdSt, AMDGPU::OpName::offset0);
289     const MachineOperand *Offset1Imm =
290         getNamedOperand(LdSt, AMDGPU::OpName::offset1);
291 
292     uint8_t Offset0 = Offset0Imm->getImm();
293     uint8_t Offset1 = Offset1Imm->getImm();
294 
295     if (Offset1 > Offset0 && Offset1 - Offset0 == 1) {
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       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
312       if (!BaseOp->isReg())
313         return false;
314 
315       Offset = EltSize * Offset0;
316 
317       return true;
318     }
319 
320     return false;
321   }
322 
323   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
324     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
325     if (SOffset && SOffset->isReg()) {
326       // We can only handle this if it's a stack access, as any other resource
327       // would require reporting multiple base registers.
328       const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
329       if (AddrReg && !AddrReg->isFI())
330         return false;
331 
332       const MachineOperand *RSrc = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
333       const SIMachineFunctionInfo *MFI
334         = LdSt.getParent()->getParent()->getInfo<SIMachineFunctionInfo>();
335       if (RSrc->getReg() != MFI->getScratchRSrcReg())
336         return false;
337 
338       const MachineOperand *OffsetImm =
339         getNamedOperand(LdSt, AMDGPU::OpName::offset);
340       BaseOp = SOffset;
341       Offset = OffsetImm->getImm();
342       return true;
343     }
344 
345     const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
346     if (!AddrReg)
347       return false;
348 
349     const MachineOperand *OffsetImm =
350         getNamedOperand(LdSt, AMDGPU::OpName::offset);
351     BaseOp = AddrReg;
352     Offset = OffsetImm->getImm();
353     if (SOffset) // soffset can be an inline immediate.
354       Offset += SOffset->getImm();
355 
356     if (!BaseOp->isReg())
357       return false;
358 
359     return true;
360   }
361 
362   if (isSMRD(LdSt)) {
363     const MachineOperand *OffsetImm =
364         getNamedOperand(LdSt, AMDGPU::OpName::offset);
365     if (!OffsetImm)
366       return false;
367 
368     const MachineOperand *SBaseReg = getNamedOperand(LdSt, AMDGPU::OpName::sbase);
369     BaseOp = SBaseReg;
370     Offset = OffsetImm->getImm();
371     if (!BaseOp->isReg())
372       return false;
373 
374     return true;
375   }
376 
377   if (isFLAT(LdSt)) {
378     const MachineOperand *VAddr = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
379     if (VAddr) {
380       // Can't analyze 2 offsets.
381       if (getNamedOperand(LdSt, AMDGPU::OpName::saddr))
382         return false;
383 
384       BaseOp = VAddr;
385     } else {
386       // scratch instructions have either vaddr or saddr.
387       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::saddr);
388     }
389 
390     Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
391     if (!BaseOp->isReg())
392       return false;
393     return true;
394   }
395 
396   return false;
397 }
398 
399 static bool memOpsHaveSameBasePtr(const MachineInstr &MI1,
400                                   const MachineOperand &BaseOp1,
401                                   const MachineInstr &MI2,
402                                   const MachineOperand &BaseOp2) {
403   // Support only base operands with base registers.
404   // Note: this could be extended to support FI operands.
405   if (!BaseOp1.isReg() || !BaseOp2.isReg())
406     return false;
407 
408   if (BaseOp1.isIdenticalTo(BaseOp2))
409     return true;
410 
411   if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
412     return false;
413 
414   auto MO1 = *MI1.memoperands_begin();
415   auto MO2 = *MI2.memoperands_begin();
416   if (MO1->getAddrSpace() != MO2->getAddrSpace())
417     return false;
418 
419   auto Base1 = MO1->getValue();
420   auto Base2 = MO2->getValue();
421   if (!Base1 || !Base2)
422     return false;
423   const MachineFunction &MF = *MI1.getParent()->getParent();
424   const DataLayout &DL = MF.getFunction().getParent()->getDataLayout();
425   Base1 = GetUnderlyingObject(Base1, DL);
426   Base2 = GetUnderlyingObject(Base2, DL);
427 
428   if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
429     return false;
430 
431   return Base1 == Base2;
432 }
433 
434 bool SIInstrInfo::shouldClusterMemOps(const MachineOperand &BaseOp1,
435                                       const MachineOperand &BaseOp2,
436                                       unsigned NumLoads) const {
437   const MachineInstr &FirstLdSt = *BaseOp1.getParent();
438   const MachineInstr &SecondLdSt = *BaseOp2.getParent();
439 
440   if (!memOpsHaveSameBasePtr(FirstLdSt, BaseOp1, SecondLdSt, BaseOp2))
441     return false;
442 
443   const MachineOperand *FirstDst = nullptr;
444   const MachineOperand *SecondDst = nullptr;
445 
446   if ((isMUBUF(FirstLdSt) && isMUBUF(SecondLdSt)) ||
447       (isMTBUF(FirstLdSt) && isMTBUF(SecondLdSt)) ||
448       (isFLAT(FirstLdSt) && isFLAT(SecondLdSt))) {
449     const unsigned MaxGlobalLoadCluster = 6;
450     if (NumLoads > MaxGlobalLoadCluster)
451       return false;
452 
453     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdata);
454     if (!FirstDst)
455       FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
456     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdata);
457     if (!SecondDst)
458       SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
459   } else if (isSMRD(FirstLdSt) && isSMRD(SecondLdSt)) {
460     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::sdst);
461     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::sdst);
462   } else if (isDS(FirstLdSt) && isDS(SecondLdSt)) {
463     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
464     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
465   }
466 
467   if (!FirstDst || !SecondDst)
468     return false;
469 
470   // Try to limit clustering based on the total number of bytes loaded
471   // rather than the number of instructions.  This is done to help reduce
472   // register pressure.  The method used is somewhat inexact, though,
473   // because it assumes that all loads in the cluster will load the
474   // same number of bytes as FirstLdSt.
475 
476   // The unit of this value is bytes.
477   // FIXME: This needs finer tuning.
478   unsigned LoadClusterThreshold = 16;
479 
480   const MachineRegisterInfo &MRI =
481       FirstLdSt.getParent()->getParent()->getRegInfo();
482 
483   const Register Reg = FirstDst->getReg();
484 
485   const TargetRegisterClass *DstRC = Register::isVirtualRegister(Reg)
486                                          ? MRI.getRegClass(Reg)
487                                          : RI.getPhysRegClass(Reg);
488 
489   return (NumLoads * (RI.getRegSizeInBits(*DstRC) / 8)) <= LoadClusterThreshold;
490 }
491 
492 // FIXME: This behaves strangely. If, for example, you have 32 load + stores,
493 // the first 16 loads will be interleaved with the stores, and the next 16 will
494 // be clustered as expected. It should really split into 2 16 store batches.
495 //
496 // Loads are clustered until this returns false, rather than trying to schedule
497 // groups of stores. This also means we have to deal with saying different
498 // address space loads should be clustered, and ones which might cause bank
499 // conflicts.
500 //
501 // This might be deprecated so it might not be worth that much effort to fix.
502 bool SIInstrInfo::shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1,
503                                           int64_t Offset0, int64_t Offset1,
504                                           unsigned NumLoads) const {
505   assert(Offset1 > Offset0 &&
506          "Second offset should be larger than first offset!");
507   // If we have less than 16 loads in a row, and the offsets are within 64
508   // bytes, then schedule together.
509 
510   // A cacheline is 64 bytes (for global memory).
511   return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
512 }
513 
514 static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB,
515                               MachineBasicBlock::iterator MI,
516                               const DebugLoc &DL, MCRegister DestReg,
517                               MCRegister SrcReg, bool KillSrc) {
518   MachineFunction *MF = MBB.getParent();
519   DiagnosticInfoUnsupported IllegalCopy(MF->getFunction(),
520                                         "illegal SGPR to VGPR copy",
521                                         DL, DS_Error);
522   LLVMContext &C = MF->getFunction().getContext();
523   C.diagnose(IllegalCopy);
524 
525   BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
526     .addReg(SrcReg, getKillRegState(KillSrc));
527 }
528 
529 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
530                               MachineBasicBlock::iterator MI,
531                               const DebugLoc &DL, MCRegister DestReg,
532                               MCRegister SrcReg, bool KillSrc) const {
533   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
534 
535   if (RC == &AMDGPU::VGPR_32RegClass) {
536     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
537            AMDGPU::SReg_32RegClass.contains(SrcReg) ||
538            AMDGPU::AGPR_32RegClass.contains(SrcReg));
539     unsigned Opc = AMDGPU::AGPR_32RegClass.contains(SrcReg) ?
540                      AMDGPU::V_ACCVGPR_READ_B32 : AMDGPU::V_MOV_B32_e32;
541     BuildMI(MBB, MI, DL, get(Opc), DestReg)
542       .addReg(SrcReg, getKillRegState(KillSrc));
543     return;
544   }
545 
546   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
547       RC == &AMDGPU::SReg_32RegClass) {
548     if (SrcReg == AMDGPU::SCC) {
549       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
550           .addImm(1)
551           .addImm(0);
552       return;
553     }
554 
555     if (DestReg == AMDGPU::VCC_LO) {
556       if (AMDGPU::SReg_32RegClass.contains(SrcReg)) {
557         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), AMDGPU::VCC_LO)
558           .addReg(SrcReg, getKillRegState(KillSrc));
559       } else {
560         // FIXME: Hack until VReg_1 removed.
561         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
562         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
563           .addImm(0)
564           .addReg(SrcReg, getKillRegState(KillSrc));
565       }
566 
567       return;
568     }
569 
570     if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
571       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
572       return;
573     }
574 
575     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
576             .addReg(SrcReg, getKillRegState(KillSrc));
577     return;
578   }
579 
580   if (RC == &AMDGPU::SReg_64RegClass) {
581     if (DestReg == AMDGPU::VCC) {
582       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
583         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
584           .addReg(SrcReg, getKillRegState(KillSrc));
585       } else {
586         // FIXME: Hack until VReg_1 removed.
587         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
588         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
589           .addImm(0)
590           .addReg(SrcReg, getKillRegState(KillSrc));
591       }
592 
593       return;
594     }
595 
596     if (!AMDGPU::SReg_64RegClass.contains(SrcReg)) {
597       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
598       return;
599     }
600 
601     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
602             .addReg(SrcReg, getKillRegState(KillSrc));
603     return;
604   }
605 
606   if (DestReg == AMDGPU::SCC) {
607     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
608     BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
609       .addReg(SrcReg, getKillRegState(KillSrc))
610       .addImm(0);
611     return;
612   }
613 
614   if (RC == &AMDGPU::AGPR_32RegClass) {
615     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
616            AMDGPU::SReg_32RegClass.contains(SrcReg) ||
617            AMDGPU::AGPR_32RegClass.contains(SrcReg));
618     if (!AMDGPU::VGPR_32RegClass.contains(SrcReg)) {
619       // First try to find defining accvgpr_write to avoid temporary registers.
620       for (auto Def = MI, E = MBB.begin(); Def != E; ) {
621         --Def;
622         if (!Def->definesRegister(SrcReg, &RI))
623           continue;
624         if (Def->getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32)
625           break;
626 
627         MachineOperand &DefOp = Def->getOperand(1);
628         assert(DefOp.isReg() || DefOp.isImm());
629 
630         if (DefOp.isReg()) {
631           // Check that register source operand if not clobbered before MI.
632           // Immediate operands are always safe to propagate.
633           bool SafeToPropagate = true;
634           for (auto I = Def; I != MI && SafeToPropagate; ++I)
635             if (I->modifiesRegister(DefOp.getReg(), &RI))
636               SafeToPropagate = false;
637 
638           if (!SafeToPropagate)
639             break;
640 
641           DefOp.setIsKill(false);
642         }
643 
644         BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32), DestReg)
645           .add(DefOp);
646         return;
647       }
648 
649       RegScavenger RS;
650       RS.enterBasicBlock(MBB);
651       RS.forward(MI);
652 
653       // Ideally we want to have three registers for a long reg_sequence copy
654       // to hide 2 waitstates between v_mov_b32 and accvgpr_write.
655       unsigned MaxVGPRs = RI.getRegPressureLimit(&AMDGPU::VGPR_32RegClass,
656                                                  *MBB.getParent());
657 
658       // Registers in the sequence are allocated contiguously so we can just
659       // use register number to pick one of three round-robin temps.
660       unsigned RegNo = DestReg % 3;
661       unsigned Tmp = RS.scavengeRegister(&AMDGPU::VGPR_32RegClass, 0);
662       if (!Tmp)
663         report_fatal_error("Cannot scavenge VGPR to copy to AGPR");
664       RS.setRegUsed(Tmp);
665       // Only loop through if there are any free registers left, otherwise
666       // scavenger may report a fatal error without emergency spill slot
667       // or spill with the slot.
668       while (RegNo-- && RS.FindUnusedReg(&AMDGPU::VGPR_32RegClass)) {
669         unsigned Tmp2 = RS.scavengeRegister(&AMDGPU::VGPR_32RegClass, 0);
670         if (!Tmp2 || RI.getHWRegIndex(Tmp2) >= MaxVGPRs)
671           break;
672         Tmp = Tmp2;
673         RS.setRegUsed(Tmp);
674       }
675       copyPhysReg(MBB, MI, DL, Tmp, SrcReg, KillSrc);
676       BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32), DestReg)
677         .addReg(Tmp, RegState::Kill);
678       return;
679     }
680 
681     BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32), DestReg)
682       .addReg(SrcReg, getKillRegState(KillSrc));
683     return;
684   }
685 
686   unsigned EltSize = 4;
687   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
688   if (RI.isSGPRClass(RC)) {
689     // TODO: Copy vec3/vec5 with s_mov_b64s then final s_mov_b32.
690     if (!(RI.getRegSizeInBits(*RC) % 64)) {
691       Opcode =  AMDGPU::S_MOV_B64;
692       EltSize = 8;
693     } else {
694       Opcode = AMDGPU::S_MOV_B32;
695       EltSize = 4;
696     }
697 
698     if (!RI.isSGPRClass(RI.getPhysRegClass(SrcReg))) {
699       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
700       return;
701     }
702   } else if (RI.hasAGPRs(RC)) {
703     Opcode = RI.hasVGPRs(RI.getPhysRegClass(SrcReg)) ?
704       AMDGPU::V_ACCVGPR_WRITE_B32 : AMDGPU::COPY;
705   } else if (RI.hasVGPRs(RC) && RI.hasAGPRs(RI.getPhysRegClass(SrcReg))) {
706     Opcode = AMDGPU::V_ACCVGPR_READ_B32;
707   }
708 
709   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
710   bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
711 
712   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
713     unsigned SubIdx;
714     if (Forward)
715       SubIdx = SubIndices[Idx];
716     else
717       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
718 
719     if (Opcode == TargetOpcode::COPY) {
720       copyPhysReg(MBB, MI, DL, RI.getSubReg(DestReg, SubIdx),
721                   RI.getSubReg(SrcReg, SubIdx), KillSrc);
722       continue;
723     }
724 
725     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
726       get(Opcode), RI.getSubReg(DestReg, SubIdx));
727 
728     Builder.addReg(RI.getSubReg(SrcReg, SubIdx));
729 
730     if (Idx == 0)
731       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
732 
733     bool UseKill = KillSrc && Idx == SubIndices.size() - 1;
734     Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
735   }
736 }
737 
738 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
739   int NewOpc;
740 
741   // Try to map original to commuted opcode
742   NewOpc = AMDGPU::getCommuteRev(Opcode);
743   if (NewOpc != -1)
744     // Check if the commuted (REV) opcode exists on the target.
745     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
746 
747   // Try to map commuted to original opcode
748   NewOpc = AMDGPU::getCommuteOrig(Opcode);
749   if (NewOpc != -1)
750     // Check if the original (non-REV) opcode exists on the target.
751     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
752 
753   return Opcode;
754 }
755 
756 void SIInstrInfo::materializeImmediate(MachineBasicBlock &MBB,
757                                        MachineBasicBlock::iterator MI,
758                                        const DebugLoc &DL, unsigned DestReg,
759                                        int64_t Value) const {
760   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
761   const TargetRegisterClass *RegClass = MRI.getRegClass(DestReg);
762   if (RegClass == &AMDGPU::SReg_32RegClass ||
763       RegClass == &AMDGPU::SGPR_32RegClass ||
764       RegClass == &AMDGPU::SReg_32_XM0RegClass ||
765       RegClass == &AMDGPU::SReg_32_XM0_XEXECRegClass) {
766     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
767       .addImm(Value);
768     return;
769   }
770 
771   if (RegClass == &AMDGPU::SReg_64RegClass ||
772       RegClass == &AMDGPU::SGPR_64RegClass ||
773       RegClass == &AMDGPU::SReg_64_XEXECRegClass) {
774     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
775       .addImm(Value);
776     return;
777   }
778 
779   if (RegClass == &AMDGPU::VGPR_32RegClass) {
780     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
781       .addImm(Value);
782     return;
783   }
784   if (RegClass == &AMDGPU::VReg_64RegClass) {
785     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO), DestReg)
786       .addImm(Value);
787     return;
788   }
789 
790   unsigned EltSize = 4;
791   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
792   if (RI.isSGPRClass(RegClass)) {
793     if (RI.getRegSizeInBits(*RegClass) > 32) {
794       Opcode =  AMDGPU::S_MOV_B64;
795       EltSize = 8;
796     } else {
797       Opcode = AMDGPU::S_MOV_B32;
798       EltSize = 4;
799     }
800   }
801 
802   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RegClass, EltSize);
803   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
804     int64_t IdxValue = Idx == 0 ? Value : 0;
805 
806     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
807       get(Opcode), RI.getSubReg(DestReg, Idx));
808     Builder.addImm(IdxValue);
809   }
810 }
811 
812 const TargetRegisterClass *
813 SIInstrInfo::getPreferredSelectRegClass(unsigned Size) const {
814   return &AMDGPU::VGPR_32RegClass;
815 }
816 
817 void SIInstrInfo::insertVectorSelect(MachineBasicBlock &MBB,
818                                      MachineBasicBlock::iterator I,
819                                      const DebugLoc &DL, unsigned DstReg,
820                                      ArrayRef<MachineOperand> Cond,
821                                      unsigned TrueReg,
822                                      unsigned FalseReg) const {
823   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
824   MachineFunction *MF = MBB.getParent();
825   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
826   const TargetRegisterClass *BoolXExecRC =
827     RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
828   assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass &&
829          "Not a VGPR32 reg");
830 
831   if (Cond.size() == 1) {
832     Register SReg = MRI.createVirtualRegister(BoolXExecRC);
833     BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
834       .add(Cond[0]);
835     BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
836       .addImm(0)
837       .addReg(FalseReg)
838       .addImm(0)
839       .addReg(TrueReg)
840       .addReg(SReg);
841   } else if (Cond.size() == 2) {
842     assert(Cond[0].isImm() && "Cond[0] is not an immediate");
843     switch (Cond[0].getImm()) {
844     case SIInstrInfo::SCC_TRUE: {
845       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
846       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
847                                             : AMDGPU::S_CSELECT_B64), SReg)
848         .addImm(1)
849         .addImm(0);
850       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
851         .addImm(0)
852         .addReg(FalseReg)
853         .addImm(0)
854         .addReg(TrueReg)
855         .addReg(SReg);
856       break;
857     }
858     case SIInstrInfo::SCC_FALSE: {
859       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
860       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
861                                             : AMDGPU::S_CSELECT_B64), SReg)
862         .addImm(0)
863         .addImm(1);
864       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
865         .addImm(0)
866         .addReg(FalseReg)
867         .addImm(0)
868         .addReg(TrueReg)
869         .addReg(SReg);
870       break;
871     }
872     case SIInstrInfo::VCCNZ: {
873       MachineOperand RegOp = Cond[1];
874       RegOp.setImplicit(false);
875       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
876       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
877         .add(RegOp);
878       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
879           .addImm(0)
880           .addReg(FalseReg)
881           .addImm(0)
882           .addReg(TrueReg)
883           .addReg(SReg);
884       break;
885     }
886     case SIInstrInfo::VCCZ: {
887       MachineOperand RegOp = Cond[1];
888       RegOp.setImplicit(false);
889       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
890       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
891         .add(RegOp);
892       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
893           .addImm(0)
894           .addReg(TrueReg)
895           .addImm(0)
896           .addReg(FalseReg)
897           .addReg(SReg);
898       break;
899     }
900     case SIInstrInfo::EXECNZ: {
901       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
902       Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
903       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
904                                             : AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
905         .addImm(0);
906       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
907                                             : AMDGPU::S_CSELECT_B64), SReg)
908         .addImm(1)
909         .addImm(0);
910       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
911         .addImm(0)
912         .addReg(FalseReg)
913         .addImm(0)
914         .addReg(TrueReg)
915         .addReg(SReg);
916       break;
917     }
918     case SIInstrInfo::EXECZ: {
919       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
920       Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
921       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
922                                             : AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
923         .addImm(0);
924       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
925                                             : AMDGPU::S_CSELECT_B64), SReg)
926         .addImm(0)
927         .addImm(1);
928       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
929         .addImm(0)
930         .addReg(FalseReg)
931         .addImm(0)
932         .addReg(TrueReg)
933         .addReg(SReg);
934       llvm_unreachable("Unhandled branch predicate EXECZ");
935       break;
936     }
937     default:
938       llvm_unreachable("invalid branch predicate");
939     }
940   } else {
941     llvm_unreachable("Can only handle Cond size 1 or 2");
942   }
943 }
944 
945 unsigned SIInstrInfo::insertEQ(MachineBasicBlock *MBB,
946                                MachineBasicBlock::iterator I,
947                                const DebugLoc &DL,
948                                unsigned SrcReg, int Value) const {
949   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
950   Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
951   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg)
952     .addImm(Value)
953     .addReg(SrcReg);
954 
955   return Reg;
956 }
957 
958 unsigned SIInstrInfo::insertNE(MachineBasicBlock *MBB,
959                                MachineBasicBlock::iterator I,
960                                const DebugLoc &DL,
961                                unsigned SrcReg, int Value) const {
962   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
963   Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
964   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg)
965     .addImm(Value)
966     .addReg(SrcReg);
967 
968   return Reg;
969 }
970 
971 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
972 
973   if (RI.hasAGPRs(DstRC))
974     return AMDGPU::COPY;
975   if (RI.getRegSizeInBits(*DstRC) == 32) {
976     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
977   } else if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC)) {
978     return AMDGPU::S_MOV_B64;
979   } else if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC)) {
980     return  AMDGPU::V_MOV_B64_PSEUDO;
981   }
982   return AMDGPU::COPY;
983 }
984 
985 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
986   switch (Size) {
987   case 4:
988     return AMDGPU::SI_SPILL_S32_SAVE;
989   case 8:
990     return AMDGPU::SI_SPILL_S64_SAVE;
991   case 12:
992     return AMDGPU::SI_SPILL_S96_SAVE;
993   case 16:
994     return AMDGPU::SI_SPILL_S128_SAVE;
995   case 20:
996     return AMDGPU::SI_SPILL_S160_SAVE;
997   case 32:
998     return AMDGPU::SI_SPILL_S256_SAVE;
999   case 64:
1000     return AMDGPU::SI_SPILL_S512_SAVE;
1001   case 128:
1002     return AMDGPU::SI_SPILL_S1024_SAVE;
1003   default:
1004     llvm_unreachable("unknown register size");
1005   }
1006 }
1007 
1008 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
1009   switch (Size) {
1010   case 4:
1011     return AMDGPU::SI_SPILL_V32_SAVE;
1012   case 8:
1013     return AMDGPU::SI_SPILL_V64_SAVE;
1014   case 12:
1015     return AMDGPU::SI_SPILL_V96_SAVE;
1016   case 16:
1017     return AMDGPU::SI_SPILL_V128_SAVE;
1018   case 20:
1019     return AMDGPU::SI_SPILL_V160_SAVE;
1020   case 32:
1021     return AMDGPU::SI_SPILL_V256_SAVE;
1022   case 64:
1023     return AMDGPU::SI_SPILL_V512_SAVE;
1024   case 128:
1025     return AMDGPU::SI_SPILL_V1024_SAVE;
1026   default:
1027     llvm_unreachable("unknown register size");
1028   }
1029 }
1030 
1031 static unsigned getAGPRSpillSaveOpcode(unsigned Size) {
1032   switch (Size) {
1033   case 4:
1034     return AMDGPU::SI_SPILL_A32_SAVE;
1035   case 8:
1036     return AMDGPU::SI_SPILL_A64_SAVE;
1037   case 16:
1038     return AMDGPU::SI_SPILL_A128_SAVE;
1039   case 64:
1040     return AMDGPU::SI_SPILL_A512_SAVE;
1041   case 128:
1042     return AMDGPU::SI_SPILL_A1024_SAVE;
1043   default:
1044     llvm_unreachable("unknown register size");
1045   }
1046 }
1047 
1048 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1049                                       MachineBasicBlock::iterator MI,
1050                                       unsigned SrcReg, bool isKill,
1051                                       int FrameIndex,
1052                                       const TargetRegisterClass *RC,
1053                                       const TargetRegisterInfo *TRI) const {
1054   MachineFunction *MF = MBB.getParent();
1055   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1056   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1057   const DebugLoc &DL = MBB.findDebugLoc(MI);
1058 
1059   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
1060   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
1061   MachinePointerInfo PtrInfo
1062     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1063   MachineMemOperand *MMO
1064     = MF->getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
1065                                Size, Align);
1066   unsigned SpillSize = TRI->getSpillSize(*RC);
1067 
1068   if (RI.isSGPRClass(RC)) {
1069     MFI->setHasSpilledSGPRs();
1070     assert(SrcReg != AMDGPU::M0 && "m0 should not be spilled");
1071 
1072     // We are only allowed to create one new instruction when spilling
1073     // registers, so we need to use pseudo instruction for spilling SGPRs.
1074     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(SpillSize));
1075 
1076     // The SGPR spill/restore instructions only work on number sgprs, so we need
1077     // to make sure we are using the correct register class.
1078     if (Register::isVirtualRegister(SrcReg) && SpillSize == 4) {
1079       MachineRegisterInfo &MRI = MF->getRegInfo();
1080       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
1081     }
1082 
1083     BuildMI(MBB, MI, DL, OpDesc)
1084       .addReg(SrcReg, getKillRegState(isKill)) // data
1085       .addFrameIndex(FrameIndex)               // addr
1086       .addMemOperand(MMO)
1087       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
1088       .addReg(MFI->getStackPtrOffsetReg(), RegState::Implicit);
1089     // Add the scratch resource registers as implicit uses because we may end up
1090     // needing them, and need to ensure that the reserved registers are
1091     // correctly handled.
1092     if (RI.spillSGPRToVGPR())
1093       FrameInfo.setStackID(FrameIndex, TargetStackID::SGPRSpill);
1094     return;
1095   }
1096 
1097   unsigned Opcode = RI.hasAGPRs(RC) ? getAGPRSpillSaveOpcode(SpillSize)
1098                                     : getVGPRSpillSaveOpcode(SpillSize);
1099   MFI->setHasSpilledVGPRs();
1100 
1101   auto MIB = BuildMI(MBB, MI, DL, get(Opcode));
1102   if (RI.hasAGPRs(RC)) {
1103     MachineRegisterInfo &MRI = MF->getRegInfo();
1104     Register Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1105     MIB.addReg(Tmp, RegState::Define);
1106   }
1107   MIB.addReg(SrcReg, getKillRegState(isKill)) // data
1108      .addFrameIndex(FrameIndex)               // addr
1109      .addReg(MFI->getScratchRSrcReg())        // scratch_rsrc
1110      .addReg(MFI->getStackPtrOffsetReg())     // scratch_offset
1111      .addImm(0)                               // offset
1112      .addMemOperand(MMO);
1113 }
1114 
1115 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
1116   switch (Size) {
1117   case 4:
1118     return AMDGPU::SI_SPILL_S32_RESTORE;
1119   case 8:
1120     return AMDGPU::SI_SPILL_S64_RESTORE;
1121   case 12:
1122     return AMDGPU::SI_SPILL_S96_RESTORE;
1123   case 16:
1124     return AMDGPU::SI_SPILL_S128_RESTORE;
1125   case 20:
1126     return AMDGPU::SI_SPILL_S160_RESTORE;
1127   case 32:
1128     return AMDGPU::SI_SPILL_S256_RESTORE;
1129   case 64:
1130     return AMDGPU::SI_SPILL_S512_RESTORE;
1131   case 128:
1132     return AMDGPU::SI_SPILL_S1024_RESTORE;
1133   default:
1134     llvm_unreachable("unknown register size");
1135   }
1136 }
1137 
1138 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
1139   switch (Size) {
1140   case 4:
1141     return AMDGPU::SI_SPILL_V32_RESTORE;
1142   case 8:
1143     return AMDGPU::SI_SPILL_V64_RESTORE;
1144   case 12:
1145     return AMDGPU::SI_SPILL_V96_RESTORE;
1146   case 16:
1147     return AMDGPU::SI_SPILL_V128_RESTORE;
1148   case 20:
1149     return AMDGPU::SI_SPILL_V160_RESTORE;
1150   case 32:
1151     return AMDGPU::SI_SPILL_V256_RESTORE;
1152   case 64:
1153     return AMDGPU::SI_SPILL_V512_RESTORE;
1154   case 128:
1155     return AMDGPU::SI_SPILL_V1024_RESTORE;
1156   default:
1157     llvm_unreachable("unknown register size");
1158   }
1159 }
1160 
1161 static unsigned getAGPRSpillRestoreOpcode(unsigned Size) {
1162   switch (Size) {
1163   case 4:
1164     return AMDGPU::SI_SPILL_A32_RESTORE;
1165   case 8:
1166     return AMDGPU::SI_SPILL_A64_RESTORE;
1167   case 16:
1168     return AMDGPU::SI_SPILL_A128_RESTORE;
1169   case 64:
1170     return AMDGPU::SI_SPILL_A512_RESTORE;
1171   case 128:
1172     return AMDGPU::SI_SPILL_A1024_RESTORE;
1173   default:
1174     llvm_unreachable("unknown register size");
1175   }
1176 }
1177 
1178 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1179                                        MachineBasicBlock::iterator MI,
1180                                        unsigned DestReg, int FrameIndex,
1181                                        const TargetRegisterClass *RC,
1182                                        const TargetRegisterInfo *TRI) const {
1183   MachineFunction *MF = MBB.getParent();
1184   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1185   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1186   const DebugLoc &DL = MBB.findDebugLoc(MI);
1187   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
1188   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
1189   unsigned SpillSize = TRI->getSpillSize(*RC);
1190 
1191   MachinePointerInfo PtrInfo
1192     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1193 
1194   MachineMemOperand *MMO = MF->getMachineMemOperand(
1195     PtrInfo, MachineMemOperand::MOLoad, Size, Align);
1196 
1197   if (RI.isSGPRClass(RC)) {
1198     MFI->setHasSpilledSGPRs();
1199     assert(DestReg != AMDGPU::M0 && "m0 should not be reloaded into");
1200 
1201     // FIXME: Maybe this should not include a memoperand because it will be
1202     // lowered to non-memory instructions.
1203     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
1204     if (Register::isVirtualRegister(DestReg) && SpillSize == 4) {
1205       MachineRegisterInfo &MRI = MF->getRegInfo();
1206       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0RegClass);
1207     }
1208 
1209     if (RI.spillSGPRToVGPR())
1210       FrameInfo.setStackID(FrameIndex, TargetStackID::SGPRSpill);
1211     BuildMI(MBB, MI, DL, OpDesc, DestReg)
1212       .addFrameIndex(FrameIndex) // addr
1213       .addMemOperand(MMO)
1214       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
1215       .addReg(MFI->getStackPtrOffsetReg(), RegState::Implicit);
1216     return;
1217   }
1218 
1219   unsigned Opcode = RI.hasAGPRs(RC) ? getAGPRSpillRestoreOpcode(SpillSize)
1220                                     : getVGPRSpillRestoreOpcode(SpillSize);
1221   auto MIB = BuildMI(MBB, MI, DL, get(Opcode), DestReg);
1222   if (RI.hasAGPRs(RC)) {
1223     MachineRegisterInfo &MRI = MF->getRegInfo();
1224     Register Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1225     MIB.addReg(Tmp, RegState::Define);
1226   }
1227   MIB.addFrameIndex(FrameIndex)        // vaddr
1228      .addReg(MFI->getScratchRSrcReg()) // scratch_rsrc
1229      .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
1230      .addImm(0)                           // offset
1231      .addMemOperand(MMO);
1232 }
1233 
1234 /// \param @Offset Offset in bytes of the FrameIndex being spilled
1235 unsigned SIInstrInfo::calculateLDSSpillAddress(
1236     MachineBasicBlock &MBB, MachineInstr &MI, RegScavenger *RS, unsigned TmpReg,
1237     unsigned FrameOffset, unsigned Size) const {
1238   MachineFunction *MF = MBB.getParent();
1239   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1240   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
1241   const DebugLoc &DL = MBB.findDebugLoc(MI);
1242   unsigned WorkGroupSize = MFI->getMaxFlatWorkGroupSize();
1243   unsigned WavefrontSize = ST.getWavefrontSize();
1244 
1245   unsigned TIDReg = MFI->getTIDReg();
1246   if (!MFI->hasCalculatedTID()) {
1247     MachineBasicBlock &Entry = MBB.getParent()->front();
1248     MachineBasicBlock::iterator Insert = Entry.front();
1249     const DebugLoc &DL = Insert->getDebugLoc();
1250 
1251     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass,
1252                                    *MF);
1253     if (TIDReg == AMDGPU::NoRegister)
1254       return TIDReg;
1255 
1256     if (!AMDGPU::isShader(MF->getFunction().getCallingConv()) &&
1257         WorkGroupSize > WavefrontSize) {
1258       Register TIDIGXReg =
1259           MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
1260       Register TIDIGYReg =
1261           MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
1262       Register TIDIGZReg =
1263           MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
1264       Register InputPtrReg =
1265           MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1266       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
1267         if (!Entry.isLiveIn(Reg))
1268           Entry.addLiveIn(Reg);
1269       }
1270 
1271       RS->enterBasicBlock(Entry);
1272       // FIXME: Can we scavenge an SReg_64 and access the subregs?
1273       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
1274       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
1275       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
1276               .addReg(InputPtrReg)
1277               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
1278       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
1279               .addReg(InputPtrReg)
1280               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
1281 
1282       // NGROUPS.X * NGROUPS.Y
1283       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
1284               .addReg(STmp1)
1285               .addReg(STmp0);
1286       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
1287       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
1288               .addReg(STmp1)
1289               .addReg(TIDIGXReg);
1290       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
1291       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
1292               .addReg(STmp0)
1293               .addReg(TIDIGYReg)
1294               .addReg(TIDReg);
1295       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
1296       getAddNoCarry(Entry, Insert, DL, TIDReg)
1297         .addReg(TIDReg)
1298         .addReg(TIDIGZReg)
1299         .addImm(0); // clamp bit
1300     } else {
1301       // Get the wave id
1302       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
1303               TIDReg)
1304               .addImm(-1)
1305               .addImm(0);
1306 
1307       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
1308               TIDReg)
1309               .addImm(-1)
1310               .addReg(TIDReg);
1311     }
1312 
1313     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
1314             TIDReg)
1315             .addImm(2)
1316             .addReg(TIDReg);
1317     MFI->setTIDReg(TIDReg);
1318   }
1319 
1320   // Add FrameIndex to LDS offset
1321   unsigned LDSOffset = MFI->getLDSSize() + (FrameOffset * WorkGroupSize);
1322   getAddNoCarry(MBB, MI, DL, TmpReg)
1323     .addImm(LDSOffset)
1324     .addReg(TIDReg)
1325     .addImm(0); // clamp bit
1326 
1327   return TmpReg;
1328 }
1329 
1330 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
1331                                    MachineBasicBlock::iterator MI,
1332                                    int Count) const {
1333   DebugLoc DL = MBB.findDebugLoc(MI);
1334   while (Count > 0) {
1335     int Arg;
1336     if (Count >= 8)
1337       Arg = 7;
1338     else
1339       Arg = Count - 1;
1340     Count -= 8;
1341     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
1342             .addImm(Arg);
1343   }
1344 }
1345 
1346 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
1347                              MachineBasicBlock::iterator MI) const {
1348   insertWaitStates(MBB, MI, 1);
1349 }
1350 
1351 void SIInstrInfo::insertReturn(MachineBasicBlock &MBB) const {
1352   auto MF = MBB.getParent();
1353   SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1354 
1355   assert(Info->isEntryFunction());
1356 
1357   if (MBB.succ_empty()) {
1358     bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end();
1359     if (HasNoTerminator) {
1360       if (Info->returnsVoid()) {
1361         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::S_ENDPGM)).addImm(0);
1362       } else {
1363         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::SI_RETURN_TO_EPILOG));
1364       }
1365     }
1366   }
1367 }
1368 
1369 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) {
1370   switch (MI.getOpcode()) {
1371   default: return 1; // FIXME: Do wait states equal cycles?
1372 
1373   case AMDGPU::S_NOP:
1374     return MI.getOperand(0).getImm() + 1;
1375   }
1376 }
1377 
1378 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1379   MachineBasicBlock &MBB = *MI.getParent();
1380   DebugLoc DL = MBB.findDebugLoc(MI);
1381   switch (MI.getOpcode()) {
1382   default: return TargetInstrInfo::expandPostRAPseudo(MI);
1383   case AMDGPU::S_MOV_B64_term:
1384     // This is only a terminator to get the correct spill code placement during
1385     // register allocation.
1386     MI.setDesc(get(AMDGPU::S_MOV_B64));
1387     break;
1388 
1389   case AMDGPU::S_MOV_B32_term:
1390     // This is only a terminator to get the correct spill code placement during
1391     // register allocation.
1392     MI.setDesc(get(AMDGPU::S_MOV_B32));
1393     break;
1394 
1395   case AMDGPU::S_XOR_B64_term:
1396     // This is only a terminator to get the correct spill code placement during
1397     // register allocation.
1398     MI.setDesc(get(AMDGPU::S_XOR_B64));
1399     break;
1400 
1401   case AMDGPU::S_XOR_B32_term:
1402     // This is only a terminator to get the correct spill code placement during
1403     // register allocation.
1404     MI.setDesc(get(AMDGPU::S_XOR_B32));
1405     break;
1406 
1407   case AMDGPU::S_OR_B32_term:
1408     // This is only a terminator to get the correct spill code placement during
1409     // register allocation.
1410     MI.setDesc(get(AMDGPU::S_OR_B32));
1411     break;
1412 
1413   case AMDGPU::S_ANDN2_B64_term:
1414     // This is only a terminator to get the correct spill code placement during
1415     // register allocation.
1416     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
1417     break;
1418 
1419   case AMDGPU::S_ANDN2_B32_term:
1420     // This is only a terminator to get the correct spill code placement during
1421     // register allocation.
1422     MI.setDesc(get(AMDGPU::S_ANDN2_B32));
1423     break;
1424 
1425   case AMDGPU::V_MOV_B64_PSEUDO: {
1426     Register Dst = MI.getOperand(0).getReg();
1427     Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
1428     Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
1429 
1430     const MachineOperand &SrcOp = MI.getOperand(1);
1431     // FIXME: Will this work for 64-bit floating point immediates?
1432     assert(!SrcOp.isFPImm());
1433     if (SrcOp.isImm()) {
1434       APInt Imm(64, SrcOp.getImm());
1435       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1436         .addImm(Imm.getLoBits(32).getZExtValue())
1437         .addReg(Dst, RegState::Implicit | RegState::Define);
1438       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1439         .addImm(Imm.getHiBits(32).getZExtValue())
1440         .addReg(Dst, RegState::Implicit | RegState::Define);
1441     } else {
1442       assert(SrcOp.isReg());
1443       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1444         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
1445         .addReg(Dst, RegState::Implicit | RegState::Define);
1446       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1447         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
1448         .addReg(Dst, RegState::Implicit | RegState::Define);
1449     }
1450     MI.eraseFromParent();
1451     break;
1452   }
1453   case AMDGPU::V_MOV_B64_DPP_PSEUDO: {
1454     expandMovDPP64(MI);
1455     break;
1456   }
1457   case AMDGPU::V_SET_INACTIVE_B32: {
1458     unsigned NotOpc = ST.isWave32() ? AMDGPU::S_NOT_B32 : AMDGPU::S_NOT_B64;
1459     unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1460     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1461       .addReg(Exec);
1462     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), MI.getOperand(0).getReg())
1463       .add(MI.getOperand(2));
1464     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1465       .addReg(Exec);
1466     MI.eraseFromParent();
1467     break;
1468   }
1469   case AMDGPU::V_SET_INACTIVE_B64: {
1470     unsigned NotOpc = ST.isWave32() ? AMDGPU::S_NOT_B32 : AMDGPU::S_NOT_B64;
1471     unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1472     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1473       .addReg(Exec);
1474     MachineInstr *Copy = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO),
1475                                  MI.getOperand(0).getReg())
1476       .add(MI.getOperand(2));
1477     expandPostRAPseudo(*Copy);
1478     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1479       .addReg(Exec);
1480     MI.eraseFromParent();
1481     break;
1482   }
1483   case AMDGPU::V_MOVRELD_B32_V1:
1484   case AMDGPU::V_MOVRELD_B32_V2:
1485   case AMDGPU::V_MOVRELD_B32_V4:
1486   case AMDGPU::V_MOVRELD_B32_V8:
1487   case AMDGPU::V_MOVRELD_B32_V16: {
1488     const MCInstrDesc &MovRelDesc = get(AMDGPU::V_MOVRELD_B32_e32);
1489     Register VecReg = MI.getOperand(0).getReg();
1490     bool IsUndef = MI.getOperand(1).isUndef();
1491     unsigned SubReg = AMDGPU::sub0 + MI.getOperand(3).getImm();
1492     assert(VecReg == MI.getOperand(1).getReg());
1493 
1494     MachineInstr *MovRel =
1495         BuildMI(MBB, MI, DL, MovRelDesc)
1496             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1497             .add(MI.getOperand(2))
1498             .addReg(VecReg, RegState::ImplicitDefine)
1499             .addReg(VecReg,
1500                     RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1501 
1502     const int ImpDefIdx =
1503         MovRelDesc.getNumOperands() + MovRelDesc.getNumImplicitUses();
1504     const int ImpUseIdx = ImpDefIdx + 1;
1505     MovRel->tieOperands(ImpDefIdx, ImpUseIdx);
1506 
1507     MI.eraseFromParent();
1508     break;
1509   }
1510   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
1511     MachineFunction &MF = *MBB.getParent();
1512     Register Reg = MI.getOperand(0).getReg();
1513     Register RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
1514     Register RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
1515 
1516     // Create a bundle so these instructions won't be re-ordered by the
1517     // post-RA scheduler.
1518     MIBundleBuilder Bundler(MBB, MI);
1519     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
1520 
1521     // Add 32-bit offset from this instruction to the start of the
1522     // constant data.
1523     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
1524                        .addReg(RegLo)
1525                        .add(MI.getOperand(1)));
1526 
1527     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
1528                                   .addReg(RegHi);
1529     MIB.add(MI.getOperand(2));
1530 
1531     Bundler.append(MIB);
1532     finalizeBundle(MBB, Bundler.begin());
1533 
1534     MI.eraseFromParent();
1535     break;
1536   }
1537   case AMDGPU::ENTER_WWM: {
1538     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1539     // WWM is entered.
1540     MI.setDesc(get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1541                                  : AMDGPU::S_OR_SAVEEXEC_B64));
1542     break;
1543   }
1544   case AMDGPU::EXIT_WWM: {
1545     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1546     // WWM is exited.
1547     MI.setDesc(get(ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64));
1548     break;
1549   }
1550   case TargetOpcode::BUNDLE: {
1551     if (!MI.mayLoad() || MI.hasUnmodeledSideEffects())
1552       return false;
1553 
1554     // If it is a load it must be a memory clause
1555     for (MachineBasicBlock::instr_iterator I = MI.getIterator();
1556          I->isBundledWithSucc(); ++I) {
1557       I->unbundleFromSucc();
1558       for (MachineOperand &MO : I->operands())
1559         if (MO.isReg())
1560           MO.setIsInternalRead(false);
1561     }
1562 
1563     MI.eraseFromParent();
1564     break;
1565   }
1566   }
1567   return true;
1568 }
1569 
1570 std::pair<MachineInstr*, MachineInstr*>
1571 SIInstrInfo::expandMovDPP64(MachineInstr &MI) const {
1572   assert (MI.getOpcode() == AMDGPU::V_MOV_B64_DPP_PSEUDO);
1573 
1574   MachineBasicBlock &MBB = *MI.getParent();
1575   DebugLoc DL = MBB.findDebugLoc(MI);
1576   MachineFunction *MF = MBB.getParent();
1577   MachineRegisterInfo &MRI = MF->getRegInfo();
1578   Register Dst = MI.getOperand(0).getReg();
1579   unsigned Part = 0;
1580   MachineInstr *Split[2];
1581 
1582 
1583   for (auto Sub : { AMDGPU::sub0, AMDGPU::sub1 }) {
1584     auto MovDPP = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_dpp));
1585     if (Dst.isPhysical()) {
1586       MovDPP.addDef(RI.getSubReg(Dst, Sub));
1587     } else {
1588       assert(MRI.isSSA());
1589       auto Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1590       MovDPP.addDef(Tmp);
1591     }
1592 
1593     for (unsigned I = 1; I <= 2; ++I) { // old and src operands.
1594       const MachineOperand &SrcOp = MI.getOperand(I);
1595       assert(!SrcOp.isFPImm());
1596       if (SrcOp.isImm()) {
1597         APInt Imm(64, SrcOp.getImm());
1598         Imm.ashrInPlace(Part * 32);
1599         MovDPP.addImm(Imm.getLoBits(32).getZExtValue());
1600       } else {
1601         assert(SrcOp.isReg());
1602         Register Src = SrcOp.getReg();
1603         if (Src.isPhysical())
1604           MovDPP.addReg(RI.getSubReg(Src, Sub));
1605         else
1606           MovDPP.addReg(Src, SrcOp.isUndef() ? RegState::Undef : 0, Sub);
1607       }
1608     }
1609 
1610     for (unsigned I = 3; I < MI.getNumExplicitOperands(); ++I)
1611       MovDPP.addImm(MI.getOperand(I).getImm());
1612 
1613     Split[Part] = MovDPP;
1614     ++Part;
1615   }
1616 
1617   if (Dst.isVirtual())
1618     BuildMI(MBB, MI, DL, get(AMDGPU::REG_SEQUENCE), Dst)
1619       .addReg(Split[0]->getOperand(0).getReg())
1620       .addImm(AMDGPU::sub0)
1621       .addReg(Split[1]->getOperand(0).getReg())
1622       .addImm(AMDGPU::sub1);
1623 
1624   MI.eraseFromParent();
1625   return std::make_pair(Split[0], Split[1]);
1626 }
1627 
1628 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
1629                                       MachineOperand &Src0,
1630                                       unsigned Src0OpName,
1631                                       MachineOperand &Src1,
1632                                       unsigned Src1OpName) const {
1633   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
1634   if (!Src0Mods)
1635     return false;
1636 
1637   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
1638   assert(Src1Mods &&
1639          "All commutable instructions have both src0 and src1 modifiers");
1640 
1641   int Src0ModsVal = Src0Mods->getImm();
1642   int Src1ModsVal = Src1Mods->getImm();
1643 
1644   Src1Mods->setImm(Src0ModsVal);
1645   Src0Mods->setImm(Src1ModsVal);
1646   return true;
1647 }
1648 
1649 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
1650                                              MachineOperand &RegOp,
1651                                              MachineOperand &NonRegOp) {
1652   Register Reg = RegOp.getReg();
1653   unsigned SubReg = RegOp.getSubReg();
1654   bool IsKill = RegOp.isKill();
1655   bool IsDead = RegOp.isDead();
1656   bool IsUndef = RegOp.isUndef();
1657   bool IsDebug = RegOp.isDebug();
1658 
1659   if (NonRegOp.isImm())
1660     RegOp.ChangeToImmediate(NonRegOp.getImm());
1661   else if (NonRegOp.isFI())
1662     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
1663   else
1664     return nullptr;
1665 
1666   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
1667   NonRegOp.setSubReg(SubReg);
1668 
1669   return &MI;
1670 }
1671 
1672 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
1673                                                   unsigned Src0Idx,
1674                                                   unsigned Src1Idx) const {
1675   assert(!NewMI && "this should never be used");
1676 
1677   unsigned Opc = MI.getOpcode();
1678   int CommutedOpcode = commuteOpcode(Opc);
1679   if (CommutedOpcode == -1)
1680     return nullptr;
1681 
1682   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
1683            static_cast<int>(Src0Idx) &&
1684          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
1685            static_cast<int>(Src1Idx) &&
1686          "inconsistency with findCommutedOpIndices");
1687 
1688   MachineOperand &Src0 = MI.getOperand(Src0Idx);
1689   MachineOperand &Src1 = MI.getOperand(Src1Idx);
1690 
1691   MachineInstr *CommutedMI = nullptr;
1692   if (Src0.isReg() && Src1.isReg()) {
1693     if (isOperandLegal(MI, Src1Idx, &Src0)) {
1694       // Be sure to copy the source modifiers to the right place.
1695       CommutedMI
1696         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
1697     }
1698 
1699   } else if (Src0.isReg() && !Src1.isReg()) {
1700     // src0 should always be able to support any operand type, so no need to
1701     // check operand legality.
1702     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
1703   } else if (!Src0.isReg() && Src1.isReg()) {
1704     if (isOperandLegal(MI, Src1Idx, &Src0))
1705       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
1706   } else {
1707     // FIXME: Found two non registers to commute. This does happen.
1708     return nullptr;
1709   }
1710 
1711   if (CommutedMI) {
1712     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
1713                         Src1, AMDGPU::OpName::src1_modifiers);
1714 
1715     CommutedMI->setDesc(get(CommutedOpcode));
1716   }
1717 
1718   return CommutedMI;
1719 }
1720 
1721 // This needs to be implemented because the source modifiers may be inserted
1722 // between the true commutable operands, and the base
1723 // TargetInstrInfo::commuteInstruction uses it.
1724 bool SIInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
1725                                         unsigned &SrcOpIdx0,
1726                                         unsigned &SrcOpIdx1) const {
1727   return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
1728 }
1729 
1730 bool SIInstrInfo::findCommutedOpIndices(MCInstrDesc Desc, unsigned &SrcOpIdx0,
1731                                         unsigned &SrcOpIdx1) const {
1732   if (!Desc.isCommutable())
1733     return false;
1734 
1735   unsigned Opc = Desc.getOpcode();
1736   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1737   if (Src0Idx == -1)
1738     return false;
1739 
1740   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1741   if (Src1Idx == -1)
1742     return false;
1743 
1744   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1745 }
1746 
1747 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
1748                                         int64_t BrOffset) const {
1749   // BranchRelaxation should never have to check s_setpc_b64 because its dest
1750   // block is unanalyzable.
1751   assert(BranchOp != AMDGPU::S_SETPC_B64);
1752 
1753   // Convert to dwords.
1754   BrOffset /= 4;
1755 
1756   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
1757   // from the next instruction.
1758   BrOffset -= 1;
1759 
1760   return isIntN(BranchOffsetBits, BrOffset);
1761 }
1762 
1763 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
1764   const MachineInstr &MI) const {
1765   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
1766     // This would be a difficult analysis to perform, but can always be legal so
1767     // there's no need to analyze it.
1768     return nullptr;
1769   }
1770 
1771   return MI.getOperand(0).getMBB();
1772 }
1773 
1774 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
1775                                            MachineBasicBlock &DestBB,
1776                                            const DebugLoc &DL,
1777                                            int64_t BrOffset,
1778                                            RegScavenger *RS) const {
1779   assert(RS && "RegScavenger required for long branching");
1780   assert(MBB.empty() &&
1781          "new block should be inserted for expanding unconditional branch");
1782   assert(MBB.pred_size() == 1);
1783 
1784   MachineFunction *MF = MBB.getParent();
1785   MachineRegisterInfo &MRI = MF->getRegInfo();
1786 
1787   // FIXME: Virtual register workaround for RegScavenger not working with empty
1788   // blocks.
1789   Register PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1790 
1791   auto I = MBB.end();
1792 
1793   // We need to compute the offset relative to the instruction immediately after
1794   // s_getpc_b64. Insert pc arithmetic code before last terminator.
1795   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
1796 
1797   // TODO: Handle > 32-bit block address.
1798   if (BrOffset >= 0) {
1799     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
1800       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1801       .addReg(PCReg, 0, AMDGPU::sub0)
1802       .addMBB(&DestBB, MO_LONG_BRANCH_FORWARD);
1803     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
1804       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1805       .addReg(PCReg, 0, AMDGPU::sub1)
1806       .addImm(0);
1807   } else {
1808     // Backwards branch.
1809     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
1810       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1811       .addReg(PCReg, 0, AMDGPU::sub0)
1812       .addMBB(&DestBB, MO_LONG_BRANCH_BACKWARD);
1813     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
1814       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1815       .addReg(PCReg, 0, AMDGPU::sub1)
1816       .addImm(0);
1817   }
1818 
1819   // Insert the indirect branch after the other terminator.
1820   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
1821     .addReg(PCReg);
1822 
1823   // FIXME: If spilling is necessary, this will fail because this scavenger has
1824   // no emergency stack slots. It is non-trivial to spill in this situation,
1825   // because the restore code needs to be specially placed after the
1826   // jump. BranchRelaxation then needs to be made aware of the newly inserted
1827   // block.
1828   //
1829   // If a spill is needed for the pc register pair, we need to insert a spill
1830   // restore block right before the destination block, and insert a short branch
1831   // into the old destination block's fallthrough predecessor.
1832   // e.g.:
1833   //
1834   // s_cbranch_scc0 skip_long_branch:
1835   //
1836   // long_branch_bb:
1837   //   spill s[8:9]
1838   //   s_getpc_b64 s[8:9]
1839   //   s_add_u32 s8, s8, restore_bb
1840   //   s_addc_u32 s9, s9, 0
1841   //   s_setpc_b64 s[8:9]
1842   //
1843   // skip_long_branch:
1844   //   foo;
1845   //
1846   // .....
1847   //
1848   // dest_bb_fallthrough_predecessor:
1849   // bar;
1850   // s_branch dest_bb
1851   //
1852   // restore_bb:
1853   //  restore s[8:9]
1854   //  fallthrough dest_bb
1855   ///
1856   // dest_bb:
1857   //   buzz;
1858 
1859   RS->enterBasicBlockEnd(MBB);
1860   unsigned Scav = RS->scavengeRegisterBackwards(
1861     AMDGPU::SReg_64RegClass,
1862     MachineBasicBlock::iterator(GetPC), false, 0);
1863   MRI.replaceRegWith(PCReg, Scav);
1864   MRI.clearVirtRegs();
1865   RS->setRegUsed(Scav);
1866 
1867   return 4 + 8 + 4 + 4;
1868 }
1869 
1870 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1871   switch (Cond) {
1872   case SIInstrInfo::SCC_TRUE:
1873     return AMDGPU::S_CBRANCH_SCC1;
1874   case SIInstrInfo::SCC_FALSE:
1875     return AMDGPU::S_CBRANCH_SCC0;
1876   case SIInstrInfo::VCCNZ:
1877     return AMDGPU::S_CBRANCH_VCCNZ;
1878   case SIInstrInfo::VCCZ:
1879     return AMDGPU::S_CBRANCH_VCCZ;
1880   case SIInstrInfo::EXECNZ:
1881     return AMDGPU::S_CBRANCH_EXECNZ;
1882   case SIInstrInfo::EXECZ:
1883     return AMDGPU::S_CBRANCH_EXECZ;
1884   default:
1885     llvm_unreachable("invalid branch predicate");
1886   }
1887 }
1888 
1889 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1890   switch (Opcode) {
1891   case AMDGPU::S_CBRANCH_SCC0:
1892     return SCC_FALSE;
1893   case AMDGPU::S_CBRANCH_SCC1:
1894     return SCC_TRUE;
1895   case AMDGPU::S_CBRANCH_VCCNZ:
1896     return VCCNZ;
1897   case AMDGPU::S_CBRANCH_VCCZ:
1898     return VCCZ;
1899   case AMDGPU::S_CBRANCH_EXECNZ:
1900     return EXECNZ;
1901   case AMDGPU::S_CBRANCH_EXECZ:
1902     return EXECZ;
1903   default:
1904     return INVALID_BR;
1905   }
1906 }
1907 
1908 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
1909                                     MachineBasicBlock::iterator I,
1910                                     MachineBasicBlock *&TBB,
1911                                     MachineBasicBlock *&FBB,
1912                                     SmallVectorImpl<MachineOperand> &Cond,
1913                                     bool AllowModify) const {
1914   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1915     // Unconditional Branch
1916     TBB = I->getOperand(0).getMBB();
1917     return false;
1918   }
1919 
1920   MachineBasicBlock *CondBB = nullptr;
1921 
1922   if (I->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
1923     CondBB = I->getOperand(1).getMBB();
1924     Cond.push_back(I->getOperand(0));
1925   } else {
1926     BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1927     if (Pred == INVALID_BR)
1928       return true;
1929 
1930     CondBB = I->getOperand(0).getMBB();
1931     Cond.push_back(MachineOperand::CreateImm(Pred));
1932     Cond.push_back(I->getOperand(1)); // Save the branch register.
1933   }
1934   ++I;
1935 
1936   if (I == MBB.end()) {
1937     // Conditional branch followed by fall-through.
1938     TBB = CondBB;
1939     return false;
1940   }
1941 
1942   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1943     TBB = CondBB;
1944     FBB = I->getOperand(0).getMBB();
1945     return false;
1946   }
1947 
1948   return true;
1949 }
1950 
1951 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1952                                 MachineBasicBlock *&FBB,
1953                                 SmallVectorImpl<MachineOperand> &Cond,
1954                                 bool AllowModify) const {
1955   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1956   auto E = MBB.end();
1957   if (I == E)
1958     return false;
1959 
1960   // Skip over the instructions that are artificially terminators for special
1961   // exec management.
1962   while (I != E && !I->isBranch() && !I->isReturn() &&
1963          I->getOpcode() != AMDGPU::SI_MASK_BRANCH) {
1964     switch (I->getOpcode()) {
1965     case AMDGPU::SI_MASK_BRANCH:
1966     case AMDGPU::S_MOV_B64_term:
1967     case AMDGPU::S_XOR_B64_term:
1968     case AMDGPU::S_ANDN2_B64_term:
1969     case AMDGPU::S_MOV_B32_term:
1970     case AMDGPU::S_XOR_B32_term:
1971     case AMDGPU::S_OR_B32_term:
1972     case AMDGPU::S_ANDN2_B32_term:
1973       break;
1974     case AMDGPU::SI_IF:
1975     case AMDGPU::SI_ELSE:
1976     case AMDGPU::SI_KILL_I1_TERMINATOR:
1977     case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1978       // FIXME: It's messy that these need to be considered here at all.
1979       return true;
1980     default:
1981       llvm_unreachable("unexpected non-branch terminator inst");
1982     }
1983 
1984     ++I;
1985   }
1986 
1987   if (I == E)
1988     return false;
1989 
1990   if (I->getOpcode() != AMDGPU::SI_MASK_BRANCH)
1991     return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
1992 
1993   ++I;
1994 
1995   // TODO: Should be able to treat as fallthrough?
1996   if (I == MBB.end())
1997     return true;
1998 
1999   if (analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify))
2000     return true;
2001 
2002   MachineBasicBlock *MaskBrDest = I->getOperand(0).getMBB();
2003 
2004   // Specifically handle the case where the conditional branch is to the same
2005   // destination as the mask branch. e.g.
2006   //
2007   // si_mask_branch BB8
2008   // s_cbranch_execz BB8
2009   // s_cbranch BB9
2010   //
2011   // This is required to understand divergent loops which may need the branches
2012   // to be relaxed.
2013   if (TBB != MaskBrDest || Cond.empty())
2014     return true;
2015 
2016   auto Pred = Cond[0].getImm();
2017   return (Pred != EXECZ && Pred != EXECNZ);
2018 }
2019 
2020 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
2021                                    int *BytesRemoved) const {
2022   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
2023 
2024   unsigned Count = 0;
2025   unsigned RemovedSize = 0;
2026   while (I != MBB.end()) {
2027     MachineBasicBlock::iterator Next = std::next(I);
2028     if (I->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
2029       I = Next;
2030       continue;
2031     }
2032 
2033     RemovedSize += getInstSizeInBytes(*I);
2034     I->eraseFromParent();
2035     ++Count;
2036     I = Next;
2037   }
2038 
2039   if (BytesRemoved)
2040     *BytesRemoved = RemovedSize;
2041 
2042   return Count;
2043 }
2044 
2045 // Copy the flags onto the implicit condition register operand.
2046 static void preserveCondRegFlags(MachineOperand &CondReg,
2047                                  const MachineOperand &OrigCond) {
2048   CondReg.setIsUndef(OrigCond.isUndef());
2049   CondReg.setIsKill(OrigCond.isKill());
2050 }
2051 
2052 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
2053                                    MachineBasicBlock *TBB,
2054                                    MachineBasicBlock *FBB,
2055                                    ArrayRef<MachineOperand> Cond,
2056                                    const DebugLoc &DL,
2057                                    int *BytesAdded) const {
2058   if (!FBB && Cond.empty()) {
2059     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
2060       .addMBB(TBB);
2061     if (BytesAdded)
2062       *BytesAdded = 4;
2063     return 1;
2064   }
2065 
2066   if(Cond.size() == 1 && Cond[0].isReg()) {
2067      BuildMI(&MBB, DL, get(AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO))
2068        .add(Cond[0])
2069        .addMBB(TBB);
2070      return 1;
2071   }
2072 
2073   assert(TBB && Cond[0].isImm());
2074 
2075   unsigned Opcode
2076     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
2077 
2078   if (!FBB) {
2079     Cond[1].isUndef();
2080     MachineInstr *CondBr =
2081       BuildMI(&MBB, DL, get(Opcode))
2082       .addMBB(TBB);
2083 
2084     // Copy the flags onto the implicit condition register operand.
2085     preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
2086 
2087     if (BytesAdded)
2088       *BytesAdded = 4;
2089     return 1;
2090   }
2091 
2092   assert(TBB && FBB);
2093 
2094   MachineInstr *CondBr =
2095     BuildMI(&MBB, DL, get(Opcode))
2096     .addMBB(TBB);
2097   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
2098     .addMBB(FBB);
2099 
2100   MachineOperand &CondReg = CondBr->getOperand(1);
2101   CondReg.setIsUndef(Cond[1].isUndef());
2102   CondReg.setIsKill(Cond[1].isKill());
2103 
2104   if (BytesAdded)
2105       *BytesAdded = 8;
2106 
2107   return 2;
2108 }
2109 
2110 bool SIInstrInfo::reverseBranchCondition(
2111   SmallVectorImpl<MachineOperand> &Cond) const {
2112   if (Cond.size() != 2) {
2113     return true;
2114   }
2115 
2116   if (Cond[0].isImm()) {
2117     Cond[0].setImm(-Cond[0].getImm());
2118     return false;
2119   }
2120 
2121   return true;
2122 }
2123 
2124 bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
2125                                   ArrayRef<MachineOperand> Cond,
2126                                   unsigned TrueReg, unsigned FalseReg,
2127                                   int &CondCycles,
2128                                   int &TrueCycles, int &FalseCycles) const {
2129   switch (Cond[0].getImm()) {
2130   case VCCNZ:
2131   case VCCZ: {
2132     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2133     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
2134     assert(MRI.getRegClass(FalseReg) == RC);
2135 
2136     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
2137     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
2138 
2139     // Limit to equal cost for branch vs. N v_cndmask_b32s.
2140     return RI.hasVGPRs(RC) && NumInsts <= 6;
2141   }
2142   case SCC_TRUE:
2143   case SCC_FALSE: {
2144     // FIXME: We could insert for VGPRs if we could replace the original compare
2145     // with a vector one.
2146     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2147     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
2148     assert(MRI.getRegClass(FalseReg) == RC);
2149 
2150     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
2151 
2152     // Multiples of 8 can do s_cselect_b64
2153     if (NumInsts % 2 == 0)
2154       NumInsts /= 2;
2155 
2156     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
2157     return RI.isSGPRClass(RC);
2158   }
2159   default:
2160     return false;
2161   }
2162 }
2163 
2164 void SIInstrInfo::insertSelect(MachineBasicBlock &MBB,
2165                                MachineBasicBlock::iterator I, const DebugLoc &DL,
2166                                unsigned DstReg, ArrayRef<MachineOperand> Cond,
2167                                unsigned TrueReg, unsigned FalseReg) const {
2168   BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
2169   if (Pred == VCCZ || Pred == SCC_FALSE) {
2170     Pred = static_cast<BranchPredicate>(-Pred);
2171     std::swap(TrueReg, FalseReg);
2172   }
2173 
2174   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2175   const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
2176   unsigned DstSize = RI.getRegSizeInBits(*DstRC);
2177 
2178   if (DstSize == 32) {
2179     unsigned SelOp = Pred == SCC_TRUE ?
2180       AMDGPU::S_CSELECT_B32 : AMDGPU::V_CNDMASK_B32_e32;
2181 
2182     // Instruction's operands are backwards from what is expected.
2183     MachineInstr *Select =
2184       BuildMI(MBB, I, DL, get(SelOp), DstReg)
2185       .addReg(FalseReg)
2186       .addReg(TrueReg);
2187 
2188     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2189     return;
2190   }
2191 
2192   if (DstSize == 64 && Pred == SCC_TRUE) {
2193     MachineInstr *Select =
2194       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
2195       .addReg(FalseReg)
2196       .addReg(TrueReg);
2197 
2198     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2199     return;
2200   }
2201 
2202   static const int16_t Sub0_15[] = {
2203     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
2204     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
2205     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
2206     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
2207   };
2208 
2209   static const int16_t Sub0_15_64[] = {
2210     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
2211     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
2212     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
2213     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
2214   };
2215 
2216   unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
2217   const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
2218   const int16_t *SubIndices = Sub0_15;
2219   int NElts = DstSize / 32;
2220 
2221   // 64-bit select is only available for SALU.
2222   // TODO: Split 96-bit into 64-bit and 32-bit, not 3x 32-bit.
2223   if (Pred == SCC_TRUE) {
2224     if (NElts % 2) {
2225       SelOp = AMDGPU::S_CSELECT_B32;
2226       EltRC = &AMDGPU::SGPR_32RegClass;
2227     } else {
2228       SelOp = AMDGPU::S_CSELECT_B64;
2229       EltRC = &AMDGPU::SGPR_64RegClass;
2230       SubIndices = Sub0_15_64;
2231       NElts /= 2;
2232     }
2233   }
2234 
2235   MachineInstrBuilder MIB = BuildMI(
2236     MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
2237 
2238   I = MIB->getIterator();
2239 
2240   SmallVector<unsigned, 8> Regs;
2241   for (int Idx = 0; Idx != NElts; ++Idx) {
2242     Register DstElt = MRI.createVirtualRegister(EltRC);
2243     Regs.push_back(DstElt);
2244 
2245     unsigned SubIdx = SubIndices[Idx];
2246 
2247     MachineInstr *Select =
2248       BuildMI(MBB, I, DL, get(SelOp), DstElt)
2249       .addReg(FalseReg, 0, SubIdx)
2250       .addReg(TrueReg, 0, SubIdx);
2251     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2252     fixImplicitOperands(*Select);
2253 
2254     MIB.addReg(DstElt)
2255        .addImm(SubIdx);
2256   }
2257 }
2258 
2259 bool SIInstrInfo::isFoldableCopy(const MachineInstr &MI) const {
2260   switch (MI.getOpcode()) {
2261   case AMDGPU::V_MOV_B32_e32:
2262   case AMDGPU::V_MOV_B32_e64:
2263   case AMDGPU::V_MOV_B64_PSEUDO: {
2264     // If there are additional implicit register operands, this may be used for
2265     // register indexing so the source register operand isn't simply copied.
2266     unsigned NumOps = MI.getDesc().getNumOperands() +
2267       MI.getDesc().getNumImplicitUses();
2268 
2269     return MI.getNumOperands() == NumOps;
2270   }
2271   case AMDGPU::S_MOV_B32:
2272   case AMDGPU::S_MOV_B64:
2273   case AMDGPU::COPY:
2274   case AMDGPU::V_ACCVGPR_WRITE_B32:
2275   case AMDGPU::V_ACCVGPR_READ_B32:
2276     return true;
2277   default:
2278     return false;
2279   }
2280 }
2281 
2282 unsigned SIInstrInfo::getAddressSpaceForPseudoSourceKind(
2283     unsigned Kind) const {
2284   switch(Kind) {
2285   case PseudoSourceValue::Stack:
2286   case PseudoSourceValue::FixedStack:
2287     return AMDGPUAS::PRIVATE_ADDRESS;
2288   case PseudoSourceValue::ConstantPool:
2289   case PseudoSourceValue::GOT:
2290   case PseudoSourceValue::JumpTable:
2291   case PseudoSourceValue::GlobalValueCallEntry:
2292   case PseudoSourceValue::ExternalSymbolCallEntry:
2293   case PseudoSourceValue::TargetCustom:
2294     return AMDGPUAS::CONSTANT_ADDRESS;
2295   }
2296   return AMDGPUAS::FLAT_ADDRESS;
2297 }
2298 
2299 static void removeModOperands(MachineInstr &MI) {
2300   unsigned Opc = MI.getOpcode();
2301   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2302                                               AMDGPU::OpName::src0_modifiers);
2303   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2304                                               AMDGPU::OpName::src1_modifiers);
2305   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2306                                               AMDGPU::OpName::src2_modifiers);
2307 
2308   MI.RemoveOperand(Src2ModIdx);
2309   MI.RemoveOperand(Src1ModIdx);
2310   MI.RemoveOperand(Src0ModIdx);
2311 }
2312 
2313 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2314                                 unsigned Reg, MachineRegisterInfo *MRI) const {
2315   if (!MRI->hasOneNonDBGUse(Reg))
2316     return false;
2317 
2318   switch (DefMI.getOpcode()) {
2319   default:
2320     return false;
2321   case AMDGPU::S_MOV_B64:
2322     // TODO: We could fold 64-bit immediates, but this get compilicated
2323     // when there are sub-registers.
2324     return false;
2325 
2326   case AMDGPU::V_MOV_B32_e32:
2327   case AMDGPU::S_MOV_B32:
2328   case AMDGPU::V_ACCVGPR_WRITE_B32:
2329     break;
2330   }
2331 
2332   const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
2333   assert(ImmOp);
2334   // FIXME: We could handle FrameIndex values here.
2335   if (!ImmOp->isImm())
2336     return false;
2337 
2338   unsigned Opc = UseMI.getOpcode();
2339   if (Opc == AMDGPU::COPY) {
2340     bool isVGPRCopy = RI.isVGPR(*MRI, UseMI.getOperand(0).getReg());
2341     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
2342     if (RI.isAGPR(*MRI, UseMI.getOperand(0).getReg())) {
2343       if (!isInlineConstant(*ImmOp, AMDGPU::OPERAND_REG_INLINE_AC_INT32))
2344         return false;
2345       NewOpc = AMDGPU::V_ACCVGPR_WRITE_B32;
2346     }
2347     UseMI.setDesc(get(NewOpc));
2348     UseMI.getOperand(1).ChangeToImmediate(ImmOp->getImm());
2349     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
2350     return true;
2351   }
2352 
2353   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64 ||
2354       Opc == AMDGPU::V_MAD_F16 || Opc == AMDGPU::V_MAC_F16_e64 ||
2355       Opc == AMDGPU::V_FMA_F32 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2356       Opc == AMDGPU::V_FMA_F16 || Opc == AMDGPU::V_FMAC_F16_e64) {
2357     // Don't fold if we are using source or output modifiers. The new VOP2
2358     // instructions don't have them.
2359     if (hasAnyModifiersSet(UseMI))
2360       return false;
2361 
2362     // If this is a free constant, there's no reason to do this.
2363     // TODO: We could fold this here instead of letting SIFoldOperands do it
2364     // later.
2365     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
2366 
2367     // Any src operand can be used for the legality check.
2368     if (isInlineConstant(UseMI, *Src0, *ImmOp))
2369       return false;
2370 
2371     bool IsF32 = Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64 ||
2372                  Opc == AMDGPU::V_FMA_F32 || Opc == AMDGPU::V_FMAC_F32_e64;
2373     bool IsFMA = Opc == AMDGPU::V_FMA_F32 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2374                  Opc == AMDGPU::V_FMA_F16 || Opc == AMDGPU::V_FMAC_F16_e64;
2375     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
2376     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
2377 
2378     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
2379     // We should only expect these to be on src0 due to canonicalizations.
2380     if (Src0->isReg() && Src0->getReg() == Reg) {
2381       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
2382         return false;
2383 
2384       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
2385         return false;
2386 
2387       unsigned NewOpc =
2388         IsFMA ? (IsF32 ? AMDGPU::V_FMAMK_F32 : AMDGPU::V_FMAMK_F16)
2389               : (IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16);
2390       if (pseudoToMCOpcode(NewOpc) == -1)
2391         return false;
2392 
2393       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
2394 
2395       const int64_t Imm = ImmOp->getImm();
2396 
2397       // FIXME: This would be a lot easier if we could return a new instruction
2398       // instead of having to modify in place.
2399 
2400       // Remove these first since they are at the end.
2401       UseMI.RemoveOperand(
2402           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2403       UseMI.RemoveOperand(
2404           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2405 
2406       Register Src1Reg = Src1->getReg();
2407       unsigned Src1SubReg = Src1->getSubReg();
2408       Src0->setReg(Src1Reg);
2409       Src0->setSubReg(Src1SubReg);
2410       Src0->setIsKill(Src1->isKill());
2411 
2412       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2413           Opc == AMDGPU::V_MAC_F16_e64 ||
2414           Opc == AMDGPU::V_FMAC_F32_e64 ||
2415           Opc == AMDGPU::V_FMAC_F16_e64)
2416         UseMI.untieRegOperand(
2417             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2418 
2419       Src1->ChangeToImmediate(Imm);
2420 
2421       removeModOperands(UseMI);
2422       UseMI.setDesc(get(NewOpc));
2423 
2424       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2425       if (DeleteDef)
2426         DefMI.eraseFromParent();
2427 
2428       return true;
2429     }
2430 
2431     // Added part is the constant: Use v_madak_{f16, f32}.
2432     if (Src2->isReg() && Src2->getReg() == Reg) {
2433       // Not allowed to use constant bus for another operand.
2434       // We can however allow an inline immediate as src0.
2435       bool Src0Inlined = false;
2436       if (Src0->isReg()) {
2437         // Try to inline constant if possible.
2438         // If the Def moves immediate and the use is single
2439         // We are saving VGPR here.
2440         MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
2441         if (Def && Def->isMoveImmediate() &&
2442           isInlineConstant(Def->getOperand(1)) &&
2443           MRI->hasOneUse(Src0->getReg())) {
2444           Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2445           Src0Inlined = true;
2446         } else if ((Register::isPhysicalRegister(Src0->getReg()) &&
2447                     (ST.getConstantBusLimit(Opc) <= 1 &&
2448                      RI.isSGPRClass(RI.getPhysRegClass(Src0->getReg())))) ||
2449                    (Register::isVirtualRegister(Src0->getReg()) &&
2450                     (ST.getConstantBusLimit(Opc) <= 1 &&
2451                      RI.isSGPRClass(MRI->getRegClass(Src0->getReg())))))
2452           return false;
2453           // VGPR is okay as Src0 - fallthrough
2454       }
2455 
2456       if (Src1->isReg() && !Src0Inlined ) {
2457         // We have one slot for inlinable constant so far - try to fill it
2458         MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
2459         if (Def && Def->isMoveImmediate() &&
2460             isInlineConstant(Def->getOperand(1)) &&
2461             MRI->hasOneUse(Src1->getReg()) &&
2462             commuteInstruction(UseMI)) {
2463             Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2464         } else if ((Register::isPhysicalRegister(Src1->getReg()) &&
2465                     RI.isSGPRClass(RI.getPhysRegClass(Src1->getReg()))) ||
2466                    (Register::isVirtualRegister(Src1->getReg()) &&
2467                     RI.isSGPRClass(MRI->getRegClass(Src1->getReg()))))
2468           return false;
2469           // VGPR is okay as Src1 - fallthrough
2470       }
2471 
2472       unsigned NewOpc =
2473         IsFMA ? (IsF32 ? AMDGPU::V_FMAAK_F32 : AMDGPU::V_FMAAK_F16)
2474               : (IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16);
2475       if (pseudoToMCOpcode(NewOpc) == -1)
2476         return false;
2477 
2478       const int64_t Imm = ImmOp->getImm();
2479 
2480       // FIXME: This would be a lot easier if we could return a new instruction
2481       // instead of having to modify in place.
2482 
2483       // Remove these first since they are at the end.
2484       UseMI.RemoveOperand(
2485           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2486       UseMI.RemoveOperand(
2487           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2488 
2489       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2490           Opc == AMDGPU::V_MAC_F16_e64 ||
2491           Opc == AMDGPU::V_FMAC_F32_e64 ||
2492           Opc == AMDGPU::V_FMAC_F16_e64)
2493         UseMI.untieRegOperand(
2494             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2495 
2496       // ChangingToImmediate adds Src2 back to the instruction.
2497       Src2->ChangeToImmediate(Imm);
2498 
2499       // These come before src2.
2500       removeModOperands(UseMI);
2501       UseMI.setDesc(get(NewOpc));
2502       // It might happen that UseMI was commuted
2503       // and we now have SGPR as SRC1. If so 2 inlined
2504       // constant and SGPR are illegal.
2505       legalizeOperands(UseMI);
2506 
2507       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2508       if (DeleteDef)
2509         DefMI.eraseFromParent();
2510 
2511       return true;
2512     }
2513   }
2514 
2515   return false;
2516 }
2517 
2518 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
2519                                 int WidthB, int OffsetB) {
2520   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
2521   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
2522   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
2523   return LowOffset + LowWidth <= HighOffset;
2524 }
2525 
2526 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(const MachineInstr &MIa,
2527                                                const MachineInstr &MIb) const {
2528   const MachineOperand *BaseOp0, *BaseOp1;
2529   int64_t Offset0, Offset1;
2530 
2531   if (getMemOperandWithOffset(MIa, BaseOp0, Offset0, &RI) &&
2532       getMemOperandWithOffset(MIb, BaseOp1, Offset1, &RI)) {
2533     if (!BaseOp0->isIdenticalTo(*BaseOp1))
2534       return false;
2535 
2536     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
2537       // FIXME: Handle ds_read2 / ds_write2.
2538       return false;
2539     }
2540     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
2541     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
2542     if (offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
2543       return true;
2544     }
2545   }
2546 
2547   return false;
2548 }
2549 
2550 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
2551                                                   const MachineInstr &MIb) const {
2552   assert(MIa.mayLoadOrStore() &&
2553          "MIa must load from or modify a memory location");
2554   assert(MIb.mayLoadOrStore() &&
2555          "MIb must load from or modify a memory location");
2556 
2557   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
2558     return false;
2559 
2560   // XXX - Can we relax this between address spaces?
2561   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
2562     return false;
2563 
2564   // TODO: Should we check the address space from the MachineMemOperand? That
2565   // would allow us to distinguish objects we know don't alias based on the
2566   // underlying address space, even if it was lowered to a different one,
2567   // e.g. private accesses lowered to use MUBUF instructions on a scratch
2568   // buffer.
2569   if (isDS(MIa)) {
2570     if (isDS(MIb))
2571       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2572 
2573     return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
2574   }
2575 
2576   if (isMUBUF(MIa) || isMTBUF(MIa)) {
2577     if (isMUBUF(MIb) || isMTBUF(MIb))
2578       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2579 
2580     return !isFLAT(MIb) && !isSMRD(MIb);
2581   }
2582 
2583   if (isSMRD(MIa)) {
2584     if (isSMRD(MIb))
2585       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2586 
2587     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
2588   }
2589 
2590   if (isFLAT(MIa)) {
2591     if (isFLAT(MIb))
2592       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2593 
2594     return false;
2595   }
2596 
2597   return false;
2598 }
2599 
2600 static int64_t getFoldableImm(const MachineOperand* MO) {
2601   if (!MO->isReg())
2602     return false;
2603   const MachineFunction *MF = MO->getParent()->getParent()->getParent();
2604   const MachineRegisterInfo &MRI = MF->getRegInfo();
2605   auto Def = MRI.getUniqueVRegDef(MO->getReg());
2606   if (Def && Def->getOpcode() == AMDGPU::V_MOV_B32_e32 &&
2607       Def->getOperand(1).isImm())
2608     return Def->getOperand(1).getImm();
2609   return AMDGPU::NoRegister;
2610 }
2611 
2612 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
2613                                                  MachineInstr &MI,
2614                                                  LiveVariables *LV) const {
2615   unsigned Opc = MI.getOpcode();
2616   bool IsF16 = false;
2617   bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2618                Opc == AMDGPU::V_FMAC_F16_e32 || Opc == AMDGPU::V_FMAC_F16_e64;
2619 
2620   switch (Opc) {
2621   default:
2622     return nullptr;
2623   case AMDGPU::V_MAC_F16_e64:
2624   case AMDGPU::V_FMAC_F16_e64:
2625     IsF16 = true;
2626     LLVM_FALLTHROUGH;
2627   case AMDGPU::V_MAC_F32_e64:
2628   case AMDGPU::V_FMAC_F32_e64:
2629     break;
2630   case AMDGPU::V_MAC_F16_e32:
2631   case AMDGPU::V_FMAC_F16_e32:
2632     IsF16 = true;
2633     LLVM_FALLTHROUGH;
2634   case AMDGPU::V_MAC_F32_e32:
2635   case AMDGPU::V_FMAC_F32_e32: {
2636     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
2637                                              AMDGPU::OpName::src0);
2638     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
2639     if (!Src0->isReg() && !Src0->isImm())
2640       return nullptr;
2641 
2642     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
2643       return nullptr;
2644 
2645     break;
2646   }
2647   }
2648 
2649   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
2650   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
2651   const MachineOperand *Src0Mods =
2652     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2653   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2654   const MachineOperand *Src1Mods =
2655     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2656   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2657   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
2658   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
2659 
2660   if (!Src0Mods && !Src1Mods && !Clamp && !Omod &&
2661       // If we have an SGPR input, we will violate the constant bus restriction.
2662       (ST.getConstantBusLimit(Opc) > 1 ||
2663        !Src0->isReg() ||
2664        !RI.isSGPRReg(MBB->getParent()->getRegInfo(), Src0->getReg()))) {
2665     if (auto Imm = getFoldableImm(Src2)) {
2666       unsigned NewOpc =
2667          IsFMA ? (IsF16 ? AMDGPU::V_FMAAK_F16 : AMDGPU::V_FMAAK_F32)
2668                : (IsF16 ? AMDGPU::V_MADAK_F16 : AMDGPU::V_MADAK_F32);
2669       if (pseudoToMCOpcode(NewOpc) != -1)
2670         return BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
2671                  .add(*Dst)
2672                  .add(*Src0)
2673                  .add(*Src1)
2674                  .addImm(Imm);
2675     }
2676     unsigned NewOpc =
2677       IsFMA ? (IsF16 ? AMDGPU::V_FMAMK_F16 : AMDGPU::V_FMAMK_F32)
2678             : (IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32);
2679     if (auto Imm = getFoldableImm(Src1)) {
2680       if (pseudoToMCOpcode(NewOpc) != -1)
2681         return BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
2682                  .add(*Dst)
2683                  .add(*Src0)
2684                  .addImm(Imm)
2685                  .add(*Src2);
2686     }
2687     if (auto Imm = getFoldableImm(Src0)) {
2688       if (pseudoToMCOpcode(NewOpc) != -1 &&
2689           isOperandLegal(MI, AMDGPU::getNamedOperandIdx(NewOpc,
2690                            AMDGPU::OpName::src0), Src1))
2691         return BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
2692                  .add(*Dst)
2693                  .add(*Src1)
2694                  .addImm(Imm)
2695                  .add(*Src2);
2696     }
2697   }
2698 
2699   unsigned NewOpc = IsFMA ? (IsF16 ? AMDGPU::V_FMA_F16 : AMDGPU::V_FMA_F32)
2700                           : (IsF16 ? AMDGPU::V_MAD_F16 : AMDGPU::V_MAD_F32);
2701   if (pseudoToMCOpcode(NewOpc) == -1)
2702     return nullptr;
2703 
2704   return BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
2705       .add(*Dst)
2706       .addImm(Src0Mods ? Src0Mods->getImm() : 0)
2707       .add(*Src0)
2708       .addImm(Src1Mods ? Src1Mods->getImm() : 0)
2709       .add(*Src1)
2710       .addImm(0) // Src mods
2711       .add(*Src2)
2712       .addImm(Clamp ? Clamp->getImm() : 0)
2713       .addImm(Omod ? Omod->getImm() : 0);
2714 }
2715 
2716 // It's not generally safe to move VALU instructions across these since it will
2717 // start using the register as a base index rather than directly.
2718 // XXX - Why isn't hasSideEffects sufficient for these?
2719 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
2720   switch (MI.getOpcode()) {
2721   case AMDGPU::S_SET_GPR_IDX_ON:
2722   case AMDGPU::S_SET_GPR_IDX_MODE:
2723   case AMDGPU::S_SET_GPR_IDX_OFF:
2724     return true;
2725   default:
2726     return false;
2727   }
2728 }
2729 
2730 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
2731                                        const MachineBasicBlock *MBB,
2732                                        const MachineFunction &MF) const {
2733   // XXX - Do we want the SP check in the base implementation?
2734 
2735   // Target-independent instructions do not have an implicit-use of EXEC, even
2736   // when they operate on VGPRs. Treating EXEC modifications as scheduling
2737   // boundaries prevents incorrect movements of such instructions.
2738   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
2739          MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
2740          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
2741          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
2742          MI.getOpcode() == AMDGPU::S_DENORM_MODE ||
2743          changesVGPRIndexingMode(MI);
2744 }
2745 
2746 bool SIInstrInfo::isAlwaysGDS(uint16_t Opcode) const {
2747   return Opcode == AMDGPU::DS_ORDERED_COUNT ||
2748          Opcode == AMDGPU::DS_GWS_INIT ||
2749          Opcode == AMDGPU::DS_GWS_SEMA_V ||
2750          Opcode == AMDGPU::DS_GWS_SEMA_BR ||
2751          Opcode == AMDGPU::DS_GWS_SEMA_P ||
2752          Opcode == AMDGPU::DS_GWS_SEMA_RELEASE_ALL ||
2753          Opcode == AMDGPU::DS_GWS_BARRIER;
2754 }
2755 
2756 bool SIInstrInfo::hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const {
2757   unsigned Opcode = MI.getOpcode();
2758 
2759   if (MI.mayStore() && isSMRD(MI))
2760     return true; // scalar store or atomic
2761 
2762   // This will terminate the function when other lanes may need to continue.
2763   if (MI.isReturn())
2764     return true;
2765 
2766   // These instructions cause shader I/O that may cause hardware lockups
2767   // when executed with an empty EXEC mask.
2768   //
2769   // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
2770   //       EXEC = 0, but checking for that case here seems not worth it
2771   //       given the typical code patterns.
2772   if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
2773       Opcode == AMDGPU::EXP || Opcode == AMDGPU::EXP_DONE ||
2774       Opcode == AMDGPU::DS_ORDERED_COUNT || Opcode == AMDGPU::S_TRAP ||
2775       Opcode == AMDGPU::DS_GWS_INIT || Opcode == AMDGPU::DS_GWS_BARRIER)
2776     return true;
2777 
2778   if (MI.isCall() || MI.isInlineAsm())
2779     return true; // conservative assumption
2780 
2781   // These are like SALU instructions in terms of effects, so it's questionable
2782   // whether we should return true for those.
2783   //
2784   // However, executing them with EXEC = 0 causes them to operate on undefined
2785   // data, which we avoid by returning true here.
2786   if (Opcode == AMDGPU::V_READFIRSTLANE_B32 || Opcode == AMDGPU::V_READLANE_B32)
2787     return true;
2788 
2789   return false;
2790 }
2791 
2792 bool SIInstrInfo::mayReadEXEC(const MachineRegisterInfo &MRI,
2793                               const MachineInstr &MI) const {
2794   if (MI.isMetaInstruction())
2795     return false;
2796 
2797   // This won't read exec if this is an SGPR->SGPR copy.
2798   if (MI.isCopyLike()) {
2799     if (!RI.isSGPRReg(MRI, MI.getOperand(0).getReg()))
2800       return true;
2801 
2802     // Make sure this isn't copying exec as a normal operand
2803     return MI.readsRegister(AMDGPU::EXEC, &RI);
2804   }
2805 
2806   // Make a conservative assumption about the callee.
2807   if (MI.isCall())
2808     return true;
2809 
2810   // Be conservative with any unhandled generic opcodes.
2811   if (!isTargetSpecificOpcode(MI.getOpcode()))
2812     return true;
2813 
2814   return !isSALU(MI) || MI.readsRegister(AMDGPU::EXEC, &RI);
2815 }
2816 
2817 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
2818   switch (Imm.getBitWidth()) {
2819   case 1: // This likely will be a condition code mask.
2820     return true;
2821 
2822   case 32:
2823     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
2824                                         ST.hasInv2PiInlineImm());
2825   case 64:
2826     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
2827                                         ST.hasInv2PiInlineImm());
2828   case 16:
2829     return ST.has16BitInsts() &&
2830            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
2831                                         ST.hasInv2PiInlineImm());
2832   default:
2833     llvm_unreachable("invalid bitwidth");
2834   }
2835 }
2836 
2837 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
2838                                    uint8_t OperandType) const {
2839   if (!MO.isImm() ||
2840       OperandType < AMDGPU::OPERAND_SRC_FIRST ||
2841       OperandType > AMDGPU::OPERAND_SRC_LAST)
2842     return false;
2843 
2844   // MachineOperand provides no way to tell the true operand size, since it only
2845   // records a 64-bit value. We need to know the size to determine if a 32-bit
2846   // floating point immediate bit pattern is legal for an integer immediate. It
2847   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
2848 
2849   int64_t Imm = MO.getImm();
2850   switch (OperandType) {
2851   case AMDGPU::OPERAND_REG_IMM_INT32:
2852   case AMDGPU::OPERAND_REG_IMM_FP32:
2853   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
2854   case AMDGPU::OPERAND_REG_INLINE_C_FP32:
2855   case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
2856   case AMDGPU::OPERAND_REG_INLINE_AC_FP32: {
2857     int32_t Trunc = static_cast<int32_t>(Imm);
2858     return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
2859   }
2860   case AMDGPU::OPERAND_REG_IMM_INT64:
2861   case AMDGPU::OPERAND_REG_IMM_FP64:
2862   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
2863   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
2864     return AMDGPU::isInlinableLiteral64(MO.getImm(),
2865                                         ST.hasInv2PiInlineImm());
2866   case AMDGPU::OPERAND_REG_IMM_INT16:
2867   case AMDGPU::OPERAND_REG_IMM_FP16:
2868   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
2869   case AMDGPU::OPERAND_REG_INLINE_C_FP16:
2870   case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
2871   case AMDGPU::OPERAND_REG_INLINE_AC_FP16: {
2872     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
2873       // A few special case instructions have 16-bit operands on subtargets
2874       // where 16-bit instructions are not legal.
2875       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
2876       // constants in these cases
2877       int16_t Trunc = static_cast<int16_t>(Imm);
2878       return ST.has16BitInsts() &&
2879              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
2880     }
2881 
2882     return false;
2883   }
2884   case AMDGPU::OPERAND_REG_IMM_V2INT16:
2885   case AMDGPU::OPERAND_REG_IMM_V2FP16:
2886   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
2887   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
2888   case AMDGPU::OPERAND_REG_INLINE_AC_V2INT16:
2889   case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: {
2890     uint32_t Trunc = static_cast<uint32_t>(Imm);
2891     return AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
2892   }
2893   default:
2894     llvm_unreachable("invalid bitwidth");
2895   }
2896 }
2897 
2898 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
2899                                         const MCOperandInfo &OpInfo) const {
2900   switch (MO.getType()) {
2901   case MachineOperand::MO_Register:
2902     return false;
2903   case MachineOperand::MO_Immediate:
2904     return !isInlineConstant(MO, OpInfo);
2905   case MachineOperand::MO_FrameIndex:
2906   case MachineOperand::MO_MachineBasicBlock:
2907   case MachineOperand::MO_ExternalSymbol:
2908   case MachineOperand::MO_GlobalAddress:
2909   case MachineOperand::MO_MCSymbol:
2910     return true;
2911   default:
2912     llvm_unreachable("unexpected operand type");
2913   }
2914 }
2915 
2916 static bool compareMachineOp(const MachineOperand &Op0,
2917                              const MachineOperand &Op1) {
2918   if (Op0.getType() != Op1.getType())
2919     return false;
2920 
2921   switch (Op0.getType()) {
2922   case MachineOperand::MO_Register:
2923     return Op0.getReg() == Op1.getReg();
2924   case MachineOperand::MO_Immediate:
2925     return Op0.getImm() == Op1.getImm();
2926   default:
2927     llvm_unreachable("Didn't expect to be comparing these operand types");
2928   }
2929 }
2930 
2931 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
2932                                     const MachineOperand &MO) const {
2933   const MCInstrDesc &InstDesc = MI.getDesc();
2934   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo];
2935 
2936   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
2937 
2938   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
2939     return true;
2940 
2941   if (OpInfo.RegClass < 0)
2942     return false;
2943 
2944   const MachineFunction *MF = MI.getParent()->getParent();
2945   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2946 
2947   if (MO.isImm() && isInlineConstant(MO, OpInfo)) {
2948     if (isMAI(MI) && ST.hasMFMAInlineLiteralBug() &&
2949         OpNo ==(unsigned)AMDGPU::getNamedOperandIdx(MI.getOpcode(),
2950                                                     AMDGPU::OpName::src2))
2951       return false;
2952     return RI.opCanUseInlineConstant(OpInfo.OperandType);
2953   }
2954 
2955   if (!RI.opCanUseLiteralConstant(OpInfo.OperandType))
2956     return false;
2957 
2958   if (!isVOP3(MI) || !AMDGPU::isSISrcOperand(InstDesc, OpNo))
2959     return true;
2960 
2961   return ST.hasVOP3Literal();
2962 }
2963 
2964 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
2965   int Op32 = AMDGPU::getVOPe32(Opcode);
2966   if (Op32 == -1)
2967     return false;
2968 
2969   return pseudoToMCOpcode(Op32) != -1;
2970 }
2971 
2972 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
2973   // The src0_modifier operand is present on all instructions
2974   // that have modifiers.
2975 
2976   return AMDGPU::getNamedOperandIdx(Opcode,
2977                                     AMDGPU::OpName::src0_modifiers) != -1;
2978 }
2979 
2980 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
2981                                   unsigned OpName) const {
2982   const MachineOperand *Mods = getNamedOperand(MI, OpName);
2983   return Mods && Mods->getImm();
2984 }
2985 
2986 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
2987   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
2988          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
2989          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
2990          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
2991          hasModifiersSet(MI, AMDGPU::OpName::omod);
2992 }
2993 
2994 bool SIInstrInfo::canShrink(const MachineInstr &MI,
2995                             const MachineRegisterInfo &MRI) const {
2996   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2997   // Can't shrink instruction with three operands.
2998   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
2999   // a special case for it.  It can only be shrunk if the third operand
3000   // is vcc, and src0_modifiers and src1_modifiers are not set.
3001   // We should handle this the same way we handle vopc, by addding
3002   // a register allocation hint pre-regalloc and then do the shrinking
3003   // post-regalloc.
3004   if (Src2) {
3005     switch (MI.getOpcode()) {
3006       default: return false;
3007 
3008       case AMDGPU::V_ADDC_U32_e64:
3009       case AMDGPU::V_SUBB_U32_e64:
3010       case AMDGPU::V_SUBBREV_U32_e64: {
3011         const MachineOperand *Src1
3012           = getNamedOperand(MI, AMDGPU::OpName::src1);
3013         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
3014           return false;
3015         // Additional verification is needed for sdst/src2.
3016         return true;
3017       }
3018       case AMDGPU::V_MAC_F32_e64:
3019       case AMDGPU::V_MAC_F16_e64:
3020       case AMDGPU::V_FMAC_F32_e64:
3021       case AMDGPU::V_FMAC_F16_e64:
3022         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
3023             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
3024           return false;
3025         break;
3026 
3027       case AMDGPU::V_CNDMASK_B32_e64:
3028         break;
3029     }
3030   }
3031 
3032   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3033   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
3034                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
3035     return false;
3036 
3037   // We don't need to check src0, all input types are legal, so just make sure
3038   // src0 isn't using any modifiers.
3039   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
3040     return false;
3041 
3042   // Can it be shrunk to a valid 32 bit opcode?
3043   if (!hasVALU32BitEncoding(MI.getOpcode()))
3044     return false;
3045 
3046   // Check output modifiers
3047   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
3048          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
3049 }
3050 
3051 // Set VCC operand with all flags from \p Orig, except for setting it as
3052 // implicit.
3053 static void copyFlagsToImplicitVCC(MachineInstr &MI,
3054                                    const MachineOperand &Orig) {
3055 
3056   for (MachineOperand &Use : MI.implicit_operands()) {
3057     if (Use.isUse() && Use.getReg() == AMDGPU::VCC) {
3058       Use.setIsUndef(Orig.isUndef());
3059       Use.setIsKill(Orig.isKill());
3060       return;
3061     }
3062   }
3063 }
3064 
3065 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
3066                                            unsigned Op32) const {
3067   MachineBasicBlock *MBB = MI.getParent();;
3068   MachineInstrBuilder Inst32 =
3069     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32));
3070 
3071   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
3072   // For VOPC instructions, this is replaced by an implicit def of vcc.
3073   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
3074   if (Op32DstIdx != -1) {
3075     // dst
3076     Inst32.add(MI.getOperand(0));
3077   } else {
3078     assert(((MI.getOperand(0).getReg() == AMDGPU::VCC) ||
3079             (MI.getOperand(0).getReg() == AMDGPU::VCC_LO)) &&
3080            "Unexpected case");
3081   }
3082 
3083   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
3084 
3085   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3086   if (Src1)
3087     Inst32.add(*Src1);
3088 
3089   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3090 
3091   if (Src2) {
3092     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
3093     if (Op32Src2Idx != -1) {
3094       Inst32.add(*Src2);
3095     } else {
3096       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
3097       // replaced with an implicit read of vcc. This was already added
3098       // during the initial BuildMI, so find it to preserve the flags.
3099       copyFlagsToImplicitVCC(*Inst32, *Src2);
3100     }
3101   }
3102 
3103   return Inst32;
3104 }
3105 
3106 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
3107                                   const MachineOperand &MO,
3108                                   const MCOperandInfo &OpInfo) const {
3109   // Literal constants use the constant bus.
3110   //if (isLiteralConstantLike(MO, OpInfo))
3111   // return true;
3112   if (MO.isImm())
3113     return !isInlineConstant(MO, OpInfo);
3114 
3115   if (!MO.isReg())
3116     return true; // Misc other operands like FrameIndex
3117 
3118   if (!MO.isUse())
3119     return false;
3120 
3121   if (Register::isVirtualRegister(MO.getReg()))
3122     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
3123 
3124   // Null is free
3125   if (MO.getReg() == AMDGPU::SGPR_NULL)
3126     return false;
3127 
3128   // SGPRs use the constant bus
3129   if (MO.isImplicit()) {
3130     return MO.getReg() == AMDGPU::M0 ||
3131            MO.getReg() == AMDGPU::VCC ||
3132            MO.getReg() == AMDGPU::VCC_LO;
3133   } else {
3134     return AMDGPU::SReg_32RegClass.contains(MO.getReg()) ||
3135            AMDGPU::SReg_64RegClass.contains(MO.getReg());
3136   }
3137 }
3138 
3139 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
3140   for (const MachineOperand &MO : MI.implicit_operands()) {
3141     // We only care about reads.
3142     if (MO.isDef())
3143       continue;
3144 
3145     switch (MO.getReg()) {
3146     case AMDGPU::VCC:
3147     case AMDGPU::VCC_LO:
3148     case AMDGPU::VCC_HI:
3149     case AMDGPU::M0:
3150     case AMDGPU::FLAT_SCR:
3151       return MO.getReg();
3152 
3153     default:
3154       break;
3155     }
3156   }
3157 
3158   return AMDGPU::NoRegister;
3159 }
3160 
3161 static bool shouldReadExec(const MachineInstr &MI) {
3162   if (SIInstrInfo::isVALU(MI)) {
3163     switch (MI.getOpcode()) {
3164     case AMDGPU::V_READLANE_B32:
3165     case AMDGPU::V_READLANE_B32_gfx6_gfx7:
3166     case AMDGPU::V_READLANE_B32_gfx10:
3167     case AMDGPU::V_READLANE_B32_vi:
3168     case AMDGPU::V_WRITELANE_B32:
3169     case AMDGPU::V_WRITELANE_B32_gfx6_gfx7:
3170     case AMDGPU::V_WRITELANE_B32_gfx10:
3171     case AMDGPU::V_WRITELANE_B32_vi:
3172       return false;
3173     }
3174 
3175     return true;
3176   }
3177 
3178   if (MI.isPreISelOpcode() ||
3179       SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
3180       SIInstrInfo::isSALU(MI) ||
3181       SIInstrInfo::isSMRD(MI))
3182     return false;
3183 
3184   return true;
3185 }
3186 
3187 static bool isSubRegOf(const SIRegisterInfo &TRI,
3188                        const MachineOperand &SuperVec,
3189                        const MachineOperand &SubReg) {
3190   if (Register::isPhysicalRegister(SubReg.getReg()))
3191     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
3192 
3193   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
3194          SubReg.getReg() == SuperVec.getReg();
3195 }
3196 
3197 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
3198                                     StringRef &ErrInfo) const {
3199   uint16_t Opcode = MI.getOpcode();
3200   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
3201     return true;
3202 
3203   const MachineFunction *MF = MI.getParent()->getParent();
3204   const MachineRegisterInfo &MRI = MF->getRegInfo();
3205 
3206   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
3207   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
3208   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
3209 
3210   // Make sure the number of operands is correct.
3211   const MCInstrDesc &Desc = get(Opcode);
3212   if (!Desc.isVariadic() &&
3213       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
3214     ErrInfo = "Instruction has wrong number of operands.";
3215     return false;
3216   }
3217 
3218   if (MI.isInlineAsm()) {
3219     // Verify register classes for inlineasm constraints.
3220     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
3221          I != E; ++I) {
3222       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
3223       if (!RC)
3224         continue;
3225 
3226       const MachineOperand &Op = MI.getOperand(I);
3227       if (!Op.isReg())
3228         continue;
3229 
3230       Register Reg = Op.getReg();
3231       if (!Register::isVirtualRegister(Reg) && !RC->contains(Reg)) {
3232         ErrInfo = "inlineasm operand has incorrect register class.";
3233         return false;
3234       }
3235     }
3236 
3237     return true;
3238   }
3239 
3240   // Make sure the register classes are correct.
3241   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
3242     if (MI.getOperand(i).isFPImm()) {
3243       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
3244                 "all fp values to integers.";
3245       return false;
3246     }
3247 
3248     int RegClass = Desc.OpInfo[i].RegClass;
3249 
3250     switch (Desc.OpInfo[i].OperandType) {
3251     case MCOI::OPERAND_REGISTER:
3252       if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
3253         ErrInfo = "Illegal immediate value for operand.";
3254         return false;
3255       }
3256       break;
3257     case AMDGPU::OPERAND_REG_IMM_INT32:
3258     case AMDGPU::OPERAND_REG_IMM_FP32:
3259       break;
3260     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3261     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3262     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3263     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3264     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3265     case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3266     case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3267     case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
3268     case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3269     case AMDGPU::OPERAND_REG_INLINE_AC_FP16: {
3270       const MachineOperand &MO = MI.getOperand(i);
3271       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
3272         ErrInfo = "Illegal immediate value for operand.";
3273         return false;
3274       }
3275       break;
3276     }
3277     case MCOI::OPERAND_IMMEDIATE:
3278     case AMDGPU::OPERAND_KIMM32:
3279       // Check if this operand is an immediate.
3280       // FrameIndex operands will be replaced by immediates, so they are
3281       // allowed.
3282       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
3283         ErrInfo = "Expected immediate, but got non-immediate";
3284         return false;
3285       }
3286       LLVM_FALLTHROUGH;
3287     default:
3288       continue;
3289     }
3290 
3291     if (!MI.getOperand(i).isReg())
3292       continue;
3293 
3294     if (RegClass != -1) {
3295       Register Reg = MI.getOperand(i).getReg();
3296       if (Reg == AMDGPU::NoRegister || Register::isVirtualRegister(Reg))
3297         continue;
3298 
3299       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
3300       if (!RC->contains(Reg)) {
3301         ErrInfo = "Operand has incorrect register class.";
3302         return false;
3303       }
3304     }
3305   }
3306 
3307   // Verify SDWA
3308   if (isSDWA(MI)) {
3309     if (!ST.hasSDWA()) {
3310       ErrInfo = "SDWA is not supported on this target";
3311       return false;
3312     }
3313 
3314     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
3315 
3316     const int OpIndicies[] = { DstIdx, Src0Idx, Src1Idx, Src2Idx };
3317 
3318     for (int OpIdx: OpIndicies) {
3319       if (OpIdx == -1)
3320         continue;
3321       const MachineOperand &MO = MI.getOperand(OpIdx);
3322 
3323       if (!ST.hasSDWAScalar()) {
3324         // Only VGPRS on VI
3325         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
3326           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
3327           return false;
3328         }
3329       } else {
3330         // No immediates on GFX9
3331         if (!MO.isReg()) {
3332           ErrInfo = "Only reg allowed as operands in SDWA instructions on GFX9";
3333           return false;
3334         }
3335       }
3336     }
3337 
3338     if (!ST.hasSDWAOmod()) {
3339       // No omod allowed on VI
3340       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
3341       if (OMod != nullptr &&
3342         (!OMod->isImm() || OMod->getImm() != 0)) {
3343         ErrInfo = "OMod not allowed in SDWA instructions on VI";
3344         return false;
3345       }
3346     }
3347 
3348     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
3349     if (isVOPC(BasicOpcode)) {
3350       if (!ST.hasSDWASdst() && DstIdx != -1) {
3351         // Only vcc allowed as dst on VI for VOPC
3352         const MachineOperand &Dst = MI.getOperand(DstIdx);
3353         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
3354           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
3355           return false;
3356         }
3357       } else if (!ST.hasSDWAOutModsVOPC()) {
3358         // No clamp allowed on GFX9 for VOPC
3359         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
3360         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
3361           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
3362           return false;
3363         }
3364 
3365         // No omod allowed on GFX9 for VOPC
3366         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
3367         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
3368           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
3369           return false;
3370         }
3371       }
3372     }
3373 
3374     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
3375     if (DstUnused && DstUnused->isImm() &&
3376         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
3377       const MachineOperand &Dst = MI.getOperand(DstIdx);
3378       if (!Dst.isReg() || !Dst.isTied()) {
3379         ErrInfo = "Dst register should have tied register";
3380         return false;
3381       }
3382 
3383       const MachineOperand &TiedMO =
3384           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
3385       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
3386         ErrInfo =
3387             "Dst register should be tied to implicit use of preserved register";
3388         return false;
3389       } else if (Register::isPhysicalRegister(TiedMO.getReg()) &&
3390                  Dst.getReg() != TiedMO.getReg()) {
3391         ErrInfo = "Dst register should use same physical register as preserved";
3392         return false;
3393       }
3394     }
3395   }
3396 
3397   // Verify MIMG
3398   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
3399     // Ensure that the return type used is large enough for all the options
3400     // being used TFE/LWE require an extra result register.
3401     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
3402     if (DMask) {
3403       uint64_t DMaskImm = DMask->getImm();
3404       uint32_t RegCount =
3405           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
3406       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
3407       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
3408       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
3409 
3410       // Adjust for packed 16 bit values
3411       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
3412         RegCount >>= 1;
3413 
3414       // Adjust if using LWE or TFE
3415       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
3416         RegCount += 1;
3417 
3418       const uint32_t DstIdx =
3419           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
3420       const MachineOperand &Dst = MI.getOperand(DstIdx);
3421       if (Dst.isReg()) {
3422         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
3423         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
3424         if (RegCount > DstSize) {
3425           ErrInfo = "MIMG instruction returns too many registers for dst "
3426                     "register class";
3427           return false;
3428         }
3429       }
3430     }
3431   }
3432 
3433   // Verify VOP*. Ignore multiple sgpr operands on writelane.
3434   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
3435       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
3436     // Only look at the true operands. Only a real operand can use the constant
3437     // bus, and we don't want to check pseudo-operands like the source modifier
3438     // flags.
3439     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
3440 
3441     unsigned ConstantBusCount = 0;
3442     unsigned LiteralCount = 0;
3443 
3444     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
3445       ++ConstantBusCount;
3446 
3447     SmallVector<unsigned, 2> SGPRsUsed;
3448     unsigned SGPRUsed = findImplicitSGPRRead(MI);
3449     if (SGPRUsed != AMDGPU::NoRegister) {
3450       ++ConstantBusCount;
3451       SGPRsUsed.push_back(SGPRUsed);
3452     }
3453 
3454     for (int OpIdx : OpIndices) {
3455       if (OpIdx == -1)
3456         break;
3457       const MachineOperand &MO = MI.getOperand(OpIdx);
3458       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
3459         if (MO.isReg()) {
3460           SGPRUsed = MO.getReg();
3461           if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
3462                 return !RI.regsOverlap(SGPRUsed, SGPR);
3463               })) {
3464             ++ConstantBusCount;
3465             SGPRsUsed.push_back(SGPRUsed);
3466           }
3467         } else {
3468           ++ConstantBusCount;
3469           ++LiteralCount;
3470         }
3471       }
3472     }
3473     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3474     // v_writelane_b32 is an exception from constant bus restriction:
3475     // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
3476     if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
3477         Opcode != AMDGPU::V_WRITELANE_B32) {
3478       ErrInfo = "VOP* instruction violates constant bus restriction";
3479       return false;
3480     }
3481 
3482     if (isVOP3(MI) && LiteralCount) {
3483       if (LiteralCount && !ST.hasVOP3Literal()) {
3484         ErrInfo = "VOP3 instruction uses literal";
3485         return false;
3486       }
3487       if (LiteralCount > 1) {
3488         ErrInfo = "VOP3 instruction uses more than one literal";
3489         return false;
3490       }
3491     }
3492   }
3493 
3494   // Special case for writelane - this can break the multiple constant bus rule,
3495   // but still can't use more than one SGPR register
3496   if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
3497     unsigned SGPRCount = 0;
3498     Register SGPRUsed = AMDGPU::NoRegister;
3499 
3500     for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx}) {
3501       if (OpIdx == -1)
3502         break;
3503 
3504       const MachineOperand &MO = MI.getOperand(OpIdx);
3505 
3506       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
3507         if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
3508           if (MO.getReg() != SGPRUsed)
3509             ++SGPRCount;
3510           SGPRUsed = MO.getReg();
3511         }
3512       }
3513       if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
3514         ErrInfo = "WRITELANE instruction violates constant bus restriction";
3515         return false;
3516       }
3517     }
3518   }
3519 
3520   // Verify misc. restrictions on specific instructions.
3521   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
3522       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
3523     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
3524     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
3525     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
3526     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
3527       if (!compareMachineOp(Src0, Src1) &&
3528           !compareMachineOp(Src0, Src2)) {
3529         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
3530         return false;
3531       }
3532     }
3533   }
3534 
3535   if (isSOP2(MI) || isSOPC(MI)) {
3536     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
3537     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
3538     unsigned Immediates = 0;
3539 
3540     if (!Src0.isReg() &&
3541         !isInlineConstant(Src0, Desc.OpInfo[Src0Idx].OperandType))
3542       Immediates++;
3543     if (!Src1.isReg() &&
3544         !isInlineConstant(Src1, Desc.OpInfo[Src1Idx].OperandType))
3545       Immediates++;
3546 
3547     if (Immediates > 1) {
3548       ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
3549       return false;
3550     }
3551   }
3552 
3553   if (isSOPK(MI)) {
3554     auto Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
3555     if (Desc.isBranch()) {
3556       if (!Op->isMBB()) {
3557         ErrInfo = "invalid branch target for SOPK instruction";
3558         return false;
3559       }
3560     } else {
3561       uint64_t Imm = Op->getImm();
3562       if (sopkIsZext(MI)) {
3563         if (!isUInt<16>(Imm)) {
3564           ErrInfo = "invalid immediate for SOPK instruction";
3565           return false;
3566         }
3567       } else {
3568         if (!isInt<16>(Imm)) {
3569           ErrInfo = "invalid immediate for SOPK instruction";
3570           return false;
3571         }
3572       }
3573     }
3574   }
3575 
3576   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
3577       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
3578       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
3579       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
3580     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
3581                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
3582 
3583     const unsigned StaticNumOps = Desc.getNumOperands() +
3584       Desc.getNumImplicitUses();
3585     const unsigned NumImplicitOps = IsDst ? 2 : 1;
3586 
3587     // Allow additional implicit operands. This allows a fixup done by the post
3588     // RA scheduler where the main implicit operand is killed and implicit-defs
3589     // are added for sub-registers that remain live after this instruction.
3590     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
3591       ErrInfo = "missing implicit register operands";
3592       return false;
3593     }
3594 
3595     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
3596     if (IsDst) {
3597       if (!Dst->isUse()) {
3598         ErrInfo = "v_movreld_b32 vdst should be a use operand";
3599         return false;
3600       }
3601 
3602       unsigned UseOpIdx;
3603       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
3604           UseOpIdx != StaticNumOps + 1) {
3605         ErrInfo = "movrel implicit operands should be tied";
3606         return false;
3607       }
3608     }
3609 
3610     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
3611     const MachineOperand &ImpUse
3612       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
3613     if (!ImpUse.isReg() || !ImpUse.isUse() ||
3614         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
3615       ErrInfo = "src0 should be subreg of implicit vector use";
3616       return false;
3617     }
3618   }
3619 
3620   // Make sure we aren't losing exec uses in the td files. This mostly requires
3621   // being careful when using let Uses to try to add other use registers.
3622   if (shouldReadExec(MI)) {
3623     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
3624       ErrInfo = "VALU instruction does not implicitly read exec mask";
3625       return false;
3626     }
3627   }
3628 
3629   if (isSMRD(MI)) {
3630     if (MI.mayStore()) {
3631       // The register offset form of scalar stores may only use m0 as the
3632       // soffset register.
3633       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
3634       if (Soff && Soff->getReg() != AMDGPU::M0) {
3635         ErrInfo = "scalar stores must use m0 as offset register";
3636         return false;
3637       }
3638     }
3639   }
3640 
3641   if (isFLAT(MI) && !MF->getSubtarget<GCNSubtarget>().hasFlatInstOffsets()) {
3642     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
3643     if (Offset->getImm() != 0) {
3644       ErrInfo = "subtarget does not support offsets in flat instructions";
3645       return false;
3646     }
3647   }
3648 
3649   if (isMIMG(MI)) {
3650     const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
3651     if (DimOp) {
3652       int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
3653                                                  AMDGPU::OpName::vaddr0);
3654       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
3655       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
3656       const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
3657           AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
3658       const AMDGPU::MIMGDimInfo *Dim =
3659           AMDGPU::getMIMGDimInfoByEncoding(DimOp->getImm());
3660 
3661       if (!Dim) {
3662         ErrInfo = "dim is out of range";
3663         return false;
3664       }
3665 
3666       bool IsNSA = SRsrcIdx - VAddr0Idx > 1;
3667       unsigned AddrWords = BaseOpcode->NumExtraArgs +
3668                            (BaseOpcode->Gradients ? Dim->NumGradients : 0) +
3669                            (BaseOpcode->Coordinates ? Dim->NumCoords : 0) +
3670                            (BaseOpcode->LodOrClampOrMip ? 1 : 0);
3671 
3672       unsigned VAddrWords;
3673       if (IsNSA) {
3674         VAddrWords = SRsrcIdx - VAddr0Idx;
3675       } else {
3676         const TargetRegisterClass *RC = getOpRegClass(MI, VAddr0Idx);
3677         VAddrWords = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 32;
3678         if (AddrWords > 8)
3679           AddrWords = 16;
3680         else if (AddrWords > 4)
3681           AddrWords = 8;
3682         else if (AddrWords == 3 && VAddrWords == 4) {
3683           // CodeGen uses the V4 variant of instructions for three addresses,
3684           // because the selection DAG does not support non-power-of-two types.
3685           AddrWords = 4;
3686         }
3687       }
3688 
3689       if (VAddrWords != AddrWords) {
3690         ErrInfo = "bad vaddr size";
3691         return false;
3692       }
3693     }
3694   }
3695 
3696   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
3697   if (DppCt) {
3698     using namespace AMDGPU::DPP;
3699 
3700     unsigned DC = DppCt->getImm();
3701     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
3702         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
3703         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
3704         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
3705         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
3706         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
3707         (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
3708       ErrInfo = "Invalid dpp_ctrl value";
3709       return false;
3710     }
3711     if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
3712         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
3713       ErrInfo = "Invalid dpp_ctrl value: "
3714                 "wavefront shifts are not supported on GFX10+";
3715       return false;
3716     }
3717     if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
3718         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
3719       ErrInfo = "Invalid dpp_ctrl value: "
3720                 "broadcasts are not supported on GFX10+";
3721       return false;
3722     }
3723     if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
3724         ST.getGeneration() < AMDGPUSubtarget::GFX10) {
3725       ErrInfo = "Invalid dpp_ctrl value: "
3726                 "row_share and row_xmask are not supported before GFX10";
3727       return false;
3728     }
3729   }
3730 
3731   return true;
3732 }
3733 
3734 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
3735   switch (MI.getOpcode()) {
3736   default: return AMDGPU::INSTRUCTION_LIST_END;
3737   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
3738   case AMDGPU::COPY: return AMDGPU::COPY;
3739   case AMDGPU::PHI: return AMDGPU::PHI;
3740   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
3741   case AMDGPU::WQM: return AMDGPU::WQM;
3742   case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
3743   case AMDGPU::WWM: return AMDGPU::WWM;
3744   case AMDGPU::S_MOV_B32: {
3745     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3746     return MI.getOperand(1).isReg() ||
3747            RI.isAGPR(MRI, MI.getOperand(0).getReg()) ?
3748            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
3749   }
3750   case AMDGPU::S_ADD_I32:
3751     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_I32_e32;
3752   case AMDGPU::S_ADDC_U32:
3753     return AMDGPU::V_ADDC_U32_e32;
3754   case AMDGPU::S_SUB_I32:
3755     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_I32_e32;
3756     // FIXME: These are not consistently handled, and selected when the carry is
3757     // used.
3758   case AMDGPU::S_ADD_U32:
3759     return AMDGPU::V_ADD_I32_e32;
3760   case AMDGPU::S_SUB_U32:
3761     return AMDGPU::V_SUB_I32_e32;
3762   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
3763   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32;
3764   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32;
3765   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32;
3766   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
3767   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
3768   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
3769   case AMDGPU::S_XNOR_B32:
3770     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
3771   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
3772   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
3773   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
3774   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
3775   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
3776   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
3777   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
3778   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
3779   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
3780   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
3781   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
3782   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
3783   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
3784   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
3785   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
3786   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
3787   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
3788   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
3789   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
3790   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
3791   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
3792   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
3793   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
3794   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
3795   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
3796   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
3797   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
3798   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
3799   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
3800   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
3801   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
3802   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
3803   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
3804   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
3805   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
3806   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
3807   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
3808   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
3809   }
3810   llvm_unreachable(
3811       "Unexpected scalar opcode without corresponding vector one!");
3812 }
3813 
3814 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
3815                                                       unsigned OpNo) const {
3816   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3817   const MCInstrDesc &Desc = get(MI.getOpcode());
3818   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
3819       Desc.OpInfo[OpNo].RegClass == -1) {
3820     Register Reg = MI.getOperand(OpNo).getReg();
3821 
3822     if (Register::isVirtualRegister(Reg))
3823       return MRI.getRegClass(Reg);
3824     return RI.getPhysRegClass(Reg);
3825   }
3826 
3827   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
3828   return RI.getRegClass(RCID);
3829 }
3830 
3831 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
3832   MachineBasicBlock::iterator I = MI;
3833   MachineBasicBlock *MBB = MI.getParent();
3834   MachineOperand &MO = MI.getOperand(OpIdx);
3835   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
3836   const SIRegisterInfo *TRI =
3837       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
3838   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
3839   const TargetRegisterClass *RC = RI.getRegClass(RCID);
3840   unsigned Size = TRI->getRegSizeInBits(*RC);
3841   unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO : AMDGPU::V_MOV_B32_e32;
3842   if (MO.isReg())
3843     Opcode = AMDGPU::COPY;
3844   else if (RI.isSGPRClass(RC))
3845     Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
3846 
3847   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
3848   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
3849     VRC = &AMDGPU::VReg_64RegClass;
3850   else
3851     VRC = &AMDGPU::VGPR_32RegClass;
3852 
3853   Register Reg = MRI.createVirtualRegister(VRC);
3854   DebugLoc DL = MBB->findDebugLoc(I);
3855   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
3856   MO.ChangeToRegister(Reg, false);
3857 }
3858 
3859 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
3860                                          MachineRegisterInfo &MRI,
3861                                          MachineOperand &SuperReg,
3862                                          const TargetRegisterClass *SuperRC,
3863                                          unsigned SubIdx,
3864                                          const TargetRegisterClass *SubRC)
3865                                          const {
3866   MachineBasicBlock *MBB = MI->getParent();
3867   DebugLoc DL = MI->getDebugLoc();
3868   Register SubReg = MRI.createVirtualRegister(SubRC);
3869 
3870   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
3871     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
3872       .addReg(SuperReg.getReg(), 0, SubIdx);
3873     return SubReg;
3874   }
3875 
3876   // Just in case the super register is itself a sub-register, copy it to a new
3877   // value so we don't need to worry about merging its subreg index with the
3878   // SubIdx passed to this function. The register coalescer should be able to
3879   // eliminate this extra copy.
3880   Register NewSuperReg = MRI.createVirtualRegister(SuperRC);
3881 
3882   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
3883     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
3884 
3885   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
3886     .addReg(NewSuperReg, 0, SubIdx);
3887 
3888   return SubReg;
3889 }
3890 
3891 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
3892   MachineBasicBlock::iterator MII,
3893   MachineRegisterInfo &MRI,
3894   MachineOperand &Op,
3895   const TargetRegisterClass *SuperRC,
3896   unsigned SubIdx,
3897   const TargetRegisterClass *SubRC) const {
3898   if (Op.isImm()) {
3899     if (SubIdx == AMDGPU::sub0)
3900       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
3901     if (SubIdx == AMDGPU::sub1)
3902       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
3903 
3904     llvm_unreachable("Unhandled register index for immediate");
3905   }
3906 
3907   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
3908                                        SubIdx, SubRC);
3909   return MachineOperand::CreateReg(SubReg, false);
3910 }
3911 
3912 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
3913 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
3914   assert(Inst.getNumExplicitOperands() == 3);
3915   MachineOperand Op1 = Inst.getOperand(1);
3916   Inst.RemoveOperand(1);
3917   Inst.addOperand(Op1);
3918 }
3919 
3920 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
3921                                     const MCOperandInfo &OpInfo,
3922                                     const MachineOperand &MO) const {
3923   if (!MO.isReg())
3924     return false;
3925 
3926   Register Reg = MO.getReg();
3927   const TargetRegisterClass *RC = Register::isVirtualRegister(Reg)
3928                                       ? MRI.getRegClass(Reg)
3929                                       : RI.getPhysRegClass(Reg);
3930 
3931   const TargetRegisterClass *DRC = RI.getRegClass(OpInfo.RegClass);
3932   if (MO.getSubReg()) {
3933     const MachineFunction *MF = MO.getParent()->getParent()->getParent();
3934     const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
3935     if (!SuperRC)
3936       return false;
3937 
3938     DRC = RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg());
3939     if (!DRC)
3940       return false;
3941   }
3942   return RC->hasSuperClassEq(DRC);
3943 }
3944 
3945 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
3946                                      const MCOperandInfo &OpInfo,
3947                                      const MachineOperand &MO) const {
3948   if (MO.isReg())
3949     return isLegalRegOperand(MRI, OpInfo, MO);
3950 
3951   // Handle non-register types that are treated like immediates.
3952   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
3953   return true;
3954 }
3955 
3956 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
3957                                  const MachineOperand *MO) const {
3958   const MachineFunction &MF = *MI.getParent()->getParent();
3959   const MachineRegisterInfo &MRI = MF.getRegInfo();
3960   const MCInstrDesc &InstDesc = MI.getDesc();
3961   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
3962   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3963   const TargetRegisterClass *DefinedRC =
3964       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
3965   if (!MO)
3966     MO = &MI.getOperand(OpIdx);
3967 
3968   int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
3969   int VOP3LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
3970   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
3971     if (isVOP3(MI) && isLiteralConstantLike(*MO, OpInfo) && !VOP3LiteralLimit--)
3972       return false;
3973 
3974     SmallDenseSet<RegSubRegPair> SGPRsUsed;
3975     if (MO->isReg())
3976       SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
3977 
3978     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3979       if (i == OpIdx)
3980         continue;
3981       const MachineOperand &Op = MI.getOperand(i);
3982       if (Op.isReg()) {
3983         RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
3984         if (!SGPRsUsed.count(SGPR) &&
3985             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
3986           if (--ConstantBusLimit <= 0)
3987             return false;
3988           SGPRsUsed.insert(SGPR);
3989         }
3990       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
3991         if (--ConstantBusLimit <= 0)
3992           return false;
3993       } else if (isVOP3(MI) && AMDGPU::isSISrcOperand(InstDesc, i) &&
3994                  isLiteralConstantLike(Op, InstDesc.OpInfo[i])) {
3995         if (!VOP3LiteralLimit--)
3996           return false;
3997         if (--ConstantBusLimit <= 0)
3998           return false;
3999       }
4000     }
4001   }
4002 
4003   if (MO->isReg()) {
4004     assert(DefinedRC);
4005     return isLegalRegOperand(MRI, OpInfo, *MO);
4006   }
4007 
4008   // Handle non-register types that are treated like immediates.
4009   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
4010 
4011   if (!DefinedRC) {
4012     // This operand expects an immediate.
4013     return true;
4014   }
4015 
4016   return isImmOperandLegal(MI, OpIdx, *MO);
4017 }
4018 
4019 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
4020                                        MachineInstr &MI) const {
4021   unsigned Opc = MI.getOpcode();
4022   const MCInstrDesc &InstrDesc = get(Opc);
4023 
4024   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4025   MachineOperand &Src0 = MI.getOperand(Src0Idx);
4026 
4027   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4028   MachineOperand &Src1 = MI.getOperand(Src1Idx);
4029 
4030   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
4031   // we need to only have one constant bus use before GFX10.
4032   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
4033   if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 &&
4034       Src0.isReg() && (RI.isSGPRReg(MRI, Src0.getReg()) ||
4035        isLiteralConstantLike(Src0, InstrDesc.OpInfo[Src0Idx])))
4036     legalizeOpWithMove(MI, Src0Idx);
4037 
4038   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
4039   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
4040   // src0/src1 with V_READFIRSTLANE.
4041   if (Opc == AMDGPU::V_WRITELANE_B32) {
4042     const DebugLoc &DL = MI.getDebugLoc();
4043     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
4044       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4045       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4046           .add(Src0);
4047       Src0.ChangeToRegister(Reg, false);
4048     }
4049     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
4050       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4051       const DebugLoc &DL = MI.getDebugLoc();
4052       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4053           .add(Src1);
4054       Src1.ChangeToRegister(Reg, false);
4055     }
4056     return;
4057   }
4058 
4059   // No VOP2 instructions support AGPRs.
4060   if (Src0.isReg() && RI.isAGPR(MRI, Src0.getReg()))
4061     legalizeOpWithMove(MI, Src0Idx);
4062 
4063   if (Src1.isReg() && RI.isAGPR(MRI, Src1.getReg()))
4064     legalizeOpWithMove(MI, Src1Idx);
4065 
4066   // VOP2 src0 instructions support all operand types, so we don't need to check
4067   // their legality. If src1 is already legal, we don't need to do anything.
4068   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
4069     return;
4070 
4071   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
4072   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
4073   // select is uniform.
4074   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
4075       RI.isVGPR(MRI, Src1.getReg())) {
4076     Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4077     const DebugLoc &DL = MI.getDebugLoc();
4078     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4079         .add(Src1);
4080     Src1.ChangeToRegister(Reg, false);
4081     return;
4082   }
4083 
4084   // We do not use commuteInstruction here because it is too aggressive and will
4085   // commute if it is possible. We only want to commute here if it improves
4086   // legality. This can be called a fairly large number of times so don't waste
4087   // compile time pointlessly swapping and checking legality again.
4088   if (HasImplicitSGPR || !MI.isCommutable()) {
4089     legalizeOpWithMove(MI, Src1Idx);
4090     return;
4091   }
4092 
4093   // If src0 can be used as src1, commuting will make the operands legal.
4094   // Otherwise we have to give up and insert a move.
4095   //
4096   // TODO: Other immediate-like operand kinds could be commuted if there was a
4097   // MachineOperand::ChangeTo* for them.
4098   if ((!Src1.isImm() && !Src1.isReg()) ||
4099       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
4100     legalizeOpWithMove(MI, Src1Idx);
4101     return;
4102   }
4103 
4104   int CommutedOpc = commuteOpcode(MI);
4105   if (CommutedOpc == -1) {
4106     legalizeOpWithMove(MI, Src1Idx);
4107     return;
4108   }
4109 
4110   MI.setDesc(get(CommutedOpc));
4111 
4112   Register Src0Reg = Src0.getReg();
4113   unsigned Src0SubReg = Src0.getSubReg();
4114   bool Src0Kill = Src0.isKill();
4115 
4116   if (Src1.isImm())
4117     Src0.ChangeToImmediate(Src1.getImm());
4118   else if (Src1.isReg()) {
4119     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
4120     Src0.setSubReg(Src1.getSubReg());
4121   } else
4122     llvm_unreachable("Should only have register or immediate operands");
4123 
4124   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
4125   Src1.setSubReg(Src0SubReg);
4126   fixImplicitOperands(MI);
4127 }
4128 
4129 // Legalize VOP3 operands. All operand types are supported for any operand
4130 // but only one literal constant and only starting from GFX10.
4131 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
4132                                        MachineInstr &MI) const {
4133   unsigned Opc = MI.getOpcode();
4134 
4135   int VOP3Idx[3] = {
4136     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
4137     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
4138     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
4139   };
4140 
4141   if (Opc == AMDGPU::V_PERMLANE16_B32 ||
4142       Opc == AMDGPU::V_PERMLANEX16_B32) {
4143     // src1 and src2 must be scalar
4144     MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
4145     MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
4146     const DebugLoc &DL = MI.getDebugLoc();
4147     if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
4148       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4149       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4150         .add(Src1);
4151       Src1.ChangeToRegister(Reg, false);
4152     }
4153     if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
4154       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4155       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4156         .add(Src2);
4157       Src2.ChangeToRegister(Reg, false);
4158     }
4159   }
4160 
4161   // Find the one SGPR operand we are allowed to use.
4162   int ConstantBusLimit = ST.getConstantBusLimit(Opc);
4163   int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4164   SmallDenseSet<unsigned> SGPRsUsed;
4165   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
4166   if (SGPRReg != AMDGPU::NoRegister) {
4167     SGPRsUsed.insert(SGPRReg);
4168     --ConstantBusLimit;
4169   }
4170 
4171   for (unsigned i = 0; i < 3; ++i) {
4172     int Idx = VOP3Idx[i];
4173     if (Idx == -1)
4174       break;
4175     MachineOperand &MO = MI.getOperand(Idx);
4176 
4177     if (!MO.isReg()) {
4178       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
4179         continue;
4180 
4181       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
4182         --LiteralLimit;
4183         --ConstantBusLimit;
4184         continue;
4185       }
4186 
4187       --LiteralLimit;
4188       --ConstantBusLimit;
4189       legalizeOpWithMove(MI, Idx);
4190       continue;
4191     }
4192 
4193     if (RI.hasAGPRs(MRI.getRegClass(MO.getReg())) &&
4194         !isOperandLegal(MI, Idx, &MO)) {
4195       legalizeOpWithMove(MI, Idx);
4196       continue;
4197     }
4198 
4199     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
4200       continue; // VGPRs are legal
4201 
4202     // We can use one SGPR in each VOP3 instruction prior to GFX10
4203     // and two starting from GFX10.
4204     if (SGPRsUsed.count(MO.getReg()))
4205       continue;
4206     if (ConstantBusLimit > 0) {
4207       SGPRsUsed.insert(MO.getReg());
4208       --ConstantBusLimit;
4209       continue;
4210     }
4211 
4212     // If we make it this far, then the operand is not legal and we must
4213     // legalize it.
4214     legalizeOpWithMove(MI, Idx);
4215   }
4216 }
4217 
4218 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
4219                                          MachineRegisterInfo &MRI) const {
4220   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
4221   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
4222   Register DstReg = MRI.createVirtualRegister(SRC);
4223   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
4224 
4225   if (RI.hasAGPRs(VRC)) {
4226     VRC = RI.getEquivalentVGPRClass(VRC);
4227     Register NewSrcReg = MRI.createVirtualRegister(VRC);
4228     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4229             get(TargetOpcode::COPY), NewSrcReg)
4230         .addReg(SrcReg);
4231     SrcReg = NewSrcReg;
4232   }
4233 
4234   if (SubRegs == 1) {
4235     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4236             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
4237         .addReg(SrcReg);
4238     return DstReg;
4239   }
4240 
4241   SmallVector<unsigned, 8> SRegs;
4242   for (unsigned i = 0; i < SubRegs; ++i) {
4243     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4244     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4245             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
4246         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
4247     SRegs.push_back(SGPR);
4248   }
4249 
4250   MachineInstrBuilder MIB =
4251       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4252               get(AMDGPU::REG_SEQUENCE), DstReg);
4253   for (unsigned i = 0; i < SubRegs; ++i) {
4254     MIB.addReg(SRegs[i]);
4255     MIB.addImm(RI.getSubRegFromChannel(i));
4256   }
4257   return DstReg;
4258 }
4259 
4260 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
4261                                        MachineInstr &MI) const {
4262 
4263   // If the pointer is store in VGPRs, then we need to move them to
4264   // SGPRs using v_readfirstlane.  This is safe because we only select
4265   // loads with uniform pointers to SMRD instruction so we know the
4266   // pointer value is uniform.
4267   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
4268   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
4269     unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
4270     SBase->setReg(SGPR);
4271   }
4272   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
4273   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
4274     unsigned SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
4275     SOff->setReg(SGPR);
4276   }
4277 }
4278 
4279 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
4280                                          MachineBasicBlock::iterator I,
4281                                          const TargetRegisterClass *DstRC,
4282                                          MachineOperand &Op,
4283                                          MachineRegisterInfo &MRI,
4284                                          const DebugLoc &DL) const {
4285   Register OpReg = Op.getReg();
4286   unsigned OpSubReg = Op.getSubReg();
4287 
4288   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
4289       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
4290 
4291   // Check if operand is already the correct register class.
4292   if (DstRC == OpRC)
4293     return;
4294 
4295   Register DstReg = MRI.createVirtualRegister(DstRC);
4296   MachineInstr *Copy =
4297       BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
4298 
4299   Op.setReg(DstReg);
4300   Op.setSubReg(0);
4301 
4302   MachineInstr *Def = MRI.getVRegDef(OpReg);
4303   if (!Def)
4304     return;
4305 
4306   // Try to eliminate the copy if it is copying an immediate value.
4307   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
4308     FoldImmediate(*Copy, *Def, OpReg, &MRI);
4309 
4310   bool ImpDef = Def->isImplicitDef();
4311   while (!ImpDef && Def && Def->isCopy()) {
4312     if (Def->getOperand(1).getReg().isPhysical())
4313       break;
4314     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
4315     ImpDef = Def && Def->isImplicitDef();
4316   }
4317   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
4318       !ImpDef)
4319     Copy->addOperand(MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
4320 }
4321 
4322 // Emit the actual waterfall loop, executing the wrapped instruction for each
4323 // unique value of \p Rsrc across all lanes. In the best case we execute 1
4324 // iteration, in the worst case we execute 64 (once per lane).
4325 static void
4326 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
4327                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
4328                           const DebugLoc &DL, MachineOperand &Rsrc) {
4329   MachineFunction &MF = *OrigBB.getParent();
4330   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
4331   const SIRegisterInfo *TRI = ST.getRegisterInfo();
4332   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4333   unsigned SaveExecOpc =
4334       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
4335   unsigned XorTermOpc =
4336       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
4337   unsigned AndOpc =
4338       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
4339   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4340 
4341   MachineBasicBlock::iterator I = LoopBB.begin();
4342 
4343   Register VRsrc = Rsrc.getReg();
4344   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
4345 
4346   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
4347   Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
4348   Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
4349   Register AndCond = MRI.createVirtualRegister(BoolXExecRC);
4350   Register SRsrcSub0 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4351   Register SRsrcSub1 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4352   Register SRsrcSub2 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4353   Register SRsrcSub3 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4354   Register SRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
4355 
4356   // Beginning of the loop, read the next Rsrc variant.
4357   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub0)
4358       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub0);
4359   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub1)
4360       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub1);
4361   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub2)
4362       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub2);
4363   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub3)
4364       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub3);
4365 
4366   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc)
4367       .addReg(SRsrcSub0)
4368       .addImm(AMDGPU::sub0)
4369       .addReg(SRsrcSub1)
4370       .addImm(AMDGPU::sub1)
4371       .addReg(SRsrcSub2)
4372       .addImm(AMDGPU::sub2)
4373       .addReg(SRsrcSub3)
4374       .addImm(AMDGPU::sub3);
4375 
4376   // Update Rsrc operand to use the SGPR Rsrc.
4377   Rsrc.setReg(SRsrc);
4378   Rsrc.setIsKill(true);
4379 
4380   // Identify all lanes with identical Rsrc operands in their VGPRs.
4381   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), CondReg0)
4382       .addReg(SRsrc, 0, AMDGPU::sub0_sub1)
4383       .addReg(VRsrc, 0, AMDGPU::sub0_sub1);
4384   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), CondReg1)
4385       .addReg(SRsrc, 0, AMDGPU::sub2_sub3)
4386       .addReg(VRsrc, 0, AMDGPU::sub2_sub3);
4387   BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndCond)
4388       .addReg(CondReg0)
4389       .addReg(CondReg1);
4390 
4391   MRI.setSimpleHint(SaveExec, AndCond);
4392 
4393   // Update EXEC to matching lanes, saving original to SaveExec.
4394   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
4395       .addReg(AndCond, RegState::Kill);
4396 
4397   // The original instruction is here; we insert the terminators after it.
4398   I = LoopBB.end();
4399 
4400   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
4401   BuildMI(LoopBB, I, DL, TII.get(XorTermOpc), Exec)
4402       .addReg(Exec)
4403       .addReg(SaveExec);
4404   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(&LoopBB);
4405 }
4406 
4407 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
4408 // with SGPRs by iterating over all unique values across all lanes.
4409 static void loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
4410                               MachineOperand &Rsrc, MachineDominatorTree *MDT) {
4411   MachineBasicBlock &MBB = *MI.getParent();
4412   MachineFunction &MF = *MBB.getParent();
4413   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
4414   const SIRegisterInfo *TRI = ST.getRegisterInfo();
4415   MachineRegisterInfo &MRI = MF.getRegInfo();
4416   MachineBasicBlock::iterator I(&MI);
4417   const DebugLoc &DL = MI.getDebugLoc();
4418   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4419   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
4420   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4421 
4422   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
4423 
4424   // Save the EXEC mask
4425   BuildMI(MBB, I, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
4426 
4427   // Killed uses in the instruction we are waterfalling around will be
4428   // incorrect due to the added control-flow.
4429   for (auto &MO : MI.uses()) {
4430     if (MO.isReg() && MO.isUse()) {
4431       MRI.clearKillFlags(MO.getReg());
4432     }
4433   }
4434 
4435   // To insert the loop we need to split the block. Move everything after this
4436   // point to a new block, and insert a new empty block between the two.
4437   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
4438   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
4439   MachineFunction::iterator MBBI(MBB);
4440   ++MBBI;
4441 
4442   MF.insert(MBBI, LoopBB);
4443   MF.insert(MBBI, RemainderBB);
4444 
4445   LoopBB->addSuccessor(LoopBB);
4446   LoopBB->addSuccessor(RemainderBB);
4447 
4448   // Move MI to the LoopBB, and the remainder of the block to RemainderBB.
4449   MachineBasicBlock::iterator J = I++;
4450   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
4451   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
4452   LoopBB->splice(LoopBB->begin(), &MBB, J);
4453 
4454   MBB.addSuccessor(LoopBB);
4455 
4456   // Update dominators. We know that MBB immediately dominates LoopBB, that
4457   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
4458   // dominates all of the successors transferred to it from MBB that MBB used
4459   // to properly dominate.
4460   if (MDT) {
4461     MDT->addNewBlock(LoopBB, &MBB);
4462     MDT->addNewBlock(RemainderBB, LoopBB);
4463     for (auto &Succ : RemainderBB->successors()) {
4464       if (MDT->properlyDominates(&MBB, Succ)) {
4465         MDT->changeImmediateDominator(Succ, RemainderBB);
4466       }
4467     }
4468   }
4469 
4470   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
4471 
4472   // Restore the EXEC mask
4473   MachineBasicBlock::iterator First = RemainderBB->begin();
4474   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
4475 }
4476 
4477 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
4478 static std::tuple<unsigned, unsigned>
4479 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
4480   MachineBasicBlock &MBB = *MI.getParent();
4481   MachineFunction &MF = *MBB.getParent();
4482   MachineRegisterInfo &MRI = MF.getRegInfo();
4483 
4484   // Extract the ptr from the resource descriptor.
4485   unsigned RsrcPtr =
4486       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
4487                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
4488 
4489   // Create an empty resource descriptor
4490   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
4491   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4492   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4493   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
4494   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
4495 
4496   // Zero64 = 0
4497   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
4498       .addImm(0);
4499 
4500   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
4501   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
4502       .addImm(RsrcDataFormat & 0xFFFFFFFF);
4503 
4504   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
4505   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
4506       .addImm(RsrcDataFormat >> 32);
4507 
4508   // NewSRsrc = {Zero64, SRsrcFormat}
4509   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
4510       .addReg(Zero64)
4511       .addImm(AMDGPU::sub0_sub1)
4512       .addReg(SRsrcFormatLo)
4513       .addImm(AMDGPU::sub2)
4514       .addReg(SRsrcFormatHi)
4515       .addImm(AMDGPU::sub3);
4516 
4517   return std::make_tuple(RsrcPtr, NewSRsrc);
4518 }
4519 
4520 void SIInstrInfo::legalizeOperands(MachineInstr &MI,
4521                                    MachineDominatorTree *MDT) const {
4522   MachineFunction &MF = *MI.getParent()->getParent();
4523   MachineRegisterInfo &MRI = MF.getRegInfo();
4524 
4525   // Legalize VOP2
4526   if (isVOP2(MI) || isVOPC(MI)) {
4527     legalizeOperandsVOP2(MRI, MI);
4528     return;
4529   }
4530 
4531   // Legalize VOP3
4532   if (isVOP3(MI)) {
4533     legalizeOperandsVOP3(MRI, MI);
4534     return;
4535   }
4536 
4537   // Legalize SMRD
4538   if (isSMRD(MI)) {
4539     legalizeOperandsSMRD(MRI, MI);
4540     return;
4541   }
4542 
4543   // Legalize REG_SEQUENCE and PHI
4544   // The register class of the operands much be the same type as the register
4545   // class of the output.
4546   if (MI.getOpcode() == AMDGPU::PHI) {
4547     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
4548     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
4549       if (!MI.getOperand(i).isReg() ||
4550           !Register::isVirtualRegister(MI.getOperand(i).getReg()))
4551         continue;
4552       const TargetRegisterClass *OpRC =
4553           MRI.getRegClass(MI.getOperand(i).getReg());
4554       if (RI.hasVectorRegisters(OpRC)) {
4555         VRC = OpRC;
4556       } else {
4557         SRC = OpRC;
4558       }
4559     }
4560 
4561     // If any of the operands are VGPR registers, then they all most be
4562     // otherwise we will create illegal VGPR->SGPR copies when legalizing
4563     // them.
4564     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
4565       if (!VRC) {
4566         assert(SRC);
4567         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
4568           VRC = &AMDGPU::VReg_1RegClass;
4569         } else
4570           VRC = RI.hasAGPRs(getOpRegClass(MI, 0))
4571                     ? RI.getEquivalentAGPRClass(SRC)
4572                     : RI.getEquivalentVGPRClass(SRC);
4573       } else {
4574           VRC = RI.hasAGPRs(getOpRegClass(MI, 0))
4575                     ? RI.getEquivalentAGPRClass(VRC)
4576                     : RI.getEquivalentVGPRClass(VRC);
4577       }
4578       RC = VRC;
4579     } else {
4580       RC = SRC;
4581     }
4582 
4583     // Update all the operands so they have the same type.
4584     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
4585       MachineOperand &Op = MI.getOperand(I);
4586       if (!Op.isReg() || !Register::isVirtualRegister(Op.getReg()))
4587         continue;
4588 
4589       // MI is a PHI instruction.
4590       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
4591       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
4592 
4593       // Avoid creating no-op copies with the same src and dst reg class.  These
4594       // confuse some of the machine passes.
4595       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
4596     }
4597   }
4598 
4599   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
4600   // VGPR dest type and SGPR sources, insert copies so all operands are
4601   // VGPRs. This seems to help operand folding / the register coalescer.
4602   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
4603     MachineBasicBlock *MBB = MI.getParent();
4604     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
4605     if (RI.hasVGPRs(DstRC)) {
4606       // Update all the operands so they are VGPR register classes. These may
4607       // not be the same register class because REG_SEQUENCE supports mixing
4608       // subregister index types e.g. sub0_sub1 + sub2 + sub3
4609       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
4610         MachineOperand &Op = MI.getOperand(I);
4611         if (!Op.isReg() || !Register::isVirtualRegister(Op.getReg()))
4612           continue;
4613 
4614         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
4615         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
4616         if (VRC == OpRC)
4617           continue;
4618 
4619         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
4620         Op.setIsKill();
4621       }
4622     }
4623 
4624     return;
4625   }
4626 
4627   // Legalize INSERT_SUBREG
4628   // src0 must have the same register class as dst
4629   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
4630     Register Dst = MI.getOperand(0).getReg();
4631     Register Src0 = MI.getOperand(1).getReg();
4632     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
4633     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
4634     if (DstRC != Src0RC) {
4635       MachineBasicBlock *MBB = MI.getParent();
4636       MachineOperand &Op = MI.getOperand(1);
4637       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
4638     }
4639     return;
4640   }
4641 
4642   // Legalize SI_INIT_M0
4643   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
4644     MachineOperand &Src = MI.getOperand(0);
4645     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
4646       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
4647     return;
4648   }
4649 
4650   // Legalize MIMG and MUBUF/MTBUF for shaders.
4651   //
4652   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
4653   // scratch memory access. In both cases, the legalization never involves
4654   // conversion to the addr64 form.
4655   if (isMIMG(MI) ||
4656       (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
4657        (isMUBUF(MI) || isMTBUF(MI)))) {
4658     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
4659     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
4660       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
4661       SRsrc->setReg(SGPR);
4662     }
4663 
4664     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
4665     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
4666       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
4667       SSamp->setReg(SGPR);
4668     }
4669     return;
4670   }
4671 
4672   // Legalize MUBUF* instructions.
4673   int RsrcIdx =
4674       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
4675   if (RsrcIdx != -1) {
4676     // We have an MUBUF instruction
4677     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
4678     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
4679     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
4680                              RI.getRegClass(RsrcRC))) {
4681       // The operands are legal.
4682       // FIXME: We may need to legalize operands besided srsrc.
4683       return;
4684     }
4685 
4686     // Legalize a VGPR Rsrc.
4687     //
4688     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
4689     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
4690     // a zero-value SRsrc.
4691     //
4692     // If the instruction is _OFFSET (both idxen and offen disabled), and we
4693     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
4694     // above.
4695     //
4696     // Otherwise we are on non-ADDR64 hardware, and/or we have
4697     // idxen/offen/bothen and we fall back to a waterfall loop.
4698 
4699     MachineBasicBlock &MBB = *MI.getParent();
4700 
4701     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
4702     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
4703       // This is already an ADDR64 instruction so we need to add the pointer
4704       // extracted from the resource descriptor to the current value of VAddr.
4705       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4706       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4707       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4708 
4709       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4710       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
4711       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
4712 
4713       unsigned RsrcPtr, NewSRsrc;
4714       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
4715 
4716       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
4717       const DebugLoc &DL = MI.getDebugLoc();
4718       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e64), NewVAddrLo)
4719         .addDef(CondReg0)
4720         .addReg(RsrcPtr, 0, AMDGPU::sub0)
4721         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
4722         .addImm(0);
4723 
4724       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
4725       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
4726         .addDef(CondReg1, RegState::Dead)
4727         .addReg(RsrcPtr, 0, AMDGPU::sub1)
4728         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
4729         .addReg(CondReg0, RegState::Kill)
4730         .addImm(0);
4731 
4732       // NewVaddr = {NewVaddrHi, NewVaddrLo}
4733       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
4734           .addReg(NewVAddrLo)
4735           .addImm(AMDGPU::sub0)
4736           .addReg(NewVAddrHi)
4737           .addImm(AMDGPU::sub1);
4738 
4739       VAddr->setReg(NewVAddr);
4740       Rsrc->setReg(NewSRsrc);
4741     } else if (!VAddr && ST.hasAddr64()) {
4742       // This instructions is the _OFFSET variant, so we need to convert it to
4743       // ADDR64.
4744       assert(MBB.getParent()->getSubtarget<GCNSubtarget>().getGeneration()
4745              < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
4746              "FIXME: Need to emit flat atomics here");
4747 
4748       unsigned RsrcPtr, NewSRsrc;
4749       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
4750 
4751       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4752       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
4753       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4754       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
4755       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
4756 
4757       // Atomics rith return have have an additional tied operand and are
4758       // missing some of the special bits.
4759       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
4760       MachineInstr *Addr64;
4761 
4762       if (!VDataIn) {
4763         // Regular buffer load / store.
4764         MachineInstrBuilder MIB =
4765             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
4766                 .add(*VData)
4767                 .addReg(NewVAddr)
4768                 .addReg(NewSRsrc)
4769                 .add(*SOffset)
4770                 .add(*Offset);
4771 
4772         // Atomics do not have this operand.
4773         if (const MachineOperand *GLC =
4774                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
4775           MIB.addImm(GLC->getImm());
4776         }
4777         if (const MachineOperand *DLC =
4778                 getNamedOperand(MI, AMDGPU::OpName::dlc)) {
4779           MIB.addImm(DLC->getImm());
4780         }
4781 
4782         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
4783 
4784         if (const MachineOperand *TFE =
4785                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
4786           MIB.addImm(TFE->getImm());
4787         }
4788 
4789         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
4790 
4791         MIB.cloneMemRefs(MI);
4792         Addr64 = MIB;
4793       } else {
4794         // Atomics with return.
4795         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
4796                      .add(*VData)
4797                      .add(*VDataIn)
4798                      .addReg(NewVAddr)
4799                      .addReg(NewSRsrc)
4800                      .add(*SOffset)
4801                      .add(*Offset)
4802                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
4803                      .cloneMemRefs(MI);
4804       }
4805 
4806       MI.removeFromParent();
4807 
4808       // NewVaddr = {NewVaddrHi, NewVaddrLo}
4809       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
4810               NewVAddr)
4811           .addReg(RsrcPtr, 0, AMDGPU::sub0)
4812           .addImm(AMDGPU::sub0)
4813           .addReg(RsrcPtr, 0, AMDGPU::sub1)
4814           .addImm(AMDGPU::sub1);
4815     } else {
4816       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
4817       // to SGPRs.
4818       loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
4819     }
4820   }
4821 }
4822 
4823 void SIInstrInfo::moveToVALU(MachineInstr &TopInst,
4824                              MachineDominatorTree *MDT) const {
4825   SetVectorType Worklist;
4826   Worklist.insert(&TopInst);
4827 
4828   while (!Worklist.empty()) {
4829     MachineInstr &Inst = *Worklist.pop_back_val();
4830     MachineBasicBlock *MBB = Inst.getParent();
4831     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4832 
4833     unsigned Opcode = Inst.getOpcode();
4834     unsigned NewOpcode = getVALUOp(Inst);
4835 
4836     // Handle some special cases
4837     switch (Opcode) {
4838     default:
4839       break;
4840     case AMDGPU::S_ADD_U64_PSEUDO:
4841     case AMDGPU::S_SUB_U64_PSEUDO:
4842       splitScalar64BitAddSub(Worklist, Inst, MDT);
4843       Inst.eraseFromParent();
4844       continue;
4845     case AMDGPU::S_ADD_I32:
4846     case AMDGPU::S_SUB_I32:
4847       // FIXME: The u32 versions currently selected use the carry.
4848       if (moveScalarAddSub(Worklist, Inst, MDT))
4849         continue;
4850 
4851       // Default handling
4852       break;
4853     case AMDGPU::S_AND_B64:
4854       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
4855       Inst.eraseFromParent();
4856       continue;
4857 
4858     case AMDGPU::S_OR_B64:
4859       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
4860       Inst.eraseFromParent();
4861       continue;
4862 
4863     case AMDGPU::S_XOR_B64:
4864       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
4865       Inst.eraseFromParent();
4866       continue;
4867 
4868     case AMDGPU::S_NAND_B64:
4869       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
4870       Inst.eraseFromParent();
4871       continue;
4872 
4873     case AMDGPU::S_NOR_B64:
4874       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
4875       Inst.eraseFromParent();
4876       continue;
4877 
4878     case AMDGPU::S_XNOR_B64:
4879       if (ST.hasDLInsts())
4880         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
4881       else
4882         splitScalar64BitXnor(Worklist, Inst, MDT);
4883       Inst.eraseFromParent();
4884       continue;
4885 
4886     case AMDGPU::S_ANDN2_B64:
4887       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
4888       Inst.eraseFromParent();
4889       continue;
4890 
4891     case AMDGPU::S_ORN2_B64:
4892       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
4893       Inst.eraseFromParent();
4894       continue;
4895 
4896     case AMDGPU::S_NOT_B64:
4897       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
4898       Inst.eraseFromParent();
4899       continue;
4900 
4901     case AMDGPU::S_BCNT1_I32_B64:
4902       splitScalar64BitBCNT(Worklist, Inst);
4903       Inst.eraseFromParent();
4904       continue;
4905 
4906     case AMDGPU::S_BFE_I64:
4907       splitScalar64BitBFE(Worklist, Inst);
4908       Inst.eraseFromParent();
4909       continue;
4910 
4911     case AMDGPU::S_LSHL_B32:
4912       if (ST.hasOnlyRevVALUShifts()) {
4913         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
4914         swapOperands(Inst);
4915       }
4916       break;
4917     case AMDGPU::S_ASHR_I32:
4918       if (ST.hasOnlyRevVALUShifts()) {
4919         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
4920         swapOperands(Inst);
4921       }
4922       break;
4923     case AMDGPU::S_LSHR_B32:
4924       if (ST.hasOnlyRevVALUShifts()) {
4925         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
4926         swapOperands(Inst);
4927       }
4928       break;
4929     case AMDGPU::S_LSHL_B64:
4930       if (ST.hasOnlyRevVALUShifts()) {
4931         NewOpcode = AMDGPU::V_LSHLREV_B64;
4932         swapOperands(Inst);
4933       }
4934       break;
4935     case AMDGPU::S_ASHR_I64:
4936       if (ST.hasOnlyRevVALUShifts()) {
4937         NewOpcode = AMDGPU::V_ASHRREV_I64;
4938         swapOperands(Inst);
4939       }
4940       break;
4941     case AMDGPU::S_LSHR_B64:
4942       if (ST.hasOnlyRevVALUShifts()) {
4943         NewOpcode = AMDGPU::V_LSHRREV_B64;
4944         swapOperands(Inst);
4945       }
4946       break;
4947 
4948     case AMDGPU::S_ABS_I32:
4949       lowerScalarAbs(Worklist, Inst);
4950       Inst.eraseFromParent();
4951       continue;
4952 
4953     case AMDGPU::S_CBRANCH_SCC0:
4954     case AMDGPU::S_CBRANCH_SCC1:
4955       // Clear unused bits of vcc
4956       if (ST.isWave32())
4957         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B32),
4958                 AMDGPU::VCC_LO)
4959             .addReg(AMDGPU::EXEC_LO)
4960             .addReg(AMDGPU::VCC_LO);
4961       else
4962         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
4963                 AMDGPU::VCC)
4964             .addReg(AMDGPU::EXEC)
4965             .addReg(AMDGPU::VCC);
4966       break;
4967 
4968     case AMDGPU::S_BFE_U64:
4969     case AMDGPU::S_BFM_B64:
4970       llvm_unreachable("Moving this op to VALU not implemented");
4971 
4972     case AMDGPU::S_PACK_LL_B32_B16:
4973     case AMDGPU::S_PACK_LH_B32_B16:
4974     case AMDGPU::S_PACK_HH_B32_B16:
4975       movePackToVALU(Worklist, MRI, Inst);
4976       Inst.eraseFromParent();
4977       continue;
4978 
4979     case AMDGPU::S_XNOR_B32:
4980       lowerScalarXnor(Worklist, Inst);
4981       Inst.eraseFromParent();
4982       continue;
4983 
4984     case AMDGPU::S_NAND_B32:
4985       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
4986       Inst.eraseFromParent();
4987       continue;
4988 
4989     case AMDGPU::S_NOR_B32:
4990       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
4991       Inst.eraseFromParent();
4992       continue;
4993 
4994     case AMDGPU::S_ANDN2_B32:
4995       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
4996       Inst.eraseFromParent();
4997       continue;
4998 
4999     case AMDGPU::S_ORN2_B32:
5000       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
5001       Inst.eraseFromParent();
5002       continue;
5003     }
5004 
5005     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
5006       // We cannot move this instruction to the VALU, so we should try to
5007       // legalize its operands instead.
5008       legalizeOperands(Inst, MDT);
5009       continue;
5010     }
5011 
5012     // Use the new VALU Opcode.
5013     const MCInstrDesc &NewDesc = get(NewOpcode);
5014     Inst.setDesc(NewDesc);
5015 
5016     // Remove any references to SCC. Vector instructions can't read from it, and
5017     // We're just about to add the implicit use / defs of VCC, and we don't want
5018     // both.
5019     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
5020       MachineOperand &Op = Inst.getOperand(i);
5021       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
5022         // Only propagate through live-def of SCC.
5023         if (Op.isDef() && !Op.isDead())
5024           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
5025         Inst.RemoveOperand(i);
5026       }
5027     }
5028 
5029     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
5030       // We are converting these to a BFE, so we need to add the missing
5031       // operands for the size and offset.
5032       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
5033       Inst.addOperand(MachineOperand::CreateImm(0));
5034       Inst.addOperand(MachineOperand::CreateImm(Size));
5035 
5036     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
5037       // The VALU version adds the second operand to the result, so insert an
5038       // extra 0 operand.
5039       Inst.addOperand(MachineOperand::CreateImm(0));
5040     }
5041 
5042     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
5043     fixImplicitOperands(Inst);
5044 
5045     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
5046       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
5047       // If we need to move this to VGPRs, we need to unpack the second operand
5048       // back into the 2 separate ones for bit offset and width.
5049       assert(OffsetWidthOp.isImm() &&
5050              "Scalar BFE is only implemented for constant width and offset");
5051       uint32_t Imm = OffsetWidthOp.getImm();
5052 
5053       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
5054       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
5055       Inst.RemoveOperand(2);                     // Remove old immediate.
5056       Inst.addOperand(MachineOperand::CreateImm(Offset));
5057       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
5058     }
5059 
5060     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
5061     unsigned NewDstReg = AMDGPU::NoRegister;
5062     if (HasDst) {
5063       Register DstReg = Inst.getOperand(0).getReg();
5064       if (Register::isPhysicalRegister(DstReg))
5065         continue;
5066 
5067       // Update the destination register class.
5068       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
5069       if (!NewDstRC)
5070         continue;
5071 
5072       if (Inst.isCopy() &&
5073           Register::isVirtualRegister(Inst.getOperand(1).getReg()) &&
5074           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
5075         // Instead of creating a copy where src and dst are the same register
5076         // class, we just replace all uses of dst with src.  These kinds of
5077         // copies interfere with the heuristics MachineSink uses to decide
5078         // whether or not to split a critical edge.  Since the pass assumes
5079         // that copies will end up as machine instructions and not be
5080         // eliminated.
5081         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
5082         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
5083         MRI.clearKillFlags(Inst.getOperand(1).getReg());
5084         Inst.getOperand(0).setReg(DstReg);
5085 
5086         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
5087         // these are deleted later, but at -O0 it would leave a suspicious
5088         // looking illegal copy of an undef register.
5089         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
5090           Inst.RemoveOperand(I);
5091         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
5092         continue;
5093       }
5094 
5095       NewDstReg = MRI.createVirtualRegister(NewDstRC);
5096       MRI.replaceRegWith(DstReg, NewDstReg);
5097     }
5098 
5099     // Legalize the operands
5100     legalizeOperands(Inst, MDT);
5101 
5102     if (HasDst)
5103      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
5104   }
5105 }
5106 
5107 // Add/sub require special handling to deal with carry outs.
5108 bool SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
5109                                    MachineDominatorTree *MDT) const {
5110   if (ST.hasAddNoCarry()) {
5111     // Assume there is no user of scc since we don't select this in that case.
5112     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
5113     // is used.
5114 
5115     MachineBasicBlock &MBB = *Inst.getParent();
5116     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5117 
5118     Register OldDstReg = Inst.getOperand(0).getReg();
5119     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5120 
5121     unsigned Opc = Inst.getOpcode();
5122     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
5123 
5124     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
5125       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
5126 
5127     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
5128     Inst.RemoveOperand(3);
5129 
5130     Inst.setDesc(get(NewOpc));
5131     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
5132     Inst.addImplicitDefUseOperands(*MBB.getParent());
5133     MRI.replaceRegWith(OldDstReg, ResultReg);
5134     legalizeOperands(Inst, MDT);
5135 
5136     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5137     return true;
5138   }
5139 
5140   return false;
5141 }
5142 
5143 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
5144                                  MachineInstr &Inst) const {
5145   MachineBasicBlock &MBB = *Inst.getParent();
5146   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5147   MachineBasicBlock::iterator MII = Inst;
5148   DebugLoc DL = Inst.getDebugLoc();
5149 
5150   MachineOperand &Dest = Inst.getOperand(0);
5151   MachineOperand &Src = Inst.getOperand(1);
5152   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5153   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5154 
5155   unsigned SubOp = ST.hasAddNoCarry() ?
5156     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_I32_e32;
5157 
5158   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
5159     .addImm(0)
5160     .addReg(Src.getReg());
5161 
5162   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
5163     .addReg(Src.getReg())
5164     .addReg(TmpReg);
5165 
5166   MRI.replaceRegWith(Dest.getReg(), ResultReg);
5167   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5168 }
5169 
5170 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
5171                                   MachineInstr &Inst) const {
5172   MachineBasicBlock &MBB = *Inst.getParent();
5173   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5174   MachineBasicBlock::iterator MII = Inst;
5175   const DebugLoc &DL = Inst.getDebugLoc();
5176 
5177   MachineOperand &Dest = Inst.getOperand(0);
5178   MachineOperand &Src0 = Inst.getOperand(1);
5179   MachineOperand &Src1 = Inst.getOperand(2);
5180 
5181   if (ST.hasDLInsts()) {
5182     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5183     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
5184     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
5185 
5186     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
5187       .add(Src0)
5188       .add(Src1);
5189 
5190     MRI.replaceRegWith(Dest.getReg(), NewDest);
5191     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
5192   } else {
5193     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
5194     // invert either source and then perform the XOR. If either source is a
5195     // scalar register, then we can leave the inversion on the scalar unit to
5196     // acheive a better distrubution of scalar and vector instructions.
5197     bool Src0IsSGPR = Src0.isReg() &&
5198                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
5199     bool Src1IsSGPR = Src1.isReg() &&
5200                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
5201     MachineInstr *Xor;
5202     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5203     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5204 
5205     // Build a pair of scalar instructions and add them to the work list.
5206     // The next iteration over the work list will lower these to the vector
5207     // unit as necessary.
5208     if (Src0IsSGPR) {
5209       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
5210       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
5211       .addReg(Temp)
5212       .add(Src1);
5213     } else if (Src1IsSGPR) {
5214       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
5215       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
5216       .add(Src0)
5217       .addReg(Temp);
5218     } else {
5219       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
5220         .add(Src0)
5221         .add(Src1);
5222       MachineInstr *Not =
5223           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
5224       Worklist.insert(Not);
5225     }
5226 
5227     MRI.replaceRegWith(Dest.getReg(), NewDest);
5228 
5229     Worklist.insert(Xor);
5230 
5231     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
5232   }
5233 }
5234 
5235 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
5236                                       MachineInstr &Inst,
5237                                       unsigned Opcode) const {
5238   MachineBasicBlock &MBB = *Inst.getParent();
5239   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5240   MachineBasicBlock::iterator MII = Inst;
5241   const DebugLoc &DL = Inst.getDebugLoc();
5242 
5243   MachineOperand &Dest = Inst.getOperand(0);
5244   MachineOperand &Src0 = Inst.getOperand(1);
5245   MachineOperand &Src1 = Inst.getOperand(2);
5246 
5247   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5248   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5249 
5250   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
5251     .add(Src0)
5252     .add(Src1);
5253 
5254   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
5255     .addReg(Interm);
5256 
5257   Worklist.insert(&Op);
5258   Worklist.insert(&Not);
5259 
5260   MRI.replaceRegWith(Dest.getReg(), NewDest);
5261   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
5262 }
5263 
5264 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
5265                                      MachineInstr &Inst,
5266                                      unsigned Opcode) const {
5267   MachineBasicBlock &MBB = *Inst.getParent();
5268   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5269   MachineBasicBlock::iterator MII = Inst;
5270   const DebugLoc &DL = Inst.getDebugLoc();
5271 
5272   MachineOperand &Dest = Inst.getOperand(0);
5273   MachineOperand &Src0 = Inst.getOperand(1);
5274   MachineOperand &Src1 = Inst.getOperand(2);
5275 
5276   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5277   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5278 
5279   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
5280     .add(Src1);
5281 
5282   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
5283     .add(Src0)
5284     .addReg(Interm);
5285 
5286   Worklist.insert(&Not);
5287   Worklist.insert(&Op);
5288 
5289   MRI.replaceRegWith(Dest.getReg(), NewDest);
5290   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
5291 }
5292 
5293 void SIInstrInfo::splitScalar64BitUnaryOp(
5294     SetVectorType &Worklist, MachineInstr &Inst,
5295     unsigned Opcode) const {
5296   MachineBasicBlock &MBB = *Inst.getParent();
5297   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5298 
5299   MachineOperand &Dest = Inst.getOperand(0);
5300   MachineOperand &Src0 = Inst.getOperand(1);
5301   DebugLoc DL = Inst.getDebugLoc();
5302 
5303   MachineBasicBlock::iterator MII = Inst;
5304 
5305   const MCInstrDesc &InstDesc = get(Opcode);
5306   const TargetRegisterClass *Src0RC = Src0.isReg() ?
5307     MRI.getRegClass(Src0.getReg()) :
5308     &AMDGPU::SGPR_32RegClass;
5309 
5310   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
5311 
5312   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
5313                                                        AMDGPU::sub0, Src0SubRC);
5314 
5315   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
5316   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
5317   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
5318 
5319   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
5320   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
5321 
5322   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
5323                                                        AMDGPU::sub1, Src0SubRC);
5324 
5325   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
5326   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
5327 
5328   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
5329   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
5330     .addReg(DestSub0)
5331     .addImm(AMDGPU::sub0)
5332     .addReg(DestSub1)
5333     .addImm(AMDGPU::sub1);
5334 
5335   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
5336 
5337   Worklist.insert(&LoHalf);
5338   Worklist.insert(&HiHalf);
5339 
5340   // We don't need to legalizeOperands here because for a single operand, src0
5341   // will support any kind of input.
5342 
5343   // Move all users of this moved value.
5344   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
5345 }
5346 
5347 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
5348                                          MachineInstr &Inst,
5349                                          MachineDominatorTree *MDT) const {
5350   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
5351 
5352   MachineBasicBlock &MBB = *Inst.getParent();
5353   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5354   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5355 
5356   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5357   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5358   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5359 
5360   Register CarryReg = MRI.createVirtualRegister(CarryRC);
5361   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
5362 
5363   MachineOperand &Dest = Inst.getOperand(0);
5364   MachineOperand &Src0 = Inst.getOperand(1);
5365   MachineOperand &Src1 = Inst.getOperand(2);
5366   const DebugLoc &DL = Inst.getDebugLoc();
5367   MachineBasicBlock::iterator MII = Inst;
5368 
5369   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
5370   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
5371   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
5372   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
5373 
5374   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
5375                                                        AMDGPU::sub0, Src0SubRC);
5376   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
5377                                                        AMDGPU::sub0, Src1SubRC);
5378 
5379 
5380   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
5381                                                        AMDGPU::sub1, Src0SubRC);
5382   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
5383                                                        AMDGPU::sub1, Src1SubRC);
5384 
5385   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
5386   MachineInstr *LoHalf =
5387     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
5388     .addReg(CarryReg, RegState::Define)
5389     .add(SrcReg0Sub0)
5390     .add(SrcReg1Sub0)
5391     .addImm(0); // clamp bit
5392 
5393   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
5394   MachineInstr *HiHalf =
5395     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
5396     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
5397     .add(SrcReg0Sub1)
5398     .add(SrcReg1Sub1)
5399     .addReg(CarryReg, RegState::Kill)
5400     .addImm(0); // clamp bit
5401 
5402   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
5403     .addReg(DestSub0)
5404     .addImm(AMDGPU::sub0)
5405     .addReg(DestSub1)
5406     .addImm(AMDGPU::sub1);
5407 
5408   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
5409 
5410   // Try to legalize the operands in case we need to swap the order to keep it
5411   // valid.
5412   legalizeOperands(*LoHalf, MDT);
5413   legalizeOperands(*HiHalf, MDT);
5414 
5415   // Move all users of this moved vlaue.
5416   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
5417 }
5418 
5419 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
5420                                            MachineInstr &Inst, unsigned Opcode,
5421                                            MachineDominatorTree *MDT) const {
5422   MachineBasicBlock &MBB = *Inst.getParent();
5423   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5424 
5425   MachineOperand &Dest = Inst.getOperand(0);
5426   MachineOperand &Src0 = Inst.getOperand(1);
5427   MachineOperand &Src1 = Inst.getOperand(2);
5428   DebugLoc DL = Inst.getDebugLoc();
5429 
5430   MachineBasicBlock::iterator MII = Inst;
5431 
5432   const MCInstrDesc &InstDesc = get(Opcode);
5433   const TargetRegisterClass *Src0RC = Src0.isReg() ?
5434     MRI.getRegClass(Src0.getReg()) :
5435     &AMDGPU::SGPR_32RegClass;
5436 
5437   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
5438   const TargetRegisterClass *Src1RC = Src1.isReg() ?
5439     MRI.getRegClass(Src1.getReg()) :
5440     &AMDGPU::SGPR_32RegClass;
5441 
5442   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
5443 
5444   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
5445                                                        AMDGPU::sub0, Src0SubRC);
5446   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
5447                                                        AMDGPU::sub0, Src1SubRC);
5448   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
5449                                                        AMDGPU::sub1, Src0SubRC);
5450   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
5451                                                        AMDGPU::sub1, Src1SubRC);
5452 
5453   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
5454   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
5455   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
5456 
5457   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
5458   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
5459                               .add(SrcReg0Sub0)
5460                               .add(SrcReg1Sub0);
5461 
5462   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
5463   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
5464                               .add(SrcReg0Sub1)
5465                               .add(SrcReg1Sub1);
5466 
5467   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
5468   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
5469     .addReg(DestSub0)
5470     .addImm(AMDGPU::sub0)
5471     .addReg(DestSub1)
5472     .addImm(AMDGPU::sub1);
5473 
5474   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
5475 
5476   Worklist.insert(&LoHalf);
5477   Worklist.insert(&HiHalf);
5478 
5479   // Move all users of this moved vlaue.
5480   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
5481 }
5482 
5483 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
5484                                        MachineInstr &Inst,
5485                                        MachineDominatorTree *MDT) const {
5486   MachineBasicBlock &MBB = *Inst.getParent();
5487   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5488 
5489   MachineOperand &Dest = Inst.getOperand(0);
5490   MachineOperand &Src0 = Inst.getOperand(1);
5491   MachineOperand &Src1 = Inst.getOperand(2);
5492   const DebugLoc &DL = Inst.getDebugLoc();
5493 
5494   MachineBasicBlock::iterator MII = Inst;
5495 
5496   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
5497 
5498   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5499 
5500   MachineOperand* Op0;
5501   MachineOperand* Op1;
5502 
5503   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
5504     Op0 = &Src0;
5505     Op1 = &Src1;
5506   } else {
5507     Op0 = &Src1;
5508     Op1 = &Src0;
5509   }
5510 
5511   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
5512     .add(*Op0);
5513 
5514   Register NewDest = MRI.createVirtualRegister(DestRC);
5515 
5516   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
5517     .addReg(Interm)
5518     .add(*Op1);
5519 
5520   MRI.replaceRegWith(Dest.getReg(), NewDest);
5521 
5522   Worklist.insert(&Xor);
5523 }
5524 
5525 void SIInstrInfo::splitScalar64BitBCNT(
5526     SetVectorType &Worklist, MachineInstr &Inst) const {
5527   MachineBasicBlock &MBB = *Inst.getParent();
5528   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5529 
5530   MachineBasicBlock::iterator MII = Inst;
5531   const DebugLoc &DL = Inst.getDebugLoc();
5532 
5533   MachineOperand &Dest = Inst.getOperand(0);
5534   MachineOperand &Src = Inst.getOperand(1);
5535 
5536   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
5537   const TargetRegisterClass *SrcRC = Src.isReg() ?
5538     MRI.getRegClass(Src.getReg()) :
5539     &AMDGPU::SGPR_32RegClass;
5540 
5541   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5542   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5543 
5544   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
5545 
5546   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
5547                                                       AMDGPU::sub0, SrcSubRC);
5548   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
5549                                                       AMDGPU::sub1, SrcSubRC);
5550 
5551   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
5552 
5553   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
5554 
5555   MRI.replaceRegWith(Dest.getReg(), ResultReg);
5556 
5557   // We don't need to legalize operands here. src0 for etiher instruction can be
5558   // an SGPR, and the second input is unused or determined here.
5559   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5560 }
5561 
5562 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
5563                                       MachineInstr &Inst) const {
5564   MachineBasicBlock &MBB = *Inst.getParent();
5565   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5566   MachineBasicBlock::iterator MII = Inst;
5567   const DebugLoc &DL = Inst.getDebugLoc();
5568 
5569   MachineOperand &Dest = Inst.getOperand(0);
5570   uint32_t Imm = Inst.getOperand(2).getImm();
5571   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
5572   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
5573 
5574   (void) Offset;
5575 
5576   // Only sext_inreg cases handled.
5577   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
5578          Offset == 0 && "Not implemented");
5579 
5580   if (BitWidth < 32) {
5581     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5582     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5583     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5584 
5585     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
5586         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
5587         .addImm(0)
5588         .addImm(BitWidth);
5589 
5590     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
5591       .addImm(31)
5592       .addReg(MidRegLo);
5593 
5594     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
5595       .addReg(MidRegLo)
5596       .addImm(AMDGPU::sub0)
5597       .addReg(MidRegHi)
5598       .addImm(AMDGPU::sub1);
5599 
5600     MRI.replaceRegWith(Dest.getReg(), ResultReg);
5601     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5602     return;
5603   }
5604 
5605   MachineOperand &Src = Inst.getOperand(1);
5606   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5607   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5608 
5609   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
5610     .addImm(31)
5611     .addReg(Src.getReg(), 0, AMDGPU::sub0);
5612 
5613   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
5614     .addReg(Src.getReg(), 0, AMDGPU::sub0)
5615     .addImm(AMDGPU::sub0)
5616     .addReg(TmpReg)
5617     .addImm(AMDGPU::sub1);
5618 
5619   MRI.replaceRegWith(Dest.getReg(), ResultReg);
5620   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5621 }
5622 
5623 void SIInstrInfo::addUsersToMoveToVALUWorklist(
5624   unsigned DstReg,
5625   MachineRegisterInfo &MRI,
5626   SetVectorType &Worklist) const {
5627   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
5628          E = MRI.use_end(); I != E;) {
5629     MachineInstr &UseMI = *I->getParent();
5630 
5631     unsigned OpNo = 0;
5632 
5633     switch (UseMI.getOpcode()) {
5634     case AMDGPU::COPY:
5635     case AMDGPU::WQM:
5636     case AMDGPU::SOFT_WQM:
5637     case AMDGPU::WWM:
5638     case AMDGPU::REG_SEQUENCE:
5639     case AMDGPU::PHI:
5640     case AMDGPU::INSERT_SUBREG:
5641       break;
5642     default:
5643       OpNo = I.getOperandNo();
5644       break;
5645     }
5646 
5647     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
5648       Worklist.insert(&UseMI);
5649 
5650       do {
5651         ++I;
5652       } while (I != E && I->getParent() == &UseMI);
5653     } else {
5654       ++I;
5655     }
5656   }
5657 }
5658 
5659 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
5660                                  MachineRegisterInfo &MRI,
5661                                  MachineInstr &Inst) const {
5662   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5663   MachineBasicBlock *MBB = Inst.getParent();
5664   MachineOperand &Src0 = Inst.getOperand(1);
5665   MachineOperand &Src1 = Inst.getOperand(2);
5666   const DebugLoc &DL = Inst.getDebugLoc();
5667 
5668   switch (Inst.getOpcode()) {
5669   case AMDGPU::S_PACK_LL_B32_B16: {
5670     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5671     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5672 
5673     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
5674     // 0.
5675     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
5676       .addImm(0xffff);
5677 
5678     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
5679       .addReg(ImmReg, RegState::Kill)
5680       .add(Src0);
5681 
5682     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32), ResultReg)
5683       .add(Src1)
5684       .addImm(16)
5685       .addReg(TmpReg, RegState::Kill);
5686     break;
5687   }
5688   case AMDGPU::S_PACK_LH_B32_B16: {
5689     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5690     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
5691       .addImm(0xffff);
5692     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32), ResultReg)
5693       .addReg(ImmReg, RegState::Kill)
5694       .add(Src0)
5695       .add(Src1);
5696     break;
5697   }
5698   case AMDGPU::S_PACK_HH_B32_B16: {
5699     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5700     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5701     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
5702       .addImm(16)
5703       .add(Src0);
5704     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
5705       .addImm(0xffff0000);
5706     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32), ResultReg)
5707       .add(Src1)
5708       .addReg(ImmReg, RegState::Kill)
5709       .addReg(TmpReg, RegState::Kill);
5710     break;
5711   }
5712   default:
5713     llvm_unreachable("unhandled s_pack_* instruction");
5714   }
5715 
5716   MachineOperand &Dest = Inst.getOperand(0);
5717   MRI.replaceRegWith(Dest.getReg(), ResultReg);
5718   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5719 }
5720 
5721 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
5722                                                MachineInstr &SCCDefInst,
5723                                                SetVectorType &Worklist) const {
5724   // Ensure that def inst defines SCC, which is still live.
5725   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
5726          !Op.isDead() && Op.getParent() == &SCCDefInst);
5727   // This assumes that all the users of SCC are in the same block
5728   // as the SCC def.
5729   for (MachineInstr &MI : // Skip the def inst itself.
5730        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
5731                   SCCDefInst.getParent()->end())) {
5732     // Check if SCC is used first.
5733     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI) != -1)
5734       Worklist.insert(&MI);
5735     // Exit if we find another SCC def.
5736     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
5737       return;
5738   }
5739 }
5740 
5741 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
5742   const MachineInstr &Inst) const {
5743   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
5744 
5745   switch (Inst.getOpcode()) {
5746   // For target instructions, getOpRegClass just returns the virtual register
5747   // class associated with the operand, so we need to find an equivalent VGPR
5748   // register class in order to move the instruction to the VALU.
5749   case AMDGPU::COPY:
5750   case AMDGPU::PHI:
5751   case AMDGPU::REG_SEQUENCE:
5752   case AMDGPU::INSERT_SUBREG:
5753   case AMDGPU::WQM:
5754   case AMDGPU::SOFT_WQM:
5755   case AMDGPU::WWM: {
5756     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
5757     if (RI.hasAGPRs(SrcRC)) {
5758       if (RI.hasAGPRs(NewDstRC))
5759         return nullptr;
5760 
5761       switch (Inst.getOpcode()) {
5762       case AMDGPU::PHI:
5763       case AMDGPU::REG_SEQUENCE:
5764       case AMDGPU::INSERT_SUBREG:
5765         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
5766         break;
5767       default:
5768         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
5769       }
5770 
5771       if (!NewDstRC)
5772         return nullptr;
5773     } else {
5774       if (RI.hasVGPRs(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
5775         return nullptr;
5776 
5777       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
5778       if (!NewDstRC)
5779         return nullptr;
5780     }
5781 
5782     return NewDstRC;
5783   }
5784   default:
5785     return NewDstRC;
5786   }
5787 }
5788 
5789 // Find the one SGPR operand we are allowed to use.
5790 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
5791                                    int OpIndices[3]) const {
5792   const MCInstrDesc &Desc = MI.getDesc();
5793 
5794   // Find the one SGPR operand we are allowed to use.
5795   //
5796   // First we need to consider the instruction's operand requirements before
5797   // legalizing. Some operands are required to be SGPRs, such as implicit uses
5798   // of VCC, but we are still bound by the constant bus requirement to only use
5799   // one.
5800   //
5801   // If the operand's class is an SGPR, we can never move it.
5802 
5803   unsigned SGPRReg = findImplicitSGPRRead(MI);
5804   if (SGPRReg != AMDGPU::NoRegister)
5805     return SGPRReg;
5806 
5807   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
5808   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5809 
5810   for (unsigned i = 0; i < 3; ++i) {
5811     int Idx = OpIndices[i];
5812     if (Idx == -1)
5813       break;
5814 
5815     const MachineOperand &MO = MI.getOperand(Idx);
5816     if (!MO.isReg())
5817       continue;
5818 
5819     // Is this operand statically required to be an SGPR based on the operand
5820     // constraints?
5821     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
5822     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
5823     if (IsRequiredSGPR)
5824       return MO.getReg();
5825 
5826     // If this could be a VGPR or an SGPR, Check the dynamic register class.
5827     Register Reg = MO.getReg();
5828     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
5829     if (RI.isSGPRClass(RegRC))
5830       UsedSGPRs[i] = Reg;
5831   }
5832 
5833   // We don't have a required SGPR operand, so we have a bit more freedom in
5834   // selecting operands to move.
5835 
5836   // Try to select the most used SGPR. If an SGPR is equal to one of the
5837   // others, we choose that.
5838   //
5839   // e.g.
5840   // V_FMA_F32 v0, s0, s0, s0 -> No moves
5841   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
5842 
5843   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
5844   // prefer those.
5845 
5846   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
5847     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
5848       SGPRReg = UsedSGPRs[0];
5849   }
5850 
5851   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
5852     if (UsedSGPRs[1] == UsedSGPRs[2])
5853       SGPRReg = UsedSGPRs[1];
5854   }
5855 
5856   return SGPRReg;
5857 }
5858 
5859 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
5860                                              unsigned OperandName) const {
5861   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
5862   if (Idx == -1)
5863     return nullptr;
5864 
5865   return &MI.getOperand(Idx);
5866 }
5867 
5868 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
5869   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
5870     return (22ULL << 44) | // IMG_FORMAT_32_FLOAT
5871            (1ULL << 56) | // RESOURCE_LEVEL = 1
5872            (3ULL << 60); // OOB_SELECT = 3
5873   }
5874 
5875   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
5876   if (ST.isAmdHsaOS()) {
5877     // Set ATC = 1. GFX9 doesn't have this bit.
5878     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5879       RsrcDataFormat |= (1ULL << 56);
5880 
5881     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
5882     // BTW, it disables TC L2 and therefore decreases performance.
5883     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
5884       RsrcDataFormat |= (2ULL << 59);
5885   }
5886 
5887   return RsrcDataFormat;
5888 }
5889 
5890 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
5891   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
5892                     AMDGPU::RSRC_TID_ENABLE |
5893                     0xffffffff; // Size;
5894 
5895   // GFX9 doesn't have ELEMENT_SIZE.
5896   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
5897     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
5898     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
5899   }
5900 
5901   // IndexStride = 64 / 32.
5902   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
5903   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
5904 
5905   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
5906   // Clear them unless we want a huge stride.
5907   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5908       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
5909     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
5910 
5911   return Rsrc23;
5912 }
5913 
5914 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
5915   unsigned Opc = MI.getOpcode();
5916 
5917   return isSMRD(Opc);
5918 }
5919 
5920 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
5921   unsigned Opc = MI.getOpcode();
5922 
5923   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
5924 }
5925 
5926 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
5927                                     int &FrameIndex) const {
5928   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5929   if (!Addr || !Addr->isFI())
5930     return AMDGPU::NoRegister;
5931 
5932   assert(!MI.memoperands_empty() &&
5933          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
5934 
5935   FrameIndex = Addr->getIndex();
5936   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
5937 }
5938 
5939 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
5940                                         int &FrameIndex) const {
5941   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
5942   assert(Addr && Addr->isFI());
5943   FrameIndex = Addr->getIndex();
5944   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
5945 }
5946 
5947 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
5948                                           int &FrameIndex) const {
5949   if (!MI.mayLoad())
5950     return AMDGPU::NoRegister;
5951 
5952   if (isMUBUF(MI) || isVGPRSpill(MI))
5953     return isStackAccess(MI, FrameIndex);
5954 
5955   if (isSGPRSpill(MI))
5956     return isSGPRStackAccess(MI, FrameIndex);
5957 
5958   return AMDGPU::NoRegister;
5959 }
5960 
5961 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
5962                                          int &FrameIndex) const {
5963   if (!MI.mayStore())
5964     return AMDGPU::NoRegister;
5965 
5966   if (isMUBUF(MI) || isVGPRSpill(MI))
5967     return isStackAccess(MI, FrameIndex);
5968 
5969   if (isSGPRSpill(MI))
5970     return isSGPRStackAccess(MI, FrameIndex);
5971 
5972   return AMDGPU::NoRegister;
5973 }
5974 
5975 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
5976   unsigned Size = 0;
5977   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
5978   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
5979   while (++I != E && I->isInsideBundle()) {
5980     assert(!I->isBundle() && "No nested bundle!");
5981     Size += getInstSizeInBytes(*I);
5982   }
5983 
5984   return Size;
5985 }
5986 
5987 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
5988   unsigned Opc = MI.getOpcode();
5989   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
5990   unsigned DescSize = Desc.getSize();
5991 
5992   // If we have a definitive size, we can use it. Otherwise we need to inspect
5993   // the operands to know the size.
5994   if (isFixedSize(MI))
5995     return DescSize;
5996 
5997   // 4-byte instructions may have a 32-bit literal encoded after them. Check
5998   // operands that coud ever be literals.
5999   if (isVALU(MI) || isSALU(MI)) {
6000     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
6001     if (Src0Idx == -1)
6002       return DescSize; // No operands.
6003 
6004     if (isLiteralConstantLike(MI.getOperand(Src0Idx), Desc.OpInfo[Src0Idx]))
6005       return isVOP3(MI) ? 12 : (DescSize + 4);
6006 
6007     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
6008     if (Src1Idx == -1)
6009       return DescSize;
6010 
6011     if (isLiteralConstantLike(MI.getOperand(Src1Idx), Desc.OpInfo[Src1Idx]))
6012       return isVOP3(MI) ? 12 : (DescSize + 4);
6013 
6014     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
6015     if (Src2Idx == -1)
6016       return DescSize;
6017 
6018     if (isLiteralConstantLike(MI.getOperand(Src2Idx), Desc.OpInfo[Src2Idx]))
6019       return isVOP3(MI) ? 12 : (DescSize + 4);
6020 
6021     return DescSize;
6022   }
6023 
6024   // Check whether we have extra NSA words.
6025   if (isMIMG(MI)) {
6026     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
6027     if (VAddr0Idx < 0)
6028       return 8;
6029 
6030     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
6031     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
6032   }
6033 
6034   switch (Opc) {
6035   case TargetOpcode::IMPLICIT_DEF:
6036   case TargetOpcode::KILL:
6037   case TargetOpcode::DBG_VALUE:
6038   case TargetOpcode::EH_LABEL:
6039     return 0;
6040   case TargetOpcode::BUNDLE:
6041     return getInstBundleSize(MI);
6042   case TargetOpcode::INLINEASM:
6043   case TargetOpcode::INLINEASM_BR: {
6044     const MachineFunction *MF = MI.getParent()->getParent();
6045     const char *AsmStr = MI.getOperand(0).getSymbolName();
6046     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(),
6047                               &MF->getSubtarget());
6048   }
6049   default:
6050     return DescSize;
6051   }
6052 }
6053 
6054 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
6055   if (!isFLAT(MI))
6056     return false;
6057 
6058   if (MI.memoperands_empty())
6059     return true;
6060 
6061   for (const MachineMemOperand *MMO : MI.memoperands()) {
6062     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
6063       return true;
6064   }
6065   return false;
6066 }
6067 
6068 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
6069   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
6070 }
6071 
6072 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
6073                                             MachineBasicBlock *IfEnd) const {
6074   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
6075   assert(TI != IfEntry->end());
6076 
6077   MachineInstr *Branch = &(*TI);
6078   MachineFunction *MF = IfEntry->getParent();
6079   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
6080 
6081   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
6082     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
6083     MachineInstr *SIIF =
6084         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
6085             .add(Branch->getOperand(0))
6086             .add(Branch->getOperand(1));
6087     MachineInstr *SIEND =
6088         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
6089             .addReg(DstReg);
6090 
6091     IfEntry->erase(TI);
6092     IfEntry->insert(IfEntry->end(), SIIF);
6093     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
6094   }
6095 }
6096 
6097 void SIInstrInfo::convertNonUniformLoopRegion(
6098     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
6099   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
6100   // We expect 2 terminators, one conditional and one unconditional.
6101   assert(TI != LoopEnd->end());
6102 
6103   MachineInstr *Branch = &(*TI);
6104   MachineFunction *MF = LoopEnd->getParent();
6105   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
6106 
6107   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
6108 
6109     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
6110     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
6111     MachineInstrBuilder HeaderPHIBuilder =
6112         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
6113     for (MachineBasicBlock::pred_iterator PI = LoopEntry->pred_begin(),
6114                                           E = LoopEntry->pred_end();
6115          PI != E; ++PI) {
6116       if (*PI == LoopEnd) {
6117         HeaderPHIBuilder.addReg(BackEdgeReg);
6118       } else {
6119         MachineBasicBlock *PMBB = *PI;
6120         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
6121         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
6122                              ZeroReg, 0);
6123         HeaderPHIBuilder.addReg(ZeroReg);
6124       }
6125       HeaderPHIBuilder.addMBB(*PI);
6126     }
6127     MachineInstr *HeaderPhi = HeaderPHIBuilder;
6128     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
6129                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
6130                                   .addReg(DstReg)
6131                                   .add(Branch->getOperand(0));
6132     MachineInstr *SILOOP =
6133         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
6134             .addReg(BackEdgeReg)
6135             .addMBB(LoopEntry);
6136 
6137     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
6138     LoopEnd->erase(TI);
6139     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
6140     LoopEnd->insert(LoopEnd->end(), SILOOP);
6141   }
6142 }
6143 
6144 ArrayRef<std::pair<int, const char *>>
6145 SIInstrInfo::getSerializableTargetIndices() const {
6146   static const std::pair<int, const char *> TargetIndices[] = {
6147       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
6148       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
6149       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
6150       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
6151       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
6152   return makeArrayRef(TargetIndices);
6153 }
6154 
6155 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
6156 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
6157 ScheduleHazardRecognizer *
6158 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
6159                                             const ScheduleDAG *DAG) const {
6160   return new GCNHazardRecognizer(DAG->MF);
6161 }
6162 
6163 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
6164 /// pass.
6165 ScheduleHazardRecognizer *
6166 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
6167   return new GCNHazardRecognizer(MF);
6168 }
6169 
6170 std::pair<unsigned, unsigned>
6171 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
6172   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
6173 }
6174 
6175 ArrayRef<std::pair<unsigned, const char *>>
6176 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
6177   static const std::pair<unsigned, const char *> TargetFlags[] = {
6178     { MO_GOTPCREL, "amdgpu-gotprel" },
6179     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
6180     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
6181     { MO_REL32_LO, "amdgpu-rel32-lo" },
6182     { MO_REL32_HI, "amdgpu-rel32-hi" },
6183     { MO_ABS32_LO, "amdgpu-abs32-lo" },
6184     { MO_ABS32_HI, "amdgpu-abs32-hi" },
6185   };
6186 
6187   return makeArrayRef(TargetFlags);
6188 }
6189 
6190 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
6191   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
6192          MI.modifiesRegister(AMDGPU::EXEC, &RI);
6193 }
6194 
6195 MachineInstrBuilder
6196 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
6197                            MachineBasicBlock::iterator I,
6198                            const DebugLoc &DL,
6199                            unsigned DestReg) const {
6200   if (ST.hasAddNoCarry())
6201     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
6202 
6203   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6204   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
6205   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
6206 
6207   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_I32_e64), DestReg)
6208            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
6209 }
6210 
6211 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
6212                                                MachineBasicBlock::iterator I,
6213                                                const DebugLoc &DL,
6214                                                Register DestReg,
6215                                                RegScavenger &RS) const {
6216   if (ST.hasAddNoCarry())
6217     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
6218 
6219   // If available, prefer to use vcc.
6220   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
6221                              ? Register(RI.getVCC())
6222                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
6223 
6224   // TODO: Users need to deal with this.
6225   if (!UnusedCarry.isValid())
6226     return MachineInstrBuilder();
6227 
6228   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_I32_e64), DestReg)
6229            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
6230 }
6231 
6232 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
6233   switch (Opcode) {
6234   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
6235   case AMDGPU::SI_KILL_I1_TERMINATOR:
6236     return true;
6237   default:
6238     return false;
6239   }
6240 }
6241 
6242 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
6243   switch (Opcode) {
6244   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
6245     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
6246   case AMDGPU::SI_KILL_I1_PSEUDO:
6247     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
6248   default:
6249     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
6250   }
6251 }
6252 
6253 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
6254   MachineBasicBlock *MBB = MI.getParent();
6255   MachineFunction *MF = MBB->getParent();
6256   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
6257 
6258   if (!ST.isWave32())
6259     return;
6260 
6261   for (auto &Op : MI.implicit_operands()) {
6262     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
6263       Op.setReg(AMDGPU::VCC_LO);
6264   }
6265 }
6266 
6267 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
6268   if (!isSMRD(MI))
6269     return false;
6270 
6271   // Check that it is using a buffer resource.
6272   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
6273   if (Idx == -1) // e.g. s_memtime
6274     return false;
6275 
6276   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
6277   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
6278 }
6279 
6280 unsigned SIInstrInfo::getNumFlatOffsetBits(unsigned AddrSpace,
6281                                            bool Signed) const {
6282   if (!ST.hasFlatInstOffsets())
6283     return 0;
6284 
6285   if (ST.hasFlatSegmentOffsetBug() && AddrSpace == AMDGPUAS::FLAT_ADDRESS)
6286     return 0;
6287 
6288   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10)
6289     return Signed ? 12 : 11;
6290 
6291   return Signed ? 13 : 12;
6292 }
6293 
6294 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
6295                                     bool Signed) const {
6296   // TODO: Should 0 be special cased?
6297   if (!ST.hasFlatInstOffsets())
6298     return false;
6299 
6300   if (ST.hasFlatSegmentOffsetBug() && AddrSpace == AMDGPUAS::FLAT_ADDRESS)
6301     return false;
6302 
6303   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
6304     return (Signed && isInt<12>(Offset)) ||
6305            (!Signed && isUInt<11>(Offset));
6306   }
6307 
6308   return (Signed && isInt<13>(Offset)) ||
6309          (!Signed && isUInt<12>(Offset));
6310 }
6311 
6312 
6313 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
6314 enum SIEncodingFamily {
6315   SI = 0,
6316   VI = 1,
6317   SDWA = 2,
6318   SDWA9 = 3,
6319   GFX80 = 4,
6320   GFX9 = 5,
6321   GFX10 = 6,
6322   SDWA10 = 7
6323 };
6324 
6325 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
6326   switch (ST.getGeneration()) {
6327   default:
6328     break;
6329   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
6330   case AMDGPUSubtarget::SEA_ISLANDS:
6331     return SIEncodingFamily::SI;
6332   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
6333   case AMDGPUSubtarget::GFX9:
6334     return SIEncodingFamily::VI;
6335   case AMDGPUSubtarget::GFX10:
6336     return SIEncodingFamily::GFX10;
6337   }
6338   llvm_unreachable("Unknown subtarget generation!");
6339 }
6340 
6341 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
6342   switch(MCOp) {
6343   // These opcodes use indirect register addressing so
6344   // they need special handling by codegen (currently missing).
6345   // Therefore it is too risky to allow these opcodes
6346   // to be selected by dpp combiner or sdwa peepholer.
6347   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
6348   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
6349   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
6350   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
6351   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
6352   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
6353   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
6354   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
6355     return true;
6356   default:
6357     return false;
6358   }
6359 }
6360 
6361 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
6362   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
6363 
6364   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
6365     ST.getGeneration() == AMDGPUSubtarget::GFX9)
6366     Gen = SIEncodingFamily::GFX9;
6367 
6368   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
6369   // subtarget has UnpackedD16VMem feature.
6370   // TODO: remove this when we discard GFX80 encoding.
6371   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
6372     Gen = SIEncodingFamily::GFX80;
6373 
6374   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
6375     switch (ST.getGeneration()) {
6376     default:
6377       Gen = SIEncodingFamily::SDWA;
6378       break;
6379     case AMDGPUSubtarget::GFX9:
6380       Gen = SIEncodingFamily::SDWA9;
6381       break;
6382     case AMDGPUSubtarget::GFX10:
6383       Gen = SIEncodingFamily::SDWA10;
6384       break;
6385     }
6386   }
6387 
6388   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
6389 
6390   // -1 means that Opcode is already a native instruction.
6391   if (MCOp == -1)
6392     return Opcode;
6393 
6394   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
6395   // no encoding in the given subtarget generation.
6396   if (MCOp == (uint16_t)-1)
6397     return -1;
6398 
6399   if (isAsmOnlyOpcode(MCOp))
6400     return -1;
6401 
6402   return MCOp;
6403 }
6404 
6405 static
6406 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
6407   assert(RegOpnd.isReg());
6408   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
6409                              getRegSubRegPair(RegOpnd);
6410 }
6411 
6412 TargetInstrInfo::RegSubRegPair
6413 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
6414   assert(MI.isRegSequence());
6415   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
6416     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
6417       auto &RegOp = MI.getOperand(1 + 2 * I);
6418       return getRegOrUndef(RegOp);
6419     }
6420   return TargetInstrInfo::RegSubRegPair();
6421 }
6422 
6423 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
6424 // Following a subreg of reg:subreg isn't supported
6425 static bool followSubRegDef(MachineInstr &MI,
6426                             TargetInstrInfo::RegSubRegPair &RSR) {
6427   if (!RSR.SubReg)
6428     return false;
6429   switch (MI.getOpcode()) {
6430   default: break;
6431   case AMDGPU::REG_SEQUENCE:
6432     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
6433     return true;
6434   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
6435   case AMDGPU::INSERT_SUBREG:
6436     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
6437       // inserted the subreg we're looking for
6438       RSR = getRegOrUndef(MI.getOperand(2));
6439     else { // the subreg in the rest of the reg
6440       auto R1 = getRegOrUndef(MI.getOperand(1));
6441       if (R1.SubReg) // subreg of subreg isn't supported
6442         return false;
6443       RSR.Reg = R1.Reg;
6444     }
6445     return true;
6446   }
6447   return false;
6448 }
6449 
6450 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
6451                                      MachineRegisterInfo &MRI) {
6452   assert(MRI.isSSA());
6453   if (!Register::isVirtualRegister(P.Reg))
6454     return nullptr;
6455 
6456   auto RSR = P;
6457   auto *DefInst = MRI.getVRegDef(RSR.Reg);
6458   while (auto *MI = DefInst) {
6459     DefInst = nullptr;
6460     switch (MI->getOpcode()) {
6461     case AMDGPU::COPY:
6462     case AMDGPU::V_MOV_B32_e32: {
6463       auto &Op1 = MI->getOperand(1);
6464       if (Op1.isReg() && Register::isVirtualRegister(Op1.getReg())) {
6465         if (Op1.isUndef())
6466           return nullptr;
6467         RSR = getRegSubRegPair(Op1);
6468         DefInst = MRI.getVRegDef(RSR.Reg);
6469       }
6470       break;
6471     }
6472     default:
6473       if (followSubRegDef(*MI, RSR)) {
6474         if (!RSR.Reg)
6475           return nullptr;
6476         DefInst = MRI.getVRegDef(RSR.Reg);
6477       }
6478     }
6479     if (!DefInst)
6480       return MI;
6481   }
6482   return nullptr;
6483 }
6484 
6485 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
6486                                       Register VReg,
6487                                       const MachineInstr &DefMI,
6488                                       const MachineInstr &UseMI) {
6489   assert(MRI.isSSA() && "Must be run on SSA");
6490 
6491   auto *TRI = MRI.getTargetRegisterInfo();
6492   auto *DefBB = DefMI.getParent();
6493 
6494   // Don't bother searching between blocks, although it is possible this block
6495   // doesn't modify exec.
6496   if (UseMI.getParent() != DefBB)
6497     return true;
6498 
6499   const int MaxInstScan = 20;
6500   int NumInst = 0;
6501 
6502   // Stop scan at the use.
6503   auto E = UseMI.getIterator();
6504   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
6505     if (I->isDebugInstr())
6506       continue;
6507 
6508     if (++NumInst > MaxInstScan)
6509       return true;
6510 
6511     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
6512       return true;
6513   }
6514 
6515   return false;
6516 }
6517 
6518 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
6519                                          Register VReg,
6520                                          const MachineInstr &DefMI) {
6521   assert(MRI.isSSA() && "Must be run on SSA");
6522 
6523   auto *TRI = MRI.getTargetRegisterInfo();
6524   auto *DefBB = DefMI.getParent();
6525 
6526   const int MaxUseInstScan = 10;
6527   int NumUseInst = 0;
6528 
6529   for (auto &UseInst : MRI.use_nodbg_instructions(VReg)) {
6530     // Don't bother searching between blocks, although it is possible this block
6531     // doesn't modify exec.
6532     if (UseInst.getParent() != DefBB)
6533       return true;
6534 
6535     if (++NumUseInst > MaxUseInstScan)
6536       return true;
6537   }
6538 
6539   const int MaxInstScan = 20;
6540   int NumInst = 0;
6541 
6542   // Stop scan when we have seen all the uses.
6543   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
6544     if (I->isDebugInstr())
6545       continue;
6546 
6547     if (++NumInst > MaxInstScan)
6548       return true;
6549 
6550     if (I->readsRegister(VReg))
6551       if (--NumUseInst == 0)
6552         return false;
6553 
6554     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
6555       return true;
6556   }
6557 }
6558 
6559 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
6560     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
6561     const DebugLoc &DL, Register Src, Register Dst) const {
6562   auto Cur = MBB.begin();
6563   if (Cur != MBB.end())
6564     do {
6565       if (!Cur->isPHI() && Cur->readsRegister(Dst))
6566         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
6567       ++Cur;
6568     } while (Cur != MBB.end() && Cur != LastPHIIt);
6569 
6570   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
6571                                                    Dst);
6572 }
6573 
6574 MachineInstr *SIInstrInfo::createPHISourceCopy(
6575     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
6576     const DebugLoc &DL, Register Src, Register SrcSubReg, Register Dst) const {
6577   if (InsPt != MBB.end() &&
6578       (InsPt->getOpcode() == AMDGPU::SI_IF ||
6579        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
6580        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
6581       InsPt->definesRegister(Src)) {
6582     InsPt++;
6583     return BuildMI(MBB, InsPt, InsPt->getDebugLoc(),
6584                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
6585                                      : AMDGPU::S_MOV_B64_term),
6586                    Dst)
6587         .addReg(Src, 0, SrcSubReg)
6588         .addReg(AMDGPU::EXEC, RegState::Implicit);
6589   }
6590   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
6591                                               Dst);
6592 }
6593 
6594 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
6595 
6596 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
6597     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
6598     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
6599     VirtRegMap *VRM) const {
6600   // This is a bit of a hack (copied from AArch64). Consider this instruction:
6601   //
6602   //   %0:sreg_32 = COPY $m0
6603   //
6604   // We explicitly chose SReg_32 for the virtual register so such a copy might
6605   // be eliminated by RegisterCoalescer. However, that may not be possible, and
6606   // %0 may even spill. We can't spill $m0 normally (it would require copying to
6607   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
6608   // TargetInstrInfo::foldMemoryOperand() is going to try.
6609   //
6610   // To prevent that, constrain the %0 register class here.
6611   if (MI.isFullCopy()) {
6612     Register DstReg = MI.getOperand(0).getReg();
6613     Register SrcReg = MI.getOperand(1).getReg();
6614 
6615     if (DstReg == AMDGPU::M0 && SrcReg.isVirtual()) {
6616       MF.getRegInfo().constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
6617       return nullptr;
6618     }
6619 
6620     if (SrcReg == AMDGPU::M0 && DstReg.isVirtual()) {
6621       MF.getRegInfo().constrainRegClass(DstReg, &AMDGPU::SReg_32_XM0RegClass);
6622       return nullptr;
6623     }
6624   }
6625 
6626   return nullptr;
6627 }
6628