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