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