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