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