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