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