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