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