R600: Don't crash on unhandled instruction in promote alloca
[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 "AMDGPUFrameLowering.h"
17 #include "AMDGPUIntrinsicInfo.h"
18 #include "AMDGPUSubtarget.h"
19 #include "R600Defines.h"
20 #include "R600InstrInfo.h"
21 #include "R600MachineFunctionInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/IR/Argument.h"
28 #include "llvm/IR/Function.h"
29
30 using namespace llvm;
31
32 R600TargetLowering::R600TargetLowering(TargetMachine &TM) :
33     AMDGPUTargetLowering(TM),
34     Gen(TM.getSubtarget<AMDGPUSubtarget>().getGeneration()) {
35   addRegisterClass(MVT::v4f32, &AMDGPU::R600_Reg128RegClass);
36   addRegisterClass(MVT::f32, &AMDGPU::R600_Reg32RegClass);
37   addRegisterClass(MVT::v4i32, &AMDGPU::R600_Reg128RegClass);
38   addRegisterClass(MVT::i32, &AMDGPU::R600_Reg32RegClass);
39   addRegisterClass(MVT::v2f32, &AMDGPU::R600_Reg64RegClass);
40   addRegisterClass(MVT::v2i32, &AMDGPU::R600_Reg64RegClass);
41
42   computeRegisterProperties();
43
44   // Set condition code actions
45   setCondCodeAction(ISD::SETO,   MVT::f32, Expand);
46   setCondCodeAction(ISD::SETUO,  MVT::f32, Expand);
47   setCondCodeAction(ISD::SETLT,  MVT::f32, Expand);
48   setCondCodeAction(ISD::SETLE,  MVT::f32, Expand);
49   setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
50   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
51   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
52   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
53   setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
54   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
55   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
56   setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
57
58   setCondCodeAction(ISD::SETLE, MVT::i32, Expand);
59   setCondCodeAction(ISD::SETLT, MVT::i32, Expand);
60   setCondCodeAction(ISD::SETULE, MVT::i32, Expand);
61   setCondCodeAction(ISD::SETULT, MVT::i32, Expand);
62
63   setOperationAction(ISD::FCOS, MVT::f32, Custom);
64   setOperationAction(ISD::FSIN, MVT::f32, Custom);
65
66   setOperationAction(ISD::SETCC, MVT::v4i32, Expand);
67   setOperationAction(ISD::SETCC, MVT::v2i32, Expand);
68
69   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
70   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
71   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
72
73   setOperationAction(ISD::FSUB, MVT::f32, Expand);
74
75   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
76   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
77   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i1, Custom);
78
79   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
80   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
81
82   setOperationAction(ISD::SETCC, MVT::i32, Expand);
83   setOperationAction(ISD::SETCC, MVT::f32, Expand);
84   setOperationAction(ISD::FP_TO_UINT, MVT::i1, Custom);
85
86   setOperationAction(ISD::SELECT, MVT::i32, Expand);
87   setOperationAction(ISD::SELECT, MVT::f32, Expand);
88   setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
89   setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
90
91   // Expand sign extension of vectors
92   if (!Subtarget->hasBFE())
93     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
94
95   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Expand);
96   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Expand);
97
98   if (!Subtarget->hasBFE())
99     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
100   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Expand);
101   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Expand);
102
103   if (!Subtarget->hasBFE())
104     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
105   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Expand);
106   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Expand);
107
108   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
109   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Expand);
110   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Expand);
111
112   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Expand);
113
114
115   // Legalize loads and stores to the private address space.
116   setOperationAction(ISD::LOAD, MVT::i32, Custom);
117   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
118   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
119
120   // EXTLOAD should be the same as ZEXTLOAD. It is legal for some address
121   // spaces, so it is custom lowered to handle those where it isn't.
122   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
123   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
124   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
125   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
126   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
127   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
128
129   setOperationAction(ISD::STORE, MVT::i8, Custom);
130   setOperationAction(ISD::STORE, MVT::i32, Custom);
131   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
132   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
133   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
134   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
135
136   setOperationAction(ISD::LOAD, MVT::i32, Custom);
137   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
138   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
139
140   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i32, Custom);
141   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f32, Custom);
142   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
143   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
144
145   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i32, Custom);
146   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f32, Custom);
147   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
148   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
149
150   setTargetDAGCombine(ISD::FP_ROUND);
151   setTargetDAGCombine(ISD::FP_TO_SINT);
152   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
153   setTargetDAGCombine(ISD::SELECT_CC);
154   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
155
156   setOperationAction(ISD::SUB, MVT::i64, Expand);
157
158   // These should be replaced by UDVIREM, but it does not happen automatically
159   // during Type Legalization
160   setOperationAction(ISD::UDIV, MVT::i64, Custom);
161   setOperationAction(ISD::UREM, MVT::i64, Custom);
162   setOperationAction(ISD::SDIV, MVT::i64, Custom);
163   setOperationAction(ISD::SREM, MVT::i64, Custom);
164
165   // We don't have 64-bit shifts. Thus we need either SHX i64 or SHX_PARTS i32
166   //  to be Legal/Custom in order to avoid library calls.
167   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
168   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
169   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
170
171   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
172
173   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
174   for (MVT VT : ScalarIntVTs) {
175     setOperationAction(ISD::ADDC, VT, Expand);
176     setOperationAction(ISD::SUBC, VT, Expand);
177     setOperationAction(ISD::ADDE, VT, Expand);
178     setOperationAction(ISD::SUBE, VT, Expand);
179   }
180
181   setBooleanContents(ZeroOrNegativeOneBooleanContent);
182   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
183   setSchedulingPreference(Sched::Source);
184 }
185
186 MachineBasicBlock * R600TargetLowering::EmitInstrWithCustomInserter(
187     MachineInstr * MI, MachineBasicBlock * BB) const {
188   MachineFunction * MF = BB->getParent();
189   MachineRegisterInfo &MRI = MF->getRegInfo();
190   MachineBasicBlock::iterator I = *MI;
191   const R600InstrInfo *TII =
192     static_cast<const R600InstrInfo*>(MF->getTarget().getInstrInfo());
193
194   switch (MI->getOpcode()) {
195   default:
196     // Replace LDS_*_RET instruction that don't have any uses with the
197     // equivalent LDS_*_NORET instruction.
198     if (TII->isLDSRetInstr(MI->getOpcode())) {
199       int DstIdx = TII->getOperandIdx(MI->getOpcode(), AMDGPU::OpName::dst);
200       assert(DstIdx != -1);
201       MachineInstrBuilder NewMI;
202       if (!MRI.use_empty(MI->getOperand(DstIdx).getReg()))
203         return BB;
204
205       NewMI = BuildMI(*BB, I, BB->findDebugLoc(I),
206                       TII->get(AMDGPU::getLDSNoRetOp(MI->getOpcode())));
207       for (unsigned i = 1, e = MI->getNumOperands(); i < e; ++i) {
208         NewMI.addOperand(MI->getOperand(i));
209       }
210     } else {
211       return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
212     }
213     break;
214   case AMDGPU::CLAMP_R600: {
215     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
216                                                    AMDGPU::MOV,
217                                                    MI->getOperand(0).getReg(),
218                                                    MI->getOperand(1).getReg());
219     TII->addFlag(NewMI, 0, MO_FLAG_CLAMP);
220     break;
221   }
222
223   case AMDGPU::FABS_R600: {
224     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
225                                                     AMDGPU::MOV,
226                                                     MI->getOperand(0).getReg(),
227                                                     MI->getOperand(1).getReg());
228     TII->addFlag(NewMI, 0, MO_FLAG_ABS);
229     break;
230   }
231
232   case AMDGPU::FNEG_R600: {
233     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
234                                                     AMDGPU::MOV,
235                                                     MI->getOperand(0).getReg(),
236                                                     MI->getOperand(1).getReg());
237     TII->addFlag(NewMI, 0, MO_FLAG_NEG);
238     break;
239   }
240
241   case AMDGPU::MASK_WRITE: {
242     unsigned maskedRegister = MI->getOperand(0).getReg();
243     assert(TargetRegisterInfo::isVirtualRegister(maskedRegister));
244     MachineInstr * defInstr = MRI.getVRegDef(maskedRegister);
245     TII->addFlag(defInstr, 0, MO_FLAG_MASK);
246     break;
247   }
248
249   case AMDGPU::MOV_IMM_F32:
250     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
251                      MI->getOperand(1).getFPImm()->getValueAPF()
252                          .bitcastToAPInt().getZExtValue());
253     break;
254   case AMDGPU::MOV_IMM_I32:
255     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
256                      MI->getOperand(1).getImm());
257     break;
258   case AMDGPU::CONST_COPY: {
259     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, MI, AMDGPU::MOV,
260         MI->getOperand(0).getReg(), AMDGPU::ALU_CONST);
261     TII->setImmOperand(NewMI, AMDGPU::OpName::src0_sel,
262         MI->getOperand(1).getImm());
263     break;
264   }
265
266   case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
267   case AMDGPU::RAT_WRITE_CACHELESS_64_eg:
268   case AMDGPU::RAT_WRITE_CACHELESS_128_eg: {
269     unsigned EOP = (std::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;
270
271     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
272             .addOperand(MI->getOperand(0))
273             .addOperand(MI->getOperand(1))
274             .addImm(EOP); // Set End of program bit
275     break;
276   }
277
278   case AMDGPU::TXD: {
279     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
280     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
281     MachineOperand &RID = MI->getOperand(4);
282     MachineOperand &SID = MI->getOperand(5);
283     unsigned TextureId = MI->getOperand(6).getImm();
284     unsigned SrcX = 0, SrcY = 1, SrcZ = 2, SrcW = 3;
285     unsigned CTX = 1, CTY = 1, CTZ = 1, CTW = 1;
286
287     switch (TextureId) {
288     case 5: // Rect
289       CTX = CTY = 0;
290       break;
291     case 6: // Shadow1D
292       SrcW = SrcZ;
293       break;
294     case 7: // Shadow2D
295       SrcW = SrcZ;
296       break;
297     case 8: // ShadowRect
298       CTX = CTY = 0;
299       SrcW = SrcZ;
300       break;
301     case 9: // 1DArray
302       SrcZ = SrcY;
303       CTZ = 0;
304       break;
305     case 10: // 2DArray
306       CTZ = 0;
307       break;
308     case 11: // Shadow1DArray
309       SrcZ = SrcY;
310       CTZ = 0;
311       break;
312     case 12: // Shadow2DArray
313       CTZ = 0;
314       break;
315     }
316     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
317             .addOperand(MI->getOperand(3))
318             .addImm(SrcX)
319             .addImm(SrcY)
320             .addImm(SrcZ)
321             .addImm(SrcW)
322             .addImm(0)
323             .addImm(0)
324             .addImm(0)
325             .addImm(0)
326             .addImm(1)
327             .addImm(2)
328             .addImm(3)
329             .addOperand(RID)
330             .addOperand(SID)
331             .addImm(CTX)
332             .addImm(CTY)
333             .addImm(CTZ)
334             .addImm(CTW);
335     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
336             .addOperand(MI->getOperand(2))
337             .addImm(SrcX)
338             .addImm(SrcY)
339             .addImm(SrcZ)
340             .addImm(SrcW)
341             .addImm(0)
342             .addImm(0)
343             .addImm(0)
344             .addImm(0)
345             .addImm(1)
346             .addImm(2)
347             .addImm(3)
348             .addOperand(RID)
349             .addOperand(SID)
350             .addImm(CTX)
351             .addImm(CTY)
352             .addImm(CTZ)
353             .addImm(CTW);
354     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_G))
355             .addOperand(MI->getOperand(0))
356             .addOperand(MI->getOperand(1))
357             .addImm(SrcX)
358             .addImm(SrcY)
359             .addImm(SrcZ)
360             .addImm(SrcW)
361             .addImm(0)
362             .addImm(0)
363             .addImm(0)
364             .addImm(0)
365             .addImm(1)
366             .addImm(2)
367             .addImm(3)
368             .addOperand(RID)
369             .addOperand(SID)
370             .addImm(CTX)
371             .addImm(CTY)
372             .addImm(CTZ)
373             .addImm(CTW)
374             .addReg(T0, RegState::Implicit)
375             .addReg(T1, RegState::Implicit);
376     break;
377   }
378
379   case AMDGPU::TXD_SHADOW: {
380     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
381     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
382     MachineOperand &RID = MI->getOperand(4);
383     MachineOperand &SID = MI->getOperand(5);
384     unsigned TextureId = MI->getOperand(6).getImm();
385     unsigned SrcX = 0, SrcY = 1, SrcZ = 2, SrcW = 3;
386     unsigned CTX = 1, CTY = 1, CTZ = 1, CTW = 1;
387
388     switch (TextureId) {
389     case 5: // Rect
390       CTX = CTY = 0;
391       break;
392     case 6: // Shadow1D
393       SrcW = SrcZ;
394       break;
395     case 7: // Shadow2D
396       SrcW = SrcZ;
397       break;
398     case 8: // ShadowRect
399       CTX = CTY = 0;
400       SrcW = SrcZ;
401       break;
402     case 9: // 1DArray
403       SrcZ = SrcY;
404       CTZ = 0;
405       break;
406     case 10: // 2DArray
407       CTZ = 0;
408       break;
409     case 11: // Shadow1DArray
410       SrcZ = SrcY;
411       CTZ = 0;
412       break;
413     case 12: // Shadow2DArray
414       CTZ = 0;
415       break;
416     }
417
418     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
419             .addOperand(MI->getOperand(3))
420             .addImm(SrcX)
421             .addImm(SrcY)
422             .addImm(SrcZ)
423             .addImm(SrcW)
424             .addImm(0)
425             .addImm(0)
426             .addImm(0)
427             .addImm(0)
428             .addImm(1)
429             .addImm(2)
430             .addImm(3)
431             .addOperand(RID)
432             .addOperand(SID)
433             .addImm(CTX)
434             .addImm(CTY)
435             .addImm(CTZ)
436             .addImm(CTW);
437     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
438             .addOperand(MI->getOperand(2))
439             .addImm(SrcX)
440             .addImm(SrcY)
441             .addImm(SrcZ)
442             .addImm(SrcW)
443             .addImm(0)
444             .addImm(0)
445             .addImm(0)
446             .addImm(0)
447             .addImm(1)
448             .addImm(2)
449             .addImm(3)
450             .addOperand(RID)
451             .addOperand(SID)
452             .addImm(CTX)
453             .addImm(CTY)
454             .addImm(CTZ)
455             .addImm(CTW);
456     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_C_G))
457             .addOperand(MI->getOperand(0))
458             .addOperand(MI->getOperand(1))
459             .addImm(SrcX)
460             .addImm(SrcY)
461             .addImm(SrcZ)
462             .addImm(SrcW)
463             .addImm(0)
464             .addImm(0)
465             .addImm(0)
466             .addImm(0)
467             .addImm(1)
468             .addImm(2)
469             .addImm(3)
470             .addOperand(RID)
471             .addOperand(SID)
472             .addImm(CTX)
473             .addImm(CTY)
474             .addImm(CTZ)
475             .addImm(CTW)
476             .addReg(T0, RegState::Implicit)
477             .addReg(T1, RegState::Implicit);
478     break;
479   }
480
481   case AMDGPU::BRANCH:
482       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
483               .addOperand(MI->getOperand(0));
484       break;
485
486   case AMDGPU::BRANCH_COND_f32: {
487     MachineInstr *NewMI =
488       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
489               AMDGPU::PREDICATE_BIT)
490               .addOperand(MI->getOperand(1))
491               .addImm(OPCODE_IS_NOT_ZERO)
492               .addImm(0); // Flags
493     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
494     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP_COND))
495             .addOperand(MI->getOperand(0))
496             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
497     break;
498   }
499
500   case AMDGPU::BRANCH_COND_i32: {
501     MachineInstr *NewMI =
502       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
503             AMDGPU::PREDICATE_BIT)
504             .addOperand(MI->getOperand(1))
505             .addImm(OPCODE_IS_NOT_ZERO_INT)
506             .addImm(0); // Flags
507     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
508     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP_COND))
509            .addOperand(MI->getOperand(0))
510             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
511     break;
512   }
513
514   case AMDGPU::EG_ExportSwz:
515   case AMDGPU::R600_ExportSwz: {
516     // Instruction is left unmodified if its not the last one of its type
517     bool isLastInstructionOfItsType = true;
518     unsigned InstExportType = MI->getOperand(1).getImm();
519     for (MachineBasicBlock::iterator NextExportInst = std::next(I),
520          EndBlock = BB->end(); NextExportInst != EndBlock;
521          NextExportInst = std::next(NextExportInst)) {
522       if (NextExportInst->getOpcode() == AMDGPU::EG_ExportSwz ||
523           NextExportInst->getOpcode() == AMDGPU::R600_ExportSwz) {
524         unsigned CurrentInstExportType = NextExportInst->getOperand(1)
525             .getImm();
526         if (CurrentInstExportType == InstExportType) {
527           isLastInstructionOfItsType = false;
528           break;
529         }
530       }
531     }
532     bool EOP = (std::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;
533     if (!EOP && !isLastInstructionOfItsType)
534       return BB;
535     unsigned CfInst = (MI->getOpcode() == AMDGPU::EG_ExportSwz)? 84 : 40;
536     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
537             .addOperand(MI->getOperand(0))
538             .addOperand(MI->getOperand(1))
539             .addOperand(MI->getOperand(2))
540             .addOperand(MI->getOperand(3))
541             .addOperand(MI->getOperand(4))
542             .addOperand(MI->getOperand(5))
543             .addOperand(MI->getOperand(6))
544             .addImm(CfInst)
545             .addImm(EOP);
546     break;
547   }
548   case AMDGPU::RETURN: {
549     // RETURN instructions must have the live-out registers as implicit uses,
550     // otherwise they appear dead.
551     R600MachineFunctionInfo *MFI = MF->getInfo<R600MachineFunctionInfo>();
552     MachineInstrBuilder MIB(*MF, MI);
553     for (unsigned i = 0, e = MFI->LiveOuts.size(); i != e; ++i)
554       MIB.addReg(MFI->LiveOuts[i], RegState::Implicit);
555     return BB;
556   }
557   }
558
559   MI->eraseFromParent();
560   return BB;
561 }
562
563 //===----------------------------------------------------------------------===//
564 // Custom DAG Lowering Operations
565 //===----------------------------------------------------------------------===//
566
567 SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
568   MachineFunction &MF = DAG.getMachineFunction();
569   R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
570   switch (Op.getOpcode()) {
571   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
572   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
573   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
574   case ISD::SHL_PARTS: return LowerSHLParts(Op, DAG);
575   case ISD::SRA_PARTS:
576   case ISD::SRL_PARTS: return LowerSRXParts(Op, DAG);
577   case ISD::FCOS:
578   case ISD::FSIN: return LowerTrig(Op, DAG);
579   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
580   case ISD::STORE: return LowerSTORE(Op, DAG);
581   case ISD::LOAD: return LowerLOAD(Op, DAG);
582   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
583   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
584   case ISD::INTRINSIC_VOID: {
585     SDValue Chain = Op.getOperand(0);
586     unsigned IntrinsicID =
587                          cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
588     switch (IntrinsicID) {
589     case AMDGPUIntrinsic::AMDGPU_store_output: {
590       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
591       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
592       MFI->LiveOuts.push_back(Reg);
593       return DAG.getCopyToReg(Chain, SDLoc(Op), Reg, Op.getOperand(2));
594     }
595     case AMDGPUIntrinsic::R600_store_swizzle: {
596       const SDValue Args[8] = {
597         Chain,
598         Op.getOperand(2), // Export Value
599         Op.getOperand(3), // ArrayBase
600         Op.getOperand(4), // Type
601         DAG.getConstant(0, MVT::i32), // SWZ_X
602         DAG.getConstant(1, MVT::i32), // SWZ_Y
603         DAG.getConstant(2, MVT::i32), // SWZ_Z
604         DAG.getConstant(3, MVT::i32) // SWZ_W
605       };
606       return DAG.getNode(AMDGPUISD::EXPORT, SDLoc(Op), Op.getValueType(), Args);
607     }
608
609     // default for switch(IntrinsicID)
610     default: break;
611     }
612     // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
613     break;
614   }
615   case ISD::INTRINSIC_WO_CHAIN: {
616     unsigned IntrinsicID =
617                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
618     EVT VT = Op.getValueType();
619     SDLoc DL(Op);
620     switch(IntrinsicID) {
621     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
622     case AMDGPUIntrinsic::R600_load_input: {
623       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
624       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
625       MachineFunction &MF = DAG.getMachineFunction();
626       MachineRegisterInfo &MRI = MF.getRegInfo();
627       MRI.addLiveIn(Reg);
628       return DAG.getCopyFromReg(DAG.getEntryNode(),
629           SDLoc(DAG.getEntryNode()), Reg, VT);
630     }
631
632     case AMDGPUIntrinsic::R600_interp_input: {
633       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
634       int ijb = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
635       MachineSDNode *interp;
636       if (ijb < 0) {
637         const MachineFunction &MF = DAG.getMachineFunction();
638         const R600InstrInfo *TII =
639           static_cast<const R600InstrInfo*>(MF.getTarget().getInstrInfo());
640         interp = DAG.getMachineNode(AMDGPU::INTERP_VEC_LOAD, DL,
641             MVT::v4f32, DAG.getTargetConstant(slot / 4 , MVT::i32));
642         return DAG.getTargetExtractSubreg(
643             TII->getRegisterInfo().getSubRegFromChannel(slot % 4),
644             DL, MVT::f32, SDValue(interp, 0));
645       }
646       MachineFunction &MF = DAG.getMachineFunction();
647       MachineRegisterInfo &MRI = MF.getRegInfo();
648       unsigned RegisterI = AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb);
649       unsigned RegisterJ = AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1);
650       MRI.addLiveIn(RegisterI);
651       MRI.addLiveIn(RegisterJ);
652       SDValue RegisterINode = DAG.getCopyFromReg(DAG.getEntryNode(),
653           SDLoc(DAG.getEntryNode()), RegisterI, MVT::f32);
654       SDValue RegisterJNode = DAG.getCopyFromReg(DAG.getEntryNode(),
655           SDLoc(DAG.getEntryNode()), RegisterJ, MVT::f32);
656
657       if (slot % 4 < 2)
658         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
659             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
660             RegisterJNode, RegisterINode);
661       else
662         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
663             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
664             RegisterJNode, RegisterINode);
665       return SDValue(interp, slot % 2);
666     }
667     case AMDGPUIntrinsic::R600_interp_xy:
668     case AMDGPUIntrinsic::R600_interp_zw: {
669       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
670       MachineSDNode *interp;
671       SDValue RegisterINode = Op.getOperand(2);
672       SDValue RegisterJNode = Op.getOperand(3);
673
674       if (IntrinsicID == AMDGPUIntrinsic::R600_interp_xy)
675         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
676             MVT::f32, MVT::f32, DAG.getTargetConstant(slot, MVT::i32),
677             RegisterJNode, RegisterINode);
678       else
679         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
680             MVT::f32, MVT::f32, DAG.getTargetConstant(slot, MVT::i32),
681             RegisterJNode, RegisterINode);
682       return DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32,
683           SDValue(interp, 0), SDValue(interp, 1));
684     }
685     case AMDGPUIntrinsic::R600_tex:
686     case AMDGPUIntrinsic::R600_texc:
687     case AMDGPUIntrinsic::R600_txl:
688     case AMDGPUIntrinsic::R600_txlc:
689     case AMDGPUIntrinsic::R600_txb:
690     case AMDGPUIntrinsic::R600_txbc:
691     case AMDGPUIntrinsic::R600_txf:
692     case AMDGPUIntrinsic::R600_txq:
693     case AMDGPUIntrinsic::R600_ddx:
694     case AMDGPUIntrinsic::R600_ddy:
695     case AMDGPUIntrinsic::R600_ldptr: {
696       unsigned TextureOp;
697       switch (IntrinsicID) {
698       case AMDGPUIntrinsic::R600_tex:
699         TextureOp = 0;
700         break;
701       case AMDGPUIntrinsic::R600_texc:
702         TextureOp = 1;
703         break;
704       case AMDGPUIntrinsic::R600_txl:
705         TextureOp = 2;
706         break;
707       case AMDGPUIntrinsic::R600_txlc:
708         TextureOp = 3;
709         break;
710       case AMDGPUIntrinsic::R600_txb:
711         TextureOp = 4;
712         break;
713       case AMDGPUIntrinsic::R600_txbc:
714         TextureOp = 5;
715         break;
716       case AMDGPUIntrinsic::R600_txf:
717         TextureOp = 6;
718         break;
719       case AMDGPUIntrinsic::R600_txq:
720         TextureOp = 7;
721         break;
722       case AMDGPUIntrinsic::R600_ddx:
723         TextureOp = 8;
724         break;
725       case AMDGPUIntrinsic::R600_ddy:
726         TextureOp = 9;
727         break;
728       case AMDGPUIntrinsic::R600_ldptr:
729         TextureOp = 10;
730         break;
731       default:
732         llvm_unreachable("Unknow Texture Operation");
733       }
734
735       SDValue TexArgs[19] = {
736         DAG.getConstant(TextureOp, MVT::i32),
737         Op.getOperand(1),
738         DAG.getConstant(0, MVT::i32),
739         DAG.getConstant(1, MVT::i32),
740         DAG.getConstant(2, MVT::i32),
741         DAG.getConstant(3, MVT::i32),
742         Op.getOperand(2),
743         Op.getOperand(3),
744         Op.getOperand(4),
745         DAG.getConstant(0, MVT::i32),
746         DAG.getConstant(1, MVT::i32),
747         DAG.getConstant(2, MVT::i32),
748         DAG.getConstant(3, MVT::i32),
749         Op.getOperand(5),
750         Op.getOperand(6),
751         Op.getOperand(7),
752         Op.getOperand(8),
753         Op.getOperand(9),
754         Op.getOperand(10)
755       };
756       return DAG.getNode(AMDGPUISD::TEXTURE_FETCH, DL, MVT::v4f32, TexArgs);
757     }
758     case AMDGPUIntrinsic::AMDGPU_dp4: {
759       SDValue Args[8] = {
760       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
761           DAG.getConstant(0, MVT::i32)),
762       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
763           DAG.getConstant(0, MVT::i32)),
764       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
765           DAG.getConstant(1, MVT::i32)),
766       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
767           DAG.getConstant(1, MVT::i32)),
768       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
769           DAG.getConstant(2, MVT::i32)),
770       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
771           DAG.getConstant(2, MVT::i32)),
772       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
773           DAG.getConstant(3, MVT::i32)),
774       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
775           DAG.getConstant(3, MVT::i32))
776       };
777       return DAG.getNode(AMDGPUISD::DOT4, DL, MVT::f32, Args);
778     }
779
780     case Intrinsic::r600_read_ngroups_x:
781       return LowerImplicitParameter(DAG, VT, DL, 0);
782     case Intrinsic::r600_read_ngroups_y:
783       return LowerImplicitParameter(DAG, VT, DL, 1);
784     case Intrinsic::r600_read_ngroups_z:
785       return LowerImplicitParameter(DAG, VT, DL, 2);
786     case Intrinsic::r600_read_global_size_x:
787       return LowerImplicitParameter(DAG, VT, DL, 3);
788     case Intrinsic::r600_read_global_size_y:
789       return LowerImplicitParameter(DAG, VT, DL, 4);
790     case Intrinsic::r600_read_global_size_z:
791       return LowerImplicitParameter(DAG, VT, DL, 5);
792     case Intrinsic::r600_read_local_size_x:
793       return LowerImplicitParameter(DAG, VT, DL, 6);
794     case Intrinsic::r600_read_local_size_y:
795       return LowerImplicitParameter(DAG, VT, DL, 7);
796     case Intrinsic::r600_read_local_size_z:
797       return LowerImplicitParameter(DAG, VT, DL, 8);
798
799     case Intrinsic::r600_read_tgid_x:
800       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
801                                   AMDGPU::T1_X, VT);
802     case Intrinsic::r600_read_tgid_y:
803       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
804                                   AMDGPU::T1_Y, VT);
805     case Intrinsic::r600_read_tgid_z:
806       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
807                                   AMDGPU::T1_Z, VT);
808     case Intrinsic::r600_read_tidig_x:
809       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
810                                   AMDGPU::T0_X, VT);
811     case Intrinsic::r600_read_tidig_y:
812       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
813                                   AMDGPU::T0_Y, VT);
814     case Intrinsic::r600_read_tidig_z:
815       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
816                                   AMDGPU::T0_Z, VT);
817     case Intrinsic::AMDGPU_rsq:
818       // XXX - I'm assuming SI's RSQ_LEGACY matches R600's behavior.
819       return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
820     }
821     // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
822     break;
823   }
824   } // end switch(Op.getOpcode())
825   return SDValue();
826 }
827
828 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
829                                             SmallVectorImpl<SDValue> &Results,
830                                             SelectionDAG &DAG) const {
831   switch (N->getOpcode()) {
832   default:
833     AMDGPUTargetLowering::ReplaceNodeResults(N, Results, DAG);
834     return;
835   case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
836     return;
837   case ISD::UDIV: {
838     SDValue Op = SDValue(N, 0);
839     SDLoc DL(Op);
840     EVT VT = Op.getValueType();
841     SDValue UDIVREM = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT),
842       N->getOperand(0), N->getOperand(1));
843     Results.push_back(UDIVREM);
844     break;
845   }
846   case ISD::UREM: {
847     SDValue Op = SDValue(N, 0);
848     SDLoc DL(Op);
849     EVT VT = Op.getValueType();
850     SDValue UDIVREM = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT),
851       N->getOperand(0), N->getOperand(1));
852     Results.push_back(UDIVREM.getValue(1));
853     break;
854   }
855   case ISD::SDIV: {
856     SDValue Op = SDValue(N, 0);
857     SDLoc DL(Op);
858     EVT VT = Op.getValueType();
859     SDValue SDIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(VT, VT),
860       N->getOperand(0), N->getOperand(1));
861     Results.push_back(SDIVREM);
862     break;
863   }
864   case ISD::SREM: {
865     SDValue Op = SDValue(N, 0);
866     SDLoc DL(Op);
867     EVT VT = Op.getValueType();
868     SDValue SDIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(VT, VT),
869       N->getOperand(0), N->getOperand(1));
870     Results.push_back(SDIVREM.getValue(1));
871     break;
872   }
873   case ISD::SDIVREM: {
874     SDValue Op = SDValue(N, 1);
875     SDValue RES = LowerSDIVREM(Op, DAG);
876     Results.push_back(RES);
877     Results.push_back(RES.getValue(1));
878     break;
879   }
880   case ISD::UDIVREM: {
881     SDValue Op = SDValue(N, 0);
882     SDLoc DL(Op);
883     EVT VT = Op.getValueType();
884     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
885
886     SDValue one = DAG.getConstant(1, HalfVT);
887     SDValue zero = DAG.getConstant(0, HalfVT);
888
889     //HiLo split
890     SDValue LHS = N->getOperand(0);
891     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
892     SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
893
894     SDValue RHS = N->getOperand(1);
895     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
896     SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
897
898     // Get Speculative values
899     SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
900     SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
901
902     SDValue REM_Hi = zero;
903     SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
904
905     SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
906     SDValue DIV_Lo = zero;
907
908     const unsigned halfBitWidth = HalfVT.getSizeInBits();
909
910     for (unsigned i = 0; i < halfBitWidth; ++i) {
911       SDValue POS = DAG.getConstant(halfBitWidth - i - 1, HalfVT);
912       // Get Value of high bit
913       SDValue HBit;
914       if (halfBitWidth == 32 && Subtarget->hasBFE()) {
915         HBit = DAG.getNode(AMDGPUISD::BFE_U32, DL, HalfVT, LHS_Lo, POS, one);
916       } else {
917         HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
918         HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
919       }
920
921       SDValue Carry = DAG.getNode(ISD::SRL, DL, HalfVT, REM_Lo,
922         DAG.getConstant(halfBitWidth - 1, HalfVT));
923       REM_Hi = DAG.getNode(ISD::SHL, DL, HalfVT, REM_Hi, one);
924       REM_Hi = DAG.getNode(ISD::OR, DL, HalfVT, REM_Hi, Carry);
925
926       REM_Lo = DAG.getNode(ISD::SHL, DL, HalfVT, REM_Lo, one);
927       REM_Lo = DAG.getNode(ISD::OR, DL, HalfVT, REM_Lo, HBit);
928
929
930       SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, REM_Hi);
931
932       SDValue BIT = DAG.getConstant(1 << (halfBitWidth - i - 1), HalfVT);
933       SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETGE);
934
935       DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
936
937       // Update REM
938
939       SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
940
941       REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETGE);
942       REM_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, REM, zero);
943       REM_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, REM, one);
944     }
945
946     SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, REM_Hi);
947     SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, DIV_Lo, DIV_Hi);
948     Results.push_back(DIV);
949     Results.push_back(REM);
950     break;
951   }
952   }
953 }
954
955 SDValue R600TargetLowering::vectorToVerticalVector(SelectionDAG &DAG,
956                                                    SDValue Vector) const {
957
958   SDLoc DL(Vector);
959   EVT VecVT = Vector.getValueType();
960   EVT EltVT = VecVT.getVectorElementType();
961   SmallVector<SDValue, 8> Args;
962
963   for (unsigned i = 0, e = VecVT.getVectorNumElements();
964                                                            i != e; ++i) {
965     Args.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
966                                Vector, DAG.getConstant(i, getVectorIdxTy())));
967   }
968
969   return DAG.getNode(AMDGPUISD::BUILD_VERTICAL_VECTOR, DL, VecVT, Args);
970 }
971
972 SDValue R600TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
973                                                     SelectionDAG &DAG) const {
974
975   SDLoc DL(Op);
976   SDValue Vector = Op.getOperand(0);
977   SDValue Index = Op.getOperand(1);
978
979   if (isa<ConstantSDNode>(Index) ||
980       Vector.getOpcode() == AMDGPUISD::BUILD_VERTICAL_VECTOR)
981     return Op;
982
983   Vector = vectorToVerticalVector(DAG, Vector);
984   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getValueType(),
985                      Vector, Index);
986 }
987
988 SDValue R600TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
989                                                    SelectionDAG &DAG) const {
990   SDLoc DL(Op);
991   SDValue Vector = Op.getOperand(0);
992   SDValue Value = Op.getOperand(1);
993   SDValue Index = Op.getOperand(2);
994
995   if (isa<ConstantSDNode>(Index) ||
996       Vector.getOpcode() == AMDGPUISD::BUILD_VERTICAL_VECTOR)
997     return Op;
998
999   Vector = vectorToVerticalVector(DAG, Vector);
1000   SDValue Insert = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, Op.getValueType(),
1001                                Vector, Value, Index);
1002   return vectorToVerticalVector(DAG, Insert);
1003 }
1004
1005 SDValue R600TargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1006   // On hw >= R700, COS/SIN input must be between -1. and 1.
1007   // Thus we lower them to TRIG ( FRACT ( x / 2Pi + 0.5) - 0.5)
1008   EVT VT = Op.getValueType();
1009   SDValue Arg = Op.getOperand(0);
1010   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1011       DAG.getNode(ISD::FADD, SDLoc(Op), VT,
1012         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1013           DAG.getConstantFP(0.15915494309, MVT::f32)),
1014         DAG.getConstantFP(0.5, MVT::f32)));
1015   unsigned TrigNode;
1016   switch (Op.getOpcode()) {
1017   case ISD::FCOS:
1018     TrigNode = AMDGPUISD::COS_HW;
1019     break;
1020   case ISD::FSIN:
1021     TrigNode = AMDGPUISD::SIN_HW;
1022     break;
1023   default:
1024     llvm_unreachable("Wrong trig opcode");
1025   }
1026   SDValue TrigVal = DAG.getNode(TrigNode, SDLoc(Op), VT,
1027       DAG.getNode(ISD::FADD, SDLoc(Op), VT, FractPart,
1028         DAG.getConstantFP(-0.5, MVT::f32)));
1029   if (Gen >= AMDGPUSubtarget::R700)
1030     return TrigVal;
1031   // On R600 hw, COS/SIN input must be between -Pi and Pi.
1032   return DAG.getNode(ISD::FMUL, SDLoc(Op), VT, TrigVal,
1033       DAG.getConstantFP(3.14159265359, MVT::f32));
1034 }
1035
1036 SDValue R600TargetLowering::LowerSHLParts(SDValue Op, SelectionDAG &DAG) const {
1037   SDLoc DL(Op);
1038   EVT VT = Op.getValueType();
1039
1040   SDValue Lo = Op.getOperand(0);
1041   SDValue Hi = Op.getOperand(1);
1042   SDValue Shift = Op.getOperand(2);
1043   SDValue Zero = DAG.getConstant(0, VT);
1044   SDValue One  = DAG.getConstant(1, VT);
1045
1046   SDValue Width  = DAG.getConstant(VT.getSizeInBits(), VT);
1047   SDValue Width1 = DAG.getConstant(VT.getSizeInBits() - 1, VT);
1048   SDValue BigShift  = DAG.getNode(ISD::SUB, DL, VT, Shift, Width);
1049   SDValue CompShift = DAG.getNode(ISD::SUB, DL, VT, Width1, Shift);
1050
1051   // The dance around Width1 is necessary for 0 special case.
1052   // Without it the CompShift might be 32, producing incorrect results in
1053   // Overflow. So we do the shift in two steps, the alternative is to
1054   // add a conditional to filter the special case.
1055
1056   SDValue Overflow = DAG.getNode(ISD::SRL, DL, VT, Lo, CompShift);
1057   Overflow = DAG.getNode(ISD::SRL, DL, VT, Overflow, One);
1058
1059   SDValue HiSmall = DAG.getNode(ISD::SHL, DL, VT, Hi, Shift);
1060   HiSmall = DAG.getNode(ISD::OR, DL, VT, HiSmall, Overflow);
1061   SDValue LoSmall = DAG.getNode(ISD::SHL, DL, VT, Lo, Shift);
1062
1063   SDValue HiBig = DAG.getNode(ISD::SHL, DL, VT, Lo, BigShift);
1064   SDValue LoBig = Zero;
1065
1066   Hi = DAG.getSelectCC(DL, Shift, Width, HiSmall, HiBig, ISD::SETULT);
1067   Lo = DAG.getSelectCC(DL, Shift, Width, LoSmall, LoBig, ISD::SETULT);
1068
1069   return DAG.getNode(ISD::MERGE_VALUES, DL, DAG.getVTList(VT,VT), Lo, Hi);
1070 }
1071
1072 SDValue R600TargetLowering::LowerSRXParts(SDValue Op, SelectionDAG &DAG) const {
1073   SDLoc DL(Op);
1074   EVT VT = Op.getValueType();
1075
1076   SDValue Lo = Op.getOperand(0);
1077   SDValue Hi = Op.getOperand(1);
1078   SDValue Shift = Op.getOperand(2);
1079   SDValue Zero = DAG.getConstant(0, VT);
1080   SDValue One  = DAG.getConstant(1, VT);
1081
1082   const bool SRA = Op.getOpcode() == ISD::SRA_PARTS;
1083
1084   SDValue Width  = DAG.getConstant(VT.getSizeInBits(), VT);
1085   SDValue Width1 = DAG.getConstant(VT.getSizeInBits() - 1, VT);
1086   SDValue BigShift  = DAG.getNode(ISD::SUB, DL, VT, Shift, Width);
1087   SDValue CompShift = DAG.getNode(ISD::SUB, DL, VT, Width1, Shift);
1088
1089   // The dance around Width1 is necessary for 0 special case.
1090   // Without it the CompShift might be 32, producing incorrect results in
1091   // Overflow. So we do the shift in two steps, the alternative is to
1092   // add a conditional to filter the special case.
1093
1094   SDValue Overflow = DAG.getNode(ISD::SHL, DL, VT, Hi, CompShift);
1095   Overflow = DAG.getNode(ISD::SHL, DL, VT, Overflow, One);
1096
1097   SDValue HiSmall = DAG.getNode(SRA ? ISD::SRA : ISD::SRL, DL, VT, Hi, Shift);
1098   SDValue LoSmall = DAG.getNode(ISD::SRL, DL, VT, Lo, Shift);
1099   LoSmall = DAG.getNode(ISD::OR, DL, VT, LoSmall, Overflow);
1100
1101   SDValue LoBig = DAG.getNode(SRA ? ISD::SRA : ISD::SRL, DL, VT, Hi, BigShift);
1102   SDValue HiBig = SRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, Width1) : Zero;
1103
1104   Hi = DAG.getSelectCC(DL, Shift, Width, HiSmall, HiBig, ISD::SETULT);
1105   Lo = DAG.getSelectCC(DL, Shift, Width, LoSmall, LoBig, ISD::SETULT);
1106
1107   return DAG.getNode(ISD::MERGE_VALUES, DL, DAG.getVTList(VT,VT), Lo, Hi);
1108 }
1109
1110 SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
1111   return DAG.getNode(
1112       ISD::SETCC,
1113       SDLoc(Op),
1114       MVT::i1,
1115       Op, DAG.getConstantFP(0.0f, MVT::f32),
1116       DAG.getCondCode(ISD::SETNE)
1117       );
1118 }
1119
1120 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
1121                                                    SDLoc DL,
1122                                                    unsigned DwordOffset) const {
1123   unsigned ByteOffset = DwordOffset * 4;
1124   PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
1125                                       AMDGPUAS::CONSTANT_BUFFER_0);
1126
1127   // We shouldn't be using an offset wider than 16-bits for implicit parameters.
1128   assert(isInt<16>(ByteOffset));
1129
1130   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
1131                      DAG.getConstant(ByteOffset, MVT::i32), // PTR
1132                      MachinePointerInfo(ConstantPointerNull::get(PtrType)),
1133                      false, false, false, 0);
1134 }
1135
1136 bool R600TargetLowering::isZero(SDValue Op) const {
1137   if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
1138     return Cst->isNullValue();
1139   } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
1140     return CstFP->isZero();
1141   } else {
1142     return false;
1143   }
1144 }
1145
1146 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
1147   SDLoc DL(Op);
1148   EVT VT = Op.getValueType();
1149
1150   SDValue LHS = Op.getOperand(0);
1151   SDValue RHS = Op.getOperand(1);
1152   SDValue True = Op.getOperand(2);
1153   SDValue False = Op.getOperand(3);
1154   SDValue CC = Op.getOperand(4);
1155   SDValue Temp;
1156
1157   // LHS and RHS are guaranteed to be the same value type
1158   EVT CompareVT = LHS.getValueType();
1159
1160   // Check if we can lower this to a native operation.
1161
1162   // Try to lower to a SET* instruction:
1163   //
1164   // SET* can match the following patterns:
1165   //
1166   // select_cc f32, f32, -1,  0, cc_supported
1167   // select_cc f32, f32, 1.0f, 0.0f, cc_supported
1168   // select_cc i32, i32, -1,  0, cc_supported
1169   //
1170
1171   // Move hardware True/False values to the correct operand.
1172   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1173   ISD::CondCode InverseCC =
1174      ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
1175   if (isHWTrueValue(False) && isHWFalseValue(True)) {
1176     if (isCondCodeLegal(InverseCC, CompareVT.getSimpleVT())) {
1177       std::swap(False, True);
1178       CC = DAG.getCondCode(InverseCC);
1179     } else {
1180       ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InverseCC);
1181       if (isCondCodeLegal(SwapInvCC, CompareVT.getSimpleVT())) {
1182         std::swap(False, True);
1183         std::swap(LHS, RHS);
1184         CC = DAG.getCondCode(SwapInvCC);
1185       }
1186     }
1187   }
1188
1189   if (isHWTrueValue(True) && isHWFalseValue(False) &&
1190       (CompareVT == VT || VT == MVT::i32)) {
1191     // This can be matched by a SET* instruction.
1192     return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
1193   }
1194
1195   // Try to lower to a CND* instruction:
1196   //
1197   // CND* can match the following patterns:
1198   //
1199   // select_cc f32, 0.0, f32, f32, cc_supported
1200   // select_cc f32, 0.0, i32, i32, cc_supported
1201   // select_cc i32, 0,   f32, f32, cc_supported
1202   // select_cc i32, 0,   i32, i32, cc_supported
1203   //
1204
1205   // Try to move the zero value to the RHS
1206   if (isZero(LHS)) {
1207     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1208     // Try swapping the operands
1209     ISD::CondCode CCSwapped = ISD::getSetCCSwappedOperands(CCOpcode);
1210     if (isCondCodeLegal(CCSwapped, CompareVT.getSimpleVT())) {
1211       std::swap(LHS, RHS);
1212       CC = DAG.getCondCode(CCSwapped);
1213     } else {
1214       // Try inverting the conditon and then swapping the operands
1215       ISD::CondCode CCInv = ISD::getSetCCInverse(CCOpcode, CompareVT.isInteger());
1216       CCSwapped = ISD::getSetCCSwappedOperands(CCInv);
1217       if (isCondCodeLegal(CCSwapped, CompareVT.getSimpleVT())) {
1218         std::swap(True, False);
1219         std::swap(LHS, RHS);
1220         CC = DAG.getCondCode(CCSwapped);
1221       }
1222     }
1223   }
1224   if (isZero(RHS)) {
1225     SDValue Cond = LHS;
1226     SDValue Zero = RHS;
1227     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1228     if (CompareVT != VT) {
1229       // Bitcast True / False to the correct types.  This will end up being
1230       // a nop, but it allows us to define only a single pattern in the
1231       // .TD files for each CND* instruction rather than having to have
1232       // one pattern for integer True/False and one for fp True/False
1233       True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
1234       False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
1235     }
1236
1237     switch (CCOpcode) {
1238     case ISD::SETONE:
1239     case ISD::SETUNE:
1240     case ISD::SETNE:
1241       CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
1242       Temp = True;
1243       True = False;
1244       False = Temp;
1245       break;
1246     default:
1247       break;
1248     }
1249     SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
1250         Cond, Zero,
1251         True, False,
1252         DAG.getCondCode(CCOpcode));
1253     return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
1254   }
1255
1256   // If we make it this for it means we have no native instructions to handle
1257   // this SELECT_CC, so we must lower it.
1258   SDValue HWTrue, HWFalse;
1259
1260   if (CompareVT == MVT::f32) {
1261     HWTrue = DAG.getConstantFP(1.0f, CompareVT);
1262     HWFalse = DAG.getConstantFP(0.0f, CompareVT);
1263   } else if (CompareVT == MVT::i32) {
1264     HWTrue = DAG.getConstant(-1, CompareVT);
1265     HWFalse = DAG.getConstant(0, CompareVT);
1266   }
1267   else {
1268     llvm_unreachable("Unhandled value type in LowerSELECT_CC");
1269   }
1270
1271   // Lower this unsupported SELECT_CC into a combination of two supported
1272   // SELECT_CC operations.
1273   SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);
1274
1275   return DAG.getNode(ISD::SELECT_CC, DL, VT,
1276       Cond, HWFalse,
1277       True, False,
1278       DAG.getCondCode(ISD::SETNE));
1279 }
1280
1281 /// LLVM generates byte-addressed pointers.  For indirect addressing, we need to
1282 /// convert these pointers to a register index.  Each register holds
1283 /// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
1284 /// \p StackWidth, which tells us how many of the 4 sub-registrers will be used
1285 /// for indirect addressing.
1286 SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
1287                                                unsigned StackWidth,
1288                                                SelectionDAG &DAG) const {
1289   unsigned SRLPad;
1290   switch(StackWidth) {
1291   case 1:
1292     SRLPad = 2;
1293     break;
1294   case 2:
1295     SRLPad = 3;
1296     break;
1297   case 4:
1298     SRLPad = 4;
1299     break;
1300   default: llvm_unreachable("Invalid stack width");
1301   }
1302
1303   return DAG.getNode(ISD::SRL, SDLoc(Ptr), Ptr.getValueType(), Ptr,
1304                      DAG.getConstant(SRLPad, MVT::i32));
1305 }
1306
1307 void R600TargetLowering::getStackAddress(unsigned StackWidth,
1308                                          unsigned ElemIdx,
1309                                          unsigned &Channel,
1310                                          unsigned &PtrIncr) const {
1311   switch (StackWidth) {
1312   default:
1313   case 1:
1314     Channel = 0;
1315     if (ElemIdx > 0) {
1316       PtrIncr = 1;
1317     } else {
1318       PtrIncr = 0;
1319     }
1320     break;
1321   case 2:
1322     Channel = ElemIdx % 2;
1323     if (ElemIdx == 2) {
1324       PtrIncr = 1;
1325     } else {
1326       PtrIncr = 0;
1327     }
1328     break;
1329   case 4:
1330     Channel = ElemIdx;
1331     PtrIncr = 0;
1332     break;
1333   }
1334 }
1335
1336 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1337   SDLoc DL(Op);
1338   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
1339   SDValue Chain = Op.getOperand(0);
1340   SDValue Value = Op.getOperand(1);
1341   SDValue Ptr = Op.getOperand(2);
1342
1343   SDValue Result = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1344   if (Result.getNode()) {
1345     return Result;
1346   }
1347
1348   if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS) {
1349     if (StoreNode->isTruncatingStore()) {
1350       EVT VT = Value.getValueType();
1351       assert(VT.bitsLE(MVT::i32));
1352       EVT MemVT = StoreNode->getMemoryVT();
1353       SDValue MaskConstant;
1354       if (MemVT == MVT::i8) {
1355         MaskConstant = DAG.getConstant(0xFF, MVT::i32);
1356       } else {
1357         assert(MemVT == MVT::i16);
1358         MaskConstant = DAG.getConstant(0xFFFF, MVT::i32);
1359       }
1360       SDValue DWordAddr = DAG.getNode(ISD::SRL, DL, VT, Ptr,
1361                                       DAG.getConstant(2, MVT::i32));
1362       SDValue ByteIndex = DAG.getNode(ISD::AND, DL, Ptr.getValueType(), Ptr,
1363                                       DAG.getConstant(0x00000003, VT));
1364       SDValue TruncValue = DAG.getNode(ISD::AND, DL, VT, Value, MaskConstant);
1365       SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, ByteIndex,
1366                                    DAG.getConstant(3, VT));
1367       SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, VT, TruncValue, Shift);
1368       SDValue Mask = DAG.getNode(ISD::SHL, DL, VT, MaskConstant, Shift);
1369       // XXX: If we add a 64-bit ZW register class, then we could use a 2 x i32
1370       // vector instead.
1371       SDValue Src[4] = {
1372         ShiftedValue,
1373         DAG.getConstant(0, MVT::i32),
1374         DAG.getConstant(0, MVT::i32),
1375         Mask
1376       };
1377       SDValue Input = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Src);
1378       SDValue Args[3] = { Chain, Input, DWordAddr };
1379       return DAG.getMemIntrinsicNode(AMDGPUISD::STORE_MSKOR, DL,
1380                                      Op->getVTList(), Args, MemVT,
1381                                      StoreNode->getMemOperand());
1382     } else if (Ptr->getOpcode() != AMDGPUISD::DWORDADDR &&
1383                Value.getValueType().bitsGE(MVT::i32)) {
1384       // Convert pointer from byte address to dword address.
1385       Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
1386                         DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
1387                                     Ptr, DAG.getConstant(2, MVT::i32)));
1388
1389       if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
1390         llvm_unreachable("Truncated and indexed stores not supported yet");
1391       } else {
1392         Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
1393       }
1394       return Chain;
1395     }
1396   }
1397
1398   EVT ValueVT = Value.getValueType();
1399
1400   if (StoreNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
1401     return SDValue();
1402   }
1403
1404   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1405   if (Ret.getNode()) {
1406     return Ret;
1407   }
1408   // Lowering for indirect addressing
1409
1410   const MachineFunction &MF = DAG.getMachineFunction();
1411   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
1412                                          getTargetMachine().getFrameLowering());
1413   unsigned StackWidth = TFL->getStackWidth(MF);
1414
1415   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
1416
1417   if (ValueVT.isVector()) {
1418     unsigned NumElemVT = ValueVT.getVectorNumElements();
1419     EVT ElemVT = ValueVT.getVectorElementType();
1420     SmallVector<SDValue, 4> Stores(NumElemVT);
1421
1422     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
1423                                       "vector width in load");
1424
1425     for (unsigned i = 0; i < NumElemVT; ++i) {
1426       unsigned Channel, PtrIncr;
1427       getStackAddress(StackWidth, i, Channel, PtrIncr);
1428       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
1429                         DAG.getConstant(PtrIncr, MVT::i32));
1430       SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT,
1431                                  Value, DAG.getConstant(i, MVT::i32));
1432
1433       Stores[i] = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1434                               Chain, Elem, Ptr,
1435                               DAG.getTargetConstant(Channel, MVT::i32));
1436     }
1437      Chain =  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
1438    } else {
1439     if (ValueVT == MVT::i8) {
1440       Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Value);
1441     }
1442     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other, Chain, Value, Ptr,
1443     DAG.getTargetConstant(0, MVT::i32)); // Channel
1444   }
1445
1446   return Chain;
1447 }
1448
1449 // return (512 + (kc_bank << 12)
1450 static int
1451 ConstantAddressBlock(unsigned AddressSpace) {
1452   switch (AddressSpace) {
1453   case AMDGPUAS::CONSTANT_BUFFER_0:
1454     return 512;
1455   case AMDGPUAS::CONSTANT_BUFFER_1:
1456     return 512 + 4096;
1457   case AMDGPUAS::CONSTANT_BUFFER_2:
1458     return 512 + 4096 * 2;
1459   case AMDGPUAS::CONSTANT_BUFFER_3:
1460     return 512 + 4096 * 3;
1461   case AMDGPUAS::CONSTANT_BUFFER_4:
1462     return 512 + 4096 * 4;
1463   case AMDGPUAS::CONSTANT_BUFFER_5:
1464     return 512 + 4096 * 5;
1465   case AMDGPUAS::CONSTANT_BUFFER_6:
1466     return 512 + 4096 * 6;
1467   case AMDGPUAS::CONSTANT_BUFFER_7:
1468     return 512 + 4096 * 7;
1469   case AMDGPUAS::CONSTANT_BUFFER_8:
1470     return 512 + 4096 * 8;
1471   case AMDGPUAS::CONSTANT_BUFFER_9:
1472     return 512 + 4096 * 9;
1473   case AMDGPUAS::CONSTANT_BUFFER_10:
1474     return 512 + 4096 * 10;
1475   case AMDGPUAS::CONSTANT_BUFFER_11:
1476     return 512 + 4096 * 11;
1477   case AMDGPUAS::CONSTANT_BUFFER_12:
1478     return 512 + 4096 * 12;
1479   case AMDGPUAS::CONSTANT_BUFFER_13:
1480     return 512 + 4096 * 13;
1481   case AMDGPUAS::CONSTANT_BUFFER_14:
1482     return 512 + 4096 * 14;
1483   case AMDGPUAS::CONSTANT_BUFFER_15:
1484     return 512 + 4096 * 15;
1485   default:
1486     return -1;
1487   }
1488 }
1489
1490 SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
1491 {
1492   EVT VT = Op.getValueType();
1493   SDLoc DL(Op);
1494   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
1495   SDValue Chain = Op.getOperand(0);
1496   SDValue Ptr = Op.getOperand(1);
1497   SDValue LoweredLoad;
1498
1499   SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1500   if (Ret.getNode()) {
1501     SDValue Ops[2] = {
1502       Ret,
1503       Chain
1504     };
1505     return DAG.getMergeValues(Ops, DL);
1506   }
1507
1508
1509   if (LoadNode->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && VT.isVector()) {
1510     SDValue MergedValues[2] = {
1511       SplitVectorLoad(Op, DAG),
1512       Chain
1513     };
1514     return DAG.getMergeValues(MergedValues, DL);
1515   }
1516
1517   int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
1518   if (ConstantBlock > -1 &&
1519       ((LoadNode->getExtensionType() == ISD::NON_EXTLOAD) ||
1520        (LoadNode->getExtensionType() == ISD::ZEXTLOAD))) {
1521     SDValue Result;
1522     if (isa<ConstantExpr>(LoadNode->getMemOperand()->getValue()) ||
1523         isa<Constant>(LoadNode->getMemOperand()->getValue()) ||
1524         isa<ConstantSDNode>(Ptr)) {
1525       SDValue Slots[4];
1526       for (unsigned i = 0; i < 4; i++) {
1527         // We want Const position encoded with the following formula :
1528         // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
1529         // const_index is Ptr computed by llvm using an alignment of 16.
1530         // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
1531         // then div by 4 at the ISel step
1532         SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
1533             DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
1534         Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
1535       }
1536       EVT NewVT = MVT::v4i32;
1537       unsigned NumElements = 4;
1538       if (VT.isVector()) {
1539         NewVT = VT;
1540         NumElements = VT.getVectorNumElements();
1541       }
1542       Result = DAG.getNode(ISD::BUILD_VECTOR, DL, NewVT,
1543                            makeArrayRef(Slots, NumElements));
1544     } else {
1545       // non-constant ptr can't be folded, keeps it as a v4f32 load
1546       Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
1547           DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32)),
1548           DAG.getConstant(LoadNode->getAddressSpace() -
1549                           AMDGPUAS::CONSTANT_BUFFER_0, MVT::i32)
1550           );
1551     }
1552
1553     if (!VT.isVector()) {
1554       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
1555           DAG.getConstant(0, MVT::i32));
1556     }
1557
1558     SDValue MergedValues[2] = {
1559       Result,
1560       Chain
1561     };
1562     return DAG.getMergeValues(MergedValues, DL);
1563   }
1564
1565   // For most operations returning SDValue() will result in the node being
1566   // expanded by the DAG Legalizer. This is not the case for ISD::LOAD, so we
1567   // need to manually expand loads that may be legal in some address spaces and
1568   // illegal in others. SEXT loads from CONSTANT_BUFFER_0 are supported for
1569   // compute shaders, since the data is sign extended when it is uploaded to the
1570   // buffer. However SEXT loads from other address spaces are not supported, so
1571   // we need to expand them here.
1572   if (LoadNode->getExtensionType() == ISD::SEXTLOAD) {
1573     EVT MemVT = LoadNode->getMemoryVT();
1574     assert(!MemVT.isVector() && (MemVT == MVT::i16 || MemVT == MVT::i8));
1575     SDValue ShiftAmount =
1576           DAG.getConstant(VT.getSizeInBits() - MemVT.getSizeInBits(), MVT::i32);
1577     SDValue NewLoad = DAG.getExtLoad(ISD::EXTLOAD, DL, VT, Chain, Ptr,
1578                                   LoadNode->getPointerInfo(), MemVT,
1579                                   LoadNode->isVolatile(),
1580                                   LoadNode->isNonTemporal(),
1581                                   LoadNode->getAlignment());
1582     SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, NewLoad, ShiftAmount);
1583     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Shl, ShiftAmount);
1584
1585     SDValue MergedValues[2] = { Sra, Chain };
1586     return DAG.getMergeValues(MergedValues, DL);
1587   }
1588
1589   if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
1590     return SDValue();
1591   }
1592
1593   // Lowering for indirect addressing
1594   const MachineFunction &MF = DAG.getMachineFunction();
1595   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
1596                                          getTargetMachine().getFrameLowering());
1597   unsigned StackWidth = TFL->getStackWidth(MF);
1598
1599   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
1600
1601   if (VT.isVector()) {
1602     unsigned NumElemVT = VT.getVectorNumElements();
1603     EVT ElemVT = VT.getVectorElementType();
1604     SDValue Loads[4];
1605
1606     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
1607                                       "vector width in load");
1608
1609     for (unsigned i = 0; i < NumElemVT; ++i) {
1610       unsigned Channel, PtrIncr;
1611       getStackAddress(StackWidth, i, Channel, PtrIncr);
1612       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
1613                         DAG.getConstant(PtrIncr, MVT::i32));
1614       Loads[i] = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, ElemVT,
1615                              Chain, Ptr,
1616                              DAG.getTargetConstant(Channel, MVT::i32),
1617                              Op.getOperand(2));
1618     }
1619     for (unsigned i = NumElemVT; i < 4; ++i) {
1620       Loads[i] = DAG.getUNDEF(ElemVT);
1621     }
1622     EVT TargetVT = EVT::getVectorVT(*DAG.getContext(), ElemVT, 4);
1623     LoweredLoad = DAG.getNode(ISD::BUILD_VECTOR, DL, TargetVT, Loads);
1624   } else {
1625     LoweredLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, VT,
1626                               Chain, Ptr,
1627                               DAG.getTargetConstant(0, MVT::i32), // Channel
1628                               Op.getOperand(2));
1629   }
1630
1631   SDValue Ops[2] = {
1632     LoweredLoad,
1633     Chain
1634   };
1635
1636   return DAG.getMergeValues(Ops, DL);
1637 }
1638
1639 SDValue R600TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1640   SDValue Chain = Op.getOperand(0);
1641   SDValue Cond  = Op.getOperand(1);
1642   SDValue Jump  = Op.getOperand(2);
1643
1644   return DAG.getNode(AMDGPUISD::BRANCH_COND, SDLoc(Op), Op.getValueType(),
1645                      Chain, Jump, Cond);
1646 }
1647
1648 /// XXX Only kernel functions are supported, so we can assume for now that
1649 /// every function is a kernel function, but in the future we should use
1650 /// separate calling conventions for kernel and non-kernel functions.
1651 SDValue R600TargetLowering::LowerFormalArguments(
1652                                       SDValue Chain,
1653                                       CallingConv::ID CallConv,
1654                                       bool isVarArg,
1655                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1656                                       SDLoc DL, SelectionDAG &DAG,
1657                                       SmallVectorImpl<SDValue> &InVals) const {
1658   SmallVector<CCValAssign, 16> ArgLocs;
1659   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1660                  getTargetMachine(), ArgLocs, *DAG.getContext());
1661   MachineFunction &MF = DAG.getMachineFunction();
1662   unsigned ShaderType = MF.getInfo<R600MachineFunctionInfo>()->ShaderType;
1663
1664   SmallVector<ISD::InputArg, 8> LocalIns;
1665
1666   getOriginalFunctionArgs(DAG, MF.getFunction(), Ins, LocalIns);
1667
1668   AnalyzeFormalArguments(CCInfo, LocalIns);
1669
1670   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1671     CCValAssign &VA = ArgLocs[i];
1672     EVT VT = Ins[i].VT;
1673     EVT MemVT = LocalIns[i].VT;
1674
1675     if (ShaderType != ShaderType::COMPUTE) {
1676       unsigned Reg = MF.addLiveIn(VA.getLocReg(), &AMDGPU::R600_Reg128RegClass);
1677       SDValue Register = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1678       InVals.push_back(Register);
1679       continue;
1680     }
1681
1682     PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
1683                                                    AMDGPUAS::CONSTANT_BUFFER_0);
1684
1685     // i64 isn't a legal type, so the register type used ends up as i32, which
1686     // isn't expected here. It attempts to create this sextload, but it ends up
1687     // being invalid. Somehow this seems to work with i64 arguments, but breaks
1688     // for <1 x i64>.
1689
1690     // The first 36 bytes of the input buffer contains information about
1691     // thread group and global sizes.
1692
1693     // FIXME: This should really check the extload type, but the handling of
1694     // extload vecto parameters seems to be broken.
1695     //ISD::LoadExtType Ext = Ins[i].Flags.isSExt() ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
1696     ISD::LoadExtType Ext = ISD::SEXTLOAD;
1697     SDValue Arg = DAG.getExtLoad(Ext, DL, VT, Chain,
1698                                  DAG.getConstant(36 + VA.getLocMemOffset(), MVT::i32),
1699                                  MachinePointerInfo(UndefValue::get(PtrTy)),
1700                                  MemVT, false, false, 4);
1701
1702     // 4 is the preferred alignment for the CONSTANT memory space.
1703     InVals.push_back(Arg);
1704   }
1705   return Chain;
1706 }
1707
1708 EVT R600TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1709    if (!VT.isVector())
1710      return MVT::i32;
1711    return VT.changeVectorElementTypeToInteger();
1712 }
1713
1714 static SDValue CompactSwizzlableVector(
1715   SelectionDAG &DAG, SDValue VectorEntry,
1716   DenseMap<unsigned, unsigned> &RemapSwizzle) {
1717   assert(VectorEntry.getOpcode() == ISD::BUILD_VECTOR);
1718   assert(RemapSwizzle.empty());
1719   SDValue NewBldVec[4] = {
1720     VectorEntry.getOperand(0),
1721     VectorEntry.getOperand(1),
1722     VectorEntry.getOperand(2),
1723     VectorEntry.getOperand(3)
1724   };
1725
1726   for (unsigned i = 0; i < 4; i++) {
1727     if (NewBldVec[i].getOpcode() == ISD::UNDEF)
1728       // We mask write here to teach later passes that the ith element of this
1729       // vector is undef. Thus we can use it to reduce 128 bits reg usage,
1730       // break false dependencies and additionnaly make assembly easier to read.
1731       RemapSwizzle[i] = 7; // SEL_MASK_WRITE
1732     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(NewBldVec[i])) {
1733       if (C->isZero()) {
1734         RemapSwizzle[i] = 4; // SEL_0
1735         NewBldVec[i] = DAG.getUNDEF(MVT::f32);
1736       } else if (C->isExactlyValue(1.0)) {
1737         RemapSwizzle[i] = 5; // SEL_1
1738         NewBldVec[i] = DAG.getUNDEF(MVT::f32);
1739       }
1740     }
1741
1742     if (NewBldVec[i].getOpcode() == ISD::UNDEF)
1743       continue;
1744     for (unsigned j = 0; j < i; j++) {
1745       if (NewBldVec[i] == NewBldVec[j]) {
1746         NewBldVec[i] = DAG.getUNDEF(NewBldVec[i].getValueType());
1747         RemapSwizzle[i] = j;
1748         break;
1749       }
1750     }
1751   }
1752
1753   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(VectorEntry),
1754                      VectorEntry.getValueType(), NewBldVec);
1755 }
1756
1757 static SDValue ReorganizeVector(SelectionDAG &DAG, SDValue VectorEntry,
1758                                 DenseMap<unsigned, unsigned> &RemapSwizzle) {
1759   assert(VectorEntry.getOpcode() == ISD::BUILD_VECTOR);
1760   assert(RemapSwizzle.empty());
1761   SDValue NewBldVec[4] = {
1762       VectorEntry.getOperand(0),
1763       VectorEntry.getOperand(1),
1764       VectorEntry.getOperand(2),
1765       VectorEntry.getOperand(3)
1766   };
1767   bool isUnmovable[4] = { false, false, false, false };
1768   for (unsigned i = 0; i < 4; i++) {
1769     RemapSwizzle[i] = i;
1770     if (NewBldVec[i].getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1771       unsigned Idx = dyn_cast<ConstantSDNode>(NewBldVec[i].getOperand(1))
1772           ->getZExtValue();
1773       if (i == Idx)
1774         isUnmovable[Idx] = true;
1775     }
1776   }
1777
1778   for (unsigned i = 0; i < 4; i++) {
1779     if (NewBldVec[i].getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1780       unsigned Idx = dyn_cast<ConstantSDNode>(NewBldVec[i].getOperand(1))
1781           ->getZExtValue();
1782       if (isUnmovable[Idx])
1783         continue;
1784       // Swap i and Idx
1785       std::swap(NewBldVec[Idx], NewBldVec[i]);
1786       std::swap(RemapSwizzle[i], RemapSwizzle[Idx]);
1787       break;
1788     }
1789   }
1790
1791   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(VectorEntry),
1792                      VectorEntry.getValueType(), NewBldVec);
1793 }
1794
1795
1796 SDValue R600TargetLowering::OptimizeSwizzle(SDValue BuildVector,
1797 SDValue Swz[4], SelectionDAG &DAG) const {
1798   assert(BuildVector.getOpcode() == ISD::BUILD_VECTOR);
1799   // Old -> New swizzle values
1800   DenseMap<unsigned, unsigned> SwizzleRemap;
1801
1802   BuildVector = CompactSwizzlableVector(DAG, BuildVector, SwizzleRemap);
1803   for (unsigned i = 0; i < 4; i++) {
1804     unsigned Idx = dyn_cast<ConstantSDNode>(Swz[i])->getZExtValue();
1805     if (SwizzleRemap.find(Idx) != SwizzleRemap.end())
1806       Swz[i] = DAG.getConstant(SwizzleRemap[Idx], MVT::i32);
1807   }
1808
1809   SwizzleRemap.clear();
1810   BuildVector = ReorganizeVector(DAG, BuildVector, SwizzleRemap);
1811   for (unsigned i = 0; i < 4; i++) {
1812     unsigned Idx = dyn_cast<ConstantSDNode>(Swz[i])->getZExtValue();
1813     if (SwizzleRemap.find(Idx) != SwizzleRemap.end())
1814       Swz[i] = DAG.getConstant(SwizzleRemap[Idx], MVT::i32);
1815   }
1816
1817   return BuildVector;
1818 }
1819
1820
1821 //===----------------------------------------------------------------------===//
1822 // Custom DAG Optimizations
1823 //===----------------------------------------------------------------------===//
1824
1825 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
1826                                               DAGCombinerInfo &DCI) const {
1827   SelectionDAG &DAG = DCI.DAG;
1828
1829   switch (N->getOpcode()) {
1830   default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1831   // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
1832   case ISD::FP_ROUND: {
1833       SDValue Arg = N->getOperand(0);
1834       if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
1835         return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), N->getValueType(0),
1836                            Arg.getOperand(0));
1837       }
1838       break;
1839     }
1840
1841   // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
1842   // (i32 select_cc f32, f32, -1, 0 cc)
1843   //
1844   // Mesa's GLSL frontend generates the above pattern a lot and we can lower
1845   // this to one of the SET*_DX10 instructions.
1846   case ISD::FP_TO_SINT: {
1847     SDValue FNeg = N->getOperand(0);
1848     if (FNeg.getOpcode() != ISD::FNEG) {
1849       return SDValue();
1850     }
1851     SDValue SelectCC = FNeg.getOperand(0);
1852     if (SelectCC.getOpcode() != ISD::SELECT_CC ||
1853         SelectCC.getOperand(0).getValueType() != MVT::f32 || // LHS
1854         SelectCC.getOperand(2).getValueType() != MVT::f32 || // True
1855         !isHWTrueValue(SelectCC.getOperand(2)) ||
1856         !isHWFalseValue(SelectCC.getOperand(3))) {
1857       return SDValue();
1858     }
1859
1860     return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N->getValueType(0),
1861                            SelectCC.getOperand(0), // LHS
1862                            SelectCC.getOperand(1), // RHS
1863                            DAG.getConstant(-1, MVT::i32), // True
1864                            DAG.getConstant(0, MVT::i32),  // Flase
1865                            SelectCC.getOperand(4)); // CC
1866
1867     break;
1868   }
1869
1870   // insert_vector_elt (build_vector elt0, ... , eltN), NewEltIdx, idx
1871   // => build_vector elt0, ... , NewEltIdx, ... , eltN
1872   case ISD::INSERT_VECTOR_ELT: {
1873     SDValue InVec = N->getOperand(0);
1874     SDValue InVal = N->getOperand(1);
1875     SDValue EltNo = N->getOperand(2);
1876     SDLoc dl(N);
1877
1878     // If the inserted element is an UNDEF, just use the input vector.
1879     if (InVal.getOpcode() == ISD::UNDEF)
1880       return InVec;
1881
1882     EVT VT = InVec.getValueType();
1883
1884     // If we can't generate a legal BUILD_VECTOR, exit
1885     if (!isOperationLegal(ISD::BUILD_VECTOR, VT))
1886       return SDValue();
1887
1888     // Check that we know which element is being inserted
1889     if (!isa<ConstantSDNode>(EltNo))
1890       return SDValue();
1891     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
1892
1893     // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
1894     // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
1895     // vector elements.
1896     SmallVector<SDValue, 8> Ops;
1897     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
1898       Ops.append(InVec.getNode()->op_begin(),
1899                  InVec.getNode()->op_end());
1900     } else if (InVec.getOpcode() == ISD::UNDEF) {
1901       unsigned NElts = VT.getVectorNumElements();
1902       Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
1903     } else {
1904       return SDValue();
1905     }
1906
1907     // Insert the element
1908     if (Elt < Ops.size()) {
1909       // All the operands of BUILD_VECTOR must have the same type;
1910       // we enforce that here.
1911       EVT OpVT = Ops[0].getValueType();
1912       if (InVal.getValueType() != OpVT)
1913         InVal = OpVT.bitsGT(InVal.getValueType()) ?
1914           DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
1915           DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
1916       Ops[Elt] = InVal;
1917     }
1918
1919     // Return the new vector
1920     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
1921   }
1922
1923   // Extract_vec (Build_vector) generated by custom lowering
1924   // also needs to be customly combined
1925   case ISD::EXTRACT_VECTOR_ELT: {
1926     SDValue Arg = N->getOperand(0);
1927     if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
1928       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1929         unsigned Element = Const->getZExtValue();
1930         return Arg->getOperand(Element);
1931       }
1932     }
1933     if (Arg.getOpcode() == ISD::BITCAST &&
1934         Arg.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
1935       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1936         unsigned Element = Const->getZExtValue();
1937         return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getVTList(),
1938             Arg->getOperand(0).getOperand(Element));
1939       }
1940     }
1941   }
1942
1943   case ISD::SELECT_CC: {
1944     // Try common optimizations
1945     SDValue Ret = AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1946     if (Ret.getNode())
1947       return Ret;
1948
1949     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1950     //      selectcc x, y, a, b, inv(cc)
1951     //
1952     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, setne ->
1953     //      selectcc x, y, a, b, cc
1954     SDValue LHS = N->getOperand(0);
1955     if (LHS.getOpcode() != ISD::SELECT_CC) {
1956       return SDValue();
1957     }
1958
1959     SDValue RHS = N->getOperand(1);
1960     SDValue True = N->getOperand(2);
1961     SDValue False = N->getOperand(3);
1962     ISD::CondCode NCC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1963
1964     if (LHS.getOperand(2).getNode() != True.getNode() ||
1965         LHS.getOperand(3).getNode() != False.getNode() ||
1966         RHS.getNode() != False.getNode()) {
1967       return SDValue();
1968     }
1969
1970     switch (NCC) {
1971     default: return SDValue();
1972     case ISD::SETNE: return LHS;
1973     case ISD::SETEQ: {
1974       ISD::CondCode LHSCC = cast<CondCodeSDNode>(LHS.getOperand(4))->get();
1975       LHSCC = ISD::getSetCCInverse(LHSCC,
1976                                   LHS.getOperand(0).getValueType().isInteger());
1977       if (DCI.isBeforeLegalizeOps() ||
1978           isCondCodeLegal(LHSCC, LHS.getOperand(0).getSimpleValueType()))
1979         return DAG.getSelectCC(SDLoc(N),
1980                                LHS.getOperand(0),
1981                                LHS.getOperand(1),
1982                                LHS.getOperand(2),
1983                                LHS.getOperand(3),
1984                                LHSCC);
1985       break;
1986     }
1987     }
1988     return SDValue();
1989   }
1990
1991   case AMDGPUISD::EXPORT: {
1992     SDValue Arg = N->getOperand(1);
1993     if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1994       break;
1995
1996     SDValue NewArgs[8] = {
1997       N->getOperand(0), // Chain
1998       SDValue(),
1999       N->getOperand(2), // ArrayBase
2000       N->getOperand(3), // Type
2001       N->getOperand(4), // SWZ_X
2002       N->getOperand(5), // SWZ_Y
2003       N->getOperand(6), // SWZ_Z
2004       N->getOperand(7) // SWZ_W
2005     };
2006     SDLoc DL(N);
2007     NewArgs[1] = OptimizeSwizzle(N->getOperand(1), &NewArgs[4], DAG);
2008     return DAG.getNode(AMDGPUISD::EXPORT, DL, N->getVTList(), NewArgs);
2009   }
2010   case AMDGPUISD::TEXTURE_FETCH: {
2011     SDValue Arg = N->getOperand(1);
2012     if (Arg.getOpcode() != ISD::BUILD_VECTOR)
2013       break;
2014
2015     SDValue NewArgs[19] = {
2016       N->getOperand(0),
2017       N->getOperand(1),
2018       N->getOperand(2),
2019       N->getOperand(3),
2020       N->getOperand(4),
2021       N->getOperand(5),
2022       N->getOperand(6),
2023       N->getOperand(7),
2024       N->getOperand(8),
2025       N->getOperand(9),
2026       N->getOperand(10),
2027       N->getOperand(11),
2028       N->getOperand(12),
2029       N->getOperand(13),
2030       N->getOperand(14),
2031       N->getOperand(15),
2032       N->getOperand(16),
2033       N->getOperand(17),
2034       N->getOperand(18),
2035     };
2036     NewArgs[1] = OptimizeSwizzle(N->getOperand(1), &NewArgs[2], DAG);
2037     return DAG.getNode(AMDGPUISD::TEXTURE_FETCH, SDLoc(N), N->getVTList(),
2038         NewArgs);
2039   }
2040   }
2041
2042   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2043 }
2044
2045 static bool
2046 FoldOperand(SDNode *ParentNode, unsigned SrcIdx, SDValue &Src, SDValue &Neg,
2047             SDValue &Abs, SDValue &Sel, SDValue &Imm, SelectionDAG &DAG) {
2048   const R600InstrInfo *TII =
2049       static_cast<const R600InstrInfo *>(DAG.getTarget().getInstrInfo());
2050   if (!Src.isMachineOpcode())
2051     return false;
2052   switch (Src.getMachineOpcode()) {
2053   case AMDGPU::FNEG_R600:
2054     if (!Neg.getNode())
2055       return false;
2056     Src = Src.getOperand(0);
2057     Neg = DAG.getTargetConstant(1, MVT::i32);
2058     return true;
2059   case AMDGPU::FABS_R600:
2060     if (!Abs.getNode())
2061       return false;
2062     Src = Src.getOperand(0);
2063     Abs = DAG.getTargetConstant(1, MVT::i32);
2064     return true;
2065   case AMDGPU::CONST_COPY: {
2066     unsigned Opcode = ParentNode->getMachineOpcode();
2067     bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
2068
2069     if (!Sel.getNode())
2070       return false;
2071
2072     SDValue CstOffset = Src.getOperand(0);
2073     if (ParentNode->getValueType(0).isVector())
2074       return false;
2075
2076     // Gather constants values
2077     int SrcIndices[] = {
2078       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
2079       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
2080       TII->getOperandIdx(Opcode, AMDGPU::OpName::src2),
2081       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_X),
2082       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Y),
2083       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Z),
2084       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_W),
2085       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_X),
2086       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Y),
2087       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Z),
2088       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_W)
2089     };
2090     std::vector<unsigned> Consts;
2091     for (int OtherSrcIdx : SrcIndices) {
2092       int OtherSelIdx = TII->getSelIdx(Opcode, OtherSrcIdx);
2093       if (OtherSrcIdx < 0 || OtherSelIdx < 0)
2094         continue;
2095       if (HasDst) {
2096         OtherSrcIdx--;
2097         OtherSelIdx--;
2098       }
2099       if (RegisterSDNode *Reg =
2100           dyn_cast<RegisterSDNode>(ParentNode->getOperand(OtherSrcIdx))) {
2101         if (Reg->getReg() == AMDGPU::ALU_CONST) {
2102           ConstantSDNode *Cst
2103             = cast<ConstantSDNode>(ParentNode->getOperand(OtherSelIdx));
2104           Consts.push_back(Cst->getZExtValue());
2105         }
2106       }
2107     }
2108
2109     ConstantSDNode *Cst = cast<ConstantSDNode>(CstOffset);
2110     Consts.push_back(Cst->getZExtValue());
2111     if (!TII->fitsConstReadLimitations(Consts)) {
2112       return false;
2113     }
2114
2115     Sel = CstOffset;
2116     Src = DAG.getRegister(AMDGPU::ALU_CONST, MVT::f32);
2117     return true;
2118   }
2119   case AMDGPU::MOV_IMM_I32:
2120   case AMDGPU::MOV_IMM_F32: {
2121     unsigned ImmReg = AMDGPU::ALU_LITERAL_X;
2122     uint64_t ImmValue = 0;
2123
2124
2125     if (Src.getMachineOpcode() == AMDGPU::MOV_IMM_F32) {
2126       ConstantFPSDNode *FPC = dyn_cast<ConstantFPSDNode>(Src.getOperand(0));
2127       float FloatValue = FPC->getValueAPF().convertToFloat();
2128       if (FloatValue == 0.0) {
2129         ImmReg = AMDGPU::ZERO;
2130       } else if (FloatValue == 0.5) {
2131         ImmReg = AMDGPU::HALF;
2132       } else if (FloatValue == 1.0) {
2133         ImmReg = AMDGPU::ONE;
2134       } else {
2135         ImmValue = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2136       }
2137     } else {
2138       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src.getOperand(0));
2139       uint64_t Value = C->getZExtValue();
2140       if (Value == 0) {
2141         ImmReg = AMDGPU::ZERO;
2142       } else if (Value == 1) {
2143         ImmReg = AMDGPU::ONE_INT;
2144       } else {
2145         ImmValue = Value;
2146       }
2147     }
2148
2149     // Check that we aren't already using an immediate.
2150     // XXX: It's possible for an instruction to have more than one
2151     // immediate operand, but this is not supported yet.
2152     if (ImmReg == AMDGPU::ALU_LITERAL_X) {
2153       if (!Imm.getNode())
2154         return false;
2155       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Imm);
2156       assert(C);
2157       if (C->getZExtValue())
2158         return false;
2159       Imm = DAG.getTargetConstant(ImmValue, MVT::i32);
2160     }
2161     Src = DAG.getRegister(ImmReg, MVT::i32);
2162     return true;
2163   }
2164   default:
2165     return false;
2166   }
2167 }
2168
2169
2170 /// \brief Fold the instructions after selecting them
2171 SDNode *R600TargetLowering::PostISelFolding(MachineSDNode *Node,
2172                                             SelectionDAG &DAG) const {
2173   const R600InstrInfo *TII =
2174       static_cast<const R600InstrInfo *>(DAG.getTarget().getInstrInfo());
2175   if (!Node->isMachineOpcode())
2176     return Node;
2177   unsigned Opcode = Node->getMachineOpcode();
2178   SDValue FakeOp;
2179
2180   std::vector<SDValue> Ops;
2181   for(SDNode::op_iterator I = Node->op_begin(), E = Node->op_end();
2182               I != E; ++I)
2183           Ops.push_back(*I);
2184
2185   if (Opcode == AMDGPU::DOT_4) {
2186     int OperandIdx[] = {
2187       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_X),
2188       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Y),
2189       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Z),
2190       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_W),
2191       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_X),
2192       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Y),
2193       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Z),
2194       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_W)
2195         };
2196     int NegIdx[] = {
2197       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_X),
2198       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_Y),
2199       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_Z),
2200       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_W),
2201       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_X),
2202       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_Y),
2203       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_Z),
2204       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_W)
2205     };
2206     int AbsIdx[] = {
2207       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_X),
2208       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_Y),
2209       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_Z),
2210       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_W),
2211       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_X),
2212       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_Y),
2213       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_Z),
2214       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_W)
2215     };
2216     for (unsigned i = 0; i < 8; i++) {
2217       if (OperandIdx[i] < 0)
2218         return Node;
2219       SDValue &Src = Ops[OperandIdx[i] - 1];
2220       SDValue &Neg = Ops[NegIdx[i] - 1];
2221       SDValue &Abs = Ops[AbsIdx[i] - 1];
2222       bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
2223       int SelIdx = TII->getSelIdx(Opcode, OperandIdx[i]);
2224       if (HasDst)
2225         SelIdx--;
2226       SDValue &Sel = (SelIdx > -1) ? Ops[SelIdx] : FakeOp;
2227       if (FoldOperand(Node, i, Src, Neg, Abs, Sel, FakeOp, DAG))
2228         return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
2229     }
2230   } else if (Opcode == AMDGPU::REG_SEQUENCE) {
2231     for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2) {
2232       SDValue &Src = Ops[i];
2233       if (FoldOperand(Node, i, Src, FakeOp, FakeOp, FakeOp, FakeOp, DAG))
2234         return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
2235     }
2236   } else if (Opcode == AMDGPU::CLAMP_R600) {
2237     SDValue Src = Node->getOperand(0);
2238     if (!Src.isMachineOpcode() ||
2239         !TII->hasInstrModifiers(Src.getMachineOpcode()))
2240       return Node;
2241     int ClampIdx = TII->getOperandIdx(Src.getMachineOpcode(),
2242         AMDGPU::OpName::clamp);
2243     if (ClampIdx < 0)
2244       return Node;
2245     std::vector<SDValue> Ops;
2246     unsigned NumOp = Src.getNumOperands();
2247     for(unsigned i = 0; i < NumOp; ++i)
2248           Ops.push_back(Src.getOperand(i));
2249     Ops[ClampIdx - 1] = DAG.getTargetConstant(1, MVT::i32);
2250     return DAG.getMachineNode(Src.getMachineOpcode(), SDLoc(Node),
2251         Node->getVTList(), Ops);
2252   } else {
2253     if (!TII->hasInstrModifiers(Opcode))
2254       return Node;
2255     int OperandIdx[] = {
2256       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
2257       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
2258       TII->getOperandIdx(Opcode, AMDGPU::OpName::src2)
2259     };
2260     int NegIdx[] = {
2261       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg),
2262       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg),
2263       TII->getOperandIdx(Opcode, AMDGPU::OpName::src2_neg)
2264     };
2265     int AbsIdx[] = {
2266       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs),
2267       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs),
2268       -1
2269     };
2270     for (unsigned i = 0; i < 3; i++) {
2271       if (OperandIdx[i] < 0)
2272         return Node;
2273       SDValue &Src = Ops[OperandIdx[i] - 1];
2274       SDValue &Neg = Ops[NegIdx[i] - 1];
2275       SDValue FakeAbs;
2276       SDValue &Abs = (AbsIdx[i] > -1) ? Ops[AbsIdx[i] - 1] : FakeAbs;
2277       bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
2278       int SelIdx = TII->getSelIdx(Opcode, OperandIdx[i]);
2279       int ImmIdx = TII->getOperandIdx(Opcode, AMDGPU::OpName::literal);
2280       if (HasDst) {
2281         SelIdx--;
2282         ImmIdx--;
2283       }
2284       SDValue &Sel = (SelIdx > -1) ? Ops[SelIdx] : FakeOp;
2285       SDValue &Imm = Ops[ImmIdx];
2286       if (FoldOperand(Node, i, Src, Neg, Abs, Sel, Imm, DAG))
2287         return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
2288     }
2289   }
2290
2291   return Node;
2292 }