OSDN Git Service

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