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