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