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