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