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 /// \brief SI Implementation of TargetInstrInfo.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "SIInstrInfo.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "GCNHazardRecognizer.h"
18 #include "SIDefines.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/ScheduleDAG.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/Support/Debug.h"
28 
29 using namespace llvm;
30 
31 // Must be at least 4 to be able to branch over minimum unconditional branch
32 // code. This is only for making it possible to write reasonably small tests for
33 // long branches.
34 static cl::opt<unsigned>
35 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
36                  cl::desc("Restrict range of branch instructions (DEBUG)"));
37 
38 SIInstrInfo::SIInstrInfo(const SISubtarget &ST)
39   : AMDGPUInstrInfo(ST), RI(ST), ST(ST) {}
40 
41 //===----------------------------------------------------------------------===//
42 // TargetInstrInfo callbacks
43 //===----------------------------------------------------------------------===//
44 
45 static unsigned getNumOperandsNoGlue(SDNode *Node) {
46   unsigned N = Node->getNumOperands();
47   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
48     --N;
49   return N;
50 }
51 
52 static SDValue findChainOperand(SDNode *Load) {
53   SDValue LastOp = Load->getOperand(getNumOperandsNoGlue(Load) - 1);
54   assert(LastOp.getValueType() == MVT::Other && "Chain missing from load node");
55   return LastOp;
56 }
57 
58 /// \brief Returns true if both nodes have the same value for the given
59 ///        operand \p Op, or if both nodes do not have this operand.
60 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
61   unsigned Opc0 = N0->getMachineOpcode();
62   unsigned Opc1 = N1->getMachineOpcode();
63 
64   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
65   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
66 
67   if (Op0Idx == -1 && Op1Idx == -1)
68     return true;
69 
70 
71   if ((Op0Idx == -1 && Op1Idx != -1) ||
72       (Op1Idx == -1 && Op0Idx != -1))
73     return false;
74 
75   // getNamedOperandIdx returns the index for the MachineInstr's operands,
76   // which includes the result as the first operand. We are indexing into the
77   // MachineSDNode's operands, so we need to skip the result operand to get
78   // the real index.
79   --Op0Idx;
80   --Op1Idx;
81 
82   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
83 }
84 
85 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
86                                                     AliasAnalysis *AA) const {
87   // TODO: The generic check fails for VALU instructions that should be
88   // rematerializable due to implicit reads of exec. We really want all of the
89   // generic logic for this except for this.
90   switch (MI.getOpcode()) {
91   case AMDGPU::V_MOV_B32_e32:
92   case AMDGPU::V_MOV_B32_e64:
93   case AMDGPU::V_MOV_B64_PSEUDO:
94     return true;
95   default:
96     return false;
97   }
98 }
99 
100 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
101                                           int64_t &Offset0,
102                                           int64_t &Offset1) const {
103   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
104     return false;
105 
106   unsigned Opc0 = Load0->getMachineOpcode();
107   unsigned Opc1 = Load1->getMachineOpcode();
108 
109   // Make sure both are actually loads.
110   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
111     return false;
112 
113   if (isDS(Opc0) && isDS(Opc1)) {
114 
115     // FIXME: Handle this case:
116     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
117       return false;
118 
119     // Check base reg.
120     if (Load0->getOperand(1) != Load1->getOperand(1))
121       return false;
122 
123     // Check chain.
124     if (findChainOperand(Load0) != findChainOperand(Load1))
125       return false;
126 
127     // Skip read2 / write2 variants for simplicity.
128     // TODO: We should report true if the used offsets are adjacent (excluded
129     // st64 versions).
130     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
131         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
132       return false;
133 
134     Offset0 = cast<ConstantSDNode>(Load0->getOperand(2))->getZExtValue();
135     Offset1 = cast<ConstantSDNode>(Load1->getOperand(2))->getZExtValue();
136     return true;
137   }
138 
139   if (isSMRD(Opc0) && isSMRD(Opc1)) {
140     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
141 
142     // Check base reg.
143     if (Load0->getOperand(0) != Load1->getOperand(0))
144       return false;
145 
146     const ConstantSDNode *Load0Offset =
147         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
148     const ConstantSDNode *Load1Offset =
149         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
150 
151     if (!Load0Offset || !Load1Offset)
152       return false;
153 
154     // Check chain.
155     if (findChainOperand(Load0) != findChainOperand(Load1))
156       return false;
157 
158     Offset0 = Load0Offset->getZExtValue();
159     Offset1 = Load1Offset->getZExtValue();
160     return true;
161   }
162 
163   // MUBUF and MTBUF can access the same addresses.
164   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
165 
166     // MUBUF and MTBUF have vaddr at different indices.
167     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
168         findChainOperand(Load0) != findChainOperand(Load1) ||
169         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
170         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
171       return false;
172 
173     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
174     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
175 
176     if (OffIdx0 == -1 || OffIdx1 == -1)
177       return false;
178 
179     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
180     // inlcude the output in the operand list, but SDNodes don't, we need to
181     // subtract the index by one.
182     --OffIdx0;
183     --OffIdx1;
184 
185     SDValue Off0 = Load0->getOperand(OffIdx0);
186     SDValue Off1 = Load1->getOperand(OffIdx1);
187 
188     // The offset might be a FrameIndexSDNode.
189     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
190       return false;
191 
192     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
193     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
194     return true;
195   }
196 
197   return false;
198 }
199 
200 static bool isStride64(unsigned Opc) {
201   switch (Opc) {
202   case AMDGPU::DS_READ2ST64_B32:
203   case AMDGPU::DS_READ2ST64_B64:
204   case AMDGPU::DS_WRITE2ST64_B32:
205   case AMDGPU::DS_WRITE2ST64_B64:
206     return true;
207   default:
208     return false;
209   }
210 }
211 
212 bool SIInstrInfo::getMemOpBaseRegImmOfs(MachineInstr &LdSt, unsigned &BaseReg,
213                                         int64_t &Offset,
214                                         const TargetRegisterInfo *TRI) const {
215   unsigned Opc = LdSt.getOpcode();
216 
217   if (isDS(LdSt)) {
218     const MachineOperand *OffsetImm =
219         getNamedOperand(LdSt, AMDGPU::OpName::offset);
220     if (OffsetImm) {
221       // Normal, single offset LDS instruction.
222       const MachineOperand *AddrReg =
223           getNamedOperand(LdSt, AMDGPU::OpName::addr);
224 
225       BaseReg = AddrReg->getReg();
226       Offset = OffsetImm->getImm();
227       return true;
228     }
229 
230     // The 2 offset instructions use offset0 and offset1 instead. We can treat
231     // these as a load with a single offset if the 2 offsets are consecutive. We
232     // will use this for some partially aligned loads.
233     const MachineOperand *Offset0Imm =
234         getNamedOperand(LdSt, AMDGPU::OpName::offset0);
235     const MachineOperand *Offset1Imm =
236         getNamedOperand(LdSt, AMDGPU::OpName::offset1);
237 
238     uint8_t Offset0 = Offset0Imm->getImm();
239     uint8_t Offset1 = Offset1Imm->getImm();
240 
241     if (Offset1 > Offset0 && Offset1 - Offset0 == 1) {
242       // Each of these offsets is in element sized units, so we need to convert
243       // to bytes of the individual reads.
244 
245       unsigned EltSize;
246       if (LdSt.mayLoad())
247         EltSize = getOpRegClass(LdSt, 0)->getSize() / 2;
248       else {
249         assert(LdSt.mayStore());
250         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
251         EltSize = getOpRegClass(LdSt, Data0Idx)->getSize();
252       }
253 
254       if (isStride64(Opc))
255         EltSize *= 64;
256 
257       const MachineOperand *AddrReg =
258           getNamedOperand(LdSt, AMDGPU::OpName::addr);
259       BaseReg = AddrReg->getReg();
260       Offset = EltSize * Offset0;
261       return true;
262     }
263 
264     return false;
265   }
266 
267   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
268     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
269     if (SOffset && SOffset->isReg())
270       return false;
271 
272     const MachineOperand *AddrReg =
273         getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
274     if (!AddrReg)
275       return false;
276 
277     const MachineOperand *OffsetImm =
278         getNamedOperand(LdSt, AMDGPU::OpName::offset);
279     BaseReg = AddrReg->getReg();
280     Offset = OffsetImm->getImm();
281 
282     if (SOffset) // soffset can be an inline immediate.
283       Offset += SOffset->getImm();
284 
285     return true;
286   }
287 
288   if (isSMRD(LdSt)) {
289     const MachineOperand *OffsetImm =
290         getNamedOperand(LdSt, AMDGPU::OpName::offset);
291     if (!OffsetImm)
292       return false;
293 
294     const MachineOperand *SBaseReg =
295         getNamedOperand(LdSt, AMDGPU::OpName::sbase);
296     BaseReg = SBaseReg->getReg();
297     Offset = OffsetImm->getImm();
298     return true;
299   }
300 
301   if (isFLAT(LdSt)) {
302     const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
303     BaseReg = AddrReg->getReg();
304     Offset = 0;
305     return true;
306   }
307 
308   return false;
309 }
310 
311 bool SIInstrInfo::shouldClusterMemOps(MachineInstr &FirstLdSt,
312                                       MachineInstr &SecondLdSt,
313                                       unsigned NumLoads) const {
314   const MachineOperand *FirstDst = nullptr;
315   const MachineOperand *SecondDst = nullptr;
316 
317   if ((isMUBUF(FirstLdSt) && isMUBUF(SecondLdSt)) ||
318       (isMTBUF(FirstLdSt) && isMTBUF(SecondLdSt)) ||
319       (isFLAT(FirstLdSt) && isFLAT(SecondLdSt))) {
320     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdata);
321     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdata);
322   } else if (isSMRD(FirstLdSt) && isSMRD(SecondLdSt)) {
323     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::sdst);
324     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::sdst);
325   } else if (isDS(FirstLdSt) && isDS(SecondLdSt)) {
326     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
327     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
328   }
329 
330   if (!FirstDst || !SecondDst)
331     return false;
332 
333   // Try to limit clustering based on the total number of bytes loaded
334   // rather than the number of instructions.  This is done to help reduce
335   // register pressure.  The method used is somewhat inexact, though,
336   // because it assumes that all loads in the cluster will load the
337   // same number of bytes as FirstLdSt.
338 
339   // The unit of this value is bytes.
340   // FIXME: This needs finer tuning.
341   unsigned LoadClusterThreshold = 16;
342 
343   const MachineRegisterInfo &MRI =
344       FirstLdSt.getParent()->getParent()->getRegInfo();
345   const TargetRegisterClass *DstRC = MRI.getRegClass(FirstDst->getReg());
346 
347   return (NumLoads * DstRC->getSize()) <= LoadClusterThreshold;
348 }
349 
350 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
351                               MachineBasicBlock::iterator MI,
352                               const DebugLoc &DL, unsigned DestReg,
353                               unsigned SrcReg, bool KillSrc) const {
354   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
355 
356   if (RC == &AMDGPU::VGPR_32RegClass) {
357     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
358            AMDGPU::SReg_32RegClass.contains(SrcReg));
359     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
360       .addReg(SrcReg, getKillRegState(KillSrc));
361     return;
362   }
363 
364   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
365       RC == &AMDGPU::SReg_32RegClass) {
366     if (SrcReg == AMDGPU::SCC) {
367       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
368           .addImm(-1)
369           .addImm(0);
370       return;
371     }
372 
373     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
374     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
375             .addReg(SrcReg, getKillRegState(KillSrc));
376     return;
377   }
378 
379   if (RC == &AMDGPU::SReg_64RegClass) {
380     if (DestReg == AMDGPU::VCC) {
381       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
382         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
383           .addReg(SrcReg, getKillRegState(KillSrc));
384       } else {
385         // FIXME: Hack until VReg_1 removed.
386         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
387         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
388           .addImm(0)
389           .addReg(SrcReg, getKillRegState(KillSrc));
390       }
391 
392       return;
393     }
394 
395     assert(AMDGPU::SReg_64RegClass.contains(SrcReg));
396     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
397             .addReg(SrcReg, getKillRegState(KillSrc));
398     return;
399   }
400 
401   if (DestReg == AMDGPU::SCC) {
402     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
403     BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
404       .addReg(SrcReg, getKillRegState(KillSrc))
405       .addImm(0);
406     return;
407   }
408 
409   unsigned EltSize = 4;
410   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
411   if (RI.isSGPRClass(RC)) {
412     if (RC->getSize() > 4) {
413       Opcode =  AMDGPU::S_MOV_B64;
414       EltSize = 8;
415     } else {
416       Opcode = AMDGPU::S_MOV_B32;
417       EltSize = 4;
418     }
419   }
420 
421   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
422   bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
423 
424   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
425     unsigned SubIdx;
426     if (Forward)
427       SubIdx = SubIndices[Idx];
428     else
429       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
430 
431     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
432       get(Opcode), RI.getSubReg(DestReg, SubIdx));
433 
434     Builder.addReg(RI.getSubReg(SrcReg, SubIdx));
435 
436     if (Idx == SubIndices.size() - 1)
437       Builder.addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
438 
439     if (Idx == 0)
440       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
441 
442     Builder.addReg(SrcReg, RegState::Implicit);
443   }
444 }
445 
446 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
447   int NewOpc;
448 
449   // Try to map original to commuted opcode
450   NewOpc = AMDGPU::getCommuteRev(Opcode);
451   if (NewOpc != -1)
452     // Check if the commuted (REV) opcode exists on the target.
453     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
454 
455   // Try to map commuted to original opcode
456   NewOpc = AMDGPU::getCommuteOrig(Opcode);
457   if (NewOpc != -1)
458     // Check if the original (non-REV) opcode exists on the target.
459     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
460 
461   return Opcode;
462 }
463 
464 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
465 
466   if (DstRC->getSize() == 4) {
467     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
468   } else if (DstRC->getSize() == 8 && RI.isSGPRClass(DstRC)) {
469     return AMDGPU::S_MOV_B64;
470   } else if (DstRC->getSize() == 8 && !RI.isSGPRClass(DstRC)) {
471     return  AMDGPU::V_MOV_B64_PSEUDO;
472   }
473   return AMDGPU::COPY;
474 }
475 
476 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
477   switch (Size) {
478   case 4:
479     return AMDGPU::SI_SPILL_S32_SAVE;
480   case 8:
481     return AMDGPU::SI_SPILL_S64_SAVE;
482   case 16:
483     return AMDGPU::SI_SPILL_S128_SAVE;
484   case 32:
485     return AMDGPU::SI_SPILL_S256_SAVE;
486   case 64:
487     return AMDGPU::SI_SPILL_S512_SAVE;
488   default:
489     llvm_unreachable("unknown register size");
490   }
491 }
492 
493 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
494   switch (Size) {
495   case 4:
496     return AMDGPU::SI_SPILL_V32_SAVE;
497   case 8:
498     return AMDGPU::SI_SPILL_V64_SAVE;
499   case 12:
500     return AMDGPU::SI_SPILL_V96_SAVE;
501   case 16:
502     return AMDGPU::SI_SPILL_V128_SAVE;
503   case 32:
504     return AMDGPU::SI_SPILL_V256_SAVE;
505   case 64:
506     return AMDGPU::SI_SPILL_V512_SAVE;
507   default:
508     llvm_unreachable("unknown register size");
509   }
510 }
511 
512 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
513                                       MachineBasicBlock::iterator MI,
514                                       unsigned SrcReg, bool isKill,
515                                       int FrameIndex,
516                                       const TargetRegisterClass *RC,
517                                       const TargetRegisterInfo *TRI) const {
518   MachineFunction *MF = MBB.getParent();
519   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
520   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
521   DebugLoc DL = MBB.findDebugLoc(MI);
522 
523   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
524   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
525   MachinePointerInfo PtrInfo
526     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
527   MachineMemOperand *MMO
528     = MF->getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
529                                Size, Align);
530 
531   if (RI.isSGPRClass(RC)) {
532     MFI->setHasSpilledSGPRs();
533 
534     // We are only allowed to create one new instruction when spilling
535     // registers, so we need to use pseudo instruction for spilling SGPRs.
536     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(RC->getSize()));
537 
538     // The SGPR spill/restore instructions only work on number sgprs, so we need
539     // to make sure we are using the correct register class.
540     if (TargetRegisterInfo::isVirtualRegister(SrcReg) && RC->getSize() == 4) {
541       MachineRegisterInfo &MRI = MF->getRegInfo();
542       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
543     }
544 
545     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc)
546       .addReg(SrcReg, getKillRegState(isKill)) // data
547       .addFrameIndex(FrameIndex)               // addr
548       .addMemOperand(MMO)
549       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
550       .addReg(MFI->getScratchWaveOffsetReg(), RegState::Implicit);
551     // Add the scratch resource registers as implicit uses because we may end up
552     // needing them, and need to ensure that the reserved registers are
553     // correctly handled.
554 
555     if (ST.hasScalarStores()) {
556       // m0 is used for offset to scalar stores if used to spill.
557       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine);
558     }
559 
560     return;
561   }
562 
563   if (!ST.isVGPRSpillingEnabled(*MF->getFunction())) {
564     LLVMContext &Ctx = MF->getFunction()->getContext();
565     Ctx.emitError("SIInstrInfo::storeRegToStackSlot - Do not know how to"
566                   " spill register");
567     BuildMI(MBB, MI, DL, get(AMDGPU::KILL))
568       .addReg(SrcReg);
569 
570     return;
571   }
572 
573   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
574 
575   unsigned Opcode = getVGPRSpillSaveOpcode(RC->getSize());
576   MFI->setHasSpilledVGPRs();
577   BuildMI(MBB, MI, DL, get(Opcode))
578     .addReg(SrcReg, getKillRegState(isKill)) // data
579     .addFrameIndex(FrameIndex)               // addr
580     .addReg(MFI->getScratchRSrcReg())        // scratch_rsrc
581     .addReg(MFI->getScratchWaveOffsetReg())  // scratch_offset
582     .addImm(0)                               // offset
583     .addMemOperand(MMO);
584 }
585 
586 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
587   switch (Size) {
588   case 4:
589     return AMDGPU::SI_SPILL_S32_RESTORE;
590   case 8:
591     return AMDGPU::SI_SPILL_S64_RESTORE;
592   case 16:
593     return AMDGPU::SI_SPILL_S128_RESTORE;
594   case 32:
595     return AMDGPU::SI_SPILL_S256_RESTORE;
596   case 64:
597     return AMDGPU::SI_SPILL_S512_RESTORE;
598   default:
599     llvm_unreachable("unknown register size");
600   }
601 }
602 
603 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
604   switch (Size) {
605   case 4:
606     return AMDGPU::SI_SPILL_V32_RESTORE;
607   case 8:
608     return AMDGPU::SI_SPILL_V64_RESTORE;
609   case 12:
610     return AMDGPU::SI_SPILL_V96_RESTORE;
611   case 16:
612     return AMDGPU::SI_SPILL_V128_RESTORE;
613   case 32:
614     return AMDGPU::SI_SPILL_V256_RESTORE;
615   case 64:
616     return AMDGPU::SI_SPILL_V512_RESTORE;
617   default:
618     llvm_unreachable("unknown register size");
619   }
620 }
621 
622 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
623                                        MachineBasicBlock::iterator MI,
624                                        unsigned DestReg, int FrameIndex,
625                                        const TargetRegisterClass *RC,
626                                        const TargetRegisterInfo *TRI) const {
627   MachineFunction *MF = MBB.getParent();
628   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
629   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
630   DebugLoc DL = MBB.findDebugLoc(MI);
631   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
632   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
633 
634   MachinePointerInfo PtrInfo
635     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
636 
637   MachineMemOperand *MMO = MF->getMachineMemOperand(
638     PtrInfo, MachineMemOperand::MOLoad, Size, Align);
639 
640   if (RI.isSGPRClass(RC)) {
641     // FIXME: Maybe this should not include a memoperand because it will be
642     // lowered to non-memory instructions.
643     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(RC->getSize()));
644     if (TargetRegisterInfo::isVirtualRegister(DestReg) && RC->getSize() == 4) {
645       MachineRegisterInfo &MRI = MF->getRegInfo();
646       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0RegClass);
647     }
648 
649     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc, DestReg)
650       .addFrameIndex(FrameIndex) // addr
651       .addMemOperand(MMO)
652       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
653       .addReg(MFI->getScratchWaveOffsetReg(), RegState::Implicit);
654 
655     if (ST.hasScalarStores()) {
656       // m0 is used for offset to scalar stores if used to spill.
657       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine);
658     }
659 
660     return;
661   }
662 
663   if (!ST.isVGPRSpillingEnabled(*MF->getFunction())) {
664     LLVMContext &Ctx = MF->getFunction()->getContext();
665     Ctx.emitError("SIInstrInfo::loadRegFromStackSlot - Do not know how to"
666                   " restore register");
667     BuildMI(MBB, MI, DL, get(AMDGPU::IMPLICIT_DEF), DestReg);
668 
669     return;
670   }
671 
672   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
673 
674   unsigned Opcode = getVGPRSpillRestoreOpcode(RC->getSize());
675   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
676     .addFrameIndex(FrameIndex)              // vaddr
677     .addReg(MFI->getScratchRSrcReg())       // scratch_rsrc
678     .addReg(MFI->getScratchWaveOffsetReg()) // scratch_offset
679     .addImm(0)                              // offset
680     .addMemOperand(MMO);
681 }
682 
683 /// \param @Offset Offset in bytes of the FrameIndex being spilled
684 unsigned SIInstrInfo::calculateLDSSpillAddress(
685     MachineBasicBlock &MBB, MachineInstr &MI, RegScavenger *RS, unsigned TmpReg,
686     unsigned FrameOffset, unsigned Size) const {
687   MachineFunction *MF = MBB.getParent();
688   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
689   const SISubtarget &ST = MF->getSubtarget<SISubtarget>();
690   const SIRegisterInfo *TRI = ST.getRegisterInfo();
691   DebugLoc DL = MBB.findDebugLoc(MI);
692   unsigned WorkGroupSize = MFI->getMaxFlatWorkGroupSize();
693   unsigned WavefrontSize = ST.getWavefrontSize();
694 
695   unsigned TIDReg = MFI->getTIDReg();
696   if (!MFI->hasCalculatedTID()) {
697     MachineBasicBlock &Entry = MBB.getParent()->front();
698     MachineBasicBlock::iterator Insert = Entry.front();
699     DebugLoc DL = Insert->getDebugLoc();
700 
701     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass,
702                                    *MF);
703     if (TIDReg == AMDGPU::NoRegister)
704       return TIDReg;
705 
706     if (!AMDGPU::isShader(MF->getFunction()->getCallingConv()) &&
707         WorkGroupSize > WavefrontSize) {
708 
709       unsigned TIDIGXReg
710         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_X);
711       unsigned TIDIGYReg
712         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Y);
713       unsigned TIDIGZReg
714         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Z);
715       unsigned InputPtrReg =
716           TRI->getPreloadedValue(*MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
717       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
718         if (!Entry.isLiveIn(Reg))
719           Entry.addLiveIn(Reg);
720       }
721 
722       RS->enterBasicBlock(Entry);
723       // FIXME: Can we scavenge an SReg_64 and access the subregs?
724       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
725       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
726       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
727               .addReg(InputPtrReg)
728               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
729       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
730               .addReg(InputPtrReg)
731               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
732 
733       // NGROUPS.X * NGROUPS.Y
734       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
735               .addReg(STmp1)
736               .addReg(STmp0);
737       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
738       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
739               .addReg(STmp1)
740               .addReg(TIDIGXReg);
741       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
742       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
743               .addReg(STmp0)
744               .addReg(TIDIGYReg)
745               .addReg(TIDReg);
746       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
747       BuildMI(Entry, Insert, DL, get(AMDGPU::V_ADD_I32_e32), TIDReg)
748               .addReg(TIDReg)
749               .addReg(TIDIGZReg);
750     } else {
751       // Get the wave id
752       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
753               TIDReg)
754               .addImm(-1)
755               .addImm(0);
756 
757       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
758               TIDReg)
759               .addImm(-1)
760               .addReg(TIDReg);
761     }
762 
763     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
764             TIDReg)
765             .addImm(2)
766             .addReg(TIDReg);
767     MFI->setTIDReg(TIDReg);
768   }
769 
770   // Add FrameIndex to LDS offset
771   unsigned LDSOffset = MFI->getLDSSize() + (FrameOffset * WorkGroupSize);
772   BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), TmpReg)
773           .addImm(LDSOffset)
774           .addReg(TIDReg);
775 
776   return TmpReg;
777 }
778 
779 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
780                                    MachineBasicBlock::iterator MI,
781                                    int Count) const {
782   DebugLoc DL = MBB.findDebugLoc(MI);
783   while (Count > 0) {
784     int Arg;
785     if (Count >= 8)
786       Arg = 7;
787     else
788       Arg = Count - 1;
789     Count -= 8;
790     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
791             .addImm(Arg);
792   }
793 }
794 
795 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
796                              MachineBasicBlock::iterator MI) const {
797   insertWaitStates(MBB, MI, 1);
798 }
799 
800 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) const {
801   switch (MI.getOpcode()) {
802   default: return 1; // FIXME: Do wait states equal cycles?
803 
804   case AMDGPU::S_NOP:
805     return MI.getOperand(0).getImm() + 1;
806   }
807 }
808 
809 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
810   MachineBasicBlock &MBB = *MI.getParent();
811   DebugLoc DL = MBB.findDebugLoc(MI);
812   switch (MI.getOpcode()) {
813   default: return AMDGPUInstrInfo::expandPostRAPseudo(MI);
814   case AMDGPU::S_MOV_B64_term: {
815     // This is only a terminator to get the correct spill code placement during
816     // register allocation.
817     MI.setDesc(get(AMDGPU::S_MOV_B64));
818     break;
819   }
820   case AMDGPU::S_XOR_B64_term: {
821     // This is only a terminator to get the correct spill code placement during
822     // register allocation.
823     MI.setDesc(get(AMDGPU::S_XOR_B64));
824     break;
825   }
826   case AMDGPU::S_ANDN2_B64_term: {
827     // This is only a terminator to get the correct spill code placement during
828     // register allocation.
829     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
830     break;
831   }
832   case AMDGPU::V_MOV_B64_PSEUDO: {
833     unsigned Dst = MI.getOperand(0).getReg();
834     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
835     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
836 
837     const MachineOperand &SrcOp = MI.getOperand(1);
838     // FIXME: Will this work for 64-bit floating point immediates?
839     assert(!SrcOp.isFPImm());
840     if (SrcOp.isImm()) {
841       APInt Imm(64, SrcOp.getImm());
842       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
843         .addImm(Imm.getLoBits(32).getZExtValue())
844         .addReg(Dst, RegState::Implicit | RegState::Define);
845       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
846         .addImm(Imm.getHiBits(32).getZExtValue())
847         .addReg(Dst, RegState::Implicit | RegState::Define);
848     } else {
849       assert(SrcOp.isReg());
850       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
851         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
852         .addReg(Dst, RegState::Implicit | RegState::Define);
853       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
854         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
855         .addReg(Dst, RegState::Implicit | RegState::Define);
856     }
857     MI.eraseFromParent();
858     break;
859   }
860   case AMDGPU::V_MOVRELD_B32_V1:
861   case AMDGPU::V_MOVRELD_B32_V2:
862   case AMDGPU::V_MOVRELD_B32_V4:
863   case AMDGPU::V_MOVRELD_B32_V8:
864   case AMDGPU::V_MOVRELD_B32_V16: {
865     const MCInstrDesc &MovRelDesc = get(AMDGPU::V_MOVRELD_B32_e32);
866     unsigned VecReg = MI.getOperand(0).getReg();
867     bool IsUndef = MI.getOperand(1).isUndef();
868     unsigned SubReg = AMDGPU::sub0 + MI.getOperand(3).getImm();
869     assert(VecReg == MI.getOperand(1).getReg());
870 
871     MachineInstr *MovRel =
872         BuildMI(MBB, MI, DL, MovRelDesc)
873             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
874             .add(MI.getOperand(2))
875             .addReg(VecReg, RegState::ImplicitDefine)
876             .addReg(VecReg,
877                     RegState::Implicit | (IsUndef ? RegState::Undef : 0));
878 
879     const int ImpDefIdx =
880         MovRelDesc.getNumOperands() + MovRelDesc.getNumImplicitUses();
881     const int ImpUseIdx = ImpDefIdx + 1;
882     MovRel->tieOperands(ImpDefIdx, ImpUseIdx);
883 
884     MI.eraseFromParent();
885     break;
886   }
887   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
888     MachineFunction &MF = *MBB.getParent();
889     unsigned Reg = MI.getOperand(0).getReg();
890     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
891     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
892 
893     // Create a bundle so these instructions won't be re-ordered by the
894     // post-RA scheduler.
895     MIBundleBuilder Bundler(MBB, MI);
896     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
897 
898     // Add 32-bit offset from this instruction to the start of the
899     // constant data.
900     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
901                        .addReg(RegLo)
902                        .add(MI.getOperand(1)));
903 
904     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
905                                   .addReg(RegHi);
906     if (MI.getOperand(2).getTargetFlags() == SIInstrInfo::MO_NONE)
907       MIB.addImm(0);
908     else
909       MIB.add(MI.getOperand(2));
910 
911     Bundler.append(MIB);
912     llvm::finalizeBundle(MBB, Bundler.begin());
913 
914     MI.eraseFromParent();
915     break;
916   }
917   }
918   return true;
919 }
920 
921 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
922                                       MachineOperand &Src0,
923                                       unsigned Src0OpName,
924                                       MachineOperand &Src1,
925                                       unsigned Src1OpName) const {
926   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
927   if (!Src0Mods)
928     return false;
929 
930   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
931   assert(Src1Mods &&
932          "All commutable instructions have both src0 and src1 modifiers");
933 
934   int Src0ModsVal = Src0Mods->getImm();
935   int Src1ModsVal = Src1Mods->getImm();
936 
937   Src1Mods->setImm(Src0ModsVal);
938   Src0Mods->setImm(Src1ModsVal);
939   return true;
940 }
941 
942 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
943                                              MachineOperand &RegOp,
944                                              MachineOperand &NonRegOp) {
945   unsigned Reg = RegOp.getReg();
946   unsigned SubReg = RegOp.getSubReg();
947   bool IsKill = RegOp.isKill();
948   bool IsDead = RegOp.isDead();
949   bool IsUndef = RegOp.isUndef();
950   bool IsDebug = RegOp.isDebug();
951 
952   if (NonRegOp.isImm())
953     RegOp.ChangeToImmediate(NonRegOp.getImm());
954   else if (NonRegOp.isFI())
955     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
956   else
957     return nullptr;
958 
959   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
960   NonRegOp.setSubReg(SubReg);
961 
962   return &MI;
963 }
964 
965 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
966                                                   unsigned Src0Idx,
967                                                   unsigned Src1Idx) const {
968   assert(!NewMI && "this should never be used");
969 
970   unsigned Opc = MI.getOpcode();
971   int CommutedOpcode = commuteOpcode(Opc);
972   if (CommutedOpcode == -1)
973     return nullptr;
974 
975   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
976            static_cast<int>(Src0Idx) &&
977          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
978            static_cast<int>(Src1Idx) &&
979          "inconsistency with findCommutedOpIndices");
980 
981   MachineOperand &Src0 = MI.getOperand(Src0Idx);
982   MachineOperand &Src1 = MI.getOperand(Src1Idx);
983 
984   MachineInstr *CommutedMI = nullptr;
985   if (Src0.isReg() && Src1.isReg()) {
986     if (isOperandLegal(MI, Src1Idx, &Src0)) {
987       // Be sure to copy the source modifiers to the right place.
988       CommutedMI
989         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
990     }
991 
992   } else if (Src0.isReg() && !Src1.isReg()) {
993     // src0 should always be able to support any operand type, so no need to
994     // check operand legality.
995     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
996   } else if (!Src0.isReg() && Src1.isReg()) {
997     if (isOperandLegal(MI, Src1Idx, &Src0))
998       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
999   } else {
1000     // FIXME: Found two non registers to commute. This does happen.
1001     return nullptr;
1002   }
1003 
1004 
1005   if (CommutedMI) {
1006     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
1007                         Src1, AMDGPU::OpName::src1_modifiers);
1008 
1009     CommutedMI->setDesc(get(CommutedOpcode));
1010   }
1011 
1012   return CommutedMI;
1013 }
1014 
1015 // This needs to be implemented because the source modifiers may be inserted
1016 // between the true commutable operands, and the base
1017 // TargetInstrInfo::commuteInstruction uses it.
1018 bool SIInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx0,
1019                                         unsigned &SrcOpIdx1) const {
1020   if (!MI.isCommutable())
1021     return false;
1022 
1023   unsigned Opc = MI.getOpcode();
1024   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1025   if (Src0Idx == -1)
1026     return false;
1027 
1028   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1029   if (Src1Idx == -1)
1030     return false;
1031 
1032   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1033 }
1034 
1035 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
1036                                         int64_t BrOffset) const {
1037   // BranchRelaxation should never have to check s_setpc_b64 because its dest
1038   // block is unanalyzable.
1039   assert(BranchOp != AMDGPU::S_SETPC_B64);
1040 
1041   // Convert to dwords.
1042   BrOffset /= 4;
1043 
1044   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
1045   // from the next instruction.
1046   BrOffset -= 1;
1047 
1048   return isIntN(BranchOffsetBits, BrOffset);
1049 }
1050 
1051 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
1052   const MachineInstr &MI) const {
1053   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
1054     // This would be a difficult analysis to perform, but can always be legal so
1055     // there's no need to analyze it.
1056     return nullptr;
1057   }
1058 
1059   return MI.getOperand(0).getMBB();
1060 }
1061 
1062 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
1063                                            MachineBasicBlock &DestBB,
1064                                            const DebugLoc &DL,
1065                                            int64_t BrOffset,
1066                                            RegScavenger *RS) const {
1067   assert(RS && "RegScavenger required for long branching");
1068   assert(MBB.empty() &&
1069          "new block should be inserted for expanding unconditional branch");
1070   assert(MBB.pred_size() == 1);
1071 
1072   MachineFunction *MF = MBB.getParent();
1073   MachineRegisterInfo &MRI = MF->getRegInfo();
1074 
1075   // FIXME: Virtual register workaround for RegScavenger not working with empty
1076   // blocks.
1077   unsigned PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1078 
1079   auto I = MBB.end();
1080 
1081   // We need to compute the offset relative to the instruction immediately after
1082   // s_getpc_b64. Insert pc arithmetic code before last terminator.
1083   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
1084 
1085   // TODO: Handle > 32-bit block address.
1086   if (BrOffset >= 0) {
1087     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
1088       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1089       .addReg(PCReg, 0, AMDGPU::sub0)
1090       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_FORWARD);
1091     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
1092       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1093       .addReg(PCReg, 0, AMDGPU::sub1)
1094       .addImm(0);
1095   } else {
1096     // Backwards branch.
1097     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
1098       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1099       .addReg(PCReg, 0, AMDGPU::sub0)
1100       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_BACKWARD);
1101     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
1102       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1103       .addReg(PCReg, 0, AMDGPU::sub1)
1104       .addImm(0);
1105   }
1106 
1107   // Insert the indirect branch after the other terminator.
1108   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
1109     .addReg(PCReg);
1110 
1111   // FIXME: If spilling is necessary, this will fail because this scavenger has
1112   // no emergency stack slots. It is non-trivial to spill in this situation,
1113   // because the restore code needs to be specially placed after the
1114   // jump. BranchRelaxation then needs to be made aware of the newly inserted
1115   // block.
1116   //
1117   // If a spill is needed for the pc register pair, we need to insert a spill
1118   // restore block right before the destination block, and insert a short branch
1119   // into the old destination block's fallthrough predecessor.
1120   // e.g.:
1121   //
1122   // s_cbranch_scc0 skip_long_branch:
1123   //
1124   // long_branch_bb:
1125   //   spill s[8:9]
1126   //   s_getpc_b64 s[8:9]
1127   //   s_add_u32 s8, s8, restore_bb
1128   //   s_addc_u32 s9, s9, 0
1129   //   s_setpc_b64 s[8:9]
1130   //
1131   // skip_long_branch:
1132   //   foo;
1133   //
1134   // .....
1135   //
1136   // dest_bb_fallthrough_predecessor:
1137   // bar;
1138   // s_branch dest_bb
1139   //
1140   // restore_bb:
1141   //  restore s[8:9]
1142   //  fallthrough dest_bb
1143   ///
1144   // dest_bb:
1145   //   buzz;
1146 
1147   RS->enterBasicBlockEnd(MBB);
1148   unsigned Scav = RS->scavengeRegister(&AMDGPU::SReg_64RegClass,
1149                                        MachineBasicBlock::iterator(GetPC), 0);
1150   MRI.replaceRegWith(PCReg, Scav);
1151   MRI.clearVirtRegs();
1152   RS->setRegUsed(Scav);
1153 
1154   return 4 + 8 + 4 + 4;
1155 }
1156 
1157 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1158   switch (Cond) {
1159   case SIInstrInfo::SCC_TRUE:
1160     return AMDGPU::S_CBRANCH_SCC1;
1161   case SIInstrInfo::SCC_FALSE:
1162     return AMDGPU::S_CBRANCH_SCC0;
1163   case SIInstrInfo::VCCNZ:
1164     return AMDGPU::S_CBRANCH_VCCNZ;
1165   case SIInstrInfo::VCCZ:
1166     return AMDGPU::S_CBRANCH_VCCZ;
1167   case SIInstrInfo::EXECNZ:
1168     return AMDGPU::S_CBRANCH_EXECNZ;
1169   case SIInstrInfo::EXECZ:
1170     return AMDGPU::S_CBRANCH_EXECZ;
1171   default:
1172     llvm_unreachable("invalid branch predicate");
1173   }
1174 }
1175 
1176 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1177   switch (Opcode) {
1178   case AMDGPU::S_CBRANCH_SCC0:
1179     return SCC_FALSE;
1180   case AMDGPU::S_CBRANCH_SCC1:
1181     return SCC_TRUE;
1182   case AMDGPU::S_CBRANCH_VCCNZ:
1183     return VCCNZ;
1184   case AMDGPU::S_CBRANCH_VCCZ:
1185     return VCCZ;
1186   case AMDGPU::S_CBRANCH_EXECNZ:
1187     return EXECNZ;
1188   case AMDGPU::S_CBRANCH_EXECZ:
1189     return EXECZ;
1190   default:
1191     return INVALID_BR;
1192   }
1193 }
1194 
1195 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
1196                                     MachineBasicBlock::iterator I,
1197                                     MachineBasicBlock *&TBB,
1198                                     MachineBasicBlock *&FBB,
1199                                     SmallVectorImpl<MachineOperand> &Cond,
1200                                     bool AllowModify) const {
1201   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1202     // Unconditional Branch
1203     TBB = I->getOperand(0).getMBB();
1204     return false;
1205   }
1206 
1207   BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1208   if (Pred == INVALID_BR)
1209     return true;
1210 
1211   MachineBasicBlock *CondBB = I->getOperand(0).getMBB();
1212   Cond.push_back(MachineOperand::CreateImm(Pred));
1213   Cond.push_back(I->getOperand(1)); // Save the branch register.
1214 
1215   ++I;
1216 
1217   if (I == MBB.end()) {
1218     // Conditional branch followed by fall-through.
1219     TBB = CondBB;
1220     return false;
1221   }
1222 
1223   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1224     TBB = CondBB;
1225     FBB = I->getOperand(0).getMBB();
1226     return false;
1227   }
1228 
1229   return true;
1230 }
1231 
1232 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1233                                 MachineBasicBlock *&FBB,
1234                                 SmallVectorImpl<MachineOperand> &Cond,
1235                                 bool AllowModify) const {
1236   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1237   if (I == MBB.end())
1238     return false;
1239 
1240   if (I->getOpcode() != AMDGPU::SI_MASK_BRANCH)
1241     return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
1242 
1243   ++I;
1244 
1245   // TODO: Should be able to treat as fallthrough?
1246   if (I == MBB.end())
1247     return true;
1248 
1249   if (analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify))
1250     return true;
1251 
1252   MachineBasicBlock *MaskBrDest = I->getOperand(0).getMBB();
1253 
1254   // Specifically handle the case where the conditional branch is to the same
1255   // destination as the mask branch. e.g.
1256   //
1257   // si_mask_branch BB8
1258   // s_cbranch_execz BB8
1259   // s_cbranch BB9
1260   //
1261   // This is required to understand divergent loops which may need the branches
1262   // to be relaxed.
1263   if (TBB != MaskBrDest || Cond.empty())
1264     return true;
1265 
1266   auto Pred = Cond[0].getImm();
1267   return (Pred != EXECZ && Pred != EXECNZ);
1268 }
1269 
1270 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
1271                                    int *BytesRemoved) const {
1272   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1273 
1274   unsigned Count = 0;
1275   unsigned RemovedSize = 0;
1276   while (I != MBB.end()) {
1277     MachineBasicBlock::iterator Next = std::next(I);
1278     if (I->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
1279       I = Next;
1280       continue;
1281     }
1282 
1283     RemovedSize += getInstSizeInBytes(*I);
1284     I->eraseFromParent();
1285     ++Count;
1286     I = Next;
1287   }
1288 
1289   if (BytesRemoved)
1290     *BytesRemoved = RemovedSize;
1291 
1292   return Count;
1293 }
1294 
1295 // Copy the flags onto the implicit condition register operand.
1296 static void preserveCondRegFlags(MachineOperand &CondReg,
1297                                  const MachineOperand &OrigCond) {
1298   CondReg.setIsUndef(OrigCond.isUndef());
1299   CondReg.setIsKill(OrigCond.isKill());
1300 }
1301 
1302 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
1303                                    MachineBasicBlock *TBB,
1304                                    MachineBasicBlock *FBB,
1305                                    ArrayRef<MachineOperand> Cond,
1306                                    const DebugLoc &DL,
1307                                    int *BytesAdded) const {
1308 
1309   if (!FBB && Cond.empty()) {
1310     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1311       .addMBB(TBB);
1312     if (BytesAdded)
1313       *BytesAdded = 4;
1314     return 1;
1315   }
1316 
1317   assert(TBB && Cond[0].isImm());
1318 
1319   unsigned Opcode
1320     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
1321 
1322   if (!FBB) {
1323     Cond[1].isUndef();
1324     MachineInstr *CondBr =
1325       BuildMI(&MBB, DL, get(Opcode))
1326       .addMBB(TBB);
1327 
1328     // Copy the flags onto the implicit condition register operand.
1329     preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
1330 
1331     if (BytesAdded)
1332       *BytesAdded = 4;
1333     return 1;
1334   }
1335 
1336   assert(TBB && FBB);
1337 
1338   MachineInstr *CondBr =
1339     BuildMI(&MBB, DL, get(Opcode))
1340     .addMBB(TBB);
1341   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1342     .addMBB(FBB);
1343 
1344   MachineOperand &CondReg = CondBr->getOperand(1);
1345   CondReg.setIsUndef(Cond[1].isUndef());
1346   CondReg.setIsKill(Cond[1].isKill());
1347 
1348   if (BytesAdded)
1349       *BytesAdded = 8;
1350 
1351   return 2;
1352 }
1353 
1354 bool SIInstrInfo::reverseBranchCondition(
1355   SmallVectorImpl<MachineOperand> &Cond) const {
1356   assert(Cond.size() == 2);
1357   Cond[0].setImm(-Cond[0].getImm());
1358   return false;
1359 }
1360 
1361 bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
1362                                   ArrayRef<MachineOperand> Cond,
1363                                   unsigned TrueReg, unsigned FalseReg,
1364                                   int &CondCycles,
1365                                   int &TrueCycles, int &FalseCycles) const {
1366   switch (Cond[0].getImm()) {
1367   case VCCNZ:
1368   case VCCZ: {
1369     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1370     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
1371     assert(MRI.getRegClass(FalseReg) == RC);
1372 
1373     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
1374     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
1375 
1376     // Limit to equal cost for branch vs. N v_cndmask_b32s.
1377     return !RI.isSGPRClass(RC) && NumInsts <= 6;
1378   }
1379   case SCC_TRUE:
1380   case SCC_FALSE: {
1381     // FIXME: We could insert for VGPRs if we could replace the original compare
1382     // with a vector one.
1383     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1384     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
1385     assert(MRI.getRegClass(FalseReg) == RC);
1386 
1387     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
1388 
1389     // Multiples of 8 can do s_cselect_b64
1390     if (NumInsts % 2 == 0)
1391       NumInsts /= 2;
1392 
1393     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
1394     return RI.isSGPRClass(RC);
1395   }
1396   default:
1397     return false;
1398   }
1399 }
1400 
1401 void SIInstrInfo::insertSelect(MachineBasicBlock &MBB,
1402                                MachineBasicBlock::iterator I, const DebugLoc &DL,
1403                                unsigned DstReg, ArrayRef<MachineOperand> Cond,
1404                                unsigned TrueReg, unsigned FalseReg) const {
1405   BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
1406   if (Pred == VCCZ || Pred == SCC_FALSE) {
1407     Pred = static_cast<BranchPredicate>(-Pred);
1408     std::swap(TrueReg, FalseReg);
1409   }
1410 
1411   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1412   const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
1413   unsigned DstSize = DstRC->getSize();
1414 
1415   if (DstSize == 4) {
1416     unsigned SelOp = Pred == SCC_TRUE ?
1417       AMDGPU::S_CSELECT_B32 : AMDGPU::V_CNDMASK_B32_e32;
1418 
1419     // Instruction's operands are backwards from what is expected.
1420     MachineInstr *Select =
1421       BuildMI(MBB, I, DL, get(SelOp), DstReg)
1422       .addReg(FalseReg)
1423       .addReg(TrueReg);
1424 
1425     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1426     return;
1427   }
1428 
1429   if (DstSize == 8 && Pred == SCC_TRUE) {
1430     MachineInstr *Select =
1431       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
1432       .addReg(FalseReg)
1433       .addReg(TrueReg);
1434 
1435     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1436     return;
1437   }
1438 
1439   static const int16_t Sub0_15[] = {
1440     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
1441     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
1442     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
1443     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
1444   };
1445 
1446   static const int16_t Sub0_15_64[] = {
1447     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
1448     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
1449     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
1450     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
1451   };
1452 
1453   unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
1454   const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
1455   const int16_t *SubIndices = Sub0_15;
1456   int NElts = DstSize / 4;
1457 
1458   // 64-bit select is only avaialble for SALU.
1459   if (Pred == SCC_TRUE) {
1460     SelOp = AMDGPU::S_CSELECT_B64;
1461     EltRC = &AMDGPU::SGPR_64RegClass;
1462     SubIndices = Sub0_15_64;
1463 
1464     assert(NElts % 2 == 0);
1465     NElts /= 2;
1466   }
1467 
1468   MachineInstrBuilder MIB = BuildMI(
1469     MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
1470 
1471   I = MIB->getIterator();
1472 
1473   SmallVector<unsigned, 8> Regs;
1474   for (int Idx = 0; Idx != NElts; ++Idx) {
1475     unsigned DstElt = MRI.createVirtualRegister(EltRC);
1476     Regs.push_back(DstElt);
1477 
1478     unsigned SubIdx = SubIndices[Idx];
1479 
1480     MachineInstr *Select =
1481       BuildMI(MBB, I, DL, get(SelOp), DstElt)
1482       .addReg(FalseReg, 0, SubIdx)
1483       .addReg(TrueReg, 0, SubIdx);
1484     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1485 
1486     MIB.addReg(DstElt)
1487        .addImm(SubIdx);
1488   }
1489 }
1490 
1491 bool SIInstrInfo::isFoldableCopy(const MachineInstr &MI) const {
1492   switch (MI.getOpcode()) {
1493   case AMDGPU::V_MOV_B32_e32:
1494   case AMDGPU::V_MOV_B32_e64:
1495   case AMDGPU::V_MOV_B64_PSEUDO: {
1496     // If there are additional implicit register operands, this may be used for
1497     // register indexing so the source register operand isn't simply copied.
1498     unsigned NumOps = MI.getDesc().getNumOperands() +
1499       MI.getDesc().getNumImplicitUses();
1500 
1501     return MI.getNumOperands() == NumOps;
1502   }
1503   case AMDGPU::S_MOV_B32:
1504   case AMDGPU::S_MOV_B64:
1505   case AMDGPU::COPY:
1506     return true;
1507   default:
1508     return false;
1509   }
1510 }
1511 
1512 static void removeModOperands(MachineInstr &MI) {
1513   unsigned Opc = MI.getOpcode();
1514   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1515                                               AMDGPU::OpName::src0_modifiers);
1516   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1517                                               AMDGPU::OpName::src1_modifiers);
1518   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1519                                               AMDGPU::OpName::src2_modifiers);
1520 
1521   MI.RemoveOperand(Src2ModIdx);
1522   MI.RemoveOperand(Src1ModIdx);
1523   MI.RemoveOperand(Src0ModIdx);
1524 }
1525 
1526 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1527                                 unsigned Reg, MachineRegisterInfo *MRI) const {
1528   if (!MRI->hasOneNonDBGUse(Reg))
1529     return false;
1530 
1531   unsigned Opc = UseMI.getOpcode();
1532   if (Opc == AMDGPU::COPY) {
1533     bool isVGPRCopy = RI.isVGPR(*MRI, UseMI.getOperand(0).getReg());
1534     switch (DefMI.getOpcode()) {
1535     default:
1536       return false;
1537     case AMDGPU::S_MOV_B64:
1538       // TODO: We could fold 64-bit immediates, but this get compilicated
1539       // when there are sub-registers.
1540       return false;
1541 
1542     case AMDGPU::V_MOV_B32_e32:
1543     case AMDGPU::S_MOV_B32:
1544       break;
1545     }
1546     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
1547     const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
1548     assert(ImmOp);
1549     // FIXME: We could handle FrameIndex values here.
1550     if (!ImmOp->isImm()) {
1551       return false;
1552     }
1553     UseMI.setDesc(get(NewOpc));
1554     UseMI.getOperand(1).ChangeToImmediate(ImmOp->getImm());
1555     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
1556     return true;
1557   }
1558 
1559   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64 ||
1560       Opc == AMDGPU::V_MAD_F16 || Opc == AMDGPU::V_MAC_F16_e64) {
1561     // Don't fold if we are using source or output modifiers. The new VOP2
1562     // instructions don't have them.
1563     if (hasAnyModifiersSet(UseMI))
1564       return false;
1565 
1566     const MachineOperand &ImmOp = DefMI.getOperand(1);
1567 
1568     // If this is a free constant, there's no reason to do this.
1569     // TODO: We could fold this here instead of letting SIFoldOperands do it
1570     // later.
1571     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
1572 
1573     // Any src operand can be used for the legality check.
1574     if (isInlineConstant(UseMI, *Src0, ImmOp))
1575       return false;
1576 
1577     bool IsF32 = Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64;
1578     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
1579     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
1580 
1581     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
1582     // We should only expect these to be on src0 due to canonicalizations.
1583     if (Src0->isReg() && Src0->getReg() == Reg) {
1584       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1585         return false;
1586 
1587       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
1588         return false;
1589 
1590       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
1591 
1592       const int64_t Imm = DefMI.getOperand(1).getImm();
1593 
1594       // FIXME: This would be a lot easier if we could return a new instruction
1595       // instead of having to modify in place.
1596 
1597       // Remove these first since they are at the end.
1598       UseMI.RemoveOperand(
1599           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1600       UseMI.RemoveOperand(
1601           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1602 
1603       unsigned Src1Reg = Src1->getReg();
1604       unsigned Src1SubReg = Src1->getSubReg();
1605       Src0->setReg(Src1Reg);
1606       Src0->setSubReg(Src1SubReg);
1607       Src0->setIsKill(Src1->isKill());
1608 
1609       if (Opc == AMDGPU::V_MAC_F32_e64 ||
1610           Opc == AMDGPU::V_MAC_F16_e64)
1611         UseMI.untieRegOperand(
1612             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1613 
1614       Src1->ChangeToImmediate(Imm);
1615 
1616       removeModOperands(UseMI);
1617       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16));
1618 
1619       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1620       if (DeleteDef)
1621         DefMI.eraseFromParent();
1622 
1623       return true;
1624     }
1625 
1626     // Added part is the constant: Use v_madak_{f16, f32}.
1627     if (Src2->isReg() && Src2->getReg() == Reg) {
1628       // Not allowed to use constant bus for another operand.
1629       // We can however allow an inline immediate as src0.
1630       if (!Src0->isImm() &&
1631           (Src0->isReg() && RI.isSGPRClass(MRI->getRegClass(Src0->getReg()))))
1632         return false;
1633 
1634       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1635         return false;
1636 
1637       const int64_t Imm = DefMI.getOperand(1).getImm();
1638 
1639       // FIXME: This would be a lot easier if we could return a new instruction
1640       // instead of having to modify in place.
1641 
1642       // Remove these first since they are at the end.
1643       UseMI.RemoveOperand(
1644           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1645       UseMI.RemoveOperand(
1646           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1647 
1648       if (Opc == AMDGPU::V_MAC_F32_e64 ||
1649           Opc == AMDGPU::V_MAC_F16_e64)
1650         UseMI.untieRegOperand(
1651             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1652 
1653       // ChangingToImmediate adds Src2 back to the instruction.
1654       Src2->ChangeToImmediate(Imm);
1655 
1656       // These come before src2.
1657       removeModOperands(UseMI);
1658       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16));
1659 
1660       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1661       if (DeleteDef)
1662         DefMI.eraseFromParent();
1663 
1664       return true;
1665     }
1666   }
1667 
1668   return false;
1669 }
1670 
1671 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
1672                                 int WidthB, int OffsetB) {
1673   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1674   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1675   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1676   return LowOffset + LowWidth <= HighOffset;
1677 }
1678 
1679 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr &MIa,
1680                                                MachineInstr &MIb) const {
1681   unsigned BaseReg0, BaseReg1;
1682   int64_t Offset0, Offset1;
1683 
1684   if (getMemOpBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
1685       getMemOpBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
1686 
1687     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
1688       // FIXME: Handle ds_read2 / ds_write2.
1689       return false;
1690     }
1691     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
1692     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
1693     if (BaseReg0 == BaseReg1 &&
1694         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
1695       return true;
1696     }
1697   }
1698 
1699   return false;
1700 }
1701 
1702 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr &MIa,
1703                                                   MachineInstr &MIb,
1704                                                   AliasAnalysis *AA) const {
1705   assert((MIa.mayLoad() || MIa.mayStore()) &&
1706          "MIa must load from or modify a memory location");
1707   assert((MIb.mayLoad() || MIb.mayStore()) &&
1708          "MIb must load from or modify a memory location");
1709 
1710   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
1711     return false;
1712 
1713   // XXX - Can we relax this between address spaces?
1714   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1715     return false;
1716 
1717   if (AA && MIa.hasOneMemOperand() && MIb.hasOneMemOperand()) {
1718     const MachineMemOperand *MMOa = *MIa.memoperands_begin();
1719     const MachineMemOperand *MMOb = *MIb.memoperands_begin();
1720     if (MMOa->getValue() && MMOb->getValue()) {
1721       MemoryLocation LocA(MMOa->getValue(), MMOa->getSize(), MMOa->getAAInfo());
1722       MemoryLocation LocB(MMOb->getValue(), MMOb->getSize(), MMOb->getAAInfo());
1723       if (!AA->alias(LocA, LocB))
1724         return true;
1725     }
1726   }
1727 
1728   // TODO: Should we check the address space from the MachineMemOperand? That
1729   // would allow us to distinguish objects we know don't alias based on the
1730   // underlying address space, even if it was lowered to a different one,
1731   // e.g. private accesses lowered to use MUBUF instructions on a scratch
1732   // buffer.
1733   if (isDS(MIa)) {
1734     if (isDS(MIb))
1735       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1736 
1737     return !isFLAT(MIb);
1738   }
1739 
1740   if (isMUBUF(MIa) || isMTBUF(MIa)) {
1741     if (isMUBUF(MIb) || isMTBUF(MIb))
1742       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1743 
1744     return !isFLAT(MIb) && !isSMRD(MIb);
1745   }
1746 
1747   if (isSMRD(MIa)) {
1748     if (isSMRD(MIb))
1749       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1750 
1751     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
1752   }
1753 
1754   if (isFLAT(MIa)) {
1755     if (isFLAT(MIb))
1756       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1757 
1758     return false;
1759   }
1760 
1761   return false;
1762 }
1763 
1764 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
1765                                                  MachineInstr &MI,
1766                                                  LiveVariables *LV) const {
1767   bool IsF16 = false;
1768 
1769   switch (MI.getOpcode()) {
1770   default:
1771     return nullptr;
1772   case AMDGPU::V_MAC_F16_e64:
1773     IsF16 = true;
1774   case AMDGPU::V_MAC_F32_e64:
1775     break;
1776   case AMDGPU::V_MAC_F16_e32:
1777     IsF16 = true;
1778   case AMDGPU::V_MAC_F32_e32: {
1779     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
1780                                              AMDGPU::OpName::src0);
1781     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
1782     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
1783       return nullptr;
1784     break;
1785   }
1786   }
1787 
1788   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
1789   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1790   const MachineOperand *Src0Mods =
1791     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
1792   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
1793   const MachineOperand *Src1Mods =
1794     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
1795   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
1796   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
1797   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
1798 
1799   return BuildMI(*MBB, MI, MI.getDebugLoc(),
1800                  get(IsF16 ? AMDGPU::V_MAD_F16 : AMDGPU::V_MAD_F32))
1801       .add(*Dst)
1802       .addImm(Src0Mods ? Src0Mods->getImm() : 0)
1803       .add(*Src0)
1804       .addImm(Src1Mods ? Src1Mods->getImm() : 0)
1805       .add(*Src1)
1806       .addImm(0) // Src mods
1807       .add(*Src2)
1808       .addImm(Clamp ? Clamp->getImm() : 0)
1809       .addImm(Omod ? Omod->getImm() : 0);
1810 }
1811 
1812 // It's not generally safe to move VALU instructions across these since it will
1813 // start using the register as a base index rather than directly.
1814 // XXX - Why isn't hasSideEffects sufficient for these?
1815 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
1816   switch (MI.getOpcode()) {
1817   case AMDGPU::S_SET_GPR_IDX_ON:
1818   case AMDGPU::S_SET_GPR_IDX_MODE:
1819   case AMDGPU::S_SET_GPR_IDX_OFF:
1820     return true;
1821   default:
1822     return false;
1823   }
1824 }
1825 
1826 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1827                                        const MachineBasicBlock *MBB,
1828                                        const MachineFunction &MF) const {
1829   // XXX - Do we want the SP check in the base implementation?
1830 
1831   // Target-independent instructions do not have an implicit-use of EXEC, even
1832   // when they operate on VGPRs. Treating EXEC modifications as scheduling
1833   // boundaries prevents incorrect movements of such instructions.
1834   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
1835          MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
1836          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
1837          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
1838          changesVGPRIndexingMode(MI);
1839 }
1840 
1841 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
1842   switch (Imm.getBitWidth()) {
1843   case 32:
1844     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
1845                                         ST.hasInv2PiInlineImm());
1846   case 64:
1847     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
1848                                         ST.hasInv2PiInlineImm());
1849   case 16:
1850     return ST.has16BitInsts() &&
1851            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
1852                                         ST.hasInv2PiInlineImm());
1853   default:
1854     llvm_unreachable("invalid bitwidth");
1855   }
1856 }
1857 
1858 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
1859                                    uint8_t OperandType) const {
1860   if (!MO.isImm() || OperandType < MCOI::OPERAND_FIRST_TARGET)
1861     return false;
1862 
1863   // MachineOperand provides no way to tell the true operand size, since it only
1864   // records a 64-bit value. We need to know the size to determine if a 32-bit
1865   // floating point immediate bit pattern is legal for an integer immediate. It
1866   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
1867 
1868   int64_t Imm = MO.getImm();
1869   switch (OperandType) {
1870   case AMDGPU::OPERAND_REG_IMM_INT32:
1871   case AMDGPU::OPERAND_REG_IMM_FP32:
1872   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
1873   case AMDGPU::OPERAND_REG_INLINE_C_FP32: {
1874     int32_t Trunc = static_cast<int32_t>(Imm);
1875     return Trunc == Imm &&
1876            AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
1877   }
1878   case AMDGPU::OPERAND_REG_IMM_INT64:
1879   case AMDGPU::OPERAND_REG_IMM_FP64:
1880   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
1881   case AMDGPU::OPERAND_REG_INLINE_C_FP64: {
1882     return AMDGPU::isInlinableLiteral64(MO.getImm(),
1883                                         ST.hasInv2PiInlineImm());
1884   }
1885   case AMDGPU::OPERAND_REG_IMM_INT16:
1886   case AMDGPU::OPERAND_REG_IMM_FP16:
1887   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
1888   case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
1889     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
1890       // A few special case instructions have 16-bit operands on subtargets
1891       // where 16-bit instructions are not legal.
1892       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
1893       // constants in these cases
1894       int16_t Trunc = static_cast<int16_t>(Imm);
1895       return ST.has16BitInsts() &&
1896              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
1897     }
1898 
1899     return false;
1900   }
1901   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
1902   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
1903     uint32_t Trunc = static_cast<uint32_t>(Imm);
1904     return  AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
1905   }
1906   default:
1907     llvm_unreachable("invalid bitwidth");
1908   }
1909 }
1910 
1911 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
1912                                         const MCOperandInfo &OpInfo) const {
1913   switch (MO.getType()) {
1914   case MachineOperand::MO_Register:
1915     return false;
1916   case MachineOperand::MO_Immediate:
1917     return !isInlineConstant(MO, OpInfo);
1918   case MachineOperand::MO_FrameIndex:
1919   case MachineOperand::MO_MachineBasicBlock:
1920   case MachineOperand::MO_ExternalSymbol:
1921   case MachineOperand::MO_GlobalAddress:
1922   case MachineOperand::MO_MCSymbol:
1923     return true;
1924   default:
1925     llvm_unreachable("unexpected operand type");
1926   }
1927 }
1928 
1929 static bool compareMachineOp(const MachineOperand &Op0,
1930                              const MachineOperand &Op1) {
1931   if (Op0.getType() != Op1.getType())
1932     return false;
1933 
1934   switch (Op0.getType()) {
1935   case MachineOperand::MO_Register:
1936     return Op0.getReg() == Op1.getReg();
1937   case MachineOperand::MO_Immediate:
1938     return Op0.getImm() == Op1.getImm();
1939   default:
1940     llvm_unreachable("Didn't expect to be comparing these operand types");
1941   }
1942 }
1943 
1944 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
1945                                     const MachineOperand &MO) const {
1946   const MCOperandInfo &OpInfo = get(MI.getOpcode()).OpInfo[OpNo];
1947 
1948   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
1949 
1950   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
1951     return true;
1952 
1953   if (OpInfo.RegClass < 0)
1954     return false;
1955 
1956   if (MO.isImm() && isInlineConstant(MO, OpInfo))
1957     return RI.opCanUseInlineConstant(OpInfo.OperandType);
1958 
1959   return RI.opCanUseLiteralConstant(OpInfo.OperandType);
1960 }
1961 
1962 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
1963   int Op32 = AMDGPU::getVOPe32(Opcode);
1964   if (Op32 == -1)
1965     return false;
1966 
1967   return pseudoToMCOpcode(Op32) != -1;
1968 }
1969 
1970 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1971   // The src0_modifier operand is present on all instructions
1972   // that have modifiers.
1973 
1974   return AMDGPU::getNamedOperandIdx(Opcode,
1975                                     AMDGPU::OpName::src0_modifiers) != -1;
1976 }
1977 
1978 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1979                                   unsigned OpName) const {
1980   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1981   return Mods && Mods->getImm();
1982 }
1983 
1984 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
1985   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1986          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1987          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
1988          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
1989          hasModifiersSet(MI, AMDGPU::OpName::omod);
1990 }
1991 
1992 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1993                                   const MachineOperand &MO,
1994                                   const MCOperandInfo &OpInfo) const {
1995   // Literal constants use the constant bus.
1996   //if (isLiteralConstantLike(MO, OpInfo))
1997   // return true;
1998   if (MO.isImm())
1999     return !isInlineConstant(MO, OpInfo);
2000 
2001   if (!MO.isReg())
2002     return true; // Misc other operands like FrameIndex
2003 
2004   if (!MO.isUse())
2005     return false;
2006 
2007   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2008     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
2009 
2010   // FLAT_SCR is just an SGPR pair.
2011   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
2012     return true;
2013 
2014   // EXEC register uses the constant bus.
2015   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
2016     return true;
2017 
2018   // SGPRs use the constant bus
2019   return (MO.getReg() == AMDGPU::VCC || MO.getReg() == AMDGPU::M0 ||
2020           (!MO.isImplicit() &&
2021            (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
2022             AMDGPU::SGPR_64RegClass.contains(MO.getReg()))));
2023 }
2024 
2025 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
2026   for (const MachineOperand &MO : MI.implicit_operands()) {
2027     // We only care about reads.
2028     if (MO.isDef())
2029       continue;
2030 
2031     switch (MO.getReg()) {
2032     case AMDGPU::VCC:
2033     case AMDGPU::M0:
2034     case AMDGPU::FLAT_SCR:
2035       return MO.getReg();
2036 
2037     default:
2038       break;
2039     }
2040   }
2041 
2042   return AMDGPU::NoRegister;
2043 }
2044 
2045 static bool shouldReadExec(const MachineInstr &MI) {
2046   if (SIInstrInfo::isVALU(MI)) {
2047     switch (MI.getOpcode()) {
2048     case AMDGPU::V_READLANE_B32:
2049     case AMDGPU::V_READLANE_B32_si:
2050     case AMDGPU::V_READLANE_B32_vi:
2051     case AMDGPU::V_WRITELANE_B32:
2052     case AMDGPU::V_WRITELANE_B32_si:
2053     case AMDGPU::V_WRITELANE_B32_vi:
2054       return false;
2055     }
2056 
2057     return true;
2058   }
2059 
2060   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
2061       SIInstrInfo::isSALU(MI) ||
2062       SIInstrInfo::isSMRD(MI))
2063     return false;
2064 
2065   return true;
2066 }
2067 
2068 static bool isSubRegOf(const SIRegisterInfo &TRI,
2069                        const MachineOperand &SuperVec,
2070                        const MachineOperand &SubReg) {
2071   if (TargetRegisterInfo::isPhysicalRegister(SubReg.getReg()))
2072     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
2073 
2074   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
2075          SubReg.getReg() == SuperVec.getReg();
2076 }
2077 
2078 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
2079                                     StringRef &ErrInfo) const {
2080   uint16_t Opcode = MI.getOpcode();
2081   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2082   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
2083   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
2084   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
2085 
2086   // Make sure the number of operands is correct.
2087   const MCInstrDesc &Desc = get(Opcode);
2088   if (!Desc.isVariadic() &&
2089       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
2090     ErrInfo = "Instruction has wrong number of operands.";
2091     return false;
2092   }
2093 
2094   if (MI.isInlineAsm()) {
2095     // Verify register classes for inlineasm constraints.
2096     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
2097          I != E; ++I) {
2098       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
2099       if (!RC)
2100         continue;
2101 
2102       const MachineOperand &Op = MI.getOperand(I);
2103       if (!Op.isReg())
2104         continue;
2105 
2106       unsigned Reg = Op.getReg();
2107       if (!TargetRegisterInfo::isVirtualRegister(Reg) && !RC->contains(Reg)) {
2108         ErrInfo = "inlineasm operand has incorrect register class.";
2109         return false;
2110       }
2111     }
2112 
2113     return true;
2114   }
2115 
2116   // Make sure the register classes are correct.
2117   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
2118     if (MI.getOperand(i).isFPImm()) {
2119       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
2120                 "all fp values to integers.";
2121       return false;
2122     }
2123 
2124     int RegClass = Desc.OpInfo[i].RegClass;
2125 
2126     switch (Desc.OpInfo[i].OperandType) {
2127     case MCOI::OPERAND_REGISTER:
2128       if (MI.getOperand(i).isImm()) {
2129         ErrInfo = "Illegal immediate value for operand.";
2130         return false;
2131       }
2132       break;
2133     case AMDGPU::OPERAND_REG_IMM_INT32:
2134     case AMDGPU::OPERAND_REG_IMM_FP32:
2135       break;
2136     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
2137     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
2138     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
2139     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
2140     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
2141     case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
2142       const MachineOperand &MO = MI.getOperand(i);
2143       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
2144         ErrInfo = "Illegal immediate value for operand.";
2145         return false;
2146       }
2147       break;
2148     }
2149     case MCOI::OPERAND_IMMEDIATE:
2150     case AMDGPU::OPERAND_KIMM32:
2151       // Check if this operand is an immediate.
2152       // FrameIndex operands will be replaced by immediates, so they are
2153       // allowed.
2154       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
2155         ErrInfo = "Expected immediate, but got non-immediate";
2156         return false;
2157       }
2158       LLVM_FALLTHROUGH;
2159     default:
2160       continue;
2161     }
2162 
2163     if (!MI.getOperand(i).isReg())
2164       continue;
2165 
2166     if (RegClass != -1) {
2167       unsigned Reg = MI.getOperand(i).getReg();
2168       if (Reg == AMDGPU::NoRegister ||
2169           TargetRegisterInfo::isVirtualRegister(Reg))
2170         continue;
2171 
2172       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
2173       if (!RC->contains(Reg)) {
2174         ErrInfo = "Operand has incorrect register class.";
2175         return false;
2176       }
2177     }
2178   }
2179 
2180   // Verify VOP*
2181   if (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI)) {
2182     // Only look at the true operands. Only a real operand can use the constant
2183     // bus, and we don't want to check pseudo-operands like the source modifier
2184     // flags.
2185     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
2186 
2187     unsigned ConstantBusCount = 0;
2188 
2189     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
2190       ++ConstantBusCount;
2191 
2192     unsigned SGPRUsed = findImplicitSGPRRead(MI);
2193     if (SGPRUsed != AMDGPU::NoRegister)
2194       ++ConstantBusCount;
2195 
2196     for (int OpIdx : OpIndices) {
2197       if (OpIdx == -1)
2198         break;
2199       const MachineOperand &MO = MI.getOperand(OpIdx);
2200       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
2201         if (MO.isReg()) {
2202           if (MO.getReg() != SGPRUsed)
2203             ++ConstantBusCount;
2204           SGPRUsed = MO.getReg();
2205         } else {
2206           ++ConstantBusCount;
2207         }
2208       }
2209     }
2210     if (ConstantBusCount > 1) {
2211       ErrInfo = "VOP* instruction uses the constant bus more than once";
2212       return false;
2213     }
2214   }
2215 
2216   // Verify misc. restrictions on specific instructions.
2217   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
2218       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
2219     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
2220     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
2221     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
2222     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
2223       if (!compareMachineOp(Src0, Src1) &&
2224           !compareMachineOp(Src0, Src2)) {
2225         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
2226         return false;
2227       }
2228     }
2229   }
2230 
2231   if (isSOPK(MI)) {
2232     int64_t Imm = getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
2233     if (sopkIsZext(MI)) {
2234       if (!isUInt<16>(Imm)) {
2235         ErrInfo = "invalid immediate for SOPK instruction";
2236         return false;
2237       }
2238     } else {
2239       if (!isInt<16>(Imm)) {
2240         ErrInfo = "invalid immediate for SOPK instruction";
2241         return false;
2242       }
2243     }
2244   }
2245 
2246   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
2247       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
2248       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
2249       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
2250     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
2251                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
2252 
2253     const unsigned StaticNumOps = Desc.getNumOperands() +
2254       Desc.getNumImplicitUses();
2255     const unsigned NumImplicitOps = IsDst ? 2 : 1;
2256 
2257     // Allow additional implicit operands. This allows a fixup done by the post
2258     // RA scheduler where the main implicit operand is killed and implicit-defs
2259     // are added for sub-registers that remain live after this instruction.
2260     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
2261       ErrInfo = "missing implicit register operands";
2262       return false;
2263     }
2264 
2265     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
2266     if (IsDst) {
2267       if (!Dst->isUse()) {
2268         ErrInfo = "v_movreld_b32 vdst should be a use operand";
2269         return false;
2270       }
2271 
2272       unsigned UseOpIdx;
2273       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
2274           UseOpIdx != StaticNumOps + 1) {
2275         ErrInfo = "movrel implicit operands should be tied";
2276         return false;
2277       }
2278     }
2279 
2280     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
2281     const MachineOperand &ImpUse
2282       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
2283     if (!ImpUse.isReg() || !ImpUse.isUse() ||
2284         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
2285       ErrInfo = "src0 should be subreg of implicit vector use";
2286       return false;
2287     }
2288   }
2289 
2290   // Make sure we aren't losing exec uses in the td files. This mostly requires
2291   // being careful when using let Uses to try to add other use registers.
2292   if (shouldReadExec(MI)) {
2293     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
2294       ErrInfo = "VALU instruction does not implicitly read exec mask";
2295       return false;
2296     }
2297   }
2298 
2299   if (isSMRD(MI)) {
2300     if (MI.mayStore()) {
2301       // The register offset form of scalar stores may only use m0 as the
2302       // soffset register.
2303       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
2304       if (Soff && Soff->getReg() != AMDGPU::M0) {
2305         ErrInfo = "scalar stores must use m0 as offset register";
2306         return false;
2307       }
2308     }
2309   }
2310 
2311   return true;
2312 }
2313 
2314 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
2315   switch (MI.getOpcode()) {
2316   default: return AMDGPU::INSTRUCTION_LIST_END;
2317   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
2318   case AMDGPU::COPY: return AMDGPU::COPY;
2319   case AMDGPU::PHI: return AMDGPU::PHI;
2320   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
2321   case AMDGPU::S_MOV_B32:
2322     return MI.getOperand(1).isReg() ?
2323            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
2324   case AMDGPU::S_ADD_I32:
2325   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
2326   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
2327   case AMDGPU::S_SUB_I32:
2328   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
2329   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
2330   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
2331   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
2332   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
2333   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
2334   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
2335   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
2336   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
2337   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
2338   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
2339   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
2340   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
2341   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
2342   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
2343   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
2344   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
2345   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
2346   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
2347   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
2348   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
2349   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
2350   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
2351   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
2352   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
2353   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
2354   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
2355   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
2356   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
2357   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
2358   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
2359   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
2360   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
2361   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
2362   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
2363   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
2364   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
2365   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
2366   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
2367   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
2368   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
2369   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
2370   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
2371   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
2372   }
2373 }
2374 
2375 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
2376   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
2377 }
2378 
2379 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
2380                                                       unsigned OpNo) const {
2381   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2382   const MCInstrDesc &Desc = get(MI.getOpcode());
2383   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
2384       Desc.OpInfo[OpNo].RegClass == -1) {
2385     unsigned Reg = MI.getOperand(OpNo).getReg();
2386 
2387     if (TargetRegisterInfo::isVirtualRegister(Reg))
2388       return MRI.getRegClass(Reg);
2389     return RI.getPhysRegClass(Reg);
2390   }
2391 
2392   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
2393   return RI.getRegClass(RCID);
2394 }
2395 
2396 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
2397   switch (MI.getOpcode()) {
2398   case AMDGPU::COPY:
2399   case AMDGPU::REG_SEQUENCE:
2400   case AMDGPU::PHI:
2401   case AMDGPU::INSERT_SUBREG:
2402     return RI.hasVGPRs(getOpRegClass(MI, 0));
2403   default:
2404     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
2405   }
2406 }
2407 
2408 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
2409   MachineBasicBlock::iterator I = MI;
2410   MachineBasicBlock *MBB = MI.getParent();
2411   MachineOperand &MO = MI.getOperand(OpIdx);
2412   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
2413   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
2414   const TargetRegisterClass *RC = RI.getRegClass(RCID);
2415   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
2416   if (MO.isReg())
2417     Opcode = AMDGPU::COPY;
2418   else if (RI.isSGPRClass(RC))
2419     Opcode = AMDGPU::S_MOV_B32;
2420 
2421   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
2422   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
2423     VRC = &AMDGPU::VReg_64RegClass;
2424   else
2425     VRC = &AMDGPU::VGPR_32RegClass;
2426 
2427   unsigned Reg = MRI.createVirtualRegister(VRC);
2428   DebugLoc DL = MBB->findDebugLoc(I);
2429   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
2430   MO.ChangeToRegister(Reg, false);
2431 }
2432 
2433 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
2434                                          MachineRegisterInfo &MRI,
2435                                          MachineOperand &SuperReg,
2436                                          const TargetRegisterClass *SuperRC,
2437                                          unsigned SubIdx,
2438                                          const TargetRegisterClass *SubRC)
2439                                          const {
2440   MachineBasicBlock *MBB = MI->getParent();
2441   DebugLoc DL = MI->getDebugLoc();
2442   unsigned SubReg = MRI.createVirtualRegister(SubRC);
2443 
2444   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
2445     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
2446       .addReg(SuperReg.getReg(), 0, SubIdx);
2447     return SubReg;
2448   }
2449 
2450   // Just in case the super register is itself a sub-register, copy it to a new
2451   // value so we don't need to worry about merging its subreg index with the
2452   // SubIdx passed to this function. The register coalescer should be able to
2453   // eliminate this extra copy.
2454   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
2455 
2456   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
2457     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
2458 
2459   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
2460     .addReg(NewSuperReg, 0, SubIdx);
2461 
2462   return SubReg;
2463 }
2464 
2465 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
2466   MachineBasicBlock::iterator MII,
2467   MachineRegisterInfo &MRI,
2468   MachineOperand &Op,
2469   const TargetRegisterClass *SuperRC,
2470   unsigned SubIdx,
2471   const TargetRegisterClass *SubRC) const {
2472   if (Op.isImm()) {
2473     if (SubIdx == AMDGPU::sub0)
2474       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
2475     if (SubIdx == AMDGPU::sub1)
2476       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
2477 
2478     llvm_unreachable("Unhandled register index for immediate");
2479   }
2480 
2481   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
2482                                        SubIdx, SubRC);
2483   return MachineOperand::CreateReg(SubReg, false);
2484 }
2485 
2486 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
2487 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
2488   assert(Inst.getNumExplicitOperands() == 3);
2489   MachineOperand Op1 = Inst.getOperand(1);
2490   Inst.RemoveOperand(1);
2491   Inst.addOperand(Op1);
2492 }
2493 
2494 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
2495                                     const MCOperandInfo &OpInfo,
2496                                     const MachineOperand &MO) const {
2497   if (!MO.isReg())
2498     return false;
2499 
2500   unsigned Reg = MO.getReg();
2501   const TargetRegisterClass *RC =
2502     TargetRegisterInfo::isVirtualRegister(Reg) ?
2503     MRI.getRegClass(Reg) :
2504     RI.getPhysRegClass(Reg);
2505 
2506   const SIRegisterInfo *TRI =
2507       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
2508   RC = TRI->getSubRegClass(RC, MO.getSubReg());
2509 
2510   // In order to be legal, the common sub-class must be equal to the
2511   // class of the current operand.  For example:
2512   //
2513   // v_mov_b32 s0 ; Operand defined as vsrc_b32
2514   //              ; RI.getCommonSubClass(s0,vsrc_b32) = sgpr ; LEGAL
2515   //
2516   // s_sendmsg 0, s0 ; Operand defined as m0reg
2517   //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
2518 
2519   return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
2520 }
2521 
2522 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
2523                                      const MCOperandInfo &OpInfo,
2524                                      const MachineOperand &MO) const {
2525   if (MO.isReg())
2526     return isLegalRegOperand(MRI, OpInfo, MO);
2527 
2528   // Handle non-register types that are treated like immediates.
2529   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
2530   return true;
2531 }
2532 
2533 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
2534                                  const MachineOperand *MO) const {
2535   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2536   const MCInstrDesc &InstDesc = MI.getDesc();
2537   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
2538   const TargetRegisterClass *DefinedRC =
2539       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
2540   if (!MO)
2541     MO = &MI.getOperand(OpIdx);
2542 
2543   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
2544 
2545     RegSubRegPair SGPRUsed;
2546     if (MO->isReg())
2547       SGPRUsed = RegSubRegPair(MO->getReg(), MO->getSubReg());
2548 
2549     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2550       if (i == OpIdx)
2551         continue;
2552       const MachineOperand &Op = MI.getOperand(i);
2553       if (Op.isReg()) {
2554         if ((Op.getReg() != SGPRUsed.Reg || Op.getSubReg() != SGPRUsed.SubReg) &&
2555             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
2556           return false;
2557         }
2558       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
2559         return false;
2560       }
2561     }
2562   }
2563 
2564   if (MO->isReg()) {
2565     assert(DefinedRC);
2566     return isLegalRegOperand(MRI, OpInfo, *MO);
2567   }
2568 
2569   // Handle non-register types that are treated like immediates.
2570   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
2571 
2572   if (!DefinedRC) {
2573     // This operand expects an immediate.
2574     return true;
2575   }
2576 
2577   return isImmOperandLegal(MI, OpIdx, *MO);
2578 }
2579 
2580 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
2581                                        MachineInstr &MI) const {
2582   unsigned Opc = MI.getOpcode();
2583   const MCInstrDesc &InstrDesc = get(Opc);
2584 
2585   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2586   MachineOperand &Src1 = MI.getOperand(Src1Idx);
2587 
2588   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
2589   // we need to only have one constant bus use.
2590   //
2591   // Note we do not need to worry about literal constants here. They are
2592   // disabled for the operand type for instructions because they will always
2593   // violate the one constant bus use rule.
2594   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
2595   if (HasImplicitSGPR) {
2596     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2597     MachineOperand &Src0 = MI.getOperand(Src0Idx);
2598 
2599     if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg()))
2600       legalizeOpWithMove(MI, Src0Idx);
2601   }
2602 
2603   // VOP2 src0 instructions support all operand types, so we don't need to check
2604   // their legality. If src1 is already legal, we don't need to do anything.
2605   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
2606     return;
2607 
2608   // We do not use commuteInstruction here because it is too aggressive and will
2609   // commute if it is possible. We only want to commute here if it improves
2610   // legality. This can be called a fairly large number of times so don't waste
2611   // compile time pointlessly swapping and checking legality again.
2612   if (HasImplicitSGPR || !MI.isCommutable()) {
2613     legalizeOpWithMove(MI, Src1Idx);
2614     return;
2615   }
2616 
2617   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2618   MachineOperand &Src0 = MI.getOperand(Src0Idx);
2619 
2620   // If src0 can be used as src1, commuting will make the operands legal.
2621   // Otherwise we have to give up and insert a move.
2622   //
2623   // TODO: Other immediate-like operand kinds could be commuted if there was a
2624   // MachineOperand::ChangeTo* for them.
2625   if ((!Src1.isImm() && !Src1.isReg()) ||
2626       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
2627     legalizeOpWithMove(MI, Src1Idx);
2628     return;
2629   }
2630 
2631   int CommutedOpc = commuteOpcode(MI);
2632   if (CommutedOpc == -1) {
2633     legalizeOpWithMove(MI, Src1Idx);
2634     return;
2635   }
2636 
2637   MI.setDesc(get(CommutedOpc));
2638 
2639   unsigned Src0Reg = Src0.getReg();
2640   unsigned Src0SubReg = Src0.getSubReg();
2641   bool Src0Kill = Src0.isKill();
2642 
2643   if (Src1.isImm())
2644     Src0.ChangeToImmediate(Src1.getImm());
2645   else if (Src1.isReg()) {
2646     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
2647     Src0.setSubReg(Src1.getSubReg());
2648   } else
2649     llvm_unreachable("Should only have register or immediate operands");
2650 
2651   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
2652   Src1.setSubReg(Src0SubReg);
2653 }
2654 
2655 // Legalize VOP3 operands. Because all operand types are supported for any
2656 // operand, and since literal constants are not allowed and should never be
2657 // seen, we only need to worry about inserting copies if we use multiple SGPR
2658 // operands.
2659 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
2660                                        MachineInstr &MI) const {
2661   unsigned Opc = MI.getOpcode();
2662 
2663   int VOP3Idx[3] = {
2664     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
2665     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
2666     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
2667   };
2668 
2669   // Find the one SGPR operand we are allowed to use.
2670   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
2671 
2672   for (unsigned i = 0; i < 3; ++i) {
2673     int Idx = VOP3Idx[i];
2674     if (Idx == -1)
2675       break;
2676     MachineOperand &MO = MI.getOperand(Idx);
2677 
2678     // We should never see a VOP3 instruction with an illegal immediate operand.
2679     if (!MO.isReg())
2680       continue;
2681 
2682     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2683       continue; // VGPRs are legal
2684 
2685     if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
2686       SGPRReg = MO.getReg();
2687       // We can use one SGPR in each VOP3 instruction.
2688       continue;
2689     }
2690 
2691     // If we make it this far, then the operand is not legal and we must
2692     // legalize it.
2693     legalizeOpWithMove(MI, Idx);
2694   }
2695 }
2696 
2697 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
2698                                          MachineRegisterInfo &MRI) const {
2699   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
2700   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
2701   unsigned DstReg = MRI.createVirtualRegister(SRC);
2702   unsigned SubRegs = VRC->getSize() / 4;
2703 
2704   SmallVector<unsigned, 8> SRegs;
2705   for (unsigned i = 0; i < SubRegs; ++i) {
2706     unsigned SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2707     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2708             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
2709         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
2710     SRegs.push_back(SGPR);
2711   }
2712 
2713   MachineInstrBuilder MIB =
2714       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2715               get(AMDGPU::REG_SEQUENCE), DstReg);
2716   for (unsigned i = 0; i < SubRegs; ++i) {
2717     MIB.addReg(SRegs[i]);
2718     MIB.addImm(RI.getSubRegFromChannel(i));
2719   }
2720   return DstReg;
2721 }
2722 
2723 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
2724                                        MachineInstr &MI) const {
2725 
2726   // If the pointer is store in VGPRs, then we need to move them to
2727   // SGPRs using v_readfirstlane.  This is safe because we only select
2728   // loads with uniform pointers to SMRD instruction so we know the
2729   // pointer value is uniform.
2730   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
2731   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
2732       unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
2733       SBase->setReg(SGPR);
2734   }
2735 }
2736 
2737 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
2738                                          MachineBasicBlock::iterator I,
2739                                          const TargetRegisterClass *DstRC,
2740                                          MachineOperand &Op,
2741                                          MachineRegisterInfo &MRI,
2742                                          const DebugLoc &DL) const {
2743 
2744   unsigned OpReg = Op.getReg();
2745   unsigned OpSubReg = Op.getSubReg();
2746 
2747   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
2748       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
2749 
2750   // Check if operand is already the correct register class.
2751   if (DstRC == OpRC)
2752     return;
2753 
2754   unsigned DstReg = MRI.createVirtualRegister(DstRC);
2755   MachineInstr *Copy =
2756       BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
2757 
2758   Op.setReg(DstReg);
2759   Op.setSubReg(0);
2760 
2761   MachineInstr *Def = MRI.getVRegDef(OpReg);
2762   if (!Def)
2763     return;
2764 
2765   // Try to eliminate the copy if it is copying an immediate value.
2766   if (Def->isMoveImmediate())
2767     FoldImmediate(*Copy, *Def, OpReg, &MRI);
2768 }
2769 
2770 void SIInstrInfo::legalizeOperands(MachineInstr &MI) const {
2771   MachineFunction &MF = *MI.getParent()->getParent();
2772   MachineRegisterInfo &MRI = MF.getRegInfo();
2773 
2774   // Legalize VOP2
2775   if (isVOP2(MI) || isVOPC(MI)) {
2776     legalizeOperandsVOP2(MRI, MI);
2777     return;
2778   }
2779 
2780   // Legalize VOP3
2781   if (isVOP3(MI)) {
2782     legalizeOperandsVOP3(MRI, MI);
2783     return;
2784   }
2785 
2786   // Legalize SMRD
2787   if (isSMRD(MI)) {
2788     legalizeOperandsSMRD(MRI, MI);
2789     return;
2790   }
2791 
2792   // Legalize REG_SEQUENCE and PHI
2793   // The register class of the operands much be the same type as the register
2794   // class of the output.
2795   if (MI.getOpcode() == AMDGPU::PHI) {
2796     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
2797     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
2798       if (!MI.getOperand(i).isReg() ||
2799           !TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
2800         continue;
2801       const TargetRegisterClass *OpRC =
2802           MRI.getRegClass(MI.getOperand(i).getReg());
2803       if (RI.hasVGPRs(OpRC)) {
2804         VRC = OpRC;
2805       } else {
2806         SRC = OpRC;
2807       }
2808     }
2809 
2810     // If any of the operands are VGPR registers, then they all most be
2811     // otherwise we will create illegal VGPR->SGPR copies when legalizing
2812     // them.
2813     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
2814       if (!VRC) {
2815         assert(SRC);
2816         VRC = RI.getEquivalentVGPRClass(SRC);
2817       }
2818       RC = VRC;
2819     } else {
2820       RC = SRC;
2821     }
2822 
2823     // Update all the operands so they have the same type.
2824     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2825       MachineOperand &Op = MI.getOperand(I);
2826       if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2827         continue;
2828 
2829       // MI is a PHI instruction.
2830       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
2831       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
2832 
2833       // Avoid creating no-op copies with the same src and dst reg class.  These
2834       // confuse some of the machine passes.
2835       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
2836     }
2837   }
2838 
2839   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
2840   // VGPR dest type and SGPR sources, insert copies so all operands are
2841   // VGPRs. This seems to help operand folding / the register coalescer.
2842   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
2843     MachineBasicBlock *MBB = MI.getParent();
2844     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
2845     if (RI.hasVGPRs(DstRC)) {
2846       // Update all the operands so they are VGPR register classes. These may
2847       // not be the same register class because REG_SEQUENCE supports mixing
2848       // subregister index types e.g. sub0_sub1 + sub2 + sub3
2849       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2850         MachineOperand &Op = MI.getOperand(I);
2851         if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2852           continue;
2853 
2854         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
2855         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
2856         if (VRC == OpRC)
2857           continue;
2858 
2859         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
2860         Op.setIsKill();
2861       }
2862     }
2863 
2864     return;
2865   }
2866 
2867   // Legalize INSERT_SUBREG
2868   // src0 must have the same register class as dst
2869   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
2870     unsigned Dst = MI.getOperand(0).getReg();
2871     unsigned Src0 = MI.getOperand(1).getReg();
2872     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
2873     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
2874     if (DstRC != Src0RC) {
2875       MachineBasicBlock *MBB = MI.getParent();
2876       MachineOperand &Op = MI.getOperand(1);
2877       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
2878     }
2879     return;
2880   }
2881 
2882   // Legalize MIMG and MUBUF/MTBUF for shaders.
2883   //
2884   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
2885   // scratch memory access. In both cases, the legalization never involves
2886   // conversion to the addr64 form.
2887   if (isMIMG(MI) ||
2888       (AMDGPU::isShader(MF.getFunction()->getCallingConv()) &&
2889        (isMUBUF(MI) || isMTBUF(MI)))) {
2890     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
2891     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
2892       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
2893       SRsrc->setReg(SGPR);
2894     }
2895 
2896     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
2897     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
2898       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
2899       SSamp->setReg(SGPR);
2900     }
2901     return;
2902   }
2903 
2904   // Legalize MUBUF* instructions by converting to addr64 form.
2905   // FIXME: If we start using the non-addr64 instructions for compute, we
2906   // may need to legalize them as above. This especially applies to the
2907   // buffer_load_format_* variants and variants with idxen (or bothen).
2908   int SRsrcIdx =
2909       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
2910   if (SRsrcIdx != -1) {
2911     // We have an MUBUF instruction
2912     MachineOperand *SRsrc = &MI.getOperand(SRsrcIdx);
2913     unsigned SRsrcRC = get(MI.getOpcode()).OpInfo[SRsrcIdx].RegClass;
2914     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
2915                                              RI.getRegClass(SRsrcRC))) {
2916       // The operands are legal.
2917       // FIXME: We may need to legalize operands besided srsrc.
2918       return;
2919     }
2920 
2921     MachineBasicBlock &MBB = *MI.getParent();
2922 
2923     // Extract the ptr from the resource descriptor.
2924     unsigned SRsrcPtr = buildExtractSubReg(MI, MRI, *SRsrc,
2925       &AMDGPU::VReg_128RegClass, AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
2926 
2927     // Create an empty resource descriptor
2928     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2929     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2930     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2931     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
2932     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
2933 
2934     // Zero64 = 0
2935     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B64), Zero64)
2936         .addImm(0);
2937 
2938     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
2939     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
2940         .addImm(RsrcDataFormat & 0xFFFFFFFF);
2941 
2942     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
2943     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
2944         .addImm(RsrcDataFormat >> 32);
2945 
2946     // NewSRsrc = {Zero64, SRsrcFormat}
2947     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewSRsrc)
2948         .addReg(Zero64)
2949         .addImm(AMDGPU::sub0_sub1)
2950         .addReg(SRsrcFormatLo)
2951         .addImm(AMDGPU::sub2)
2952         .addReg(SRsrcFormatHi)
2953         .addImm(AMDGPU::sub3);
2954 
2955     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
2956     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2957     if (VAddr) {
2958       // This is already an ADDR64 instruction so we need to add the pointer
2959       // extracted from the resource descriptor to the current value of VAddr.
2960       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2961       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2962 
2963       // NewVaddrLo = SRsrcPtr:sub0 + VAddr:sub0
2964       DebugLoc DL = MI.getDebugLoc();
2965       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), NewVAddrLo)
2966         .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2967         .addReg(VAddr->getReg(), 0, AMDGPU::sub0);
2968 
2969       // NewVaddrHi = SRsrcPtr:sub1 + VAddr:sub1
2970       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e32), NewVAddrHi)
2971         .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2972         .addReg(VAddr->getReg(), 0, AMDGPU::sub1);
2973 
2974       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2975       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
2976           .addReg(NewVAddrLo)
2977           .addImm(AMDGPU::sub0)
2978           .addReg(NewVAddrHi)
2979           .addImm(AMDGPU::sub1);
2980     } else {
2981       // This instructions is the _OFFSET variant, so we need to convert it to
2982       // ADDR64.
2983       assert(MBB.getParent()->getSubtarget<SISubtarget>().getGeneration()
2984              < SISubtarget::VOLCANIC_ISLANDS &&
2985              "FIXME: Need to emit flat atomics here");
2986 
2987       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
2988       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
2989       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
2990       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
2991 
2992       // Atomics rith return have have an additional tied operand and are
2993       // missing some of the special bits.
2994       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
2995       MachineInstr *Addr64;
2996 
2997       if (!VDataIn) {
2998         // Regular buffer load / store.
2999         MachineInstrBuilder MIB =
3000             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
3001                 .add(*VData)
3002                 .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
3003                 // This will be replaced later
3004                 // with the new value of vaddr.
3005                 .add(*SRsrc)
3006                 .add(*SOffset)
3007                 .add(*Offset);
3008 
3009         // Atomics do not have this operand.
3010         if (const MachineOperand *GLC =
3011                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
3012           MIB.addImm(GLC->getImm());
3013         }
3014 
3015         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
3016 
3017         if (const MachineOperand *TFE =
3018                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
3019           MIB.addImm(TFE->getImm());
3020         }
3021 
3022         MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3023         Addr64 = MIB;
3024       } else {
3025         // Atomics with return.
3026         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
3027                      .add(*VData)
3028                      .add(*VDataIn)
3029                      .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
3030                      // This will be replaced later
3031                      // with the new value of vaddr.
3032                      .add(*SRsrc)
3033                      .add(*SOffset)
3034                      .add(*Offset)
3035                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
3036                      .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3037       }
3038 
3039       MI.removeFromParent();
3040 
3041       // NewVaddr = {NewVaddrHi, NewVaddrLo}
3042       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
3043               NewVAddr)
3044           .addReg(SRsrcPtr, 0, AMDGPU::sub0)
3045           .addImm(AMDGPU::sub0)
3046           .addReg(SRsrcPtr, 0, AMDGPU::sub1)
3047           .addImm(AMDGPU::sub1);
3048 
3049       VAddr = getNamedOperand(*Addr64, AMDGPU::OpName::vaddr);
3050       SRsrc = getNamedOperand(*Addr64, AMDGPU::OpName::srsrc);
3051     }
3052 
3053     // Update the instruction to use NewVaddr
3054     VAddr->setReg(NewVAddr);
3055     // Update the instruction to use NewSRsrc
3056     SRsrc->setReg(NewSRsrc);
3057   }
3058 }
3059 
3060 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
3061   SmallVector<MachineInstr *, 128> Worklist;
3062   Worklist.push_back(&TopInst);
3063 
3064   while (!Worklist.empty()) {
3065     MachineInstr &Inst = *Worklist.pop_back_val();
3066     MachineBasicBlock *MBB = Inst.getParent();
3067     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
3068 
3069     unsigned Opcode = Inst.getOpcode();
3070     unsigned NewOpcode = getVALUOp(Inst);
3071 
3072     // Handle some special cases
3073     switch (Opcode) {
3074     default:
3075       break;
3076     case AMDGPU::S_AND_B64:
3077       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_AND_B32_e64);
3078       Inst.eraseFromParent();
3079       continue;
3080 
3081     case AMDGPU::S_OR_B64:
3082       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_OR_B32_e64);
3083       Inst.eraseFromParent();
3084       continue;
3085 
3086     case AMDGPU::S_XOR_B64:
3087       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_XOR_B32_e64);
3088       Inst.eraseFromParent();
3089       continue;
3090 
3091     case AMDGPU::S_NOT_B64:
3092       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::V_NOT_B32_e32);
3093       Inst.eraseFromParent();
3094       continue;
3095 
3096     case AMDGPU::S_BCNT1_I32_B64:
3097       splitScalar64BitBCNT(Worklist, Inst);
3098       Inst.eraseFromParent();
3099       continue;
3100 
3101     case AMDGPU::S_BFE_I64: {
3102       splitScalar64BitBFE(Worklist, Inst);
3103       Inst.eraseFromParent();
3104       continue;
3105     }
3106 
3107     case AMDGPU::S_LSHL_B32:
3108       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
3109         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
3110         swapOperands(Inst);
3111       }
3112       break;
3113     case AMDGPU::S_ASHR_I32:
3114       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
3115         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
3116         swapOperands(Inst);
3117       }
3118       break;
3119     case AMDGPU::S_LSHR_B32:
3120       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
3121         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
3122         swapOperands(Inst);
3123       }
3124       break;
3125     case AMDGPU::S_LSHL_B64:
3126       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
3127         NewOpcode = AMDGPU::V_LSHLREV_B64;
3128         swapOperands(Inst);
3129       }
3130       break;
3131     case AMDGPU::S_ASHR_I64:
3132       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
3133         NewOpcode = AMDGPU::V_ASHRREV_I64;
3134         swapOperands(Inst);
3135       }
3136       break;
3137     case AMDGPU::S_LSHR_B64:
3138       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
3139         NewOpcode = AMDGPU::V_LSHRREV_B64;
3140         swapOperands(Inst);
3141       }
3142       break;
3143 
3144     case AMDGPU::S_ABS_I32:
3145       lowerScalarAbs(Worklist, Inst);
3146       Inst.eraseFromParent();
3147       continue;
3148 
3149     case AMDGPU::S_CBRANCH_SCC0:
3150     case AMDGPU::S_CBRANCH_SCC1:
3151       // Clear unused bits of vcc
3152       BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
3153               AMDGPU::VCC)
3154           .addReg(AMDGPU::EXEC)
3155           .addReg(AMDGPU::VCC);
3156       break;
3157 
3158     case AMDGPU::S_BFE_U64:
3159     case AMDGPU::S_BFM_B64:
3160       llvm_unreachable("Moving this op to VALU not implemented");
3161 
3162     case AMDGPU::S_PACK_LL_B32_B16:
3163     case AMDGPU::S_PACK_LH_B32_B16:
3164     case AMDGPU::S_PACK_HH_B32_B16: {
3165       movePackToVALU(Worklist, MRI, Inst);
3166       Inst.eraseFromParent();
3167       continue;
3168     }
3169     }
3170 
3171     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
3172       // We cannot move this instruction to the VALU, so we should try to
3173       // legalize its operands instead.
3174       legalizeOperands(Inst);
3175       continue;
3176     }
3177 
3178     // Use the new VALU Opcode.
3179     const MCInstrDesc &NewDesc = get(NewOpcode);
3180     Inst.setDesc(NewDesc);
3181 
3182     // Remove any references to SCC. Vector instructions can't read from it, and
3183     // We're just about to add the implicit use / defs of VCC, and we don't want
3184     // both.
3185     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
3186       MachineOperand &Op = Inst.getOperand(i);
3187       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
3188         Inst.RemoveOperand(i);
3189         addSCCDefUsersToVALUWorklist(Inst, Worklist);
3190       }
3191     }
3192 
3193     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
3194       // We are converting these to a BFE, so we need to add the missing
3195       // operands for the size and offset.
3196       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
3197       Inst.addOperand(MachineOperand::CreateImm(0));
3198       Inst.addOperand(MachineOperand::CreateImm(Size));
3199 
3200     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
3201       // The VALU version adds the second operand to the result, so insert an
3202       // extra 0 operand.
3203       Inst.addOperand(MachineOperand::CreateImm(0));
3204     }
3205 
3206     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
3207 
3208     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
3209       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
3210       // If we need to move this to VGPRs, we need to unpack the second operand
3211       // back into the 2 separate ones for bit offset and width.
3212       assert(OffsetWidthOp.isImm() &&
3213              "Scalar BFE is only implemented for constant width and offset");
3214       uint32_t Imm = OffsetWidthOp.getImm();
3215 
3216       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
3217       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
3218       Inst.RemoveOperand(2);                     // Remove old immediate.
3219       Inst.addOperand(MachineOperand::CreateImm(Offset));
3220       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
3221     }
3222 
3223     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
3224     unsigned NewDstReg = AMDGPU::NoRegister;
3225     if (HasDst) {
3226       // Update the destination register class.
3227       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
3228       if (!NewDstRC)
3229         continue;
3230 
3231       unsigned DstReg = Inst.getOperand(0).getReg();
3232       if (Inst.isCopy() &&
3233           TargetRegisterInfo::isVirtualRegister(Inst.getOperand(1).getReg()) &&
3234           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
3235         // Instead of creating a copy where src and dst are the same register
3236         // class, we just replace all uses of dst with src.  These kinds of
3237         // copies interfere with the heuristics MachineSink uses to decide
3238         // whether or not to split a critical edge.  Since the pass assumes
3239         // that copies will end up as machine instructions and not be
3240         // eliminated.
3241         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
3242         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
3243         MRI.clearKillFlags(Inst.getOperand(1).getReg());
3244         Inst.getOperand(0).setReg(DstReg);
3245         continue;
3246       }
3247 
3248       NewDstReg = MRI.createVirtualRegister(NewDstRC);
3249       MRI.replaceRegWith(DstReg, NewDstReg);
3250     }
3251 
3252     // Legalize the operands
3253     legalizeOperands(Inst);
3254 
3255     if (HasDst)
3256      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
3257   }
3258 }
3259 
3260 void SIInstrInfo::lowerScalarAbs(SmallVectorImpl<MachineInstr *> &Worklist,
3261                                  MachineInstr &Inst) const {
3262   MachineBasicBlock &MBB = *Inst.getParent();
3263   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3264   MachineBasicBlock::iterator MII = Inst;
3265   DebugLoc DL = Inst.getDebugLoc();
3266 
3267   MachineOperand &Dest = Inst.getOperand(0);
3268   MachineOperand &Src = Inst.getOperand(1);
3269   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3270   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3271 
3272   BuildMI(MBB, MII, DL, get(AMDGPU::V_SUB_I32_e32), TmpReg)
3273     .addImm(0)
3274     .addReg(Src.getReg());
3275 
3276   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
3277     .addReg(Src.getReg())
3278     .addReg(TmpReg);
3279 
3280   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3281   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3282 }
3283 
3284 void SIInstrInfo::splitScalar64BitUnaryOp(
3285     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
3286     unsigned Opcode) const {
3287   MachineBasicBlock &MBB = *Inst.getParent();
3288   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3289 
3290   MachineOperand &Dest = Inst.getOperand(0);
3291   MachineOperand &Src0 = Inst.getOperand(1);
3292   DebugLoc DL = Inst.getDebugLoc();
3293 
3294   MachineBasicBlock::iterator MII = Inst;
3295 
3296   const MCInstrDesc &InstDesc = get(Opcode);
3297   const TargetRegisterClass *Src0RC = Src0.isReg() ?
3298     MRI.getRegClass(Src0.getReg()) :
3299     &AMDGPU::SGPR_32RegClass;
3300 
3301   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
3302 
3303   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3304                                                        AMDGPU::sub0, Src0SubRC);
3305 
3306   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
3307   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
3308   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
3309 
3310   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
3311   BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
3312 
3313   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3314                                                        AMDGPU::sub1, Src0SubRC);
3315 
3316   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
3317   BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
3318 
3319   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
3320   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
3321     .addReg(DestSub0)
3322     .addImm(AMDGPU::sub0)
3323     .addReg(DestSub1)
3324     .addImm(AMDGPU::sub1);
3325 
3326   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
3327 
3328   // We don't need to legalizeOperands here because for a single operand, src0
3329   // will support any kind of input.
3330 
3331   // Move all users of this moved value.
3332   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
3333 }
3334 
3335 void SIInstrInfo::splitScalar64BitBinaryOp(
3336     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
3337     unsigned Opcode) const {
3338   MachineBasicBlock &MBB = *Inst.getParent();
3339   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3340 
3341   MachineOperand &Dest = Inst.getOperand(0);
3342   MachineOperand &Src0 = Inst.getOperand(1);
3343   MachineOperand &Src1 = Inst.getOperand(2);
3344   DebugLoc DL = Inst.getDebugLoc();
3345 
3346   MachineBasicBlock::iterator MII = Inst;
3347 
3348   const MCInstrDesc &InstDesc = get(Opcode);
3349   const TargetRegisterClass *Src0RC = Src0.isReg() ?
3350     MRI.getRegClass(Src0.getReg()) :
3351     &AMDGPU::SGPR_32RegClass;
3352 
3353   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
3354   const TargetRegisterClass *Src1RC = Src1.isReg() ?
3355     MRI.getRegClass(Src1.getReg()) :
3356     &AMDGPU::SGPR_32RegClass;
3357 
3358   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
3359 
3360   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3361                                                        AMDGPU::sub0, Src0SubRC);
3362   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
3363                                                        AMDGPU::sub0, Src1SubRC);
3364 
3365   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
3366   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
3367   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
3368 
3369   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
3370   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
3371                               .add(SrcReg0Sub0)
3372                               .add(SrcReg1Sub0);
3373 
3374   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3375                                                        AMDGPU::sub1, Src0SubRC);
3376   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
3377                                                        AMDGPU::sub1, Src1SubRC);
3378 
3379   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
3380   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
3381                               .add(SrcReg0Sub1)
3382                               .add(SrcReg1Sub1);
3383 
3384   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
3385   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
3386     .addReg(DestSub0)
3387     .addImm(AMDGPU::sub0)
3388     .addReg(DestSub1)
3389     .addImm(AMDGPU::sub1);
3390 
3391   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
3392 
3393   // Try to legalize the operands in case we need to swap the order to keep it
3394   // valid.
3395   legalizeOperands(LoHalf);
3396   legalizeOperands(HiHalf);
3397 
3398   // Move all users of this moved vlaue.
3399   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
3400 }
3401 
3402 void SIInstrInfo::splitScalar64BitBCNT(
3403     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst) const {
3404   MachineBasicBlock &MBB = *Inst.getParent();
3405   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3406 
3407   MachineBasicBlock::iterator MII = Inst;
3408   DebugLoc DL = Inst.getDebugLoc();
3409 
3410   MachineOperand &Dest = Inst.getOperand(0);
3411   MachineOperand &Src = Inst.getOperand(1);
3412 
3413   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
3414   const TargetRegisterClass *SrcRC = Src.isReg() ?
3415     MRI.getRegClass(Src.getReg()) :
3416     &AMDGPU::SGPR_32RegClass;
3417 
3418   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3419   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3420 
3421   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
3422 
3423   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
3424                                                       AMDGPU::sub0, SrcSubRC);
3425   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
3426                                                       AMDGPU::sub1, SrcSubRC);
3427 
3428   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
3429 
3430   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
3431 
3432   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3433 
3434   // We don't need to legalize operands here. src0 for etiher instruction can be
3435   // an SGPR, and the second input is unused or determined here.
3436   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3437 }
3438 
3439 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
3440                                       MachineInstr &Inst) const {
3441   MachineBasicBlock &MBB = *Inst.getParent();
3442   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3443   MachineBasicBlock::iterator MII = Inst;
3444   DebugLoc DL = Inst.getDebugLoc();
3445 
3446   MachineOperand &Dest = Inst.getOperand(0);
3447   uint32_t Imm = Inst.getOperand(2).getImm();
3448   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
3449   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
3450 
3451   (void) Offset;
3452 
3453   // Only sext_inreg cases handled.
3454   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
3455          Offset == 0 && "Not implemented");
3456 
3457   if (BitWidth < 32) {
3458     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3459     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3460     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
3461 
3462     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
3463         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
3464         .addImm(0)
3465         .addImm(BitWidth);
3466 
3467     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
3468       .addImm(31)
3469       .addReg(MidRegLo);
3470 
3471     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
3472       .addReg(MidRegLo)
3473       .addImm(AMDGPU::sub0)
3474       .addReg(MidRegHi)
3475       .addImm(AMDGPU::sub1);
3476 
3477     MRI.replaceRegWith(Dest.getReg(), ResultReg);
3478     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3479     return;
3480   }
3481 
3482   MachineOperand &Src = Inst.getOperand(1);
3483   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3484   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
3485 
3486   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
3487     .addImm(31)
3488     .addReg(Src.getReg(), 0, AMDGPU::sub0);
3489 
3490   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
3491     .addReg(Src.getReg(), 0, AMDGPU::sub0)
3492     .addImm(AMDGPU::sub0)
3493     .addReg(TmpReg)
3494     .addImm(AMDGPU::sub1);
3495 
3496   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3497   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3498 }
3499 
3500 void SIInstrInfo::addUsersToMoveToVALUWorklist(
3501   unsigned DstReg,
3502   MachineRegisterInfo &MRI,
3503   SmallVectorImpl<MachineInstr *> &Worklist) const {
3504   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
3505          E = MRI.use_end(); I != E;) {
3506     MachineInstr &UseMI = *I->getParent();
3507     if (!canReadVGPR(UseMI, I.getOperandNo())) {
3508       Worklist.push_back(&UseMI);
3509 
3510       do {
3511         ++I;
3512       } while (I != E && I->getParent() == &UseMI);
3513     } else {
3514       ++I;
3515     }
3516   }
3517 }
3518 
3519 void SIInstrInfo::movePackToVALU(SmallVectorImpl<MachineInstr *> &Worklist,
3520                                  MachineRegisterInfo &MRI,
3521                                  MachineInstr &Inst) const {
3522   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3523   MachineBasicBlock *MBB = Inst.getParent();
3524   MachineOperand &Src0 = Inst.getOperand(1);
3525   MachineOperand &Src1 = Inst.getOperand(2);
3526   const DebugLoc &DL = Inst.getDebugLoc();
3527 
3528   switch (Inst.getOpcode()) {
3529   case AMDGPU::S_PACK_LL_B32_B16: {
3530     // v_pack_b32_f16 flushes denormals if not enabled. Use it if the default
3531     // is to leave them untouched.
3532     // XXX: Does this do anything to NaNs?
3533     if (ST.hasFP16Denormals()) {
3534       BuildMI(*MBB, Inst, DL, get(AMDGPU::V_PACK_B32_F16), ResultReg)
3535         .addImm(0)  // src0_modifiers
3536         .add(Src0)  // src0
3537         .addImm(0)  // src1_modifiers
3538         .add(Src1)  // src2
3539         .addImm(0)  // clamp
3540         .addImm(0); // omod
3541     } else {
3542       unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3543       unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3544 
3545       // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
3546       // 0.
3547       BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
3548         .addImm(0xffff);
3549 
3550       BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
3551         .addReg(ImmReg, RegState::Kill)
3552         .add(Src0);
3553 
3554       BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32), ResultReg)
3555         .add(Src1)
3556         .addImm(16)
3557         .addReg(TmpReg, RegState::Kill);
3558     }
3559 
3560     break;
3561   }
3562   case AMDGPU::S_PACK_LH_B32_B16: {
3563     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3564     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
3565       .addImm(0xffff);
3566     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32), ResultReg)
3567       .addReg(ImmReg, RegState::Kill)
3568       .add(Src0)
3569       .add(Src1);
3570     break;
3571   }
3572   case AMDGPU::S_PACK_HH_B32_B16: {
3573     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3574     unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3575     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
3576       .addImm(16)
3577       .add(Src0);
3578     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
3579       .addImm(0xffff);
3580     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32), ResultReg)
3581       .add(Src1)
3582       .addReg(ImmReg, RegState::Kill)
3583       .addReg(TmpReg, RegState::Kill);
3584     break;
3585   }
3586   default:
3587     llvm_unreachable("unhandled s_pack_* instruction");
3588   }
3589 
3590   MachineOperand &Dest = Inst.getOperand(0);
3591   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3592   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3593 }
3594 
3595 void SIInstrInfo::addSCCDefUsersToVALUWorklist(
3596     MachineInstr &SCCDefInst, SmallVectorImpl<MachineInstr *> &Worklist) const {
3597   // This assumes that all the users of SCC are in the same block
3598   // as the SCC def.
3599   for (MachineInstr &MI :
3600        llvm::make_range(MachineBasicBlock::iterator(SCCDefInst),
3601                         SCCDefInst.getParent()->end())) {
3602     // Exit if we find another SCC def.
3603     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC) != -1)
3604       return;
3605 
3606     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC) != -1)
3607       Worklist.push_back(&MI);
3608   }
3609 }
3610 
3611 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
3612   const MachineInstr &Inst) const {
3613   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
3614 
3615   switch (Inst.getOpcode()) {
3616   // For target instructions, getOpRegClass just returns the virtual register
3617   // class associated with the operand, so we need to find an equivalent VGPR
3618   // register class in order to move the instruction to the VALU.
3619   case AMDGPU::COPY:
3620   case AMDGPU::PHI:
3621   case AMDGPU::REG_SEQUENCE:
3622   case AMDGPU::INSERT_SUBREG:
3623     if (RI.hasVGPRs(NewDstRC))
3624       return nullptr;
3625 
3626     NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
3627     if (!NewDstRC)
3628       return nullptr;
3629     return NewDstRC;
3630   default:
3631     return NewDstRC;
3632   }
3633 }
3634 
3635 // Find the one SGPR operand we are allowed to use.
3636 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
3637                                    int OpIndices[3]) const {
3638   const MCInstrDesc &Desc = MI.getDesc();
3639 
3640   // Find the one SGPR operand we are allowed to use.
3641   //
3642   // First we need to consider the instruction's operand requirements before
3643   // legalizing. Some operands are required to be SGPRs, such as implicit uses
3644   // of VCC, but we are still bound by the constant bus requirement to only use
3645   // one.
3646   //
3647   // If the operand's class is an SGPR, we can never move it.
3648 
3649   unsigned SGPRReg = findImplicitSGPRRead(MI);
3650   if (SGPRReg != AMDGPU::NoRegister)
3651     return SGPRReg;
3652 
3653   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
3654   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3655 
3656   for (unsigned i = 0; i < 3; ++i) {
3657     int Idx = OpIndices[i];
3658     if (Idx == -1)
3659       break;
3660 
3661     const MachineOperand &MO = MI.getOperand(Idx);
3662     if (!MO.isReg())
3663       continue;
3664 
3665     // Is this operand statically required to be an SGPR based on the operand
3666     // constraints?
3667     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
3668     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
3669     if (IsRequiredSGPR)
3670       return MO.getReg();
3671 
3672     // If this could be a VGPR or an SGPR, Check the dynamic register class.
3673     unsigned Reg = MO.getReg();
3674     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
3675     if (RI.isSGPRClass(RegRC))
3676       UsedSGPRs[i] = Reg;
3677   }
3678 
3679   // We don't have a required SGPR operand, so we have a bit more freedom in
3680   // selecting operands to move.
3681 
3682   // Try to select the most used SGPR. If an SGPR is equal to one of the
3683   // others, we choose that.
3684   //
3685   // e.g.
3686   // V_FMA_F32 v0, s0, s0, s0 -> No moves
3687   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
3688 
3689   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
3690   // prefer those.
3691 
3692   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
3693     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
3694       SGPRReg = UsedSGPRs[0];
3695   }
3696 
3697   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
3698     if (UsedSGPRs[1] == UsedSGPRs[2])
3699       SGPRReg = UsedSGPRs[1];
3700   }
3701 
3702   return SGPRReg;
3703 }
3704 
3705 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
3706                                              unsigned OperandName) const {
3707   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
3708   if (Idx == -1)
3709     return nullptr;
3710 
3711   return &MI.getOperand(Idx);
3712 }
3713 
3714 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
3715   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
3716   if (ST.isAmdHsaOS()) {
3717     // Set ATC = 1. GFX9 doesn't have this bit.
3718     if (ST.getGeneration() <= SISubtarget::VOLCANIC_ISLANDS)
3719       RsrcDataFormat |= (1ULL << 56);
3720 
3721     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
3722     // BTW, it disables TC L2 and therefore decreases performance.
3723     if (ST.getGeneration() == SISubtarget::VOLCANIC_ISLANDS)
3724       RsrcDataFormat |= (2ULL << 59);
3725   }
3726 
3727   return RsrcDataFormat;
3728 }
3729 
3730 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
3731   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
3732                     AMDGPU::RSRC_TID_ENABLE |
3733                     0xffffffff; // Size;
3734 
3735   // GFX9 doesn't have ELEMENT_SIZE.
3736   if (ST.getGeneration() <= SISubtarget::VOLCANIC_ISLANDS) {
3737     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
3738     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
3739   }
3740 
3741   // IndexStride = 64.
3742   Rsrc23 |= UINT64_C(3) << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
3743 
3744   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
3745   // Clear them unless we want a huge stride.
3746   if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3747     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
3748 
3749   return Rsrc23;
3750 }
3751 
3752 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
3753   unsigned Opc = MI.getOpcode();
3754 
3755   return isSMRD(Opc);
3756 }
3757 
3758 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
3759   unsigned Opc = MI.getOpcode();
3760 
3761   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
3762 }
3763 
3764 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
3765                                     int &FrameIndex) const {
3766   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
3767   if (!Addr || !Addr->isFI())
3768     return AMDGPU::NoRegister;
3769 
3770   assert(!MI.memoperands_empty() &&
3771          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUASI.PRIVATE_ADDRESS);
3772 
3773   FrameIndex = Addr->getIndex();
3774   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
3775 }
3776 
3777 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
3778                                         int &FrameIndex) const {
3779   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
3780   assert(Addr && Addr->isFI());
3781   FrameIndex = Addr->getIndex();
3782   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
3783 }
3784 
3785 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
3786                                           int &FrameIndex) const {
3787 
3788   if (!MI.mayLoad())
3789     return AMDGPU::NoRegister;
3790 
3791   if (isMUBUF(MI) || isVGPRSpill(MI))
3792     return isStackAccess(MI, FrameIndex);
3793 
3794   if (isSGPRSpill(MI))
3795     return isSGPRStackAccess(MI, FrameIndex);
3796 
3797   return AMDGPU::NoRegister;
3798 }
3799 
3800 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
3801                                          int &FrameIndex) const {
3802   if (!MI.mayStore())
3803     return AMDGPU::NoRegister;
3804 
3805   if (isMUBUF(MI) || isVGPRSpill(MI))
3806     return isStackAccess(MI, FrameIndex);
3807 
3808   if (isSGPRSpill(MI))
3809     return isSGPRStackAccess(MI, FrameIndex);
3810 
3811   return AMDGPU::NoRegister;
3812 }
3813 
3814 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
3815   unsigned Opc = MI.getOpcode();
3816   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
3817   unsigned DescSize = Desc.getSize();
3818 
3819   // If we have a definitive size, we can use it. Otherwise we need to inspect
3820   // the operands to know the size.
3821   //
3822   // FIXME: Instructions that have a base 32-bit encoding report their size as
3823   // 4, even though they are really 8 bytes if they have a literal operand.
3824   if (DescSize != 0 && DescSize != 4)
3825     return DescSize;
3826 
3827   // 4-byte instructions may have a 32-bit literal encoded after them. Check
3828   // operands that coud ever be literals.
3829   if (isVALU(MI) || isSALU(MI)) {
3830     if (isFixedSize(MI))
3831       return DescSize;
3832 
3833     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3834     if (Src0Idx == -1)
3835       return 4; // No operands.
3836 
3837     if (isLiteralConstantLike(MI.getOperand(Src0Idx), Desc.OpInfo[Src0Idx]))
3838       return 8;
3839 
3840     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3841     if (Src1Idx == -1)
3842       return 4;
3843 
3844     if (isLiteralConstantLike(MI.getOperand(Src1Idx), Desc.OpInfo[Src1Idx]))
3845       return 8;
3846 
3847     return 4;
3848   }
3849 
3850   if (DescSize == 4)
3851     return 4;
3852 
3853   switch (Opc) {
3854   case TargetOpcode::IMPLICIT_DEF:
3855   case TargetOpcode::KILL:
3856   case TargetOpcode::DBG_VALUE:
3857   case TargetOpcode::BUNDLE:
3858   case TargetOpcode::EH_LABEL:
3859     return 0;
3860   case TargetOpcode::INLINEASM: {
3861     const MachineFunction *MF = MI.getParent()->getParent();
3862     const char *AsmStr = MI.getOperand(0).getSymbolName();
3863     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
3864   }
3865   default:
3866     llvm_unreachable("unable to find instruction size");
3867   }
3868 }
3869 
3870 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
3871   if (!isFLAT(MI))
3872     return false;
3873 
3874   if (MI.memoperands_empty())
3875     return true;
3876 
3877   for (const MachineMemOperand *MMO : MI.memoperands()) {
3878     if (MMO->getAddrSpace() == AMDGPUASI.FLAT_ADDRESS)
3879       return true;
3880   }
3881   return false;
3882 }
3883 
3884 ArrayRef<std::pair<int, const char *>>
3885 SIInstrInfo::getSerializableTargetIndices() const {
3886   static const std::pair<int, const char *> TargetIndices[] = {
3887       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
3888       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
3889       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
3890       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
3891       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
3892   return makeArrayRef(TargetIndices);
3893 }
3894 
3895 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
3896 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
3897 ScheduleHazardRecognizer *
3898 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
3899                                             const ScheduleDAG *DAG) const {
3900   return new GCNHazardRecognizer(DAG->MF);
3901 }
3902 
3903 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
3904 /// pass.
3905 ScheduleHazardRecognizer *
3906 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
3907   return new GCNHazardRecognizer(MF);
3908 }
3909 
3910 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
3911   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
3912          MI.modifiesRegister(AMDGPU::EXEC, &RI);
3913 }
3914