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