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