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