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