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