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