R600/SI: Use VALU instructions for copying i1 values
[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::VSrc_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::VSrc_32RegClass);
40
41   addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
42   addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
43   addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
44
45   addRegisterClass(MVT::v4i32, &AMDGPU::VSrc_128RegClass);
46   addRegisterClass(MVT::v4f32, &AMDGPU::VSrc_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 /// Usually ISel will insert a copy between terminator insturction that output
448 /// a value and the S_BRANCH* at the end of the block.  This causes
449 /// MachineBasicBlock::getFirstTerminator() to return the incorrect value,
450 /// so we want to make sure there are no copies between terminators at the
451 /// end of blocks.
452 static void LowerTerminatorWithOutput(unsigned Opcode, MachineBasicBlock *BB,
453                                       MachineInstr *MI,
454                                       const TargetInstrInfo *TII,
455                                       MachineRegisterInfo &MRI) {
456   unsigned DstReg = MI->getOperand(0).getReg();
457   // Usually ISel will insert a copy between the SI_IF_NON_TERM instruction
458   // and the S_BRANCH* terminator.  We want to replace SI_IF_NO_TERM with
459   // SI_IF and we can't have any instructions between S_BRANCH* and SI_IF,
460   // since they are both terminators
461   assert(MRI.hasOneUse(DstReg));
462   MachineOperand &Use = *MRI.use_begin(DstReg);
463   MachineInstr *UseMI = Use.getParent();
464   assert(UseMI->getOpcode() == AMDGPU::COPY);
465
466   MRI.replaceRegWith(UseMI->getOperand(0).getReg(), DstReg);
467   UseMI->eraseFromParent();
468   BuildMI(*BB, BB->getFirstTerminator(), MI->getDebugLoc(),
469           TII->get(Opcode))
470           .addOperand(MI->getOperand(0))
471           .addOperand(MI->getOperand(1))
472           .addOperand(MI->getOperand(2));
473   MI->eraseFromParent();
474 }
475
476 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
477     MachineInstr * MI, MachineBasicBlock * BB) const {
478
479   MachineBasicBlock::iterator I = *MI;
480   const SIInstrInfo *TII =
481     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
482   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
483
484   switch (MI->getOpcode()) {
485   default:
486     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
487   case AMDGPU::BRANCH: return BB;
488   case AMDGPU::SI_ADDR64_RSRC: {
489     unsigned SuperReg = MI->getOperand(0).getReg();
490     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
491     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
492     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
493     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
494     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
495             .addOperand(MI->getOperand(1));
496     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
497             .addImm(0);
498     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
499             .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
500     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
501             .addReg(SubRegHiLo)
502             .addImm(AMDGPU::sub0)
503             .addReg(SubRegHiHi)
504             .addImm(AMDGPU::sub1);
505     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
506             .addReg(SubRegLo)
507             .addImm(AMDGPU::sub0_sub1)
508             .addReg(SubRegHi)
509             .addImm(AMDGPU::sub2_sub3);
510     MI->eraseFromParent();
511     break;
512   }
513   case AMDGPU::SI_IF_NON_TERM:
514     LowerTerminatorWithOutput(AMDGPU::SI_IF, BB, MI, TII, MRI);
515     break;
516   case AMDGPU::SI_ELSE_NON_TERM:
517     LowerTerminatorWithOutput(AMDGPU::SI_ELSE, BB, MI, TII, MRI);
518     break;
519   case AMDGPU::V_SUB_F64:
520     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
521             MI->getOperand(0).getReg())
522             .addReg(MI->getOperand(1).getReg())
523             .addReg(MI->getOperand(2).getReg())
524             .addImm(0)  /* src2 */
525             .addImm(0)  /* ABS */
526             .addImm(0)  /* CLAMP */
527             .addImm(0)  /* OMOD */
528             .addImm(2); /* NEG */
529     MI->eraseFromParent();
530     break;
531
532   case AMDGPU::SI_RegisterStorePseudo: {
533     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
534     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
535     MachineInstrBuilder MIB =
536         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
537                 Reg);
538     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
539       MIB.addOperand(MI->getOperand(i));
540
541     MI->eraseFromParent();
542   }
543   }
544   return BB;
545 }
546
547 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
548   if (!VT.isVector()) {
549     return MVT::i1;
550   }
551   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
552 }
553
554 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
555   return MVT::i32;
556 }
557
558 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
559   VT = VT.getScalarType();
560
561   if (!VT.isSimple())
562     return false;
563
564   switch (VT.getSimpleVT().SimpleTy) {
565   case MVT::f32:
566     return false; /* There is V_MAD_F32 for f32 */
567   case MVT::f64:
568     return true;
569   default:
570     break;
571   }
572
573   return false;
574 }
575
576 //===----------------------------------------------------------------------===//
577 // Custom DAG Lowering Operations
578 //===----------------------------------------------------------------------===//
579
580 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
581   MachineFunction &MF = DAG.getMachineFunction();
582   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
583   switch (Op.getOpcode()) {
584   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
585   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
586   case ISD::LOAD: {
587     LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
588     if (Op.getValueType().isVector() &&
589         (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
590          Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
591          (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
592           Op.getValueType().getVectorNumElements() > 4))) {
593       SDValue MergedValues[2] = {
594         SplitVectorLoad(Op, DAG),
595         Load->getChain()
596       };
597       return DAG.getMergeValues(MergedValues, SDLoc(Op));
598     } else {
599       return LowerLOAD(Op, DAG);
600     }
601   }
602
603   case ISD::SELECT: return LowerSELECT(Op, DAG);
604   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
605   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
606   case ISD::STORE: return LowerSTORE(Op, DAG);
607   case ISD::ANY_EXTEND: // Fall-through
608   case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
609   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
610   case ISD::INTRINSIC_WO_CHAIN: {
611     unsigned IntrinsicID =
612                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
613     EVT VT = Op.getValueType();
614     SDLoc DL(Op);
615     //XXX: Hardcoded we only use two to store the pointer to the parameters.
616     unsigned NumUserSGPRs = 2;
617     switch (IntrinsicID) {
618     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
619     case Intrinsic::r600_read_ngroups_x:
620       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
621     case Intrinsic::r600_read_ngroups_y:
622       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
623     case Intrinsic::r600_read_ngroups_z:
624       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
625     case Intrinsic::r600_read_global_size_x:
626       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
627     case Intrinsic::r600_read_global_size_y:
628       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
629     case Intrinsic::r600_read_global_size_z:
630       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
631     case Intrinsic::r600_read_local_size_x:
632       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
633     case Intrinsic::r600_read_local_size_y:
634       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
635     case Intrinsic::r600_read_local_size_z:
636       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
637     case Intrinsic::r600_read_tgid_x:
638       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
639                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
640     case Intrinsic::r600_read_tgid_y:
641       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
642                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
643     case Intrinsic::r600_read_tgid_z:
644       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
645                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
646     case Intrinsic::r600_read_tidig_x:
647       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
648                                   AMDGPU::VGPR0, VT);
649     case Intrinsic::r600_read_tidig_y:
650       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
651                                   AMDGPU::VGPR1, VT);
652     case Intrinsic::r600_read_tidig_z:
653       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
654                                   AMDGPU::VGPR2, VT);
655     case AMDGPUIntrinsic::SI_load_const: {
656       SDValue Ops [] = {
657         Op.getOperand(1),
658         Op.getOperand(2)
659       };
660
661       MachineMemOperand *MMO = MF.getMachineMemOperand(
662           MachinePointerInfo(),
663           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
664           VT.getSizeInBits() / 8, 4);
665       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
666                                      Op->getVTList(), Ops, VT, MMO);
667     }
668     case AMDGPUIntrinsic::SI_sample:
669       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
670     case AMDGPUIntrinsic::SI_sampleb:
671       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
672     case AMDGPUIntrinsic::SI_sampled:
673       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
674     case AMDGPUIntrinsic::SI_samplel:
675       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
676     case AMDGPUIntrinsic::SI_vs_load_input:
677       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
678                          Op.getOperand(1),
679                          Op.getOperand(2),
680                          Op.getOperand(3));
681     }
682   }
683
684   case ISD::INTRINSIC_VOID:
685     SDValue Chain = Op.getOperand(0);
686     unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
687
688     switch (IntrinsicID) {
689       case AMDGPUIntrinsic::SI_tbuffer_store: {
690         SDLoc DL(Op);
691         SDValue Ops [] = {
692           Chain,
693           Op.getOperand(2),
694           Op.getOperand(3),
695           Op.getOperand(4),
696           Op.getOperand(5),
697           Op.getOperand(6),
698           Op.getOperand(7),
699           Op.getOperand(8),
700           Op.getOperand(9),
701           Op.getOperand(10),
702           Op.getOperand(11),
703           Op.getOperand(12),
704           Op.getOperand(13),
705           Op.getOperand(14)
706         };
707         EVT VT = Op.getOperand(3).getValueType();
708
709         MachineMemOperand *MMO = MF.getMachineMemOperand(
710             MachinePointerInfo(),
711             MachineMemOperand::MOStore,
712             VT.getSizeInBits() / 8, 4);
713         return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
714                                        Op->getVTList(), Ops, VT, MMO);
715       }
716       default:
717         break;
718     }
719   }
720   return SDValue();
721 }
722
723 /// \brief Helper function for LowerBRCOND
724 static SDNode *findUser(SDValue Value, unsigned Opcode) {
725
726   SDNode *Parent = Value.getNode();
727   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
728        I != E; ++I) {
729
730     if (I.getUse().get() != Value)
731       continue;
732
733     if (I->getOpcode() == Opcode)
734       return *I;
735   }
736   return nullptr;
737 }
738
739 /// This transforms the control flow intrinsics to get the branch destination as
740 /// last parameter, also switches branch target with BR if the need arise
741 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
742                                       SelectionDAG &DAG) const {
743
744   SDLoc DL(BRCOND);
745
746   SDNode *Intr = BRCOND.getOperand(1).getNode();
747   SDValue Target = BRCOND.getOperand(2);
748   SDNode *BR = nullptr;
749
750   if (Intr->getOpcode() == ISD::SETCC) {
751     // As long as we negate the condition everything is fine
752     SDNode *SetCC = Intr;
753     assert(SetCC->getConstantOperandVal(1) == 1);
754     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
755            ISD::SETNE);
756     Intr = SetCC->getOperand(0).getNode();
757
758   } else {
759     // Get the target from BR if we don't negate the condition
760     BR = findUser(BRCOND, ISD::BR);
761     Target = BR->getOperand(1);
762   }
763
764   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
765
766   // Build the result and
767   SmallVector<EVT, 4> Res;
768   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
769     Res.push_back(Intr->getValueType(i));
770
771   // operands of the new intrinsic call
772   SmallVector<SDValue, 4> Ops;
773   Ops.push_back(BRCOND.getOperand(0));
774   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
775     Ops.push_back(Intr->getOperand(i));
776   Ops.push_back(Target);
777
778   // build the new intrinsic call
779   SDNode *Result = DAG.getNode(
780     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
781     DAG.getVTList(Res), Ops).getNode();
782
783   if (BR) {
784     // Give the branch instruction our target
785     SDValue Ops[] = {
786       BR->getOperand(0),
787       BRCOND.getOperand(2)
788     };
789     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops);
790   }
791
792   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
793
794   // Copy the intrinsic results to registers
795   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
796     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
797     if (!CopyToReg)
798       continue;
799
800     Chain = DAG.getCopyToReg(
801       Chain, DL,
802       CopyToReg->getOperand(1),
803       SDValue(Result, i - 1),
804       SDValue());
805
806     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
807   }
808
809   // Remove the old intrinsic from the chain
810   DAG.ReplaceAllUsesOfValueWith(
811     SDValue(Intr, Intr->getNumValues() - 1),
812     Intr->getOperand(0));
813
814   return Chain;
815 }
816
817 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
818   SDLoc DL(Op);
819   LoadSDNode *Load = cast<LoadSDNode>(Op);
820   SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
821   SDValue MergedValues[2];
822   MergedValues[1] = Load->getChain();
823   if (Ret.getNode()) {
824     MergedValues[0] = Ret;
825     return DAG.getMergeValues(MergedValues, DL);
826   }
827
828   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
829     return SDValue();
830   }
831
832   EVT MemVT = Load->getMemoryVT();
833
834   assert(!MemVT.isVector() && "Private loads should be scalarized");
835   assert(!MemVT.isFloatingPoint() && "FP loads should be promoted to int");
836
837   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
838                             DAG.getConstant(2, MVT::i32));
839   Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
840                     Load->getChain(), Ptr,
841                     DAG.getTargetConstant(0, MVT::i32),
842                     Op.getOperand(2));
843   if (MemVT.getSizeInBits() == 64) {
844     SDValue IncPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
845                                  DAG.getConstant(1, MVT::i32));
846
847     SDValue LoadUpper = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
848                                     Load->getChain(), IncPtr,
849                                     DAG.getTargetConstant(0, MVT::i32),
850                                     Op.getOperand(2));
851
852     Ret = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ret, LoadUpper);
853   }
854
855   MergedValues[0] = Ret;
856   return DAG.getMergeValues(MergedValues, DL);
857
858 }
859
860 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
861                                                const SDValue &Op,
862                                                SelectionDAG &DAG) const {
863   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
864                      Op.getOperand(2),
865                      Op.getOperand(3),
866                      Op.getOperand(4));
867 }
868
869 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
870   if (Op.getValueType() != MVT::i64)
871     return SDValue();
872
873   SDLoc DL(Op);
874   SDValue Cond = Op.getOperand(0);
875
876   SDValue Zero = DAG.getConstant(0, MVT::i32);
877   SDValue One = DAG.getConstant(1, MVT::i32);
878
879   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
880   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
881
882   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
883   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
884
885   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
886
887   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
888   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
889
890   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
891
892   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
893   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
894 }
895
896 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
897   SDValue LHS = Op.getOperand(0);
898   SDValue RHS = Op.getOperand(1);
899   SDValue True = Op.getOperand(2);
900   SDValue False = Op.getOperand(3);
901   SDValue CC = Op.getOperand(4);
902   EVT VT = Op.getValueType();
903   SDLoc DL(Op);
904
905   // Possible Min/Max pattern
906   SDValue MinMax = LowerMinMax(Op, DAG);
907   if (MinMax.getNode()) {
908     return MinMax;
909   }
910
911   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
912   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
913 }
914
915 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
916                                            SelectionDAG &DAG) const {
917   EVT VT = Op.getValueType();
918   SDLoc DL(Op);
919
920   if (VT != MVT::i64) {
921     return SDValue();
922   }
923
924   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
925                                                  DAG.getConstant(31, MVT::i32));
926
927   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
928 }
929
930 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
931   SDLoc DL(Op);
932   StoreSDNode *Store = cast<StoreSDNode>(Op);
933   EVT VT = Store->getMemoryVT();
934
935   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
936   if (Ret.getNode())
937     return Ret;
938
939   if (VT.isVector() && VT.getVectorNumElements() >= 8)
940       return SplitVectorStore(Op, DAG);
941
942   if (VT == MVT::i1)
943     return DAG.getTruncStore(Store->getChain(), DL,
944                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
945                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
946
947   if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
948     return SDValue();
949
950   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
951                             DAG.getConstant(2, MVT::i32));
952   SDValue Chain = Store->getChain();
953   SmallVector<SDValue, 8> Values;
954
955   if (Store->isTruncatingStore()) {
956     unsigned Mask = 0;
957     if (Store->getMemoryVT() == MVT::i8) {
958       Mask = 0xff;
959     } else if (Store->getMemoryVT() == MVT::i16) {
960       Mask = 0xffff;
961     }
962     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
963                               Chain, Store->getBasePtr(),
964                               DAG.getConstant(0, MVT::i32));
965     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
966                                   DAG.getConstant(0x3, MVT::i32));
967     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
968                                    DAG.getConstant(3, MVT::i32));
969     SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
970                                       DAG.getConstant(Mask, MVT::i32));
971     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
972                                        MaskedValue, ShiftAmt);
973     SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
974                                   DAG.getConstant(32, MVT::i32), ShiftAmt);
975     SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
976                                   DAG.getConstant(Mask, MVT::i32),
977                                   RotrAmt);
978     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
979     Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
980
981     Values.push_back(Dst);
982   } else if (VT == MVT::i64) {
983     for (unsigned i = 0; i < 2; ++i) {
984       Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
985                        Store->getValue(), DAG.getConstant(i, MVT::i32)));
986     }
987   } else if (VT == MVT::i128) {
988     for (unsigned i = 0; i < 2; ++i) {
989       for (unsigned j = 0; j < 2; ++j) {
990         Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
991                            DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
992                            Store->getValue(), DAG.getConstant(i, MVT::i32)),
993                          DAG.getConstant(j, MVT::i32)));
994       }
995     }
996   } else {
997     Values.push_back(Store->getValue());
998   }
999
1000   for (unsigned i = 0; i < Values.size(); ++i) {
1001     SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
1002                                   Ptr, DAG.getConstant(i, MVT::i32));
1003     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1004                         Chain, Values[i], PartPtr,
1005                         DAG.getTargetConstant(0, MVT::i32));
1006   }
1007   return Chain;
1008 }
1009
1010
1011 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
1012                                            SelectionDAG &DAG) const {
1013   EVT VT = Op.getValueType();
1014   SDLoc DL(Op);
1015
1016   if (VT != MVT::i64) {
1017     return SDValue();
1018   }
1019
1020   SDValue Src = Op.getOperand(0);
1021   if (Src.getValueType() != MVT::i32)
1022     Src = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Src);
1023
1024   SDValue Zero = DAG.getConstant(0, MVT::i32);
1025   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Src, Zero);
1026 }
1027
1028 //===----------------------------------------------------------------------===//
1029 // Custom DAG optimizations
1030 //===----------------------------------------------------------------------===//
1031
1032 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1033                                             DAGCombinerInfo &DCI) const {
1034   SelectionDAG &DAG = DCI.DAG;
1035   SDLoc DL(N);
1036   EVT VT = N->getValueType(0);
1037
1038   switch (N->getOpcode()) {
1039     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1040     case ISD::SELECT_CC: {
1041       ConstantSDNode *True, *False;
1042       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
1043       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1044           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1045           && True->isAllOnesValue()
1046           && False->isNullValue()
1047           && VT == MVT::i1) {
1048         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
1049                            N->getOperand(1), N->getOperand(4));
1050
1051       }
1052       break;
1053     }
1054     case ISD::SETCC: {
1055       SDValue Arg0 = N->getOperand(0);
1056       SDValue Arg1 = N->getOperand(1);
1057       SDValue CC = N->getOperand(2);
1058       ConstantSDNode * C = nullptr;
1059       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1060
1061       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1062       if (VT == MVT::i1
1063           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1064           && Arg0.getOperand(0).getValueType() == MVT::i1
1065           && (C = dyn_cast<ConstantSDNode>(Arg1))
1066           && C->isNullValue()
1067           && CCOp == ISD::SETNE) {
1068         return SimplifySetCC(VT, Arg0.getOperand(0),
1069                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1070       }
1071       break;
1072     }
1073   }
1074   return SDValue();
1075 }
1076
1077 /// \brief Test if RegClass is one of the VSrc classes
1078 static bool isVSrc(unsigned RegClass) {
1079   return AMDGPU::VSrc_32RegClassID == RegClass ||
1080          AMDGPU::VSrc_64RegClassID == RegClass;
1081 }
1082
1083 /// \brief Test if RegClass is one of the SSrc classes
1084 static bool isSSrc(unsigned RegClass) {
1085   return AMDGPU::SSrc_32RegClassID == RegClass ||
1086          AMDGPU::SSrc_64RegClassID == RegClass;
1087 }
1088
1089 /// \brief Analyze the possible immediate value Op
1090 ///
1091 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1092 /// and the immediate value if it's a literal immediate
1093 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1094
1095   union {
1096     int32_t I;
1097     float F;
1098   } Imm;
1099
1100   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1101     if (Node->getZExtValue() >> 32) {
1102         return -1;
1103     }
1104     Imm.I = Node->getSExtValue();
1105   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1106     if (N->getValueType(0) != MVT::f32)
1107       return -1;
1108     Imm.F = Node->getValueAPF().convertToFloat();
1109   } else
1110     return -1; // It isn't an immediate
1111
1112   if ((Imm.I >= -16 && Imm.I <= 64) ||
1113       Imm.F == 0.5f || Imm.F == -0.5f ||
1114       Imm.F == 1.0f || Imm.F == -1.0f ||
1115       Imm.F == 2.0f || Imm.F == -2.0f ||
1116       Imm.F == 4.0f || Imm.F == -4.0f)
1117     return 0; // It's an inline immediate
1118
1119   return Imm.I; // It's a literal immediate
1120 }
1121
1122 /// \brief Try to fold an immediate directly into an instruction
1123 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1124                                bool &ScalarSlotUsed) const {
1125
1126   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1127   const SIInstrInfo *TII =
1128     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1129   if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1130     return false;
1131
1132   const SDValue &Op = Mov->getOperand(0);
1133   int32_t Value = analyzeImmediate(Op.getNode());
1134   if (Value == -1) {
1135     // Not an immediate at all
1136     return false;
1137
1138   } else if (Value == 0) {
1139     // Inline immediates can always be fold
1140     Operand = Op;
1141     return true;
1142
1143   } else if (Value == Immediate) {
1144     // Already fold literal immediate
1145     Operand = Op;
1146     return true;
1147
1148   } else if (!ScalarSlotUsed && !Immediate) {
1149     // Fold this literal immediate
1150     ScalarSlotUsed = true;
1151     Immediate = Value;
1152     Operand = Op;
1153     return true;
1154
1155   }
1156
1157   return false;
1158 }
1159
1160 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1161                                    SelectionDAG &DAG, const SDValue &Op) const {
1162   const SIInstrInfo *TII =
1163     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1164   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1165
1166   if (!Op->isMachineOpcode()) {
1167     switch(Op->getOpcode()) {
1168     case ISD::CopyFromReg: {
1169       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1170       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1171       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1172         return MRI.getRegClass(Reg);
1173       }
1174       return TRI.getPhysRegClass(Reg);
1175     }
1176     default:  return nullptr;
1177     }
1178   }
1179   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1180   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1181   if (OpClassID != -1) {
1182     return TRI.getRegClass(OpClassID);
1183   }
1184   switch(Op.getMachineOpcode()) {
1185   case AMDGPU::COPY_TO_REGCLASS:
1186     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1187     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1188
1189     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1190     // class, then the register class for the value could be either a
1191     // VReg or and SReg.  In order to get a more accurate
1192     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1193         OpClassID == AMDGPU::VSrc_64RegClassID) {
1194       return getRegClassForNode(DAG, Op.getOperand(0));
1195     }
1196     return TRI.getRegClass(OpClassID);
1197   case AMDGPU::EXTRACT_SUBREG: {
1198     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1199     const TargetRegisterClass *SuperClass =
1200       getRegClassForNode(DAG, Op.getOperand(0));
1201     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1202   }
1203   case AMDGPU::REG_SEQUENCE:
1204     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1205     return TRI.getRegClass(
1206       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1207   default:
1208     return getRegClassFor(Op.getSimpleValueType());
1209   }
1210 }
1211
1212 /// \brief Does "Op" fit into register class "RegClass" ?
1213 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1214                                     unsigned RegClass) const {
1215   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1216   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1217   if (!RC) {
1218     return false;
1219   }
1220   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1221 }
1222
1223 /// \brief Make sure that we don't exeed the number of allowed scalars
1224 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1225                                        unsigned RegClass,
1226                                        bool &ScalarSlotUsed) const {
1227
1228   // First map the operands register class to a destination class
1229   if (RegClass == AMDGPU::VSrc_32RegClassID)
1230     RegClass = AMDGPU::VReg_32RegClassID;
1231   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1232     RegClass = AMDGPU::VReg_64RegClassID;
1233   else
1234     return;
1235
1236   // Nothing to do if they fit naturally
1237   if (fitsRegClass(DAG, Operand, RegClass))
1238     return;
1239
1240   // If the scalar slot isn't used yet use it now
1241   if (!ScalarSlotUsed) {
1242     ScalarSlotUsed = true;
1243     return;
1244   }
1245
1246   // This is a conservative aproach. It is possible that we can't determine the
1247   // correct register class and copy too often, but better safe than sorry.
1248   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1249   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1250                                     Operand.getValueType(), Operand, RC);
1251   Operand = SDValue(Node, 0);
1252 }
1253
1254 /// \returns true if \p Node's operands are different from the SDValue list
1255 /// \p Ops
1256 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1257   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1258     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1259       return true;
1260     }
1261   }
1262   return false;
1263 }
1264
1265 /// \brief Try to fold the Nodes operands into the Node
1266 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1267                                        SelectionDAG &DAG) const {
1268
1269   // Original encoding (either e32 or e64)
1270   int Opcode = Node->getMachineOpcode();
1271   const SIInstrInfo *TII =
1272     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1273   const MCInstrDesc *Desc = &TII->get(Opcode);
1274
1275   unsigned NumDefs = Desc->getNumDefs();
1276   unsigned NumOps = Desc->getNumOperands();
1277
1278   // Commuted opcode if available
1279   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1280   const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1281
1282   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1283   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1284
1285   // e64 version if available, -1 otherwise
1286   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1287   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1288
1289   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1290   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
1291
1292   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1293   bool HaveVSrc = false, HaveSSrc = false;
1294
1295   // First figure out what we alread have in this instruction
1296   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1297        i != e && Op < NumOps; ++i, ++Op) {
1298
1299     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1300     if (isVSrc(RegClass))
1301       HaveVSrc = true;
1302     else if (isSSrc(RegClass))
1303       HaveSSrc = true;
1304     else
1305       continue;
1306
1307     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1308     if (Imm != -1 && Imm != 0) {
1309       // Literal immediate
1310       Immediate = Imm;
1311     }
1312   }
1313
1314   // If we neither have VSrc nor SSrc it makes no sense to continue
1315   if (!HaveVSrc && !HaveSSrc)
1316     return Node;
1317
1318   // No scalar allowed when we have both VSrc and SSrc
1319   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1320
1321   // Second go over the operands and try to fold them
1322   std::vector<SDValue> Ops;
1323   bool Promote2e64 = false;
1324   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1325        i != e && Op < NumOps; ++i, ++Op) {
1326
1327     const SDValue &Operand = Node->getOperand(i);
1328     Ops.push_back(Operand);
1329
1330     // Already folded immediate ?
1331     if (isa<ConstantSDNode>(Operand.getNode()) ||
1332         isa<ConstantFPSDNode>(Operand.getNode()))
1333       continue;
1334
1335     // Is this a VSrc or SSrc operand ?
1336     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1337     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1338       // Try to fold the immediates
1339       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1340         // Folding didn't worked, make sure we don't hit the SReg limit
1341         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1342       }
1343       continue;
1344     }
1345
1346     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1347
1348       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1349       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1350
1351       // Test if it makes sense to swap operands
1352       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1353           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1354            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1355
1356         // Swap commutable operands
1357         std::swap(Ops[0], Ops[1]);
1358
1359         Desc = DescRev;
1360         DescRev = nullptr;
1361         continue;
1362       }
1363     }
1364
1365     if (DescE64 && !Immediate) {
1366
1367       // Test if it makes sense to switch to e64 encoding
1368       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1369       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1370         continue;
1371
1372       int32_t TmpImm = -1;
1373       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1374           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1375            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1376
1377         // Switch to e64 encoding
1378         Immediate = -1;
1379         Promote2e64 = true;
1380         Desc = DescE64;
1381         DescE64 = nullptr;
1382       }
1383     }
1384   }
1385
1386   if (Promote2e64) {
1387     // Add the modifier flags while promoting
1388     for (unsigned i = 0; i < 4; ++i)
1389       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1390   }
1391
1392   // Add optional chain and glue
1393   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1394     Ops.push_back(Node->getOperand(i));
1395
1396   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1397   // this case a brand new node is always be created, even if the operands
1398   // are the same as before.  So, manually check if anything has been changed.
1399   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1400     return Node;
1401   }
1402
1403   // Create a complete new instruction
1404   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1405 }
1406
1407 /// \brief Helper function for adjustWritemask
1408 static unsigned SubIdx2Lane(unsigned Idx) {
1409   switch (Idx) {
1410   default: return 0;
1411   case AMDGPU::sub0: return 0;
1412   case AMDGPU::sub1: return 1;
1413   case AMDGPU::sub2: return 2;
1414   case AMDGPU::sub3: return 3;
1415   }
1416 }
1417
1418 /// \brief Adjust the writemask of MIMG instructions
1419 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1420                                        SelectionDAG &DAG) const {
1421   SDNode *Users[4] = { };
1422   unsigned Lane = 0;
1423   unsigned OldDmask = Node->getConstantOperandVal(0);
1424   unsigned NewDmask = 0;
1425
1426   // Try to figure out the used register components
1427   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1428        I != E; ++I) {
1429
1430     // Abort if we can't understand the usage
1431     if (!I->isMachineOpcode() ||
1432         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1433       return;
1434
1435     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1436     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1437     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1438     // set, etc.
1439     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1440
1441     // Set which texture component corresponds to the lane.
1442     unsigned Comp;
1443     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1444       assert(Dmask);
1445       Comp = countTrailingZeros(Dmask);
1446       Dmask &= ~(1 << Comp);
1447     }
1448
1449     // Abort if we have more than one user per component
1450     if (Users[Lane])
1451       return;
1452
1453     Users[Lane] = *I;
1454     NewDmask |= 1 << Comp;
1455   }
1456
1457   // Abort if there's no change
1458   if (NewDmask == OldDmask)
1459     return;
1460
1461   // Adjust the writemask in the node
1462   std::vector<SDValue> Ops;
1463   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1464   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1465     Ops.push_back(Node->getOperand(i));
1466   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1467
1468   // If we only got one lane, replace it with a copy
1469   // (if NewDmask has only one bit set...)
1470   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1471     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1472     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1473                                       SDLoc(), Users[Lane]->getValueType(0),
1474                                       SDValue(Node, 0), RC);
1475     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1476     return;
1477   }
1478
1479   // Update the users of the node with the new indices
1480   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1481
1482     SDNode *User = Users[i];
1483     if (!User)
1484       continue;
1485
1486     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1487     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1488
1489     switch (Idx) {
1490     default: break;
1491     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1492     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1493     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1494     }
1495   }
1496 }
1497
1498 /// \brief Fold the instructions after slecting them
1499 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1500                                           SelectionDAG &DAG) const {
1501   const SIInstrInfo *TII =
1502       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1503   Node = AdjustRegClass(Node, DAG);
1504
1505   if (TII->isMIMG(Node->getMachineOpcode()))
1506     adjustWritemask(Node, DAG);
1507
1508   return foldOperands(Node, DAG);
1509 }
1510
1511 /// \brief Assign the register class depending on the number of
1512 /// bits set in the writemask
1513 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1514                                                      SDNode *Node) const {
1515   const SIInstrInfo *TII =
1516       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1517   if (!TII->isMIMG(MI->getOpcode()))
1518     return;
1519
1520   unsigned VReg = MI->getOperand(0).getReg();
1521   unsigned Writemask = MI->getOperand(1).getImm();
1522   unsigned BitsSet = 0;
1523   for (unsigned i = 0; i < 4; ++i)
1524     BitsSet += Writemask & (1 << i) ? 1 : 0;
1525
1526   const TargetRegisterClass *RC;
1527   switch (BitsSet) {
1528   default: return;
1529   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1530   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1531   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1532   }
1533
1534   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1535   MI->setDesc(TII->get(NewOpcode));
1536   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1537   MRI.setRegClass(VReg, RC);
1538 }
1539
1540 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1541                                                 SelectionDAG &DAG) const {
1542
1543   SDLoc DL(N);
1544   unsigned NewOpcode = N->getMachineOpcode();
1545
1546   switch (N->getMachineOpcode()) {
1547   default: return N;
1548   case AMDGPU::S_LOAD_DWORD_IMM:
1549     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1550     // Fall-through
1551   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1552     if (NewOpcode == N->getMachineOpcode()) {
1553       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1554     }
1555     // Fall-through
1556   case AMDGPU::S_LOAD_DWORDX4_IMM:
1557   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1558     if (NewOpcode == N->getMachineOpcode()) {
1559       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1560     }
1561     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1562       return N;
1563     }
1564     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1565     SDValue Ops[] = {
1566       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1567                                  DAG.getConstant(0, MVT::i64)), 0),
1568       N->getOperand(0),
1569       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1570     };
1571     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1572   }
1573   }
1574 }
1575
1576 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1577                                                const TargetRegisterClass *RC,
1578                                                unsigned Reg, EVT VT) const {
1579   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1580
1581   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1582                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1583 }