R600/SI: Move all rsrc building functions to SIISelLowering
[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   case AMDGPU::FCLAMP_SI: {
639     const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
640         getTargetMachine().getSubtargetImpl()->getInstrInfo());
641     DebugLoc DL = MI->getDebugLoc();
642     unsigned DestReg = MI->getOperand(0).getReg();
643     BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
644       .addImm(0) // SRC0 modifiers
645       .addOperand(MI->getOperand(1))
646       .addImm(0) // SRC1 modifiers
647       .addImm(0) // SRC1
648       .addImm(1) // CLAMP
649       .addImm(0); // OMOD
650     MI->eraseFromParent();
651   }
652   }
653   return BB;
654 }
655
656 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
657   if (!VT.isVector()) {
658     return MVT::i1;
659   }
660   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
661 }
662
663 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
664   return MVT::i32;
665 }
666
667 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
668   VT = VT.getScalarType();
669
670   if (!VT.isSimple())
671     return false;
672
673   switch (VT.getSimpleVT().SimpleTy) {
674   case MVT::f32:
675     return false; /* There is V_MAD_F32 for f32 */
676   case MVT::f64:
677     return true;
678   default:
679     break;
680   }
681
682   return false;
683 }
684
685 //===----------------------------------------------------------------------===//
686 // Custom DAG Lowering Operations
687 //===----------------------------------------------------------------------===//
688
689 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
690   switch (Op.getOpcode()) {
691   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
692   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
693   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
694   case ISD::LOAD: {
695     SDValue Result = LowerLOAD(Op, DAG);
696     assert((!Result.getNode() ||
697             Result.getNode()->getNumValues() == 2) &&
698            "Load should return a value and a chain");
699     return Result;
700   }
701
702   case ISD::FSIN:
703   case ISD::FCOS:
704     return LowerTrig(Op, DAG);
705   case ISD::SELECT: return LowerSELECT(Op, DAG);
706   case ISD::FDIV: return LowerFDIV(Op, DAG);
707   case ISD::STORE: return LowerSTORE(Op, DAG);
708   case ISD::GlobalAddress: {
709     MachineFunction &MF = DAG.getMachineFunction();
710     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
711     return LowerGlobalAddress(MFI, Op, DAG);
712   }
713   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
714   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
715   }
716   return SDValue();
717 }
718
719 /// \brief Helper function for LowerBRCOND
720 static SDNode *findUser(SDValue Value, unsigned Opcode) {
721
722   SDNode *Parent = Value.getNode();
723   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
724        I != E; ++I) {
725
726     if (I.getUse().get() != Value)
727       continue;
728
729     if (I->getOpcode() == Opcode)
730       return *I;
731   }
732   return nullptr;
733 }
734
735 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
736
737   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
738   unsigned FrameIndex = FINode->getIndex();
739
740   return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
741 }
742
743 /// This transforms the control flow intrinsics to get the branch destination as
744 /// last parameter, also switches branch target with BR if the need arise
745 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
746                                       SelectionDAG &DAG) const {
747
748   SDLoc DL(BRCOND);
749
750   SDNode *Intr = BRCOND.getOperand(1).getNode();
751   SDValue Target = BRCOND.getOperand(2);
752   SDNode *BR = nullptr;
753
754   if (Intr->getOpcode() == ISD::SETCC) {
755     // As long as we negate the condition everything is fine
756     SDNode *SetCC = Intr;
757     assert(SetCC->getConstantOperandVal(1) == 1);
758     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
759            ISD::SETNE);
760     Intr = SetCC->getOperand(0).getNode();
761
762   } else {
763     // Get the target from BR if we don't negate the condition
764     BR = findUser(BRCOND, ISD::BR);
765     Target = BR->getOperand(1);
766   }
767
768   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
769
770   // Build the result and
771   SmallVector<EVT, 4> Res;
772   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
773     Res.push_back(Intr->getValueType(i));
774
775   // operands of the new intrinsic call
776   SmallVector<SDValue, 4> Ops;
777   Ops.push_back(BRCOND.getOperand(0));
778   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
779     Ops.push_back(Intr->getOperand(i));
780   Ops.push_back(Target);
781
782   // build the new intrinsic call
783   SDNode *Result = DAG.getNode(
784     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
785     DAG.getVTList(Res), Ops).getNode();
786
787   if (BR) {
788     // Give the branch instruction our target
789     SDValue Ops[] = {
790       BR->getOperand(0),
791       BRCOND.getOperand(2)
792     };
793     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
794     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
795     BR = NewBR.getNode();
796   }
797
798   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
799
800   // Copy the intrinsic results to registers
801   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
802     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
803     if (!CopyToReg)
804       continue;
805
806     Chain = DAG.getCopyToReg(
807       Chain, DL,
808       CopyToReg->getOperand(1),
809       SDValue(Result, i - 1),
810       SDValue());
811
812     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
813   }
814
815   // Remove the old intrinsic from the chain
816   DAG.ReplaceAllUsesOfValueWith(
817     SDValue(Intr, Intr->getNumValues() - 1),
818     Intr->getOperand(0));
819
820   return Chain;
821 }
822
823 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
824                                              SDValue Op,
825                                              SelectionDAG &DAG) const {
826   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
827
828   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
829     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
830
831   SDLoc DL(GSD);
832   const GlobalValue *GV = GSD->getGlobal();
833   MVT PtrVT = getPointerTy(GSD->getAddressSpace());
834
835   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
836   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
837
838   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
839                               DAG.getConstant(0, MVT::i32));
840   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
841                               DAG.getConstant(1, MVT::i32));
842
843   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
844                            PtrLo, GA);
845   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
846                            PtrHi, DAG.getConstant(0, MVT::i32),
847                            SDValue(Lo.getNode(), 1));
848   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
849 }
850
851 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
852                                                   SelectionDAG &DAG) const {
853   MachineFunction &MF = DAG.getMachineFunction();
854   const SIRegisterInfo *TRI =
855       static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
856
857   EVT VT = Op.getValueType();
858   SDLoc DL(Op);
859   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
860
861   switch (IntrinsicID) {
862   case Intrinsic::r600_read_ngroups_x:
863     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
864                           SI::KernelInputOffsets::NGROUPS_X, false);
865   case Intrinsic::r600_read_ngroups_y:
866     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
867                           SI::KernelInputOffsets::NGROUPS_Y, false);
868   case Intrinsic::r600_read_ngroups_z:
869     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
870                           SI::KernelInputOffsets::NGROUPS_Z, false);
871   case Intrinsic::r600_read_global_size_x:
872     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
873                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
874   case Intrinsic::r600_read_global_size_y:
875     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
876                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
877   case Intrinsic::r600_read_global_size_z:
878     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
879                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
880   case Intrinsic::r600_read_local_size_x:
881     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
882                           SI::KernelInputOffsets::LOCAL_SIZE_X, false);
883   case Intrinsic::r600_read_local_size_y:
884     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
885                           SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
886   case Intrinsic::r600_read_local_size_z:
887     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
888                           SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
889
890   case Intrinsic::AMDGPU_read_workdim:
891     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
892                           MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
893                           false);
894
895   case Intrinsic::r600_read_tgid_x:
896     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
897       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
898   case Intrinsic::r600_read_tgid_y:
899     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
900       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
901   case Intrinsic::r600_read_tgid_z:
902     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
903       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
904   case Intrinsic::r600_read_tidig_x:
905     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
906       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
907   case Intrinsic::r600_read_tidig_y:
908     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
909       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
910   case Intrinsic::r600_read_tidig_z:
911     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
912       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
913   case AMDGPUIntrinsic::SI_load_const: {
914     SDValue Ops[] = {
915       Op.getOperand(1),
916       Op.getOperand(2)
917     };
918
919     MachineMemOperand *MMO = MF.getMachineMemOperand(
920       MachinePointerInfo(),
921       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
922       VT.getStoreSize(), 4);
923     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
924                                    Op->getVTList(), Ops, VT, MMO);
925   }
926   case AMDGPUIntrinsic::SI_sample:
927     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
928   case AMDGPUIntrinsic::SI_sampleb:
929     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
930   case AMDGPUIntrinsic::SI_sampled:
931     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
932   case AMDGPUIntrinsic::SI_samplel:
933     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
934   case AMDGPUIntrinsic::SI_vs_load_input:
935     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
936                        Op.getOperand(1),
937                        Op.getOperand(2),
938                        Op.getOperand(3));
939   default:
940     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
941   }
942 }
943
944 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
945                                               SelectionDAG &DAG) const {
946   MachineFunction &MF = DAG.getMachineFunction();
947   SDValue Chain = Op.getOperand(0);
948   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
949
950   switch (IntrinsicID) {
951   case AMDGPUIntrinsic::SI_tbuffer_store: {
952     SDLoc DL(Op);
953     SDValue Ops[] = {
954       Chain,
955       Op.getOperand(2),
956       Op.getOperand(3),
957       Op.getOperand(4),
958       Op.getOperand(5),
959       Op.getOperand(6),
960       Op.getOperand(7),
961       Op.getOperand(8),
962       Op.getOperand(9),
963       Op.getOperand(10),
964       Op.getOperand(11),
965       Op.getOperand(12),
966       Op.getOperand(13),
967       Op.getOperand(14)
968     };
969
970     EVT VT = Op.getOperand(3).getValueType();
971
972     MachineMemOperand *MMO = MF.getMachineMemOperand(
973       MachinePointerInfo(),
974       MachineMemOperand::MOStore,
975       VT.getStoreSize(), 4);
976     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
977                                    Op->getVTList(), Ops, VT, MMO);
978   }
979   default:
980     return SDValue();
981   }
982 }
983
984 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
985   SDLoc DL(Op);
986   LoadSDNode *Load = cast<LoadSDNode>(Op);
987
988   if (Op.getValueType().isVector()) {
989     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
990            "Custom lowering for non-i32 vectors hasn't been implemented.");
991     unsigned NumElements = Op.getValueType().getVectorNumElements();
992     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
993     switch (Load->getAddressSpace()) {
994       default: break;
995       case AMDGPUAS::GLOBAL_ADDRESS:
996       case AMDGPUAS::PRIVATE_ADDRESS:
997         // v4 loads are supported for private and global memory.
998         if (NumElements <= 4)
999           break;
1000         // fall-through
1001       case AMDGPUAS::LOCAL_ADDRESS:
1002         return ScalarizeVectorLoad(Op, DAG);
1003     }
1004   }
1005
1006   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1007 }
1008
1009 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1010                                                const SDValue &Op,
1011                                                SelectionDAG &DAG) const {
1012   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1013                      Op.getOperand(2),
1014                      Op.getOperand(3),
1015                      Op.getOperand(4));
1016 }
1017
1018 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1019   if (Op.getValueType() != MVT::i64)
1020     return SDValue();
1021
1022   SDLoc DL(Op);
1023   SDValue Cond = Op.getOperand(0);
1024
1025   SDValue Zero = DAG.getConstant(0, MVT::i32);
1026   SDValue One = DAG.getConstant(1, MVT::i32);
1027
1028   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1029   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1030
1031   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1032   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1033
1034   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1035
1036   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1037   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1038
1039   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1040
1041   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1042   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1043 }
1044
1045 // Catch division cases where we can use shortcuts with rcp and rsq
1046 // instructions.
1047 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1048   SDLoc SL(Op);
1049   SDValue LHS = Op.getOperand(0);
1050   SDValue RHS = Op.getOperand(1);
1051   EVT VT = Op.getValueType();
1052   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1053
1054   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1055     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1056         CLHS->isExactlyValue(1.0)) {
1057       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1058       // the CI documentation has a worst case error of 1 ulp.
1059       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1060       // use it as long as we aren't trying to use denormals.
1061
1062       // 1.0 / sqrt(x) -> rsq(x)
1063       //
1064       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1065       // error seems really high at 2^29 ULP.
1066       if (RHS.getOpcode() == ISD::FSQRT)
1067         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1068
1069       // 1.0 / x -> rcp(x)
1070       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1071     }
1072   }
1073
1074   if (Unsafe) {
1075     // Turn into multiply by the reciprocal.
1076     // x / y -> x * (1.0 / y)
1077     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1078     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1079   }
1080
1081   return SDValue();
1082 }
1083
1084 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1085   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1086   if (FastLowered.getNode())
1087     return FastLowered;
1088
1089   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1090   // selection error for now rather than do something incorrect.
1091   if (Subtarget->hasFP32Denormals())
1092     return SDValue();
1093
1094   SDLoc SL(Op);
1095   SDValue LHS = Op.getOperand(0);
1096   SDValue RHS = Op.getOperand(1);
1097
1098   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1099
1100   const APFloat K0Val(BitsToFloat(0x6f800000));
1101   const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1102
1103   const APFloat K1Val(BitsToFloat(0x2f800000));
1104   const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1105
1106   const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1107
1108   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1109
1110   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1111
1112   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1113
1114   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1115
1116   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1117
1118   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1119
1120   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1121 }
1122
1123 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1124   return SDValue();
1125 }
1126
1127 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1128   EVT VT = Op.getValueType();
1129
1130   if (VT == MVT::f32)
1131     return LowerFDIV32(Op, DAG);
1132
1133   if (VT == MVT::f64)
1134     return LowerFDIV64(Op, DAG);
1135
1136   llvm_unreachable("Unexpected type for fdiv");
1137 }
1138
1139 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1140   SDLoc DL(Op);
1141   StoreSDNode *Store = cast<StoreSDNode>(Op);
1142   EVT VT = Store->getMemoryVT();
1143
1144   // These stores are legal.
1145   if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1146       VT.isVector() && VT.getVectorNumElements() == 2 &&
1147       VT.getVectorElementType() == MVT::i32)
1148     return SDValue();
1149
1150   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1151     if (VT.isVector() && VT.getVectorNumElements() > 4)
1152       return ScalarizeVectorStore(Op, DAG);
1153     return SDValue();
1154   }
1155
1156   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1157   if (Ret.getNode())
1158     return Ret;
1159
1160   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1161       return ScalarizeVectorStore(Op, DAG);
1162
1163   if (VT == MVT::i1)
1164     return DAG.getTruncStore(Store->getChain(), DL,
1165                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1166                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1167
1168   return SDValue();
1169 }
1170
1171 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1172   EVT VT = Op.getValueType();
1173   SDValue Arg = Op.getOperand(0);
1174   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1175         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1176           DAG.getConstantFP(0.5 / M_PI, VT)));
1177
1178   switch (Op.getOpcode()) {
1179   case ISD::FCOS:
1180     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1181   case ISD::FSIN:
1182     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1183   default:
1184     llvm_unreachable("Wrong trig opcode");
1185   }
1186 }
1187
1188 //===----------------------------------------------------------------------===//
1189 // Custom DAG optimizations
1190 //===----------------------------------------------------------------------===//
1191
1192 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1193                                                      DAGCombinerInfo &DCI) {
1194   EVT VT = N->getValueType(0);
1195   EVT ScalarVT = VT.getScalarType();
1196   if (ScalarVT != MVT::f32)
1197     return SDValue();
1198
1199   SelectionDAG &DAG = DCI.DAG;
1200   SDLoc DL(N);
1201
1202   SDValue Src = N->getOperand(0);
1203   EVT SrcVT = Src.getValueType();
1204
1205   // TODO: We could try to match extracting the higher bytes, which would be
1206   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1207   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1208   // about in practice.
1209   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1210     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1211       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1212       DCI.AddToWorklist(Cvt.getNode());
1213       return Cvt;
1214     }
1215   }
1216
1217   // We are primarily trying to catch operations on illegal vector types
1218   // before they are expanded.
1219   // For scalars, we can use the more flexible method of checking masked bits
1220   // after legalization.
1221   if (!DCI.isBeforeLegalize() ||
1222       !SrcVT.isVector() ||
1223       SrcVT.getVectorElementType() != MVT::i8) {
1224     return SDValue();
1225   }
1226
1227   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1228
1229   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1230   // size as 4.
1231   unsigned NElts = SrcVT.getVectorNumElements();
1232   if (!SrcVT.isSimple() && NElts != 3)
1233     return SDValue();
1234
1235   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1236   // prevent a mess from expanding to v4i32 and repacking.
1237   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1238     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1239     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1240     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1241
1242     LoadSDNode *Load = cast<LoadSDNode>(Src);
1243     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1244                                      Load->getChain(),
1245                                      Load->getBasePtr(),
1246                                      LoadVT,
1247                                      Load->getMemOperand());
1248
1249     // Make sure successors of the original load stay after it by updating
1250     // them to use the new Chain.
1251     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1252
1253     SmallVector<SDValue, 4> Elts;
1254     if (RegVT.isVector())
1255       DAG.ExtractVectorElements(NewLoad, Elts);
1256     else
1257       Elts.push_back(NewLoad);
1258
1259     SmallVector<SDValue, 4> Ops;
1260
1261     unsigned EltIdx = 0;
1262     for (SDValue Elt : Elts) {
1263       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1264       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1265         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1266         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1267         DCI.AddToWorklist(Cvt.getNode());
1268         Ops.push_back(Cvt);
1269       }
1270
1271       ++EltIdx;
1272     }
1273
1274     assert(Ops.size() == NElts);
1275
1276     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1277   }
1278
1279   return SDValue();
1280 }
1281
1282 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1283
1284 // This is a variant of
1285 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1286 //
1287 // The normal DAG combiner will do this, but only if the add has one use since
1288 // that would increase the number of instructions.
1289 //
1290 // This prevents us from seeing a constant offset that can be folded into a
1291 // memory instruction's addressing mode. If we know the resulting add offset of
1292 // a pointer can be folded into an addressing offset, we can replace the pointer
1293 // operand with the add of new constant offset. This eliminates one of the uses,
1294 // and may allow the remaining use to also be simplified.
1295 //
1296 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1297                                                unsigned AddrSpace,
1298                                                DAGCombinerInfo &DCI) const {
1299   SDValue N0 = N->getOperand(0);
1300   SDValue N1 = N->getOperand(1);
1301
1302   if (N0.getOpcode() != ISD::ADD)
1303     return SDValue();
1304
1305   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1306   if (!CN1)
1307     return SDValue();
1308
1309   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1310   if (!CAdd)
1311     return SDValue();
1312
1313   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1314       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1315
1316   // If the resulting offset is too large, we can't fold it into the addressing
1317   // mode offset.
1318   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1319   if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1320     return SDValue();
1321
1322   SelectionDAG &DAG = DCI.DAG;
1323   SDLoc SL(N);
1324   EVT VT = N->getValueType(0);
1325
1326   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1327   SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1328
1329   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1330 }
1331
1332 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1333                                             DAGCombinerInfo &DCI) const {
1334   SelectionDAG &DAG = DCI.DAG;
1335   SDLoc DL(N);
1336   EVT VT = N->getValueType(0);
1337
1338   switch (N->getOpcode()) {
1339     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1340     case ISD::SETCC: {
1341       SDValue Arg0 = N->getOperand(0);
1342       SDValue Arg1 = N->getOperand(1);
1343       SDValue CC = N->getOperand(2);
1344       ConstantSDNode * C = nullptr;
1345       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1346
1347       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1348       if (VT == MVT::i1
1349           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1350           && Arg0.getOperand(0).getValueType() == MVT::i1
1351           && (C = dyn_cast<ConstantSDNode>(Arg1))
1352           && C->isNullValue()
1353           && CCOp == ISD::SETNE) {
1354         return SimplifySetCC(VT, Arg0.getOperand(0),
1355                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1356       }
1357       break;
1358     }
1359
1360   case AMDGPUISD::CVT_F32_UBYTE0:
1361   case AMDGPUISD::CVT_F32_UBYTE1:
1362   case AMDGPUISD::CVT_F32_UBYTE2:
1363   case AMDGPUISD::CVT_F32_UBYTE3: {
1364     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1365
1366     SDValue Src = N->getOperand(0);
1367     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1368
1369     APInt KnownZero, KnownOne;
1370     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1371                                           !DCI.isBeforeLegalizeOps());
1372     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1373     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1374         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1375       DCI.CommitTargetLoweringOpt(TLO);
1376     }
1377
1378     break;
1379   }
1380
1381   case ISD::UINT_TO_FP: {
1382     return performUCharToFloatCombine(N, DCI);
1383
1384   case ISD::FADD: {
1385     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1386       break;
1387
1388     EVT VT = N->getValueType(0);
1389     if (VT != MVT::f32)
1390       break;
1391
1392     SDValue LHS = N->getOperand(0);
1393     SDValue RHS = N->getOperand(1);
1394
1395     // These should really be instruction patterns, but writing patterns with
1396     // source modiifiers is a pain.
1397
1398     // fadd (fadd (a, a), b) -> mad 2.0, a, b
1399     if (LHS.getOpcode() == ISD::FADD) {
1400       SDValue A = LHS.getOperand(0);
1401       if (A == LHS.getOperand(1)) {
1402         const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1403         return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1404       }
1405     }
1406
1407     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1408     if (RHS.getOpcode() == ISD::FADD) {
1409       SDValue A = RHS.getOperand(0);
1410       if (A == RHS.getOperand(1)) {
1411         const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1412         return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1413       }
1414     }
1415
1416     break;
1417   }
1418   case ISD::FSUB: {
1419     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1420       break;
1421
1422     EVT VT = N->getValueType(0);
1423
1424     // Try to get the fneg to fold into the source modifier. This undoes generic
1425     // DAG combines and folds them into the mad.
1426     if (VT == MVT::f32) {
1427       SDValue LHS = N->getOperand(0);
1428       SDValue RHS = N->getOperand(1);
1429
1430       if (LHS.getOpcode() == ISD::FMUL) {
1431         // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1432
1433         SDValue A = LHS.getOperand(0);
1434         SDValue B = LHS.getOperand(1);
1435         SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1436
1437         return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1438       }
1439
1440       if (RHS.getOpcode() == ISD::FMUL) {
1441         // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1442
1443         SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1444         SDValue B = RHS.getOperand(1);
1445         SDValue C = LHS;
1446
1447         return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1448       }
1449
1450       if (LHS.getOpcode() == ISD::FADD) {
1451         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1452
1453         SDValue A = LHS.getOperand(0);
1454         if (A == LHS.getOperand(1)) {
1455           const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1456           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1457
1458           return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1459         }
1460       }
1461
1462       if (RHS.getOpcode() == ISD::FADD) {
1463         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1464
1465         SDValue A = RHS.getOperand(0);
1466         if (A == RHS.getOperand(1)) {
1467           const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1468           return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1469         }
1470       }
1471     }
1472
1473     break;
1474   }
1475   }
1476   case ISD::LOAD:
1477   case ISD::STORE:
1478   case ISD::ATOMIC_LOAD:
1479   case ISD::ATOMIC_STORE:
1480   case ISD::ATOMIC_CMP_SWAP:
1481   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1482   case ISD::ATOMIC_SWAP:
1483   case ISD::ATOMIC_LOAD_ADD:
1484   case ISD::ATOMIC_LOAD_SUB:
1485   case ISD::ATOMIC_LOAD_AND:
1486   case ISD::ATOMIC_LOAD_OR:
1487   case ISD::ATOMIC_LOAD_XOR:
1488   case ISD::ATOMIC_LOAD_NAND:
1489   case ISD::ATOMIC_LOAD_MIN:
1490   case ISD::ATOMIC_LOAD_MAX:
1491   case ISD::ATOMIC_LOAD_UMIN:
1492   case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1493     if (DCI.isBeforeLegalize())
1494       break;
1495
1496     MemSDNode *MemNode = cast<MemSDNode>(N);
1497     SDValue Ptr = MemNode->getBasePtr();
1498
1499     // TODO: We could also do this for multiplies.
1500     unsigned AS = MemNode->getAddressSpace();
1501     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1502       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1503       if (NewPtr) {
1504         SmallVector<SDValue, 8> NewOps;
1505         for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1506           NewOps.push_back(MemNode->getOperand(I));
1507
1508         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1509         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1510       }
1511     }
1512     break;
1513   }
1514   }
1515   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1516 }
1517
1518 /// \brief Test if RegClass is one of the VSrc classes
1519 static bool isVSrc(unsigned RegClass) {
1520   switch(RegClass) {
1521     default: return false;
1522     case AMDGPU::VSrc_32RegClassID:
1523     case AMDGPU::VCSrc_32RegClassID:
1524     case AMDGPU::VSrc_64RegClassID:
1525     case AMDGPU::VCSrc_64RegClassID:
1526       return true;
1527   }
1528 }
1529
1530 /// \brief Test if RegClass is one of the SSrc classes
1531 static bool isSSrc(unsigned RegClass) {
1532   return AMDGPU::SSrc_32RegClassID == RegClass ||
1533          AMDGPU::SSrc_64RegClassID == RegClass;
1534 }
1535
1536 /// \brief Analyze the possible immediate value Op
1537 ///
1538 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1539 /// and the immediate value if it's a literal immediate
1540 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1541
1542   union {
1543     int32_t I;
1544     float F;
1545   } Imm;
1546
1547   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1548     if (Node->getZExtValue() >> 32) {
1549         return -1;
1550     }
1551     Imm.I = Node->getSExtValue();
1552   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1553     if (N->getValueType(0) != MVT::f32)
1554       return -1;
1555     Imm.F = Node->getValueAPF().convertToFloat();
1556   } else
1557     return -1; // It isn't an immediate
1558
1559   if ((Imm.I >= -16 && Imm.I <= 64) ||
1560       Imm.F == 0.5f || Imm.F == -0.5f ||
1561       Imm.F == 1.0f || Imm.F == -1.0f ||
1562       Imm.F == 2.0f || Imm.F == -2.0f ||
1563       Imm.F == 4.0f || Imm.F == -4.0f)
1564     return 0; // It's an inline immediate
1565
1566   return Imm.I; // It's a literal immediate
1567 }
1568
1569 /// \brief Try to fold an immediate directly into an instruction
1570 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1571                                bool &ScalarSlotUsed) const {
1572
1573   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1574   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1575       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1576   if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1577     return false;
1578
1579   const SDValue &Op = Mov->getOperand(0);
1580   int32_t Value = analyzeImmediate(Op.getNode());
1581   if (Value == -1) {
1582     // Not an immediate at all
1583     return false;
1584
1585   } else if (Value == 0) {
1586     // Inline immediates can always be fold
1587     Operand = Op;
1588     return true;
1589
1590   } else if (Value == Immediate) {
1591     // Already fold literal immediate
1592     Operand = Op;
1593     return true;
1594
1595   } else if (!ScalarSlotUsed && !Immediate) {
1596     // Fold this literal immediate
1597     ScalarSlotUsed = true;
1598     Immediate = Value;
1599     Operand = Op;
1600     return true;
1601
1602   }
1603
1604   return false;
1605 }
1606
1607 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1608                                    SelectionDAG &DAG, const SDValue &Op) const {
1609   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1610       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1611   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1612
1613   if (!Op->isMachineOpcode()) {
1614     switch(Op->getOpcode()) {
1615     case ISD::CopyFromReg: {
1616       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1617       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1618       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1619         return MRI.getRegClass(Reg);
1620       }
1621       return TRI.getPhysRegClass(Reg);
1622     }
1623     default:  return nullptr;
1624     }
1625   }
1626   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1627   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1628   if (OpClassID != -1) {
1629     return TRI.getRegClass(OpClassID);
1630   }
1631   switch(Op.getMachineOpcode()) {
1632   case AMDGPU::COPY_TO_REGCLASS:
1633     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1634     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1635
1636     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1637     // class, then the register class for the value could be either a
1638     // VReg or and SReg.  In order to get a more accurate
1639     if (isVSrc(OpClassID))
1640       return getRegClassForNode(DAG, Op.getOperand(0));
1641
1642     return TRI.getRegClass(OpClassID);
1643   case AMDGPU::EXTRACT_SUBREG: {
1644     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1645     const TargetRegisterClass *SuperClass =
1646       getRegClassForNode(DAG, Op.getOperand(0));
1647     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1648   }
1649   case AMDGPU::REG_SEQUENCE:
1650     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1651     return TRI.getRegClass(
1652       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1653   default:
1654     return getRegClassFor(Op.getSimpleValueType());
1655   }
1656 }
1657
1658 /// \brief Does "Op" fit into register class "RegClass" ?
1659 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1660                                     unsigned RegClass) const {
1661   const TargetRegisterInfo *TRI =
1662       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1663   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1664   if (!RC) {
1665     return false;
1666   }
1667   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1668 }
1669
1670 /// \returns true if \p Node's operands are different from the SDValue list
1671 /// \p Ops
1672 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1673   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1674     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1675       return true;
1676     }
1677   }
1678   return false;
1679 }
1680
1681 /// TODO: This needs to be removed. It's current primary purpose is to fold
1682 /// immediates into operands when legal. The legalization parts are redundant
1683 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1684 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1685                                            SelectionDAG &DAG) const {
1686   // Original encoding (either e32 or e64)
1687   int Opcode = Node->getMachineOpcode();
1688   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1689       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1690   const MCInstrDesc *Desc = &TII->get(Opcode);
1691
1692   unsigned NumDefs = Desc->getNumDefs();
1693   unsigned NumOps = Desc->getNumOperands();
1694
1695   // Commuted opcode if available
1696   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1697   const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1698
1699   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1700   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1701
1702   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1703   bool HaveVSrc = false, HaveSSrc = false;
1704
1705   // First figure out what we already have in this instruction.
1706   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1707        i != e && Op < NumOps; ++i, ++Op) {
1708
1709     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1710     if (isVSrc(RegClass))
1711       HaveVSrc = true;
1712     else if (isSSrc(RegClass))
1713       HaveSSrc = true;
1714     else
1715       continue;
1716
1717     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1718     if (Imm != -1 && Imm != 0) {
1719       // Literal immediate
1720       Immediate = Imm;
1721     }
1722   }
1723
1724   // If we neither have VSrc nor SSrc, it makes no sense to continue.
1725   if (!HaveVSrc && !HaveSSrc)
1726     return Node;
1727
1728   // No scalar allowed when we have both VSrc and SSrc
1729   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1730
1731   // If this instruction has an implicit use of VCC, then it can't use the
1732   // constant bus.
1733   for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1734     if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1735       ScalarSlotUsed = true;
1736       break;
1737     }
1738   }
1739
1740   // Second go over the operands and try to fold them
1741   std::vector<SDValue> Ops;
1742   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1743        i != e && Op < NumOps; ++i, ++Op) {
1744
1745     const SDValue &Operand = Node->getOperand(i);
1746     Ops.push_back(Operand);
1747
1748     // Already folded immediate?
1749     if (isa<ConstantSDNode>(Operand.getNode()) ||
1750         isa<ConstantFPSDNode>(Operand.getNode()))
1751       continue;
1752
1753     // Is this a VSrc or SSrc operand?
1754     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1755     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1756       // Try to fold the immediates. If this ends up with multiple constant bus
1757       // uses, it will be legalized later.
1758       foldImm(Ops[i], Immediate, ScalarSlotUsed);
1759       continue;
1760     }
1761
1762     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1763
1764       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1765       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1766
1767       // Test if it makes sense to swap operands
1768       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1769           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1770            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1771
1772         // Swap commutable operands
1773         std::swap(Ops[0], Ops[1]);
1774
1775         Desc = DescRev;
1776         DescRev = nullptr;
1777         continue;
1778       }
1779     }
1780   }
1781
1782   // Add optional chain and glue
1783   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1784     Ops.push_back(Node->getOperand(i));
1785
1786   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1787   // this case a brand new node is always be created, even if the operands
1788   // are the same as before.  So, manually check if anything has been changed.
1789   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1790     return Node;
1791   }
1792
1793   // Create a complete new instruction
1794   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1795 }
1796
1797 /// \brief Helper function for adjustWritemask
1798 static unsigned SubIdx2Lane(unsigned Idx) {
1799   switch (Idx) {
1800   default: return 0;
1801   case AMDGPU::sub0: return 0;
1802   case AMDGPU::sub1: return 1;
1803   case AMDGPU::sub2: return 2;
1804   case AMDGPU::sub3: return 3;
1805   }
1806 }
1807
1808 /// \brief Adjust the writemask of MIMG instructions
1809 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1810                                        SelectionDAG &DAG) const {
1811   SDNode *Users[4] = { };
1812   unsigned Lane = 0;
1813   unsigned OldDmask = Node->getConstantOperandVal(0);
1814   unsigned NewDmask = 0;
1815
1816   // Try to figure out the used register components
1817   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1818        I != E; ++I) {
1819
1820     // Abort if we can't understand the usage
1821     if (!I->isMachineOpcode() ||
1822         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1823       return;
1824
1825     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1826     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1827     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1828     // set, etc.
1829     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1830
1831     // Set which texture component corresponds to the lane.
1832     unsigned Comp;
1833     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1834       assert(Dmask);
1835       Comp = countTrailingZeros(Dmask);
1836       Dmask &= ~(1 << Comp);
1837     }
1838
1839     // Abort if we have more than one user per component
1840     if (Users[Lane])
1841       return;
1842
1843     Users[Lane] = *I;
1844     NewDmask |= 1 << Comp;
1845   }
1846
1847   // Abort if there's no change
1848   if (NewDmask == OldDmask)
1849     return;
1850
1851   // Adjust the writemask in the node
1852   std::vector<SDValue> Ops;
1853   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1854   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1855     Ops.push_back(Node->getOperand(i));
1856   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1857
1858   // If we only got one lane, replace it with a copy
1859   // (if NewDmask has only one bit set...)
1860   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1861     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1862     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1863                                       SDLoc(), Users[Lane]->getValueType(0),
1864                                       SDValue(Node, 0), RC);
1865     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1866     return;
1867   }
1868
1869   // Update the users of the node with the new indices
1870   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1871
1872     SDNode *User = Users[i];
1873     if (!User)
1874       continue;
1875
1876     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1877     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1878
1879     switch (Idx) {
1880     default: break;
1881     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1882     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1883     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1884     }
1885   }
1886 }
1887
1888 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1889 /// with frame index operands.
1890 /// LLVM assumes that inputs are to these instructions are registers.
1891 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1892                                                      SelectionDAG &DAG) const {
1893
1894   SmallVector<SDValue, 8> Ops;
1895   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1896     if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1897       Ops.push_back(Node->getOperand(i));
1898       continue;
1899     }
1900
1901     SDLoc DL(Node);
1902     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1903                                      Node->getOperand(i).getValueType(),
1904                                      Node->getOperand(i)), 0));
1905   }
1906
1907   DAG.UpdateNodeOperands(Node, Ops);
1908 }
1909
1910 /// \brief Fold the instructions after selecting them.
1911 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1912                                           SelectionDAG &DAG) const {
1913   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1914       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1915   Node = AdjustRegClass(Node, DAG);
1916
1917   if (TII->isMIMG(Node->getMachineOpcode()))
1918     adjustWritemask(Node, DAG);
1919
1920   if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1921       Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1922     legalizeTargetIndependentNode(Node, DAG);
1923     return Node;
1924   }
1925
1926   return legalizeOperands(Node, DAG);
1927 }
1928
1929 /// \brief Assign the register class depending on the number of
1930 /// bits set in the writemask
1931 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1932                                                      SDNode *Node) const {
1933   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1934       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1935
1936   TII->legalizeOperands(MI);
1937
1938   if (TII->isMIMG(MI->getOpcode())) {
1939     unsigned VReg = MI->getOperand(0).getReg();
1940     unsigned Writemask = MI->getOperand(1).getImm();
1941     unsigned BitsSet = 0;
1942     for (unsigned i = 0; i < 4; ++i)
1943       BitsSet += Writemask & (1 << i) ? 1 : 0;
1944
1945     const TargetRegisterClass *RC;
1946     switch (BitsSet) {
1947     default: return;
1948     case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1949     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1950     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1951     }
1952
1953     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1954     MI->setDesc(TII->get(NewOpcode));
1955     MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1956     MRI.setRegClass(VReg, RC);
1957     return;
1958   }
1959
1960   // Replace unused atomics with the no return version.
1961   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1962   if (NoRetAtomicOp != -1) {
1963     if (!Node->hasAnyUseOfValue(0)) {
1964       MI->setDesc(TII->get(NoRetAtomicOp));
1965       MI->RemoveOperand(0);
1966     }
1967
1968     return;
1969   }
1970 }
1971
1972 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
1973   SDValue K = DAG.getTargetConstant(Val, MVT::i32);
1974   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
1975 }
1976
1977 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
1978                                                 SDLoc DL,
1979                                                 SDValue Ptr) const {
1980 #if 1
1981     // XXX - Workaround for moveToVALU not handling different register class
1982     // inserts for REG_SEQUENCE.
1983
1984     // Build the half of the subregister with the constants.
1985     const SDValue Ops0[] = {
1986       DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
1987       buildSMovImm32(DAG, DL, 0),
1988       DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
1989       buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
1990       DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
1991     };
1992
1993     SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1994                                                   MVT::v2i32, Ops0), 0);
1995
1996     // Combine the constants and the pointer.
1997     const SDValue Ops1[] = {
1998       DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
1999       Ptr,
2000       DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2001       SubRegHi,
2002       DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2003     };
2004
2005     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2006 #else
2007     const SDValue Ops[] = {
2008       DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2009       Ptr,
2010       DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2011       buildSMovImm32(DAG, DL, 0),
2012       DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2013       buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
2014       DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2015     };
2016
2017     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2018
2019 #endif
2020 }
2021
2022 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2023 ///        The TID (Thread ID) is multipled by the stride value (bits [61:48]
2024 ///        of the resource descriptor) to create an offset, which is added to the
2025 ///        resource ponter.
2026 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2027                                            SDLoc DL,
2028                                            SDValue Ptr,
2029                                            uint32_t RsrcDword1,
2030                                            uint64_t RsrcDword2And3) const {
2031   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2032   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2033   if (RsrcDword1) {
2034     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2035                                      DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2036   }
2037
2038   SDValue DataLo = buildSMovImm32(DAG, DL,
2039                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2040   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2041
2042   const SDValue Ops[] = {
2043     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2044     PtrLo,
2045     DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2046     PtrHi,
2047     DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2048     DataLo,
2049     DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2050     DataHi,
2051     DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2052   };
2053
2054   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2055 }
2056
2057 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2058                                                   SDLoc DL,
2059                                                   SDValue Ptr) const {
2060   uint64_t Rsrc = AMDGPU::RSRC_DATA_FORMAT | AMDGPU::RSRC_TID_ENABLE |
2061                   0xffffffff; // Size
2062
2063   return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2064 }
2065
2066 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2067                                                 SelectionDAG &DAG) const {
2068
2069   SDLoc DL(N);
2070   unsigned NewOpcode = N->getMachineOpcode();
2071
2072   switch (N->getMachineOpcode()) {
2073   default: return N;
2074   case AMDGPU::S_LOAD_DWORD_IMM:
2075     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2076     // Fall-through
2077   case AMDGPU::S_LOAD_DWORDX2_SGPR:
2078     if (NewOpcode == N->getMachineOpcode()) {
2079       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2080     }
2081     // Fall-through
2082   case AMDGPU::S_LOAD_DWORDX4_IMM:
2083   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2084     if (NewOpcode == N->getMachineOpcode()) {
2085       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2086     }
2087     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2088       return N;
2089     }
2090     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2091
2092     const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2093     SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2094     MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2095
2096     SmallVector<SDValue, 8> Ops;
2097     Ops.push_back(SDValue(RSrc, 0));
2098     Ops.push_back(N->getOperand(0));
2099     Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
2100
2101     // Copy remaining operands so we keep any chain and glue nodes that follow
2102     // the normal operands.
2103     for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2104       Ops.push_back(N->getOperand(I));
2105
2106     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2107   }
2108   }
2109 }
2110
2111 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2112                                                const TargetRegisterClass *RC,
2113                                                unsigned Reg, EVT VT) const {
2114   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2115
2116   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2117                             cast<RegisterSDNode>(VReg)->getReg(), VT);
2118 }