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