25acaa57187d2c369e134fd1e00502224dd32449
[oota-llvm.git] / lib / Target / R600 / SIISelLowering.cpp
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
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 Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifdef _MSC_VER
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #include <cmath>
19 #endif
20
21 #include "SIISelLowering.h"
22 #include "AMDGPU.h"
23 #include "AMDGPUIntrinsicInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/ADT/SmallString.h"
35
36 using namespace llvm;
37
38 SITargetLowering::SITargetLowering(TargetMachine &TM) :
39     AMDGPUTargetLowering(TM) {
40   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
41   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
42
43   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
44   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
45
46   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
47   addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
48
49   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
50   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
51   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
52
53   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
54   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
55
56   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
57   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
58
59   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
60   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
61
62   computeRegisterProperties();
63
64   // Condition Codes
65   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
66   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
67   setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
68   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
69   setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
70   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
71
72   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
73   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
74   setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
75   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
76   setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
77   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
78
79   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
80   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
81   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
82   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
83
84   setOperationAction(ISD::ADD, MVT::i32, Legal);
85   setOperationAction(ISD::ADDC, MVT::i32, Legal);
86   setOperationAction(ISD::ADDE, MVT::i32, Legal);
87   setOperationAction(ISD::SUBC, MVT::i32, Legal);
88   setOperationAction(ISD::SUBE, MVT::i32, Legal);
89
90   setOperationAction(ISD::FSIN, MVT::f32, Custom);
91   setOperationAction(ISD::FCOS, MVT::f32, Custom);
92
93   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
94   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
95   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
96   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
97
98   // We need to custom lower vector stores from local memory
99   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
100   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
101   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
102
103   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
104   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
105
106   setOperationAction(ISD::STORE, MVT::i1, Custom);
107   setOperationAction(ISD::STORE, MVT::i32, Custom);
108   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
109   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
110
111   setOperationAction(ISD::SELECT, MVT::f32, Promote);
112   AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
113   setOperationAction(ISD::SELECT, MVT::i64, Custom);
114   setOperationAction(ISD::SELECT, MVT::f64, Promote);
115   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
116
117   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
118   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
119   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
120   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
121
122   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
123   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
124
125   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
126
127   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
129   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
130
131   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
132   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
133   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
134
135   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
136   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
137   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
138
139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
140
141   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
142
143   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
144   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
145   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
146   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
147
148   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
149   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
150
151   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
152   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
153   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
154   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
155   setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
156   setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
157
158   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
159   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
160   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
161   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
162
163   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
164   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
165   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
166   setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
167   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
168
169   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
170   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
171   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
172   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
173   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
174   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
175
176   setOperationAction(ISD::LOAD, MVT::i1, Custom);
177
178   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
179   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
180   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
181
182   // These should use UDIVREM, so set them to expand
183   setOperationAction(ISD::UDIV, MVT::i64, Expand);
184   setOperationAction(ISD::UREM, MVT::i64, Expand);
185
186   // We only support LOAD/STORE and vector manipulation ops for vectors
187   // with > 4 elements.
188   MVT VecTypes[] = {
189     MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
190   };
191
192   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
193   setOperationAction(ISD::SELECT, MVT::i1, Promote);
194
195   for (MVT VT : VecTypes) {
196     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
197       switch(Op) {
198       case ISD::LOAD:
199       case ISD::STORE:
200       case ISD::BUILD_VECTOR:
201       case ISD::BITCAST:
202       case ISD::EXTRACT_VECTOR_ELT:
203       case ISD::INSERT_VECTOR_ELT:
204       case ISD::INSERT_SUBVECTOR:
205       case ISD::EXTRACT_SUBVECTOR:
206         break;
207       case ISD::CONCAT_VECTORS:
208         setOperationAction(Op, VT, Custom);
209         break;
210       default:
211         setOperationAction(Op, VT, Expand);
212         break;
213       }
214     }
215   }
216
217   for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
218     MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
219     setOperationAction(ISD::FTRUNC, VT, Expand);
220     setOperationAction(ISD::FCEIL, VT, Expand);
221     setOperationAction(ISD::FFLOOR, VT, Expand);
222   }
223
224   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
225     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
226     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
227     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
228     setOperationAction(ISD::FRINT, MVT::f64, Legal);
229   }
230
231   setOperationAction(ISD::FDIV, MVT::f32, Custom);
232
233   setTargetDAGCombine(ISD::FADD);
234   setTargetDAGCombine(ISD::FSUB);
235   setTargetDAGCombine(ISD::SELECT_CC);
236   setTargetDAGCombine(ISD::SETCC);
237
238   setTargetDAGCombine(ISD::UINT_TO_FP);
239
240   // All memory operations. Some folding on the pointer operand is done to help
241   // matching the constant offsets in the addressing modes.
242   setTargetDAGCombine(ISD::LOAD);
243   setTargetDAGCombine(ISD::STORE);
244   setTargetDAGCombine(ISD::ATOMIC_LOAD);
245   setTargetDAGCombine(ISD::ATOMIC_STORE);
246   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
247   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
248   setTargetDAGCombine(ISD::ATOMIC_SWAP);
249   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
250   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
251   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
252   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
253   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
254   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
255   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
256   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
257   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
258   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
259
260   setSchedulingPreference(Sched::RegPressure);
261 }
262
263 //===----------------------------------------------------------------------===//
264 // TargetLowering queries
265 //===----------------------------------------------------------------------===//
266
267 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
268                                           EVT) const {
269   // SI has some legal vector types, but no legal vector operations. Say no
270   // shuffles are legal in order to prefer scalarizing some vector operations.
271   return false;
272 }
273
274 // FIXME: This really needs an address space argument. The immediate offset
275 // size is different for different sets of memory instruction sets.
276
277 // The single offset DS instructions have a 16-bit unsigned byte offset.
278 //
279 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
280 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
281 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
282 //
283 // SMRD instructions have an 8-bit, dword offset.
284 //
285 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
286                                              Type *Ty) const {
287   // No global is ever allowed as a base.
288   if (AM.BaseGV)
289     return false;
290
291   // Allow a 16-bit unsigned immediate field, since this is what DS instructions
292   // use.
293   if (!isUInt<16>(AM.BaseOffs))
294     return false;
295
296   // Only support r+r,
297   switch (AM.Scale) {
298   case 0:  // "r+i" or just "i", depending on HasBaseReg.
299     break;
300   case 1:
301     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
302       return false;
303     // Otherwise we have r+r or r+i.
304     break;
305   case 2:
306     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
307       return false;
308     // Allow 2*r as r+r.
309     break;
310   default: // Don't allow n * r
311     return false;
312   }
313
314   return true;
315 }
316
317 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT  VT,
318                                                       unsigned AddrSpace,
319                                                       unsigned Align,
320                                                       bool *IsFast) const {
321   if (IsFast)
322     *IsFast = false;
323
324   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
325   // which isn't a simple VT.
326   if (!VT.isSimple() || VT == MVT::Other)
327     return false;
328
329   // XXX - CI changes say "Support for unaligned memory accesses" but I don't
330   // see what for specifically. The wording everywhere else seems to be the
331   // same.
332
333   // XXX - The only mention I see of this in the ISA manual is for LDS direct
334   // reads the "byte address and must be dword aligned". Is it also true for the
335   // normal loads and stores?
336   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
337     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
338     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
339     // with adjacent offsets.
340     return Align % 4 == 0;
341   }
342
343   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
344   // byte-address are ignored, thus forcing Dword alignment.
345   // This applies to private, global, and constant memory.
346   if (IsFast)
347     *IsFast = true;
348   return VT.bitsGT(MVT::i32);
349 }
350
351 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
352                                           unsigned SrcAlign, bool IsMemset,
353                                           bool ZeroMemset,
354                                           bool MemcpyStrSrc,
355                                           MachineFunction &MF) const {
356   // FIXME: Should account for address space here.
357
358   // The default fallback uses the private pointer size as a guess for a type to
359   // use. Make sure we switch these to 64-bit accesses.
360
361   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
362     return MVT::v4i32;
363
364   if (Size >= 8 && DstAlign >= 4)
365     return MVT::v2i32;
366
367   // Use the default.
368   return MVT::Other;
369 }
370
371 TargetLoweringBase::LegalizeTypeAction
372 SITargetLowering::getPreferredVectorAction(EVT VT) const {
373   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
374     return TypeSplitVector;
375
376   return TargetLoweringBase::getPreferredVectorAction(VT);
377 }
378
379 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
380                                                          Type *Ty) const {
381   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
382       getTargetMachine().getSubtargetImpl()->getInstrInfo());
383   return TII->isInlineConstant(Imm);
384 }
385
386 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
387                                          SDLoc SL, SDValue Chain,
388                                          unsigned Offset, bool Signed) const {
389   const DataLayout *DL = getDataLayout();
390   MachineFunction &MF = DAG.getMachineFunction();
391   const SIRegisterInfo *TRI =
392       static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
393   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
394
395   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
396
397   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
398   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
399   SDValue BasePtr =  DAG.getCopyFromReg(Chain, SL,
400                            MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
401   SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
402                                              DAG.getConstant(Offset, MVT::i64));
403   SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
404   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
405
406   return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
407                      VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
408                      false, // isVolatile
409                      true, // isNonTemporal
410                      true, // isInvariant
411                      DL->getABITypeAlignment(Ty)); // Alignment
412 }
413
414 SDValue SITargetLowering::LowerFormalArguments(
415                                       SDValue Chain,
416                                       CallingConv::ID CallConv,
417                                       bool isVarArg,
418                                       const SmallVectorImpl<ISD::InputArg> &Ins,
419                                       SDLoc DL, SelectionDAG &DAG,
420                                       SmallVectorImpl<SDValue> &InVals) const {
421
422   const TargetMachine &TM = getTargetMachine();
423   const SIRegisterInfo *TRI =
424       static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
425
426   MachineFunction &MF = DAG.getMachineFunction();
427   FunctionType *FType = MF.getFunction()->getFunctionType();
428   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
429
430   assert(CallConv == CallingConv::C);
431
432   SmallVector<ISD::InputArg, 16> Splits;
433   BitVector Skipped(Ins.size());
434
435   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
436     const ISD::InputArg &Arg = Ins[i];
437
438     // First check if it's a PS input addr
439     if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
440         !Arg.Flags.isByVal()) {
441
442       assert((PSInputNum <= 15) && "Too many PS inputs!");
443
444       if (!Arg.Used) {
445         // We can savely skip PS inputs
446         Skipped.set(i);
447         ++PSInputNum;
448         continue;
449       }
450
451       Info->PSInputAddr |= 1 << PSInputNum++;
452     }
453
454     // Second split vertices into their elements
455     if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
456       ISD::InputArg NewArg = Arg;
457       NewArg.Flags.setSplit();
458       NewArg.VT = Arg.VT.getVectorElementType();
459
460       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
461       // three or five element vertex only needs three or five registers,
462       // NOT four or eigth.
463       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
464       unsigned NumElements = ParamType->getVectorNumElements();
465
466       for (unsigned j = 0; j != NumElements; ++j) {
467         Splits.push_back(NewArg);
468         NewArg.PartOffset += NewArg.VT.getStoreSize();
469       }
470
471     } else if (Info->getShaderType() != ShaderType::COMPUTE) {
472       Splits.push_back(Arg);
473     }
474   }
475
476   SmallVector<CCValAssign, 16> ArgLocs;
477   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
478                  *DAG.getContext());
479
480   // At least one interpolation mode must be enabled or else the GPU will hang.
481   if (Info->getShaderType() == ShaderType::PIXEL &&
482       (Info->PSInputAddr & 0x7F) == 0) {
483     Info->PSInputAddr |= 1;
484     CCInfo.AllocateReg(AMDGPU::VGPR0);
485     CCInfo.AllocateReg(AMDGPU::VGPR1);
486   }
487
488   // The pointer to the list of arguments is stored in SGPR0, SGPR1
489         // The pointer to the scratch buffer is stored in SGPR2, SGPR3
490   if (Info->getShaderType() == ShaderType::COMPUTE) {
491     Info->NumUserSGPRs = 4;
492
493     unsigned InputPtrReg =
494         TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
495     unsigned InputPtrRegLo =
496         TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
497     unsigned InputPtrRegHi =
498         TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
499
500     unsigned ScratchPtrReg =
501         TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
502     unsigned ScratchPtrRegLo =
503         TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
504     unsigned ScratchPtrRegHi =
505         TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
506
507     CCInfo.AllocateReg(InputPtrRegLo);
508     CCInfo.AllocateReg(InputPtrRegHi);
509     CCInfo.AllocateReg(ScratchPtrRegLo);
510     CCInfo.AllocateReg(ScratchPtrRegHi);
511     MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
512     MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
513   }
514
515   if (Info->getShaderType() == ShaderType::COMPUTE) {
516     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
517                             Splits);
518   }
519
520   AnalyzeFormalArguments(CCInfo, Splits);
521
522   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
523
524     const ISD::InputArg &Arg = Ins[i];
525     if (Skipped[i]) {
526       InVals.push_back(DAG.getUNDEF(Arg.VT));
527       continue;
528     }
529
530     CCValAssign &VA = ArgLocs[ArgIdx++];
531     EVT VT = VA.getLocVT();
532
533     if (VA.isMemLoc()) {
534       VT = Ins[i].VT;
535       EVT MemVT = Splits[i].VT;
536       const unsigned Offset = 36 + VA.getLocMemOffset();
537       // The first 36 bytes of the input buffer contains information about
538       // thread group and global sizes.
539       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, DAG.getRoot(),
540                                    Offset, Ins[i].Flags.isSExt());
541
542       const PointerType *ParamTy =
543           dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
544       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
545           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
546         // On SI local pointers are just offsets into LDS, so they are always
547         // less than 16-bits.  On CI and newer they could potentially be
548         // real pointers, so we can't guarantee their size.
549         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
550                           DAG.getValueType(MVT::i16));
551       }
552
553       InVals.push_back(Arg);
554       Info->ABIArgOffset = Offset + MemVT.getStoreSize();
555       continue;
556     }
557     assert(VA.isRegLoc() && "Parameter must be in a register!");
558
559     unsigned Reg = VA.getLocReg();
560
561     if (VT == MVT::i64) {
562       // For now assume it is a pointer
563       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
564                                      &AMDGPU::SReg_64RegClass);
565       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
566       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
567       continue;
568     }
569
570     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
571
572     Reg = MF.addLiveIn(Reg, RC);
573     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
574
575     if (Arg.VT.isVector()) {
576
577       // Build a vector from the registers
578       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
579       unsigned NumElements = ParamType->getVectorNumElements();
580
581       SmallVector<SDValue, 4> Regs;
582       Regs.push_back(Val);
583       for (unsigned j = 1; j != NumElements; ++j) {
584         Reg = ArgLocs[ArgIdx++].getLocReg();
585         Reg = MF.addLiveIn(Reg, RC);
586         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
587       }
588
589       // Fill up the missing vector elements
590       NumElements = Arg.VT.getVectorNumElements() - NumElements;
591       for (unsigned j = 0; j != NumElements; ++j)
592         Regs.push_back(DAG.getUNDEF(VT));
593
594       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
595       continue;
596     }
597
598     InVals.push_back(Val);
599   }
600   return Chain;
601 }
602
603 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
604     MachineInstr * MI, MachineBasicBlock * BB) const {
605
606   MachineBasicBlock::iterator I = *MI;
607   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
608       getTargetMachine().getSubtargetImpl()->getInstrInfo());
609
610   switch (MI->getOpcode()) {
611   default:
612     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
613   case AMDGPU::BRANCH: return BB;
614   case AMDGPU::V_SUB_F64: {
615     unsigned DestReg = MI->getOperand(0).getReg();
616     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
617       .addImm(0)  // SRC0 modifiers
618       .addReg(MI->getOperand(1).getReg())
619       .addImm(1)  // SRC1 modifiers
620       .addReg(MI->getOperand(2).getReg())
621       .addImm(0)  // CLAMP
622       .addImm(0); // OMOD
623     MI->eraseFromParent();
624     break;
625   }
626   case AMDGPU::SI_RegisterStorePseudo: {
627     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
628     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
629     MachineInstrBuilder MIB =
630         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
631                 Reg);
632     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
633       MIB.addOperand(MI->getOperand(i));
634
635     MI->eraseFromParent();
636     break;
637   }
638   }
639   return BB;
640 }
641
642 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
643   if (!VT.isVector()) {
644     return MVT::i1;
645   }
646   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
647 }
648
649 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
650   return MVT::i32;
651 }
652
653 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
654   VT = VT.getScalarType();
655
656   if (!VT.isSimple())
657     return false;
658
659   switch (VT.getSimpleVT().SimpleTy) {
660   case MVT::f32:
661     return false; /* There is V_MAD_F32 for f32 */
662   case MVT::f64:
663     return true;
664   default:
665     break;
666   }
667
668   return false;
669 }
670
671 //===----------------------------------------------------------------------===//
672 // Custom DAG Lowering Operations
673 //===----------------------------------------------------------------------===//
674
675 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
676   switch (Op.getOpcode()) {
677   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
678   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
679   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
680   case ISD::LOAD: {
681     SDValue Result = LowerLOAD(Op, DAG);
682     assert((!Result.getNode() ||
683             Result.getNode()->getNumValues() == 2) &&
684            "Load should return a value and a chain");
685     return Result;
686   }
687
688   case ISD::FSIN:
689   case ISD::FCOS:
690     return LowerTrig(Op, DAG);
691   case ISD::SELECT: return LowerSELECT(Op, DAG);
692   case ISD::FDIV: return LowerFDIV(Op, DAG);
693   case ISD::STORE: return LowerSTORE(Op, DAG);
694   case ISD::GlobalAddress: {
695     MachineFunction &MF = DAG.getMachineFunction();
696     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
697     return LowerGlobalAddress(MFI, Op, DAG);
698   }
699   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
700   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
701   }
702   return SDValue();
703 }
704
705 /// \brief Helper function for LowerBRCOND
706 static SDNode *findUser(SDValue Value, unsigned Opcode) {
707
708   SDNode *Parent = Value.getNode();
709   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
710        I != E; ++I) {
711
712     if (I.getUse().get() != Value)
713       continue;
714
715     if (I->getOpcode() == Opcode)
716       return *I;
717   }
718   return nullptr;
719 }
720
721 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
722
723   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
724   unsigned FrameIndex = FINode->getIndex();
725
726   return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
727 }
728
729 /// This transforms the control flow intrinsics to get the branch destination as
730 /// last parameter, also switches branch target with BR if the need arise
731 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
732                                       SelectionDAG &DAG) const {
733
734   SDLoc DL(BRCOND);
735
736   SDNode *Intr = BRCOND.getOperand(1).getNode();
737   SDValue Target = BRCOND.getOperand(2);
738   SDNode *BR = nullptr;
739
740   if (Intr->getOpcode() == ISD::SETCC) {
741     // As long as we negate the condition everything is fine
742     SDNode *SetCC = Intr;
743     assert(SetCC->getConstantOperandVal(1) == 1);
744     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
745            ISD::SETNE);
746     Intr = SetCC->getOperand(0).getNode();
747
748   } else {
749     // Get the target from BR if we don't negate the condition
750     BR = findUser(BRCOND, ISD::BR);
751     Target = BR->getOperand(1);
752   }
753
754   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
755
756   // Build the result and
757   SmallVector<EVT, 4> Res;
758   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
759     Res.push_back(Intr->getValueType(i));
760
761   // operands of the new intrinsic call
762   SmallVector<SDValue, 4> Ops;
763   Ops.push_back(BRCOND.getOperand(0));
764   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
765     Ops.push_back(Intr->getOperand(i));
766   Ops.push_back(Target);
767
768   // build the new intrinsic call
769   SDNode *Result = DAG.getNode(
770     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
771     DAG.getVTList(Res), Ops).getNode();
772
773   if (BR) {
774     // Give the branch instruction our target
775     SDValue Ops[] = {
776       BR->getOperand(0),
777       BRCOND.getOperand(2)
778     };
779     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
780     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
781     BR = NewBR.getNode();
782   }
783
784   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
785
786   // Copy the intrinsic results to registers
787   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
788     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
789     if (!CopyToReg)
790       continue;
791
792     Chain = DAG.getCopyToReg(
793       Chain, DL,
794       CopyToReg->getOperand(1),
795       SDValue(Result, i - 1),
796       SDValue());
797
798     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
799   }
800
801   // Remove the old intrinsic from the chain
802   DAG.ReplaceAllUsesOfValueWith(
803     SDValue(Intr, Intr->getNumValues() - 1),
804     Intr->getOperand(0));
805
806   return Chain;
807 }
808
809 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
810                                              SDValue Op,
811                                              SelectionDAG &DAG) const {
812   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
813
814   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
815     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
816
817   SDLoc DL(GSD);
818   const GlobalValue *GV = GSD->getGlobal();
819   MVT PtrVT = getPointerTy(GSD->getAddressSpace());
820
821   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
822   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
823
824   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
825                               DAG.getConstant(0, MVT::i32));
826   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
827                               DAG.getConstant(1, MVT::i32));
828
829   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
830                            PtrLo, GA);
831   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
832                            PtrHi, DAG.getConstant(0, MVT::i32),
833                            SDValue(Lo.getNode(), 1));
834   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
835 }
836
837 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
838                                                   SelectionDAG &DAG) const {
839   MachineFunction &MF = DAG.getMachineFunction();
840   const SIRegisterInfo *TRI =
841       static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
842
843   EVT VT = Op.getValueType();
844   SDLoc DL(Op);
845   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
846
847   switch (IntrinsicID) {
848   case Intrinsic::r600_read_ngroups_x:
849     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
850                           SI::KernelInputOffsets::NGROUPS_X, false);
851   case Intrinsic::r600_read_ngroups_y:
852     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
853                           SI::KernelInputOffsets::NGROUPS_Y, false);
854   case Intrinsic::r600_read_ngroups_z:
855     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
856                           SI::KernelInputOffsets::NGROUPS_Z, false);
857   case Intrinsic::r600_read_global_size_x:
858     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
859                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
860   case Intrinsic::r600_read_global_size_y:
861     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
862                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
863   case Intrinsic::r600_read_global_size_z:
864     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
865                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
866   case Intrinsic::r600_read_local_size_x:
867     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
868                           SI::KernelInputOffsets::LOCAL_SIZE_X, false);
869   case Intrinsic::r600_read_local_size_y:
870     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
871                           SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
872   case Intrinsic::r600_read_local_size_z:
873     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
874                           SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
875
876   case Intrinsic::AMDGPU_read_workdim:
877     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
878                           MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
879                           false);
880
881   case Intrinsic::r600_read_tgid_x:
882     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
883       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
884   case Intrinsic::r600_read_tgid_y:
885     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
886       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
887   case Intrinsic::r600_read_tgid_z:
888     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
889       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
890   case Intrinsic::r600_read_tidig_x:
891     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
892       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
893   case Intrinsic::r600_read_tidig_y:
894     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
895       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
896   case Intrinsic::r600_read_tidig_z:
897     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
898       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
899   case AMDGPUIntrinsic::SI_load_const: {
900     SDValue Ops[] = {
901       Op.getOperand(1),
902       Op.getOperand(2)
903     };
904
905     MachineMemOperand *MMO = MF.getMachineMemOperand(
906       MachinePointerInfo(),
907       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
908       VT.getStoreSize(), 4);
909     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
910                                    Op->getVTList(), Ops, VT, MMO);
911   }
912   case AMDGPUIntrinsic::SI_sample:
913     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
914   case AMDGPUIntrinsic::SI_sampleb:
915     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
916   case AMDGPUIntrinsic::SI_sampled:
917     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
918   case AMDGPUIntrinsic::SI_samplel:
919     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
920   case AMDGPUIntrinsic::SI_vs_load_input:
921     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
922                        Op.getOperand(1),
923                        Op.getOperand(2),
924                        Op.getOperand(3));
925   default:
926     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
927   }
928 }
929
930 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
931                                               SelectionDAG &DAG) const {
932   MachineFunction &MF = DAG.getMachineFunction();
933   SDValue Chain = Op.getOperand(0);
934   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
935
936   switch (IntrinsicID) {
937   case AMDGPUIntrinsic::SI_tbuffer_store: {
938     SDLoc DL(Op);
939     SDValue Ops[] = {
940       Chain,
941       Op.getOperand(2),
942       Op.getOperand(3),
943       Op.getOperand(4),
944       Op.getOperand(5),
945       Op.getOperand(6),
946       Op.getOperand(7),
947       Op.getOperand(8),
948       Op.getOperand(9),
949       Op.getOperand(10),
950       Op.getOperand(11),
951       Op.getOperand(12),
952       Op.getOperand(13),
953       Op.getOperand(14)
954     };
955
956     EVT VT = Op.getOperand(3).getValueType();
957
958     MachineMemOperand *MMO = MF.getMachineMemOperand(
959       MachinePointerInfo(),
960       MachineMemOperand::MOStore,
961       VT.getStoreSize(), 4);
962     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
963                                    Op->getVTList(), Ops, VT, MMO);
964   }
965   default:
966     return SDValue();
967   }
968 }
969
970 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
971   SDLoc DL(Op);
972   LoadSDNode *Load = cast<LoadSDNode>(Op);
973
974   if (Op.getValueType().isVector()) {
975     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
976            "Custom lowering for non-i32 vectors hasn't been implemented.");
977     unsigned NumElements = Op.getValueType().getVectorNumElements();
978     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
979     switch (Load->getAddressSpace()) {
980       default: break;
981       case AMDGPUAS::GLOBAL_ADDRESS:
982       case AMDGPUAS::PRIVATE_ADDRESS:
983         // v4 loads are supported for private and global memory.
984         if (NumElements <= 4)
985           break;
986         // fall-through
987       case AMDGPUAS::LOCAL_ADDRESS:
988         return ScalarizeVectorLoad(Op, DAG);
989     }
990   }
991
992   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
993 }
994
995 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
996                                                const SDValue &Op,
997                                                SelectionDAG &DAG) const {
998   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
999                      Op.getOperand(2),
1000                      Op.getOperand(3),
1001                      Op.getOperand(4));
1002 }
1003
1004 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1005   if (Op.getValueType() != MVT::i64)
1006     return SDValue();
1007
1008   SDLoc DL(Op);
1009   SDValue Cond = Op.getOperand(0);
1010
1011   SDValue Zero = DAG.getConstant(0, MVT::i32);
1012   SDValue One = DAG.getConstant(1, MVT::i32);
1013
1014   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1015   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1016
1017   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1018   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1019
1020   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1021
1022   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1023   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1024
1025   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1026
1027   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1028   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1029 }
1030
1031 // Catch division cases where we can use shortcuts with rcp and rsq
1032 // instructions.
1033 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1034   SDLoc SL(Op);
1035   SDValue LHS = Op.getOperand(0);
1036   SDValue RHS = Op.getOperand(1);
1037   EVT VT = Op.getValueType();
1038   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1039
1040   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1041     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1042         CLHS->isExactlyValue(1.0)) {
1043       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1044       // the CI documentation has a worst case error of 1 ulp.
1045       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1046       // use it as long as we aren't trying to use denormals.
1047
1048       // 1.0 / sqrt(x) -> rsq(x)
1049       //
1050       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1051       // error seems really high at 2^29 ULP.
1052       if (RHS.getOpcode() == ISD::FSQRT)
1053         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1054
1055       // 1.0 / x -> rcp(x)
1056       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1057     }
1058   }
1059
1060   if (Unsafe) {
1061     // Turn into multiply by the reciprocal.
1062     // x / y -> x * (1.0 / y)
1063     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1064     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1065   }
1066
1067   return SDValue();
1068 }
1069
1070 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1071   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1072   if (FastLowered.getNode())
1073     return FastLowered;
1074
1075   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1076   // selection error for now rather than do something incorrect.
1077   if (Subtarget->hasFP32Denormals())
1078     return SDValue();
1079
1080   SDLoc SL(Op);
1081   SDValue LHS = Op.getOperand(0);
1082   SDValue RHS = Op.getOperand(1);
1083
1084   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1085
1086   const APFloat K0Val(BitsToFloat(0x6f800000));
1087   const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1088
1089   const APFloat K1Val(BitsToFloat(0x2f800000));
1090   const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1091
1092   const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1093
1094   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1095
1096   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1097
1098   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1099
1100   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1101
1102   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1103
1104   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1105
1106   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1107 }
1108
1109 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1110   return SDValue();
1111 }
1112
1113 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1114   EVT VT = Op.getValueType();
1115
1116   if (VT == MVT::f32)
1117     return LowerFDIV32(Op, DAG);
1118
1119   if (VT == MVT::f64)
1120     return LowerFDIV64(Op, DAG);
1121
1122   llvm_unreachable("Unexpected type for fdiv");
1123 }
1124
1125 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1126   SDLoc DL(Op);
1127   StoreSDNode *Store = cast<StoreSDNode>(Op);
1128   EVT VT = Store->getMemoryVT();
1129
1130   // These stores are legal.
1131   if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1132       VT.isVector() && VT.getVectorNumElements() == 2 &&
1133       VT.getVectorElementType() == MVT::i32)
1134     return SDValue();
1135
1136   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1137     if (VT.isVector() && VT.getVectorNumElements() > 4)
1138       return ScalarizeVectorStore(Op, DAG);
1139     return SDValue();
1140   }
1141
1142   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1143   if (Ret.getNode())
1144     return Ret;
1145
1146   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1147       return ScalarizeVectorStore(Op, DAG);
1148
1149   if (VT == MVT::i1)
1150     return DAG.getTruncStore(Store->getChain(), DL,
1151                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1152                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1153
1154   return SDValue();
1155 }
1156
1157 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1158   EVT VT = Op.getValueType();
1159   SDValue Arg = Op.getOperand(0);
1160   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1161         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1162           DAG.getConstantFP(0.5 / M_PI, VT)));
1163
1164   switch (Op.getOpcode()) {
1165   case ISD::FCOS:
1166     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1167   case ISD::FSIN:
1168     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1169   default:
1170     llvm_unreachable("Wrong trig opcode");
1171   }
1172 }
1173
1174 //===----------------------------------------------------------------------===//
1175 // Custom DAG optimizations
1176 //===----------------------------------------------------------------------===//
1177
1178 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1179                                                      DAGCombinerInfo &DCI) {
1180   EVT VT = N->getValueType(0);
1181   EVT ScalarVT = VT.getScalarType();
1182   if (ScalarVT != MVT::f32)
1183     return SDValue();
1184
1185   SelectionDAG &DAG = DCI.DAG;
1186   SDLoc DL(N);
1187
1188   SDValue Src = N->getOperand(0);
1189   EVT SrcVT = Src.getValueType();
1190
1191   // TODO: We could try to match extracting the higher bytes, which would be
1192   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1193   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1194   // about in practice.
1195   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1196     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1197       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1198       DCI.AddToWorklist(Cvt.getNode());
1199       return Cvt;
1200     }
1201   }
1202
1203   // We are primarily trying to catch operations on illegal vector types
1204   // before they are expanded.
1205   // For scalars, we can use the more flexible method of checking masked bits
1206   // after legalization.
1207   if (!DCI.isBeforeLegalize() ||
1208       !SrcVT.isVector() ||
1209       SrcVT.getVectorElementType() != MVT::i8) {
1210     return SDValue();
1211   }
1212
1213   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1214
1215   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1216   // size as 4.
1217   unsigned NElts = SrcVT.getVectorNumElements();
1218   if (!SrcVT.isSimple() && NElts != 3)
1219     return SDValue();
1220
1221   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1222   // prevent a mess from expanding to v4i32 and repacking.
1223   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1224     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1225     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1226     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1227
1228     LoadSDNode *Load = cast<LoadSDNode>(Src);
1229     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1230                                      Load->getChain(),
1231                                      Load->getBasePtr(),
1232                                      LoadVT,
1233                                      Load->getMemOperand());
1234
1235     // Make sure successors of the original load stay after it by updating
1236     // them to use the new Chain.
1237     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1238
1239     SmallVector<SDValue, 4> Elts;
1240     if (RegVT.isVector())
1241       DAG.ExtractVectorElements(NewLoad, Elts);
1242     else
1243       Elts.push_back(NewLoad);
1244
1245     SmallVector<SDValue, 4> Ops;
1246
1247     unsigned EltIdx = 0;
1248     for (SDValue Elt : Elts) {
1249       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1250       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1251         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1252         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1253         DCI.AddToWorklist(Cvt.getNode());
1254         Ops.push_back(Cvt);
1255       }
1256
1257       ++EltIdx;
1258     }
1259
1260     assert(Ops.size() == NElts);
1261
1262     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1263   }
1264
1265   return SDValue();
1266 }
1267
1268 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1269
1270 // This is a variant of
1271 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1272 //
1273 // The normal DAG combiner will do this, but only if the add has one use since
1274 // that would increase the number of instructions.
1275 //
1276 // This prevents us from seeing a constant offset that can be folded into a
1277 // memory instruction's addressing mode. If we know the resulting add offset of
1278 // a pointer can be folded into an addressing offset, we can replace the pointer
1279 // operand with the add of new constant offset. This eliminates one of the uses,
1280 // and may allow the remaining use to also be simplified.
1281 //
1282 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1283                                                unsigned AddrSpace,
1284                                                DAGCombinerInfo &DCI) const {
1285   SDValue N0 = N->getOperand(0);
1286   SDValue N1 = N->getOperand(1);
1287
1288   if (N0.getOpcode() != ISD::ADD)
1289     return SDValue();
1290
1291   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1292   if (!CN1)
1293     return SDValue();
1294
1295   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1296   if (!CAdd)
1297     return SDValue();
1298
1299   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1300       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1301
1302   // If the resulting offset is too large, we can't fold it into the addressing
1303   // mode offset.
1304   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1305   if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1306     return SDValue();
1307
1308   SelectionDAG &DAG = DCI.DAG;
1309   SDLoc SL(N);
1310   EVT VT = N->getValueType(0);
1311
1312   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1313   SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1314
1315   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1316 }
1317
1318 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1319                                             DAGCombinerInfo &DCI) const {
1320   SelectionDAG &DAG = DCI.DAG;
1321   SDLoc DL(N);
1322   EVT VT = N->getValueType(0);
1323
1324   switch (N->getOpcode()) {
1325     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1326     case ISD::SETCC: {
1327       SDValue Arg0 = N->getOperand(0);
1328       SDValue Arg1 = N->getOperand(1);
1329       SDValue CC = N->getOperand(2);
1330       ConstantSDNode * C = nullptr;
1331       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1332
1333       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1334       if (VT == MVT::i1
1335           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1336           && Arg0.getOperand(0).getValueType() == MVT::i1
1337           && (C = dyn_cast<ConstantSDNode>(Arg1))
1338           && C->isNullValue()
1339           && CCOp == ISD::SETNE) {
1340         return SimplifySetCC(VT, Arg0.getOperand(0),
1341                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1342       }
1343       break;
1344     }
1345
1346   case AMDGPUISD::CVT_F32_UBYTE0:
1347   case AMDGPUISD::CVT_F32_UBYTE1:
1348   case AMDGPUISD::CVT_F32_UBYTE2:
1349   case AMDGPUISD::CVT_F32_UBYTE3: {
1350     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1351
1352     SDValue Src = N->getOperand(0);
1353     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1354
1355     APInt KnownZero, KnownOne;
1356     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1357                                           !DCI.isBeforeLegalizeOps());
1358     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1359     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1360         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1361       DCI.CommitTargetLoweringOpt(TLO);
1362     }
1363
1364     break;
1365   }
1366
1367   case ISD::UINT_TO_FP: {
1368     return performUCharToFloatCombine(N, DCI);
1369
1370   case ISD::FADD: {
1371     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1372       break;
1373
1374     EVT VT = N->getValueType(0);
1375     if (VT != MVT::f32)
1376       break;
1377
1378     SDValue LHS = N->getOperand(0);
1379     SDValue RHS = N->getOperand(1);
1380
1381     // These should really be instruction patterns, but writing patterns with
1382     // source modiifiers is a pain.
1383
1384     // fadd (fadd (a, a), b) -> mad 2.0, a, b
1385     if (LHS.getOpcode() == ISD::FADD) {
1386       SDValue A = LHS.getOperand(0);
1387       if (A == LHS.getOperand(1)) {
1388         const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1389         return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1390       }
1391     }
1392
1393     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1394     if (RHS.getOpcode() == ISD::FADD) {
1395       SDValue A = RHS.getOperand(0);
1396       if (A == RHS.getOperand(1)) {
1397         const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1398         return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1399       }
1400     }
1401
1402     break;
1403   }
1404   case ISD::FSUB: {
1405     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1406       break;
1407
1408     EVT VT = N->getValueType(0);
1409
1410     // Try to get the fneg to fold into the source modifier. This undoes generic
1411     // DAG combines and folds them into the mad.
1412     if (VT == MVT::f32) {
1413       SDValue LHS = N->getOperand(0);
1414       SDValue RHS = N->getOperand(1);
1415
1416       if (LHS.getOpcode() == ISD::FMUL) {
1417         // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1418
1419         SDValue A = LHS.getOperand(0);
1420         SDValue B = LHS.getOperand(1);
1421         SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1422
1423         return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1424       }
1425
1426       if (RHS.getOpcode() == ISD::FMUL) {
1427         // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1428
1429         SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1430         SDValue B = RHS.getOperand(1);
1431         SDValue C = LHS;
1432
1433         return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1434       }
1435
1436       if (LHS.getOpcode() == ISD::FADD) {
1437         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1438
1439         SDValue A = LHS.getOperand(0);
1440         if (A == LHS.getOperand(1)) {
1441           const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1442           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1443
1444           return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1445         }
1446       }
1447
1448       if (RHS.getOpcode() == ISD::FADD) {
1449         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1450
1451         SDValue A = RHS.getOperand(0);
1452         if (A == RHS.getOperand(1)) {
1453           const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1454           return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1455         }
1456       }
1457     }
1458
1459     break;
1460   }
1461   }
1462   case ISD::LOAD:
1463   case ISD::STORE:
1464   case ISD::ATOMIC_LOAD:
1465   case ISD::ATOMIC_STORE:
1466   case ISD::ATOMIC_CMP_SWAP:
1467   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1468   case ISD::ATOMIC_SWAP:
1469   case ISD::ATOMIC_LOAD_ADD:
1470   case ISD::ATOMIC_LOAD_SUB:
1471   case ISD::ATOMIC_LOAD_AND:
1472   case ISD::ATOMIC_LOAD_OR:
1473   case ISD::ATOMIC_LOAD_XOR:
1474   case ISD::ATOMIC_LOAD_NAND:
1475   case ISD::ATOMIC_LOAD_MIN:
1476   case ISD::ATOMIC_LOAD_MAX:
1477   case ISD::ATOMIC_LOAD_UMIN:
1478   case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1479     if (DCI.isBeforeLegalize())
1480       break;
1481
1482     MemSDNode *MemNode = cast<MemSDNode>(N);
1483     SDValue Ptr = MemNode->getBasePtr();
1484
1485     // TODO: We could also do this for multiplies.
1486     unsigned AS = MemNode->getAddressSpace();
1487     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1488       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1489       if (NewPtr) {
1490         SmallVector<SDValue, 8> NewOps;
1491         for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1492           NewOps.push_back(MemNode->getOperand(I));
1493
1494         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1495         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1496       }
1497     }
1498     break;
1499   }
1500   }
1501   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1502 }
1503
1504 /// \brief Test if RegClass is one of the VSrc classes
1505 static bool isVSrc(unsigned RegClass) {
1506   switch(RegClass) {
1507     default: return false;
1508     case AMDGPU::VSrc_32RegClassID:
1509     case AMDGPU::VCSrc_32RegClassID:
1510     case AMDGPU::VSrc_64RegClassID:
1511     case AMDGPU::VCSrc_64RegClassID:
1512       return true;
1513   }
1514 }
1515
1516 /// \brief Test if RegClass is one of the SSrc classes
1517 static bool isSSrc(unsigned RegClass) {
1518   return AMDGPU::SSrc_32RegClassID == RegClass ||
1519          AMDGPU::SSrc_64RegClassID == RegClass;
1520 }
1521
1522 /// \brief Analyze the possible immediate value Op
1523 ///
1524 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1525 /// and the immediate value if it's a literal immediate
1526 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1527
1528   union {
1529     int32_t I;
1530     float F;
1531   } Imm;
1532
1533   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1534     if (Node->getZExtValue() >> 32) {
1535         return -1;
1536     }
1537     Imm.I = Node->getSExtValue();
1538   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1539     if (N->getValueType(0) != MVT::f32)
1540       return -1;
1541     Imm.F = Node->getValueAPF().convertToFloat();
1542   } else
1543     return -1; // It isn't an immediate
1544
1545   if ((Imm.I >= -16 && Imm.I <= 64) ||
1546       Imm.F == 0.5f || Imm.F == -0.5f ||
1547       Imm.F == 1.0f || Imm.F == -1.0f ||
1548       Imm.F == 2.0f || Imm.F == -2.0f ||
1549       Imm.F == 4.0f || Imm.F == -4.0f)
1550     return 0; // It's an inline immediate
1551
1552   return Imm.I; // It's a literal immediate
1553 }
1554
1555 /// \brief Try to fold an immediate directly into an instruction
1556 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1557                                bool &ScalarSlotUsed) const {
1558
1559   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1560   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1561       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1562   if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1563     return false;
1564
1565   const SDValue &Op = Mov->getOperand(0);
1566   int32_t Value = analyzeImmediate(Op.getNode());
1567   if (Value == -1) {
1568     // Not an immediate at all
1569     return false;
1570
1571   } else if (Value == 0) {
1572     // Inline immediates can always be fold
1573     Operand = Op;
1574     return true;
1575
1576   } else if (Value == Immediate) {
1577     // Already fold literal immediate
1578     Operand = Op;
1579     return true;
1580
1581   } else if (!ScalarSlotUsed && !Immediate) {
1582     // Fold this literal immediate
1583     ScalarSlotUsed = true;
1584     Immediate = Value;
1585     Operand = Op;
1586     return true;
1587
1588   }
1589
1590   return false;
1591 }
1592
1593 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1594                                    SelectionDAG &DAG, const SDValue &Op) const {
1595   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1596       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1597   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1598
1599   if (!Op->isMachineOpcode()) {
1600     switch(Op->getOpcode()) {
1601     case ISD::CopyFromReg: {
1602       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1603       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1604       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1605         return MRI.getRegClass(Reg);
1606       }
1607       return TRI.getPhysRegClass(Reg);
1608     }
1609     default:  return nullptr;
1610     }
1611   }
1612   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1613   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1614   if (OpClassID != -1) {
1615     return TRI.getRegClass(OpClassID);
1616   }
1617   switch(Op.getMachineOpcode()) {
1618   case AMDGPU::COPY_TO_REGCLASS:
1619     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1620     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1621
1622     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1623     // class, then the register class for the value could be either a
1624     // VReg or and SReg.  In order to get a more accurate
1625     if (isVSrc(OpClassID))
1626       return getRegClassForNode(DAG, Op.getOperand(0));
1627
1628     return TRI.getRegClass(OpClassID);
1629   case AMDGPU::EXTRACT_SUBREG: {
1630     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1631     const TargetRegisterClass *SuperClass =
1632       getRegClassForNode(DAG, Op.getOperand(0));
1633     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1634   }
1635   case AMDGPU::REG_SEQUENCE:
1636     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1637     return TRI.getRegClass(
1638       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1639   default:
1640     return getRegClassFor(Op.getSimpleValueType());
1641   }
1642 }
1643
1644 /// \brief Does "Op" fit into register class "RegClass" ?
1645 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1646                                     unsigned RegClass) const {
1647   const TargetRegisterInfo *TRI =
1648       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1649   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1650   if (!RC) {
1651     return false;
1652   }
1653   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1654 }
1655
1656 /// \returns true if \p Node's operands are different from the SDValue list
1657 /// \p Ops
1658 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1659   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1660     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1661       return true;
1662     }
1663   }
1664   return false;
1665 }
1666
1667 /// TODO: This needs to be removed. It's current primary purpose is to fold
1668 /// immediates into operands when legal. The legalization parts are redundant
1669 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1670 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1671                                            SelectionDAG &DAG) const {
1672   // Original encoding (either e32 or e64)
1673   int Opcode = Node->getMachineOpcode();
1674   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1675       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1676   const MCInstrDesc *Desc = &TII->get(Opcode);
1677
1678   unsigned NumDefs = Desc->getNumDefs();
1679   unsigned NumOps = Desc->getNumOperands();
1680
1681   // Commuted opcode if available
1682   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1683   const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1684
1685   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1686   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1687
1688   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1689   bool HaveVSrc = false, HaveSSrc = false;
1690
1691   // First figure out what we already have in this instruction.
1692   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1693        i != e && Op < NumOps; ++i, ++Op) {
1694
1695     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1696     if (isVSrc(RegClass))
1697       HaveVSrc = true;
1698     else if (isSSrc(RegClass))
1699       HaveSSrc = true;
1700     else
1701       continue;
1702
1703     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1704     if (Imm != -1 && Imm != 0) {
1705       // Literal immediate
1706       Immediate = Imm;
1707     }
1708   }
1709
1710   // If we neither have VSrc nor SSrc, it makes no sense to continue.
1711   if (!HaveVSrc && !HaveSSrc)
1712     return Node;
1713
1714   // No scalar allowed when we have both VSrc and SSrc
1715   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1716
1717   // If this instruction has an implicit use of VCC, then it can't use the
1718   // constant bus.
1719   for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1720     if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1721       ScalarSlotUsed = true;
1722       break;
1723     }
1724   }
1725
1726   // Second go over the operands and try to fold them
1727   std::vector<SDValue> Ops;
1728   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1729        i != e && Op < NumOps; ++i, ++Op) {
1730
1731     const SDValue &Operand = Node->getOperand(i);
1732     Ops.push_back(Operand);
1733
1734     // Already folded immediate?
1735     if (isa<ConstantSDNode>(Operand.getNode()) ||
1736         isa<ConstantFPSDNode>(Operand.getNode()))
1737       continue;
1738
1739     // Is this a VSrc or SSrc operand?
1740     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1741     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1742       // Try to fold the immediates. If this ends up with multiple constant bus
1743       // uses, it will be legalized later.
1744       foldImm(Ops[i], Immediate, ScalarSlotUsed);
1745       continue;
1746     }
1747
1748     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1749
1750       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1751       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1752
1753       // Test if it makes sense to swap operands
1754       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1755           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1756            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1757
1758         // Swap commutable operands
1759         std::swap(Ops[0], Ops[1]);
1760
1761         Desc = DescRev;
1762         DescRev = nullptr;
1763         continue;
1764       }
1765     }
1766   }
1767
1768   // Add optional chain and glue
1769   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1770     Ops.push_back(Node->getOperand(i));
1771
1772   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1773   // this case a brand new node is always be created, even if the operands
1774   // are the same as before.  So, manually check if anything has been changed.
1775   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1776     return Node;
1777   }
1778
1779   // Create a complete new instruction
1780   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1781 }
1782
1783 /// \brief Helper function for adjustWritemask
1784 static unsigned SubIdx2Lane(unsigned Idx) {
1785   switch (Idx) {
1786   default: return 0;
1787   case AMDGPU::sub0: return 0;
1788   case AMDGPU::sub1: return 1;
1789   case AMDGPU::sub2: return 2;
1790   case AMDGPU::sub3: return 3;
1791   }
1792 }
1793
1794 /// \brief Adjust the writemask of MIMG instructions
1795 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1796                                        SelectionDAG &DAG) const {
1797   SDNode *Users[4] = { };
1798   unsigned Lane = 0;
1799   unsigned OldDmask = Node->getConstantOperandVal(0);
1800   unsigned NewDmask = 0;
1801
1802   // Try to figure out the used register components
1803   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1804        I != E; ++I) {
1805
1806     // Abort if we can't understand the usage
1807     if (!I->isMachineOpcode() ||
1808         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1809       return;
1810
1811     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1812     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1813     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1814     // set, etc.
1815     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1816
1817     // Set which texture component corresponds to the lane.
1818     unsigned Comp;
1819     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1820       assert(Dmask);
1821       Comp = countTrailingZeros(Dmask);
1822       Dmask &= ~(1 << Comp);
1823     }
1824
1825     // Abort if we have more than one user per component
1826     if (Users[Lane])
1827       return;
1828
1829     Users[Lane] = *I;
1830     NewDmask |= 1 << Comp;
1831   }
1832
1833   // Abort if there's no change
1834   if (NewDmask == OldDmask)
1835     return;
1836
1837   // Adjust the writemask in the node
1838   std::vector<SDValue> Ops;
1839   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1840   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1841     Ops.push_back(Node->getOperand(i));
1842   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1843
1844   // If we only got one lane, replace it with a copy
1845   // (if NewDmask has only one bit set...)
1846   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1847     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1848     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1849                                       SDLoc(), Users[Lane]->getValueType(0),
1850                                       SDValue(Node, 0), RC);
1851     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1852     return;
1853   }
1854
1855   // Update the users of the node with the new indices
1856   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1857
1858     SDNode *User = Users[i];
1859     if (!User)
1860       continue;
1861
1862     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1863     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1864
1865     switch (Idx) {
1866     default: break;
1867     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1868     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1869     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1870     }
1871   }
1872 }
1873
1874 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1875 /// with frame index operands.
1876 /// LLVM assumes that inputs are to these instructions are registers.
1877 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1878                                                      SelectionDAG &DAG) const {
1879
1880   SmallVector<SDValue, 8> Ops;
1881   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1882     if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1883       Ops.push_back(Node->getOperand(i));
1884       continue;
1885     }
1886
1887     SDLoc DL(Node);
1888     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1889                                      Node->getOperand(i).getValueType(),
1890                                      Node->getOperand(i)), 0));
1891   }
1892
1893   DAG.UpdateNodeOperands(Node, Ops);
1894 }
1895
1896 /// \brief Fold the instructions after selecting them.
1897 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1898                                           SelectionDAG &DAG) const {
1899   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1900       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1901   Node = AdjustRegClass(Node, DAG);
1902
1903   if (TII->isMIMG(Node->getMachineOpcode()))
1904     adjustWritemask(Node, DAG);
1905
1906   if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1907       Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1908     legalizeTargetIndependentNode(Node, DAG);
1909     return Node;
1910   }
1911
1912   return legalizeOperands(Node, DAG);
1913 }
1914
1915 /// \brief Assign the register class depending on the number of
1916 /// bits set in the writemask
1917 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1918                                                      SDNode *Node) const {
1919   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1920       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1921
1922   TII->legalizeOperands(MI);
1923
1924   if (TII->isMIMG(MI->getOpcode())) {
1925     unsigned VReg = MI->getOperand(0).getReg();
1926     unsigned Writemask = MI->getOperand(1).getImm();
1927     unsigned BitsSet = 0;
1928     for (unsigned i = 0; i < 4; ++i)
1929       BitsSet += Writemask & (1 << i) ? 1 : 0;
1930
1931     const TargetRegisterClass *RC;
1932     switch (BitsSet) {
1933     default: return;
1934     case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1935     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1936     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1937     }
1938
1939     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1940     MI->setDesc(TII->get(NewOpcode));
1941     MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1942     MRI.setRegClass(VReg, RC);
1943     return;
1944   }
1945
1946   // Replace unused atomics with the no return version.
1947   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1948   if (NoRetAtomicOp != -1) {
1949     if (!Node->hasAnyUseOfValue(0)) {
1950       MI->setDesc(TII->get(NoRetAtomicOp));
1951       MI->RemoveOperand(0);
1952     }
1953
1954     return;
1955   }
1956 }
1957
1958 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
1959   SDValue K = DAG.getTargetConstant(Val, MVT::i32);
1960   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
1961 }
1962
1963 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
1964                                                 SDLoc DL,
1965                                                 SDValue Ptr) const {
1966 #if 1
1967     // XXX - Workaround for moveToVALU not handling different register class
1968     // inserts for REG_SEQUENCE.
1969
1970     // Build the half of the subregister with the constants.
1971     const SDValue Ops0[] = {
1972       DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
1973       buildSMovImm32(DAG, DL, 0),
1974       DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
1975       buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
1976       DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
1977     };
1978
1979     SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1980                                                   MVT::v2i32, Ops0), 0);
1981
1982     // Combine the constants and the pointer.
1983     const SDValue Ops1[] = {
1984       DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
1985       Ptr,
1986       DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
1987       SubRegHi,
1988       DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
1989     };
1990
1991     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
1992 #else
1993     const SDValue Ops[] = {
1994       DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
1995       Ptr,
1996       DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
1997       buildSMovImm32(DAG, DL, 0),
1998       DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
1999       buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
2000       DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2001     };
2002
2003     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2004
2005 #endif
2006 }
2007
2008 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2009 ///        The TID (Thread ID) is multipled by the stride value (bits [61:48]
2010 ///        of the resource descriptor) to create an offset, which is added to the
2011 ///        resource ponter.
2012 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2013                                            SDLoc DL,
2014                                            SDValue Ptr,
2015                                            uint32_t RsrcDword1,
2016                                            uint64_t RsrcDword2And3) const {
2017   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2018   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2019   if (RsrcDword1) {
2020     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2021                                      DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2022   }
2023
2024   SDValue DataLo = buildSMovImm32(DAG, DL,
2025                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2026   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2027
2028   const SDValue Ops[] = {
2029     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2030     PtrLo,
2031     DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2032     PtrHi,
2033     DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2034     DataLo,
2035     DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2036     DataHi,
2037     DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2038   };
2039
2040   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2041 }
2042
2043 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2044                                                   SDLoc DL,
2045                                                   SDValue Ptr) const {
2046   uint64_t Rsrc = AMDGPU::RSRC_DATA_FORMAT | AMDGPU::RSRC_TID_ENABLE |
2047                   0xffffffff; // Size
2048
2049   return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2050 }
2051
2052 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2053                                                 SelectionDAG &DAG) const {
2054
2055   SDLoc DL(N);
2056   unsigned NewOpcode = N->getMachineOpcode();
2057
2058   switch (N->getMachineOpcode()) {
2059   default: return N;
2060   case AMDGPU::S_LOAD_DWORD_IMM:
2061     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2062     // Fall-through
2063   case AMDGPU::S_LOAD_DWORDX2_SGPR:
2064     if (NewOpcode == N->getMachineOpcode()) {
2065       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2066     }
2067     // Fall-through
2068   case AMDGPU::S_LOAD_DWORDX4_IMM:
2069   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2070     if (NewOpcode == N->getMachineOpcode()) {
2071       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2072     }
2073     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2074       return N;
2075     }
2076     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2077
2078     const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2079     SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2080     MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2081
2082     SmallVector<SDValue, 8> Ops;
2083     Ops.push_back(SDValue(RSrc, 0));
2084     Ops.push_back(N->getOperand(0));
2085     Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
2086
2087     // Copy remaining operands so we keep any chain and glue nodes that follow
2088     // the normal operands.
2089     for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2090       Ops.push_back(N->getOperand(I));
2091
2092     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2093   }
2094   }
2095 }
2096
2097 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2098                                                const TargetRegisterClass *RC,
2099                                                unsigned Reg, EVT VT) const {
2100   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2101
2102   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2103                             cast<RegisterSDNode>(VReg)->getReg(), VT);
2104 }