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