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