9cbba6c54eaf7673fd80fe674fd7f1d926e3ad37
[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::i32, 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 = MF.getMachineMemOperand(
427           MachinePointerInfo(),
428           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
429           VT.getSizeInBits() / 8, 4);
430       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
431                                      Op->getVTList(), Ops, 2, VT, MMO);
432     }
433     case AMDGPUIntrinsic::SI_sample:
434       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
435     case AMDGPUIntrinsic::SI_sampleb:
436       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
437     case AMDGPUIntrinsic::SI_sampled:
438       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
439     case AMDGPUIntrinsic::SI_samplel:
440       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
441     case AMDGPUIntrinsic::SI_vs_load_input:
442       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
443                          ResourceDescriptorToi128(Op.getOperand(1), DAG),
444                          Op.getOperand(2),
445                          Op.getOperand(3));
446     }
447   }
448   }
449   return SDValue();
450 }
451
452 /// \brief Helper function for LowerBRCOND
453 static SDNode *findUser(SDValue Value, unsigned Opcode) {
454
455   SDNode *Parent = Value.getNode();
456   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
457        I != E; ++I) {
458
459     if (I.getUse().get() != Value)
460       continue;
461
462     if (I->getOpcode() == Opcode)
463       return *I;
464   }
465   return 0;
466 }
467
468 /// This transforms the control flow intrinsics to get the branch destination as
469 /// last parameter, also switches branch target with BR if the need arise
470 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
471                                       SelectionDAG &DAG) const {
472
473   SDLoc DL(BRCOND);
474
475   SDNode *Intr = BRCOND.getOperand(1).getNode();
476   SDValue Target = BRCOND.getOperand(2);
477   SDNode *BR = 0;
478
479   if (Intr->getOpcode() == ISD::SETCC) {
480     // As long as we negate the condition everything is fine
481     SDNode *SetCC = Intr;
482     assert(SetCC->getConstantOperandVal(1) == 1);
483     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
484            ISD::SETNE);
485     Intr = SetCC->getOperand(0).getNode();
486
487   } else {
488     // Get the target from BR if we don't negate the condition
489     BR = findUser(BRCOND, ISD::BR);
490     Target = BR->getOperand(1);
491   }
492
493   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
494
495   // Build the result and
496   SmallVector<EVT, 4> Res;
497   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
498     Res.push_back(Intr->getValueType(i));
499
500   // operands of the new intrinsic call
501   SmallVector<SDValue, 4> Ops;
502   Ops.push_back(BRCOND.getOperand(0));
503   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
504     Ops.push_back(Intr->getOperand(i));
505   Ops.push_back(Target);
506
507   // build the new intrinsic call
508   SDNode *Result = DAG.getNode(
509     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
510     DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
511
512   if (BR) {
513     // Give the branch instruction our target
514     SDValue Ops[] = {
515       BR->getOperand(0),
516       BRCOND.getOperand(2)
517     };
518     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
519   }
520
521   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
522
523   // Copy the intrinsic results to registers
524   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
525     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
526     if (!CopyToReg)
527       continue;
528
529     Chain = DAG.getCopyToReg(
530       Chain, DL,
531       CopyToReg->getOperand(1),
532       SDValue(Result, i - 1),
533       SDValue());
534
535     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
536   }
537
538   // Remove the old intrinsic from the chain
539   DAG.ReplaceAllUsesOfValueWith(
540     SDValue(Intr, Intr->getNumValues() - 1),
541     Intr->getOperand(0));
542
543   return Chain;
544 }
545
546 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
547                                              SelectionDAG &DAG) const {
548
549   if (Op.getValueType() == MVT::i128) {
550     return Op;
551   }
552
553   assert(Op.getOpcode() == ISD::UNDEF);
554
555   return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
556                      DAG.getConstant(0, MVT::i64),
557                      DAG.getConstant(0, MVT::i64));
558 }
559
560 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
561                                                const SDValue &Op,
562                                                SelectionDAG &DAG) const {
563   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
564                      Op.getOperand(2),
565                      ResourceDescriptorToi128(Op.getOperand(3), DAG),
566                      Op.getOperand(4));
567 }
568
569 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
570   SDValue LHS = Op.getOperand(0);
571   SDValue RHS = Op.getOperand(1);
572   SDValue True = Op.getOperand(2);
573   SDValue False = Op.getOperand(3);
574   SDValue CC = Op.getOperand(4);
575   EVT VT = Op.getValueType();
576   SDLoc DL(Op);
577
578   // Possible Min/Max pattern
579   SDValue MinMax = LowerMinMax(Op, DAG);
580   if (MinMax.getNode()) {
581     return MinMax;
582   }
583
584   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
585   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
586 }
587
588 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
589                                            SelectionDAG &DAG) const {
590   EVT VT = Op.getValueType();
591   SDLoc DL(Op);
592
593   if (VT != MVT::i64) {
594     return SDValue();
595   }
596
597   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
598                                                  DAG.getConstant(31, MVT::i32));
599
600   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
601 }
602
603 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
604                                            SelectionDAG &DAG) const {
605   EVT VT = Op.getValueType();
606   SDLoc DL(Op);
607
608   if (VT != MVT::i64) {
609     return SDValue();
610   }
611
612   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
613                                               DAG.getConstant(0, MVT::i32));
614 }
615
616 //===----------------------------------------------------------------------===//
617 // Custom DAG optimizations
618 //===----------------------------------------------------------------------===//
619
620 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
621                                             DAGCombinerInfo &DCI) const {
622   SelectionDAG &DAG = DCI.DAG;
623   SDLoc DL(N);
624   EVT VT = N->getValueType(0);
625
626   switch (N->getOpcode()) {
627     default: break;
628     case ISD::SELECT_CC: {
629       N->dump();
630       ConstantSDNode *True, *False;
631       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
632       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
633           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
634           && True->isAllOnesValue()
635           && False->isNullValue()
636           && VT == MVT::i1) {
637         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
638                            N->getOperand(1), N->getOperand(4));
639
640       }
641       break;
642     }
643     case ISD::SETCC: {
644       SDValue Arg0 = N->getOperand(0);
645       SDValue Arg1 = N->getOperand(1);
646       SDValue CC = N->getOperand(2);
647       ConstantSDNode * C = NULL;
648       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
649
650       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
651       if (VT == MVT::i1
652           && Arg0.getOpcode() == ISD::SIGN_EXTEND
653           && Arg0.getOperand(0).getValueType() == MVT::i1
654           && (C = dyn_cast<ConstantSDNode>(Arg1))
655           && C->isNullValue()
656           && CCOp == ISD::SETNE) {
657         return SimplifySetCC(VT, Arg0.getOperand(0),
658                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
659       }
660       break;
661     }
662   }
663   return SDValue();
664 }
665
666 /// \brief Test if RegClass is one of the VSrc classes
667 static bool isVSrc(unsigned RegClass) {
668   return AMDGPU::VSrc_32RegClassID == RegClass ||
669          AMDGPU::VSrc_64RegClassID == RegClass;
670 }
671
672 /// \brief Test if RegClass is one of the SSrc classes
673 static bool isSSrc(unsigned RegClass) {
674   return AMDGPU::SSrc_32RegClassID == RegClass ||
675          AMDGPU::SSrc_64RegClassID == RegClass;
676 }
677
678 /// \brief Analyze the possible immediate value Op
679 ///
680 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
681 /// and the immediate value if it's a literal immediate
682 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
683
684   union {
685     int32_t I;
686     float F;
687   } Imm;
688
689   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
690     if (Node->getZExtValue() >> 32) {
691         return -1;
692     }
693     Imm.I = Node->getSExtValue();
694   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
695     Imm.F = Node->getValueAPF().convertToFloat();
696   else
697     return -1; // It isn't an immediate
698
699   if ((Imm.I >= -16 && Imm.I <= 64) ||
700       Imm.F == 0.5f || Imm.F == -0.5f ||
701       Imm.F == 1.0f || Imm.F == -1.0f ||
702       Imm.F == 2.0f || Imm.F == -2.0f ||
703       Imm.F == 4.0f || Imm.F == -4.0f)
704     return 0; // It's an inline immediate
705
706   return Imm.I; // It's a literal immediate
707 }
708
709 /// \brief Try to fold an immediate directly into an instruction
710 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
711                                bool &ScalarSlotUsed) const {
712
713   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
714   const SIInstrInfo *TII =
715     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
716   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
717     return false;
718
719   const SDValue &Op = Mov->getOperand(0);
720   int32_t Value = analyzeImmediate(Op.getNode());
721   if (Value == -1) {
722     // Not an immediate at all
723     return false;
724
725   } else if (Value == 0) {
726     // Inline immediates can always be fold
727     Operand = Op;
728     return true;
729
730   } else if (Value == Immediate) {
731     // Already fold literal immediate
732     Operand = Op;
733     return true;
734
735   } else if (!ScalarSlotUsed && !Immediate) {
736     // Fold this literal immediate
737     ScalarSlotUsed = true;
738     Immediate = Value;
739     Operand = Op;
740     return true;
741
742   }
743
744   return false;
745 }
746
747 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
748                                    SelectionDAG &DAG, const SDValue &Op) const {
749   const SIInstrInfo *TII =
750     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
751   const SIRegisterInfo &TRI = TII->getRegisterInfo();
752
753   if (!Op->isMachineOpcode()) {
754     switch(Op->getOpcode()) {
755     case ISD::CopyFromReg: {
756       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
757       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
758       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
759         return MRI.getRegClass(Reg);
760       }
761       return TRI.getPhysRegClass(Reg);
762     }
763     default:  return NULL;
764     }
765   }
766   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
767   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
768   if (OpClassID != -1) {
769     return TRI.getRegClass(OpClassID);
770   }
771   switch(Op.getMachineOpcode()) {
772   case AMDGPU::COPY_TO_REGCLASS:
773     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
774     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
775
776     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
777     // class, then the register class for the value could be either a
778     // VReg or and SReg.  In order to get a more accurate
779     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
780         OpClassID == AMDGPU::VSrc_64RegClassID) {
781       return getRegClassForNode(DAG, Op.getOperand(0));
782     }
783     return TRI.getRegClass(OpClassID);
784   case AMDGPU::EXTRACT_SUBREG: {
785     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
786     const TargetRegisterClass *SuperClass =
787       getRegClassForNode(DAG, Op.getOperand(0));
788     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
789   }
790   case AMDGPU::REG_SEQUENCE:
791     // Operand 0 is the register class id for REG_SEQUENCE instructions.
792     return TRI.getRegClass(
793       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
794   default:
795     return getRegClassFor(Op.getSimpleValueType());
796   }
797 }
798
799 /// \brief Does "Op" fit into register class "RegClass" ?
800 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
801                                     unsigned RegClass) const {
802   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
803   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
804   if (!RC) {
805     return false;
806   }
807   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
808 }
809
810 /// \brief Make sure that we don't exeed the number of allowed scalars
811 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
812                                        unsigned RegClass,
813                                        bool &ScalarSlotUsed) const {
814
815   // First map the operands register class to a destination class
816   if (RegClass == AMDGPU::VSrc_32RegClassID)
817     RegClass = AMDGPU::VReg_32RegClassID;
818   else if (RegClass == AMDGPU::VSrc_64RegClassID)
819     RegClass = AMDGPU::VReg_64RegClassID;
820   else
821     return;
822
823   // Nothing todo if they fit naturaly
824   if (fitsRegClass(DAG, Operand, RegClass))
825     return;
826
827   // If the scalar slot isn't used yet use it now
828   if (!ScalarSlotUsed) {
829     ScalarSlotUsed = true;
830     return;
831   }
832
833   // This is a conservative aproach, it is possible that we can't determine
834   // the correct register class and copy too often, but better save than sorry.
835   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
836   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
837                                     Operand.getValueType(), Operand, RC);
838   Operand = SDValue(Node, 0);
839 }
840
841 /// \returns true if \p Node's operands are different from the SDValue list
842 /// \p Ops
843 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
844   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
845     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
846       return true;
847     }
848   }
849   return false;
850 }
851
852 /// \brief Try to fold the Nodes operands into the Node
853 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
854                                        SelectionDAG &DAG) const {
855
856   // Original encoding (either e32 or e64)
857   int Opcode = Node->getMachineOpcode();
858   const SIInstrInfo *TII =
859     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
860   const MCInstrDesc *Desc = &TII->get(Opcode);
861
862   unsigned NumDefs = Desc->getNumDefs();
863   unsigned NumOps = Desc->getNumOperands();
864
865   // Commuted opcode if available
866   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
867   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
868
869   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
870   assert(!DescRev || DescRev->getNumOperands() == NumOps);
871
872   // e64 version if available, -1 otherwise
873   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
874   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
875
876   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
877   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
878
879   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
880   bool HaveVSrc = false, HaveSSrc = false;
881
882   // First figure out what we alread have in this instruction
883   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
884        i != e && Op < NumOps; ++i, ++Op) {
885
886     unsigned RegClass = Desc->OpInfo[Op].RegClass;
887     if (isVSrc(RegClass))
888       HaveVSrc = true;
889     else if (isSSrc(RegClass))
890       HaveSSrc = true;
891     else
892       continue;
893
894     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
895     if (Imm != -1 && Imm != 0) {
896       // Literal immediate
897       Immediate = Imm;
898     }
899   }
900
901   // If we neither have VSrc nor SSrc it makes no sense to continue
902   if (!HaveVSrc && !HaveSSrc)
903     return Node;
904
905   // No scalar allowed when we have both VSrc and SSrc
906   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
907
908   // Second go over the operands and try to fold them
909   std::vector<SDValue> Ops;
910   bool Promote2e64 = false;
911   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
912        i != e && Op < NumOps; ++i, ++Op) {
913
914     const SDValue &Operand = Node->getOperand(i);
915     Ops.push_back(Operand);
916
917     // Already folded immediate ?
918     if (isa<ConstantSDNode>(Operand.getNode()) ||
919         isa<ConstantFPSDNode>(Operand.getNode()))
920       continue;
921
922     // Is this a VSrc or SSrc operand ?
923     unsigned RegClass = Desc->OpInfo[Op].RegClass;
924     if (isVSrc(RegClass) || isSSrc(RegClass)) {
925       // Try to fold the immediates
926       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
927         // Folding didn't worked, make sure we don't hit the SReg limit
928         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
929       }
930       continue;
931     }
932
933     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
934
935       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
936       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
937
938       // Test if it makes sense to swap operands
939       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
940           (!fitsRegClass(DAG, Ops[1], RegClass) &&
941            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
942
943         // Swap commutable operands
944         SDValue Tmp = Ops[1];
945         Ops[1] = Ops[0];
946         Ops[0] = Tmp;
947
948         Desc = DescRev;
949         DescRev = 0;
950         continue;
951       }
952     }
953
954     if (DescE64 && !Immediate) {
955
956       // Test if it makes sense to switch to e64 encoding
957       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
958       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
959         continue;
960
961       int32_t TmpImm = -1;
962       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
963           (!fitsRegClass(DAG, Ops[i], RegClass) &&
964            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
965
966         // Switch to e64 encoding
967         Immediate = -1;
968         Promote2e64 = true;
969         Desc = DescE64;
970         DescE64 = 0;
971       }
972     }
973   }
974
975   if (Promote2e64) {
976     // Add the modifier flags while promoting
977     for (unsigned i = 0; i < 4; ++i)
978       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
979   }
980
981   // Add optional chain and glue
982   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
983     Ops.push_back(Node->getOperand(i));
984
985   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
986   // this case a brand new node is always be created, even if the operands
987   // are the same as before.  So, manually check if anything has been changed.
988   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
989     return Node;
990   }
991
992   // Create a complete new instruction
993   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
994 }
995
996 /// \brief Helper function for adjustWritemask
997 static unsigned SubIdx2Lane(unsigned Idx) {
998   switch (Idx) {
999   default: return 0;
1000   case AMDGPU::sub0: return 0;
1001   case AMDGPU::sub1: return 1;
1002   case AMDGPU::sub2: return 2;
1003   case AMDGPU::sub3: return 3;
1004   }
1005 }
1006
1007 /// \brief Adjust the writemask of MIMG instructions
1008 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1009                                        SelectionDAG &DAG) const {
1010   SDNode *Users[4] = { };
1011   unsigned Writemask = 0, Lane = 0;
1012
1013   // Try to figure out the used register components
1014   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1015        I != E; ++I) {
1016
1017     // Abort if we can't understand the usage
1018     if (!I->isMachineOpcode() ||
1019         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1020       return;
1021
1022     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1023
1024     // Abort if we have more than one user per component
1025     if (Users[Lane])
1026       return;
1027
1028     Users[Lane] = *I;
1029     Writemask |= 1 << Lane;
1030   }
1031
1032   // Abort if all components are used
1033   if (Writemask == 0xf)
1034     return;
1035
1036   // Adjust the writemask in the node
1037   std::vector<SDValue> Ops;
1038   Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1039   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1040     Ops.push_back(Node->getOperand(i));
1041   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1042
1043   // If we only got one lane, replace it with a copy
1044   if (Writemask == (1U << Lane)) {
1045     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1046     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1047                                       SDLoc(), Users[Lane]->getValueType(0),
1048                                       SDValue(Node, 0), RC);
1049     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1050     return;
1051   }
1052
1053   // Update the users of the node with the new indices
1054   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1055
1056     SDNode *User = Users[i];
1057     if (!User)
1058       continue;
1059
1060     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1061     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1062
1063     switch (Idx) {
1064     default: break;
1065     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1066     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1067     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1068     }
1069   }
1070 }
1071
1072 /// \brief Fold the instructions after slecting them
1073 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1074                                           SelectionDAG &DAG) const {
1075   const SIInstrInfo *TII =
1076       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1077   Node = AdjustRegClass(Node, DAG);
1078
1079   if (TII->isMIMG(Node->getMachineOpcode()))
1080     adjustWritemask(Node, DAG);
1081
1082   return foldOperands(Node, DAG);
1083 }
1084
1085 /// \brief Assign the register class depending on the number of
1086 /// bits set in the writemask
1087 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1088                                                      SDNode *Node) const {
1089   const SIInstrInfo *TII =
1090       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1091   if (!TII->isMIMG(MI->getOpcode()))
1092     return;
1093
1094   unsigned VReg = MI->getOperand(0).getReg();
1095   unsigned Writemask = MI->getOperand(1).getImm();
1096   unsigned BitsSet = 0;
1097   for (unsigned i = 0; i < 4; ++i)
1098     BitsSet += Writemask & (1 << i) ? 1 : 0;
1099
1100   const TargetRegisterClass *RC;
1101   switch (BitsSet) {
1102   default: return;
1103   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1104   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1105   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1106   }
1107
1108   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1109   MRI.setRegClass(VReg, RC);
1110 }
1111
1112 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1113                                                 SelectionDAG &DAG) const {
1114
1115   SDLoc DL(N);
1116   unsigned NewOpcode = N->getMachineOpcode();
1117
1118   switch (N->getMachineOpcode()) {
1119   default: return N;
1120   case AMDGPU::S_LOAD_DWORD_IMM:
1121     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1122     // Fall-through
1123   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1124     if (NewOpcode == N->getMachineOpcode()) {
1125       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1126     }
1127     // Fall-through
1128   case AMDGPU::S_LOAD_DWORDX4_IMM:
1129   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1130     if (NewOpcode == N->getMachineOpcode()) {
1131       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1132     }
1133     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1134       return N;
1135     }
1136     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1137     SDValue Ops[] = {
1138       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1139                                  DAG.getConstant(0, MVT::i64)), 0),
1140       N->getOperand(0),
1141       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1142     };
1143     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1144   }
1145   }
1146 }
1147
1148 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1149                                                const TargetRegisterClass *RC,
1150                                                unsigned Reg, EVT VT) const {
1151   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1152
1153   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1154                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1155 }