R600: Expand vselect for v4i32 and v2i32
[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/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Function.h"
25
26 using namespace llvm;
27
28 R600TargetLowering::R600TargetLowering(TargetMachine &TM) :
29     AMDGPUTargetLowering(TM),
30     TII(static_cast<const R600InstrInfo*>(TM.getInstrInfo())) {
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::OR, MVT::v4i32, Expand);
47   setOperationAction(ISD::OR, MVT::v2i32, Expand);
48   setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Expand);
49   setOperationAction(ISD::SHL, MVT::v4i32, Expand);
50   setOperationAction(ISD::SHL, MVT::v2i32, Expand);
51   setOperationAction(ISD::SRL, MVT::v4i32, Expand);
52   setOperationAction(ISD::SRL, MVT::v2i32, Expand);
53   setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Expand);
54   setOperationAction(ISD::UDIV, MVT::v4i32, Expand);
55   setOperationAction(ISD::UREM, MVT::v4i32, Expand);
56   setOperationAction(ISD::SETCC, MVT::v4i32, Expand);
57   setOperationAction(ISD::XOR, MVT::v4i32, Expand);
58   setOperationAction(ISD::XOR, MVT::v2i32, Expand);
59
60   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
61   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
62
63   setOperationAction(ISD::FSUB, MVT::f32, Expand);
64
65   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
66   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
67   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i1, Custom);
68
69   setOperationAction(ISD::ROTL, MVT::i32, Custom);
70
71   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
72   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
73
74   setOperationAction(ISD::SETCC, MVT::i32, Expand);
75   setOperationAction(ISD::SETCC, MVT::f32, Expand);
76   setOperationAction(ISD::FP_TO_UINT, MVT::i1, Custom);
77
78   setOperationAction(ISD::SELECT, MVT::i32, Custom);
79   setOperationAction(ISD::SELECT, MVT::f32, Custom);
80
81   setOperationAction(ISD::VSELECT, MVT::v4i32, Expand);
82   setOperationAction(ISD::VSELECT, MVT::v2i32, Expand);
83
84   // Legalize loads and stores to the private address space.
85   setOperationAction(ISD::LOAD, MVT::i32, Custom);
86   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
87   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
88   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
89   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
90   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
91   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Custom);
92   setOperationAction(ISD::STORE, MVT::i8, Custom);
93   setOperationAction(ISD::STORE, MVT::i32, Custom);
94   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
95   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
96
97   setOperationAction(ISD::LOAD, MVT::i32, Custom);
98   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
99   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
100
101   setTargetDAGCombine(ISD::FP_ROUND);
102   setTargetDAGCombine(ISD::FP_TO_SINT);
103   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
104   setTargetDAGCombine(ISD::SELECT_CC);
105
106   setBooleanContents(ZeroOrNegativeOneBooleanContent);
107   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
108   setSchedulingPreference(Sched::VLIW);
109 }
110
111 MachineBasicBlock * R600TargetLowering::EmitInstrWithCustomInserter(
112     MachineInstr * MI, MachineBasicBlock * BB) const {
113   MachineFunction * MF = BB->getParent();
114   MachineRegisterInfo &MRI = MF->getRegInfo();
115   MachineBasicBlock::iterator I = *MI;
116
117   switch (MI->getOpcode()) {
118   default: return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
119   case AMDGPU::CLAMP_R600: {
120     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
121                                                    AMDGPU::MOV,
122                                                    MI->getOperand(0).getReg(),
123                                                    MI->getOperand(1).getReg());
124     TII->addFlag(NewMI, 0, MO_FLAG_CLAMP);
125     break;
126   }
127
128   case AMDGPU::FABS_R600: {
129     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
130                                                     AMDGPU::MOV,
131                                                     MI->getOperand(0).getReg(),
132                                                     MI->getOperand(1).getReg());
133     TII->addFlag(NewMI, 0, MO_FLAG_ABS);
134     break;
135   }
136
137   case AMDGPU::FNEG_R600: {
138     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
139                                                     AMDGPU::MOV,
140                                                     MI->getOperand(0).getReg(),
141                                                     MI->getOperand(1).getReg());
142     TII->addFlag(NewMI, 0, MO_FLAG_NEG);
143     break;
144   }
145
146   case AMDGPU::MASK_WRITE: {
147     unsigned maskedRegister = MI->getOperand(0).getReg();
148     assert(TargetRegisterInfo::isVirtualRegister(maskedRegister));
149     MachineInstr * defInstr = MRI.getVRegDef(maskedRegister);
150     TII->addFlag(defInstr, 0, MO_FLAG_MASK);
151     break;
152   }
153
154   case AMDGPU::MOV_IMM_F32:
155     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
156                      MI->getOperand(1).getFPImm()->getValueAPF()
157                          .bitcastToAPInt().getZExtValue());
158     break;
159   case AMDGPU::MOV_IMM_I32:
160     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
161                      MI->getOperand(1).getImm());
162     break;
163   case AMDGPU::CONST_COPY: {
164     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, MI, AMDGPU::MOV,
165         MI->getOperand(0).getReg(), AMDGPU::ALU_CONST);
166     TII->setImmOperand(NewMI, R600Operands::SRC0_SEL,
167         MI->getOperand(1).getImm());
168     break;
169   }
170
171   case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
172   case AMDGPU::RAT_WRITE_CACHELESS_128_eg: {
173     unsigned EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;
174
175     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
176             .addOperand(MI->getOperand(0))
177             .addOperand(MI->getOperand(1))
178             .addImm(EOP); // Set End of program bit
179     break;
180   }
181
182   case AMDGPU::TXD: {
183     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
184     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
185
186     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
187             .addOperand(MI->getOperand(3))
188             .addOperand(MI->getOperand(4))
189             .addOperand(MI->getOperand(5))
190             .addOperand(MI->getOperand(6));
191     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
192             .addOperand(MI->getOperand(2))
193             .addOperand(MI->getOperand(4))
194             .addOperand(MI->getOperand(5))
195             .addOperand(MI->getOperand(6));
196     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_G))
197             .addOperand(MI->getOperand(0))
198             .addOperand(MI->getOperand(1))
199             .addOperand(MI->getOperand(4))
200             .addOperand(MI->getOperand(5))
201             .addOperand(MI->getOperand(6))
202             .addReg(T0, RegState::Implicit)
203             .addReg(T1, RegState::Implicit);
204     break;
205   }
206
207   case AMDGPU::TXD_SHADOW: {
208     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
209     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
210
211     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
212             .addOperand(MI->getOperand(3))
213             .addOperand(MI->getOperand(4))
214             .addOperand(MI->getOperand(5))
215             .addOperand(MI->getOperand(6));
216     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
217             .addOperand(MI->getOperand(2))
218             .addOperand(MI->getOperand(4))
219             .addOperand(MI->getOperand(5))
220             .addOperand(MI->getOperand(6));
221     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_C_G))
222             .addOperand(MI->getOperand(0))
223             .addOperand(MI->getOperand(1))
224             .addOperand(MI->getOperand(4))
225             .addOperand(MI->getOperand(5))
226             .addOperand(MI->getOperand(6))
227             .addReg(T0, RegState::Implicit)
228             .addReg(T1, RegState::Implicit);
229     break;
230   }
231
232   case AMDGPU::BRANCH:
233       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
234               .addOperand(MI->getOperand(0));
235       break;
236
237   case AMDGPU::BRANCH_COND_f32: {
238     MachineInstr *NewMI =
239       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
240               AMDGPU::PREDICATE_BIT)
241               .addOperand(MI->getOperand(1))
242               .addImm(OPCODE_IS_NOT_ZERO)
243               .addImm(0); // Flags
244     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
245     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP_COND))
246             .addOperand(MI->getOperand(0))
247             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
248     break;
249   }
250
251   case AMDGPU::BRANCH_COND_i32: {
252     MachineInstr *NewMI =
253       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
254             AMDGPU::PREDICATE_BIT)
255             .addOperand(MI->getOperand(1))
256             .addImm(OPCODE_IS_NOT_ZERO_INT)
257             .addImm(0); // Flags
258     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
259     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP_COND))
260            .addOperand(MI->getOperand(0))
261             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
262     break;
263   }
264
265   case AMDGPU::EG_ExportSwz:
266   case AMDGPU::R600_ExportSwz: {
267     // Instruction is left unmodified if its not the last one of its type
268     bool isLastInstructionOfItsType = true;
269     unsigned InstExportType = MI->getOperand(1).getImm();
270     for (MachineBasicBlock::iterator NextExportInst = llvm::next(I),
271          EndBlock = BB->end(); NextExportInst != EndBlock;
272          NextExportInst = llvm::next(NextExportInst)) {
273       if (NextExportInst->getOpcode() == AMDGPU::EG_ExportSwz ||
274           NextExportInst->getOpcode() == AMDGPU::R600_ExportSwz) {
275         unsigned CurrentInstExportType = NextExportInst->getOperand(1)
276             .getImm();
277         if (CurrentInstExportType == InstExportType) {
278           isLastInstructionOfItsType = false;
279           break;
280         }
281       }
282     }
283     bool EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN)? 1 : 0;
284     if (!EOP && !isLastInstructionOfItsType)
285       return BB;
286     unsigned CfInst = (MI->getOpcode() == AMDGPU::EG_ExportSwz)? 84 : 40;
287     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
288             .addOperand(MI->getOperand(0))
289             .addOperand(MI->getOperand(1))
290             .addOperand(MI->getOperand(2))
291             .addOperand(MI->getOperand(3))
292             .addOperand(MI->getOperand(4))
293             .addOperand(MI->getOperand(5))
294             .addOperand(MI->getOperand(6))
295             .addImm(CfInst)
296             .addImm(EOP);
297     break;
298   }
299   case AMDGPU::RETURN: {
300     // RETURN instructions must have the live-out registers as implicit uses,
301     // otherwise they appear dead.
302     R600MachineFunctionInfo *MFI = MF->getInfo<R600MachineFunctionInfo>();
303     MachineInstrBuilder MIB(*MF, MI);
304     for (unsigned i = 0, e = MFI->LiveOuts.size(); i != e; ++i)
305       MIB.addReg(MFI->LiveOuts[i], RegState::Implicit);
306     return BB;
307   }
308   }
309
310   MI->eraseFromParent();
311   return BB;
312 }
313
314 //===----------------------------------------------------------------------===//
315 // Custom DAG Lowering Operations
316 //===----------------------------------------------------------------------===//
317
318 using namespace llvm::Intrinsic;
319 using namespace llvm::AMDGPUIntrinsic;
320
321 SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
322   switch (Op.getOpcode()) {
323   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
324   case ISD::ROTL: return LowerROTL(Op, DAG);
325   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
326   case ISD::SELECT: return LowerSELECT(Op, DAG);
327   case ISD::STORE: return LowerSTORE(Op, DAG);
328   case ISD::LOAD: return LowerLOAD(Op, DAG);
329   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
330   case ISD::INTRINSIC_VOID: {
331     SDValue Chain = Op.getOperand(0);
332     unsigned IntrinsicID =
333                          cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
334     switch (IntrinsicID) {
335     case AMDGPUIntrinsic::AMDGPU_store_output: {
336       MachineFunction &MF = DAG.getMachineFunction();
337       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
338       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
339       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
340       MFI->LiveOuts.push_back(Reg);
341       return DAG.getCopyToReg(Chain, Op.getDebugLoc(), Reg, Op.getOperand(2));
342     }
343     case AMDGPUIntrinsic::R600_store_swizzle: {
344       const SDValue Args[8] = {
345         Chain,
346         Op.getOperand(2), // Export Value
347         Op.getOperand(3), // ArrayBase
348         Op.getOperand(4), // Type
349         DAG.getConstant(0, MVT::i32), // SWZ_X
350         DAG.getConstant(1, MVT::i32), // SWZ_Y
351         DAG.getConstant(2, MVT::i32), // SWZ_Z
352         DAG.getConstant(3, MVT::i32) // SWZ_W
353       };
354       return DAG.getNode(AMDGPUISD::EXPORT, Op.getDebugLoc(), Op.getValueType(),
355           Args, 8);
356     }
357
358     // default for switch(IntrinsicID)
359     default: break;
360     }
361     // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
362     break;
363   }
364   case ISD::INTRINSIC_WO_CHAIN: {
365     unsigned IntrinsicID =
366                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
367     EVT VT = Op.getValueType();
368     DebugLoc DL = Op.getDebugLoc();
369     switch(IntrinsicID) {
370     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
371     case AMDGPUIntrinsic::R600_load_input: {
372       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
373       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
374       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass, Reg, VT);
375     }
376
377     case AMDGPUIntrinsic::R600_interp_input: {
378       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
379       int ijb = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
380       MachineSDNode *interp;
381       if (ijb < 0) {
382         interp = DAG.getMachineNode(AMDGPU::INTERP_VEC_LOAD, DL,
383             MVT::v4f32, DAG.getTargetConstant(slot / 4 , MVT::i32));
384         return DAG.getTargetExtractSubreg(
385             TII->getRegisterInfo().getSubRegFromChannel(slot % 4),
386             DL, MVT::f32, SDValue(interp, 0));
387       }
388
389       if (slot % 4 < 2)
390         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
391             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
392             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
393                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
394             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
395                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
396       else
397         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
398             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
399             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
400                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
401             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
402                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
403
404       return SDValue(interp, slot % 2);
405     }
406
407     case r600_read_ngroups_x:
408       return LowerImplicitParameter(DAG, VT, DL, 0);
409     case r600_read_ngroups_y:
410       return LowerImplicitParameter(DAG, VT, DL, 1);
411     case r600_read_ngroups_z:
412       return LowerImplicitParameter(DAG, VT, DL, 2);
413     case r600_read_global_size_x:
414       return LowerImplicitParameter(DAG, VT, DL, 3);
415     case r600_read_global_size_y:
416       return LowerImplicitParameter(DAG, VT, DL, 4);
417     case r600_read_global_size_z:
418       return LowerImplicitParameter(DAG, VT, DL, 5);
419     case r600_read_local_size_x:
420       return LowerImplicitParameter(DAG, VT, DL, 6);
421     case r600_read_local_size_y:
422       return LowerImplicitParameter(DAG, VT, DL, 7);
423     case r600_read_local_size_z:
424       return LowerImplicitParameter(DAG, VT, DL, 8);
425
426     case r600_read_tgid_x:
427       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
428                                   AMDGPU::T1_X, VT);
429     case r600_read_tgid_y:
430       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
431                                   AMDGPU::T1_Y, VT);
432     case r600_read_tgid_z:
433       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
434                                   AMDGPU::T1_Z, VT);
435     case r600_read_tidig_x:
436       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
437                                   AMDGPU::T0_X, VT);
438     case r600_read_tidig_y:
439       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
440                                   AMDGPU::T0_Y, VT);
441     case r600_read_tidig_z:
442       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
443                                   AMDGPU::T0_Z, VT);
444     }
445     // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
446     break;
447   }
448   } // end switch(Op.getOpcode())
449   return SDValue();
450 }
451
452 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
453                                             SmallVectorImpl<SDValue> &Results,
454                                             SelectionDAG &DAG) const {
455   switch (N->getOpcode()) {
456   default: return;
457   case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
458     return;
459   case ISD::LOAD: {
460     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
461     Results.push_back(SDValue(Node, 0));
462     Results.push_back(SDValue(Node, 1));
463     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
464     // function
465     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
466     return;
467   }
468   case ISD::STORE:
469     SDNode *Node = LowerSTORE(SDValue(N, 0), DAG).getNode();
470     Results.push_back(SDValue(Node, 0));
471     return;
472   }
473 }
474
475 SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
476   return DAG.getNode(
477       ISD::SETCC,
478       Op.getDebugLoc(),
479       MVT::i1,
480       Op, DAG.getConstantFP(0.0f, MVT::f32),
481       DAG.getCondCode(ISD::SETNE)
482       );
483 }
484
485 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
486                                                    DebugLoc DL,
487                                                    unsigned DwordOffset) const {
488   unsigned ByteOffset = DwordOffset * 4;
489   PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
490                                       AMDGPUAS::PARAM_I_ADDRESS);
491
492   // We shouldn't be using an offset wider than 16-bits for implicit parameters.
493   assert(isInt<16>(ByteOffset));
494
495   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
496                      DAG.getConstant(ByteOffset, MVT::i32), // PTR
497                      MachinePointerInfo(ConstantPointerNull::get(PtrType)),
498                      false, false, false, 0);
499 }
500
501 SDValue R600TargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
502
503   MachineFunction &MF = DAG.getMachineFunction();
504   const AMDGPUFrameLowering *TFL =
505    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
506
507   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
508   assert(FIN);
509
510   unsigned FrameIndex = FIN->getIndex();
511   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
512   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF), MVT::i32);
513 }
514
515 SDValue R600TargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
516   DebugLoc DL = Op.getDebugLoc();
517   EVT VT = Op.getValueType();
518
519   return DAG.getNode(AMDGPUISD::BITALIGN, DL, VT,
520                      Op.getOperand(0),
521                      Op.getOperand(0),
522                      DAG.getNode(ISD::SUB, DL, VT,
523                                  DAG.getConstant(32, MVT::i32),
524                                  Op.getOperand(1)));
525 }
526
527 bool R600TargetLowering::isZero(SDValue Op) const {
528   if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
529     return Cst->isNullValue();
530   } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
531     return CstFP->isZero();
532   } else {
533     return false;
534   }
535 }
536
537 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
538   DebugLoc DL = Op.getDebugLoc();
539   EVT VT = Op.getValueType();
540
541   SDValue LHS = Op.getOperand(0);
542   SDValue RHS = Op.getOperand(1);
543   SDValue True = Op.getOperand(2);
544   SDValue False = Op.getOperand(3);
545   SDValue CC = Op.getOperand(4);
546   SDValue Temp;
547
548   // LHS and RHS are guaranteed to be the same value type
549   EVT CompareVT = LHS.getValueType();
550
551   // Check if we can lower this to a native operation.
552
553   // Try to lower to a SET* instruction:
554   //
555   // SET* can match the following patterns:
556   //
557   // select_cc f32, f32, -1,  0, cc_any
558   // select_cc f32, f32, 1.0f, 0.0f, cc_any
559   // select_cc i32, i32, -1,  0, cc_any
560   //
561
562   // Move hardware True/False values to the correct operand.
563   if (isHWTrueValue(False) && isHWFalseValue(True)) {
564     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
565     std::swap(False, True);
566     CC = DAG.getCondCode(ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32));
567   }
568
569   if (isHWTrueValue(True) && isHWFalseValue(False) &&
570       (CompareVT == VT || VT == MVT::i32)) {
571     // This can be matched by a SET* instruction.
572     return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
573   }
574
575   // Try to lower to a CND* instruction:
576   //
577   // CND* can match the following patterns:
578   //
579   // select_cc f32, 0.0, f32, f32, cc_any
580   // select_cc f32, 0.0, i32, i32, cc_any
581   // select_cc i32, 0,   f32, f32, cc_any
582   // select_cc i32, 0,   i32, i32, cc_any
583   //
584   if (isZero(LHS) || isZero(RHS)) {
585     SDValue Cond = (isZero(LHS) ? RHS : LHS);
586     SDValue Zero = (isZero(LHS) ? LHS : RHS);
587     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
588     if (CompareVT != VT) {
589       // Bitcast True / False to the correct types.  This will end up being
590       // a nop, but it allows us to define only a single pattern in the
591       // .TD files for each CND* instruction rather than having to have
592       // one pattern for integer True/False and one for fp True/False
593       True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
594       False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
595     }
596     if (isZero(LHS)) {
597       CCOpcode = ISD::getSetCCSwappedOperands(CCOpcode);
598     }
599
600     switch (CCOpcode) {
601     case ISD::SETONE:
602     case ISD::SETUNE:
603     case ISD::SETNE:
604     case ISD::SETULE:
605     case ISD::SETULT:
606     case ISD::SETOLE:
607     case ISD::SETOLT:
608     case ISD::SETLE:
609     case ISD::SETLT:
610       CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
611       Temp = True;
612       True = False;
613       False = Temp;
614       break;
615     default:
616       break;
617     }
618     SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
619         Cond, Zero,
620         True, False,
621         DAG.getCondCode(CCOpcode));
622     return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
623   }
624
625
626   // Possible Min/Max pattern
627   SDValue MinMax = LowerMinMax(Op, DAG);
628   if (MinMax.getNode()) {
629     return MinMax;
630   }
631
632   // If we make it this for it means we have no native instructions to handle
633   // this SELECT_CC, so we must lower it.
634   SDValue HWTrue, HWFalse;
635
636   if (CompareVT == MVT::f32) {
637     HWTrue = DAG.getConstantFP(1.0f, CompareVT);
638     HWFalse = DAG.getConstantFP(0.0f, CompareVT);
639   } else if (CompareVT == MVT::i32) {
640     HWTrue = DAG.getConstant(-1, CompareVT);
641     HWFalse = DAG.getConstant(0, CompareVT);
642   }
643   else {
644     assert(!"Unhandled value type in LowerSELECT_CC");
645   }
646
647   // Lower this unsupported SELECT_CC into a combination of two supported
648   // SELECT_CC operations.
649   SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);
650
651   return DAG.getNode(ISD::SELECT_CC, DL, VT,
652       Cond, HWFalse,
653       True, False,
654       DAG.getCondCode(ISD::SETNE));
655 }
656
657 SDValue R600TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
658   return DAG.getNode(ISD::SELECT_CC,
659       Op.getDebugLoc(),
660       Op.getValueType(),
661       Op.getOperand(0),
662       DAG.getConstant(0, MVT::i32),
663       Op.getOperand(1),
664       Op.getOperand(2),
665       DAG.getCondCode(ISD::SETNE));
666 }
667
668 /// LLVM generates byte-addresed pointers.  For indirect addressing, we need to
669 /// convert these pointers to a register index.  Each register holds
670 /// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
671 /// \p StackWidth, which tells us how many of the 4 sub-registrers will be used
672 /// for indirect addressing.
673 SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
674                                                unsigned StackWidth,
675                                                SelectionDAG &DAG) const {
676   unsigned SRLPad;
677   switch(StackWidth) {
678   case 1:
679     SRLPad = 2;
680     break;
681   case 2:
682     SRLPad = 3;
683     break;
684   case 4:
685     SRLPad = 4;
686     break;
687   default: llvm_unreachable("Invalid stack width");
688   }
689
690   return DAG.getNode(ISD::SRL, Ptr.getDebugLoc(), Ptr.getValueType(), Ptr,
691                      DAG.getConstant(SRLPad, MVT::i32));
692 }
693
694 void R600TargetLowering::getStackAddress(unsigned StackWidth,
695                                          unsigned ElemIdx,
696                                          unsigned &Channel,
697                                          unsigned &PtrIncr) const {
698   switch (StackWidth) {
699   default:
700   case 1:
701     Channel = 0;
702     if (ElemIdx > 0) {
703       PtrIncr = 1;
704     } else {
705       PtrIncr = 0;
706     }
707     break;
708   case 2:
709     Channel = ElemIdx % 2;
710     if (ElemIdx == 2) {
711       PtrIncr = 1;
712     } else {
713       PtrIncr = 0;
714     }
715     break;
716   case 4:
717     Channel = ElemIdx;
718     PtrIncr = 0;
719     break;
720   }
721 }
722
723 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
724   DebugLoc DL = Op.getDebugLoc();
725   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
726   SDValue Chain = Op.getOperand(0);
727   SDValue Value = Op.getOperand(1);
728   SDValue Ptr = Op.getOperand(2);
729
730   if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
731       Ptr->getOpcode() != AMDGPUISD::DWORDADDR) {
732     // Convert pointer from byte address to dword address.
733     Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
734                       DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
735                                   Ptr, DAG.getConstant(2, MVT::i32)));
736
737     if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
738       assert(!"Truncated and indexed stores not supported yet");
739     } else {
740       Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
741     }
742     return Chain;
743   }
744
745   EVT ValueVT = Value.getValueType();
746
747   if (StoreNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
748     return SDValue();
749   }
750
751   // Lowering for indirect addressing
752
753   const MachineFunction &MF = DAG.getMachineFunction();
754   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
755                                          getTargetMachine().getFrameLowering());
756   unsigned StackWidth = TFL->getStackWidth(MF);
757
758   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
759
760   if (ValueVT.isVector()) {
761     unsigned NumElemVT = ValueVT.getVectorNumElements();
762     EVT ElemVT = ValueVT.getVectorElementType();
763     SDValue Stores[4];
764
765     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
766                                       "vector width in load");
767
768     for (unsigned i = 0; i < NumElemVT; ++i) {
769       unsigned Channel, PtrIncr;
770       getStackAddress(StackWidth, i, Channel, PtrIncr);
771       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
772                         DAG.getConstant(PtrIncr, MVT::i32));
773       SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT,
774                                  Value, DAG.getConstant(i, MVT::i32));
775
776       Stores[i] = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
777                               Chain, Elem, Ptr,
778                               DAG.getTargetConstant(Channel, MVT::i32));
779     }
780      Chain =  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores, NumElemVT);
781    } else {
782     if (ValueVT == MVT::i8) {
783       Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Value);
784     }
785     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other, Chain, Value, Ptr,
786     DAG.getTargetConstant(0, MVT::i32)); // Channel 
787   }
788
789   return Chain;
790 }
791
792 // return (512 + (kc_bank << 12)
793 static int
794 ConstantAddressBlock(unsigned AddressSpace) {
795   switch (AddressSpace) {
796   case AMDGPUAS::CONSTANT_BUFFER_0:
797     return 512;
798   case AMDGPUAS::CONSTANT_BUFFER_1:
799     return 512 + 4096;
800   case AMDGPUAS::CONSTANT_BUFFER_2:
801     return 512 + 4096 * 2;
802   case AMDGPUAS::CONSTANT_BUFFER_3:
803     return 512 + 4096 * 3;
804   case AMDGPUAS::CONSTANT_BUFFER_4:
805     return 512 + 4096 * 4;
806   case AMDGPUAS::CONSTANT_BUFFER_5:
807     return 512 + 4096 * 5;
808   case AMDGPUAS::CONSTANT_BUFFER_6:
809     return 512 + 4096 * 6;
810   case AMDGPUAS::CONSTANT_BUFFER_7:
811     return 512 + 4096 * 7;
812   case AMDGPUAS::CONSTANT_BUFFER_8:
813     return 512 + 4096 * 8;
814   case AMDGPUAS::CONSTANT_BUFFER_9:
815     return 512 + 4096 * 9;
816   case AMDGPUAS::CONSTANT_BUFFER_10:
817     return 512 + 4096 * 10;
818   case AMDGPUAS::CONSTANT_BUFFER_11:
819     return 512 + 4096 * 11;
820   case AMDGPUAS::CONSTANT_BUFFER_12:
821     return 512 + 4096 * 12;
822   case AMDGPUAS::CONSTANT_BUFFER_13:
823     return 512 + 4096 * 13;
824   case AMDGPUAS::CONSTANT_BUFFER_14:
825     return 512 + 4096 * 14;
826   case AMDGPUAS::CONSTANT_BUFFER_15:
827     return 512 + 4096 * 15;
828   default:
829     return -1;
830   }
831 }
832
833 SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
834 {
835   EVT VT = Op.getValueType();
836   DebugLoc DL = Op.getDebugLoc();
837   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
838   SDValue Chain = Op.getOperand(0);
839   SDValue Ptr = Op.getOperand(1);
840   SDValue LoweredLoad;
841
842   int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
843   if (ConstantBlock > -1) {
844     SDValue Result;
845     if (dyn_cast<ConstantExpr>(LoadNode->getSrcValue()) ||
846         dyn_cast<Constant>(LoadNode->getSrcValue()) ||
847         dyn_cast<ConstantSDNode>(Ptr)) {
848       SDValue Slots[4];
849       for (unsigned i = 0; i < 4; i++) {
850         // We want Const position encoded with the following formula :
851         // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
852         // const_index is Ptr computed by llvm using an alignment of 16.
853         // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
854         // then div by 4 at the ISel step
855         SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
856             DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
857         Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
858       }
859       Result = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Slots, 4);
860     } else {
861       // non constant ptr cant be folded, keeps it as a v4f32 load
862       Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
863           DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32)),
864           DAG.getConstant(LoadNode->getAddressSpace() -
865                           AMDGPUAS::CONSTANT_BUFFER_0, MVT::i32)
866           );
867     }
868
869     if (!VT.isVector()) {
870       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
871           DAG.getConstant(0, MVT::i32));
872     }
873
874     SDValue MergedValues[2] = {
875         Result,
876         Chain
877     };
878     return DAG.getMergeValues(MergedValues, 2, DL);
879   }
880
881   if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
882     return SDValue();
883   }
884
885   // Lowering for indirect addressing
886   const MachineFunction &MF = DAG.getMachineFunction();
887   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
888                                          getTargetMachine().getFrameLowering());
889   unsigned StackWidth = TFL->getStackWidth(MF);
890
891   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
892
893   if (VT.isVector()) {
894     unsigned NumElemVT = VT.getVectorNumElements();
895     EVT ElemVT = VT.getVectorElementType();
896     SDValue Loads[4];
897
898     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
899                                       "vector width in load");
900
901     for (unsigned i = 0; i < NumElemVT; ++i) {
902       unsigned Channel, PtrIncr;
903       getStackAddress(StackWidth, i, Channel, PtrIncr);
904       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
905                         DAG.getConstant(PtrIncr, MVT::i32));
906       Loads[i] = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, ElemVT,
907                              Chain, Ptr,
908                              DAG.getTargetConstant(Channel, MVT::i32),
909                              Op.getOperand(2));
910     }
911     for (unsigned i = NumElemVT; i < 4; ++i) {
912       Loads[i] = DAG.getUNDEF(ElemVT);
913     }
914     EVT TargetVT = EVT::getVectorVT(*DAG.getContext(), ElemVT, 4);
915     LoweredLoad = DAG.getNode(ISD::BUILD_VECTOR, DL, TargetVT, Loads, 4);
916   } else {
917     LoweredLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, VT,
918                               Chain, Ptr,
919                               DAG.getTargetConstant(0, MVT::i32), // Channel
920                               Op.getOperand(2));
921   }
922
923   SDValue Ops[2];
924   Ops[0] = LoweredLoad;
925   Ops[1] = Chain;
926
927   return DAG.getMergeValues(Ops, 2, DL);
928 }
929
930 /// XXX Only kernel functions are supported, so we can assume for now that
931 /// every function is a kernel function, but in the future we should use
932 /// separate calling conventions for kernel and non-kernel functions.
933 SDValue R600TargetLowering::LowerFormalArguments(
934                                       SDValue Chain,
935                                       CallingConv::ID CallConv,
936                                       bool isVarArg,
937                                       const SmallVectorImpl<ISD::InputArg> &Ins,
938                                       DebugLoc DL, SelectionDAG &DAG,
939                                       SmallVectorImpl<SDValue> &InVals) const {
940   unsigned ParamOffsetBytes = 36;
941   Function::const_arg_iterator FuncArg =
942                             DAG.getMachineFunction().getFunction()->arg_begin();
943   for (unsigned i = 0, e = Ins.size(); i < e; ++i, ++FuncArg) {
944     EVT VT = Ins[i].VT;
945     Type *ArgType = FuncArg->getType();
946     unsigned ArgSizeInBits = ArgType->isPointerTy() ?
947                              32 : ArgType->getPrimitiveSizeInBits();
948     unsigned ArgBytes = ArgSizeInBits >> 3;
949     EVT ArgVT;
950     if (ArgSizeInBits < VT.getSizeInBits()) {
951       assert(!ArgType->isFloatTy() &&
952              "Extending floating point arguments not supported yet");
953       ArgVT = MVT::getIntegerVT(ArgSizeInBits);
954     } else {
955       ArgVT = VT;
956     }
957     PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
958                                                     AMDGPUAS::PARAM_I_ADDRESS);
959     SDValue Arg = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getRoot(),
960                                 DAG.getConstant(ParamOffsetBytes, MVT::i32),
961                                        MachinePointerInfo(UndefValue::get(PtrTy)),
962                                        ArgVT, false, false, ArgBytes);
963     InVals.push_back(Arg);
964     ParamOffsetBytes += ArgBytes;
965   }
966   return Chain;
967 }
968
969 EVT R600TargetLowering::getSetCCResultType(EVT VT) const {
970    if (!VT.isVector()) return MVT::i32;
971    return VT.changeVectorElementTypeToInteger();
972 }
973
974 //===----------------------------------------------------------------------===//
975 // Custom DAG Optimizations
976 //===----------------------------------------------------------------------===//
977
978 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
979                                               DAGCombinerInfo &DCI) const {
980   SelectionDAG &DAG = DCI.DAG;
981
982   switch (N->getOpcode()) {
983   // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
984   case ISD::FP_ROUND: {
985       SDValue Arg = N->getOperand(0);
986       if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
987         return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), N->getValueType(0),
988                            Arg.getOperand(0));
989       }
990       break;
991     }
992
993   // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
994   // (i32 select_cc f32, f32, -1, 0 cc)
995   //
996   // Mesa's GLSL frontend generates the above pattern a lot and we can lower
997   // this to one of the SET*_DX10 instructions.
998   case ISD::FP_TO_SINT: {
999     SDValue FNeg = N->getOperand(0);
1000     if (FNeg.getOpcode() != ISD::FNEG) {
1001       return SDValue();
1002     }
1003     SDValue SelectCC = FNeg.getOperand(0);
1004     if (SelectCC.getOpcode() != ISD::SELECT_CC ||
1005         SelectCC.getOperand(0).getValueType() != MVT::f32 || // LHS
1006         SelectCC.getOperand(2).getValueType() != MVT::f32 || // True
1007         !isHWTrueValue(SelectCC.getOperand(2)) ||
1008         !isHWFalseValue(SelectCC.getOperand(3))) {
1009       return SDValue();
1010     }
1011
1012     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N->getValueType(0),
1013                            SelectCC.getOperand(0), // LHS
1014                            SelectCC.getOperand(1), // RHS
1015                            DAG.getConstant(-1, MVT::i32), // True
1016                            DAG.getConstant(0, MVT::i32),  // Flase
1017                            SelectCC.getOperand(4)); // CC
1018
1019     break;
1020   }
1021   // Extract_vec (Build_vector) generated by custom lowering
1022   // also needs to be customly combined
1023   case ISD::EXTRACT_VECTOR_ELT: {
1024     SDValue Arg = N->getOperand(0);
1025     if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
1026       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1027         unsigned Element = Const->getZExtValue();
1028         return Arg->getOperand(Element);
1029       }
1030     }
1031     if (Arg.getOpcode() == ISD::BITCAST &&
1032         Arg.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
1033       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1034         unsigned Element = Const->getZExtValue();
1035         return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getVTList(),
1036             Arg->getOperand(0).getOperand(Element));
1037       }
1038     }
1039   }
1040
1041   case ISD::SELECT_CC: {
1042     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1043     //      selectcc x, y, a, b, inv(cc)
1044     //
1045     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, setne ->
1046     //      selectcc x, y, a, b, cc
1047     SDValue LHS = N->getOperand(0);
1048     if (LHS.getOpcode() != ISD::SELECT_CC) {
1049       return SDValue();
1050     }
1051
1052     SDValue RHS = N->getOperand(1);
1053     SDValue True = N->getOperand(2);
1054     SDValue False = N->getOperand(3);
1055     ISD::CondCode NCC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1056
1057     if (LHS.getOperand(2).getNode() != True.getNode() ||
1058         LHS.getOperand(3).getNode() != False.getNode() ||
1059         RHS.getNode() != False.getNode()) {
1060       return SDValue();
1061     }
1062
1063     switch (NCC) {
1064     default: return SDValue();
1065     case ISD::SETNE: return LHS;
1066     case ISD::SETEQ: {
1067       ISD::CondCode LHSCC = cast<CondCodeSDNode>(LHS.getOperand(4))->get();
1068       LHSCC = ISD::getSetCCInverse(LHSCC,
1069                                   LHS.getOperand(0).getValueType().isInteger());
1070       return DAG.getSelectCC(N->getDebugLoc(),
1071                              LHS.getOperand(0),
1072                              LHS.getOperand(1),
1073                              LHS.getOperand(2),
1074                              LHS.getOperand(3),
1075                              LHSCC);
1076     }
1077     }
1078   }
1079   case AMDGPUISD::EXPORT: {
1080     SDValue Arg = N->getOperand(1);
1081     if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1082       break;
1083     SDValue NewBldVec[4] = {
1084         DAG.getUNDEF(MVT::f32),
1085         DAG.getUNDEF(MVT::f32),
1086         DAG.getUNDEF(MVT::f32),
1087         DAG.getUNDEF(MVT::f32)
1088       };
1089     SDValue NewArgs[8] = {
1090       N->getOperand(0), // Chain
1091       SDValue(),
1092       N->getOperand(2), // ArrayBase
1093       N->getOperand(3), // Type
1094       N->getOperand(4), // SWZ_X
1095       N->getOperand(5), // SWZ_Y
1096       N->getOperand(6), // SWZ_Z
1097       N->getOperand(7) // SWZ_W
1098     };
1099     for (unsigned i = 0; i < Arg.getNumOperands(); i++) {
1100       if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Arg.getOperand(i))) {
1101         if (C->isZero()) {
1102           NewArgs[4 + i] = DAG.getConstant(4, MVT::i32); // SEL_0
1103         } else if (C->isExactlyValue(1.0)) {
1104           NewArgs[4 + i] = DAG.getConstant(5, MVT::i32); // SEL_0
1105         } else {
1106           NewBldVec[i] = Arg.getOperand(i);
1107         }
1108       } else {
1109         NewBldVec[i] = Arg.getOperand(i);
1110       }
1111     }
1112     DebugLoc DL = N->getDebugLoc();
1113     NewArgs[1] = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4f32, NewBldVec, 4);
1114     return DAG.getNode(AMDGPUISD::EXPORT, DL, N->getVTList(), NewArgs, 8);
1115   }
1116   }
1117   return SDValue();
1118 }