1 //===-- R600ISelLowering.cpp - R600 DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for R600
13 //===----------------------------------------------------------------------===//
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"
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);
63 computeRegisterProperties(STI.getRegisterInfo());
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);
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);
77 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
78 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Custom);
79 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Custom);
81 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
82 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Custom);
83 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Custom);
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);
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);
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);
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);
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);
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);
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);
138 setOperationAction(ISD::FCOS, MVT::f32, Custom);
139 setOperationAction(ISD::FSIN, MVT::f32, Custom);
141 setOperationAction(ISD::SETCC, MVT::v4i32, Expand);
142 setOperationAction(ISD::SETCC, MVT::v2i32, Expand);
144 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
145 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
146 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
148 setOperationAction(ISD::FSUB, MVT::f32, Expand);
150 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
151 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
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);
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);
165 // ADD, SUB overflow.
166 // TODO: turn these into Legal?
167 if (Subtarget->hasCARRY())
168 setOperationAction(ISD::UADDO, MVT::i32, Custom);
170 if (Subtarget->hasBORROW())
171 setOperationAction(ISD::USUBO, MVT::i32, Custom);
173 // Expand sign extension of vectors
174 if (!Subtarget->hasBFE())
175 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
177 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Expand);
178 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Expand);
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);
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);
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);
194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Expand);
196 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
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);
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);
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);
214 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
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);
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);
229 setSchedulingPreference(Sched::Source);
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);
239 const R600Subtarget *R600TargetLowering::getSubtarget() const {
240 return static_cast<const R600Subtarget *>(Subtarget);
243 static inline bool isEOP(MachineBasicBlock::iterator I) {
244 if (std::next(I) == I->getParent()->end())
246 return std::next(I)->getOpcode() == AMDGPU::RETURN;
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();
257 switch (MI.getOpcode()) {
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)
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));
277 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
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);
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);
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);
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);
312 case AMDGPU::MOV_IMM_F32:
313 TII->buildMovImm(*BB, I, MI.getOperand(0).getReg(), MI.getOperand(1)
320 case AMDGPU::MOV_IMM_I32:
321 TII->buildMovImm(*BB, I, MI.getOperand(0).getReg(),
322 MI.getOperand(1).getImm());
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);
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());
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
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
361 BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
362 .add(MI.getOperand(0));
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)
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);
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)
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);
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)
405 if (CurrentInstExportType == InstExportType) {
406 isLastInstructionOfItsType = false;
412 if (!EOP && !isLastInstructionOfItsType)
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))
427 case AMDGPU::RETURN: {
432 MI.eraseFromParent();
436 //===----------------------------------------------------------------------===//
437 // Custom DAG Lowering Operations
438 //===----------------------------------------------------------------------===//
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);
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);
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);
457 SDValue Result = LowerLOAD(Op, DAG);
458 assert((!Result.getNode() ||
459 Result.getNode()->getNumValues() == 2) &&
460 "Load should return a value and a chain");
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: {
474 const SDValue Args[8] = {
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
484 return DAG.getNode(AMDGPUISD::R600_EXPORT, DL, Op.getValueType(), Args);
487 // default for switch(IntrinsicID)
490 // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
493 case ISD::INTRINSIC_WO_CHAIN: {
494 unsigned IntrinsicID =
495 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
496 EVT VT = Op.getValueType();
498 switch(IntrinsicID) {
499 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
500 case AMDGPUIntrinsic::r600_tex:
501 case AMDGPUIntrinsic::r600_texc: {
503 switch (IntrinsicID) {
504 case AMDGPUIntrinsic::r600_tex:
507 case AMDGPUIntrinsic::r600_texc:
511 llvm_unreachable("unhandled texture operation");
514 SDValue TexArgs[19] = {
515 DAG.getConstant(TextureOp, DL, MVT::i32),
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),
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),
535 return DAG.getNode(AMDGPUISD::TEXTURE_FETCH, DL, MVT::v4f32, TexArgs);
537 case AMDGPUIntrinsic::r600_dot4: {
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))
556 return DAG.getNode(AMDGPUISD::DOT4, DL, MVT::f32, Args);
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);
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);
583 case Intrinsic::r600_read_tgid_x:
584 return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
586 case Intrinsic::r600_read_tgid_y:
587 return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
589 case Intrinsic::r600_read_tgid_z:
590 return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
592 case Intrinsic::r600_read_tidig_x:
593 return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
595 case Intrinsic::r600_read_tidig_y:
596 return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
598 case Intrinsic::r600_read_tidig_z:
599 return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
602 case Intrinsic::r600_recipsqrt_ieee:
603 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
605 case Intrinsic::r600_recipsqrt_clamped:
606 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
609 // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
612 } // end switch(Op.getOpcode())
616 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
617 SmallVectorImpl<SDValue> &Results,
618 SelectionDAG &DAG) const {
619 switch (N->getOpcode()) {
621 AMDGPUTargetLowering::ReplaceNodeResults(N, Results, DAG);
623 case ISD::FP_TO_UINT:
624 if (N->getValueType(0) == MVT::i1) {
625 Results.push_back(lowerFP_TO_UINT(N->getOperand(0), DAG));
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.
632 case ISD::FP_TO_SINT: {
633 if (N->getValueType(0) == MVT::i1) {
634 Results.push_back(lowerFP_TO_SINT(N->getOperand(0), DAG));
639 if (expandFP_TO_SINT(N, Result, DAG))
640 Results.push_back(Result);
644 SDValue Op = SDValue(N, 1);
645 SDValue RES = LowerSDIVREM(Op, DAG);
646 Results.push_back(RES);
647 Results.push_back(RES.getValue(1));
651 SDValue Op = SDValue(N, 0);
652 LowerUDIVREM64(Op, DAG, Results);
658 SDValue R600TargetLowering::vectorToVerticalVector(SelectionDAG &DAG,
659 SDValue Vector) const {
661 EVT VecVT = Vector.getValueType();
662 EVT EltVT = VecVT.getVectorElementType();
663 SmallVector<SDValue, 8> Args;
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()))));
671 return DAG.getNode(AMDGPUISD::BUILD_VERTICAL_VECTOR, DL, VecVT, Args);
674 SDValue R600TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
675 SelectionDAG &DAG) const {
677 SDValue Vector = Op.getOperand(0);
678 SDValue Index = Op.getOperand(1);
680 if (isa<ConstantSDNode>(Index) ||
681 Vector.getOpcode() == AMDGPUISD::BUILD_VERTICAL_VECTOR)
684 Vector = vectorToVerticalVector(DAG, Vector);
685 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getValueType(),
689 SDValue R600TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
690 SelectionDAG &DAG) const {
692 SDValue Vector = Op.getOperand(0);
693 SDValue Value = Op.getOperand(1);
694 SDValue Index = Op.getOperand(2);
696 if (isa<ConstantSDNode>(Index) ||
697 Vector.getOpcode() == AMDGPUISD::BUILD_VERTICAL_VECTOR)
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);
706 SDValue R600TargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
708 SelectionDAG &DAG) const {
709 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
710 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS)
711 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
713 const DataLayout &DL = DAG.getDataLayout();
714 const GlobalValue *GV = GSD->getGlobal();
715 MVT ConstPtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
717 SDValue GA = DAG.getTargetGlobalAddress(GV, SDLoc(GSD), ConstPtrVT);
718 return DAG.getNode(AMDGPUISD::CONST_DATA_PTR, SDLoc(GSD), ConstPtrVT, GA);
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);
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)));
735 switch (Op.getOpcode()) {
737 TrigNode = AMDGPUISD::COS_HW;
740 TrigNode = AMDGPUISD::SIN_HW;
743 llvm_unreachable("Wrong trig opcode");
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)
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));
755 SDValue R600TargetLowering::LowerSHLParts(SDValue Op, SelectionDAG &DAG) const {
757 EVT VT = Op.getValueType();
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);
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);
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.
775 SDValue Overflow = DAG.getNode(ISD::SRL, DL, VT, Lo, CompShift);
776 Overflow = DAG.getNode(ISD::SRL, DL, VT, Overflow, One);
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);
782 SDValue HiBig = DAG.getNode(ISD::SHL, DL, VT, Lo, BigShift);
783 SDValue LoBig = Zero;
785 Hi = DAG.getSelectCC(DL, Shift, Width, HiSmall, HiBig, ISD::SETULT);
786 Lo = DAG.getSelectCC(DL, Shift, Width, LoSmall, LoBig, ISD::SETULT);
788 return DAG.getNode(ISD::MERGE_VALUES, DL, DAG.getVTList(VT,VT), Lo, Hi);
791 SDValue R600TargetLowering::LowerSRXParts(SDValue Op, SelectionDAG &DAG) const {
793 EVT VT = Op.getValueType();
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);
801 const bool SRA = Op.getOpcode() == ISD::SRA_PARTS;
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);
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.
813 SDValue Overflow = DAG.getNode(ISD::SHL, DL, VT, Hi, CompShift);
814 Overflow = DAG.getNode(ISD::SHL, DL, VT, Overflow, One);
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);
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;
823 Hi = DAG.getSelectCC(DL, Shift, Width, HiSmall, HiBig, ISD::SETULT);
824 Lo = DAG.getSelectCC(DL, Shift, Width, LoSmall, LoBig, ISD::SETULT);
826 return DAG.getNode(ISD::MERGE_VALUES, DL, DAG.getVTList(VT,VT), Lo, Hi);
829 SDValue R600TargetLowering::LowerUADDSUBO(SDValue Op, SelectionDAG &DAG,
830 unsigned mainop, unsigned ovf) const {
832 EVT VT = Op.getValueType();
834 SDValue Lo = Op.getOperand(0);
835 SDValue Hi = Op.getOperand(1);
837 SDValue OVF = DAG.getNode(ovf, DL, VT, Lo, Hi);
839 OVF = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, OVF,
840 DAG.getValueType(MVT::i1));
842 SDValue Res = DAG.getNode(mainop, DL, VT, Lo, Hi);
844 return DAG.getNode(ISD::MERGE_VALUES, DL, DAG.getVTList(VT, VT), Res, OVF);
847 SDValue R600TargetLowering::lowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) const {
853 Op, DAG.getConstantFP(1.0f, DL, MVT::f32),
854 DAG.getCondCode(ISD::SETEQ));
857 SDValue R600TargetLowering::lowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const {
863 Op, DAG.getConstantFP(-1.0f, DL, MVT::f32),
864 DAG.getCondCode(ISD::SETEQ));
867 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
869 unsigned DwordOffset) const {
870 unsigned ByteOffset = DwordOffset * 4;
871 PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
872 AMDGPUASI.CONSTANT_BUFFER_0);
874 // We shouldn't be using an offset wider than 16-bits for implicit parameters.
875 assert(isInt<16>(ByteOffset));
877 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
878 DAG.getConstant(ByteOffset, DL, MVT::i32), // PTR
879 MachinePointerInfo(ConstantPointerNull::get(PtrType)));
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();
892 bool R600TargetLowering::isHWTrueValue(SDValue Op) const {
893 if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
894 return CFP->isExactlyValue(1.0);
896 return isAllOnesConstant(Op);
899 bool R600TargetLowering::isHWFalseValue(SDValue Op) const {
900 if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
901 return CFP->getValueAPF().isZero();
903 return isNullConstant(Op);
906 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
908 EVT VT = Op.getValueType();
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);
917 if (VT == MVT::f32) {
918 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
919 SDValue MinMax = combineFMinMaxLegacy(DL, VT, LHS, RHS, True, False, CC, DCI);
924 // LHS and RHS are guaranteed to be the same value type
925 EVT CompareVT = LHS.getValueType();
927 // Check if we can lower this to a native operation.
929 // Try to lower to a SET* instruction:
931 // SET* can match the following patterns:
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
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);
947 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InverseCC);
948 if (isCondCodeLegal(SwapInvCC, CompareVT.getSimpleVT())) {
949 std::swap(False, True);
951 CC = DAG.getCondCode(SwapInvCC);
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);
962 // Try to lower to a CND* instruction:
964 // CND* can match the following patterns:
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
972 // Try to move the zero value to the RHS
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())) {
979 CC = DAG.getCondCode(CCSwapped);
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);
987 CC = DAG.getCondCode(CCSwapped);
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);
1008 CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
1016 SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
1019 DAG.getCondCode(CCOpcode));
1020 return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
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;
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);
1035 llvm_unreachable("Unhandled value type in LowerSELECT_CC");
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);
1042 return DAG.getNode(ISD::SELECT_CC, DL, VT,
1045 DAG.getCondCode(ISD::SETNE));
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 {
1057 switch(StackWidth) {
1067 default: llvm_unreachable("Invalid stack width");
1071 return DAG.getNode(ISD::SRL, DL, Ptr.getValueType(), Ptr,
1072 DAG.getConstant(SRLPad, DL, MVT::i32));
1075 void R600TargetLowering::getStackAddress(unsigned StackWidth,
1078 unsigned &PtrIncr) const {
1079 switch (StackWidth) {
1090 Channel = ElemIdx % 2;
1104 SDValue R600TargetLowering::lowerPrivateTruncStore(StoreSDNode *Store,
1105 SelectionDAG &DAG) const {
1107 //TODO: Who creates the i8 stores?
1108 assert(Store->isTruncatingStore()
1109 || Store->getValue().getValueType() == MVT::i8);
1110 assert(Store->getAddressSpace() == AMDGPUASI.PRIVATE_ADDRESS);
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);;
1120 llvm_unreachable("Unsupported private trunc store");
1123 SDValue OldChain = Store->getChain();
1124 bool VectorTrunc = (OldChain.getOpcode() == AMDGPUISD::DUMMY_CHAIN);
1126 SDValue Chain = VectorTrunc ? OldChain->getOperand(0) : OldChain;
1127 SDValue BasePtr = Store->getBasePtr();
1128 SDValue Offset = Store->getOffset();
1129 EVT MemVT = Store->getMemoryVT();
1131 SDValue LoadPtr = BasePtr;
1132 if (!Offset.isUndef()) {
1133 LoadPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, Offset);
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));
1142 // TODO: can we be smarter about machine pointer info?
1143 SDValue Dst = DAG.getLoad(MVT::i32, DL, Chain, Ptr, MachinePointerInfo());
1145 Chain = Dst.getValue(1);
1147 // Get offset in dword
1148 SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, LoadPtr,
1149 DAG.getConstant(0x3, DL, MVT::i32));
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));
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,
1160 // Mask the value to the right type
1161 SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
1163 // Shift the value in place
1164 SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1165 MaskedValue, ShiftAmt);
1167 // Shift the mask in place
1168 SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, Mask, ShiftAmt);
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);
1174 // Cleanup the target bits
1175 Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1178 SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1181 // TODO: Can we be smarter about MachinePointerInfo?
1182 SDValue NewStore = DAG.getStore(Chain, DL, Value, Ptr, MachinePointerInfo());
1184 // If we are part of expanded vector, make our neighbors depend on this store
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);
1193 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1194 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
1195 unsigned AS = StoreNode->getAddressSpace();
1197 SDValue Chain = StoreNode->getChain();
1198 SDValue Ptr = StoreNode->getBasePtr();
1199 SDValue Value = StoreNode->getValue();
1201 EVT VT = Value.getValueType();
1202 EVT MemVT = StoreNode->getMemoryVT();
1203 EVT PtrVT = Ptr.getValueType();
1207 // Neither LOCAL nor PRIVATE can do vectors at the moment
1208 if ((AS == AMDGPUASI.LOCAL_ADDRESS || AS == AMDGPUASI.PRIVATE_ADDRESS) &&
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);
1222 return scalarizeVectorStore(StoreNode, DAG);
1225 unsigned Align = StoreNode->getAlignment();
1226 if (Align < MemVT.getStoreSize() &&
1227 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
1228 return expandUnalignedStore(StoreNode, DAG);
1231 SDValue DWordAddr = DAG.getNode(ISD::SRL, DL, PtrVT, Ptr,
1232 DAG.getConstant(2, DL, PtrVT));
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);
1243 assert(MemVT == MVT::i16);
1244 assert(StoreNode->getAlignment() >= 2);
1245 MaskConstant = DAG.getConstant(0xFFFF, DL, MVT::i32);
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));
1253 // Put the mask in correct place
1254 SDValue Mask = DAG.getNode(ISD::SHL, DL, VT, MaskConstant, BitShift);
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);
1260 // XXX: If we add a 64-bit ZW register class, then we could use a 2 x i32
1264 DAG.getConstant(0, DL, MVT::i32),
1265 DAG.getConstant(0, DL, MVT::i32),
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);
1277 if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
1278 llvm_unreachable("Truncated and indexed stores not supported yet");
1280 Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
1286 // GLOBAL_ADDRESS has been handled above, LOCAL_ADDRESS allows all sizes
1287 if (AS != AMDGPUASI.PRIVATE_ADDRESS)
1290 if (MemVT.bitsLT(MVT::i32))
1291 return lowerPrivateTruncStore(StoreNode, DAG);
1293 // Standard i32+ store, tag it with DWORDADDR to note that the address
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());
1300 // Tagged i32+ stores will be matched by patterns
1304 // return (512 + (kc_bank << 12)
1306 ConstantAddressBlock(unsigned AddressSpace, AMDGPUAS AMDGPUASI) {
1307 switch (AddressSpace) {
1308 case AMDGPUASI.CONSTANT_BUFFER_0:
1310 case AMDGPUASI.CONSTANT_BUFFER_1:
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;
1345 SDValue R600TargetLowering::lowerPrivateExtLoad(SDValue Op,
1346 SelectionDAG &DAG) const {
1348 LoadSDNode *Load = cast<LoadSDNode>(Op);
1349 ISD::LoadExtType ExtType = Load->getExtensionType();
1350 EVT MemVT = Load->getMemoryVT();
1351 assert(Load->getAlignment() >= MemVT.getStoreSize());
1353 SDValue BasePtr = Load->getBasePtr();
1354 SDValue Chain = Load->getChain();
1355 SDValue Offset = Load->getOffset();
1357 SDValue LoadPtr = BasePtr;
1358 if (!Offset.isUndef()) {
1359 LoadPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, Offset);
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));
1368 // TODO: can we be smarter about machine pointer info?
1369 SDValue Read = DAG.getLoad(MVT::i32, DL, Chain, Ptr, MachinePointerInfo());
1371 // Get offset within the register.
1372 SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
1373 LoadPtr, DAG.getConstant(0x3, DL, MVT::i32));
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));
1379 // Shift to the right.
1380 SDValue Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Read, ShiftAmt);
1382 // Eliminate the upper bits by setting them to ...
1383 EVT MemEltVT = MemVT.getScalarType();
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);
1394 Read.getValue(1) // This should be our output chain
1397 return DAG.getMergeValues(Ops, DL);
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();
1406 if (AS == AMDGPUASI.PRIVATE_ADDRESS &&
1407 ExtType != ISD::NON_EXTLOAD && MemVT.bitsLT(MVT::i32)) {
1408 return lowerPrivateExtLoad(Op, DAG);
1412 EVT VT = Op.getValueType();
1413 SDValue Chain = LoadNode->getChain();
1414 SDValue Ptr = LoadNode->getBasePtr();
1416 if ((LoadNode->getAddressSpace() == AMDGPUASI.LOCAL_ADDRESS ||
1417 LoadNode->getAddressSpace() == AMDGPUASI.PRIVATE_ADDRESS) &&
1419 return scalarizeVectorLoad(LoadNode, DAG);
1422 int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace(),
1424 if (ConstantBlock > -1 &&
1425 ((LoadNode->getExtensionType() == ISD::NON_EXTLOAD) ||
1426 (LoadNode->getExtensionType() == ISD::ZEXTLOAD))) {
1428 if (isa<ConstantExpr>(LoadNode->getMemOperand()->getValue()) ||
1429 isa<Constant>(LoadNode->getMemOperand()->getValue()) ||
1430 isa<ConstantSDNode>(Ptr)) {
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);
1442 EVT NewVT = MVT::v4i32;
1443 unsigned NumElements = 4;
1444 if (VT.isVector()) {
1446 NumElements = VT.getVectorNumElements();
1448 Result = DAG.getBuildVector(NewVT, DL, makeArrayRef(Slots, NumElements));
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)
1459 if (!VT.isVector()) {
1460 Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
1461 DAG.getConstant(0, DL, MVT::i32));
1464 SDValue MergedValues[2] = {
1468 return DAG.getMergeValues(MergedValues, DL);
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));
1487 SDValue MergedValues[2] = { Res, Chain };
1488 return DAG.getMergeValues(MergedValues, DL);
1491 if (LoadNode->getAddressSpace() != AMDGPUASI.PRIVATE_ADDRESS) {
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());
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);
1510 return DAG.getNode(AMDGPUISD::BRANCH_COND, SDLoc(Op), Op.getValueType(),
1514 SDValue R600TargetLowering::lowerFrameIndex(SDValue Op,
1515 SelectionDAG &DAG) const {
1516 MachineFunction &MF = DAG.getMachineFunction();
1517 const R600FrameLowering *TFL = getSubtarget()->getFrameLowering();
1519 FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op);
1521 unsigned FrameIndex = FIN->getIndex();
1522 unsigned IgnoredFrameReg;
1524 TFL->getFrameIndexReference(MF, FrameIndex, IgnoredFrameReg);
1525 return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF), SDLoc(Op),
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,
1539 MachineFunction &MF = DAG.getMachineFunction();
1540 R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
1542 SmallVector<ISD::InputArg, 8> LocalIns;
1544 if (AMDGPU::isShader(CallConv)) {
1545 AnalyzeFormalArguments(CCInfo, Ins);
1547 analyzeFormalArgumentsCompute(CCInfo, Ins);
1550 for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1551 CCValAssign &VA = ArgLocs[i];
1552 const ISD::InputArg &In = Ins[i];
1554 EVT MemVT = VA.getLocVT();
1555 if (!VT.isVector() && MemVT.isVector()) {
1556 // Get load source type if scalarized.
1557 MemVT = MemVT.getVectorElementType();
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);
1567 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
1568 AMDGPUASI.CONSTANT_BUFFER_0);
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
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.
1582 // Ext = In.Flags.isSExt() ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
1583 Ext = ISD::SEXTLOAD;
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.
1590 unsigned ValBase = ArgLocs[In.getOrigArgIndex()].getLocMemOffset();
1591 unsigned PartOffset = VA.getLocMemOffset();
1592 unsigned Offset = Subtarget->getExplicitKernelArgOffset(MF) + VA.getLocMemOffset();
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);
1602 // 4 is the preferred alignment for the CONSTANT memory space.
1603 InVals.push_back(Arg);
1604 MFI->setABIArgOffset(Offset + MemVT.getStoreSize());
1609 EVT R600TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1613 return VT.changeVectorElementTypeToInteger();
1616 bool R600TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1619 bool *IsFast) const {
1623 if (!VT.isSimple() || VT == MVT::Other)
1626 if (VT.bitsLT(MVT::i32))
1629 // TODO: This is a rough estimate.
1633 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
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)
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])) {
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);
1664 if (NewBldVec[i].isUndef())
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;
1675 return DAG.getBuildVector(VectorEntry.getValueType(), SDLoc(VectorEntry),
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)
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))
1696 isUnmovable[Idx] = true;
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))
1704 if (isUnmovable[Idx])
1707 std::swap(NewBldVec[Idx], NewBldVec[i]);
1708 std::swap(RemapSwizzle[i], RemapSwizzle[Idx]);
1713 return DAG.getBuildVector(VectorEntry.getValueType(), SDLoc(VectorEntry),
1717 SDValue R600TargetLowering::OptimizeSwizzle(SDValue BuildVector, SDValue Swz[4],
1719 const SDLoc &DL) const {
1720 assert(BuildVector.getOpcode() == ISD::BUILD_VECTOR);
1721 // Old -> New swizzle values
1722 DenseMap<unsigned, unsigned> SwizzleRemap;
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);
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);
1742 //===----------------------------------------------------------------------===//
1743 // Custom DAG Optimizations
1744 //===----------------------------------------------------------------------===//
1746 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
1747 DAGCombinerInfo &DCI) const {
1748 SelectionDAG &DAG = DCI.DAG;
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),
1762 // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
1763 // (i32 select_cc f32, f32, -1, 0 cc)
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) {
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))) {
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
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);
1798 // If the inserted element is an UNDEF, just use the input vector.
1799 if (InVal.isUndef())
1802 EVT VT = InVec.getValueType();
1804 // If we can't generate a legal BUILD_VECTOR, exit
1805 if (!isOperationLegal(ISD::BUILD_VECTOR, VT))
1808 // Check that we know which element is being inserted
1809 if (!isa<ConstantSDNode>(EltNo))
1811 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
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
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()));
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);
1839 // Return the new vector
1840 return DAG.getBuildVector(VT, DL, Ops);
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);
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));
1866 case ISD::SELECT_CC: {
1867 // Try common optimizations
1868 if (SDValue Ret = AMDGPUTargetLowering::PerformDAGCombine(N, DCI))
1871 // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1872 // selectcc x, y, a, b, inv(cc)
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) {
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();
1886 if (LHS.getOperand(2).getNode() != True.getNode() ||
1887 LHS.getOperand(3).getNode() != False.getNode() ||
1888 RHS.getNode() != False.getNode()) {
1893 default: return SDValue();
1894 case ISD::SETNE: return LHS;
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,
1913 case AMDGPUISD::R600_EXPORT: {
1914 SDValue Arg = N->getOperand(1);
1915 if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1918 SDValue NewArgs[8] = {
1919 N->getOperand(0), // Chain
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
1928 NewArgs[1] = OptimizeSwizzle(N->getOperand(1), &NewArgs[4], DAG, DL);
1929 return DAG.getNode(AMDGPUISD::R600_EXPORT, DL, N->getVTList(), NewArgs);
1931 case AMDGPUISD::TEXTURE_FETCH: {
1932 SDValue Arg = N->getOperand(1);
1933 if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1936 SDValue NewArgs[19] = {
1957 NewArgs[1] = OptimizeSwizzle(N->getOperand(1), &NewArgs[2], DAG, DL);
1958 return DAG.getNode(AMDGPUISD::TEXTURE_FETCH, DL, N->getVTList(), NewArgs);
1963 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
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())
1974 switch (Src.getMachineOpcode()) {
1975 case AMDGPU::FNEG_R600:
1978 Src = Src.getOperand(0);
1979 Neg = DAG.getTargetConstant(1, SDLoc(ParentNode), MVT::i32);
1981 case AMDGPU::FABS_R600:
1984 Src = Src.getOperand(0);
1985 Abs = DAG.getTargetConstant(1, SDLoc(ParentNode), MVT::i32);
1987 case AMDGPU::CONST_COPY: {
1988 unsigned Opcode = ParentNode->getMachineOpcode();
1989 bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
1994 SDValue CstOffset = Src.getOperand(0);
1995 if (ParentNode->getValueType(0).isVector())
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)
2012 std::vector<unsigned> Consts;
2013 for (int OtherSrcIdx : SrcIndices) {
2014 int OtherSelIdx = TII->getSelIdx(Opcode, OtherSrcIdx);
2015 if (OtherSrcIdx < 0 || OtherSelIdx < 0)
2021 if (RegisterSDNode *Reg =
2022 dyn_cast<RegisterSDNode>(ParentNode->getOperand(OtherSrcIdx))) {
2023 if (Reg->getReg() == AMDGPU::ALU_CONST) {
2025 = cast<ConstantSDNode>(ParentNode->getOperand(OtherSelIdx));
2026 Consts.push_back(Cst->getZExtValue());
2031 ConstantSDNode *Cst = cast<ConstantSDNode>(CstOffset);
2032 Consts.push_back(Cst->getZExtValue());
2033 if (!TII->fitsConstReadLimitations(Consts)) {
2038 Src = DAG.getRegister(AMDGPU::ALU_CONST, MVT::f32);
2041 case AMDGPU::MOV_IMM_GLOBAL_ADDR:
2042 // Check if the Imm slot is used. Taken from below.
2043 if (cast<ConstantSDNode>(Imm)->getZExtValue())
2045 Imm = Src.getOperand(0);
2046 Src = DAG.getRegister(AMDGPU::ALU_LITERAL_X, MVT::i32);
2048 case AMDGPU::MOV_IMM_I32:
2049 case AMDGPU::MOV_IMM_F32: {
2050 unsigned ImmReg = AMDGPU::ALU_LITERAL_X;
2051 uint64_t ImmValue = 0;
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;
2063 ImmValue = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2066 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src.getOperand(0));
2067 uint64_t Value = C->getZExtValue();
2069 ImmReg = AMDGPU::ZERO;
2070 } else if (Value == 1) {
2071 ImmReg = AMDGPU::ONE_INT;
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) {
2083 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Imm);
2085 if (C->getZExtValue())
2087 Imm = DAG.getTargetConstant(ImmValue, SDLoc(ParentNode), MVT::i32);
2089 Src = DAG.getRegister(ImmReg, MVT::i32);
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())
2104 unsigned Opcode = Node->getMachineOpcode();
2107 std::vector<SDValue> Ops(Node->op_begin(), Node->op_end());
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)
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)
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)
2140 for (unsigned i = 0; i < 8; i++) {
2141 if (OperandIdx[i] < 0)
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]);
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);
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);
2160 } else if (Opcode == AMDGPU::CLAMP_R600) {
2161 SDValue Src = Node->getOperand(0);
2162 if (!Src.isMachineOpcode() ||
2163 !TII->hasInstrModifiers(Src.getMachineOpcode()))
2165 int ClampIdx = TII->getOperandIdx(Src.getMachineOpcode(),
2166 AMDGPU::OpName::clamp);
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);
2175 if (!TII->hasInstrModifiers(Opcode))
2177 int OperandIdx[] = {
2178 TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
2179 TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
2180 TII->getOperandIdx(Opcode, AMDGPU::OpName::src2)
2183 TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg),
2184 TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg),
2185 TII->getOperandIdx(Opcode, AMDGPU::OpName::src2_neg)
2188 TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs),
2189 TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs),
2192 for (unsigned i = 0; i < 3; i++) {
2193 if (OperandIdx[i] < 0)
2195 SDValue &Src = Ops[OperandIdx[i] - 1];
2196 SDValue &Neg = Ops[NegIdx[i] - 1];
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);
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);