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