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