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