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