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