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