R600: Check if a sextload should be used for parameter loads.
[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 #include "SIISelLowering.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUSubtarget.h"
18 #include "AMDILIntrinsicInfo.h"
19 #include "SIInstrInfo.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "SIRegisterInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/IR/Function.h"
27
28 using namespace llvm;
29
30 SITargetLowering::SITargetLowering(TargetMachine &TM) :
31     AMDGPUTargetLowering(TM) {
32   addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
33   addRegisterClass(MVT::i64, &AMDGPU::VSrc_64RegClass);
34
35   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
36   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
37
38   addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
39   addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
40
41   addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
42   addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
43   addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
44
45   addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
46   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
47   addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
48
49   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
50   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
51
52   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
53   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
54
55   computeRegisterProperties();
56
57   // Condition Codes
58   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
59   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
60   setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
61   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
62   setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
63   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
64
65   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
66   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
67   setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
68   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
69   setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
70   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
71
72   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
73   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
74   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
75   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
76
77   setOperationAction(ISD::ADD, MVT::i32, Legal);
78   setOperationAction(ISD::ADDC, MVT::i32, Legal);
79   setOperationAction(ISD::ADDE, MVT::i32, Legal);
80
81   setOperationAction(ISD::BITCAST, MVT::i128, Legal);
82
83   // We need to custom lower vector stores from local memory
84   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
85   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
86   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
87   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
88
89   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
90   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
91
92   // We need to custom lower loads/stores from private memory
93   setOperationAction(ISD::LOAD, MVT::i32, Custom);
94   setOperationAction(ISD::LOAD, MVT::i64, Custom);
95   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
96   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
97   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
98
99   setOperationAction(ISD::STORE, MVT::i1, Custom);
100   setOperationAction(ISD::STORE, MVT::i32, Custom);
101   setOperationAction(ISD::STORE, MVT::i64, Custom);
102   setOperationAction(ISD::STORE, MVT::i128, Custom);
103   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
104   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
105
106   setOperationAction(ISD::SELECT, MVT::i64, Custom);
107   setOperationAction(ISD::SELECT, MVT::f64, Promote);
108   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
109
110   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
111   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
112
113   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
114
115   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
116   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
117
118   setOperationAction(ISD::ANY_EXTEND, MVT::i64, Custom);
119   setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
120   setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
121
122   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
123   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
124   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
125   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
126
127   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
128
129   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
130   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
131   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
132   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
133   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
134   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
135   setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
136   setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
137
138   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
139   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
140   setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
141   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
142   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
143   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
144   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
146   setTruncStoreAction(MVT::i128, MVT::i64, Expand);
147   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
148   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
149
150   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
151   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
152   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
153
154   // We only support LOAD/STORE and vector manipulation ops for vectors
155   // with > 4 elements.
156   MVT VecTypes[] = {
157     MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
158   };
159
160   const size_t NumVecTypes = array_lengthof(VecTypes);
161   for (unsigned Type = 0; Type < NumVecTypes; ++Type) {
162     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
163       switch(Op) {
164       case ISD::LOAD:
165       case ISD::STORE:
166       case ISD::BUILD_VECTOR:
167       case ISD::BITCAST:
168       case ISD::EXTRACT_VECTOR_ELT:
169       case ISD::INSERT_VECTOR_ELT:
170       case ISD::CONCAT_VECTORS:
171       case ISD::INSERT_SUBVECTOR:
172       case ISD::EXTRACT_SUBVECTOR:
173         break;
174       default:
175         setOperationAction(Op, VecTypes[Type], Expand);
176         break;
177       }
178     }
179   }
180
181   for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
182     MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
183     setOperationAction(ISD::FTRUNC, VT, Expand);
184     setOperationAction(ISD::FCEIL, VT, Expand);
185     setOperationAction(ISD::FFLOOR, VT, Expand);
186   }
187
188   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
189     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
190     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
191     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
192   }
193
194   setTargetDAGCombine(ISD::SELECT_CC);
195   setTargetDAGCombine(ISD::SETCC);
196
197   setSchedulingPreference(Sched::RegPressure);
198 }
199
200 //===----------------------------------------------------------------------===//
201 // TargetLowering queries
202 //===----------------------------------------------------------------------===//
203
204 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
205                                                      unsigned AddrSpace,
206                                                      bool *IsFast) const {
207   // XXX: This depends on the address space and also we may want to revist
208   // the alignment values we specify in the DataLayout.
209   if (!VT.isSimple() || VT == MVT::Other)
210     return false;
211   return VT.bitsGT(MVT::i32);
212 }
213
214 bool SITargetLowering::shouldSplitVectorType(EVT VT) const {
215   return VT.getScalarType().bitsLE(MVT::i16);
216 }
217
218 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
219                                                          Type *Ty) const {
220   const SIInstrInfo *TII =
221     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
222   return TII->isInlineConstant(Imm);
223 }
224
225 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
226                                          SDLoc DL, SDValue Chain,
227                                          unsigned Offset, bool Signed) const {
228   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
229   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
230                                             AMDGPUAS::CONSTANT_ADDRESS);
231   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
232                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
233   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
234                                              DAG.getConstant(Offset, MVT::i64));
235   return DAG.getExtLoad(Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
236                             MachinePointerInfo(UndefValue::get(PtrTy)), MemVT,
237                             false, false, MemVT.getSizeInBits() >> 3);
238
239 }
240
241 SDValue SITargetLowering::LowerFormalArguments(
242                                       SDValue Chain,
243                                       CallingConv::ID CallConv,
244                                       bool isVarArg,
245                                       const SmallVectorImpl<ISD::InputArg> &Ins,
246                                       SDLoc DL, SelectionDAG &DAG,
247                                       SmallVectorImpl<SDValue> &InVals) const {
248
249   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
250
251   MachineFunction &MF = DAG.getMachineFunction();
252   FunctionType *FType = MF.getFunction()->getFunctionType();
253   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
254
255   assert(CallConv == CallingConv::C);
256
257   SmallVector<ISD::InputArg, 16> Splits;
258   uint32_t Skipped = 0;
259
260   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
261     const ISD::InputArg &Arg = Ins[i];
262
263     // First check if it's a PS input addr
264     if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
265         !Arg.Flags.isByVal()) {
266
267       assert((PSInputNum <= 15) && "Too many PS inputs!");
268
269       if (!Arg.Used) {
270         // We can savely skip PS inputs
271         Skipped |= 1 << i;
272         ++PSInputNum;
273         continue;
274       }
275
276       Info->PSInputAddr |= 1 << PSInputNum++;
277     }
278
279     // Second split vertices into their elements
280     if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
281       ISD::InputArg NewArg = Arg;
282       NewArg.Flags.setSplit();
283       NewArg.VT = Arg.VT.getVectorElementType();
284
285       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
286       // three or five element vertex only needs three or five registers,
287       // NOT four or eigth.
288       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
289       unsigned NumElements = ParamType->getVectorNumElements();
290
291       for (unsigned j = 0; j != NumElements; ++j) {
292         Splits.push_back(NewArg);
293         NewArg.PartOffset += NewArg.VT.getStoreSize();
294       }
295
296     } else if (Info->ShaderType != ShaderType::COMPUTE) {
297       Splits.push_back(Arg);
298     }
299   }
300
301   SmallVector<CCValAssign, 16> ArgLocs;
302   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
303                  getTargetMachine(), ArgLocs, *DAG.getContext());
304
305   // At least one interpolation mode must be enabled or else the GPU will hang.
306   if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
307     Info->PSInputAddr |= 1;
308     CCInfo.AllocateReg(AMDGPU::VGPR0);
309     CCInfo.AllocateReg(AMDGPU::VGPR1);
310   }
311
312   // The pointer to the list of arguments is stored in SGPR0, SGPR1
313   if (Info->ShaderType == ShaderType::COMPUTE) {
314     CCInfo.AllocateReg(AMDGPU::SGPR0);
315     CCInfo.AllocateReg(AMDGPU::SGPR1);
316     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
317   }
318
319   if (Info->ShaderType == ShaderType::COMPUTE) {
320     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
321                             Splits);
322   }
323
324   AnalyzeFormalArguments(CCInfo, Splits);
325
326   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
327
328     const ISD::InputArg &Arg = Ins[i];
329     if (Skipped & (1 << i)) {
330       InVals.push_back(DAG.getUNDEF(Arg.VT));
331       continue;
332     }
333
334     CCValAssign &VA = ArgLocs[ArgIdx++];
335     EVT VT = VA.getLocVT();
336
337     if (VA.isMemLoc()) {
338       VT = Ins[i].VT;
339       EVT MemVT = Splits[i].VT;
340       // The first 36 bytes of the input buffer contains information about
341       // thread group and global sizes.
342       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, DAG.getRoot(),
343                                    36 + VA.getLocMemOffset(),
344                                    Ins[i].Flags.isSExt());
345       InVals.push_back(Arg);
346       continue;
347     }
348     assert(VA.isRegLoc() && "Parameter must be in a register!");
349
350     unsigned Reg = VA.getLocReg();
351
352     if (VT == MVT::i64) {
353       // For now assume it is a pointer
354       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
355                                      &AMDGPU::SReg_64RegClass);
356       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
357       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
358       continue;
359     }
360
361     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
362
363     Reg = MF.addLiveIn(Reg, RC);
364     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
365
366     if (Arg.VT.isVector()) {
367
368       // Build a vector from the registers
369       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
370       unsigned NumElements = ParamType->getVectorNumElements();
371
372       SmallVector<SDValue, 4> Regs;
373       Regs.push_back(Val);
374       for (unsigned j = 1; j != NumElements; ++j) {
375         Reg = ArgLocs[ArgIdx++].getLocReg();
376         Reg = MF.addLiveIn(Reg, RC);
377         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
378       }
379
380       // Fill up the missing vector elements
381       NumElements = Arg.VT.getVectorNumElements() - NumElements;
382       for (unsigned j = 0; j != NumElements; ++j)
383         Regs.push_back(DAG.getUNDEF(VT));
384
385       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
386                                    Regs.data(), Regs.size()));
387       continue;
388     }
389
390     InVals.push_back(Val);
391   }
392   return Chain;
393 }
394
395 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
396     MachineInstr * MI, MachineBasicBlock * BB) const {
397
398   MachineBasicBlock::iterator I = *MI;
399
400   switch (MI->getOpcode()) {
401   default:
402     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
403   case AMDGPU::BRANCH: return BB;
404   case AMDGPU::SI_ADDR64_RSRC: {
405     const SIInstrInfo *TII =
406       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
407     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
408     unsigned SuperReg = MI->getOperand(0).getReg();
409     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
410     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
411     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
412     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
413     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
414             .addOperand(MI->getOperand(1));
415     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
416             .addImm(0);
417     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
418             .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
419     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
420             .addReg(SubRegHiLo)
421             .addImm(AMDGPU::sub0)
422             .addReg(SubRegHiHi)
423             .addImm(AMDGPU::sub1);
424     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
425             .addReg(SubRegLo)
426             .addImm(AMDGPU::sub0_sub1)
427             .addReg(SubRegHi)
428             .addImm(AMDGPU::sub2_sub3);
429     MI->eraseFromParent();
430     break;
431   }
432   case AMDGPU::V_SUB_F64: {
433     const SIInstrInfo *TII =
434       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
435     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
436             MI->getOperand(0).getReg())
437             .addReg(MI->getOperand(1).getReg())
438             .addReg(MI->getOperand(2).getReg())
439             .addImm(0)  /* src2 */
440             .addImm(0)  /* ABS */
441             .addImm(0)  /* CLAMP */
442             .addImm(0)  /* OMOD */
443             .addImm(2); /* NEG */
444     MI->eraseFromParent();
445     break;
446   }
447   case AMDGPU::SI_RegisterStorePseudo: {
448     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
449     const SIInstrInfo *TII =
450       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
451     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
452     MachineInstrBuilder MIB =
453         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
454                 Reg);
455     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
456       MIB.addOperand(MI->getOperand(i));
457
458     MI->eraseFromParent();
459   }
460   }
461   return BB;
462 }
463
464 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
465   if (!VT.isVector()) {
466     return MVT::i1;
467   }
468   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
469 }
470
471 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
472   return MVT::i32;
473 }
474
475 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
476   VT = VT.getScalarType();
477
478   if (!VT.isSimple())
479     return false;
480
481   switch (VT.getSimpleVT().SimpleTy) {
482   case MVT::f32:
483     return false; /* There is V_MAD_F32 for f32 */
484   case MVT::f64:
485     return true;
486   default:
487     break;
488   }
489
490   return false;
491 }
492
493 //===----------------------------------------------------------------------===//
494 // Custom DAG Lowering Operations
495 //===----------------------------------------------------------------------===//
496
497 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
498   MachineFunction &MF = DAG.getMachineFunction();
499   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
500   switch (Op.getOpcode()) {
501   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
502   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
503   case ISD::LOAD: {
504     LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
505     if (Op.getValueType().isVector() &&
506         (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
507          Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
508          (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
509           Op.getValueType().getVectorNumElements() > 4))) {
510       SDValue MergedValues[2] = {
511         SplitVectorLoad(Op, DAG),
512         Load->getChain()
513       };
514       return DAG.getMergeValues(MergedValues, 2, SDLoc(Op));
515     } else {
516       return LowerLOAD(Op, DAG);
517     }
518   }
519
520   case ISD::SELECT: return LowerSELECT(Op, DAG);
521   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
522   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
523   case ISD::STORE: return LowerSTORE(Op, DAG);
524   case ISD::ANY_EXTEND: // Fall-through
525   case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
526   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
527   case ISD::INTRINSIC_WO_CHAIN: {
528     unsigned IntrinsicID =
529                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
530     EVT VT = Op.getValueType();
531     SDLoc DL(Op);
532     //XXX: Hardcoded we only use two to store the pointer to the parameters.
533     unsigned NumUserSGPRs = 2;
534     switch (IntrinsicID) {
535     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
536     case Intrinsic::r600_read_ngroups_x:
537       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
538     case Intrinsic::r600_read_ngroups_y:
539       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
540     case Intrinsic::r600_read_ngroups_z:
541       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
542     case Intrinsic::r600_read_global_size_x:
543       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
544     case Intrinsic::r600_read_global_size_y:
545       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
546     case Intrinsic::r600_read_global_size_z:
547       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
548     case Intrinsic::r600_read_local_size_x:
549       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
550     case Intrinsic::r600_read_local_size_y:
551       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
552     case Intrinsic::r600_read_local_size_z:
553       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
554     case Intrinsic::r600_read_tgid_x:
555       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
556                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
557     case Intrinsic::r600_read_tgid_y:
558       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
559                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
560     case Intrinsic::r600_read_tgid_z:
561       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
562                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
563     case Intrinsic::r600_read_tidig_x:
564       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
565                                   AMDGPU::VGPR0, VT);
566     case Intrinsic::r600_read_tidig_y:
567       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
568                                   AMDGPU::VGPR1, VT);
569     case Intrinsic::r600_read_tidig_z:
570       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
571                                   AMDGPU::VGPR2, VT);
572     case AMDGPUIntrinsic::SI_load_const: {
573       SDValue Ops [] = {
574         ResourceDescriptorToi128(Op.getOperand(1), DAG),
575         Op.getOperand(2)
576       };
577
578       MachineMemOperand *MMO = MF.getMachineMemOperand(
579           MachinePointerInfo(),
580           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
581           VT.getSizeInBits() / 8, 4);
582       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
583                                      Op->getVTList(), Ops, 2, VT, MMO);
584     }
585     case AMDGPUIntrinsic::SI_sample:
586       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
587     case AMDGPUIntrinsic::SI_sampleb:
588       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
589     case AMDGPUIntrinsic::SI_sampled:
590       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
591     case AMDGPUIntrinsic::SI_samplel:
592       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
593     case AMDGPUIntrinsic::SI_vs_load_input:
594       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
595                          ResourceDescriptorToi128(Op.getOperand(1), DAG),
596                          Op.getOperand(2),
597                          Op.getOperand(3));
598     }
599   }
600
601   case ISD::INTRINSIC_VOID:
602     SDValue Chain = Op.getOperand(0);
603     unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
604
605     switch (IntrinsicID) {
606       case AMDGPUIntrinsic::SI_tbuffer_store: {
607         SDLoc DL(Op);
608         SDValue Ops [] = {
609           Chain,
610           ResourceDescriptorToi128(Op.getOperand(2), DAG),
611           Op.getOperand(3),
612           Op.getOperand(4),
613           Op.getOperand(5),
614           Op.getOperand(6),
615           Op.getOperand(7),
616           Op.getOperand(8),
617           Op.getOperand(9),
618           Op.getOperand(10),
619           Op.getOperand(11),
620           Op.getOperand(12),
621           Op.getOperand(13),
622           Op.getOperand(14)
623         };
624         EVT VT = Op.getOperand(3).getValueType();
625
626         MachineMemOperand *MMO = MF.getMachineMemOperand(
627             MachinePointerInfo(),
628             MachineMemOperand::MOStore,
629             VT.getSizeInBits() / 8, 4);
630         return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
631                                        Op->getVTList(), Ops,
632                                        sizeof(Ops)/sizeof(Ops[0]), VT, MMO);
633       }
634       default:
635         break;
636     }
637   }
638   return SDValue();
639 }
640
641 /// \brief Helper function for LowerBRCOND
642 static SDNode *findUser(SDValue Value, unsigned Opcode) {
643
644   SDNode *Parent = Value.getNode();
645   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
646        I != E; ++I) {
647
648     if (I.getUse().get() != Value)
649       continue;
650
651     if (I->getOpcode() == Opcode)
652       return *I;
653   }
654   return 0;
655 }
656
657 /// This transforms the control flow intrinsics to get the branch destination as
658 /// last parameter, also switches branch target with BR if the need arise
659 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
660                                       SelectionDAG &DAG) const {
661
662   SDLoc DL(BRCOND);
663
664   SDNode *Intr = BRCOND.getOperand(1).getNode();
665   SDValue Target = BRCOND.getOperand(2);
666   SDNode *BR = 0;
667
668   if (Intr->getOpcode() == ISD::SETCC) {
669     // As long as we negate the condition everything is fine
670     SDNode *SetCC = Intr;
671     assert(SetCC->getConstantOperandVal(1) == 1);
672     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
673            ISD::SETNE);
674     Intr = SetCC->getOperand(0).getNode();
675
676   } else {
677     // Get the target from BR if we don't negate the condition
678     BR = findUser(BRCOND, ISD::BR);
679     Target = BR->getOperand(1);
680   }
681
682   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
683
684   // Build the result and
685   SmallVector<EVT, 4> Res;
686   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
687     Res.push_back(Intr->getValueType(i));
688
689   // operands of the new intrinsic call
690   SmallVector<SDValue, 4> Ops;
691   Ops.push_back(BRCOND.getOperand(0));
692   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
693     Ops.push_back(Intr->getOperand(i));
694   Ops.push_back(Target);
695
696   // build the new intrinsic call
697   SDNode *Result = DAG.getNode(
698     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
699     DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
700
701   if (BR) {
702     // Give the branch instruction our target
703     SDValue Ops[] = {
704       BR->getOperand(0),
705       BRCOND.getOperand(2)
706     };
707     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
708   }
709
710   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
711
712   // Copy the intrinsic results to registers
713   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
714     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
715     if (!CopyToReg)
716       continue;
717
718     Chain = DAG.getCopyToReg(
719       Chain, DL,
720       CopyToReg->getOperand(1),
721       SDValue(Result, i - 1),
722       SDValue());
723
724     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
725   }
726
727   // Remove the old intrinsic from the chain
728   DAG.ReplaceAllUsesOfValueWith(
729     SDValue(Intr, Intr->getNumValues() - 1),
730     Intr->getOperand(0));
731
732   return Chain;
733 }
734
735 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
736   SDLoc DL(Op);
737   LoadSDNode *Load = cast<LoadSDNode>(Op);
738   SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
739   SDValue MergedValues[2];
740   MergedValues[1] = Load->getChain();
741   if (Ret.getNode()) {
742     MergedValues[0] = Ret;
743     return DAG.getMergeValues(MergedValues, 2, DL);
744   }
745
746   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
747     return SDValue();
748   }
749
750   EVT MemVT = Load->getMemoryVT();
751
752   assert(!MemVT.isVector() && "Private loads should be scalarized");
753   assert(!MemVT.isFloatingPoint() && "FP loads should be promoted to int");
754
755   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
756                             DAG.getConstant(2, MVT::i32));
757   Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
758                     Load->getChain(), Ptr,
759                     DAG.getTargetConstant(0, MVT::i32),
760                     Op.getOperand(2));
761   if (MemVT.getSizeInBits() == 64) {
762     SDValue IncPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
763                                  DAG.getConstant(1, MVT::i32));
764
765     SDValue LoadUpper = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
766                                     Load->getChain(), IncPtr,
767                                     DAG.getTargetConstant(0, MVT::i32),
768                                     Op.getOperand(2));
769
770     Ret = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ret, LoadUpper);
771   }
772
773   MergedValues[0] = Ret;
774   return DAG.getMergeValues(MergedValues, 2, DL);
775
776 }
777
778 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
779                                              SelectionDAG &DAG) const {
780
781   if (Op.getValueType() == MVT::i128) {
782     return Op;
783   }
784
785   assert(Op.getOpcode() == ISD::UNDEF);
786
787   return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
788                      DAG.getConstant(0, MVT::i64),
789                      DAG.getConstant(0, MVT::i64));
790 }
791
792 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
793                                                const SDValue &Op,
794                                                SelectionDAG &DAG) const {
795   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
796                      Op.getOperand(2),
797                      ResourceDescriptorToi128(Op.getOperand(3), DAG),
798                      Op.getOperand(4));
799 }
800
801 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
802   if (Op.getValueType() != MVT::i64)
803     return SDValue();
804
805   SDLoc DL(Op);
806   SDValue Cond = Op.getOperand(0);
807
808   SDValue Zero = DAG.getConstant(0, MVT::i32);
809   SDValue One = DAG.getConstant(1, MVT::i32);
810
811   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
812   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
813
814   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
815   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
816
817   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
818
819   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
820   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
821
822   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
823
824   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
825   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
826 }
827
828 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
829   SDValue LHS = Op.getOperand(0);
830   SDValue RHS = Op.getOperand(1);
831   SDValue True = Op.getOperand(2);
832   SDValue False = Op.getOperand(3);
833   SDValue CC = Op.getOperand(4);
834   EVT VT = Op.getValueType();
835   SDLoc DL(Op);
836
837   // Possible Min/Max pattern
838   SDValue MinMax = LowerMinMax(Op, DAG);
839   if (MinMax.getNode()) {
840     return MinMax;
841   }
842
843   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
844   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
845 }
846
847 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
848                                            SelectionDAG &DAG) const {
849   EVT VT = Op.getValueType();
850   SDLoc DL(Op);
851
852   if (VT != MVT::i64) {
853     return SDValue();
854   }
855
856   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
857                                                  DAG.getConstant(31, MVT::i32));
858
859   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
860 }
861
862 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
863   SDLoc DL(Op);
864   StoreSDNode *Store = cast<StoreSDNode>(Op);
865   EVT VT = Store->getMemoryVT();
866
867   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
868   if (Ret.getNode())
869     return Ret;
870
871   if (VT.isVector() && VT.getVectorNumElements() >= 8)
872       return SplitVectorStore(Op, DAG);
873
874   if (VT == MVT::i1)
875     return DAG.getTruncStore(Store->getChain(), DL,
876                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
877                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
878
879   if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
880     return SDValue();
881
882   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
883                             DAG.getConstant(2, MVT::i32));
884   SDValue Chain = Store->getChain();
885   SmallVector<SDValue, 8> Values;
886
887   if (Store->isTruncatingStore()) {
888     unsigned Mask = 0;
889     if (Store->getMemoryVT() == MVT::i8) {
890       Mask = 0xff;
891     } else if (Store->getMemoryVT() == MVT::i16) {
892       Mask = 0xffff;
893     }
894     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
895                               Chain, Store->getBasePtr(),
896                               DAG.getConstant(0, MVT::i32));
897     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
898                                   DAG.getConstant(0x3, MVT::i32));
899     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
900                                    DAG.getConstant(3, MVT::i32));
901     SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
902                                       DAG.getConstant(Mask, MVT::i32));
903     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
904                                        MaskedValue, ShiftAmt);
905     SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
906                                   DAG.getConstant(32, MVT::i32), ShiftAmt);
907     SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
908                                   DAG.getConstant(Mask, MVT::i32),
909                                   RotrAmt);
910     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
911     Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
912
913     Values.push_back(Dst);
914   } else if (VT == MVT::i64) {
915     for (unsigned i = 0; i < 2; ++i) {
916       Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
917                        Store->getValue(), DAG.getConstant(i, MVT::i32)));
918     }
919   } else if (VT == MVT::i128) {
920     for (unsigned i = 0; i < 2; ++i) {
921       for (unsigned j = 0; j < 2; ++j) {
922         Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
923                            DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
924                            Store->getValue(), DAG.getConstant(i, MVT::i32)),
925                          DAG.getConstant(j, MVT::i32)));
926       }
927     }
928   } else {
929     Values.push_back(Store->getValue());
930   }
931
932   for (unsigned i = 0; i < Values.size(); ++i) {
933     SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
934                                   Ptr, DAG.getConstant(i, MVT::i32));
935     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
936                         Chain, Values[i], PartPtr,
937                         DAG.getTargetConstant(0, MVT::i32));
938   }
939   return Chain;
940 }
941
942
943 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
944                                            SelectionDAG &DAG) const {
945   EVT VT = Op.getValueType();
946   SDLoc DL(Op);
947
948   if (VT != MVT::i64) {
949     return SDValue();
950   }
951
952   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
953                                               DAG.getConstant(0, MVT::i32));
954 }
955
956 //===----------------------------------------------------------------------===//
957 // Custom DAG optimizations
958 //===----------------------------------------------------------------------===//
959
960 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
961                                             DAGCombinerInfo &DCI) const {
962   SelectionDAG &DAG = DCI.DAG;
963   SDLoc DL(N);
964   EVT VT = N->getValueType(0);
965
966   switch (N->getOpcode()) {
967     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
968     case ISD::SELECT_CC: {
969       ConstantSDNode *True, *False;
970       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
971       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
972           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
973           && True->isAllOnesValue()
974           && False->isNullValue()
975           && VT == MVT::i1) {
976         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
977                            N->getOperand(1), N->getOperand(4));
978
979       }
980       break;
981     }
982     case ISD::SETCC: {
983       SDValue Arg0 = N->getOperand(0);
984       SDValue Arg1 = N->getOperand(1);
985       SDValue CC = N->getOperand(2);
986       ConstantSDNode * C = NULL;
987       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
988
989       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
990       if (VT == MVT::i1
991           && Arg0.getOpcode() == ISD::SIGN_EXTEND
992           && Arg0.getOperand(0).getValueType() == MVT::i1
993           && (C = dyn_cast<ConstantSDNode>(Arg1))
994           && C->isNullValue()
995           && CCOp == ISD::SETNE) {
996         return SimplifySetCC(VT, Arg0.getOperand(0),
997                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
998       }
999       break;
1000     }
1001   }
1002   return SDValue();
1003 }
1004
1005 /// \brief Test if RegClass is one of the VSrc classes
1006 static bool isVSrc(unsigned RegClass) {
1007   return AMDGPU::VSrc_32RegClassID == RegClass ||
1008          AMDGPU::VSrc_64RegClassID == RegClass;
1009 }
1010
1011 /// \brief Test if RegClass is one of the SSrc classes
1012 static bool isSSrc(unsigned RegClass) {
1013   return AMDGPU::SSrc_32RegClassID == RegClass ||
1014          AMDGPU::SSrc_64RegClassID == RegClass;
1015 }
1016
1017 /// \brief Analyze the possible immediate value Op
1018 ///
1019 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1020 /// and the immediate value if it's a literal immediate
1021 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1022
1023   union {
1024     int32_t I;
1025     float F;
1026   } Imm;
1027
1028   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1029     if (Node->getZExtValue() >> 32) {
1030         return -1;
1031     }
1032     Imm.I = Node->getSExtValue();
1033   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1034     if (N->getValueType(0) != MVT::f32)
1035       return -1;
1036     Imm.F = Node->getValueAPF().convertToFloat();
1037   } else
1038     return -1; // It isn't an immediate
1039
1040   if ((Imm.I >= -16 && Imm.I <= 64) ||
1041       Imm.F == 0.5f || Imm.F == -0.5f ||
1042       Imm.F == 1.0f || Imm.F == -1.0f ||
1043       Imm.F == 2.0f || Imm.F == -2.0f ||
1044       Imm.F == 4.0f || Imm.F == -4.0f)
1045     return 0; // It's an inline immediate
1046
1047   return Imm.I; // It's a literal immediate
1048 }
1049
1050 /// \brief Try to fold an immediate directly into an instruction
1051 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1052                                bool &ScalarSlotUsed) const {
1053
1054   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1055   const SIInstrInfo *TII =
1056     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1057   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
1058     return false;
1059
1060   const SDValue &Op = Mov->getOperand(0);
1061   int32_t Value = analyzeImmediate(Op.getNode());
1062   if (Value == -1) {
1063     // Not an immediate at all
1064     return false;
1065
1066   } else if (Value == 0) {
1067     // Inline immediates can always be fold
1068     Operand = Op;
1069     return true;
1070
1071   } else if (Value == Immediate) {
1072     // Already fold literal immediate
1073     Operand = Op;
1074     return true;
1075
1076   } else if (!ScalarSlotUsed && !Immediate) {
1077     // Fold this literal immediate
1078     ScalarSlotUsed = true;
1079     Immediate = Value;
1080     Operand = Op;
1081     return true;
1082
1083   }
1084
1085   return false;
1086 }
1087
1088 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1089                                    SelectionDAG &DAG, const SDValue &Op) const {
1090   const SIInstrInfo *TII =
1091     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1092   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1093
1094   if (!Op->isMachineOpcode()) {
1095     switch(Op->getOpcode()) {
1096     case ISD::CopyFromReg: {
1097       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1098       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1099       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1100         return MRI.getRegClass(Reg);
1101       }
1102       return TRI.getPhysRegClass(Reg);
1103     }
1104     default:  return NULL;
1105     }
1106   }
1107   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1108   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1109   if (OpClassID != -1) {
1110     return TRI.getRegClass(OpClassID);
1111   }
1112   switch(Op.getMachineOpcode()) {
1113   case AMDGPU::COPY_TO_REGCLASS:
1114     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1115     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1116
1117     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1118     // class, then the register class for the value could be either a
1119     // VReg or and SReg.  In order to get a more accurate
1120     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1121         OpClassID == AMDGPU::VSrc_64RegClassID) {
1122       return getRegClassForNode(DAG, Op.getOperand(0));
1123     }
1124     return TRI.getRegClass(OpClassID);
1125   case AMDGPU::EXTRACT_SUBREG: {
1126     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1127     const TargetRegisterClass *SuperClass =
1128       getRegClassForNode(DAG, Op.getOperand(0));
1129     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1130   }
1131   case AMDGPU::REG_SEQUENCE:
1132     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1133     return TRI.getRegClass(
1134       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1135   default:
1136     return getRegClassFor(Op.getSimpleValueType());
1137   }
1138 }
1139
1140 /// \brief Does "Op" fit into register class "RegClass" ?
1141 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1142                                     unsigned RegClass) const {
1143   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1144   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1145   if (!RC) {
1146     return false;
1147   }
1148   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1149 }
1150
1151 /// \brief Make sure that we don't exeed the number of allowed scalars
1152 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1153                                        unsigned RegClass,
1154                                        bool &ScalarSlotUsed) const {
1155
1156   // First map the operands register class to a destination class
1157   if (RegClass == AMDGPU::VSrc_32RegClassID)
1158     RegClass = AMDGPU::VReg_32RegClassID;
1159   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1160     RegClass = AMDGPU::VReg_64RegClassID;
1161   else
1162     return;
1163
1164   // Nothing to do if they fit naturally
1165   if (fitsRegClass(DAG, Operand, RegClass))
1166     return;
1167
1168   // If the scalar slot isn't used yet use it now
1169   if (!ScalarSlotUsed) {
1170     ScalarSlotUsed = true;
1171     return;
1172   }
1173
1174   // This is a conservative aproach. It is possible that we can't determine the
1175   // correct register class and copy too often, but better safe than sorry.
1176   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1177   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1178                                     Operand.getValueType(), Operand, RC);
1179   Operand = SDValue(Node, 0);
1180 }
1181
1182 /// \returns true if \p Node's operands are different from the SDValue list
1183 /// \p Ops
1184 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1185   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1186     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1187       return true;
1188     }
1189   }
1190   return false;
1191 }
1192
1193 /// \brief Try to fold the Nodes operands into the Node
1194 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1195                                        SelectionDAG &DAG) const {
1196
1197   // Original encoding (either e32 or e64)
1198   int Opcode = Node->getMachineOpcode();
1199   const SIInstrInfo *TII =
1200     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1201   const MCInstrDesc *Desc = &TII->get(Opcode);
1202
1203   unsigned NumDefs = Desc->getNumDefs();
1204   unsigned NumOps = Desc->getNumOperands();
1205
1206   // Commuted opcode if available
1207   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1208   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
1209
1210   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1211   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1212
1213   // e64 version if available, -1 otherwise
1214   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1215   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
1216
1217   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1218   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
1219
1220   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1221   bool HaveVSrc = false, HaveSSrc = false;
1222
1223   // First figure out what we alread have in this instruction
1224   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1225        i != e && Op < NumOps; ++i, ++Op) {
1226
1227     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1228     if (isVSrc(RegClass))
1229       HaveVSrc = true;
1230     else if (isSSrc(RegClass))
1231       HaveSSrc = true;
1232     else
1233       continue;
1234
1235     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1236     if (Imm != -1 && Imm != 0) {
1237       // Literal immediate
1238       Immediate = Imm;
1239     }
1240   }
1241
1242   // If we neither have VSrc nor SSrc it makes no sense to continue
1243   if (!HaveVSrc && !HaveSSrc)
1244     return Node;
1245
1246   // No scalar allowed when we have both VSrc and SSrc
1247   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1248
1249   // Second go over the operands and try to fold them
1250   std::vector<SDValue> Ops;
1251   bool Promote2e64 = false;
1252   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1253        i != e && Op < NumOps; ++i, ++Op) {
1254
1255     const SDValue &Operand = Node->getOperand(i);
1256     Ops.push_back(Operand);
1257
1258     // Already folded immediate ?
1259     if (isa<ConstantSDNode>(Operand.getNode()) ||
1260         isa<ConstantFPSDNode>(Operand.getNode()))
1261       continue;
1262
1263     // Is this a VSrc or SSrc operand ?
1264     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1265     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1266       // Try to fold the immediates
1267       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1268         // Folding didn't worked, make sure we don't hit the SReg limit
1269         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1270       }
1271       continue;
1272     }
1273
1274     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1275
1276       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1277       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1278
1279       // Test if it makes sense to swap operands
1280       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1281           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1282            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1283
1284         // Swap commutable operands
1285         std::swap(Ops[0], Ops[1]);
1286
1287         Desc = DescRev;
1288         DescRev = 0;
1289         continue;
1290       }
1291     }
1292
1293     if (DescE64 && !Immediate) {
1294
1295       // Test if it makes sense to switch to e64 encoding
1296       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1297       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1298         continue;
1299
1300       int32_t TmpImm = -1;
1301       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1302           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1303            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1304
1305         // Switch to e64 encoding
1306         Immediate = -1;
1307         Promote2e64 = true;
1308         Desc = DescE64;
1309         DescE64 = 0;
1310       }
1311     }
1312   }
1313
1314   if (Promote2e64) {
1315     // Add the modifier flags while promoting
1316     for (unsigned i = 0; i < 4; ++i)
1317       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1318   }
1319
1320   // Add optional chain and glue
1321   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1322     Ops.push_back(Node->getOperand(i));
1323
1324   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1325   // this case a brand new node is always be created, even if the operands
1326   // are the same as before.  So, manually check if anything has been changed.
1327   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1328     return Node;
1329   }
1330
1331   // Create a complete new instruction
1332   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1333 }
1334
1335 /// \brief Helper function for adjustWritemask
1336 static unsigned SubIdx2Lane(unsigned Idx) {
1337   switch (Idx) {
1338   default: return 0;
1339   case AMDGPU::sub0: return 0;
1340   case AMDGPU::sub1: return 1;
1341   case AMDGPU::sub2: return 2;
1342   case AMDGPU::sub3: return 3;
1343   }
1344 }
1345
1346 /// \brief Adjust the writemask of MIMG instructions
1347 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1348                                        SelectionDAG &DAG) const {
1349   SDNode *Users[4] = { };
1350   unsigned Lane = 0;
1351   unsigned OldDmask = Node->getConstantOperandVal(0);
1352   unsigned NewDmask = 0;
1353
1354   // Try to figure out the used register components
1355   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1356        I != E; ++I) {
1357
1358     // Abort if we can't understand the usage
1359     if (!I->isMachineOpcode() ||
1360         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1361       return;
1362
1363     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1364     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1365     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1366     // set, etc.
1367     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1368
1369     // Set which texture component corresponds to the lane.
1370     unsigned Comp;
1371     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1372       assert(Dmask);
1373       Comp = countTrailingZeros(Dmask);
1374       Dmask &= ~(1 << Comp);
1375     }
1376
1377     // Abort if we have more than one user per component
1378     if (Users[Lane])
1379       return;
1380
1381     Users[Lane] = *I;
1382     NewDmask |= 1 << Comp;
1383   }
1384
1385   // Abort if there's no change
1386   if (NewDmask == OldDmask)
1387     return;
1388
1389   // Adjust the writemask in the node
1390   std::vector<SDValue> Ops;
1391   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1392   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1393     Ops.push_back(Node->getOperand(i));
1394   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1395
1396   // If we only got one lane, replace it with a copy
1397   // (if NewDmask has only one bit set...)
1398   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1399     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1400     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1401                                       SDLoc(), Users[Lane]->getValueType(0),
1402                                       SDValue(Node, 0), RC);
1403     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1404     return;
1405   }
1406
1407   // Update the users of the node with the new indices
1408   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1409
1410     SDNode *User = Users[i];
1411     if (!User)
1412       continue;
1413
1414     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1415     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1416
1417     switch (Idx) {
1418     default: break;
1419     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1420     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1421     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1422     }
1423   }
1424 }
1425
1426 /// \brief Fold the instructions after slecting them
1427 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1428                                           SelectionDAG &DAG) const {
1429   const SIInstrInfo *TII =
1430       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1431   Node = AdjustRegClass(Node, DAG);
1432
1433   if (TII->isMIMG(Node->getMachineOpcode()))
1434     adjustWritemask(Node, DAG);
1435
1436   return foldOperands(Node, DAG);
1437 }
1438
1439 /// \brief Assign the register class depending on the number of
1440 /// bits set in the writemask
1441 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1442                                                      SDNode *Node) const {
1443   const SIInstrInfo *TII =
1444       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1445   if (!TII->isMIMG(MI->getOpcode()))
1446     return;
1447
1448   unsigned VReg = MI->getOperand(0).getReg();
1449   unsigned Writemask = MI->getOperand(1).getImm();
1450   unsigned BitsSet = 0;
1451   for (unsigned i = 0; i < 4; ++i)
1452     BitsSet += Writemask & (1 << i) ? 1 : 0;
1453
1454   const TargetRegisterClass *RC;
1455   switch (BitsSet) {
1456   default: return;
1457   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1458   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1459   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1460   }
1461
1462   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1463   MI->setDesc(TII->get(NewOpcode));
1464   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1465   MRI.setRegClass(VReg, RC);
1466 }
1467
1468 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1469                                                 SelectionDAG &DAG) const {
1470
1471   SDLoc DL(N);
1472   unsigned NewOpcode = N->getMachineOpcode();
1473
1474   switch (N->getMachineOpcode()) {
1475   default: return N;
1476   case AMDGPU::S_LOAD_DWORD_IMM:
1477     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1478     // Fall-through
1479   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1480     if (NewOpcode == N->getMachineOpcode()) {
1481       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1482     }
1483     // Fall-through
1484   case AMDGPU::S_LOAD_DWORDX4_IMM:
1485   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1486     if (NewOpcode == N->getMachineOpcode()) {
1487       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1488     }
1489     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1490       return N;
1491     }
1492     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1493     SDValue Ops[] = {
1494       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1495                                  DAG.getConstant(0, MVT::i64)), 0),
1496       N->getOperand(0),
1497       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1498     };
1499     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1500   }
1501   }
1502 }
1503
1504 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1505                                                const TargetRegisterClass *RC,
1506                                                unsigned Reg, EVT VT) const {
1507   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1508
1509   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1510                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1511 }