R600: Simplify stream outputs intrinsic
[oota-llvm.git] / lib / Target / R600 / R600ISelLowering.cpp
1 //===-- R600ISelLowering.cpp - R600 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 R600
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "R600ISelLowering.h"
16 #include "R600Defines.h"
17 #include "R600InstrInfo.h"
18 #include "R600MachineFunctionInfo.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/Function.h"
24
25 using namespace llvm;
26
27 R600TargetLowering::R600TargetLowering(TargetMachine &TM) :
28     AMDGPUTargetLowering(TM),
29     TII(static_cast<const R600InstrInfo*>(TM.getInstrInfo())) {
30   setOperationAction(ISD::MUL, MVT::i64, Expand);
31   addRegisterClass(MVT::v4f32, &AMDGPU::R600_Reg128RegClass);
32   addRegisterClass(MVT::f32, &AMDGPU::R600_Reg32RegClass);
33   addRegisterClass(MVT::v4i32, &AMDGPU::R600_Reg128RegClass);
34   addRegisterClass(MVT::i32, &AMDGPU::R600_Reg32RegClass);
35   computeRegisterProperties();
36
37   setOperationAction(ISD::FADD, MVT::v4f32, Expand);
38   setOperationAction(ISD::FMUL, MVT::v4f32, Expand);
39   setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
40   setOperationAction(ISD::FSUB, MVT::v4f32, Expand);
41
42   setOperationAction(ISD::ADD,  MVT::v4i32, Expand);
43   setOperationAction(ISD::AND,  MVT::v4i32, Expand);
44   setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Expand);
45   setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Expand);
46   setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Expand);
47   setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Expand);
48   setOperationAction(ISD::UDIV, MVT::v4i32, Expand);
49   setOperationAction(ISD::UREM, MVT::v4i32, Expand);
50   setOperationAction(ISD::SETCC, MVT::v4i32, Expand);
51
52   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
53   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
54
55   setOperationAction(ISD::FSUB, MVT::f32, Expand);
56
57   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
58   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
59   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i1, Custom);
60   setOperationAction(ISD::FPOW, MVT::f32, Custom);
61
62   setOperationAction(ISD::ROTL, MVT::i32, Custom);
63
64   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
65   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
66
67   setOperationAction(ISD::SETCC, MVT::i32, Custom);
68   setOperationAction(ISD::SETCC, MVT::f32, Custom);
69   setOperationAction(ISD::FP_TO_UINT, MVT::i1, Custom);
70
71   setOperationAction(ISD::SELECT, MVT::i32, Custom);
72   setOperationAction(ISD::SELECT, MVT::f32, Custom);
73
74   setOperationAction(ISD::STORE, MVT::i32, Custom);
75   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
76
77   setOperationAction(ISD::LOAD, MVT::i32, Custom);
78   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
79   setTargetDAGCombine(ISD::FP_ROUND);
80   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
81
82   setSchedulingPreference(Sched::VLIW);
83 }
84
85 MachineBasicBlock * R600TargetLowering::EmitInstrWithCustomInserter(
86     MachineInstr * MI, MachineBasicBlock * BB) const {
87   MachineFunction * MF = BB->getParent();
88   MachineRegisterInfo &MRI = MF->getRegInfo();
89   MachineBasicBlock::iterator I = *MI;
90
91   switch (MI->getOpcode()) {
92   default: return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
93   case AMDGPU::SHADER_TYPE: break;
94   case AMDGPU::CLAMP_R600: {
95     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
96                                                    AMDGPU::MOV,
97                                                    MI->getOperand(0).getReg(),
98                                                    MI->getOperand(1).getReg());
99     TII->addFlag(NewMI, 0, MO_FLAG_CLAMP);
100     break;
101   }
102
103   case AMDGPU::FABS_R600: {
104     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
105                                                     AMDGPU::MOV,
106                                                     MI->getOperand(0).getReg(),
107                                                     MI->getOperand(1).getReg());
108     TII->addFlag(NewMI, 0, MO_FLAG_ABS);
109     break;
110   }
111
112   case AMDGPU::FNEG_R600: {
113     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
114                                                     AMDGPU::MOV,
115                                                     MI->getOperand(0).getReg(),
116                                                     MI->getOperand(1).getReg());
117     TII->addFlag(NewMI, 0, MO_FLAG_NEG);
118     break;
119   }
120
121   case AMDGPU::MASK_WRITE: {
122     unsigned maskedRegister = MI->getOperand(0).getReg();
123     assert(TargetRegisterInfo::isVirtualRegister(maskedRegister));
124     MachineInstr * defInstr = MRI.getVRegDef(maskedRegister);
125     TII->addFlag(defInstr, 0, MO_FLAG_MASK);
126     break;
127   }
128
129   case AMDGPU::MOV_IMM_F32:
130     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
131                      MI->getOperand(1).getFPImm()->getValueAPF()
132                          .bitcastToAPInt().getZExtValue());
133     break;
134   case AMDGPU::MOV_IMM_I32:
135     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
136                      MI->getOperand(1).getImm());
137     break;
138
139
140   case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
141   case AMDGPU::RAT_WRITE_CACHELESS_128_eg: {
142     unsigned EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;
143
144     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
145             .addOperand(MI->getOperand(0))
146             .addOperand(MI->getOperand(1))
147             .addImm(EOP); // Set End of program bit
148     break;
149   }
150
151   case AMDGPU::RESERVE_REG: {
152     R600MachineFunctionInfo * MFI = MF->getInfo<R600MachineFunctionInfo>();
153     int64_t ReservedIndex = MI->getOperand(0).getImm();
154     unsigned ReservedReg =
155                          AMDGPU::R600_TReg32RegClass.getRegister(ReservedIndex);
156     MFI->ReservedRegs.push_back(ReservedReg);
157     unsigned SuperReg =
158           AMDGPU::R600_Reg128RegClass.getRegister(ReservedIndex / 4);
159     MFI->ReservedRegs.push_back(SuperReg);
160     break;
161   }
162
163   case AMDGPU::TXD: {
164     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
165     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
166
167     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
168             .addOperand(MI->getOperand(3))
169             .addOperand(MI->getOperand(4))
170             .addOperand(MI->getOperand(5))
171             .addOperand(MI->getOperand(6));
172     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
173             .addOperand(MI->getOperand(2))
174             .addOperand(MI->getOperand(4))
175             .addOperand(MI->getOperand(5))
176             .addOperand(MI->getOperand(6));
177     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_G))
178             .addOperand(MI->getOperand(0))
179             .addOperand(MI->getOperand(1))
180             .addOperand(MI->getOperand(4))
181             .addOperand(MI->getOperand(5))
182             .addOperand(MI->getOperand(6))
183             .addReg(T0, RegState::Implicit)
184             .addReg(T1, RegState::Implicit);
185     break;
186   }
187
188   case AMDGPU::TXD_SHADOW: {
189     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
190     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
191
192     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
193             .addOperand(MI->getOperand(3))
194             .addOperand(MI->getOperand(4))
195             .addOperand(MI->getOperand(5))
196             .addOperand(MI->getOperand(6));
197     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
198             .addOperand(MI->getOperand(2))
199             .addOperand(MI->getOperand(4))
200             .addOperand(MI->getOperand(5))
201             .addOperand(MI->getOperand(6));
202     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_C_G))
203             .addOperand(MI->getOperand(0))
204             .addOperand(MI->getOperand(1))
205             .addOperand(MI->getOperand(4))
206             .addOperand(MI->getOperand(5))
207             .addOperand(MI->getOperand(6))
208             .addReg(T0, RegState::Implicit)
209             .addReg(T1, RegState::Implicit);
210     break;
211   }
212
213   case AMDGPU::BRANCH:
214       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
215               .addOperand(MI->getOperand(0))
216               .addReg(0);
217       break;
218
219   case AMDGPU::BRANCH_COND_f32: {
220     MachineInstr *NewMI =
221       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
222               AMDGPU::PREDICATE_BIT)
223               .addOperand(MI->getOperand(1))
224               .addImm(OPCODE_IS_NOT_ZERO)
225               .addImm(0); // Flags
226     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
227     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
228             .addOperand(MI->getOperand(0))
229             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
230     break;
231   }
232
233   case AMDGPU::BRANCH_COND_i32: {
234     MachineInstr *NewMI =
235       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
236             AMDGPU::PREDICATE_BIT)
237             .addOperand(MI->getOperand(1))
238             .addImm(OPCODE_IS_NOT_ZERO_INT)
239             .addImm(0); // Flags
240     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
241     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
242            .addOperand(MI->getOperand(0))
243             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
244     break;
245   }
246
247   case AMDGPU::input_perspective: {
248     R600MachineFunctionInfo *MFI = MF->getInfo<R600MachineFunctionInfo>();
249
250     // XXX Be more fine about register reservation
251     for (unsigned i = 0; i < 4; i ++) {
252       unsigned ReservedReg = AMDGPU::R600_TReg32RegClass.getRegister(i);
253       MFI->ReservedRegs.push_back(ReservedReg);
254     }
255
256     switch (MI->getOperand(1).getImm()) {
257     case 0:// Perspective
258       MFI->HasPerspectiveInterpolation = true;
259       break;
260     case 1:// Linear
261       MFI->HasLinearInterpolation = true;
262       break;
263     default:
264       assert(0 && "Unknow ij index");
265     }
266
267     return BB;
268   }
269
270   case AMDGPU::EG_ExportSwz:
271   case AMDGPU::R600_ExportSwz: {
272     bool EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN)? 1 : 0;
273     if (!EOP)
274       return BB;
275     unsigned CfInst = (MI->getOpcode() == AMDGPU::EG_ExportSwz)? 84 : 40;
276     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
277             .addOperand(MI->getOperand(0))
278             .addOperand(MI->getOperand(1))
279             .addOperand(MI->getOperand(2))
280             .addOperand(MI->getOperand(3))
281             .addOperand(MI->getOperand(4))
282             .addOperand(MI->getOperand(5))
283             .addOperand(MI->getOperand(6))
284             .addImm(CfInst)
285             .addImm(1);
286     break;
287   }
288   }
289
290   MI->eraseFromParent();
291   return BB;
292 }
293
294 //===----------------------------------------------------------------------===//
295 // Custom DAG Lowering Operations
296 //===----------------------------------------------------------------------===//
297
298 using namespace llvm::Intrinsic;
299 using namespace llvm::AMDGPUIntrinsic;
300
301 static SDValue
302 InsertScalarToRegisterExport(SelectionDAG &DAG, DebugLoc DL, SDNode **ExportMap,
303     unsigned Slot, unsigned Channel, unsigned Inst, unsigned Type,
304     SDValue Scalar, SDValue Chain) {
305   if (!ExportMap[Slot]) {
306     SDValue Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT,
307       DL, MVT::v4f32,
308       DAG.getUNDEF(MVT::v4f32),
309       Scalar,
310       DAG.getConstant(Channel, MVT::i32));
311
312     unsigned Mask = 1 << Channel;
313
314     const SDValue Ops[] = {Chain, Vector, DAG.getConstant(Inst, MVT::i32),
315         DAG.getConstant(Type, MVT::i32), DAG.getConstant(Slot, MVT::i32),
316         DAG.getConstant(Mask, MVT::i32)};
317
318     SDValue Res =  DAG.getNode(
319         AMDGPUISD::EXPORT,
320         DL,
321         MVT::Other,
322         Ops, 6);
323      ExportMap[Slot] = Res.getNode();
324      return Res;
325   }
326
327   SDNode *ExportInstruction = (SDNode *) ExportMap[Slot] ;
328   SDValue PreviousVector = ExportInstruction->getOperand(1);
329   SDValue Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT,
330       DL, MVT::v4f32,
331       PreviousVector,
332       Scalar,
333       DAG.getConstant(Channel, MVT::i32));
334
335   unsigned Mask = dyn_cast<ConstantSDNode>(ExportInstruction->getOperand(5))
336       ->getZExtValue();
337   Mask |= (1 << Channel);
338
339   const SDValue Ops[] = {ExportInstruction->getOperand(0), Vector,
340       DAG.getConstant(Inst, MVT::i32),
341       DAG.getConstant(Type, MVT::i32),
342       DAG.getConstant(Slot, MVT::i32),
343       DAG.getConstant(Mask, MVT::i32)};
344
345   DAG.UpdateNodeOperands(ExportInstruction,
346       Ops, 6);
347
348   return Chain;
349
350 }
351
352 SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
353   switch (Op.getOpcode()) {
354   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
355   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
356   case ISD::ROTL: return LowerROTL(Op, DAG);
357   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
358   case ISD::SELECT: return LowerSELECT(Op, DAG);
359   case ISD::SETCC: return LowerSETCC(Op, DAG);
360   case ISD::STORE: return LowerSTORE(Op, DAG);
361   case ISD::LOAD: return LowerLOAD(Op, DAG);
362   case ISD::FPOW: return LowerFPOW(Op, DAG);
363   case ISD::INTRINSIC_VOID: {
364     SDValue Chain = Op.getOperand(0);
365     unsigned IntrinsicID =
366                          cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
367     switch (IntrinsicID) {
368     case AMDGPUIntrinsic::AMDGPU_store_output: {
369       MachineFunction &MF = DAG.getMachineFunction();
370       MachineRegisterInfo &MRI = MF.getRegInfo();
371       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
372       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
373       if (!MRI.isLiveOut(Reg)) {
374         MRI.addLiveOut(Reg);
375       }
376       return DAG.getCopyToReg(Chain, Op.getDebugLoc(), Reg, Op.getOperand(2));
377     }
378     case AMDGPUIntrinsic::R600_store_pixel_color: {
379       MachineFunction &MF = DAG.getMachineFunction();
380       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
381       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
382
383       SDNode **OutputsMap = MFI->Outputs;
384       return InsertScalarToRegisterExport(DAG, Op.getDebugLoc(), OutputsMap,
385           RegIndex / 4, RegIndex % 4, 0, 0, Op.getOperand(2),
386           Chain);
387
388     }
389
390     // default for switch(IntrinsicID)
391     default: break;
392     }
393     // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
394     break;
395   }
396   case ISD::INTRINSIC_WO_CHAIN: {
397     unsigned IntrinsicID =
398                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
399     EVT VT = Op.getValueType();
400     DebugLoc DL = Op.getDebugLoc();
401     switch(IntrinsicID) {
402     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
403     case AMDGPUIntrinsic::R600_load_input: {
404       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
405       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
406       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass, Reg, VT);
407     }
408     case AMDGPUIntrinsic::R600_load_input_perspective: {
409       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
410       if (slot < 0)
411         return DAG.getUNDEF(MVT::f32);
412       SDValue FullVector = DAG.getNode(
413           AMDGPUISD::INTERP,
414           DL, MVT::v4f32,
415           DAG.getConstant(0, MVT::i32), DAG.getConstant(slot / 4 , MVT::i32));
416       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
417         DL, VT, FullVector, DAG.getConstant(slot % 4, MVT::i32));
418     }
419     case AMDGPUIntrinsic::R600_load_input_linear: {
420       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
421       if (slot < 0)
422         return DAG.getUNDEF(MVT::f32);
423       SDValue FullVector = DAG.getNode(
424         AMDGPUISD::INTERP,
425         DL, MVT::v4f32,
426         DAG.getConstant(1, MVT::i32), DAG.getConstant(slot / 4 , MVT::i32));
427       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
428         DL, VT, FullVector, DAG.getConstant(slot % 4, MVT::i32));
429     }
430     case AMDGPUIntrinsic::R600_load_input_constant: {
431       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
432       if (slot < 0)
433         return DAG.getUNDEF(MVT::f32);
434       SDValue FullVector = DAG.getNode(
435         AMDGPUISD::INTERP_P0,
436         DL, MVT::v4f32,
437         DAG.getConstant(slot / 4 , MVT::i32));
438       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
439           DL, VT, FullVector, DAG.getConstant(slot % 4, MVT::i32));
440     }
441
442     case r600_read_ngroups_x:
443       return LowerImplicitParameter(DAG, VT, DL, 0);
444     case r600_read_ngroups_y:
445       return LowerImplicitParameter(DAG, VT, DL, 1);
446     case r600_read_ngroups_z:
447       return LowerImplicitParameter(DAG, VT, DL, 2);
448     case r600_read_global_size_x:
449       return LowerImplicitParameter(DAG, VT, DL, 3);
450     case r600_read_global_size_y:
451       return LowerImplicitParameter(DAG, VT, DL, 4);
452     case r600_read_global_size_z:
453       return LowerImplicitParameter(DAG, VT, DL, 5);
454     case r600_read_local_size_x:
455       return LowerImplicitParameter(DAG, VT, DL, 6);
456     case r600_read_local_size_y:
457       return LowerImplicitParameter(DAG, VT, DL, 7);
458     case r600_read_local_size_z:
459       return LowerImplicitParameter(DAG, VT, DL, 8);
460
461     case r600_read_tgid_x:
462       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
463                                   AMDGPU::T1_X, VT);
464     case r600_read_tgid_y:
465       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
466                                   AMDGPU::T1_Y, VT);
467     case r600_read_tgid_z:
468       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
469                                   AMDGPU::T1_Z, VT);
470     case r600_read_tidig_x:
471       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
472                                   AMDGPU::T0_X, VT);
473     case r600_read_tidig_y:
474       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
475                                   AMDGPU::T0_Y, VT);
476     case r600_read_tidig_z:
477       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
478                                   AMDGPU::T0_Z, VT);
479     }
480     // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
481     break;
482   }
483   } // end switch(Op.getOpcode())
484   return SDValue();
485 }
486
487 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
488                                             SmallVectorImpl<SDValue> &Results,
489                                             SelectionDAG &DAG) const {
490   switch (N->getOpcode()) {
491   default: return;
492   case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
493     return;
494   case ISD::LOAD: {
495     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
496     Results.push_back(SDValue(Node, 0));
497     Results.push_back(SDValue(Node, 1));
498     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
499     // function
500     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
501     return;
502   }
503   }
504 }
505
506 SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
507   return DAG.getNode(
508       ISD::SETCC,
509       Op.getDebugLoc(),
510       MVT::i1,
511       Op, DAG.getConstantFP(0.0f, MVT::f32),
512       DAG.getCondCode(ISD::SETNE)
513       );
514 }
515
516 SDValue R600TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
517   SDValue Chain = Op.getOperand(0);
518   SDValue CC = Op.getOperand(1);
519   SDValue LHS   = Op.getOperand(2);
520   SDValue RHS   = Op.getOperand(3);
521   SDValue JumpT  = Op.getOperand(4);
522   SDValue CmpValue;
523   SDValue Result;
524
525   if (LHS.getValueType() == MVT::i32) {
526     CmpValue = DAG.getNode(
527         ISD::SELECT_CC,
528         Op.getDebugLoc(),
529         MVT::i32,
530         LHS, RHS,
531         DAG.getConstant(-1, MVT::i32),
532         DAG.getConstant(0, MVT::i32),
533         CC);
534   } else if (LHS.getValueType() == MVT::f32) {
535     CmpValue = DAG.getNode(
536         ISD::SELECT_CC,
537         Op.getDebugLoc(),
538         MVT::f32,
539         LHS, RHS,
540         DAG.getConstantFP(1.0f, MVT::f32),
541         DAG.getConstantFP(0.0f, MVT::f32),
542         CC);
543   } else {
544     assert(0 && "Not valid type for br_cc");
545   }
546   Result = DAG.getNode(
547       AMDGPUISD::BRANCH_COND,
548       CmpValue.getDebugLoc(),
549       MVT::Other, Chain,
550       JumpT, CmpValue);
551   return Result;
552 }
553
554 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
555                                                    DebugLoc DL,
556                                                    unsigned DwordOffset) const {
557   unsigned ByteOffset = DwordOffset * 4;
558   PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
559                                       AMDGPUAS::PARAM_I_ADDRESS);
560
561   // We shouldn't be using an offset wider than 16-bits for implicit parameters.
562   assert(isInt<16>(ByteOffset));
563
564   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
565                      DAG.getConstant(ByteOffset, MVT::i32), // PTR
566                      MachinePointerInfo(ConstantPointerNull::get(PtrType)),
567                      false, false, false, 0);
568 }
569
570 SDValue R600TargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
571   DebugLoc DL = Op.getDebugLoc();
572   EVT VT = Op.getValueType();
573
574   return DAG.getNode(AMDGPUISD::BITALIGN, DL, VT,
575                      Op.getOperand(0),
576                      Op.getOperand(0),
577                      DAG.getNode(ISD::SUB, DL, VT,
578                                  DAG.getConstant(32, MVT::i32),
579                                  Op.getOperand(1)));
580 }
581
582 bool R600TargetLowering::isZero(SDValue Op) const {
583   if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
584     return Cst->isNullValue();
585   } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
586     return CstFP->isZero();
587   } else {
588     return false;
589   }
590 }
591
592 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
593   DebugLoc DL = Op.getDebugLoc();
594   EVT VT = Op.getValueType();
595
596   SDValue LHS = Op.getOperand(0);
597   SDValue RHS = Op.getOperand(1);
598   SDValue True = Op.getOperand(2);
599   SDValue False = Op.getOperand(3);
600   SDValue CC = Op.getOperand(4);
601   SDValue Temp;
602
603   // LHS and RHS are guaranteed to be the same value type
604   EVT CompareVT = LHS.getValueType();
605
606   // Check if we can lower this to a native operation.
607
608   // Try to lower to a CND* instruction:
609   // CND* instructions requires RHS to be zero.  Some SELECT_CC nodes that
610   // can be lowered to CND* instructions can also be lowered to SET*
611   // instructions.  CND* instructions are cheaper, because they dont't
612   // require additional instructions to convert their result to the correct
613   // value type, so this check should be first.
614   if (isZero(LHS) || isZero(RHS)) {
615     SDValue Cond = (isZero(LHS) ? RHS : LHS);
616     SDValue Zero = (isZero(LHS) ? LHS : RHS);
617     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
618     if (CompareVT != VT) {
619       // Bitcast True / False to the correct types.  This will end up being
620       // a nop, but it allows us to define only a single pattern in the
621       // .TD files for each CND* instruction rather than having to have
622       // one pattern for integer True/False and one for fp True/False
623       True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
624       False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
625     }
626     if (isZero(LHS)) {
627       CCOpcode = ISD::getSetCCSwappedOperands(CCOpcode);
628     }
629
630     switch (CCOpcode) {
631     case ISD::SETONE:
632     case ISD::SETUNE:
633     case ISD::SETNE:
634     case ISD::SETULE:
635     case ISD::SETULT:
636     case ISD::SETOLE:
637     case ISD::SETOLT:
638     case ISD::SETLE:
639     case ISD::SETLT:
640       CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
641       Temp = True;
642       True = False;
643       False = Temp;
644       break;
645     default:
646       break;
647     }
648     SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
649         Cond, Zero,
650         True, False,
651         DAG.getCondCode(CCOpcode));
652     return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
653   }
654
655   // Try to lower to a SET* instruction:
656   // We need all the operands of SELECT_CC to have the same value type, so if
657   // necessary we need to change True and False to be the same type as LHS and
658   // RHS, and then convert the result of the select_cc back to the correct type.
659
660   // Move hardware True/False values to the correct operand.
661   if (isHWTrueValue(False) && isHWFalseValue(True)) {
662     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
663     std::swap(False, True);
664     CC = DAG.getCondCode(ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32));
665   }
666
667   if (isHWTrueValue(True) && isHWFalseValue(False)) {
668     if (CompareVT !=  VT) {
669       if (VT == MVT::f32 && CompareVT == MVT::i32) {
670         SDValue Boolean = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
671             LHS, RHS,
672             DAG.getConstant(-1, MVT::i32),
673             DAG.getConstant(0, MVT::i32),
674             CC);
675         // Convert integer values of true (-1) and false (0) to fp values of
676         // true (1.0f) and false (0.0f).
677         SDValue LSB = DAG.getNode(ISD::AND, DL, MVT::i32, Boolean,
678                                                   DAG.getConstant(1, MVT::i32));
679         return DAG.getNode(ISD::UINT_TO_FP, DL, VT, LSB);
680       } else if (VT == MVT::i32 && CompareVT == MVT::f32) {
681         SDValue BoolAsFlt = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
682             LHS, RHS,
683             DAG.getConstantFP(1.0f, MVT::f32),
684             DAG.getConstantFP(0.0f, MVT::f32),
685             CC);
686         // Convert fp values of true (1.0f) and false (0.0f) to integer values
687         // of true (-1) and false (0).
688         SDValue Neg = DAG.getNode(ISD::FNEG, DL, MVT::f32, BoolAsFlt);
689         return DAG.getNode(ISD::FP_TO_SINT, DL, VT, Neg);
690       } else {
691         // I don't think there will be any other type pairings.
692         assert(!"Unhandled operand type parings in SELECT_CC");
693       }
694     } else {
695       // This SELECT_CC is already legal.
696       return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
697     }
698   }
699
700   // Possible Min/Max pattern
701   SDValue MinMax = LowerMinMax(Op, DAG);
702   if (MinMax.getNode()) {
703     return MinMax;
704   }
705
706   // If we make it this for it means we have no native instructions to handle
707   // this SELECT_CC, so we must lower it.
708   SDValue HWTrue, HWFalse;
709
710   if (CompareVT == MVT::f32) {
711     HWTrue = DAG.getConstantFP(1.0f, CompareVT);
712     HWFalse = DAG.getConstantFP(0.0f, CompareVT);
713   } else if (CompareVT == MVT::i32) {
714     HWTrue = DAG.getConstant(-1, CompareVT);
715     HWFalse = DAG.getConstant(0, CompareVT);
716   }
717   else {
718     assert(!"Unhandled value type in LowerSELECT_CC");
719   }
720
721   // Lower this unsupported SELECT_CC into a combination of two supported
722   // SELECT_CC operations.
723   SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);
724
725   return DAG.getNode(ISD::SELECT_CC, DL, VT,
726       Cond, HWFalse,
727       True, False,
728       DAG.getCondCode(ISD::SETNE));
729 }
730
731 SDValue R600TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
732   return DAG.getNode(ISD::SELECT_CC,
733       Op.getDebugLoc(),
734       Op.getValueType(),
735       Op.getOperand(0),
736       DAG.getConstant(0, MVT::i32),
737       Op.getOperand(1),
738       Op.getOperand(2),
739       DAG.getCondCode(ISD::SETNE));
740 }
741
742 SDValue R600TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
743   SDValue Cond;
744   SDValue LHS = Op.getOperand(0);
745   SDValue RHS = Op.getOperand(1);
746   SDValue CC  = Op.getOperand(2);
747   DebugLoc DL = Op.getDebugLoc();
748   assert(Op.getValueType() == MVT::i32);
749   if (LHS.getValueType() == MVT::i32) {
750     Cond = DAG.getNode(
751         ISD::SELECT_CC,
752         Op.getDebugLoc(),
753         MVT::i32,
754         LHS, RHS,
755         DAG.getConstant(-1, MVT::i32),
756         DAG.getConstant(0, MVT::i32),
757         CC);
758   } else if (LHS.getValueType() == MVT::f32) {
759     Cond = DAG.getNode(
760         ISD::SELECT_CC,
761         Op.getDebugLoc(),
762         MVT::f32,
763         LHS, RHS,
764         DAG.getConstantFP(1.0f, MVT::f32),
765         DAG.getConstantFP(0.0f, MVT::f32),
766         CC);
767     Cond = DAG.getNode(
768         ISD::FP_TO_SINT,
769         DL,
770         MVT::i32,
771         Cond);
772   } else {
773     assert(0 && "Not valid type for set_cc");
774   }
775   Cond = DAG.getNode(
776       ISD::AND,
777       DL,
778       MVT::i32,
779       DAG.getConstant(1, MVT::i32),
780       Cond);
781   return Cond;
782 }
783
784 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
785   DebugLoc DL = Op.getDebugLoc();
786   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
787   SDValue Chain = Op.getOperand(0);
788   SDValue Value = Op.getOperand(1);
789   SDValue Ptr = Op.getOperand(2);
790
791   if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
792       Ptr->getOpcode() != AMDGPUISD::DWORDADDR) {
793     // Convert pointer from byte address to dword address.
794     Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
795                       DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
796                                   Ptr, DAG.getConstant(2, MVT::i32)));
797
798     if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
799       assert(!"Truncated and indexed stores not supported yet");
800     } else {
801       Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
802     }
803     return Chain;
804   }
805   return SDValue();
806 }
807
808 // return (512 + (kc_bank << 12)
809 static int
810 ConstantAddressBlock(unsigned AddressSpace) {
811   switch (AddressSpace) {
812   case AMDGPUAS::CONSTANT_BUFFER_0:
813     return 512;
814   case AMDGPUAS::CONSTANT_BUFFER_1:
815     return 512 + 4096;
816   case AMDGPUAS::CONSTANT_BUFFER_2:
817     return 512 + 4096 * 2;
818   case AMDGPUAS::CONSTANT_BUFFER_3:
819     return 512 + 4096 * 3;
820   case AMDGPUAS::CONSTANT_BUFFER_4:
821     return 512 + 4096 * 4;
822   case AMDGPUAS::CONSTANT_BUFFER_5:
823     return 512 + 4096 * 5;
824   case AMDGPUAS::CONSTANT_BUFFER_6:
825     return 512 + 4096 * 6;
826   case AMDGPUAS::CONSTANT_BUFFER_7:
827     return 512 + 4096 * 7;
828   case AMDGPUAS::CONSTANT_BUFFER_8:
829     return 512 + 4096 * 8;
830   case AMDGPUAS::CONSTANT_BUFFER_9:
831     return 512 + 4096 * 9;
832   case AMDGPUAS::CONSTANT_BUFFER_10:
833     return 512 + 4096 * 10;
834   case AMDGPUAS::CONSTANT_BUFFER_11:
835     return 512 + 4096 * 11;
836   case AMDGPUAS::CONSTANT_BUFFER_12:
837     return 512 + 4096 * 12;
838   case AMDGPUAS::CONSTANT_BUFFER_13:
839     return 512 + 4096 * 13;
840   case AMDGPUAS::CONSTANT_BUFFER_14:
841     return 512 + 4096 * 14;
842   case AMDGPUAS::CONSTANT_BUFFER_15:
843     return 512 + 4096 * 15;
844   default:
845     return -1;
846   }
847 }
848
849 SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
850 {
851   EVT VT = Op.getValueType();
852   DebugLoc DL = Op.getDebugLoc();
853   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
854   SDValue Chain = Op.getOperand(0);
855   SDValue Ptr = Op.getOperand(1);
856   SDValue LoweredLoad;
857
858   int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
859   if (ConstantBlock > -1) {
860     SDValue Result;
861     if (dyn_cast<ConstantExpr>(LoadNode->getSrcValue()) ||
862         dyn_cast<Constant>(LoadNode->getSrcValue())) {
863       SDValue Slots[4];
864       for (unsigned i = 0; i < 4; i++) {
865         // We want Const position encoded with the following formula :
866         // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
867         // const_index is Ptr computed by llvm using an alignment of 16.
868         // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
869         // then div by 4 at the ISel step
870         SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
871             DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
872         Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
873       }
874       Result = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Slots, 4);
875     } else {
876       // non constant ptr cant be folded, keeps it as a v4f32 load
877       Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
878           DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32))
879           );
880     }
881
882     if (!VT.isVector()) {
883       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
884           DAG.getConstant(0, MVT::i32));
885     }
886
887     SDValue MergedValues[2] = {
888         Result,
889         Chain
890     };
891     return DAG.getMergeValues(MergedValues, 2, DL);
892   }
893
894   return SDValue();
895 }
896
897 SDValue R600TargetLowering::LowerFPOW(SDValue Op,
898     SelectionDAG &DAG) const {
899   DebugLoc DL = Op.getDebugLoc();
900   EVT VT = Op.getValueType();
901   SDValue LogBase = DAG.getNode(ISD::FLOG2, DL, VT, Op.getOperand(0));
902   SDValue MulLogBase = DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), LogBase);
903   return DAG.getNode(ISD::FEXP2, DL, VT, MulLogBase);
904 }
905
906 /// XXX Only kernel functions are supported, so we can assume for now that
907 /// every function is a kernel function, but in the future we should use
908 /// separate calling conventions for kernel and non-kernel functions.
909 SDValue R600TargetLowering::LowerFormalArguments(
910                                       SDValue Chain,
911                                       CallingConv::ID CallConv,
912                                       bool isVarArg,
913                                       const SmallVectorImpl<ISD::InputArg> &Ins,
914                                       DebugLoc DL, SelectionDAG &DAG,
915                                       SmallVectorImpl<SDValue> &InVals) const {
916   unsigned ParamOffsetBytes = 36;
917   Function::const_arg_iterator FuncArg =
918                             DAG.getMachineFunction().getFunction()->arg_begin();
919   for (unsigned i = 0, e = Ins.size(); i < e; ++i, ++FuncArg) {
920     EVT VT = Ins[i].VT;
921     Type *ArgType = FuncArg->getType();
922     unsigned ArgSizeInBits = ArgType->isPointerTy() ?
923                              32 : ArgType->getPrimitiveSizeInBits();
924     unsigned ArgBytes = ArgSizeInBits >> 3;
925     EVT ArgVT;
926     if (ArgSizeInBits < VT.getSizeInBits()) {
927       assert(!ArgType->isFloatTy() &&
928              "Extending floating point arguments not supported yet");
929       ArgVT = MVT::getIntegerVT(ArgSizeInBits);
930     } else {
931       ArgVT = VT;
932     }
933     PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
934                                                     AMDGPUAS::PARAM_I_ADDRESS);
935     SDValue Arg = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getRoot(),
936                                 DAG.getConstant(ParamOffsetBytes, MVT::i32),
937                                        MachinePointerInfo(new Argument(PtrTy)),
938                                        ArgVT, false, false, ArgBytes);
939     InVals.push_back(Arg);
940     ParamOffsetBytes += ArgBytes;
941   }
942   return Chain;
943 }
944
945 EVT R600TargetLowering::getSetCCResultType(EVT VT) const {
946    if (!VT.isVector()) return MVT::i32;
947    return VT.changeVectorElementTypeToInteger();
948 }
949
950 //===----------------------------------------------------------------------===//
951 // Custom DAG Optimizations
952 //===----------------------------------------------------------------------===//
953
954 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
955                                               DAGCombinerInfo &DCI) const {
956   SelectionDAG &DAG = DCI.DAG;
957
958   switch (N->getOpcode()) {
959   // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
960   case ISD::FP_ROUND: {
961       SDValue Arg = N->getOperand(0);
962       if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
963         return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), N->getValueType(0),
964                            Arg.getOperand(0));
965       }
966       break;
967     }
968   // Extract_vec (Build_vector) generated by custom lowering
969   // also needs to be customly combined
970   case ISD::EXTRACT_VECTOR_ELT: {
971     SDValue Arg = N->getOperand(0);
972     if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
973       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
974         unsigned Element = Const->getZExtValue();
975         return Arg->getOperand(Element);
976       }
977     }
978   }
979   }
980   return SDValue();
981 }