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