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