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