1 //===- SIInstrInfo.cpp - SI Instruction Information  ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// SI Implementation of TargetInstrInfo.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "SIInstrInfo.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUIntrinsicInfo.h"
18 #include "AMDGPUSubtarget.h"
19 #include "GCNHazardRecognizer.h"
20 #include "SIDefines.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "Utils/AMDGPUBaseInfo.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/MemoryLocation.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineDominators.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineInstrBundle.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/RegisterScavenging.h"
44 #include "llvm/CodeGen/ScheduleDAG.h"
45 #include "llvm/CodeGen/SelectionDAGNodes.h"
46 #include "llvm/CodeGen/TargetOpcodes.h"
47 #include "llvm/CodeGen/TargetRegisterInfo.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/DiagnosticInfo.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/InlineAsm.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/MC/MCInstrDesc.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MachineValueType.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Target/TargetMachine.h"
61 #include <cassert>
62 #include <cstdint>
63 #include <iterator>
64 #include <utility>
65 
66 using namespace llvm;
67 
68 #define GET_INSTRINFO_CTOR_DTOR
69 #include "AMDGPUGenInstrInfo.inc"
70 
71 namespace llvm {
72 namespace AMDGPU {
73 #define GET_D16ImageDimIntrinsics_IMPL
74 #define GET_ImageDimIntrinsicTable_IMPL
75 #define GET_RsrcIntrinsics_IMPL
76 #include "AMDGPUGenSearchableTables.inc"
77 }
78 }
79 
80 
81 // Must be at least 4 to be able to branch over minimum unconditional branch
82 // code. This is only for making it possible to write reasonably small tests for
83 // long branches.
84 static cl::opt<unsigned>
85 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
86                  cl::desc("Restrict range of branch instructions (DEBUG)"));
87 
88 SIInstrInfo::SIInstrInfo(const GCNSubtarget &ST)
89   : AMDGPUGenInstrInfo(AMDGPU::ADJCALLSTACKUP, AMDGPU::ADJCALLSTACKDOWN),
90     RI(ST), ST(ST) {}
91 
92 //===----------------------------------------------------------------------===//
93 // TargetInstrInfo callbacks
94 //===----------------------------------------------------------------------===//
95 
96 static unsigned getNumOperandsNoGlue(SDNode *Node) {
97   unsigned N = Node->getNumOperands();
98   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
99     --N;
100   return N;
101 }
102 
103 static SDValue findChainOperand(SDNode *Load) {
104   SDValue LastOp = Load->getOperand(getNumOperandsNoGlue(Load) - 1);
105   assert(LastOp.getValueType() == MVT::Other && "Chain missing from load node");
106   return LastOp;
107 }
108 
109 /// Returns true if both nodes have the same value for the given
110 ///        operand \p Op, or if both nodes do not have this operand.
111 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
112   unsigned Opc0 = N0->getMachineOpcode();
113   unsigned Opc1 = N1->getMachineOpcode();
114 
115   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
116   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
117 
118   if (Op0Idx == -1 && Op1Idx == -1)
119     return true;
120 
121 
122   if ((Op0Idx == -1 && Op1Idx != -1) ||
123       (Op1Idx == -1 && Op0Idx != -1))
124     return false;
125 
126   // getNamedOperandIdx returns the index for the MachineInstr's operands,
127   // which includes the result as the first operand. We are indexing into the
128   // MachineSDNode's operands, so we need to skip the result operand to get
129   // the real index.
130   --Op0Idx;
131   --Op1Idx;
132 
133   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
134 }
135 
136 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
137                                                     AliasAnalysis *AA) const {
138   // TODO: The generic check fails for VALU instructions that should be
139   // rematerializable due to implicit reads of exec. We really want all of the
140   // generic logic for this except for this.
141   switch (MI.getOpcode()) {
142   case AMDGPU::V_MOV_B32_e32:
143   case AMDGPU::V_MOV_B32_e64:
144   case AMDGPU::V_MOV_B64_PSEUDO:
145     return true;
146   default:
147     return false;
148   }
149 }
150 
151 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
152                                           int64_t &Offset0,
153                                           int64_t &Offset1) const {
154   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
155     return false;
156 
157   unsigned Opc0 = Load0->getMachineOpcode();
158   unsigned Opc1 = Load1->getMachineOpcode();
159 
160   // Make sure both are actually loads.
161   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
162     return false;
163 
164   if (isDS(Opc0) && isDS(Opc1)) {
165 
166     // FIXME: Handle this case:
167     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
168       return false;
169 
170     // Check base reg.
171     if (Load0->getOperand(1) != Load1->getOperand(1))
172       return false;
173 
174     // Check chain.
175     if (findChainOperand(Load0) != findChainOperand(Load1))
176       return false;
177 
178     // Skip read2 / write2 variants for simplicity.
179     // TODO: We should report true if the used offsets are adjacent (excluded
180     // st64 versions).
181     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
182         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
183       return false;
184 
185     Offset0 = cast<ConstantSDNode>(Load0->getOperand(2))->getZExtValue();
186     Offset1 = cast<ConstantSDNode>(Load1->getOperand(2))->getZExtValue();
187     return true;
188   }
189 
190   if (isSMRD(Opc0) && isSMRD(Opc1)) {
191     // Skip time and cache invalidation instructions.
192     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::sbase) == -1 ||
193         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::sbase) == -1)
194       return false;
195 
196     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
197 
198     // Check base reg.
199     if (Load0->getOperand(0) != Load1->getOperand(0))
200       return false;
201 
202     const ConstantSDNode *Load0Offset =
203         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
204     const ConstantSDNode *Load1Offset =
205         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
206 
207     if (!Load0Offset || !Load1Offset)
208       return false;
209 
210     // Check chain.
211     if (findChainOperand(Load0) != findChainOperand(Load1))
212       return false;
213 
214     Offset0 = Load0Offset->getZExtValue();
215     Offset1 = Load1Offset->getZExtValue();
216     return true;
217   }
218 
219   // MUBUF and MTBUF can access the same addresses.
220   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
221 
222     // MUBUF and MTBUF have vaddr at different indices.
223     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
224         findChainOperand(Load0) != findChainOperand(Load1) ||
225         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
226         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
227       return false;
228 
229     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
230     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
231 
232     if (OffIdx0 == -1 || OffIdx1 == -1)
233       return false;
234 
235     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
236     // inlcude the output in the operand list, but SDNodes don't, we need to
237     // subtract the index by one.
238     --OffIdx0;
239     --OffIdx1;
240 
241     SDValue Off0 = Load0->getOperand(OffIdx0);
242     SDValue Off1 = Load1->getOperand(OffIdx1);
243 
244     // The offset might be a FrameIndexSDNode.
245     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
246       return false;
247 
248     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
249     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
250     return true;
251   }
252 
253   return false;
254 }
255 
256 static bool isStride64(unsigned Opc) {
257   switch (Opc) {
258   case AMDGPU::DS_READ2ST64_B32:
259   case AMDGPU::DS_READ2ST64_B64:
260   case AMDGPU::DS_WRITE2ST64_B32:
261   case AMDGPU::DS_WRITE2ST64_B64:
262     return true;
263   default:
264     return false;
265   }
266 }
267 
268 bool SIInstrInfo::getMemOpBaseRegImmOfs(MachineInstr &LdSt, unsigned &BaseReg,
269                                         int64_t &Offset,
270                                         const TargetRegisterInfo *TRI) const {
271   unsigned Opc = LdSt.getOpcode();
272 
273   if (isDS(LdSt)) {
274     const MachineOperand *OffsetImm =
275         getNamedOperand(LdSt, AMDGPU::OpName::offset);
276     if (OffsetImm) {
277       // Normal, single offset LDS instruction.
278       const MachineOperand *AddrReg =
279           getNamedOperand(LdSt, AMDGPU::OpName::addr);
280 
281       BaseReg = AddrReg->getReg();
282       Offset = OffsetImm->getImm();
283       return true;
284     }
285 
286     // The 2 offset instructions use offset0 and offset1 instead. We can treat
287     // these as a load with a single offset if the 2 offsets are consecutive. We
288     // will use this for some partially aligned loads.
289     const MachineOperand *Offset0Imm =
290         getNamedOperand(LdSt, AMDGPU::OpName::offset0);
291     const MachineOperand *Offset1Imm =
292         getNamedOperand(LdSt, AMDGPU::OpName::offset1);
293 
294     uint8_t Offset0 = Offset0Imm->getImm();
295     uint8_t Offset1 = Offset1Imm->getImm();
296 
297     if (Offset1 > Offset0 && Offset1 - Offset0 == 1) {
298       // Each of these offsets is in element sized units, so we need to convert
299       // to bytes of the individual reads.
300 
301       unsigned EltSize;
302       if (LdSt.mayLoad())
303         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, 0)) / 16;
304       else {
305         assert(LdSt.mayStore());
306         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
307         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, Data0Idx)) / 8;
308       }
309 
310       if (isStride64(Opc))
311         EltSize *= 64;
312 
313       const MachineOperand *AddrReg =
314           getNamedOperand(LdSt, AMDGPU::OpName::addr);
315       BaseReg = AddrReg->getReg();
316       Offset = EltSize * Offset0;
317       return true;
318     }
319 
320     return false;
321   }
322 
323   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
324     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
325     if (SOffset && SOffset->isReg())
326       return false;
327 
328     const MachineOperand *AddrReg =
329         getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
330     if (!AddrReg)
331       return false;
332 
333     const MachineOperand *OffsetImm =
334         getNamedOperand(LdSt, AMDGPU::OpName::offset);
335     BaseReg = AddrReg->getReg();
336     Offset = OffsetImm->getImm();
337 
338     if (SOffset) // soffset can be an inline immediate.
339       Offset += SOffset->getImm();
340 
341     return true;
342   }
343 
344   if (isSMRD(LdSt)) {
345     const MachineOperand *OffsetImm =
346         getNamedOperand(LdSt, AMDGPU::OpName::offset);
347     if (!OffsetImm)
348       return false;
349 
350     const MachineOperand *SBaseReg =
351         getNamedOperand(LdSt, AMDGPU::OpName::sbase);
352     BaseReg = SBaseReg->getReg();
353     Offset = OffsetImm->getImm();
354     return true;
355   }
356 
357   if (isFLAT(LdSt)) {
358     const MachineOperand *VAddr = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
359     if (VAddr) {
360       // Can't analyze 2 offsets.
361       if (getNamedOperand(LdSt, AMDGPU::OpName::saddr))
362         return false;
363 
364       BaseReg = VAddr->getReg();
365     } else {
366       // scratch instructions have either vaddr or saddr.
367       BaseReg = getNamedOperand(LdSt, AMDGPU::OpName::saddr)->getReg();
368     }
369 
370     Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
371     return true;
372   }
373 
374   return false;
375 }
376 
377 static bool memOpsHaveSameBasePtr(const MachineInstr &MI1, unsigned BaseReg1,
378                                   const MachineInstr &MI2, unsigned BaseReg2) {
379   if (BaseReg1 == BaseReg2)
380     return true;
381 
382   if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
383     return false;
384 
385   auto MO1 = *MI1.memoperands_begin();
386   auto MO2 = *MI2.memoperands_begin();
387   if (MO1->getAddrSpace() != MO2->getAddrSpace())
388     return false;
389 
390   auto Base1 = MO1->getValue();
391   auto Base2 = MO2->getValue();
392   if (!Base1 || !Base2)
393     return false;
394   const MachineFunction &MF = *MI1.getParent()->getParent();
395   const DataLayout &DL = MF.getFunction().getParent()->getDataLayout();
396   Base1 = GetUnderlyingObject(Base1, DL);
397   Base2 = GetUnderlyingObject(Base1, DL);
398 
399   if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
400     return false;
401 
402   return Base1 == Base2;
403 }
404 
405 bool SIInstrInfo::shouldClusterMemOps(MachineInstr &FirstLdSt,
406                                       unsigned BaseReg1,
407                                       MachineInstr &SecondLdSt,
408                                       unsigned BaseReg2,
409                                       unsigned NumLoads) const {
410   if (!memOpsHaveSameBasePtr(FirstLdSt, BaseReg1, SecondLdSt, BaseReg2))
411     return false;
412 
413   const MachineOperand *FirstDst = nullptr;
414   const MachineOperand *SecondDst = nullptr;
415 
416   if ((isMUBUF(FirstLdSt) && isMUBUF(SecondLdSt)) ||
417       (isMTBUF(FirstLdSt) && isMTBUF(SecondLdSt)) ||
418       (isFLAT(FirstLdSt) && isFLAT(SecondLdSt))) {
419     const unsigned MaxGlobalLoadCluster = 6;
420     if (NumLoads > MaxGlobalLoadCluster)
421       return false;
422 
423     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdata);
424     if (!FirstDst)
425       FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
426     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdata);
427     if (!SecondDst)
428       SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
429   } else if (isSMRD(FirstLdSt) && isSMRD(SecondLdSt)) {
430     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::sdst);
431     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::sdst);
432   } else if (isDS(FirstLdSt) && isDS(SecondLdSt)) {
433     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
434     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
435   }
436 
437   if (!FirstDst || !SecondDst)
438     return false;
439 
440   // Try to limit clustering based on the total number of bytes loaded
441   // rather than the number of instructions.  This is done to help reduce
442   // register pressure.  The method used is somewhat inexact, though,
443   // because it assumes that all loads in the cluster will load the
444   // same number of bytes as FirstLdSt.
445 
446   // The unit of this value is bytes.
447   // FIXME: This needs finer tuning.
448   unsigned LoadClusterThreshold = 16;
449 
450   const MachineRegisterInfo &MRI =
451       FirstLdSt.getParent()->getParent()->getRegInfo();
452   const TargetRegisterClass *DstRC = MRI.getRegClass(FirstDst->getReg());
453 
454   return (NumLoads * (RI.getRegSizeInBits(*DstRC) / 8)) <= LoadClusterThreshold;
455 }
456 
457 // FIXME: This behaves strangely. If, for example, you have 32 load + stores,
458 // the first 16 loads will be interleaved with the stores, and the next 16 will
459 // be clustered as expected. It should really split into 2 16 store batches.
460 //
461 // Loads are clustered until this returns false, rather than trying to schedule
462 // groups of stores. This also means we have to deal with saying different
463 // address space loads should be clustered, and ones which might cause bank
464 // conflicts.
465 //
466 // This might be deprecated so it might not be worth that much effort to fix.
467 bool SIInstrInfo::shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1,
468                                           int64_t Offset0, int64_t Offset1,
469                                           unsigned NumLoads) const {
470   assert(Offset1 > Offset0 &&
471          "Second offset should be larger than first offset!");
472   // If we have less than 16 loads in a row, and the offsets are within 64
473   // bytes, then schedule together.
474 
475   // A cacheline is 64 bytes (for global memory).
476   return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
477 }
478 
479 static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB,
480                               MachineBasicBlock::iterator MI,
481                               const DebugLoc &DL, unsigned DestReg,
482                               unsigned SrcReg, bool KillSrc) {
483   MachineFunction *MF = MBB.getParent();
484   DiagnosticInfoUnsupported IllegalCopy(MF->getFunction(),
485                                         "illegal SGPR to VGPR copy",
486                                         DL, DS_Error);
487   LLVMContext &C = MF->getFunction().getContext();
488   C.diagnose(IllegalCopy);
489 
490   BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
491     .addReg(SrcReg, getKillRegState(KillSrc));
492 }
493 
494 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
495                               MachineBasicBlock::iterator MI,
496                               const DebugLoc &DL, unsigned DestReg,
497                               unsigned SrcReg, bool KillSrc) const {
498   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
499 
500   if (RC == &AMDGPU::VGPR_32RegClass) {
501     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
502            AMDGPU::SReg_32RegClass.contains(SrcReg));
503     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
504       .addReg(SrcReg, getKillRegState(KillSrc));
505     return;
506   }
507 
508   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
509       RC == &AMDGPU::SReg_32RegClass) {
510     if (SrcReg == AMDGPU::SCC) {
511       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
512           .addImm(-1)
513           .addImm(0);
514       return;
515     }
516 
517     if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
518       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
519       return;
520     }
521 
522     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
523             .addReg(SrcReg, getKillRegState(KillSrc));
524     return;
525   }
526 
527   if (RC == &AMDGPU::SReg_64RegClass) {
528     if (DestReg == AMDGPU::VCC) {
529       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
530         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
531           .addReg(SrcReg, getKillRegState(KillSrc));
532       } else {
533         // FIXME: Hack until VReg_1 removed.
534         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
535         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
536           .addImm(0)
537           .addReg(SrcReg, getKillRegState(KillSrc));
538       }
539 
540       return;
541     }
542 
543     if (!AMDGPU::SReg_64RegClass.contains(SrcReg)) {
544       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
545       return;
546     }
547 
548     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
549             .addReg(SrcReg, getKillRegState(KillSrc));
550     return;
551   }
552 
553   if (DestReg == AMDGPU::SCC) {
554     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
555     BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
556       .addReg(SrcReg, getKillRegState(KillSrc))
557       .addImm(0);
558     return;
559   }
560 
561   unsigned EltSize = 4;
562   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
563   if (RI.isSGPRClass(RC)) {
564     if (RI.getRegSizeInBits(*RC) > 32) {
565       Opcode =  AMDGPU::S_MOV_B64;
566       EltSize = 8;
567     } else {
568       Opcode = AMDGPU::S_MOV_B32;
569       EltSize = 4;
570     }
571 
572     if (!RI.isSGPRClass(RI.getPhysRegClass(SrcReg))) {
573       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
574       return;
575     }
576   }
577 
578   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
579   bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
580 
581   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
582     unsigned SubIdx;
583     if (Forward)
584       SubIdx = SubIndices[Idx];
585     else
586       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
587 
588     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
589       get(Opcode), RI.getSubReg(DestReg, SubIdx));
590 
591     Builder.addReg(RI.getSubReg(SrcReg, SubIdx));
592 
593     if (Idx == 0)
594       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
595 
596     bool UseKill = KillSrc && Idx == SubIndices.size() - 1;
597     Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
598   }
599 }
600 
601 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
602   int NewOpc;
603 
604   // Try to map original to commuted opcode
605   NewOpc = AMDGPU::getCommuteRev(Opcode);
606   if (NewOpc != -1)
607     // Check if the commuted (REV) opcode exists on the target.
608     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
609 
610   // Try to map commuted to original opcode
611   NewOpc = AMDGPU::getCommuteOrig(Opcode);
612   if (NewOpc != -1)
613     // Check if the original (non-REV) opcode exists on the target.
614     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
615 
616   return Opcode;
617 }
618 
619 void SIInstrInfo::materializeImmediate(MachineBasicBlock &MBB,
620                                        MachineBasicBlock::iterator MI,
621                                        const DebugLoc &DL, unsigned DestReg,
622                                        int64_t Value) const {
623   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
624   const TargetRegisterClass *RegClass = MRI.getRegClass(DestReg);
625   if (RegClass == &AMDGPU::SReg_32RegClass ||
626       RegClass == &AMDGPU::SGPR_32RegClass ||
627       RegClass == &AMDGPU::SReg_32_XM0RegClass ||
628       RegClass == &AMDGPU::SReg_32_XM0_XEXECRegClass) {
629     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
630       .addImm(Value);
631     return;
632   }
633 
634   if (RegClass == &AMDGPU::SReg_64RegClass ||
635       RegClass == &AMDGPU::SGPR_64RegClass ||
636       RegClass == &AMDGPU::SReg_64_XEXECRegClass) {
637     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
638       .addImm(Value);
639     return;
640   }
641 
642   if (RegClass == &AMDGPU::VGPR_32RegClass) {
643     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
644       .addImm(Value);
645     return;
646   }
647   if (RegClass == &AMDGPU::VReg_64RegClass) {
648     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO), DestReg)
649       .addImm(Value);
650     return;
651   }
652 
653   unsigned EltSize = 4;
654   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
655   if (RI.isSGPRClass(RegClass)) {
656     if (RI.getRegSizeInBits(*RegClass) > 32) {
657       Opcode =  AMDGPU::S_MOV_B64;
658       EltSize = 8;
659     } else {
660       Opcode = AMDGPU::S_MOV_B32;
661       EltSize = 4;
662     }
663   }
664 
665   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RegClass, EltSize);
666   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
667     int64_t IdxValue = Idx == 0 ? Value : 0;
668 
669     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
670       get(Opcode), RI.getSubReg(DestReg, Idx));
671     Builder.addImm(IdxValue);
672   }
673 }
674 
675 const TargetRegisterClass *
676 SIInstrInfo::getPreferredSelectRegClass(unsigned Size) const {
677   return &AMDGPU::VGPR_32RegClass;
678 }
679 
680 void SIInstrInfo::insertVectorSelect(MachineBasicBlock &MBB,
681                                      MachineBasicBlock::iterator I,
682                                      const DebugLoc &DL, unsigned DstReg,
683                                      ArrayRef<MachineOperand> Cond,
684                                      unsigned TrueReg,
685                                      unsigned FalseReg) const {
686   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
687   assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass &&
688          "Not a VGPR32 reg");
689 
690   if (Cond.size() == 1) {
691     unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
692     BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
693       .add(Cond[0]);
694     BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
695       .addReg(FalseReg)
696       .addReg(TrueReg)
697       .addReg(SReg);
698   } else if (Cond.size() == 2) {
699     assert(Cond[0].isImm() && "Cond[0] is not an immediate");
700     switch (Cond[0].getImm()) {
701     case SIInstrInfo::SCC_TRUE: {
702       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
703       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
704         .addImm(-1)
705         .addImm(0);
706       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
707         .addReg(FalseReg)
708         .addReg(TrueReg)
709         .addReg(SReg);
710       break;
711     }
712     case SIInstrInfo::SCC_FALSE: {
713       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
714       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
715         .addImm(0)
716         .addImm(-1);
717       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
718         .addReg(FalseReg)
719         .addReg(TrueReg)
720         .addReg(SReg);
721       break;
722     }
723     case SIInstrInfo::VCCNZ: {
724       MachineOperand RegOp = Cond[1];
725       RegOp.setImplicit(false);
726       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
727       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
728         .add(RegOp);
729       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
730           .addReg(FalseReg)
731           .addReg(TrueReg)
732           .addReg(SReg);
733       break;
734     }
735     case SIInstrInfo::VCCZ: {
736       MachineOperand RegOp = Cond[1];
737       RegOp.setImplicit(false);
738       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
739       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
740         .add(RegOp);
741       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
742           .addReg(TrueReg)
743           .addReg(FalseReg)
744           .addReg(SReg);
745       break;
746     }
747     case SIInstrInfo::EXECNZ: {
748       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
749       unsigned SReg2 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
750       BuildMI(MBB, I, DL, get(AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
751         .addImm(0);
752       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
753         .addImm(-1)
754         .addImm(0);
755       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
756         .addReg(FalseReg)
757         .addReg(TrueReg)
758         .addReg(SReg);
759       break;
760     }
761     case SIInstrInfo::EXECZ: {
762       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
763       unsigned SReg2 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
764       BuildMI(MBB, I, DL, get(AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
765         .addImm(0);
766       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
767         .addImm(0)
768         .addImm(-1);
769       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
770         .addReg(FalseReg)
771         .addReg(TrueReg)
772         .addReg(SReg);
773       llvm_unreachable("Unhandled branch predicate EXECZ");
774       break;
775     }
776     default:
777       llvm_unreachable("invalid branch predicate");
778     }
779   } else {
780     llvm_unreachable("Can only handle Cond size 1 or 2");
781   }
782 }
783 
784 unsigned SIInstrInfo::insertEQ(MachineBasicBlock *MBB,
785                                MachineBasicBlock::iterator I,
786                                const DebugLoc &DL,
787                                unsigned SrcReg, int Value) const {
788   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
789   unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
790   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg)
791     .addImm(Value)
792     .addReg(SrcReg);
793 
794   return Reg;
795 }
796 
797 unsigned SIInstrInfo::insertNE(MachineBasicBlock *MBB,
798                                MachineBasicBlock::iterator I,
799                                const DebugLoc &DL,
800                                unsigned SrcReg, int Value) const {
801   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
802   unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
803   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg)
804     .addImm(Value)
805     .addReg(SrcReg);
806 
807   return Reg;
808 }
809 
810 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
811 
812   if (RI.getRegSizeInBits(*DstRC) == 32) {
813     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
814   } else if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC)) {
815     return AMDGPU::S_MOV_B64;
816   } else if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC)) {
817     return  AMDGPU::V_MOV_B64_PSEUDO;
818   }
819   return AMDGPU::COPY;
820 }
821 
822 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
823   switch (Size) {
824   case 4:
825     return AMDGPU::SI_SPILL_S32_SAVE;
826   case 8:
827     return AMDGPU::SI_SPILL_S64_SAVE;
828   case 16:
829     return AMDGPU::SI_SPILL_S128_SAVE;
830   case 32:
831     return AMDGPU::SI_SPILL_S256_SAVE;
832   case 64:
833     return AMDGPU::SI_SPILL_S512_SAVE;
834   default:
835     llvm_unreachable("unknown register size");
836   }
837 }
838 
839 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
840   switch (Size) {
841   case 4:
842     return AMDGPU::SI_SPILL_V32_SAVE;
843   case 8:
844     return AMDGPU::SI_SPILL_V64_SAVE;
845   case 12:
846     return AMDGPU::SI_SPILL_V96_SAVE;
847   case 16:
848     return AMDGPU::SI_SPILL_V128_SAVE;
849   case 32:
850     return AMDGPU::SI_SPILL_V256_SAVE;
851   case 64:
852     return AMDGPU::SI_SPILL_V512_SAVE;
853   default:
854     llvm_unreachable("unknown register size");
855   }
856 }
857 
858 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
859                                       MachineBasicBlock::iterator MI,
860                                       unsigned SrcReg, bool isKill,
861                                       int FrameIndex,
862                                       const TargetRegisterClass *RC,
863                                       const TargetRegisterInfo *TRI) const {
864   MachineFunction *MF = MBB.getParent();
865   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
866   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
867   DebugLoc DL = MBB.findDebugLoc(MI);
868 
869   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
870   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
871   MachinePointerInfo PtrInfo
872     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
873   MachineMemOperand *MMO
874     = MF->getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
875                                Size, Align);
876   unsigned SpillSize = TRI->getSpillSize(*RC);
877 
878   if (RI.isSGPRClass(RC)) {
879     MFI->setHasSpilledSGPRs();
880 
881     // We are only allowed to create one new instruction when spilling
882     // registers, so we need to use pseudo instruction for spilling SGPRs.
883     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(SpillSize));
884 
885     // The SGPR spill/restore instructions only work on number sgprs, so we need
886     // to make sure we are using the correct register class.
887     if (TargetRegisterInfo::isVirtualRegister(SrcReg) && SpillSize == 4) {
888       MachineRegisterInfo &MRI = MF->getRegInfo();
889       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
890     }
891 
892     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc)
893       .addReg(SrcReg, getKillRegState(isKill)) // data
894       .addFrameIndex(FrameIndex)               // addr
895       .addMemOperand(MMO)
896       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
897       .addReg(MFI->getFrameOffsetReg(), RegState::Implicit);
898     // Add the scratch resource registers as implicit uses because we may end up
899     // needing them, and need to ensure that the reserved registers are
900     // correctly handled.
901 
902     FrameInfo.setStackID(FrameIndex, SIStackID::SGPR_SPILL);
903     if (ST.hasScalarStores()) {
904       // m0 is used for offset to scalar stores if used to spill.
905       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine | RegState::Dead);
906     }
907 
908     return;
909   }
910 
911   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
912 
913   unsigned Opcode = getVGPRSpillSaveOpcode(SpillSize);
914   MFI->setHasSpilledVGPRs();
915   BuildMI(MBB, MI, DL, get(Opcode))
916     .addReg(SrcReg, getKillRegState(isKill)) // data
917     .addFrameIndex(FrameIndex)               // addr
918     .addReg(MFI->getScratchRSrcReg())        // scratch_rsrc
919     .addReg(MFI->getFrameOffsetReg())        // scratch_offset
920     .addImm(0)                               // offset
921     .addMemOperand(MMO);
922 }
923 
924 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
925   switch (Size) {
926   case 4:
927     return AMDGPU::SI_SPILL_S32_RESTORE;
928   case 8:
929     return AMDGPU::SI_SPILL_S64_RESTORE;
930   case 16:
931     return AMDGPU::SI_SPILL_S128_RESTORE;
932   case 32:
933     return AMDGPU::SI_SPILL_S256_RESTORE;
934   case 64:
935     return AMDGPU::SI_SPILL_S512_RESTORE;
936   default:
937     llvm_unreachable("unknown register size");
938   }
939 }
940 
941 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
942   switch (Size) {
943   case 4:
944     return AMDGPU::SI_SPILL_V32_RESTORE;
945   case 8:
946     return AMDGPU::SI_SPILL_V64_RESTORE;
947   case 12:
948     return AMDGPU::SI_SPILL_V96_RESTORE;
949   case 16:
950     return AMDGPU::SI_SPILL_V128_RESTORE;
951   case 32:
952     return AMDGPU::SI_SPILL_V256_RESTORE;
953   case 64:
954     return AMDGPU::SI_SPILL_V512_RESTORE;
955   default:
956     llvm_unreachable("unknown register size");
957   }
958 }
959 
960 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
961                                        MachineBasicBlock::iterator MI,
962                                        unsigned DestReg, int FrameIndex,
963                                        const TargetRegisterClass *RC,
964                                        const TargetRegisterInfo *TRI) const {
965   MachineFunction *MF = MBB.getParent();
966   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
967   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
968   DebugLoc DL = MBB.findDebugLoc(MI);
969   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
970   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
971   unsigned SpillSize = TRI->getSpillSize(*RC);
972 
973   MachinePointerInfo PtrInfo
974     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
975 
976   MachineMemOperand *MMO = MF->getMachineMemOperand(
977     PtrInfo, MachineMemOperand::MOLoad, Size, Align);
978 
979   if (RI.isSGPRClass(RC)) {
980     // FIXME: Maybe this should not include a memoperand because it will be
981     // lowered to non-memory instructions.
982     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
983     if (TargetRegisterInfo::isVirtualRegister(DestReg) && SpillSize == 4) {
984       MachineRegisterInfo &MRI = MF->getRegInfo();
985       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0RegClass);
986     }
987 
988     FrameInfo.setStackID(FrameIndex, SIStackID::SGPR_SPILL);
989     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc, DestReg)
990       .addFrameIndex(FrameIndex) // addr
991       .addMemOperand(MMO)
992       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
993       .addReg(MFI->getFrameOffsetReg(), RegState::Implicit);
994 
995     if (ST.hasScalarStores()) {
996       // m0 is used for offset to scalar stores if used to spill.
997       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine | RegState::Dead);
998     }
999 
1000     return;
1001   }
1002 
1003   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
1004 
1005   unsigned Opcode = getVGPRSpillRestoreOpcode(SpillSize);
1006   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
1007     .addFrameIndex(FrameIndex)        // vaddr
1008     .addReg(MFI->getScratchRSrcReg()) // scratch_rsrc
1009     .addReg(MFI->getFrameOffsetReg()) // scratch_offset
1010     .addImm(0)                        // offset
1011     .addMemOperand(MMO);
1012 }
1013 
1014 /// \param @Offset Offset in bytes of the FrameIndex being spilled
1015 unsigned SIInstrInfo::calculateLDSSpillAddress(
1016     MachineBasicBlock &MBB, MachineInstr &MI, RegScavenger *RS, unsigned TmpReg,
1017     unsigned FrameOffset, unsigned Size) const {
1018   MachineFunction *MF = MBB.getParent();
1019   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1020   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
1021   DebugLoc DL = MBB.findDebugLoc(MI);
1022   unsigned WorkGroupSize = MFI->getMaxFlatWorkGroupSize();
1023   unsigned WavefrontSize = ST.getWavefrontSize();
1024 
1025   unsigned TIDReg = MFI->getTIDReg();
1026   if (!MFI->hasCalculatedTID()) {
1027     MachineBasicBlock &Entry = MBB.getParent()->front();
1028     MachineBasicBlock::iterator Insert = Entry.front();
1029     DebugLoc DL = Insert->getDebugLoc();
1030 
1031     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass,
1032                                    *MF);
1033     if (TIDReg == AMDGPU::NoRegister)
1034       return TIDReg;
1035 
1036     if (!AMDGPU::isShader(MF->getFunction().getCallingConv()) &&
1037         WorkGroupSize > WavefrontSize) {
1038       unsigned TIDIGXReg
1039         = MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
1040       unsigned TIDIGYReg
1041         = MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
1042       unsigned TIDIGZReg
1043         = MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
1044       unsigned InputPtrReg =
1045           MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1046       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
1047         if (!Entry.isLiveIn(Reg))
1048           Entry.addLiveIn(Reg);
1049       }
1050 
1051       RS->enterBasicBlock(Entry);
1052       // FIXME: Can we scavenge an SReg_64 and access the subregs?
1053       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
1054       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
1055       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
1056               .addReg(InputPtrReg)
1057               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
1058       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
1059               .addReg(InputPtrReg)
1060               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
1061 
1062       // NGROUPS.X * NGROUPS.Y
1063       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
1064               .addReg(STmp1)
1065               .addReg(STmp0);
1066       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
1067       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
1068               .addReg(STmp1)
1069               .addReg(TIDIGXReg);
1070       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
1071       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
1072               .addReg(STmp0)
1073               .addReg(TIDIGYReg)
1074               .addReg(TIDReg);
1075       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
1076       getAddNoCarry(Entry, Insert, DL, TIDReg)
1077         .addReg(TIDReg)
1078         .addReg(TIDIGZReg);
1079     } else {
1080       // Get the wave id
1081       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
1082               TIDReg)
1083               .addImm(-1)
1084               .addImm(0);
1085 
1086       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
1087               TIDReg)
1088               .addImm(-1)
1089               .addReg(TIDReg);
1090     }
1091 
1092     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
1093             TIDReg)
1094             .addImm(2)
1095             .addReg(TIDReg);
1096     MFI->setTIDReg(TIDReg);
1097   }
1098 
1099   // Add FrameIndex to LDS offset
1100   unsigned LDSOffset = MFI->getLDSSize() + (FrameOffset * WorkGroupSize);
1101   getAddNoCarry(MBB, MI, DL, TmpReg)
1102     .addImm(LDSOffset)
1103     .addReg(TIDReg);
1104 
1105   return TmpReg;
1106 }
1107 
1108 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
1109                                    MachineBasicBlock::iterator MI,
1110                                    int Count) const {
1111   DebugLoc DL = MBB.findDebugLoc(MI);
1112   while (Count > 0) {
1113     int Arg;
1114     if (Count >= 8)
1115       Arg = 7;
1116     else
1117       Arg = Count - 1;
1118     Count -= 8;
1119     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
1120             .addImm(Arg);
1121   }
1122 }
1123 
1124 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
1125                              MachineBasicBlock::iterator MI) const {
1126   insertWaitStates(MBB, MI, 1);
1127 }
1128 
1129 void SIInstrInfo::insertReturn(MachineBasicBlock &MBB) const {
1130   auto MF = MBB.getParent();
1131   SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1132 
1133   assert(Info->isEntryFunction());
1134 
1135   if (MBB.succ_empty()) {
1136     bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end();
1137     if (HasNoTerminator)
1138       BuildMI(MBB, MBB.end(), DebugLoc(),
1139               get(Info->returnsVoid() ? AMDGPU::S_ENDPGM : AMDGPU::SI_RETURN_TO_EPILOG));
1140   }
1141 }
1142 
1143 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) const {
1144   switch (MI.getOpcode()) {
1145   default: return 1; // FIXME: Do wait states equal cycles?
1146 
1147   case AMDGPU::S_NOP:
1148     return MI.getOperand(0).getImm() + 1;
1149   }
1150 }
1151 
1152 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1153   MachineBasicBlock &MBB = *MI.getParent();
1154   DebugLoc DL = MBB.findDebugLoc(MI);
1155   switch (MI.getOpcode()) {
1156   default: return TargetInstrInfo::expandPostRAPseudo(MI);
1157   case AMDGPU::S_MOV_B64_term:
1158     // This is only a terminator to get the correct spill code placement during
1159     // register allocation.
1160     MI.setDesc(get(AMDGPU::S_MOV_B64));
1161     break;
1162 
1163   case AMDGPU::S_XOR_B64_term:
1164     // This is only a terminator to get the correct spill code placement during
1165     // register allocation.
1166     MI.setDesc(get(AMDGPU::S_XOR_B64));
1167     break;
1168 
1169   case AMDGPU::S_ANDN2_B64_term:
1170     // This is only a terminator to get the correct spill code placement during
1171     // register allocation.
1172     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
1173     break;
1174 
1175   case AMDGPU::V_MOV_B64_PSEUDO: {
1176     unsigned Dst = MI.getOperand(0).getReg();
1177     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
1178     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
1179 
1180     const MachineOperand &SrcOp = MI.getOperand(1);
1181     // FIXME: Will this work for 64-bit floating point immediates?
1182     assert(!SrcOp.isFPImm());
1183     if (SrcOp.isImm()) {
1184       APInt Imm(64, SrcOp.getImm());
1185       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1186         .addImm(Imm.getLoBits(32).getZExtValue())
1187         .addReg(Dst, RegState::Implicit | RegState::Define);
1188       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1189         .addImm(Imm.getHiBits(32).getZExtValue())
1190         .addReg(Dst, RegState::Implicit | RegState::Define);
1191     } else {
1192       assert(SrcOp.isReg());
1193       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1194         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
1195         .addReg(Dst, RegState::Implicit | RegState::Define);
1196       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1197         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
1198         .addReg(Dst, RegState::Implicit | RegState::Define);
1199     }
1200     MI.eraseFromParent();
1201     break;
1202   }
1203   case AMDGPU::V_SET_INACTIVE_B32: {
1204     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1205       .addReg(AMDGPU::EXEC);
1206     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), MI.getOperand(0).getReg())
1207       .add(MI.getOperand(2));
1208     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1209       .addReg(AMDGPU::EXEC);
1210     MI.eraseFromParent();
1211     break;
1212   }
1213   case AMDGPU::V_SET_INACTIVE_B64: {
1214     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1215       .addReg(AMDGPU::EXEC);
1216     MachineInstr *Copy = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO),
1217                                  MI.getOperand(0).getReg())
1218       .add(MI.getOperand(2));
1219     expandPostRAPseudo(*Copy);
1220     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1221       .addReg(AMDGPU::EXEC);
1222     MI.eraseFromParent();
1223     break;
1224   }
1225   case AMDGPU::V_MOVRELD_B32_V1:
1226   case AMDGPU::V_MOVRELD_B32_V2:
1227   case AMDGPU::V_MOVRELD_B32_V4:
1228   case AMDGPU::V_MOVRELD_B32_V8:
1229   case AMDGPU::V_MOVRELD_B32_V16: {
1230     const MCInstrDesc &MovRelDesc = get(AMDGPU::V_MOVRELD_B32_e32);
1231     unsigned VecReg = MI.getOperand(0).getReg();
1232     bool IsUndef = MI.getOperand(1).isUndef();
1233     unsigned SubReg = AMDGPU::sub0 + MI.getOperand(3).getImm();
1234     assert(VecReg == MI.getOperand(1).getReg());
1235 
1236     MachineInstr *MovRel =
1237         BuildMI(MBB, MI, DL, MovRelDesc)
1238             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1239             .add(MI.getOperand(2))
1240             .addReg(VecReg, RegState::ImplicitDefine)
1241             .addReg(VecReg,
1242                     RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1243 
1244     const int ImpDefIdx =
1245         MovRelDesc.getNumOperands() + MovRelDesc.getNumImplicitUses();
1246     const int ImpUseIdx = ImpDefIdx + 1;
1247     MovRel->tieOperands(ImpDefIdx, ImpUseIdx);
1248 
1249     MI.eraseFromParent();
1250     break;
1251   }
1252   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
1253     MachineFunction &MF = *MBB.getParent();
1254     unsigned Reg = MI.getOperand(0).getReg();
1255     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
1256     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
1257 
1258     // Create a bundle so these instructions won't be re-ordered by the
1259     // post-RA scheduler.
1260     MIBundleBuilder Bundler(MBB, MI);
1261     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
1262 
1263     // Add 32-bit offset from this instruction to the start of the
1264     // constant data.
1265     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
1266                        .addReg(RegLo)
1267                        .add(MI.getOperand(1)));
1268 
1269     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
1270                                   .addReg(RegHi);
1271     if (MI.getOperand(2).getTargetFlags() == SIInstrInfo::MO_NONE)
1272       MIB.addImm(0);
1273     else
1274       MIB.add(MI.getOperand(2));
1275 
1276     Bundler.append(MIB);
1277     finalizeBundle(MBB, Bundler.begin());
1278 
1279     MI.eraseFromParent();
1280     break;
1281   }
1282   case AMDGPU::EXIT_WWM: {
1283     // This only gets its own opcode so that SIFixWWMLiveness can tell when WWM
1284     // is exited.
1285     MI.setDesc(get(AMDGPU::S_MOV_B64));
1286     break;
1287   }
1288   case TargetOpcode::BUNDLE: {
1289     if (!MI.mayLoad())
1290       return false;
1291 
1292     // If it is a load it must be a memory clause
1293     for (MachineBasicBlock::instr_iterator I = MI.getIterator();
1294          I->isBundledWithSucc(); ++I) {
1295       I->unbundleFromSucc();
1296       for (MachineOperand &MO : I->operands())
1297         if (MO.isReg())
1298           MO.setIsInternalRead(false);
1299     }
1300 
1301     MI.eraseFromParent();
1302     break;
1303   }
1304   }
1305   return true;
1306 }
1307 
1308 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
1309                                       MachineOperand &Src0,
1310                                       unsigned Src0OpName,
1311                                       MachineOperand &Src1,
1312                                       unsigned Src1OpName) const {
1313   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
1314   if (!Src0Mods)
1315     return false;
1316 
1317   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
1318   assert(Src1Mods &&
1319          "All commutable instructions have both src0 and src1 modifiers");
1320 
1321   int Src0ModsVal = Src0Mods->getImm();
1322   int Src1ModsVal = Src1Mods->getImm();
1323 
1324   Src1Mods->setImm(Src0ModsVal);
1325   Src0Mods->setImm(Src1ModsVal);
1326   return true;
1327 }
1328 
1329 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
1330                                              MachineOperand &RegOp,
1331                                              MachineOperand &NonRegOp) {
1332   unsigned Reg = RegOp.getReg();
1333   unsigned SubReg = RegOp.getSubReg();
1334   bool IsKill = RegOp.isKill();
1335   bool IsDead = RegOp.isDead();
1336   bool IsUndef = RegOp.isUndef();
1337   bool IsDebug = RegOp.isDebug();
1338 
1339   if (NonRegOp.isImm())
1340     RegOp.ChangeToImmediate(NonRegOp.getImm());
1341   else if (NonRegOp.isFI())
1342     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
1343   else
1344     return nullptr;
1345 
1346   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
1347   NonRegOp.setSubReg(SubReg);
1348 
1349   return &MI;
1350 }
1351 
1352 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
1353                                                   unsigned Src0Idx,
1354                                                   unsigned Src1Idx) const {
1355   assert(!NewMI && "this should never be used");
1356 
1357   unsigned Opc = MI.getOpcode();
1358   int CommutedOpcode = commuteOpcode(Opc);
1359   if (CommutedOpcode == -1)
1360     return nullptr;
1361 
1362   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
1363            static_cast<int>(Src0Idx) &&
1364          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
1365            static_cast<int>(Src1Idx) &&
1366          "inconsistency with findCommutedOpIndices");
1367 
1368   MachineOperand &Src0 = MI.getOperand(Src0Idx);
1369   MachineOperand &Src1 = MI.getOperand(Src1Idx);
1370 
1371   MachineInstr *CommutedMI = nullptr;
1372   if (Src0.isReg() && Src1.isReg()) {
1373     if (isOperandLegal(MI, Src1Idx, &Src0)) {
1374       // Be sure to copy the source modifiers to the right place.
1375       CommutedMI
1376         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
1377     }
1378 
1379   } else if (Src0.isReg() && !Src1.isReg()) {
1380     // src0 should always be able to support any operand type, so no need to
1381     // check operand legality.
1382     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
1383   } else if (!Src0.isReg() && Src1.isReg()) {
1384     if (isOperandLegal(MI, Src1Idx, &Src0))
1385       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
1386   } else {
1387     // FIXME: Found two non registers to commute. This does happen.
1388     return nullptr;
1389   }
1390 
1391   if (CommutedMI) {
1392     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
1393                         Src1, AMDGPU::OpName::src1_modifiers);
1394 
1395     CommutedMI->setDesc(get(CommutedOpcode));
1396   }
1397 
1398   return CommutedMI;
1399 }
1400 
1401 // This needs to be implemented because the source modifiers may be inserted
1402 // between the true commutable operands, and the base
1403 // TargetInstrInfo::commuteInstruction uses it.
1404 bool SIInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx0,
1405                                         unsigned &SrcOpIdx1) const {
1406   return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
1407 }
1408 
1409 bool SIInstrInfo::findCommutedOpIndices(MCInstrDesc Desc, unsigned &SrcOpIdx0,
1410                                         unsigned &SrcOpIdx1) const {
1411   if (!Desc.isCommutable())
1412     return false;
1413 
1414   unsigned Opc = Desc.getOpcode();
1415   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1416   if (Src0Idx == -1)
1417     return false;
1418 
1419   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1420   if (Src1Idx == -1)
1421     return false;
1422 
1423   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1424 }
1425 
1426 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
1427                                         int64_t BrOffset) const {
1428   // BranchRelaxation should never have to check s_setpc_b64 because its dest
1429   // block is unanalyzable.
1430   assert(BranchOp != AMDGPU::S_SETPC_B64);
1431 
1432   // Convert to dwords.
1433   BrOffset /= 4;
1434 
1435   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
1436   // from the next instruction.
1437   BrOffset -= 1;
1438 
1439   return isIntN(BranchOffsetBits, BrOffset);
1440 }
1441 
1442 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
1443   const MachineInstr &MI) const {
1444   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
1445     // This would be a difficult analysis to perform, but can always be legal so
1446     // there's no need to analyze it.
1447     return nullptr;
1448   }
1449 
1450   return MI.getOperand(0).getMBB();
1451 }
1452 
1453 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
1454                                            MachineBasicBlock &DestBB,
1455                                            const DebugLoc &DL,
1456                                            int64_t BrOffset,
1457                                            RegScavenger *RS) const {
1458   assert(RS && "RegScavenger required for long branching");
1459   assert(MBB.empty() &&
1460          "new block should be inserted for expanding unconditional branch");
1461   assert(MBB.pred_size() == 1);
1462 
1463   MachineFunction *MF = MBB.getParent();
1464   MachineRegisterInfo &MRI = MF->getRegInfo();
1465 
1466   // FIXME: Virtual register workaround for RegScavenger not working with empty
1467   // blocks.
1468   unsigned PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1469 
1470   auto I = MBB.end();
1471 
1472   // We need to compute the offset relative to the instruction immediately after
1473   // s_getpc_b64. Insert pc arithmetic code before last terminator.
1474   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
1475 
1476   // TODO: Handle > 32-bit block address.
1477   if (BrOffset >= 0) {
1478     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
1479       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1480       .addReg(PCReg, 0, AMDGPU::sub0)
1481       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_FORWARD);
1482     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
1483       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1484       .addReg(PCReg, 0, AMDGPU::sub1)
1485       .addImm(0);
1486   } else {
1487     // Backwards branch.
1488     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
1489       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1490       .addReg(PCReg, 0, AMDGPU::sub0)
1491       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_BACKWARD);
1492     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
1493       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1494       .addReg(PCReg, 0, AMDGPU::sub1)
1495       .addImm(0);
1496   }
1497 
1498   // Insert the indirect branch after the other terminator.
1499   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
1500     .addReg(PCReg);
1501 
1502   // FIXME: If spilling is necessary, this will fail because this scavenger has
1503   // no emergency stack slots. It is non-trivial to spill in this situation,
1504   // because the restore code needs to be specially placed after the
1505   // jump. BranchRelaxation then needs to be made aware of the newly inserted
1506   // block.
1507   //
1508   // If a spill is needed for the pc register pair, we need to insert a spill
1509   // restore block right before the destination block, and insert a short branch
1510   // into the old destination block's fallthrough predecessor.
1511   // e.g.:
1512   //
1513   // s_cbranch_scc0 skip_long_branch:
1514   //
1515   // long_branch_bb:
1516   //   spill s[8:9]
1517   //   s_getpc_b64 s[8:9]
1518   //   s_add_u32 s8, s8, restore_bb
1519   //   s_addc_u32 s9, s9, 0
1520   //   s_setpc_b64 s[8:9]
1521   //
1522   // skip_long_branch:
1523   //   foo;
1524   //
1525   // .....
1526   //
1527   // dest_bb_fallthrough_predecessor:
1528   // bar;
1529   // s_branch dest_bb
1530   //
1531   // restore_bb:
1532   //  restore s[8:9]
1533   //  fallthrough dest_bb
1534   ///
1535   // dest_bb:
1536   //   buzz;
1537 
1538   RS->enterBasicBlockEnd(MBB);
1539   unsigned Scav = RS->scavengeRegisterBackwards(
1540     AMDGPU::SReg_64RegClass,
1541     MachineBasicBlock::iterator(GetPC), false, 0);
1542   MRI.replaceRegWith(PCReg, Scav);
1543   MRI.clearVirtRegs();
1544   RS->setRegUsed(Scav);
1545 
1546   return 4 + 8 + 4 + 4;
1547 }
1548 
1549 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1550   switch (Cond) {
1551   case SIInstrInfo::SCC_TRUE:
1552     return AMDGPU::S_CBRANCH_SCC1;
1553   case SIInstrInfo::SCC_FALSE:
1554     return AMDGPU::S_CBRANCH_SCC0;
1555   case SIInstrInfo::VCCNZ:
1556     return AMDGPU::S_CBRANCH_VCCNZ;
1557   case SIInstrInfo::VCCZ:
1558     return AMDGPU::S_CBRANCH_VCCZ;
1559   case SIInstrInfo::EXECNZ:
1560     return AMDGPU::S_CBRANCH_EXECNZ;
1561   case SIInstrInfo::EXECZ:
1562     return AMDGPU::S_CBRANCH_EXECZ;
1563   default:
1564     llvm_unreachable("invalid branch predicate");
1565   }
1566 }
1567 
1568 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1569   switch (Opcode) {
1570   case AMDGPU::S_CBRANCH_SCC0:
1571     return SCC_FALSE;
1572   case AMDGPU::S_CBRANCH_SCC1:
1573     return SCC_TRUE;
1574   case AMDGPU::S_CBRANCH_VCCNZ:
1575     return VCCNZ;
1576   case AMDGPU::S_CBRANCH_VCCZ:
1577     return VCCZ;
1578   case AMDGPU::S_CBRANCH_EXECNZ:
1579     return EXECNZ;
1580   case AMDGPU::S_CBRANCH_EXECZ:
1581     return EXECZ;
1582   default:
1583     return INVALID_BR;
1584   }
1585 }
1586 
1587 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
1588                                     MachineBasicBlock::iterator I,
1589                                     MachineBasicBlock *&TBB,
1590                                     MachineBasicBlock *&FBB,
1591                                     SmallVectorImpl<MachineOperand> &Cond,
1592                                     bool AllowModify) const {
1593   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1594     // Unconditional Branch
1595     TBB = I->getOperand(0).getMBB();
1596     return false;
1597   }
1598 
1599   MachineBasicBlock *CondBB = nullptr;
1600 
1601   if (I->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
1602     CondBB = I->getOperand(1).getMBB();
1603     Cond.push_back(I->getOperand(0));
1604   } else {
1605     BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1606     if (Pred == INVALID_BR)
1607       return true;
1608 
1609     CondBB = I->getOperand(0).getMBB();
1610     Cond.push_back(MachineOperand::CreateImm(Pred));
1611     Cond.push_back(I->getOperand(1)); // Save the branch register.
1612   }
1613   ++I;
1614 
1615   if (I == MBB.end()) {
1616     // Conditional branch followed by fall-through.
1617     TBB = CondBB;
1618     return false;
1619   }
1620 
1621   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1622     TBB = CondBB;
1623     FBB = I->getOperand(0).getMBB();
1624     return false;
1625   }
1626 
1627   return true;
1628 }
1629 
1630 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1631                                 MachineBasicBlock *&FBB,
1632                                 SmallVectorImpl<MachineOperand> &Cond,
1633                                 bool AllowModify) const {
1634   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1635   if (I == MBB.end())
1636     return false;
1637 
1638   if (I->getOpcode() != AMDGPU::SI_MASK_BRANCH)
1639     return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
1640 
1641   ++I;
1642 
1643   // TODO: Should be able to treat as fallthrough?
1644   if (I == MBB.end())
1645     return true;
1646 
1647   if (analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify))
1648     return true;
1649 
1650   MachineBasicBlock *MaskBrDest = I->getOperand(0).getMBB();
1651 
1652   // Specifically handle the case where the conditional branch is to the same
1653   // destination as the mask branch. e.g.
1654   //
1655   // si_mask_branch BB8
1656   // s_cbranch_execz BB8
1657   // s_cbranch BB9
1658   //
1659   // This is required to understand divergent loops which may need the branches
1660   // to be relaxed.
1661   if (TBB != MaskBrDest || Cond.empty())
1662     return true;
1663 
1664   auto Pred = Cond[0].getImm();
1665   return (Pred != EXECZ && Pred != EXECNZ);
1666 }
1667 
1668 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
1669                                    int *BytesRemoved) const {
1670   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1671 
1672   unsigned Count = 0;
1673   unsigned RemovedSize = 0;
1674   while (I != MBB.end()) {
1675     MachineBasicBlock::iterator Next = std::next(I);
1676     if (I->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
1677       I = Next;
1678       continue;
1679     }
1680 
1681     RemovedSize += getInstSizeInBytes(*I);
1682     I->eraseFromParent();
1683     ++Count;
1684     I = Next;
1685   }
1686 
1687   if (BytesRemoved)
1688     *BytesRemoved = RemovedSize;
1689 
1690   return Count;
1691 }
1692 
1693 // Copy the flags onto the implicit condition register operand.
1694 static void preserveCondRegFlags(MachineOperand &CondReg,
1695                                  const MachineOperand &OrigCond) {
1696   CondReg.setIsUndef(OrigCond.isUndef());
1697   CondReg.setIsKill(OrigCond.isKill());
1698 }
1699 
1700 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
1701                                    MachineBasicBlock *TBB,
1702                                    MachineBasicBlock *FBB,
1703                                    ArrayRef<MachineOperand> Cond,
1704                                    const DebugLoc &DL,
1705                                    int *BytesAdded) const {
1706   if (!FBB && Cond.empty()) {
1707     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1708       .addMBB(TBB);
1709     if (BytesAdded)
1710       *BytesAdded = 4;
1711     return 1;
1712   }
1713 
1714   if(Cond.size() == 1 && Cond[0].isReg()) {
1715      BuildMI(&MBB, DL, get(AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO))
1716        .add(Cond[0])
1717        .addMBB(TBB);
1718      return 1;
1719   }
1720 
1721   assert(TBB && Cond[0].isImm());
1722 
1723   unsigned Opcode
1724     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
1725 
1726   if (!FBB) {
1727     Cond[1].isUndef();
1728     MachineInstr *CondBr =
1729       BuildMI(&MBB, DL, get(Opcode))
1730       .addMBB(TBB);
1731 
1732     // Copy the flags onto the implicit condition register operand.
1733     preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
1734 
1735     if (BytesAdded)
1736       *BytesAdded = 4;
1737     return 1;
1738   }
1739 
1740   assert(TBB && FBB);
1741 
1742   MachineInstr *CondBr =
1743     BuildMI(&MBB, DL, get(Opcode))
1744     .addMBB(TBB);
1745   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1746     .addMBB(FBB);
1747 
1748   MachineOperand &CondReg = CondBr->getOperand(1);
1749   CondReg.setIsUndef(Cond[1].isUndef());
1750   CondReg.setIsKill(Cond[1].isKill());
1751 
1752   if (BytesAdded)
1753       *BytesAdded = 8;
1754 
1755   return 2;
1756 }
1757 
1758 bool SIInstrInfo::reverseBranchCondition(
1759   SmallVectorImpl<MachineOperand> &Cond) const {
1760   if (Cond.size() != 2) {
1761     return true;
1762   }
1763 
1764   if (Cond[0].isImm()) {
1765     Cond[0].setImm(-Cond[0].getImm());
1766     return false;
1767   }
1768 
1769   return true;
1770 }
1771 
1772 bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
1773                                   ArrayRef<MachineOperand> Cond,
1774                                   unsigned TrueReg, unsigned FalseReg,
1775                                   int &CondCycles,
1776                                   int &TrueCycles, int &FalseCycles) const {
1777   switch (Cond[0].getImm()) {
1778   case VCCNZ:
1779   case VCCZ: {
1780     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1781     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
1782     assert(MRI.getRegClass(FalseReg) == RC);
1783 
1784     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
1785     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
1786 
1787     // Limit to equal cost for branch vs. N v_cndmask_b32s.
1788     return !RI.isSGPRClass(RC) && NumInsts <= 6;
1789   }
1790   case SCC_TRUE:
1791   case SCC_FALSE: {
1792     // FIXME: We could insert for VGPRs if we could replace the original compare
1793     // with a vector one.
1794     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1795     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
1796     assert(MRI.getRegClass(FalseReg) == RC);
1797 
1798     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
1799 
1800     // Multiples of 8 can do s_cselect_b64
1801     if (NumInsts % 2 == 0)
1802       NumInsts /= 2;
1803 
1804     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
1805     return RI.isSGPRClass(RC);
1806   }
1807   default:
1808     return false;
1809   }
1810 }
1811 
1812 void SIInstrInfo::insertSelect(MachineBasicBlock &MBB,
1813                                MachineBasicBlock::iterator I, const DebugLoc &DL,
1814                                unsigned DstReg, ArrayRef<MachineOperand> Cond,
1815                                unsigned TrueReg, unsigned FalseReg) const {
1816   BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
1817   if (Pred == VCCZ || Pred == SCC_FALSE) {
1818     Pred = static_cast<BranchPredicate>(-Pred);
1819     std::swap(TrueReg, FalseReg);
1820   }
1821 
1822   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1823   const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
1824   unsigned DstSize = RI.getRegSizeInBits(*DstRC);
1825 
1826   if (DstSize == 32) {
1827     unsigned SelOp = Pred == SCC_TRUE ?
1828       AMDGPU::S_CSELECT_B32 : AMDGPU::V_CNDMASK_B32_e32;
1829 
1830     // Instruction's operands are backwards from what is expected.
1831     MachineInstr *Select =
1832       BuildMI(MBB, I, DL, get(SelOp), DstReg)
1833       .addReg(FalseReg)
1834       .addReg(TrueReg);
1835 
1836     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1837     return;
1838   }
1839 
1840   if (DstSize == 64 && Pred == SCC_TRUE) {
1841     MachineInstr *Select =
1842       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
1843       .addReg(FalseReg)
1844       .addReg(TrueReg);
1845 
1846     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1847     return;
1848   }
1849 
1850   static const int16_t Sub0_15[] = {
1851     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
1852     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
1853     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
1854     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
1855   };
1856 
1857   static const int16_t Sub0_15_64[] = {
1858     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
1859     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
1860     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
1861     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
1862   };
1863 
1864   unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
1865   const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
1866   const int16_t *SubIndices = Sub0_15;
1867   int NElts = DstSize / 32;
1868 
1869   // 64-bit select is only avaialble for SALU.
1870   if (Pred == SCC_TRUE) {
1871     SelOp = AMDGPU::S_CSELECT_B64;
1872     EltRC = &AMDGPU::SGPR_64RegClass;
1873     SubIndices = Sub0_15_64;
1874 
1875     assert(NElts % 2 == 0);
1876     NElts /= 2;
1877   }
1878 
1879   MachineInstrBuilder MIB = BuildMI(
1880     MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
1881 
1882   I = MIB->getIterator();
1883 
1884   SmallVector<unsigned, 8> Regs;
1885   for (int Idx = 0; Idx != NElts; ++Idx) {
1886     unsigned DstElt = MRI.createVirtualRegister(EltRC);
1887     Regs.push_back(DstElt);
1888 
1889     unsigned SubIdx = SubIndices[Idx];
1890 
1891     MachineInstr *Select =
1892       BuildMI(MBB, I, DL, get(SelOp), DstElt)
1893       .addReg(FalseReg, 0, SubIdx)
1894       .addReg(TrueReg, 0, SubIdx);
1895     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1896 
1897     MIB.addReg(DstElt)
1898        .addImm(SubIdx);
1899   }
1900 }
1901 
1902 bool SIInstrInfo::isFoldableCopy(const MachineInstr &MI) const {
1903   switch (MI.getOpcode()) {
1904   case AMDGPU::V_MOV_B32_e32:
1905   case AMDGPU::V_MOV_B32_e64:
1906   case AMDGPU::V_MOV_B64_PSEUDO: {
1907     // If there are additional implicit register operands, this may be used for
1908     // register indexing so the source register operand isn't simply copied.
1909     unsigned NumOps = MI.getDesc().getNumOperands() +
1910       MI.getDesc().getNumImplicitUses();
1911 
1912     return MI.getNumOperands() == NumOps;
1913   }
1914   case AMDGPU::S_MOV_B32:
1915   case AMDGPU::S_MOV_B64:
1916   case AMDGPU::COPY:
1917     return true;
1918   default:
1919     return false;
1920   }
1921 }
1922 
1923 unsigned SIInstrInfo::getAddressSpaceForPseudoSourceKind(
1924     unsigned Kind) const {
1925   switch(Kind) {
1926   case PseudoSourceValue::Stack:
1927   case PseudoSourceValue::FixedStack:
1928     return AMDGPUAS::PRIVATE_ADDRESS;
1929   case PseudoSourceValue::ConstantPool:
1930   case PseudoSourceValue::GOT:
1931   case PseudoSourceValue::JumpTable:
1932   case PseudoSourceValue::GlobalValueCallEntry:
1933   case PseudoSourceValue::ExternalSymbolCallEntry:
1934   case PseudoSourceValue::TargetCustom:
1935     return AMDGPUAS::CONSTANT_ADDRESS;
1936   }
1937   return AMDGPUAS::FLAT_ADDRESS;
1938 }
1939 
1940 static void removeModOperands(MachineInstr &MI) {
1941   unsigned Opc = MI.getOpcode();
1942   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1943                                               AMDGPU::OpName::src0_modifiers);
1944   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1945                                               AMDGPU::OpName::src1_modifiers);
1946   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1947                                               AMDGPU::OpName::src2_modifiers);
1948 
1949   MI.RemoveOperand(Src2ModIdx);
1950   MI.RemoveOperand(Src1ModIdx);
1951   MI.RemoveOperand(Src0ModIdx);
1952 }
1953 
1954 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1955                                 unsigned Reg, MachineRegisterInfo *MRI) const {
1956   if (!MRI->hasOneNonDBGUse(Reg))
1957     return false;
1958 
1959   switch (DefMI.getOpcode()) {
1960   default:
1961     return false;
1962   case AMDGPU::S_MOV_B64:
1963     // TODO: We could fold 64-bit immediates, but this get compilicated
1964     // when there are sub-registers.
1965     return false;
1966 
1967   case AMDGPU::V_MOV_B32_e32:
1968   case AMDGPU::S_MOV_B32:
1969     break;
1970   }
1971 
1972   const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
1973   assert(ImmOp);
1974   // FIXME: We could handle FrameIndex values here.
1975   if (!ImmOp->isImm())
1976     return false;
1977 
1978   unsigned Opc = UseMI.getOpcode();
1979   if (Opc == AMDGPU::COPY) {
1980     bool isVGPRCopy = RI.isVGPR(*MRI, UseMI.getOperand(0).getReg());
1981     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
1982     UseMI.setDesc(get(NewOpc));
1983     UseMI.getOperand(1).ChangeToImmediate(ImmOp->getImm());
1984     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
1985     return true;
1986   }
1987 
1988   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64 ||
1989       Opc == AMDGPU::V_MAD_F16 || Opc == AMDGPU::V_MAC_F16_e64) {
1990     // Don't fold if we are using source or output modifiers. The new VOP2
1991     // instructions don't have them.
1992     if (hasAnyModifiersSet(UseMI))
1993       return false;
1994 
1995     // If this is a free constant, there's no reason to do this.
1996     // TODO: We could fold this here instead of letting SIFoldOperands do it
1997     // later.
1998     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
1999 
2000     // Any src operand can be used for the legality check.
2001     if (isInlineConstant(UseMI, *Src0, *ImmOp))
2002       return false;
2003 
2004     bool IsF32 = Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64;
2005     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
2006     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
2007 
2008     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
2009     // We should only expect these to be on src0 due to canonicalizations.
2010     if (Src0->isReg() && Src0->getReg() == Reg) {
2011       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
2012         return false;
2013 
2014       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
2015         return false;
2016 
2017       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
2018 
2019       const int64_t Imm = ImmOp->getImm();
2020 
2021       // FIXME: This would be a lot easier if we could return a new instruction
2022       // instead of having to modify in place.
2023 
2024       // Remove these first since they are at the end.
2025       UseMI.RemoveOperand(
2026           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2027       UseMI.RemoveOperand(
2028           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2029 
2030       unsigned Src1Reg = Src1->getReg();
2031       unsigned Src1SubReg = Src1->getSubReg();
2032       Src0->setReg(Src1Reg);
2033       Src0->setSubReg(Src1SubReg);
2034       Src0->setIsKill(Src1->isKill());
2035 
2036       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2037           Opc == AMDGPU::V_MAC_F16_e64)
2038         UseMI.untieRegOperand(
2039             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2040 
2041       Src1->ChangeToImmediate(Imm);
2042 
2043       removeModOperands(UseMI);
2044       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16));
2045 
2046       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2047       if (DeleteDef)
2048         DefMI.eraseFromParent();
2049 
2050       return true;
2051     }
2052 
2053     // Added part is the constant: Use v_madak_{f16, f32}.
2054     if (Src2->isReg() && Src2->getReg() == Reg) {
2055       // Not allowed to use constant bus for another operand.
2056       // We can however allow an inline immediate as src0.
2057       bool Src0Inlined = false;
2058       if (Src0->isReg()) {
2059         // Try to inline constant if possible.
2060         // If the Def moves immediate and the use is single
2061         // We are saving VGPR here.
2062         MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
2063         if (Def && Def->isMoveImmediate() &&
2064           isInlineConstant(Def->getOperand(1)) &&
2065           MRI->hasOneUse(Src0->getReg())) {
2066           Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2067           Src0Inlined = true;
2068         } else if ((RI.isPhysicalRegister(Src0->getReg()) &&
2069             RI.isSGPRClass(RI.getPhysRegClass(Src0->getReg()))) ||
2070             (RI.isVirtualRegister(Src0->getReg()) &&
2071             RI.isSGPRClass(MRI->getRegClass(Src0->getReg()))))
2072           return false;
2073           // VGPR is okay as Src0 - fallthrough
2074       }
2075 
2076       if (Src1->isReg() && !Src0Inlined ) {
2077         // We have one slot for inlinable constant so far - try to fill it
2078         MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
2079         if (Def && Def->isMoveImmediate() &&
2080             isInlineConstant(Def->getOperand(1)) &&
2081             MRI->hasOneUse(Src1->getReg()) &&
2082             commuteInstruction(UseMI)) {
2083             Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2084         } else if ((RI.isPhysicalRegister(Src1->getReg()) &&
2085             RI.isSGPRClass(RI.getPhysRegClass(Src1->getReg()))) ||
2086             (RI.isVirtualRegister(Src1->getReg()) &&
2087             RI.isSGPRClass(MRI->getRegClass(Src1->getReg()))))
2088           return false;
2089           // VGPR is okay as Src1 - fallthrough
2090       }
2091 
2092       const int64_t Imm = ImmOp->getImm();
2093 
2094       // FIXME: This would be a lot easier if we could return a new instruction
2095       // instead of having to modify in place.
2096 
2097       // Remove these first since they are at the end.
2098       UseMI.RemoveOperand(
2099           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2100       UseMI.RemoveOperand(
2101           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2102 
2103       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2104           Opc == AMDGPU::V_MAC_F16_e64)
2105         UseMI.untieRegOperand(
2106             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2107 
2108       // ChangingToImmediate adds Src2 back to the instruction.
2109       Src2->ChangeToImmediate(Imm);
2110 
2111       // These come before src2.
2112       removeModOperands(UseMI);
2113       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16));
2114 
2115       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2116       if (DeleteDef)
2117         DefMI.eraseFromParent();
2118 
2119       return true;
2120     }
2121   }
2122 
2123   return false;
2124 }
2125 
2126 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
2127                                 int WidthB, int OffsetB) {
2128   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
2129   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
2130   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
2131   return LowOffset + LowWidth <= HighOffset;
2132 }
2133 
2134 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr &MIa,
2135                                                MachineInstr &MIb) const {
2136   unsigned BaseReg0, BaseReg1;
2137   int64_t Offset0, Offset1;
2138 
2139   if (getMemOpBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
2140       getMemOpBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
2141 
2142     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
2143       // FIXME: Handle ds_read2 / ds_write2.
2144       return false;
2145     }
2146     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
2147     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
2148     if (BaseReg0 == BaseReg1 &&
2149         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
2150       return true;
2151     }
2152   }
2153 
2154   return false;
2155 }
2156 
2157 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr &MIa,
2158                                                   MachineInstr &MIb,
2159                                                   AliasAnalysis *AA) const {
2160   assert((MIa.mayLoad() || MIa.mayStore()) &&
2161          "MIa must load from or modify a memory location");
2162   assert((MIb.mayLoad() || MIb.mayStore()) &&
2163          "MIb must load from or modify a memory location");
2164 
2165   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
2166     return false;
2167 
2168   // XXX - Can we relax this between address spaces?
2169   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
2170     return false;
2171 
2172   if (AA && MIa.hasOneMemOperand() && MIb.hasOneMemOperand()) {
2173     const MachineMemOperand *MMOa = *MIa.memoperands_begin();
2174     const MachineMemOperand *MMOb = *MIb.memoperands_begin();
2175     if (MMOa->getValue() && MMOb->getValue()) {
2176       MemoryLocation LocA(MMOa->getValue(), MMOa->getSize(), MMOa->getAAInfo());
2177       MemoryLocation LocB(MMOb->getValue(), MMOb->getSize(), MMOb->getAAInfo());
2178       if (!AA->alias(LocA, LocB))
2179         return true;
2180     }
2181   }
2182 
2183   // TODO: Should we check the address space from the MachineMemOperand? That
2184   // would allow us to distinguish objects we know don't alias based on the
2185   // underlying address space, even if it was lowered to a different one,
2186   // e.g. private accesses lowered to use MUBUF instructions on a scratch
2187   // buffer.
2188   if (isDS(MIa)) {
2189     if (isDS(MIb))
2190       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2191 
2192     return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
2193   }
2194 
2195   if (isMUBUF(MIa) || isMTBUF(MIa)) {
2196     if (isMUBUF(MIb) || isMTBUF(MIb))
2197       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2198 
2199     return !isFLAT(MIb) && !isSMRD(MIb);
2200   }
2201 
2202   if (isSMRD(MIa)) {
2203     if (isSMRD(MIb))
2204       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2205 
2206     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
2207   }
2208 
2209   if (isFLAT(MIa)) {
2210     if (isFLAT(MIb))
2211       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2212 
2213     return false;
2214   }
2215 
2216   return false;
2217 }
2218 
2219 static int64_t getFoldableImm(const MachineOperand* MO) {
2220   if (!MO->isReg())
2221     return false;
2222   const MachineFunction *MF = MO->getParent()->getParent()->getParent();
2223   const MachineRegisterInfo &MRI = MF->getRegInfo();
2224   auto Def = MRI.getUniqueVRegDef(MO->getReg());
2225   if (Def && Def->getOpcode() == AMDGPU::V_MOV_B32_e32 &&
2226       Def->getOperand(1).isImm())
2227     return Def->getOperand(1).getImm();
2228   return AMDGPU::NoRegister;
2229 }
2230 
2231 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
2232                                                  MachineInstr &MI,
2233                                                  LiveVariables *LV) const {
2234   unsigned Opc = MI.getOpcode();
2235   bool IsF16 = false;
2236   bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F32_e64;
2237 
2238   switch (Opc) {
2239   default:
2240     return nullptr;
2241   case AMDGPU::V_MAC_F16_e64:
2242     IsF16 = true;
2243     LLVM_FALLTHROUGH;
2244   case AMDGPU::V_MAC_F32_e64:
2245   case AMDGPU::V_FMAC_F32_e64:
2246     break;
2247   case AMDGPU::V_MAC_F16_e32:
2248     IsF16 = true;
2249     LLVM_FALLTHROUGH;
2250   case AMDGPU::V_MAC_F32_e32:
2251   case AMDGPU::V_FMAC_F32_e32: {
2252     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
2253                                              AMDGPU::OpName::src0);
2254     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
2255     if (!Src0->isReg() && !Src0->isImm())
2256       return nullptr;
2257 
2258     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
2259       return nullptr;
2260 
2261     break;
2262   }
2263   }
2264 
2265   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
2266   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
2267   const MachineOperand *Src0Mods =
2268     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2269   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2270   const MachineOperand *Src1Mods =
2271     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2272   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2273   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
2274   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
2275 
2276   if (!IsFMA && !Src0Mods && !Src1Mods && !Clamp && !Omod &&
2277       // If we have an SGPR input, we will violate the constant bus restriction.
2278       (!Src0->isReg() || !RI.isSGPRReg(MBB->getParent()->getRegInfo(), Src0->getReg()))) {
2279     if (auto Imm = getFoldableImm(Src2)) {
2280       return BuildMI(*MBB, MI, MI.getDebugLoc(),
2281                      get(IsF16 ? AMDGPU::V_MADAK_F16 : AMDGPU::V_MADAK_F32))
2282                .add(*Dst)
2283                .add(*Src0)
2284                .add(*Src1)
2285                .addImm(Imm);
2286     }
2287     if (auto Imm = getFoldableImm(Src1)) {
2288       return BuildMI(*MBB, MI, MI.getDebugLoc(),
2289                      get(IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32))
2290                .add(*Dst)
2291                .add(*Src0)
2292                .addImm(Imm)
2293                .add(*Src2);
2294     }
2295     if (auto Imm = getFoldableImm(Src0)) {
2296       if (isOperandLegal(MI, AMDGPU::getNamedOperandIdx(AMDGPU::V_MADMK_F32,
2297                            AMDGPU::OpName::src0), Src1))
2298         return BuildMI(*MBB, MI, MI.getDebugLoc(),
2299                        get(IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32))
2300                  .add(*Dst)
2301                  .add(*Src1)
2302                  .addImm(Imm)
2303                  .add(*Src2);
2304     }
2305   }
2306 
2307   assert((!IsFMA || !IsF16) && "fmac only expected with f32");
2308   unsigned NewOpc = IsFMA ? AMDGPU::V_FMA_F32 :
2309     (IsF16 ? AMDGPU::V_MAD_F16 : AMDGPU::V_MAD_F32);
2310   return BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
2311       .add(*Dst)
2312       .addImm(Src0Mods ? Src0Mods->getImm() : 0)
2313       .add(*Src0)
2314       .addImm(Src1Mods ? Src1Mods->getImm() : 0)
2315       .add(*Src1)
2316       .addImm(0) // Src mods
2317       .add(*Src2)
2318       .addImm(Clamp ? Clamp->getImm() : 0)
2319       .addImm(Omod ? Omod->getImm() : 0);
2320 }
2321 
2322 // It's not generally safe to move VALU instructions across these since it will
2323 // start using the register as a base index rather than directly.
2324 // XXX - Why isn't hasSideEffects sufficient for these?
2325 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
2326   switch (MI.getOpcode()) {
2327   case AMDGPU::S_SET_GPR_IDX_ON:
2328   case AMDGPU::S_SET_GPR_IDX_MODE:
2329   case AMDGPU::S_SET_GPR_IDX_OFF:
2330     return true;
2331   default:
2332     return false;
2333   }
2334 }
2335 
2336 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
2337                                        const MachineBasicBlock *MBB,
2338                                        const MachineFunction &MF) const {
2339   // XXX - Do we want the SP check in the base implementation?
2340 
2341   // Target-independent instructions do not have an implicit-use of EXEC, even
2342   // when they operate on VGPRs. Treating EXEC modifications as scheduling
2343   // boundaries prevents incorrect movements of such instructions.
2344   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
2345          MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
2346          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
2347          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
2348          changesVGPRIndexingMode(MI);
2349 }
2350 
2351 bool SIInstrInfo::hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const {
2352   unsigned Opcode = MI.getOpcode();
2353 
2354   if (MI.mayStore() && isSMRD(MI))
2355     return true; // scalar store or atomic
2356 
2357   // These instructions cause shader I/O that may cause hardware lockups
2358   // when executed with an empty EXEC mask.
2359   //
2360   // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
2361   //       EXEC = 0, but checking for that case here seems not worth it
2362   //       given the typical code patterns.
2363   if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
2364       Opcode == AMDGPU::EXP || Opcode == AMDGPU::EXP_DONE)
2365     return true;
2366 
2367   if (MI.isInlineAsm())
2368     return true; // conservative assumption
2369 
2370   // These are like SALU instructions in terms of effects, so it's questionable
2371   // whether we should return true for those.
2372   //
2373   // However, executing them with EXEC = 0 causes them to operate on undefined
2374   // data, which we avoid by returning true here.
2375   if (Opcode == AMDGPU::V_READFIRSTLANE_B32 || Opcode == AMDGPU::V_READLANE_B32)
2376     return true;
2377 
2378   return false;
2379 }
2380 
2381 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
2382   switch (Imm.getBitWidth()) {
2383   case 32:
2384     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
2385                                         ST.hasInv2PiInlineImm());
2386   case 64:
2387     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
2388                                         ST.hasInv2PiInlineImm());
2389   case 16:
2390     return ST.has16BitInsts() &&
2391            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
2392                                         ST.hasInv2PiInlineImm());
2393   default:
2394     llvm_unreachable("invalid bitwidth");
2395   }
2396 }
2397 
2398 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
2399                                    uint8_t OperandType) const {
2400   if (!MO.isImm() ||
2401       OperandType < AMDGPU::OPERAND_SRC_FIRST ||
2402       OperandType > AMDGPU::OPERAND_SRC_LAST)
2403     return false;
2404 
2405   // MachineOperand provides no way to tell the true operand size, since it only
2406   // records a 64-bit value. We need to know the size to determine if a 32-bit
2407   // floating point immediate bit pattern is legal for an integer immediate. It
2408   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
2409 
2410   int64_t Imm = MO.getImm();
2411   switch (OperandType) {
2412   case AMDGPU::OPERAND_REG_IMM_INT32:
2413   case AMDGPU::OPERAND_REG_IMM_FP32:
2414   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
2415   case AMDGPU::OPERAND_REG_INLINE_C_FP32: {
2416     int32_t Trunc = static_cast<int32_t>(Imm);
2417     return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
2418   }
2419   case AMDGPU::OPERAND_REG_IMM_INT64:
2420   case AMDGPU::OPERAND_REG_IMM_FP64:
2421   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
2422   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
2423     return AMDGPU::isInlinableLiteral64(MO.getImm(),
2424                                         ST.hasInv2PiInlineImm());
2425   case AMDGPU::OPERAND_REG_IMM_INT16:
2426   case AMDGPU::OPERAND_REG_IMM_FP16:
2427   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
2428   case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
2429     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
2430       // A few special case instructions have 16-bit operands on subtargets
2431       // where 16-bit instructions are not legal.
2432       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
2433       // constants in these cases
2434       int16_t Trunc = static_cast<int16_t>(Imm);
2435       return ST.has16BitInsts() &&
2436              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
2437     }
2438 
2439     return false;
2440   }
2441   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
2442   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
2443     if (isUInt<16>(Imm)) {
2444       int16_t Trunc = static_cast<int16_t>(Imm);
2445       return ST.has16BitInsts() &&
2446              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
2447     }
2448     if (!(Imm & 0xffff)) {
2449       return ST.has16BitInsts() &&
2450              AMDGPU::isInlinableLiteral16(Imm >> 16, ST.hasInv2PiInlineImm());
2451     }
2452     uint32_t Trunc = static_cast<uint32_t>(Imm);
2453     return  AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
2454   }
2455   default:
2456     llvm_unreachable("invalid bitwidth");
2457   }
2458 }
2459 
2460 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
2461                                         const MCOperandInfo &OpInfo) const {
2462   switch (MO.getType()) {
2463   case MachineOperand::MO_Register:
2464     return false;
2465   case MachineOperand::MO_Immediate:
2466     return !isInlineConstant(MO, OpInfo);
2467   case MachineOperand::MO_FrameIndex:
2468   case MachineOperand::MO_MachineBasicBlock:
2469   case MachineOperand::MO_ExternalSymbol:
2470   case MachineOperand::MO_GlobalAddress:
2471   case MachineOperand::MO_MCSymbol:
2472     return true;
2473   default:
2474     llvm_unreachable("unexpected operand type");
2475   }
2476 }
2477 
2478 static bool compareMachineOp(const MachineOperand &Op0,
2479                              const MachineOperand &Op1) {
2480   if (Op0.getType() != Op1.getType())
2481     return false;
2482 
2483   switch (Op0.getType()) {
2484   case MachineOperand::MO_Register:
2485     return Op0.getReg() == Op1.getReg();
2486   case MachineOperand::MO_Immediate:
2487     return Op0.getImm() == Op1.getImm();
2488   default:
2489     llvm_unreachable("Didn't expect to be comparing these operand types");
2490   }
2491 }
2492 
2493 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
2494                                     const MachineOperand &MO) const {
2495   const MCOperandInfo &OpInfo = get(MI.getOpcode()).OpInfo[OpNo];
2496 
2497   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
2498 
2499   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
2500     return true;
2501 
2502   if (OpInfo.RegClass < 0)
2503     return false;
2504 
2505   if (MO.isImm() && isInlineConstant(MO, OpInfo))
2506     return RI.opCanUseInlineConstant(OpInfo.OperandType);
2507 
2508   return RI.opCanUseLiteralConstant(OpInfo.OperandType);
2509 }
2510 
2511 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
2512   int Op32 = AMDGPU::getVOPe32(Opcode);
2513   if (Op32 == -1)
2514     return false;
2515 
2516   return pseudoToMCOpcode(Op32) != -1;
2517 }
2518 
2519 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
2520   // The src0_modifier operand is present on all instructions
2521   // that have modifiers.
2522 
2523   return AMDGPU::getNamedOperandIdx(Opcode,
2524                                     AMDGPU::OpName::src0_modifiers) != -1;
2525 }
2526 
2527 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
2528                                   unsigned OpName) const {
2529   const MachineOperand *Mods = getNamedOperand(MI, OpName);
2530   return Mods && Mods->getImm();
2531 }
2532 
2533 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
2534   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
2535          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
2536          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
2537          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
2538          hasModifiersSet(MI, AMDGPU::OpName::omod);
2539 }
2540 
2541 bool SIInstrInfo::canShrink(const MachineInstr &MI,
2542                             const MachineRegisterInfo &MRI) const {
2543   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2544   // Can't shrink instruction with three operands.
2545   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
2546   // a special case for it.  It can only be shrunk if the third operand
2547   // is vcc.  We should handle this the same way we handle vopc, by addding
2548   // a register allocation hint pre-regalloc and then do the shrinking
2549   // post-regalloc.
2550   if (Src2) {
2551     switch (MI.getOpcode()) {
2552       default: return false;
2553 
2554       case AMDGPU::V_ADDC_U32_e64:
2555       case AMDGPU::V_SUBB_U32_e64:
2556       case AMDGPU::V_SUBBREV_U32_e64: {
2557         const MachineOperand *Src1
2558           = getNamedOperand(MI, AMDGPU::OpName::src1);
2559         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
2560           return false;
2561         // Additional verification is needed for sdst/src2.
2562         return true;
2563       }
2564       case AMDGPU::V_MAC_F32_e64:
2565       case AMDGPU::V_MAC_F16_e64:
2566       case AMDGPU::V_FMAC_F32_e64:
2567         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
2568             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
2569           return false;
2570         break;
2571 
2572       case AMDGPU::V_CNDMASK_B32_e64:
2573         break;
2574     }
2575   }
2576 
2577   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2578   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
2579                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
2580     return false;
2581 
2582   // We don't need to check src0, all input types are legal, so just make sure
2583   // src0 isn't using any modifiers.
2584   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
2585     return false;
2586 
2587   // Check output modifiers
2588   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
2589          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
2590 }
2591 
2592 // Set VCC operand with all flags from \p Orig, except for setting it as
2593 // implicit.
2594 static void copyFlagsToImplicitVCC(MachineInstr &MI,
2595                                    const MachineOperand &Orig) {
2596 
2597   for (MachineOperand &Use : MI.implicit_operands()) {
2598     if (Use.isUse() && Use.getReg() == AMDGPU::VCC) {
2599       Use.setIsUndef(Orig.isUndef());
2600       Use.setIsKill(Orig.isKill());
2601       return;
2602     }
2603   }
2604 }
2605 
2606 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
2607                                            unsigned Op32) const {
2608   MachineBasicBlock *MBB = MI.getParent();;
2609   MachineInstrBuilder Inst32 =
2610     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32));
2611 
2612   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
2613   // For VOPC instructions, this is replaced by an implicit def of vcc.
2614   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
2615   if (Op32DstIdx != -1) {
2616     // dst
2617     Inst32.add(MI.getOperand(0));
2618   } else {
2619     assert(MI.getOperand(0).getReg() == AMDGPU::VCC &&
2620            "Unexpected case");
2621   }
2622 
2623   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
2624 
2625   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2626   if (Src1)
2627     Inst32.add(*Src1);
2628 
2629   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2630 
2631   if (Src2) {
2632     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
2633     if (Op32Src2Idx != -1) {
2634       Inst32.add(*Src2);
2635     } else {
2636       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
2637       // replaced with an implicit read of vcc. This was already added
2638       // during the initial BuildMI, so find it to preserve the flags.
2639       copyFlagsToImplicitVCC(*Inst32, *Src2);
2640     }
2641   }
2642 
2643   return Inst32;
2644 }
2645 
2646 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
2647                                   const MachineOperand &MO,
2648                                   const MCOperandInfo &OpInfo) const {
2649   // Literal constants use the constant bus.
2650   //if (isLiteralConstantLike(MO, OpInfo))
2651   // return true;
2652   if (MO.isImm())
2653     return !isInlineConstant(MO, OpInfo);
2654 
2655   if (!MO.isReg())
2656     return true; // Misc other operands like FrameIndex
2657 
2658   if (!MO.isUse())
2659     return false;
2660 
2661   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2662     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
2663 
2664   // FLAT_SCR is just an SGPR pair.
2665   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
2666     return true;
2667 
2668   // EXEC register uses the constant bus.
2669   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
2670     return true;
2671 
2672   // SGPRs use the constant bus
2673   return (MO.getReg() == AMDGPU::VCC || MO.getReg() == AMDGPU::M0 ||
2674           (!MO.isImplicit() &&
2675            (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
2676             AMDGPU::SGPR_64RegClass.contains(MO.getReg()))));
2677 }
2678 
2679 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
2680   for (const MachineOperand &MO : MI.implicit_operands()) {
2681     // We only care about reads.
2682     if (MO.isDef())
2683       continue;
2684 
2685     switch (MO.getReg()) {
2686     case AMDGPU::VCC:
2687     case AMDGPU::M0:
2688     case AMDGPU::FLAT_SCR:
2689       return MO.getReg();
2690 
2691     default:
2692       break;
2693     }
2694   }
2695 
2696   return AMDGPU::NoRegister;
2697 }
2698 
2699 static bool shouldReadExec(const MachineInstr &MI) {
2700   if (SIInstrInfo::isVALU(MI)) {
2701     switch (MI.getOpcode()) {
2702     case AMDGPU::V_READLANE_B32:
2703     case AMDGPU::V_READLANE_B32_si:
2704     case AMDGPU::V_READLANE_B32_vi:
2705     case AMDGPU::V_WRITELANE_B32:
2706     case AMDGPU::V_WRITELANE_B32_si:
2707     case AMDGPU::V_WRITELANE_B32_vi:
2708       return false;
2709     }
2710 
2711     return true;
2712   }
2713 
2714   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
2715       SIInstrInfo::isSALU(MI) ||
2716       SIInstrInfo::isSMRD(MI))
2717     return false;
2718 
2719   return true;
2720 }
2721 
2722 static bool isSubRegOf(const SIRegisterInfo &TRI,
2723                        const MachineOperand &SuperVec,
2724                        const MachineOperand &SubReg) {
2725   if (TargetRegisterInfo::isPhysicalRegister(SubReg.getReg()))
2726     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
2727 
2728   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
2729          SubReg.getReg() == SuperVec.getReg();
2730 }
2731 
2732 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
2733                                     StringRef &ErrInfo) const {
2734   uint16_t Opcode = MI.getOpcode();
2735   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
2736     return true;
2737 
2738   const MachineFunction *MF = MI.getParent()->getParent();
2739   const MachineRegisterInfo &MRI = MF->getRegInfo();
2740 
2741   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
2742   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
2743   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
2744 
2745   // Make sure the number of operands is correct.
2746   const MCInstrDesc &Desc = get(Opcode);
2747   if (!Desc.isVariadic() &&
2748       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
2749     ErrInfo = "Instruction has wrong number of operands.";
2750     return false;
2751   }
2752 
2753   if (MI.isInlineAsm()) {
2754     // Verify register classes for inlineasm constraints.
2755     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
2756          I != E; ++I) {
2757       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
2758       if (!RC)
2759         continue;
2760 
2761       const MachineOperand &Op = MI.getOperand(I);
2762       if (!Op.isReg())
2763         continue;
2764 
2765       unsigned Reg = Op.getReg();
2766       if (!TargetRegisterInfo::isVirtualRegister(Reg) && !RC->contains(Reg)) {
2767         ErrInfo = "inlineasm operand has incorrect register class.";
2768         return false;
2769       }
2770     }
2771 
2772     return true;
2773   }
2774 
2775   // Make sure the register classes are correct.
2776   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
2777     if (MI.getOperand(i).isFPImm()) {
2778       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
2779                 "all fp values to integers.";
2780       return false;
2781     }
2782 
2783     int RegClass = Desc.OpInfo[i].RegClass;
2784 
2785     switch (Desc.OpInfo[i].OperandType) {
2786     case MCOI::OPERAND_REGISTER:
2787       if (MI.getOperand(i).isImm()) {
2788         ErrInfo = "Illegal immediate value for operand.";
2789         return false;
2790       }
2791       break;
2792     case AMDGPU::OPERAND_REG_IMM_INT32:
2793     case AMDGPU::OPERAND_REG_IMM_FP32:
2794       break;
2795     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
2796     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
2797     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
2798     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
2799     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
2800     case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
2801       const MachineOperand &MO = MI.getOperand(i);
2802       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
2803         ErrInfo = "Illegal immediate value for operand.";
2804         return false;
2805       }
2806       break;
2807     }
2808     case MCOI::OPERAND_IMMEDIATE:
2809     case AMDGPU::OPERAND_KIMM32:
2810       // Check if this operand is an immediate.
2811       // FrameIndex operands will be replaced by immediates, so they are
2812       // allowed.
2813       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
2814         ErrInfo = "Expected immediate, but got non-immediate";
2815         return false;
2816       }
2817       LLVM_FALLTHROUGH;
2818     default:
2819       continue;
2820     }
2821 
2822     if (!MI.getOperand(i).isReg())
2823       continue;
2824 
2825     if (RegClass != -1) {
2826       unsigned Reg = MI.getOperand(i).getReg();
2827       if (Reg == AMDGPU::NoRegister ||
2828           TargetRegisterInfo::isVirtualRegister(Reg))
2829         continue;
2830 
2831       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
2832       if (!RC->contains(Reg)) {
2833         ErrInfo = "Operand has incorrect register class.";
2834         return false;
2835       }
2836     }
2837   }
2838 
2839   // Verify SDWA
2840   if (isSDWA(MI)) {
2841     if (!ST.hasSDWA()) {
2842       ErrInfo = "SDWA is not supported on this target";
2843       return false;
2844     }
2845 
2846     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
2847 
2848     const int OpIndicies[] = { DstIdx, Src0Idx, Src1Idx, Src2Idx };
2849 
2850     for (int OpIdx: OpIndicies) {
2851       if (OpIdx == -1)
2852         continue;
2853       const MachineOperand &MO = MI.getOperand(OpIdx);
2854 
2855       if (!ST.hasSDWAScalar()) {
2856         // Only VGPRS on VI
2857         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
2858           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
2859           return false;
2860         }
2861       } else {
2862         // No immediates on GFX9
2863         if (!MO.isReg()) {
2864           ErrInfo = "Only reg allowed as operands in SDWA instructions on GFX9";
2865           return false;
2866         }
2867       }
2868     }
2869 
2870     if (!ST.hasSDWAOmod()) {
2871       // No omod allowed on VI
2872       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
2873       if (OMod != nullptr &&
2874         (!OMod->isImm() || OMod->getImm() != 0)) {
2875         ErrInfo = "OMod not allowed in SDWA instructions on VI";
2876         return false;
2877       }
2878     }
2879 
2880     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
2881     if (isVOPC(BasicOpcode)) {
2882       if (!ST.hasSDWASdst() && DstIdx != -1) {
2883         // Only vcc allowed as dst on VI for VOPC
2884         const MachineOperand &Dst = MI.getOperand(DstIdx);
2885         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
2886           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
2887           return false;
2888         }
2889       } else if (!ST.hasSDWAOutModsVOPC()) {
2890         // No clamp allowed on GFX9 for VOPC
2891         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
2892         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
2893           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
2894           return false;
2895         }
2896 
2897         // No omod allowed on GFX9 for VOPC
2898         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
2899         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
2900           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
2901           return false;
2902         }
2903       }
2904     }
2905 
2906     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
2907     if (DstUnused && DstUnused->isImm() &&
2908         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
2909       const MachineOperand &Dst = MI.getOperand(DstIdx);
2910       if (!Dst.isReg() || !Dst.isTied()) {
2911         ErrInfo = "Dst register should have tied register";
2912         return false;
2913       }
2914 
2915       const MachineOperand &TiedMO =
2916           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
2917       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
2918         ErrInfo =
2919             "Dst register should be tied to implicit use of preserved register";
2920         return false;
2921       } else if (TargetRegisterInfo::isPhysicalRegister(TiedMO.getReg()) &&
2922                  Dst.getReg() != TiedMO.getReg()) {
2923         ErrInfo = "Dst register should use same physical register as preserved";
2924         return false;
2925       }
2926     }
2927   }
2928 
2929   // Verify VOP*. Ignore multiple sgpr operands on writelane.
2930   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
2931       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
2932     // Only look at the true operands. Only a real operand can use the constant
2933     // bus, and we don't want to check pseudo-operands like the source modifier
2934     // flags.
2935     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
2936 
2937     unsigned ConstantBusCount = 0;
2938     unsigned LiteralCount = 0;
2939 
2940     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
2941       ++ConstantBusCount;
2942 
2943     unsigned SGPRUsed = findImplicitSGPRRead(MI);
2944     if (SGPRUsed != AMDGPU::NoRegister)
2945       ++ConstantBusCount;
2946 
2947     for (int OpIdx : OpIndices) {
2948       if (OpIdx == -1)
2949         break;
2950       const MachineOperand &MO = MI.getOperand(OpIdx);
2951       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
2952         if (MO.isReg()) {
2953           if (MO.getReg() != SGPRUsed)
2954             ++ConstantBusCount;
2955           SGPRUsed = MO.getReg();
2956         } else {
2957           ++ConstantBusCount;
2958           ++LiteralCount;
2959         }
2960       }
2961     }
2962     if (ConstantBusCount > 1) {
2963       ErrInfo = "VOP* instruction uses the constant bus more than once";
2964       return false;
2965     }
2966 
2967     if (isVOP3(MI) && LiteralCount) {
2968       ErrInfo = "VOP3 instruction uses literal";
2969       return false;
2970     }
2971   }
2972 
2973   // Verify misc. restrictions on specific instructions.
2974   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
2975       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
2976     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
2977     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
2978     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
2979     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
2980       if (!compareMachineOp(Src0, Src1) &&
2981           !compareMachineOp(Src0, Src2)) {
2982         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
2983         return false;
2984       }
2985     }
2986   }
2987 
2988   if (isSOPK(MI)) {
2989     int64_t Imm = getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
2990     if (sopkIsZext(MI)) {
2991       if (!isUInt<16>(Imm)) {
2992         ErrInfo = "invalid immediate for SOPK instruction";
2993         return false;
2994       }
2995     } else {
2996       if (!isInt<16>(Imm)) {
2997         ErrInfo = "invalid immediate for SOPK instruction";
2998         return false;
2999       }
3000     }
3001   }
3002 
3003   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
3004       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
3005       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
3006       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
3007     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
3008                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
3009 
3010     const unsigned StaticNumOps = Desc.getNumOperands() +
3011       Desc.getNumImplicitUses();
3012     const unsigned NumImplicitOps = IsDst ? 2 : 1;
3013 
3014     // Allow additional implicit operands. This allows a fixup done by the post
3015     // RA scheduler where the main implicit operand is killed and implicit-defs
3016     // are added for sub-registers that remain live after this instruction.
3017     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
3018       ErrInfo = "missing implicit register operands";
3019       return false;
3020     }
3021 
3022     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
3023     if (IsDst) {
3024       if (!Dst->isUse()) {
3025         ErrInfo = "v_movreld_b32 vdst should be a use operand";
3026         return false;
3027       }
3028 
3029       unsigned UseOpIdx;
3030       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
3031           UseOpIdx != StaticNumOps + 1) {
3032         ErrInfo = "movrel implicit operands should be tied";
3033         return false;
3034       }
3035     }
3036 
3037     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
3038     const MachineOperand &ImpUse
3039       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
3040     if (!ImpUse.isReg() || !ImpUse.isUse() ||
3041         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
3042       ErrInfo = "src0 should be subreg of implicit vector use";
3043       return false;
3044     }
3045   }
3046 
3047   // Make sure we aren't losing exec uses in the td files. This mostly requires
3048   // being careful when using let Uses to try to add other use registers.
3049   if (shouldReadExec(MI)) {
3050     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
3051       ErrInfo = "VALU instruction does not implicitly read exec mask";
3052       return false;
3053     }
3054   }
3055 
3056   if (isSMRD(MI)) {
3057     if (MI.mayStore()) {
3058       // The register offset form of scalar stores may only use m0 as the
3059       // soffset register.
3060       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
3061       if (Soff && Soff->getReg() != AMDGPU::M0) {
3062         ErrInfo = "scalar stores must use m0 as offset register";
3063         return false;
3064       }
3065     }
3066   }
3067 
3068   if (isFLAT(MI) && !MF->getSubtarget<GCNSubtarget>().hasFlatInstOffsets()) {
3069     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
3070     if (Offset->getImm() != 0) {
3071       ErrInfo = "subtarget does not support offsets in flat instructions";
3072       return false;
3073     }
3074   }
3075 
3076   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
3077   if (DppCt) {
3078     using namespace AMDGPU::DPP;
3079 
3080     unsigned DC = DppCt->getImm();
3081     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
3082         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
3083         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
3084         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
3085         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
3086         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST)) {
3087       ErrInfo = "Invalid dpp_ctrl value";
3088       return false;
3089     }
3090   }
3091 
3092   return true;
3093 }
3094 
3095 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
3096   switch (MI.getOpcode()) {
3097   default: return AMDGPU::INSTRUCTION_LIST_END;
3098   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
3099   case AMDGPU::COPY: return AMDGPU::COPY;
3100   case AMDGPU::PHI: return AMDGPU::PHI;
3101   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
3102   case AMDGPU::WQM: return AMDGPU::WQM;
3103   case AMDGPU::WWM: return AMDGPU::WWM;
3104   case AMDGPU::S_MOV_B32:
3105     return MI.getOperand(1).isReg() ?
3106            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
3107   case AMDGPU::S_ADD_I32:
3108     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_I32_e32;
3109   case AMDGPU::S_ADDC_U32:
3110     return AMDGPU::V_ADDC_U32_e32;
3111   case AMDGPU::S_SUB_I32:
3112     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_I32_e32;
3113     // FIXME: These are not consistently handled, and selected when the carry is
3114     // used.
3115   case AMDGPU::S_ADD_U32:
3116     return AMDGPU::V_ADD_I32_e32;
3117   case AMDGPU::S_SUB_U32:
3118     return AMDGPU::V_SUB_I32_e32;
3119   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
3120   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
3121   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
3122   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
3123   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
3124   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
3125   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
3126   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
3127   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
3128   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
3129   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
3130   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
3131   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
3132   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
3133   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
3134   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
3135   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
3136   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
3137   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
3138   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
3139   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
3140   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
3141   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
3142   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
3143   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
3144   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
3145   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
3146   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
3147   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
3148   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
3149   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
3150   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
3151   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
3152   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
3153   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
3154   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
3155   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
3156   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
3157   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
3158   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
3159   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
3160   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
3161   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
3162   }
3163 }
3164 
3165 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
3166                                                       unsigned OpNo) const {
3167   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3168   const MCInstrDesc &Desc = get(MI.getOpcode());
3169   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
3170       Desc.OpInfo[OpNo].RegClass == -1) {
3171     unsigned Reg = MI.getOperand(OpNo).getReg();
3172 
3173     if (TargetRegisterInfo::isVirtualRegister(Reg))
3174       return MRI.getRegClass(Reg);
3175     return RI.getPhysRegClass(Reg);
3176   }
3177 
3178   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
3179   return RI.getRegClass(RCID);
3180 }
3181 
3182 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
3183   switch (MI.getOpcode()) {
3184   case AMDGPU::COPY:
3185   case AMDGPU::REG_SEQUENCE:
3186   case AMDGPU::PHI:
3187   case AMDGPU::INSERT_SUBREG:
3188     return RI.hasVGPRs(getOpRegClass(MI, 0));
3189   default:
3190     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
3191   }
3192 }
3193 
3194 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
3195   MachineBasicBlock::iterator I = MI;
3196   MachineBasicBlock *MBB = MI.getParent();
3197   MachineOperand &MO = MI.getOperand(OpIdx);
3198   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
3199   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
3200   const TargetRegisterClass *RC = RI.getRegClass(RCID);
3201   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
3202   if (MO.isReg())
3203     Opcode = AMDGPU::COPY;
3204   else if (RI.isSGPRClass(RC))
3205     Opcode = AMDGPU::S_MOV_B32;
3206 
3207   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
3208   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
3209     VRC = &AMDGPU::VReg_64RegClass;
3210   else
3211     VRC = &AMDGPU::VGPR_32RegClass;
3212 
3213   unsigned Reg = MRI.createVirtualRegister(VRC);
3214   DebugLoc DL = MBB->findDebugLoc(I);
3215   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
3216   MO.ChangeToRegister(Reg, false);
3217 }
3218 
3219 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
3220                                          MachineRegisterInfo &MRI,
3221                                          MachineOperand &SuperReg,
3222                                          const TargetRegisterClass *SuperRC,
3223                                          unsigned SubIdx,
3224                                          const TargetRegisterClass *SubRC)
3225                                          const {
3226   MachineBasicBlock *MBB = MI->getParent();
3227   DebugLoc DL = MI->getDebugLoc();
3228   unsigned SubReg = MRI.createVirtualRegister(SubRC);
3229 
3230   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
3231     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
3232       .addReg(SuperReg.getReg(), 0, SubIdx);
3233     return SubReg;
3234   }
3235 
3236   // Just in case the super register is itself a sub-register, copy it to a new
3237   // value so we don't need to worry about merging its subreg index with the
3238   // SubIdx passed to this function. The register coalescer should be able to
3239   // eliminate this extra copy.
3240   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
3241 
3242   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
3243     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
3244 
3245   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
3246     .addReg(NewSuperReg, 0, SubIdx);
3247 
3248   return SubReg;
3249 }
3250 
3251 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
3252   MachineBasicBlock::iterator MII,
3253   MachineRegisterInfo &MRI,
3254   MachineOperand &Op,
3255   const TargetRegisterClass *SuperRC,
3256   unsigned SubIdx,
3257   const TargetRegisterClass *SubRC) const {
3258   if (Op.isImm()) {
3259     if (SubIdx == AMDGPU::sub0)
3260       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
3261     if (SubIdx == AMDGPU::sub1)
3262       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
3263 
3264     llvm_unreachable("Unhandled register index for immediate");
3265   }
3266 
3267   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
3268                                        SubIdx, SubRC);
3269   return MachineOperand::CreateReg(SubReg, false);
3270 }
3271 
3272 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
3273 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
3274   assert(Inst.getNumExplicitOperands() == 3);
3275   MachineOperand Op1 = Inst.getOperand(1);
3276   Inst.RemoveOperand(1);
3277   Inst.addOperand(Op1);
3278 }
3279 
3280 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
3281                                     const MCOperandInfo &OpInfo,
3282                                     const MachineOperand &MO) const {
3283   if (!MO.isReg())
3284     return false;
3285 
3286   unsigned Reg = MO.getReg();
3287   const TargetRegisterClass *RC =
3288     TargetRegisterInfo::isVirtualRegister(Reg) ?
3289     MRI.getRegClass(Reg) :
3290     RI.getPhysRegClass(Reg);
3291 
3292   const SIRegisterInfo *TRI =
3293       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
3294   RC = TRI->getSubRegClass(RC, MO.getSubReg());
3295 
3296   // In order to be legal, the common sub-class must be equal to the
3297   // class of the current operand.  For example:
3298   //
3299   // v_mov_b32 s0 ; Operand defined as vsrc_b32
3300   //              ; RI.getCommonSubClass(s0,vsrc_b32) = sgpr ; LEGAL
3301   //
3302   // s_sendmsg 0, s0 ; Operand defined as m0reg
3303   //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
3304 
3305   return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
3306 }
3307 
3308 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
3309                                      const MCOperandInfo &OpInfo,
3310                                      const MachineOperand &MO) const {
3311   if (MO.isReg())
3312     return isLegalRegOperand(MRI, OpInfo, MO);
3313 
3314   // Handle non-register types that are treated like immediates.
3315   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
3316   return true;
3317 }
3318 
3319 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
3320                                  const MachineOperand *MO) const {
3321   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3322   const MCInstrDesc &InstDesc = MI.getDesc();
3323   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
3324   const TargetRegisterClass *DefinedRC =
3325       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
3326   if (!MO)
3327     MO = &MI.getOperand(OpIdx);
3328 
3329   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
3330 
3331     RegSubRegPair SGPRUsed;
3332     if (MO->isReg())
3333       SGPRUsed = RegSubRegPair(MO->getReg(), MO->getSubReg());
3334 
3335     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3336       if (i == OpIdx)
3337         continue;
3338       const MachineOperand &Op = MI.getOperand(i);
3339       if (Op.isReg()) {
3340         if ((Op.getReg() != SGPRUsed.Reg || Op.getSubReg() != SGPRUsed.SubReg) &&
3341             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
3342           return false;
3343         }
3344       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
3345         return false;
3346       }
3347     }
3348   }
3349 
3350   if (MO->isReg()) {
3351     assert(DefinedRC);
3352     return isLegalRegOperand(MRI, OpInfo, *MO);
3353   }
3354 
3355   // Handle non-register types that are treated like immediates.
3356   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
3357 
3358   if (!DefinedRC) {
3359     // This operand expects an immediate.
3360     return true;
3361   }
3362 
3363   return isImmOperandLegal(MI, OpIdx, *MO);
3364 }
3365 
3366 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
3367                                        MachineInstr &MI) const {
3368   unsigned Opc = MI.getOpcode();
3369   const MCInstrDesc &InstrDesc = get(Opc);
3370 
3371   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3372   MachineOperand &Src1 = MI.getOperand(Src1Idx);
3373 
3374   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
3375   // we need to only have one constant bus use.
3376   //
3377   // Note we do not need to worry about literal constants here. They are
3378   // disabled for the operand type for instructions because they will always
3379   // violate the one constant bus use rule.
3380   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
3381   if (HasImplicitSGPR) {
3382     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3383     MachineOperand &Src0 = MI.getOperand(Src0Idx);
3384 
3385     if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg()))
3386       legalizeOpWithMove(MI, Src0Idx);
3387   }
3388 
3389   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
3390   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
3391   // src0/src1 with V_READFIRSTLANE.
3392   if (Opc == AMDGPU::V_WRITELANE_B32) {
3393     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3394     MachineOperand &Src0 = MI.getOperand(Src0Idx);
3395     const DebugLoc &DL = MI.getDebugLoc();
3396     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
3397       unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3398       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
3399           .add(Src0);
3400       Src0.ChangeToRegister(Reg, false);
3401     }
3402     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
3403       unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3404       const DebugLoc &DL = MI.getDebugLoc();
3405       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
3406           .add(Src1);
3407       Src1.ChangeToRegister(Reg, false);
3408     }
3409     return;
3410   }
3411 
3412   // VOP2 src0 instructions support all operand types, so we don't need to check
3413   // their legality. If src1 is already legal, we don't need to do anything.
3414   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
3415     return;
3416 
3417   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
3418   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
3419   // select is uniform.
3420   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
3421       RI.isVGPR(MRI, Src1.getReg())) {
3422     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3423     const DebugLoc &DL = MI.getDebugLoc();
3424     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
3425         .add(Src1);
3426     Src1.ChangeToRegister(Reg, false);
3427     return;
3428   }
3429 
3430   // We do not use commuteInstruction here because it is too aggressive and will
3431   // commute if it is possible. We only want to commute here if it improves
3432   // legality. This can be called a fairly large number of times so don't waste
3433   // compile time pointlessly swapping and checking legality again.
3434   if (HasImplicitSGPR || !MI.isCommutable()) {
3435     legalizeOpWithMove(MI, Src1Idx);
3436     return;
3437   }
3438 
3439   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3440   MachineOperand &Src0 = MI.getOperand(Src0Idx);
3441 
3442   // If src0 can be used as src1, commuting will make the operands legal.
3443   // Otherwise we have to give up and insert a move.
3444   //
3445   // TODO: Other immediate-like operand kinds could be commuted if there was a
3446   // MachineOperand::ChangeTo* for them.
3447   if ((!Src1.isImm() && !Src1.isReg()) ||
3448       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
3449     legalizeOpWithMove(MI, Src1Idx);
3450     return;
3451   }
3452 
3453   int CommutedOpc = commuteOpcode(MI);
3454   if (CommutedOpc == -1) {
3455     legalizeOpWithMove(MI, Src1Idx);
3456     return;
3457   }
3458 
3459   MI.setDesc(get(CommutedOpc));
3460 
3461   unsigned Src0Reg = Src0.getReg();
3462   unsigned Src0SubReg = Src0.getSubReg();
3463   bool Src0Kill = Src0.isKill();
3464 
3465   if (Src1.isImm())
3466     Src0.ChangeToImmediate(Src1.getImm());
3467   else if (Src1.isReg()) {
3468     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
3469     Src0.setSubReg(Src1.getSubReg());
3470   } else
3471     llvm_unreachable("Should only have register or immediate operands");
3472 
3473   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
3474   Src1.setSubReg(Src0SubReg);
3475 }
3476 
3477 // Legalize VOP3 operands. Because all operand types are supported for any
3478 // operand, and since literal constants are not allowed and should never be
3479 // seen, we only need to worry about inserting copies if we use multiple SGPR
3480 // operands.
3481 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
3482                                        MachineInstr &MI) const {
3483   unsigned Opc = MI.getOpcode();
3484 
3485   int VOP3Idx[3] = {
3486     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
3487     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
3488     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
3489   };
3490 
3491   // Find the one SGPR operand we are allowed to use.
3492   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
3493 
3494   for (unsigned i = 0; i < 3; ++i) {
3495     int Idx = VOP3Idx[i];
3496     if (Idx == -1)
3497       break;
3498     MachineOperand &MO = MI.getOperand(Idx);
3499 
3500     // We should never see a VOP3 instruction with an illegal immediate operand.
3501     if (!MO.isReg())
3502       continue;
3503 
3504     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
3505       continue; // VGPRs are legal
3506 
3507     if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
3508       SGPRReg = MO.getReg();
3509       // We can use one SGPR in each VOP3 instruction.
3510       continue;
3511     }
3512 
3513     // If we make it this far, then the operand is not legal and we must
3514     // legalize it.
3515     legalizeOpWithMove(MI, Idx);
3516   }
3517 }
3518 
3519 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
3520                                          MachineRegisterInfo &MRI) const {
3521   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
3522   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
3523   unsigned DstReg = MRI.createVirtualRegister(SRC);
3524   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
3525 
3526   if (SubRegs == 1) {
3527     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
3528             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
3529         .addReg(SrcReg);
3530     return DstReg;
3531   }
3532 
3533   SmallVector<unsigned, 8> SRegs;
3534   for (unsigned i = 0; i < SubRegs; ++i) {
3535     unsigned SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3536     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
3537             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
3538         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
3539     SRegs.push_back(SGPR);
3540   }
3541 
3542   MachineInstrBuilder MIB =
3543       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
3544               get(AMDGPU::REG_SEQUENCE), DstReg);
3545   for (unsigned i = 0; i < SubRegs; ++i) {
3546     MIB.addReg(SRegs[i]);
3547     MIB.addImm(RI.getSubRegFromChannel(i));
3548   }
3549   return DstReg;
3550 }
3551 
3552 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
3553                                        MachineInstr &MI) const {
3554 
3555   // If the pointer is store in VGPRs, then we need to move them to
3556   // SGPRs using v_readfirstlane.  This is safe because we only select
3557   // loads with uniform pointers to SMRD instruction so we know the
3558   // pointer value is uniform.
3559   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
3560   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
3561       unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
3562       SBase->setReg(SGPR);
3563   }
3564 }
3565 
3566 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
3567                                          MachineBasicBlock::iterator I,
3568                                          const TargetRegisterClass *DstRC,
3569                                          MachineOperand &Op,
3570                                          MachineRegisterInfo &MRI,
3571                                          const DebugLoc &DL) const {
3572   unsigned OpReg = Op.getReg();
3573   unsigned OpSubReg = Op.getSubReg();
3574 
3575   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
3576       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
3577 
3578   // Check if operand is already the correct register class.
3579   if (DstRC == OpRC)
3580     return;
3581 
3582   unsigned DstReg = MRI.createVirtualRegister(DstRC);
3583   MachineInstr *Copy =
3584       BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
3585 
3586   Op.setReg(DstReg);
3587   Op.setSubReg(0);
3588 
3589   MachineInstr *Def = MRI.getVRegDef(OpReg);
3590   if (!Def)
3591     return;
3592 
3593   // Try to eliminate the copy if it is copying an immediate value.
3594   if (Def->isMoveImmediate())
3595     FoldImmediate(*Copy, *Def, OpReg, &MRI);
3596 }
3597 
3598 // Emit the actual waterfall loop, executing the wrapped instruction for each
3599 // unique value of \p Rsrc across all lanes. In the best case we execute 1
3600 // iteration, in the worst case we execute 64 (once per lane).
3601 static void
3602 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
3603                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3604                           const DebugLoc &DL, MachineOperand &Rsrc) {
3605   MachineBasicBlock::iterator I = LoopBB.begin();
3606 
3607   unsigned VRsrc = Rsrc.getReg();
3608   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
3609 
3610   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3611   unsigned CondReg0 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3612   unsigned CondReg1 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3613   unsigned AndCond = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3614   unsigned SRsrcSub0 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3615   unsigned SRsrcSub1 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3616   unsigned SRsrcSub2 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3617   unsigned SRsrcSub3 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3618   unsigned SRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
3619 
3620   // Beginning of the loop, read the next Rsrc variant.
3621   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub0)
3622       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub0);
3623   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub1)
3624       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub1);
3625   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub2)
3626       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub2);
3627   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub3)
3628       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub3);
3629 
3630   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc)
3631       .addReg(SRsrcSub0)
3632       .addImm(AMDGPU::sub0)
3633       .addReg(SRsrcSub1)
3634       .addImm(AMDGPU::sub1)
3635       .addReg(SRsrcSub2)
3636       .addImm(AMDGPU::sub2)
3637       .addReg(SRsrcSub3)
3638       .addImm(AMDGPU::sub3);
3639 
3640   // Update Rsrc operand to use the SGPR Rsrc.
3641   Rsrc.setReg(SRsrc);
3642   Rsrc.setIsKill(true);
3643 
3644   // Identify all lanes with identical Rsrc operands in their VGPRs.
3645   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), CondReg0)
3646       .addReg(SRsrc, 0, AMDGPU::sub0_sub1)
3647       .addReg(VRsrc, 0, AMDGPU::sub0_sub1);
3648   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), CondReg1)
3649       .addReg(SRsrc, 0, AMDGPU::sub2_sub3)
3650       .addReg(VRsrc, 0, AMDGPU::sub2_sub3);
3651   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_AND_B64), AndCond)
3652       .addReg(CondReg0)
3653       .addReg(CondReg1);
3654 
3655   MRI.setSimpleHint(SaveExec, AndCond);
3656 
3657   // Update EXEC to matching lanes, saving original to SaveExec.
3658   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_AND_SAVEEXEC_B64), SaveExec)
3659       .addReg(AndCond, RegState::Kill);
3660 
3661   // The original instruction is here; we insert the terminators after it.
3662   I = LoopBB.end();
3663 
3664   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3665   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC)
3666       .addReg(AMDGPU::EXEC)
3667       .addReg(SaveExec);
3668   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(&LoopBB);
3669 }
3670 
3671 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
3672 // with SGPRs by iterating over all unique values across all lanes.
3673 static void loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
3674                               MachineOperand &Rsrc, MachineDominatorTree *MDT) {
3675   MachineBasicBlock &MBB = *MI.getParent();
3676   MachineFunction &MF = *MBB.getParent();
3677   MachineRegisterInfo &MRI = MF.getRegInfo();
3678   MachineBasicBlock::iterator I(&MI);
3679   const DebugLoc &DL = MI.getDebugLoc();
3680 
3681   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3682 
3683   // Save the EXEC mask
3684   BuildMI(MBB, I, DL, TII.get(AMDGPU::S_MOV_B64), SaveExec)
3685       .addReg(AMDGPU::EXEC);
3686 
3687   // Killed uses in the instruction we are waterfalling around will be
3688   // incorrect due to the added control-flow.
3689   for (auto &MO : MI.uses()) {
3690     if (MO.isReg() && MO.isUse()) {
3691       MRI.clearKillFlags(MO.getReg());
3692     }
3693   }
3694 
3695   // To insert the loop we need to split the block. Move everything after this
3696   // point to a new block, and insert a new empty block between the two.
3697   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
3698   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
3699   MachineFunction::iterator MBBI(MBB);
3700   ++MBBI;
3701 
3702   MF.insert(MBBI, LoopBB);
3703   MF.insert(MBBI, RemainderBB);
3704 
3705   LoopBB->addSuccessor(LoopBB);
3706   LoopBB->addSuccessor(RemainderBB);
3707 
3708   // Move MI to the LoopBB, and the remainder of the block to RemainderBB.
3709   MachineBasicBlock::iterator J = I++;
3710   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3711   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3712   LoopBB->splice(LoopBB->begin(), &MBB, J);
3713 
3714   MBB.addSuccessor(LoopBB);
3715 
3716   // Update dominators. We know that MBB immediately dominates LoopBB, that
3717   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
3718   // dominates all of the successors transferred to it from MBB that MBB used
3719   // to dominate.
3720   if (MDT) {
3721     MDT->addNewBlock(LoopBB, &MBB);
3722     MDT->addNewBlock(RemainderBB, LoopBB);
3723     for (auto &Succ : RemainderBB->successors()) {
3724       if (MDT->dominates(&MBB, Succ)) {
3725         MDT->changeImmediateDominator(Succ, RemainderBB);
3726       }
3727     }
3728   }
3729 
3730   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
3731 
3732   // Restore the EXEC mask
3733   MachineBasicBlock::iterator First = RemainderBB->begin();
3734   BuildMI(*RemainderBB, First, DL, TII.get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
3735       .addReg(SaveExec);
3736 }
3737 
3738 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
3739 static std::tuple<unsigned, unsigned>
3740 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
3741   MachineBasicBlock &MBB = *MI.getParent();
3742   MachineFunction &MF = *MBB.getParent();
3743   MachineRegisterInfo &MRI = MF.getRegInfo();
3744 
3745   // Extract the ptr from the resource descriptor.
3746   unsigned RsrcPtr =
3747       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
3748                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
3749 
3750   // Create an empty resource descriptor
3751   unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3752   unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3753   unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3754   unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
3755   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
3756 
3757   // Zero64 = 0
3758   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
3759       .addImm(0);
3760 
3761   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
3762   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
3763       .addImm(RsrcDataFormat & 0xFFFFFFFF);
3764 
3765   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
3766   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
3767       .addImm(RsrcDataFormat >> 32);
3768 
3769   // NewSRsrc = {Zero64, SRsrcFormat}
3770   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
3771       .addReg(Zero64)
3772       .addImm(AMDGPU::sub0_sub1)
3773       .addReg(SRsrcFormatLo)
3774       .addImm(AMDGPU::sub2)
3775       .addReg(SRsrcFormatHi)
3776       .addImm(AMDGPU::sub3);
3777 
3778   return std::make_tuple(RsrcPtr, NewSRsrc);
3779 }
3780 
3781 void SIInstrInfo::legalizeOperands(MachineInstr &MI,
3782                                    MachineDominatorTree *MDT) const {
3783   MachineFunction &MF = *MI.getParent()->getParent();
3784   MachineRegisterInfo &MRI = MF.getRegInfo();
3785 
3786   // Legalize VOP2
3787   if (isVOP2(MI) || isVOPC(MI)) {
3788     legalizeOperandsVOP2(MRI, MI);
3789     return;
3790   }
3791 
3792   // Legalize VOP3
3793   if (isVOP3(MI)) {
3794     legalizeOperandsVOP3(MRI, MI);
3795     return;
3796   }
3797 
3798   // Legalize SMRD
3799   if (isSMRD(MI)) {
3800     legalizeOperandsSMRD(MRI, MI);
3801     return;
3802   }
3803 
3804   // Legalize REG_SEQUENCE and PHI
3805   // The register class of the operands much be the same type as the register
3806   // class of the output.
3807   if (MI.getOpcode() == AMDGPU::PHI) {
3808     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
3809     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3810       if (!MI.getOperand(i).isReg() ||
3811           !TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
3812         continue;
3813       const TargetRegisterClass *OpRC =
3814           MRI.getRegClass(MI.getOperand(i).getReg());
3815       if (RI.hasVGPRs(OpRC)) {
3816         VRC = OpRC;
3817       } else {
3818         SRC = OpRC;
3819       }
3820     }
3821 
3822     // If any of the operands are VGPR registers, then they all most be
3823     // otherwise we will create illegal VGPR->SGPR copies when legalizing
3824     // them.
3825     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
3826       if (!VRC) {
3827         assert(SRC);
3828         VRC = RI.getEquivalentVGPRClass(SRC);
3829       }
3830       RC = VRC;
3831     } else {
3832       RC = SRC;
3833     }
3834 
3835     // Update all the operands so they have the same type.
3836     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3837       MachineOperand &Op = MI.getOperand(I);
3838       if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
3839         continue;
3840 
3841       // MI is a PHI instruction.
3842       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
3843       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
3844 
3845       // Avoid creating no-op copies with the same src and dst reg class.  These
3846       // confuse some of the machine passes.
3847       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
3848     }
3849   }
3850 
3851   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
3852   // VGPR dest type and SGPR sources, insert copies so all operands are
3853   // VGPRs. This seems to help operand folding / the register coalescer.
3854   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
3855     MachineBasicBlock *MBB = MI.getParent();
3856     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
3857     if (RI.hasVGPRs(DstRC)) {
3858       // Update all the operands so they are VGPR register classes. These may
3859       // not be the same register class because REG_SEQUENCE supports mixing
3860       // subregister index types e.g. sub0_sub1 + sub2 + sub3
3861       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3862         MachineOperand &Op = MI.getOperand(I);
3863         if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
3864           continue;
3865 
3866         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
3867         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
3868         if (VRC == OpRC)
3869           continue;
3870 
3871         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
3872         Op.setIsKill();
3873       }
3874     }
3875 
3876     return;
3877   }
3878 
3879   // Legalize INSERT_SUBREG
3880   // src0 must have the same register class as dst
3881   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
3882     unsigned Dst = MI.getOperand(0).getReg();
3883     unsigned Src0 = MI.getOperand(1).getReg();
3884     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
3885     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
3886     if (DstRC != Src0RC) {
3887       MachineBasicBlock *MBB = MI.getParent();
3888       MachineOperand &Op = MI.getOperand(1);
3889       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
3890     }
3891     return;
3892   }
3893 
3894   // Legalize SI_INIT_M0
3895   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
3896     MachineOperand &Src = MI.getOperand(0);
3897     if (Src.isReg() && RI.hasVGPRs(MRI.getRegClass(Src.getReg())))
3898       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
3899     return;
3900   }
3901 
3902   // Legalize MIMG and MUBUF/MTBUF for shaders.
3903   //
3904   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
3905   // scratch memory access. In both cases, the legalization never involves
3906   // conversion to the addr64 form.
3907   if (isMIMG(MI) ||
3908       (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3909        (isMUBUF(MI) || isMTBUF(MI)))) {
3910     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
3911     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
3912       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
3913       SRsrc->setReg(SGPR);
3914     }
3915 
3916     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
3917     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
3918       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
3919       SSamp->setReg(SGPR);
3920     }
3921     return;
3922   }
3923 
3924   // Legalize MUBUF* instructions.
3925   int RsrcIdx =
3926       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
3927   if (RsrcIdx != -1) {
3928     // We have an MUBUF instruction
3929     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
3930     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
3931     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
3932                              RI.getRegClass(RsrcRC))) {
3933       // The operands are legal.
3934       // FIXME: We may need to legalize operands besided srsrc.
3935       return;
3936     }
3937 
3938     // Legalize a VGPR Rsrc.
3939     //
3940     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
3941     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
3942     // a zero-value SRsrc.
3943     //
3944     // If the instruction is _OFFSET (both idxen and offen disabled), and we
3945     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
3946     // above.
3947     //
3948     // Otherwise we are on non-ADDR64 hardware, and/or we have
3949     // idxen/offen/bothen and we fall back to a waterfall loop.
3950 
3951     MachineBasicBlock &MBB = *MI.getParent();
3952 
3953     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
3954     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
3955       // This is already an ADDR64 instruction so we need to add the pointer
3956       // extracted from the resource descriptor to the current value of VAddr.
3957       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3958       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3959       unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
3960 
3961       unsigned RsrcPtr, NewSRsrc;
3962       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
3963 
3964       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
3965       DebugLoc DL = MI.getDebugLoc();
3966       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), NewVAddrLo)
3967           .addReg(RsrcPtr, 0, AMDGPU::sub0)
3968           .addReg(VAddr->getReg(), 0, AMDGPU::sub0);
3969 
3970       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
3971       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e32), NewVAddrHi)
3972           .addReg(RsrcPtr, 0, AMDGPU::sub1)
3973           .addReg(VAddr->getReg(), 0, AMDGPU::sub1);
3974 
3975       // NewVaddr = {NewVaddrHi, NewVaddrLo}
3976       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
3977           .addReg(NewVAddrLo)
3978           .addImm(AMDGPU::sub0)
3979           .addReg(NewVAddrHi)
3980           .addImm(AMDGPU::sub1);
3981 
3982       VAddr->setReg(NewVAddr);
3983       Rsrc->setReg(NewSRsrc);
3984     } else if (!VAddr && ST.hasAddr64()) {
3985       // This instructions is the _OFFSET variant, so we need to convert it to
3986       // ADDR64.
3987       assert(MBB.getParent()->getSubtarget<GCNSubtarget>().getGeneration()
3988              < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
3989              "FIXME: Need to emit flat atomics here");
3990 
3991       unsigned RsrcPtr, NewSRsrc;
3992       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
3993 
3994       unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
3995       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
3996       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
3997       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
3998       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
3999 
4000       // Atomics rith return have have an additional tied operand and are
4001       // missing some of the special bits.
4002       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
4003       MachineInstr *Addr64;
4004 
4005       if (!VDataIn) {
4006         // Regular buffer load / store.
4007         MachineInstrBuilder MIB =
4008             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
4009                 .add(*VData)
4010                 .addReg(NewVAddr)
4011                 .addReg(NewSRsrc)
4012                 .add(*SOffset)
4013                 .add(*Offset);
4014 
4015         // Atomics do not have this operand.
4016         if (const MachineOperand *GLC =
4017                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
4018           MIB.addImm(GLC->getImm());
4019         }
4020 
4021         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
4022 
4023         if (const MachineOperand *TFE =
4024                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
4025           MIB.addImm(TFE->getImm());
4026         }
4027 
4028         MIB.cloneMemRefs(MI);
4029         Addr64 = MIB;
4030       } else {
4031         // Atomics with return.
4032         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
4033                      .add(*VData)
4034                      .add(*VDataIn)
4035                      .addReg(NewVAddr)
4036                      .addReg(NewSRsrc)
4037                      .add(*SOffset)
4038                      .add(*Offset)
4039                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
4040                      .cloneMemRefs(MI);
4041       }
4042 
4043       MI.removeFromParent();
4044 
4045       // NewVaddr = {NewVaddrHi, NewVaddrLo}
4046       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
4047               NewVAddr)
4048           .addReg(RsrcPtr, 0, AMDGPU::sub0)
4049           .addImm(AMDGPU::sub0)
4050           .addReg(RsrcPtr, 0, AMDGPU::sub1)
4051           .addImm(AMDGPU::sub1);
4052     } else {
4053       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
4054       // to SGPRs.
4055       loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
4056     }
4057   }
4058 }
4059 
4060 void SIInstrInfo::moveToVALU(MachineInstr &TopInst,
4061                              MachineDominatorTree *MDT) const {
4062   SetVectorType Worklist;
4063   Worklist.insert(&TopInst);
4064 
4065   while (!Worklist.empty()) {
4066     MachineInstr &Inst = *Worklist.pop_back_val();
4067     MachineBasicBlock *MBB = Inst.getParent();
4068     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4069 
4070     unsigned Opcode = Inst.getOpcode();
4071     unsigned NewOpcode = getVALUOp(Inst);
4072 
4073     // Handle some special cases
4074     switch (Opcode) {
4075     default:
4076       break;
4077     case AMDGPU::S_ADD_U64_PSEUDO:
4078     case AMDGPU::S_SUB_U64_PSEUDO:
4079       splitScalar64BitAddSub(Worklist, Inst, MDT);
4080       Inst.eraseFromParent();
4081       continue;
4082     case AMDGPU::S_ADD_I32:
4083     case AMDGPU::S_SUB_I32:
4084       // FIXME: The u32 versions currently selected use the carry.
4085       if (moveScalarAddSub(Worklist, Inst, MDT))
4086         continue;
4087 
4088       // Default handling
4089       break;
4090     case AMDGPU::S_AND_B64:
4091       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_AND_B32_e64, MDT);
4092       Inst.eraseFromParent();
4093       continue;
4094 
4095     case AMDGPU::S_OR_B64:
4096       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_OR_B32_e64, MDT);
4097       Inst.eraseFromParent();
4098       continue;
4099 
4100     case AMDGPU::S_XOR_B64:
4101       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_XOR_B32_e64, MDT);
4102       Inst.eraseFromParent();
4103       continue;
4104 
4105     case AMDGPU::S_NOT_B64:
4106       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::V_NOT_B32_e32);
4107       Inst.eraseFromParent();
4108       continue;
4109 
4110     case AMDGPU::S_BCNT1_I32_B64:
4111       splitScalar64BitBCNT(Worklist, Inst);
4112       Inst.eraseFromParent();
4113       continue;
4114 
4115     case AMDGPU::S_BFE_I64:
4116       splitScalar64BitBFE(Worklist, Inst);
4117       Inst.eraseFromParent();
4118       continue;
4119 
4120     case AMDGPU::S_LSHL_B32:
4121       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4122         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
4123         swapOperands(Inst);
4124       }
4125       break;
4126     case AMDGPU::S_ASHR_I32:
4127       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4128         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
4129         swapOperands(Inst);
4130       }
4131       break;
4132     case AMDGPU::S_LSHR_B32:
4133       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4134         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
4135         swapOperands(Inst);
4136       }
4137       break;
4138     case AMDGPU::S_LSHL_B64:
4139       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4140         NewOpcode = AMDGPU::V_LSHLREV_B64;
4141         swapOperands(Inst);
4142       }
4143       break;
4144     case AMDGPU::S_ASHR_I64:
4145       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4146         NewOpcode = AMDGPU::V_ASHRREV_I64;
4147         swapOperands(Inst);
4148       }
4149       break;
4150     case AMDGPU::S_LSHR_B64:
4151       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4152         NewOpcode = AMDGPU::V_LSHRREV_B64;
4153         swapOperands(Inst);
4154       }
4155       break;
4156 
4157     case AMDGPU::S_ABS_I32:
4158       lowerScalarAbs(Worklist, Inst);
4159       Inst.eraseFromParent();
4160       continue;
4161 
4162     case AMDGPU::S_CBRANCH_SCC0:
4163     case AMDGPU::S_CBRANCH_SCC1:
4164       // Clear unused bits of vcc
4165       BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
4166               AMDGPU::VCC)
4167           .addReg(AMDGPU::EXEC)
4168           .addReg(AMDGPU::VCC);
4169       break;
4170 
4171     case AMDGPU::S_BFE_U64:
4172     case AMDGPU::S_BFM_B64:
4173       llvm_unreachable("Moving this op to VALU not implemented");
4174 
4175     case AMDGPU::S_PACK_LL_B32_B16:
4176     case AMDGPU::S_PACK_LH_B32_B16:
4177     case AMDGPU::S_PACK_HH_B32_B16:
4178       movePackToVALU(Worklist, MRI, Inst);
4179       Inst.eraseFromParent();
4180       continue;
4181 
4182     case AMDGPU::S_XNOR_B32:
4183       lowerScalarXnor(Worklist, Inst);
4184       Inst.eraseFromParent();
4185       continue;
4186 
4187     case AMDGPU::S_XNOR_B64:
4188       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
4189       Inst.eraseFromParent();
4190       continue;
4191 
4192     case AMDGPU::S_BUFFER_LOAD_DWORD_SGPR:
4193     case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR:
4194     case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR:
4195     case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR:
4196     case AMDGPU::S_BUFFER_LOAD_DWORDX16_SGPR: {
4197       unsigned VDst;
4198       unsigned NewOpcode;
4199 
4200       switch(Opcode) {
4201       case AMDGPU::S_BUFFER_LOAD_DWORD_SGPR:
4202         NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_OFFEN;
4203         VDst = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4204         break;
4205       case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR:
4206         NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_OFFEN;
4207         VDst = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4208         break;
4209       case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR:
4210         NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_OFFEN;
4211         VDst = MRI.createVirtualRegister(&AMDGPU::VReg_128RegClass);
4212         break;
4213       case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR:
4214       case AMDGPU::S_BUFFER_LOAD_DWORDX16_SGPR:
4215         splitScalarBuffer(Worklist, Inst);
4216         Inst.eraseFromParent();
4217         continue;
4218       }
4219 
4220       const MachineOperand *VAddr = getNamedOperand(Inst, AMDGPU::OpName::soff);
4221       auto Add = MRI.getUniqueVRegDef(VAddr->getReg());
4222       unsigned Offset = 0;
4223 
4224       // FIXME: This isn't safe because the addressing mode doesn't work
4225       // correctly if vaddr is negative.
4226       //
4227       // FIXME: Should probably be done somewhere else, maybe SIFoldOperands.
4228       //
4229       // See if we can extract an immediate offset by recognizing one of these:
4230       //   V_ADD_I32_e32 dst, imm, src1
4231       //   V_ADD_I32_e32 dst, (S_MOV_B32 imm), src1
4232       // V_ADD will be removed by "Remove dead machine instructions".
4233       if (Add &&
4234           (Add->getOpcode() == AMDGPU::V_ADD_I32_e32 ||
4235            Add->getOpcode() == AMDGPU::V_ADD_U32_e32 ||
4236            Add->getOpcode() == AMDGPU::V_ADD_U32_e64)) {
4237         static const unsigned SrcNames[2] = {
4238           AMDGPU::OpName::src0,
4239           AMDGPU::OpName::src1,
4240         };
4241 
4242         // Find a literal offset in one of source operands.
4243         for (int i = 0; i < 2; i++) {
4244           const MachineOperand *Src =
4245             getNamedOperand(*Add, SrcNames[i]);
4246 
4247           if (Src->isReg()) {
4248             MachineInstr *Def = MRI.getUniqueVRegDef(Src->getReg());
4249             if (Def) {
4250               if (Def->isMoveImmediate())
4251                 Src = &Def->getOperand(1);
4252               else if (Def->isCopy()) {
4253                 auto Mov = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
4254                 if (Mov && Mov->isMoveImmediate()) {
4255                   Src = &Mov->getOperand(1);
4256                 }
4257               }
4258             }
4259           }
4260 
4261           if (Src) {
4262             if (Src->isImm())
4263               Offset = Src->getImm();
4264             else if (Src->isCImm())
4265               Offset = Src->getCImm()->getZExtValue();
4266           }
4267 
4268           if (Offset && isLegalMUBUFImmOffset(Offset)) {
4269             VAddr = getNamedOperand(*Add, SrcNames[!i]);
4270             break;
4271           }
4272 
4273           Offset = 0;
4274         }
4275       }
4276 
4277       MachineInstr *NewInstr =
4278           BuildMI(*MBB, Inst, Inst.getDebugLoc(),
4279                   get(NewOpcode), VDst)
4280               .add(*VAddr)                                        // vaddr
4281               .add(*getNamedOperand(Inst, AMDGPU::OpName::sbase)) // srsrc
4282               .addImm(0)                                          // soffset
4283               .addImm(Offset)                                     // offset
4284               .addImm(getNamedOperand(Inst, AMDGPU::OpName::glc)->getImm())
4285               .addImm(0) // slc
4286               .addImm(0) // tfe
4287               .cloneMemRefs(Inst)
4288               .getInstr();
4289 
4290       MRI.replaceRegWith(getNamedOperand(Inst, AMDGPU::OpName::sdst)->getReg(),
4291                          VDst);
4292       addUsersToMoveToVALUWorklist(VDst, MRI, Worklist);
4293       Inst.eraseFromParent();
4294 
4295       // Legalize all operands other than the offset. Notably, convert the srsrc
4296       // into SGPRs using v_readfirstlane if needed.
4297       legalizeOperands(*NewInstr, MDT);
4298       continue;
4299     }
4300     }
4301 
4302     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
4303       // We cannot move this instruction to the VALU, so we should try to
4304       // legalize its operands instead.
4305       legalizeOperands(Inst, MDT);
4306       continue;
4307     }
4308 
4309     // Use the new VALU Opcode.
4310     const MCInstrDesc &NewDesc = get(NewOpcode);
4311     Inst.setDesc(NewDesc);
4312 
4313     // Remove any references to SCC. Vector instructions can't read from it, and
4314     // We're just about to add the implicit use / defs of VCC, and we don't want
4315     // both.
4316     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
4317       MachineOperand &Op = Inst.getOperand(i);
4318       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
4319         Inst.RemoveOperand(i);
4320         addSCCDefUsersToVALUWorklist(Inst, Worklist);
4321       }
4322     }
4323 
4324     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
4325       // We are converting these to a BFE, so we need to add the missing
4326       // operands for the size and offset.
4327       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
4328       Inst.addOperand(MachineOperand::CreateImm(0));
4329       Inst.addOperand(MachineOperand::CreateImm(Size));
4330 
4331     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
4332       // The VALU version adds the second operand to the result, so insert an
4333       // extra 0 operand.
4334       Inst.addOperand(MachineOperand::CreateImm(0));
4335     }
4336 
4337     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
4338 
4339     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
4340       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
4341       // If we need to move this to VGPRs, we need to unpack the second operand
4342       // back into the 2 separate ones for bit offset and width.
4343       assert(OffsetWidthOp.isImm() &&
4344              "Scalar BFE is only implemented for constant width and offset");
4345       uint32_t Imm = OffsetWidthOp.getImm();
4346 
4347       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
4348       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
4349       Inst.RemoveOperand(2);                     // Remove old immediate.
4350       Inst.addOperand(MachineOperand::CreateImm(Offset));
4351       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
4352     }
4353 
4354     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
4355     unsigned NewDstReg = AMDGPU::NoRegister;
4356     if (HasDst) {
4357       unsigned DstReg = Inst.getOperand(0).getReg();
4358       if (TargetRegisterInfo::isPhysicalRegister(DstReg))
4359         continue;
4360 
4361       // Update the destination register class.
4362       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
4363       if (!NewDstRC)
4364         continue;
4365 
4366       if (Inst.isCopy() &&
4367           TargetRegisterInfo::isVirtualRegister(Inst.getOperand(1).getReg()) &&
4368           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
4369         // Instead of creating a copy where src and dst are the same register
4370         // class, we just replace all uses of dst with src.  These kinds of
4371         // copies interfere with the heuristics MachineSink uses to decide
4372         // whether or not to split a critical edge.  Since the pass assumes
4373         // that copies will end up as machine instructions and not be
4374         // eliminated.
4375         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
4376         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
4377         MRI.clearKillFlags(Inst.getOperand(1).getReg());
4378         Inst.getOperand(0).setReg(DstReg);
4379 
4380         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
4381         // these are deleted later, but at -O0 it would leave a suspicious
4382         // looking illegal copy of an undef register.
4383         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
4384           Inst.RemoveOperand(I);
4385         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
4386         continue;
4387       }
4388 
4389       NewDstReg = MRI.createVirtualRegister(NewDstRC);
4390       MRI.replaceRegWith(DstReg, NewDstReg);
4391     }
4392 
4393     // Legalize the operands
4394     legalizeOperands(Inst, MDT);
4395 
4396     if (HasDst)
4397      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
4398   }
4399 }
4400 
4401 // Add/sub require special handling to deal with carry outs.
4402 bool SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
4403                                    MachineDominatorTree *MDT) const {
4404   if (ST.hasAddNoCarry()) {
4405     // Assume there is no user of scc since we don't select this in that case.
4406     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
4407     // is used.
4408 
4409     MachineBasicBlock &MBB = *Inst.getParent();
4410     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4411 
4412     unsigned OldDstReg = Inst.getOperand(0).getReg();
4413     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4414 
4415     unsigned Opc = Inst.getOpcode();
4416     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
4417 
4418     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
4419       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
4420 
4421     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
4422     Inst.RemoveOperand(3);
4423 
4424     Inst.setDesc(get(NewOpc));
4425     Inst.addImplicitDefUseOperands(*MBB.getParent());
4426     MRI.replaceRegWith(OldDstReg, ResultReg);
4427     legalizeOperands(Inst, MDT);
4428 
4429     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4430     return true;
4431   }
4432 
4433   return false;
4434 }
4435 
4436 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
4437                                  MachineInstr &Inst) const {
4438   MachineBasicBlock &MBB = *Inst.getParent();
4439   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4440   MachineBasicBlock::iterator MII = Inst;
4441   DebugLoc DL = Inst.getDebugLoc();
4442 
4443   MachineOperand &Dest = Inst.getOperand(0);
4444   MachineOperand &Src = Inst.getOperand(1);
4445   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4446   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4447 
4448   unsigned SubOp = ST.hasAddNoCarry() ?
4449     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_I32_e32;
4450 
4451   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
4452     .addImm(0)
4453     .addReg(Src.getReg());
4454 
4455   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
4456     .addReg(Src.getReg())
4457     .addReg(TmpReg);
4458 
4459   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4460   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4461 }
4462 
4463 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
4464                                   MachineInstr &Inst) const {
4465   MachineBasicBlock &MBB = *Inst.getParent();
4466   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4467   MachineBasicBlock::iterator MII = Inst;
4468   const DebugLoc &DL = Inst.getDebugLoc();
4469 
4470   MachineOperand &Dest = Inst.getOperand(0);
4471   MachineOperand &Src0 = Inst.getOperand(1);
4472   MachineOperand &Src1 = Inst.getOperand(2);
4473 
4474   legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
4475   legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
4476 
4477   unsigned NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4478   if (ST.hasDLInsts()) {
4479     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
4480       .add(Src0)
4481       .add(Src1);
4482   } else {
4483     unsigned Xor = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4484     BuildMI(MBB, MII, DL, get(AMDGPU::V_XOR_B32_e64), Xor)
4485       .add(Src0)
4486       .add(Src1);
4487 
4488     BuildMI(MBB, MII, DL, get(AMDGPU::V_NOT_B32_e64), NewDest)
4489       .addReg(Xor);
4490   }
4491 
4492   MRI.replaceRegWith(Dest.getReg(), NewDest);
4493   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
4494 }
4495 
4496 void SIInstrInfo::splitScalar64BitUnaryOp(
4497     SetVectorType &Worklist, MachineInstr &Inst,
4498     unsigned Opcode) const {
4499   MachineBasicBlock &MBB = *Inst.getParent();
4500   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4501 
4502   MachineOperand &Dest = Inst.getOperand(0);
4503   MachineOperand &Src0 = Inst.getOperand(1);
4504   DebugLoc DL = Inst.getDebugLoc();
4505 
4506   MachineBasicBlock::iterator MII = Inst;
4507 
4508   const MCInstrDesc &InstDesc = get(Opcode);
4509   const TargetRegisterClass *Src0RC = Src0.isReg() ?
4510     MRI.getRegClass(Src0.getReg()) :
4511     &AMDGPU::SGPR_32RegClass;
4512 
4513   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
4514 
4515   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4516                                                        AMDGPU::sub0, Src0SubRC);
4517 
4518   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
4519   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
4520   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
4521 
4522   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
4523   BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
4524 
4525   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4526                                                        AMDGPU::sub1, Src0SubRC);
4527 
4528   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
4529   BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
4530 
4531   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
4532   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
4533     .addReg(DestSub0)
4534     .addImm(AMDGPU::sub0)
4535     .addReg(DestSub1)
4536     .addImm(AMDGPU::sub1);
4537 
4538   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4539 
4540   // We don't need to legalizeOperands here because for a single operand, src0
4541   // will support any kind of input.
4542 
4543   // Move all users of this moved value.
4544   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4545 }
4546 
4547 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
4548                                          MachineInstr &Inst,
4549                                          MachineDominatorTree *MDT) const {
4550   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4551 
4552   MachineBasicBlock &MBB = *Inst.getParent();
4553   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4554 
4555   unsigned FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4556   unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4557   unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4558 
4559   unsigned CarryReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
4560   unsigned DeadCarryReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
4561 
4562   MachineOperand &Dest = Inst.getOperand(0);
4563   MachineOperand &Src0 = Inst.getOperand(1);
4564   MachineOperand &Src1 = Inst.getOperand(2);
4565   const DebugLoc &DL = Inst.getDebugLoc();
4566   MachineBasicBlock::iterator MII = Inst;
4567 
4568   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
4569   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
4570   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
4571   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
4572 
4573   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4574                                                        AMDGPU::sub0, Src0SubRC);
4575   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4576                                                        AMDGPU::sub0, Src1SubRC);
4577 
4578 
4579   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4580                                                        AMDGPU::sub1, Src0SubRC);
4581   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4582                                                        AMDGPU::sub1, Src1SubRC);
4583 
4584   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
4585   MachineInstr *LoHalf =
4586     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
4587     .addReg(CarryReg, RegState::Define)
4588     .add(SrcReg0Sub0)
4589     .add(SrcReg1Sub0);
4590 
4591   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4592   MachineInstr *HiHalf =
4593     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
4594     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4595     .add(SrcReg0Sub1)
4596     .add(SrcReg1Sub1)
4597     .addReg(CarryReg, RegState::Kill);
4598 
4599   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
4600     .addReg(DestSub0)
4601     .addImm(AMDGPU::sub0)
4602     .addReg(DestSub1)
4603     .addImm(AMDGPU::sub1);
4604 
4605   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4606 
4607   // Try to legalize the operands in case we need to swap the order to keep it
4608   // valid.
4609   legalizeOperands(*LoHalf, MDT);
4610   legalizeOperands(*HiHalf, MDT);
4611 
4612   // Move all users of this moved vlaue.
4613   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4614 }
4615 
4616 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
4617                                            MachineInstr &Inst, unsigned Opcode,
4618                                            MachineDominatorTree *MDT) const {
4619   MachineBasicBlock &MBB = *Inst.getParent();
4620   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4621 
4622   MachineOperand &Dest = Inst.getOperand(0);
4623   MachineOperand &Src0 = Inst.getOperand(1);
4624   MachineOperand &Src1 = Inst.getOperand(2);
4625   DebugLoc DL = Inst.getDebugLoc();
4626 
4627   MachineBasicBlock::iterator MII = Inst;
4628 
4629   const MCInstrDesc &InstDesc = get(Opcode);
4630   const TargetRegisterClass *Src0RC = Src0.isReg() ?
4631     MRI.getRegClass(Src0.getReg()) :
4632     &AMDGPU::SGPR_32RegClass;
4633 
4634   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
4635   const TargetRegisterClass *Src1RC = Src1.isReg() ?
4636     MRI.getRegClass(Src1.getReg()) :
4637     &AMDGPU::SGPR_32RegClass;
4638 
4639   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
4640 
4641   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4642                                                        AMDGPU::sub0, Src0SubRC);
4643   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4644                                                        AMDGPU::sub0, Src1SubRC);
4645 
4646   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
4647   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
4648   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
4649 
4650   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
4651   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
4652                               .add(SrcReg0Sub0)
4653                               .add(SrcReg1Sub0);
4654 
4655   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4656                                                        AMDGPU::sub1, Src0SubRC);
4657   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4658                                                        AMDGPU::sub1, Src1SubRC);
4659 
4660   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
4661   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
4662                               .add(SrcReg0Sub1)
4663                               .add(SrcReg1Sub1);
4664 
4665   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
4666   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
4667     .addReg(DestSub0)
4668     .addImm(AMDGPU::sub0)
4669     .addReg(DestSub1)
4670     .addImm(AMDGPU::sub1);
4671 
4672   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4673 
4674   // Try to legalize the operands in case we need to swap the order to keep it
4675   // valid.
4676   legalizeOperands(LoHalf, MDT);
4677   legalizeOperands(HiHalf, MDT);
4678 
4679   // Move all users of this moved vlaue.
4680   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4681 }
4682 
4683 void SIInstrInfo::splitScalar64BitBCNT(
4684     SetVectorType &Worklist, MachineInstr &Inst) const {
4685   MachineBasicBlock &MBB = *Inst.getParent();
4686   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4687 
4688   MachineBasicBlock::iterator MII = Inst;
4689   DebugLoc DL = Inst.getDebugLoc();
4690 
4691   MachineOperand &Dest = Inst.getOperand(0);
4692   MachineOperand &Src = Inst.getOperand(1);
4693 
4694   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
4695   const TargetRegisterClass *SrcRC = Src.isReg() ?
4696     MRI.getRegClass(Src.getReg()) :
4697     &AMDGPU::SGPR_32RegClass;
4698 
4699   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4700   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4701 
4702   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
4703 
4704   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
4705                                                       AMDGPU::sub0, SrcSubRC);
4706   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
4707                                                       AMDGPU::sub1, SrcSubRC);
4708 
4709   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
4710 
4711   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
4712 
4713   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4714 
4715   // We don't need to legalize operands here. src0 for etiher instruction can be
4716   // an SGPR, and the second input is unused or determined here.
4717   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4718 }
4719 
4720 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
4721                                       MachineInstr &Inst) const {
4722   MachineBasicBlock &MBB = *Inst.getParent();
4723   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4724   MachineBasicBlock::iterator MII = Inst;
4725   DebugLoc DL = Inst.getDebugLoc();
4726 
4727   MachineOperand &Dest = Inst.getOperand(0);
4728   uint32_t Imm = Inst.getOperand(2).getImm();
4729   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
4730   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
4731 
4732   (void) Offset;
4733 
4734   // Only sext_inreg cases handled.
4735   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
4736          Offset == 0 && "Not implemented");
4737 
4738   if (BitWidth < 32) {
4739     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4740     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4741     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4742 
4743     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
4744         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
4745         .addImm(0)
4746         .addImm(BitWidth);
4747 
4748     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
4749       .addImm(31)
4750       .addReg(MidRegLo);
4751 
4752     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
4753       .addReg(MidRegLo)
4754       .addImm(AMDGPU::sub0)
4755       .addReg(MidRegHi)
4756       .addImm(AMDGPU::sub1);
4757 
4758     MRI.replaceRegWith(Dest.getReg(), ResultReg);
4759     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4760     return;
4761   }
4762 
4763   MachineOperand &Src = Inst.getOperand(1);
4764   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4765   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4766 
4767   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
4768     .addImm(31)
4769     .addReg(Src.getReg(), 0, AMDGPU::sub0);
4770 
4771   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
4772     .addReg(Src.getReg(), 0, AMDGPU::sub0)
4773     .addImm(AMDGPU::sub0)
4774     .addReg(TmpReg)
4775     .addImm(AMDGPU::sub1);
4776 
4777   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4778   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4779 }
4780 
4781 void SIInstrInfo::splitScalarBuffer(SetVectorType &Worklist,
4782                                     MachineInstr &Inst) const {
4783   MachineBasicBlock &MBB = *Inst.getParent();
4784   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4785 
4786   MachineBasicBlock::iterator MII = Inst;
4787   auto &DL = Inst.getDebugLoc();
4788 
4789   MachineOperand &Dest = *getNamedOperand(Inst, AMDGPU::OpName::sdst);;
4790   MachineOperand &Rsrc = *getNamedOperand(Inst, AMDGPU::OpName::sbase);
4791   MachineOperand &Offset = *getNamedOperand(Inst, AMDGPU::OpName::soff);
4792   MachineOperand &Glc = *getNamedOperand(Inst, AMDGPU::OpName::glc);
4793 
4794   unsigned Opcode = Inst.getOpcode();
4795   unsigned NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_OFFEN;
4796   unsigned Count = 0;
4797   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
4798   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
4799 
4800   switch(Opcode) {
4801   default:
4802     return;
4803   case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR:
4804     Count = 2;
4805     break;
4806   case AMDGPU::S_BUFFER_LOAD_DWORDX16_SGPR:
4807     Count = 4;
4808     break;
4809   }
4810 
4811   // FIXME: Should also attempt to build VAddr and Offset like the non-split
4812   // case (see call site for this function)
4813 
4814   // Create a vector of result registers
4815   SmallVector<unsigned, 8> ResultRegs;
4816   for (unsigned i = 0; i < Count ; ++i) {
4817     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_128RegClass);
4818     MachineInstr &NewMI = *BuildMI(MBB, MII, DL, get(NewOpcode), ResultReg)
4819       .addReg(Offset.getReg())  // offset
4820       .addReg(Rsrc.getReg())    // rsrc
4821       .addImm(0)                // soffset
4822       .addImm(i << 4)           // inst_offset
4823       .addImm(Glc.getImm())     // glc
4824       .addImm(0)                // slc
4825       .addImm(0)                // tfe
4826       .addMemOperand(*Inst.memoperands_begin());
4827     // Extract the 4 32 bit sub-registers from the result to add into the final REG_SEQUENCE
4828     auto &NewDestOp = NewMI.getOperand(0);
4829     for (unsigned i = 0 ; i < 4 ; i++)
4830       ResultRegs.push_back(buildExtractSubReg(MII, MRI, NewDestOp, &AMDGPU::VReg_128RegClass,
4831                                               RI.getSubRegFromChannel(i), &AMDGPU::VGPR_32RegClass));
4832   }
4833   // Create a new combined result to replace original with
4834   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
4835   MachineInstrBuilder CombinedResBuilder = BuildMI(MBB, MII, DL,
4836                                   get(TargetOpcode::REG_SEQUENCE), FullDestReg);
4837 
4838   for (unsigned i = 0 ; i < Count * 4 ; ++i) {
4839     CombinedResBuilder
4840       .addReg(ResultRegs[i])
4841       .addImm(RI.getSubRegFromChannel(i));
4842   }
4843 
4844   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4845   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4846 }
4847 
4848 void SIInstrInfo::addUsersToMoveToVALUWorklist(
4849   unsigned DstReg,
4850   MachineRegisterInfo &MRI,
4851   SetVectorType &Worklist) const {
4852   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
4853          E = MRI.use_end(); I != E;) {
4854     MachineInstr &UseMI = *I->getParent();
4855     if (!canReadVGPR(UseMI, I.getOperandNo())) {
4856       Worklist.insert(&UseMI);
4857 
4858       do {
4859         ++I;
4860       } while (I != E && I->getParent() == &UseMI);
4861     } else {
4862       ++I;
4863     }
4864   }
4865 }
4866 
4867 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
4868                                  MachineRegisterInfo &MRI,
4869                                  MachineInstr &Inst) const {
4870   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4871   MachineBasicBlock *MBB = Inst.getParent();
4872   MachineOperand &Src0 = Inst.getOperand(1);
4873   MachineOperand &Src1 = Inst.getOperand(2);
4874   const DebugLoc &DL = Inst.getDebugLoc();
4875 
4876   switch (Inst.getOpcode()) {
4877   case AMDGPU::S_PACK_LL_B32_B16: {
4878     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4879     unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4880 
4881     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
4882     // 0.
4883     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
4884       .addImm(0xffff);
4885 
4886     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
4887       .addReg(ImmReg, RegState::Kill)
4888       .add(Src0);
4889 
4890     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32), ResultReg)
4891       .add(Src1)
4892       .addImm(16)
4893       .addReg(TmpReg, RegState::Kill);
4894     break;
4895   }
4896   case AMDGPU::S_PACK_LH_B32_B16: {
4897     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4898     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
4899       .addImm(0xffff);
4900     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32), ResultReg)
4901       .addReg(ImmReg, RegState::Kill)
4902       .add(Src0)
4903       .add(Src1);
4904     break;
4905   }
4906   case AMDGPU::S_PACK_HH_B32_B16: {
4907     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4908     unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4909     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
4910       .addImm(16)
4911       .add(Src0);
4912     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
4913       .addImm(0xffff0000);
4914     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32), ResultReg)
4915       .add(Src1)
4916       .addReg(ImmReg, RegState::Kill)
4917       .addReg(TmpReg, RegState::Kill);
4918     break;
4919   }
4920   default:
4921     llvm_unreachable("unhandled s_pack_* instruction");
4922   }
4923 
4924   MachineOperand &Dest = Inst.getOperand(0);
4925   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4926   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4927 }
4928 
4929 void SIInstrInfo::addSCCDefUsersToVALUWorklist(
4930     MachineInstr &SCCDefInst, SetVectorType &Worklist) const {
4931   // This assumes that all the users of SCC are in the same block
4932   // as the SCC def.
4933   for (MachineInstr &MI :
4934        make_range(MachineBasicBlock::iterator(SCCDefInst),
4935                       SCCDefInst.getParent()->end())) {
4936     // Exit if we find another SCC def.
4937     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
4938       return;
4939 
4940     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI) != -1)
4941       Worklist.insert(&MI);
4942   }
4943 }
4944 
4945 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
4946   const MachineInstr &Inst) const {
4947   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
4948 
4949   switch (Inst.getOpcode()) {
4950   // For target instructions, getOpRegClass just returns the virtual register
4951   // class associated with the operand, so we need to find an equivalent VGPR
4952   // register class in order to move the instruction to the VALU.
4953   case AMDGPU::COPY:
4954   case AMDGPU::PHI:
4955   case AMDGPU::REG_SEQUENCE:
4956   case AMDGPU::INSERT_SUBREG:
4957   case AMDGPU::WQM:
4958   case AMDGPU::WWM:
4959     if (RI.hasVGPRs(NewDstRC))
4960       return nullptr;
4961 
4962     NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
4963     if (!NewDstRC)
4964       return nullptr;
4965     return NewDstRC;
4966   default:
4967     return NewDstRC;
4968   }
4969 }
4970 
4971 // Find the one SGPR operand we are allowed to use.
4972 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
4973                                    int OpIndices[3]) const {
4974   const MCInstrDesc &Desc = MI.getDesc();
4975 
4976   // Find the one SGPR operand we are allowed to use.
4977   //
4978   // First we need to consider the instruction's operand requirements before
4979   // legalizing. Some operands are required to be SGPRs, such as implicit uses
4980   // of VCC, but we are still bound by the constant bus requirement to only use
4981   // one.
4982   //
4983   // If the operand's class is an SGPR, we can never move it.
4984 
4985   unsigned SGPRReg = findImplicitSGPRRead(MI);
4986   if (SGPRReg != AMDGPU::NoRegister)
4987     return SGPRReg;
4988 
4989   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
4990   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4991 
4992   for (unsigned i = 0; i < 3; ++i) {
4993     int Idx = OpIndices[i];
4994     if (Idx == -1)
4995       break;
4996 
4997     const MachineOperand &MO = MI.getOperand(Idx);
4998     if (!MO.isReg())
4999       continue;
5000 
5001     // Is this operand statically required to be an SGPR based on the operand
5002     // constraints?
5003     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
5004     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
5005     if (IsRequiredSGPR)
5006       return MO.getReg();
5007 
5008     // If this could be a VGPR or an SGPR, Check the dynamic register class.
5009     unsigned Reg = MO.getReg();
5010     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
5011     if (RI.isSGPRClass(RegRC))
5012       UsedSGPRs[i] = Reg;
5013   }
5014 
5015   // We don't have a required SGPR operand, so we have a bit more freedom in
5016   // selecting operands to move.
5017 
5018   // Try to select the most used SGPR. If an SGPR is equal to one of the
5019   // others, we choose that.
5020   //
5021   // e.g.
5022   // V_FMA_F32 v0, s0, s0, s0 -> No moves
5023   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
5024 
5025   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
5026   // prefer those.
5027 
5028   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
5029     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
5030       SGPRReg = UsedSGPRs[0];
5031   }
5032 
5033   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
5034     if (UsedSGPRs[1] == UsedSGPRs[2])
5035       SGPRReg = UsedSGPRs[1];
5036   }
5037 
5038   return SGPRReg;
5039 }
5040 
5041 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
5042                                              unsigned OperandName) const {
5043   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
5044   if (Idx == -1)
5045     return nullptr;
5046 
5047   return &MI.getOperand(Idx);
5048 }
5049 
5050 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
5051   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
5052   if (ST.isAmdHsaOS()) {
5053     // Set ATC = 1. GFX9 doesn't have this bit.
5054     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5055       RsrcDataFormat |= (1ULL << 56);
5056 
5057     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
5058     // BTW, it disables TC L2 and therefore decreases performance.
5059     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
5060       RsrcDataFormat |= (2ULL << 59);
5061   }
5062 
5063   return RsrcDataFormat;
5064 }
5065 
5066 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
5067   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
5068                     AMDGPU::RSRC_TID_ENABLE |
5069                     0xffffffff; // Size;
5070 
5071   // GFX9 doesn't have ELEMENT_SIZE.
5072   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
5073     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
5074     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
5075   }
5076 
5077   // IndexStride = 64.
5078   Rsrc23 |= UINT64_C(3) << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
5079 
5080   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
5081   // Clear them unless we want a huge stride.
5082   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5083     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
5084 
5085   return Rsrc23;
5086 }
5087 
5088 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
5089   unsigned Opc = MI.getOpcode();
5090 
5091   return isSMRD(Opc);
5092 }
5093 
5094 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
5095   unsigned Opc = MI.getOpcode();
5096 
5097   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
5098 }
5099 
5100 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
5101                                     int &FrameIndex) const {
5102   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5103   if (!Addr || !Addr->isFI())
5104     return AMDGPU::NoRegister;
5105 
5106   assert(!MI.memoperands_empty() &&
5107          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
5108 
5109   FrameIndex = Addr->getIndex();
5110   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
5111 }
5112 
5113 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
5114                                         int &FrameIndex) const {
5115   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
5116   assert(Addr && Addr->isFI());
5117   FrameIndex = Addr->getIndex();
5118   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
5119 }
5120 
5121 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
5122                                           int &FrameIndex) const {
5123   if (!MI.mayLoad())
5124     return AMDGPU::NoRegister;
5125 
5126   if (isMUBUF(MI) || isVGPRSpill(MI))
5127     return isStackAccess(MI, FrameIndex);
5128 
5129   if (isSGPRSpill(MI))
5130     return isSGPRStackAccess(MI, FrameIndex);
5131 
5132   return AMDGPU::NoRegister;
5133 }
5134 
5135 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
5136                                          int &FrameIndex) const {
5137   if (!MI.mayStore())
5138     return AMDGPU::NoRegister;
5139 
5140   if (isMUBUF(MI) || isVGPRSpill(MI))
5141     return isStackAccess(MI, FrameIndex);
5142 
5143   if (isSGPRSpill(MI))
5144     return isSGPRStackAccess(MI, FrameIndex);
5145 
5146   return AMDGPU::NoRegister;
5147 }
5148 
5149 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
5150   unsigned Size = 0;
5151   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
5152   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
5153   while (++I != E && I->isInsideBundle()) {
5154     assert(!I->isBundle() && "No nested bundle!");
5155     Size += getInstSizeInBytes(*I);
5156   }
5157 
5158   return Size;
5159 }
5160 
5161 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
5162   unsigned Opc = MI.getOpcode();
5163   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
5164   unsigned DescSize = Desc.getSize();
5165 
5166   // If we have a definitive size, we can use it. Otherwise we need to inspect
5167   // the operands to know the size.
5168   if (isFixedSize(MI))
5169     return DescSize;
5170 
5171   // 4-byte instructions may have a 32-bit literal encoded after them. Check
5172   // operands that coud ever be literals.
5173   if (isVALU(MI) || isSALU(MI)) {
5174     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
5175     if (Src0Idx == -1)
5176       return DescSize; // No operands.
5177 
5178     if (isLiteralConstantLike(MI.getOperand(Src0Idx), Desc.OpInfo[Src0Idx]))
5179       return DescSize + 4;
5180 
5181     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5182     if (Src1Idx == -1)
5183       return DescSize;
5184 
5185     if (isLiteralConstantLike(MI.getOperand(Src1Idx), Desc.OpInfo[Src1Idx]))
5186       return DescSize + 4;
5187 
5188     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
5189     if (Src2Idx == -1)
5190       return DescSize;
5191 
5192     if (isLiteralConstantLike(MI.getOperand(Src2Idx), Desc.OpInfo[Src2Idx]))
5193       return DescSize + 4;
5194 
5195     return DescSize;
5196   }
5197 
5198   switch (Opc) {
5199   case TargetOpcode::IMPLICIT_DEF:
5200   case TargetOpcode::KILL:
5201   case TargetOpcode::DBG_VALUE:
5202   case TargetOpcode::EH_LABEL:
5203     return 0;
5204   case TargetOpcode::BUNDLE:
5205     return getInstBundleSize(MI);
5206   case TargetOpcode::INLINEASM: {
5207     const MachineFunction *MF = MI.getParent()->getParent();
5208     const char *AsmStr = MI.getOperand(0).getSymbolName();
5209     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
5210   }
5211   default:
5212     return DescSize;
5213   }
5214 }
5215 
5216 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
5217   if (!isFLAT(MI))
5218     return false;
5219 
5220   if (MI.memoperands_empty())
5221     return true;
5222 
5223   for (const MachineMemOperand *MMO : MI.memoperands()) {
5224     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
5225       return true;
5226   }
5227   return false;
5228 }
5229 
5230 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
5231   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
5232 }
5233 
5234 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
5235                                             MachineBasicBlock *IfEnd) const {
5236   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
5237   assert(TI != IfEntry->end());
5238 
5239   MachineInstr *Branch = &(*TI);
5240   MachineFunction *MF = IfEntry->getParent();
5241   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
5242 
5243   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
5244     unsigned DstReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5245     MachineInstr *SIIF =
5246         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
5247             .add(Branch->getOperand(0))
5248             .add(Branch->getOperand(1));
5249     MachineInstr *SIEND =
5250         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
5251             .addReg(DstReg);
5252 
5253     IfEntry->erase(TI);
5254     IfEntry->insert(IfEntry->end(), SIIF);
5255     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
5256   }
5257 }
5258 
5259 void SIInstrInfo::convertNonUniformLoopRegion(
5260     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
5261   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
5262   // We expect 2 terminators, one conditional and one unconditional.
5263   assert(TI != LoopEnd->end());
5264 
5265   MachineInstr *Branch = &(*TI);
5266   MachineFunction *MF = LoopEnd->getParent();
5267   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
5268 
5269   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
5270 
5271     unsigned DstReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5272     unsigned BackEdgeReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5273     MachineInstrBuilder HeaderPHIBuilder =
5274         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
5275     for (MachineBasicBlock::pred_iterator PI = LoopEntry->pred_begin(),
5276                                           E = LoopEntry->pred_end();
5277          PI != E; ++PI) {
5278       if (*PI == LoopEnd) {
5279         HeaderPHIBuilder.addReg(BackEdgeReg);
5280       } else {
5281         MachineBasicBlock *PMBB = *PI;
5282         unsigned ZeroReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5283         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
5284                              ZeroReg, 0);
5285         HeaderPHIBuilder.addReg(ZeroReg);
5286       }
5287       HeaderPHIBuilder.addMBB(*PI);
5288     }
5289     MachineInstr *HeaderPhi = HeaderPHIBuilder;
5290     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
5291                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
5292                                   .addReg(DstReg)
5293                                   .add(Branch->getOperand(0));
5294     MachineInstr *SILOOP =
5295         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
5296             .addReg(BackEdgeReg)
5297             .addMBB(LoopEntry);
5298 
5299     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
5300     LoopEnd->erase(TI);
5301     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
5302     LoopEnd->insert(LoopEnd->end(), SILOOP);
5303   }
5304 }
5305 
5306 ArrayRef<std::pair<int, const char *>>
5307 SIInstrInfo::getSerializableTargetIndices() const {
5308   static const std::pair<int, const char *> TargetIndices[] = {
5309       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
5310       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
5311       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
5312       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
5313       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
5314   return makeArrayRef(TargetIndices);
5315 }
5316 
5317 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
5318 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
5319 ScheduleHazardRecognizer *
5320 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
5321                                             const ScheduleDAG *DAG) const {
5322   return new GCNHazardRecognizer(DAG->MF);
5323 }
5324 
5325 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
5326 /// pass.
5327 ScheduleHazardRecognizer *
5328 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
5329   return new GCNHazardRecognizer(MF);
5330 }
5331 
5332 std::pair<unsigned, unsigned>
5333 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
5334   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
5335 }
5336 
5337 ArrayRef<std::pair<unsigned, const char *>>
5338 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
5339   static const std::pair<unsigned, const char *> TargetFlags[] = {
5340     { MO_GOTPCREL, "amdgpu-gotprel" },
5341     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
5342     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
5343     { MO_REL32_LO, "amdgpu-rel32-lo" },
5344     { MO_REL32_HI, "amdgpu-rel32-hi" }
5345   };
5346 
5347   return makeArrayRef(TargetFlags);
5348 }
5349 
5350 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
5351   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
5352          MI.modifiesRegister(AMDGPU::EXEC, &RI);
5353 }
5354 
5355 MachineInstrBuilder
5356 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
5357                            MachineBasicBlock::iterator I,
5358                            const DebugLoc &DL,
5359                            unsigned DestReg) const {
5360   if (ST.hasAddNoCarry())
5361     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
5362 
5363   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5364   unsigned UnusedCarry = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5365   MRI.setRegAllocationHint(UnusedCarry, 0, AMDGPU::VCC);
5366 
5367   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_I32_e64), DestReg)
5368            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
5369 }
5370 
5371 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
5372   switch (Opcode) {
5373   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
5374   case AMDGPU::SI_KILL_I1_TERMINATOR:
5375     return true;
5376   default:
5377     return false;
5378   }
5379 }
5380 
5381 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
5382   switch (Opcode) {
5383   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
5384     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
5385   case AMDGPU::SI_KILL_I1_PSEUDO:
5386     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
5387   default:
5388     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
5389   }
5390 }
5391 
5392 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
5393   if (!isSMRD(MI))
5394     return false;
5395 
5396   // Check that it is using a buffer resource.
5397   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
5398   if (Idx == -1) // e.g. s_memtime
5399     return false;
5400 
5401   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
5402   return RCID == AMDGPU::SReg_128RegClassID;
5403 }
5404 
5405 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
5406 enum SIEncodingFamily {
5407   SI = 0,
5408   VI = 1,
5409   SDWA = 2,
5410   SDWA9 = 3,
5411   GFX80 = 4,
5412   GFX9 = 5
5413 };
5414 
5415 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
5416   switch (ST.getGeneration()) {
5417   default:
5418     break;
5419   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
5420   case AMDGPUSubtarget::SEA_ISLANDS:
5421     return SIEncodingFamily::SI;
5422   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
5423   case AMDGPUSubtarget::GFX9:
5424     return SIEncodingFamily::VI;
5425   }
5426   llvm_unreachable("Unknown subtarget generation!");
5427 }
5428 
5429 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
5430   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
5431 
5432   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
5433     ST.getGeneration() >= AMDGPUSubtarget::GFX9)
5434     Gen = SIEncodingFamily::GFX9;
5435 
5436   if (get(Opcode).TSFlags & SIInstrFlags::SDWA)
5437     Gen = ST.getGeneration() == AMDGPUSubtarget::GFX9 ? SIEncodingFamily::SDWA9
5438                                                       : SIEncodingFamily::SDWA;
5439   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
5440   // subtarget has UnpackedD16VMem feature.
5441   // TODO: remove this when we discard GFX80 encoding.
5442   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
5443     Gen = SIEncodingFamily::GFX80;
5444 
5445   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
5446 
5447   // -1 means that Opcode is already a native instruction.
5448   if (MCOp == -1)
5449     return Opcode;
5450 
5451   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
5452   // no encoding in the given subtarget generation.
5453   if (MCOp == (uint16_t)-1)
5454     return -1;
5455 
5456   return MCOp;
5457 }
5458