[PM] Switch the TargetMachine interface from accepting a pass manager
[oota-llvm.git] / lib / Target / R600 / AMDGPUISelDAGToDAG.cpp
1 //===-- AMDILISelDAGToDAG.cpp - A dag to dag inst selector for AMDIL ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //==-----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Defines an instruction selector for the AMDGPU target.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "AMDGPUInstrInfo.h"
15 #include "AMDGPUISelLowering.h" // For AMDGPUISD
16 #include "AMDGPURegisterInfo.h"
17 #include "AMDGPUSubtarget.h"
18 #include "R600InstrInfo.h"
19 #include "SIDefines.h"
20 #include "SIISelLowering.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/IR/Function.h"
29
30 using namespace llvm;
31
32 //===----------------------------------------------------------------------===//
33 // Instruction Selector Implementation
34 //===----------------------------------------------------------------------===//
35
36 namespace {
37 /// AMDGPU specific code to select AMDGPU machine instructions for
38 /// SelectionDAG operations.
39 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
40   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
41   // make the right decision when generating code for different targets.
42   const AMDGPUSubtarget *Subtarget;
43 public:
44   AMDGPUDAGToDAGISel(TargetMachine &TM);
45   virtual ~AMDGPUDAGToDAGISel();
46   bool runOnMachineFunction(MachineFunction &MF) override;
47   SDNode *Select(SDNode *N) override;
48   const char *getPassName() const override;
49   void PostprocessISelDAG() override;
50
51 private:
52   bool isInlineImmediate(SDNode *N) const;
53   inline SDValue getSmallIPtrImm(unsigned Imm);
54   bool FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg, SDValue &Abs,
55                    const R600InstrInfo *TII);
56   bool FoldOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
57   bool FoldDotOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
58
59   // Complex pattern selectors
60   bool SelectADDRParam(SDValue Addr, SDValue& R1, SDValue& R2);
61   bool SelectADDR(SDValue N, SDValue &R1, SDValue &R2);
62   bool SelectADDR64(SDValue N, SDValue &R1, SDValue &R2);
63
64   static bool checkType(const Value *ptr, unsigned int addrspace);
65   static bool checkPrivateAddress(const MachineMemOperand *Op);
66
67   static bool isGlobalStore(const StoreSDNode *N);
68   static bool isFlatStore(const StoreSDNode *N);
69   static bool isPrivateStore(const StoreSDNode *N);
70   static bool isLocalStore(const StoreSDNode *N);
71   static bool isRegionStore(const StoreSDNode *N);
72
73   bool isCPLoad(const LoadSDNode *N) const;
74   bool isConstantLoad(const LoadSDNode *N, int cbID) const;
75   bool isGlobalLoad(const LoadSDNode *N) const;
76   bool isFlatLoad(const LoadSDNode *N) const;
77   bool isParamLoad(const LoadSDNode *N) const;
78   bool isPrivateLoad(const LoadSDNode *N) const;
79   bool isLocalLoad(const LoadSDNode *N) const;
80   bool isRegionLoad(const LoadSDNode *N) const;
81
82   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
83   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
84   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
85                                        SDValue& Offset);
86   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
87   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
88   bool isDSOffsetLegal(const SDValue &Base, unsigned Offset,
89                        unsigned OffsetBits) const;
90   bool SelectDS1Addr1Offset(SDValue Ptr, SDValue &Base, SDValue &Offset) const;
91   bool SelectDS64Bit4ByteAligned(SDValue Ptr, SDValue &Base, SDValue &Offset0,
92                                  SDValue &Offset1) const;
93   void SelectMUBUF(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
94                    SDValue &SOffset, SDValue &Offset, SDValue &Offen,
95                    SDValue &Idxen, SDValue &Addr64, SDValue &GLC, SDValue &SLC,
96                    SDValue &TFE) const;
97   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
98                          SDValue &Offset) const;
99   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
100                          SDValue &VAddr, SDValue &Offset,
101                          SDValue &SLC) const;
102   bool SelectMUBUFScratch(SDValue Addr, SDValue &RSrc, SDValue &VAddr,
103                           SDValue &SOffset, SDValue &ImmOffset) const;
104   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &SOffset,
105                          SDValue &Offset, SDValue &GLC, SDValue &SLC,
106                          SDValue &TFE) const;
107   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
108                          SDValue &Offset, SDValue &GLC) const;
109   SDNode *SelectAddrSpaceCast(SDNode *N);
110   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
111   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
112                        SDValue &Clamp, SDValue &Omod) const;
113
114   bool SelectVOP3Mods0Clamp(SDValue In, SDValue &Src, SDValue &SrcMods,
115                             SDValue &Omod) const;
116   bool SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src, SDValue &SrcMods,
117                                  SDValue &Clamp,
118                                  SDValue &Omod) const;
119
120   SDNode *SelectADD_SUB_I64(SDNode *N);
121   SDNode *SelectDIV_SCALE(SDNode *N);
122
123   // Include the pieces autogenerated from the target description.
124 #include "AMDGPUGenDAGISel.inc"
125 };
126 }  // end anonymous namespace
127
128 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
129 // DAG, ready for instruction scheduling.
130 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM) {
131   return new AMDGPUDAGToDAGISel(TM);
132 }
133
134 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
135     : SelectionDAGISel(TM) {}
136
137 bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
138   Subtarget = &static_cast<const AMDGPUSubtarget &>(MF.getSubtarget());
139   return SelectionDAGISel::runOnMachineFunction(MF);
140 }
141
142 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
143 }
144
145 bool AMDGPUDAGToDAGISel::isInlineImmediate(SDNode *N) const {
146   const SITargetLowering *TL
147       = static_cast<const SITargetLowering *>(getTargetLowering());
148   return TL->analyzeImmediate(N) == 0;
149 }
150
151 /// \brief Determine the register class for \p OpNo
152 /// \returns The register class of the virtual register that will be used for
153 /// the given operand number \OpNo or NULL if the register class cannot be
154 /// determined.
155 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
156                                                           unsigned OpNo) const {
157   if (!N->isMachineOpcode())
158     return nullptr;
159
160   switch (N->getMachineOpcode()) {
161   default: {
162     const MCInstrDesc &Desc =
163         Subtarget->getInstrInfo()->get(N->getMachineOpcode());
164     unsigned OpIdx = Desc.getNumDefs() + OpNo;
165     if (OpIdx >= Desc.getNumOperands())
166       return nullptr;
167     int RegClass = Desc.OpInfo[OpIdx].RegClass;
168     if (RegClass == -1)
169       return nullptr;
170
171     return Subtarget->getRegisterInfo()->getRegClass(RegClass);
172   }
173   case AMDGPU::REG_SEQUENCE: {
174     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
175     const TargetRegisterClass *SuperRC =
176         Subtarget->getRegisterInfo()->getRegClass(RCID);
177
178     SDValue SubRegOp = N->getOperand(OpNo + 1);
179     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
180     return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
181                                                               SubRegIdx);
182   }
183   }
184 }
185
186 SDValue AMDGPUDAGToDAGISel::getSmallIPtrImm(unsigned int Imm) {
187   return CurDAG->getTargetConstant(Imm, MVT::i32);
188 }
189
190 bool AMDGPUDAGToDAGISel::SelectADDRParam(
191   SDValue Addr, SDValue& R1, SDValue& R2) {
192
193   if (Addr.getOpcode() == ISD::FrameIndex) {
194     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
195       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
196       R2 = CurDAG->getTargetConstant(0, MVT::i32);
197     } else {
198       R1 = Addr;
199       R2 = CurDAG->getTargetConstant(0, MVT::i32);
200     }
201   } else if (Addr.getOpcode() == ISD::ADD) {
202     R1 = Addr.getOperand(0);
203     R2 = Addr.getOperand(1);
204   } else {
205     R1 = Addr;
206     R2 = CurDAG->getTargetConstant(0, MVT::i32);
207   }
208   return true;
209 }
210
211 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
212   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
213       Addr.getOpcode() == ISD::TargetGlobalAddress) {
214     return false;
215   }
216   return SelectADDRParam(Addr, R1, R2);
217 }
218
219
220 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
221   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
222       Addr.getOpcode() == ISD::TargetGlobalAddress) {
223     return false;
224   }
225
226   if (Addr.getOpcode() == ISD::FrameIndex) {
227     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
228       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
229       R2 = CurDAG->getTargetConstant(0, MVT::i64);
230     } else {
231       R1 = Addr;
232       R2 = CurDAG->getTargetConstant(0, MVT::i64);
233     }
234   } else if (Addr.getOpcode() == ISD::ADD) {
235     R1 = Addr.getOperand(0);
236     R2 = Addr.getOperand(1);
237   } else {
238     R1 = Addr;
239     R2 = CurDAG->getTargetConstant(0, MVT::i64);
240   }
241   return true;
242 }
243
244 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
245   unsigned int Opc = N->getOpcode();
246   if (N->isMachineOpcode()) {
247     N->setNodeId(-1);
248     return nullptr;   // Already selected.
249   }
250
251   switch (Opc) {
252   default: break;
253   // We are selecting i64 ADD here instead of custom lower it during
254   // DAG legalization, so we can fold some i64 ADDs used for address
255   // calculation into the LOAD and STORE instructions.
256   case ISD::ADD:
257   case ISD::SUB: {
258     if (N->getValueType(0) != MVT::i64 ||
259         Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
260       break;
261
262     return SelectADD_SUB_I64(N);
263   }
264   case ISD::SCALAR_TO_VECTOR:
265   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
266   case ISD::BUILD_VECTOR: {
267     unsigned RegClassID;
268     const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
269     EVT VT = N->getValueType(0);
270     unsigned NumVectorElts = VT.getVectorNumElements();
271     EVT EltVT = VT.getVectorElementType();
272     assert(EltVT.bitsEq(MVT::i32));
273     if (Subtarget->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
274       bool UseVReg = true;
275       for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
276                                                     U != E; ++U) {
277         if (!U->isMachineOpcode()) {
278           continue;
279         }
280         const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
281         if (!RC) {
282           continue;
283         }
284         if (static_cast<const SIRegisterInfo *>(TRI)->isSGPRClass(RC)) {
285           UseVReg = false;
286         }
287       }
288       switch(NumVectorElts) {
289       case 1: RegClassID = UseVReg ? AMDGPU::VGPR_32RegClassID :
290                                      AMDGPU::SReg_32RegClassID;
291         break;
292       case 2: RegClassID = UseVReg ? AMDGPU::VReg_64RegClassID :
293                                      AMDGPU::SReg_64RegClassID;
294         break;
295       case 4: RegClassID = UseVReg ? AMDGPU::VReg_128RegClassID :
296                                      AMDGPU::SReg_128RegClassID;
297         break;
298       case 8: RegClassID = UseVReg ? AMDGPU::VReg_256RegClassID :
299                                      AMDGPU::SReg_256RegClassID;
300         break;
301       case 16: RegClassID = UseVReg ? AMDGPU::VReg_512RegClassID :
302                                       AMDGPU::SReg_512RegClassID;
303         break;
304       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
305       }
306     } else {
307       // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
308       // that adds a 128 bits reg copy when going through TwoAddressInstructions
309       // pass. We want to avoid 128 bits copies as much as possible because they
310       // can't be bundled by our scheduler.
311       switch(NumVectorElts) {
312       case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
313       case 4:
314         if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
315           RegClassID = AMDGPU::R600_Reg128VerticalRegClassID;
316         else
317           RegClassID = AMDGPU::R600_Reg128RegClassID;
318         break;
319       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
320       }
321     }
322
323     SDValue RegClass = CurDAG->getTargetConstant(RegClassID, MVT::i32);
324
325     if (NumVectorElts == 1) {
326       return CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT,
327                                   N->getOperand(0), RegClass);
328     }
329
330     assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
331                                   "supported yet");
332     // 16 = Max Num Vector Elements
333     // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
334     // 1 = Vector Register Class
335     SmallVector<SDValue, 16 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
336
337     RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, MVT::i32);
338     bool IsRegSeq = true;
339     unsigned NOps = N->getNumOperands();
340     for (unsigned i = 0; i < NOps; i++) {
341       // XXX: Why is this here?
342       if (dyn_cast<RegisterSDNode>(N->getOperand(i))) {
343         IsRegSeq = false;
344         break;
345       }
346       RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
347       RegSeqArgs[1 + (2 * i) + 1] =
348               CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
349     }
350
351     if (NOps != NumVectorElts) {
352       // Fill in the missing undef elements if this was a scalar_to_vector.
353       assert(Opc == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
354
355       MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
356                                                      SDLoc(N), EltVT);
357       for (unsigned i = NOps; i < NumVectorElts; ++i) {
358         RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
359         RegSeqArgs[1 + (2 * i) + 1] =
360           CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
361       }
362     }
363
364     if (!IsRegSeq)
365       break;
366     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
367                                 RegSeqArgs);
368   }
369   case ISD::BUILD_PAIR: {
370     SDValue RC, SubReg0, SubReg1;
371     if (Subtarget->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
372       break;
373     }
374     if (N->getValueType(0) == MVT::i128) {
375       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32);
376       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, MVT::i32);
377       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, MVT::i32);
378     } else if (N->getValueType(0) == MVT::i64) {
379       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32);
380       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
381       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
382     } else {
383       llvm_unreachable("Unhandled value type for BUILD_PAIR");
384     }
385     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
386                             N->getOperand(1), SubReg1 };
387     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
388                                   SDLoc(N), N->getValueType(0), Ops);
389   }
390
391   case ISD::Constant:
392   case ISD::ConstantFP: {
393     if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
394         N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
395       break;
396
397     uint64_t Imm;
398     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
399       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
400     else {
401       ConstantSDNode *C = cast<ConstantSDNode>(N);
402       Imm = C->getZExtValue();
403     }
404
405     SDNode *Lo = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
406                                 CurDAG->getConstant(Imm & 0xFFFFFFFF, MVT::i32));
407     SDNode *Hi = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
408                                 CurDAG->getConstant(Imm >> 32, MVT::i32));
409     const SDValue Ops[] = {
410       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
411       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
412       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32)
413     };
414
415     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, SDLoc(N),
416                                   N->getValueType(0), Ops);
417   }
418
419   case ISD::LOAD: {
420     // To simplify the TableGen patters, we replace all i64 loads with
421     // v2i32 loads.  Alternatively, we could promote i64 loads to v2i32
422     // during DAG legalization, however, so places (ExpandUnalignedLoad)
423     // in the DAG legalizer assume that if i64 is legal, so doing this
424     // promotion early can cause problems.
425     EVT VT = N->getValueType(0);
426     LoadSDNode *LD = cast<LoadSDNode>(N);
427     if (VT != MVT::i64 || LD->getExtensionType() != ISD::NON_EXTLOAD)
428       break;
429
430     SDValue NewLoad = CurDAG->getLoad(MVT::v2i32, SDLoc(N), LD->getChain(),
431                                      LD->getBasePtr(), LD->getMemOperand());
432     SDValue BitCast = CurDAG->getNode(ISD::BITCAST, SDLoc(N),
433                                       MVT::i64, NewLoad);
434     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLoad.getValue(1));
435     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), BitCast);
436     SelectCode(NewLoad.getNode());
437     N = BitCast.getNode();
438     break;
439   }
440
441   case AMDGPUISD::REGISTER_LOAD: {
442     if (Subtarget->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS)
443       break;
444     SDValue Addr, Offset;
445
446     SelectADDRIndirect(N->getOperand(1), Addr, Offset);
447     const SDValue Ops[] = {
448       Addr,
449       Offset,
450       CurDAG->getTargetConstant(0, MVT::i32),
451       N->getOperand(0),
452     };
453     return CurDAG->getMachineNode(AMDGPU::SI_RegisterLoad, SDLoc(N),
454                                   CurDAG->getVTList(MVT::i32, MVT::i64, MVT::Other),
455                                   Ops);
456   }
457   case AMDGPUISD::REGISTER_STORE: {
458     if (Subtarget->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS)
459       break;
460     SDValue Addr, Offset;
461     SelectADDRIndirect(N->getOperand(2), Addr, Offset);
462     const SDValue Ops[] = {
463       N->getOperand(1),
464       Addr,
465       Offset,
466       CurDAG->getTargetConstant(0, MVT::i32),
467       N->getOperand(0),
468     };
469     return CurDAG->getMachineNode(AMDGPU::SI_RegisterStorePseudo, SDLoc(N),
470                                         CurDAG->getVTList(MVT::Other),
471                                         Ops);
472   }
473
474   case AMDGPUISD::BFE_I32:
475   case AMDGPUISD::BFE_U32: {
476     if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
477       break;
478
479     // There is a scalar version available, but unlike the vector version which
480     // has a separate operand for the offset and width, the scalar version packs
481     // the width and offset into a single operand. Try to move to the scalar
482     // version if the offsets are constant, so that we can try to keep extended
483     // loads of kernel arguments in SGPRs.
484
485     // TODO: Technically we could try to pattern match scalar bitshifts of
486     // dynamic values, but it's probably not useful.
487     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
488     if (!Offset)
489       break;
490
491     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
492     if (!Width)
493       break;
494
495     bool Signed = Opc == AMDGPUISD::BFE_I32;
496
497     // Transformation function, pack the offset and width of a BFE into
498     // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
499     // source, bits [5:0] contain the offset and bits [22:16] the width.
500
501     uint32_t OffsetVal = Offset->getZExtValue();
502     uint32_t WidthVal = Width->getZExtValue();
503
504     uint32_t PackedVal = OffsetVal | WidthVal << 16;
505
506     SDValue PackedOffsetWidth = CurDAG->getTargetConstant(PackedVal, MVT::i32);
507     return CurDAG->getMachineNode(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32,
508                                   SDLoc(N),
509                                   MVT::i32,
510                                   N->getOperand(0),
511                                   PackedOffsetWidth);
512
513   }
514   case AMDGPUISD::DIV_SCALE: {
515     return SelectDIV_SCALE(N);
516   }
517   case ISD::CopyToReg: {
518     const SITargetLowering& Lowering =
519       *static_cast<const SITargetLowering*>(getTargetLowering());
520     Lowering.legalizeTargetIndependentNode(N, *CurDAG);
521     break;
522   }
523   case ISD::ADDRSPACECAST:
524     return SelectAddrSpaceCast(N);
525   }
526
527   return SelectCode(N);
528 }
529
530
531 bool AMDGPUDAGToDAGISel::checkType(const Value *Ptr, unsigned AS) {
532   assert(AS != 0 && "Use checkPrivateAddress instead.");
533   if (!Ptr)
534     return false;
535
536   return Ptr->getType()->getPointerAddressSpace() == AS;
537 }
538
539 bool AMDGPUDAGToDAGISel::checkPrivateAddress(const MachineMemOperand *Op) {
540   if (Op->getPseudoValue())
541     return true;
542
543   if (PointerType *PT = dyn_cast<PointerType>(Op->getValue()->getType()))
544     return PT->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS;
545
546   return false;
547 }
548
549 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
550   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
551 }
552
553 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
554   const Value *MemVal = N->getMemOperand()->getValue();
555   return (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
556           !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
557           !checkType(MemVal, AMDGPUAS::REGION_ADDRESS));
558 }
559
560 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
561   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
562 }
563
564 bool AMDGPUDAGToDAGISel::isFlatStore(const StoreSDNode *N) {
565   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::FLAT_ADDRESS);
566 }
567
568 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
569   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
570 }
571
572 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int CbId) const {
573   const Value *MemVal = N->getMemOperand()->getValue();
574   if (CbId == -1)
575     return checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS);
576
577   return checkType(MemVal, AMDGPUAS::CONSTANT_BUFFER_0 + CbId);
578 }
579
580 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
581   if (N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS)
582     if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
583         N->getMemoryVT().bitsLT(MVT::i32))
584       return true;
585
586   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
587 }
588
589 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
590   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::PARAM_I_ADDRESS);
591 }
592
593 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
594   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
595 }
596
597 bool AMDGPUDAGToDAGISel::isFlatLoad(const  LoadSDNode *N) const {
598   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::FLAT_ADDRESS);
599 }
600
601 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
602   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
603 }
604
605 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
606   MachineMemOperand *MMO = N->getMemOperand();
607   if (checkPrivateAddress(N->getMemOperand())) {
608     if (MMO) {
609       const PseudoSourceValue *PSV = MMO->getPseudoValue();
610       if (PSV && PSV == PseudoSourceValue::getConstantPool()) {
611         return true;
612       }
613     }
614   }
615   return false;
616 }
617
618 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
619   if (checkPrivateAddress(N->getMemOperand())) {
620     // Check to make sure we are not a constant pool load or a constant load
621     // that is marked as a private load
622     if (isCPLoad(N) || isConstantLoad(N, -1)) {
623       return false;
624     }
625   }
626
627   const Value *MemVal = N->getMemOperand()->getValue();
628   if (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
629       !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
630       !checkType(MemVal, AMDGPUAS::FLAT_ADDRESS) &&
631       !checkType(MemVal, AMDGPUAS::REGION_ADDRESS) &&
632       !checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS) &&
633       !checkType(MemVal, AMDGPUAS::PARAM_D_ADDRESS) &&
634       !checkType(MemVal, AMDGPUAS::PARAM_I_ADDRESS)) {
635     return true;
636   }
637   return false;
638 }
639
640 const char *AMDGPUDAGToDAGISel::getPassName() const {
641   return "AMDGPU DAG->DAG Pattern Instruction Selection";
642 }
643
644 #ifdef DEBUGTMP
645 #undef INT64_C
646 #endif
647 #undef DEBUGTMP
648
649 //===----------------------------------------------------------------------===//
650 // Complex Patterns
651 //===----------------------------------------------------------------------===//
652
653 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
654                                                          SDValue& IntPtr) {
655   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
656     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, true);
657     return true;
658   }
659   return false;
660 }
661
662 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
663     SDValue& BaseReg, SDValue &Offset) {
664   if (!isa<ConstantSDNode>(Addr)) {
665     BaseReg = Addr;
666     Offset = CurDAG->getIntPtrConstant(0, true);
667     return true;
668   }
669   return false;
670 }
671
672 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
673                                            SDValue &Offset) {
674   ConstantSDNode *IMMOffset;
675
676   if (Addr.getOpcode() == ISD::ADD
677       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
678       && isInt<16>(IMMOffset->getZExtValue())) {
679
680       Base = Addr.getOperand(0);
681       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
682       return true;
683   // If the pointer address is constant, we can move it to the offset field.
684   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
685              && isInt<16>(IMMOffset->getZExtValue())) {
686     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
687                                   SDLoc(CurDAG->getEntryNode()),
688                                   AMDGPU::ZERO, MVT::i32);
689     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
690     return true;
691   }
692
693   // Default case, no offset
694   Base = Addr;
695   Offset = CurDAG->getTargetConstant(0, MVT::i32);
696   return true;
697 }
698
699 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
700                                             SDValue &Offset) {
701   ConstantSDNode *C;
702
703   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
704     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
705     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
706   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
707             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
708     Base = Addr.getOperand(0);
709     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
710   } else {
711     Base = Addr;
712     Offset = CurDAG->getTargetConstant(0, MVT::i32);
713   }
714
715   return true;
716 }
717
718 SDNode *AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
719   SDLoc DL(N);
720   SDValue LHS = N->getOperand(0);
721   SDValue RHS = N->getOperand(1);
722
723   bool IsAdd = (N->getOpcode() == ISD::ADD);
724
725   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
726   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
727
728   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
729                                        DL, MVT::i32, LHS, Sub0);
730   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
731                                        DL, MVT::i32, LHS, Sub1);
732
733   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
734                                        DL, MVT::i32, RHS, Sub0);
735   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
736                                        DL, MVT::i32, RHS, Sub1);
737
738   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
739   SDValue AddLoArgs[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
740
741
742   unsigned Opc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
743   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
744
745   SDNode *AddLo = CurDAG->getMachineNode( Opc, DL, VTList, AddLoArgs);
746   SDValue Carry(AddLo, 1);
747   SDNode *AddHi
748     = CurDAG->getMachineNode(CarryOpc, DL, MVT::i32,
749                              SDValue(Hi0, 0), SDValue(Hi1, 0), Carry);
750
751   SDValue Args[5] = {
752     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
753     SDValue(AddLo,0),
754     Sub0,
755     SDValue(AddHi,0),
756     Sub1,
757   };
758   return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, MVT::i64, Args);
759 }
760
761 SDNode *AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
762   SDLoc SL(N);
763   EVT VT = N->getValueType(0);
764
765   assert(VT == MVT::f32 || VT == MVT::f64);
766
767   unsigned Opc
768     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
769
770   const SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
771   const SDValue False = CurDAG->getTargetConstant(0, MVT::i1);
772   SDValue Ops[] = {
773     Zero,             // src0_modifiers
774     N->getOperand(0), // src0
775     Zero,             // src1_modifiers
776     N->getOperand(1), // src1
777     Zero,             // src2_modifiers
778     N->getOperand(2), // src2
779     False,            // clamp
780     Zero              // omod
781   };
782
783   return CurDAG->SelectNodeTo(N, Opc, VT, MVT::i1, Ops);
784 }
785
786 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(const SDValue &Base, unsigned Offset,
787                                          unsigned OffsetBits) const {
788   if ((OffsetBits == 16 && !isUInt<16>(Offset)) ||
789       (OffsetBits == 8 && !isUInt<8>(Offset)))
790     return false;
791
792   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS)
793     return true;
794
795   // On Southern Islands instruction with a negative base value and an offset
796   // don't seem to work.
797   return CurDAG->SignBitIsZero(Base);
798 }
799
800 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
801                                               SDValue &Offset) const {
802   if (CurDAG->isBaseWithConstantOffset(Addr)) {
803     SDValue N0 = Addr.getOperand(0);
804     SDValue N1 = Addr.getOperand(1);
805     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
806     if (isDSOffsetLegal(N0, C1->getSExtValue(), 16)) {
807       // (add n0, c0)
808       Base = N0;
809       Offset = N1;
810       return true;
811     }
812   }
813
814   // If we have a constant address, prefer to put the constant into the
815   // offset. This can save moves to load the constant address since multiple
816   // operations can share the zero base address register, and enables merging
817   // into read2 / write2 instructions.
818   if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
819     if (isUInt<16>(CAddr->getZExtValue())) {
820       SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
821       MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
822                                  SDLoc(Addr), MVT::i32, Zero);
823       Base = SDValue(MovZero, 0);
824       Offset = Addr;
825       return true;
826     }
827   }
828
829   // default case
830   Base = Addr;
831   Offset = CurDAG->getTargetConstant(0, MVT::i16);
832   return true;
833 }
834
835 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
836                                                    SDValue &Offset0,
837                                                    SDValue &Offset1) const {
838   if (CurDAG->isBaseWithConstantOffset(Addr)) {
839     SDValue N0 = Addr.getOperand(0);
840     SDValue N1 = Addr.getOperand(1);
841     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
842     unsigned DWordOffset0 = C1->getZExtValue() / 4;
843     unsigned DWordOffset1 = DWordOffset0 + 1;
844     // (add n0, c0)
845     if (isDSOffsetLegal(N0, DWordOffset1, 8)) {
846       Base = N0;
847       Offset0 = CurDAG->getTargetConstant(DWordOffset0, MVT::i8);
848       Offset1 = CurDAG->getTargetConstant(DWordOffset1, MVT::i8);
849       return true;
850     }
851   }
852
853   if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
854     unsigned DWordOffset0 = CAddr->getZExtValue() / 4;
855     unsigned DWordOffset1 = DWordOffset0 + 1;
856     assert(4 * DWordOffset0 == CAddr->getZExtValue());
857
858     if (isUInt<8>(DWordOffset0) && isUInt<8>(DWordOffset1)) {
859       SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
860       MachineSDNode *MovZero
861         = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
862                                  SDLoc(Addr), MVT::i32, Zero);
863       Base = SDValue(MovZero, 0);
864       Offset0 = CurDAG->getTargetConstant(DWordOffset0, MVT::i8);
865       Offset1 = CurDAG->getTargetConstant(DWordOffset1, MVT::i8);
866       return true;
867     }
868   }
869
870   // default case
871   Base = Addr;
872   Offset0 = CurDAG->getTargetConstant(0, MVT::i8);
873   Offset1 = CurDAG->getTargetConstant(1, MVT::i8);
874   return true;
875 }
876
877 static bool isLegalMUBUFImmOffset(const ConstantSDNode *Imm) {
878   return isUInt<12>(Imm->getZExtValue());
879 }
880
881 void AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr,
882                                      SDValue &VAddr, SDValue &SOffset,
883                                      SDValue &Offset, SDValue &Offen,
884                                      SDValue &Idxen, SDValue &Addr64,
885                                      SDValue &GLC, SDValue &SLC,
886                                      SDValue &TFE) const {
887   SDLoc DL(Addr);
888
889   GLC = CurDAG->getTargetConstant(0, MVT::i1);
890   SLC = CurDAG->getTargetConstant(0, MVT::i1);
891   TFE = CurDAG->getTargetConstant(0, MVT::i1);
892
893   Idxen = CurDAG->getTargetConstant(0, MVT::i1);
894   Offen = CurDAG->getTargetConstant(0, MVT::i1);
895   Addr64 = CurDAG->getTargetConstant(0, MVT::i1);
896   SOffset = CurDAG->getTargetConstant(0, MVT::i32);
897
898   if (CurDAG->isBaseWithConstantOffset(Addr)) {
899     SDValue N0 = Addr.getOperand(0);
900     SDValue N1 = Addr.getOperand(1);
901     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
902
903     if (isLegalMUBUFImmOffset(C1)) {
904
905       if (N0.getOpcode() == ISD::ADD) {
906         // (add (add N2, N3), C1) -> addr64
907         SDValue N2 = N0.getOperand(0);
908         SDValue N3 = N0.getOperand(1);
909         Addr64 = CurDAG->getTargetConstant(1, MVT::i1);
910         Ptr = N2;
911         VAddr = N3;
912         Offset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
913         return;
914       }
915
916       // (add N0, C1) -> offset
917       VAddr = CurDAG->getTargetConstant(0, MVT::i32);
918       Ptr = N0;
919       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
920       return;
921     }
922   }
923   if (Addr.getOpcode() == ISD::ADD) {
924     // (add N0, N1) -> addr64
925     SDValue N0 = Addr.getOperand(0);
926     SDValue N1 = Addr.getOperand(1);
927     Addr64 = CurDAG->getTargetConstant(1, MVT::i1);
928     Ptr = N0;
929     VAddr = N1;
930     Offset = CurDAG->getTargetConstant(0, MVT::i16);
931     return;
932   }
933
934   // default case -> offset
935   VAddr = CurDAG->getTargetConstant(0, MVT::i32);
936   Ptr = Addr;
937   Offset = CurDAG->getTargetConstant(0, MVT::i16);
938
939 }
940
941 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
942                                            SDValue &VAddr,
943                                            SDValue &Offset) const {
944   SDValue Ptr, SOffset, Offen, Idxen, Addr64, GLC, SLC, TFE;
945
946   SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
947               GLC, SLC, TFE);
948
949   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
950   if (C->getSExtValue()) {
951     SDLoc DL(Addr);
952
953     const SITargetLowering& Lowering =
954       *static_cast<const SITargetLowering*>(getTargetLowering());
955
956     SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
957     return true;
958   }
959
960   return false;
961 }
962
963 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
964                                            SDValue &VAddr, SDValue &Offset,
965                                            SDValue &SLC) const {
966   SLC = CurDAG->getTargetConstant(0, MVT::i1);
967
968   return SelectMUBUFAddr64(Addr, SRsrc, VAddr, Offset);
969 }
970
971 bool AMDGPUDAGToDAGISel::SelectMUBUFScratch(SDValue Addr, SDValue &Rsrc,
972                                             SDValue &VAddr, SDValue &SOffset,
973                                             SDValue &ImmOffset) const {
974
975   SDLoc DL(Addr);
976   MachineFunction &MF = CurDAG->getMachineFunction();
977   const SIRegisterInfo *TRI =
978       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
979   MachineRegisterInfo &MRI = MF.getRegInfo();
980   const SITargetLowering& Lowering =
981     *static_cast<const SITargetLowering*>(getTargetLowering());
982
983   unsigned ScratchOffsetReg =
984       TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET);
985   Lowering.CreateLiveInRegister(*CurDAG, &AMDGPU::SReg_32RegClass,
986                                 ScratchOffsetReg, MVT::i32);
987   SDValue Sym0 = CurDAG->getExternalSymbol("SCRATCH_RSRC_DWORD0", MVT::i32);
988   SDValue ScratchRsrcDword0 =
989       SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, Sym0), 0);
990
991   SDValue Sym1 = CurDAG->getExternalSymbol("SCRATCH_RSRC_DWORD1", MVT::i32);
992   SDValue ScratchRsrcDword1 =
993       SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, Sym1), 0);
994
995   const SDValue RsrcOps[] = {
996       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
997       ScratchRsrcDword0,
998       CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
999       ScratchRsrcDword1,
1000       CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32),
1001   };
1002   SDValue ScratchPtr = SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1003                                               MVT::v2i32, RsrcOps), 0);
1004   Rsrc = SDValue(Lowering.buildScratchRSRC(*CurDAG, DL, ScratchPtr), 0);
1005   SOffset = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
1006       MRI.getLiveInVirtReg(ScratchOffsetReg), MVT::i32);
1007
1008   // (add n0, c1)
1009   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1010     SDValue N1 = Addr.getOperand(1);
1011     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1012
1013     if (isLegalMUBUFImmOffset(C1)) {
1014       VAddr = Addr.getOperand(0);
1015       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
1016       return true;
1017     }
1018   }
1019
1020   // (node)
1021   VAddr = Addr;
1022   ImmOffset = CurDAG->getTargetConstant(0, MVT::i16);
1023   return true;
1024 }
1025
1026 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1027                                            SDValue &SOffset, SDValue &Offset,
1028                                            SDValue &GLC, SDValue &SLC,
1029                                            SDValue &TFE) const {
1030   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1031   const SIInstrInfo *TII =
1032     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1033
1034   SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1035               GLC, SLC, TFE);
1036
1037   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1038       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1039       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1040     uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1041                     APInt::getAllOnesValue(32).getZExtValue(); // Size
1042     SDLoc DL(Addr);
1043
1044     const SITargetLowering& Lowering =
1045       *static_cast<const SITargetLowering*>(getTargetLowering());
1046
1047     SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1048     return true;
1049   }
1050   return false;
1051 }
1052
1053 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1054                                            SDValue &Soffset, SDValue &Offset,
1055                                            SDValue &GLC) const {
1056   SDValue SLC, TFE;
1057
1058   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE);
1059 }
1060
1061 // FIXME: This is incorrect and only enough to be able to compile.
1062 SDNode *AMDGPUDAGToDAGISel::SelectAddrSpaceCast(SDNode *N) {
1063   AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(N);
1064   SDLoc DL(N);
1065
1066   assert(Subtarget->hasFlatAddressSpace() &&
1067          "addrspacecast only supported with flat address space!");
1068
1069   assert((ASC->getSrcAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
1070           ASC->getDestAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) &&
1071          "Cannot cast address space to / from constant address!");
1072
1073   assert((ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS ||
1074           ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) &&
1075          "Can only cast to / from flat address space!");
1076
1077   // The flat instructions read the address as the index of the VGPR holding the
1078   // address, so casting should just be reinterpreting the base VGPR, so just
1079   // insert trunc / bitcast / zext.
1080
1081   SDValue Src = ASC->getOperand(0);
1082   EVT DestVT = ASC->getValueType(0);
1083   EVT SrcVT = Src.getValueType();
1084
1085   unsigned SrcSize = SrcVT.getSizeInBits();
1086   unsigned DestSize = DestVT.getSizeInBits();
1087
1088   if (SrcSize > DestSize) {
1089     assert(SrcSize == 64 && DestSize == 32);
1090     return CurDAG->getMachineNode(
1091       TargetOpcode::EXTRACT_SUBREG,
1092       DL,
1093       DestVT,
1094       Src,
1095       CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32));
1096   }
1097
1098
1099   if (DestSize > SrcSize) {
1100     assert(SrcSize == 32 && DestSize == 64);
1101
1102     // FIXME: This is probably wrong, we should never be defining
1103     // a register class with both VGPRs and SGPRs
1104     SDValue RC = CurDAG->getTargetConstant(AMDGPU::VS_64RegClassID, MVT::i32);
1105
1106     const SDValue Ops[] = {
1107       RC,
1108       Src,
1109       CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
1110       SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
1111                                      CurDAG->getConstant(0, MVT::i32)), 0),
1112       CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32)
1113     };
1114
1115     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1116                                   SDLoc(N), N->getValueType(0), Ops);
1117   }
1118
1119   assert(SrcSize == 64 && DestSize == 64);
1120   return CurDAG->getNode(ISD::BITCAST, DL, DestVT, Src).getNode();
1121 }
1122
1123 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
1124                                         SDValue &SrcMods) const {
1125
1126   unsigned Mods = 0;
1127
1128   Src = In;
1129
1130   if (Src.getOpcode() == ISD::FNEG) {
1131     Mods |= SISrcMods::NEG;
1132     Src = Src.getOperand(0);
1133   }
1134
1135   if (Src.getOpcode() == ISD::FABS) {
1136     Mods |= SISrcMods::ABS;
1137     Src = Src.getOperand(0);
1138   }
1139
1140   SrcMods = CurDAG->getTargetConstant(Mods, MVT::i32);
1141
1142   return true;
1143 }
1144
1145 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
1146                                          SDValue &SrcMods, SDValue &Clamp,
1147                                          SDValue &Omod) const {
1148   // FIXME: Handle Clamp and Omod
1149   Clamp = CurDAG->getTargetConstant(0, MVT::i32);
1150   Omod = CurDAG->getTargetConstant(0, MVT::i32);
1151
1152   return SelectVOP3Mods(In, Src, SrcMods);
1153 }
1154
1155 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp(SDValue In, SDValue &Src,
1156                                               SDValue &SrcMods,
1157                                               SDValue &Omod) const {
1158   // FIXME: Handle Omod
1159   Omod = CurDAG->getTargetConstant(0, MVT::i32);
1160
1161   return SelectVOP3Mods(In, Src, SrcMods);
1162 }
1163
1164 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src,
1165                                                    SDValue &SrcMods,
1166                                                    SDValue &Clamp,
1167                                                    SDValue &Omod) const {
1168   Clamp = Omod = CurDAG->getTargetConstant(0, MVT::i32);
1169   return SelectVOP3Mods(In, Src, SrcMods);
1170 }
1171
1172 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
1173   const AMDGPUTargetLowering& Lowering =
1174     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
1175   bool IsModified = false;
1176   do {
1177     IsModified = false;
1178     // Go over all selected nodes and try to fold them a bit more
1179     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1180          E = CurDAG->allnodes_end(); I != E; ++I) {
1181
1182       SDNode *Node = I;
1183
1184       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1185       if (!MachineNode)
1186         continue;
1187
1188       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
1189       if (ResNode != Node) {
1190         ReplaceUses(Node, ResNode);
1191         IsModified = true;
1192       }
1193     }
1194     CurDAG->RemoveDeadNodes();
1195   } while (IsModified);
1196 }