LLVM  8.0.0svn
SIISelLowering.cpp
Go to the documentation of this file.
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #if defined(_MSC_VER) || defined(__MINGW32__)
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #endif
19 
20 #include "SIISelLowering.h"
21 #include "AMDGPU.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "AMDGPUTargetMachine.h"
25 #include "SIDefines.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/CodeGen/Analysis.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
73 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/KnownBits.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
94  "amdgpu-vgpr-index-mode",
95  cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
96  cl::init(false));
97 
99  "amdgpu-frame-index-zero-bits",
100  cl::desc("High bits of frame index assumed to be zero"),
101  cl::init(5),
103 
104 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
105  unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
106  for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
107  if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
108  return AMDGPU::SGPR0 + Reg;
109  }
110  }
111  llvm_unreachable("Cannot allocate sgpr");
112 }
113 
115  const GCNSubtarget &STI)
116  : AMDGPUTargetLowering(TM, STI),
117  Subtarget(&STI) {
118  addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
119  addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
120 
121  addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
122  addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
123 
124  addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
125  addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
126  addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
127 
128  addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129  addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
130 
131  addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132  addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
133 
134  addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
135  addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
136 
137  addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
138  addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
139 
140  if (Subtarget->has16BitInsts()) {
141  addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
142  addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
143 
144  // Unless there are also VOP3P operations, not operations are really legal.
145  addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
146  addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
147  addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
148  addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
149  }
150 
152 
153  // We need to custom lower vector stores from local memory
160 
167 
178 
181 
186 
192 
197 
200 
208 
216 
220 
225 
232 
235 
238 
242 
243 #if 0
246 #endif
247 
248  // We only support LOAD/STORE and vector manipulation ops for vectors
249  // with > 4 elements.
252  for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
253  switch (Op) {
254  case ISD::LOAD:
255  case ISD::STORE:
256  case ISD::BUILD_VECTOR:
257  case ISD::BITCAST:
263  break;
264  case ISD::CONCAT_VECTORS:
266  break;
267  default:
269  break;
270  }
271  }
272  }
273 
275 
276  // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
277  // is expanded to avoid having two separate loops in case the index is a VGPR.
278 
279  // Most operations are naturally 32-bit vector operations. We only support
280  // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
281  for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
284 
287 
290 
293  }
294 
299 
302 
303  // Avoid stack access for these.
304  // TODO: Generalize to more vector types.
309 
315 
319 
324 
325  // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
326  // and output demarshalling
329 
330  // We can't return success/failure, only the old value,
331  // let LLVM add the comparison
334 
335  if (Subtarget->hasFlatAddressSpace()) {
338  }
339 
342 
343  // On SI this is s_memtime and s_memrealtime on VI.
347 
348  if (Subtarget->has16BitInsts()) {
352  }
353 
354  // v_mad_f32 does not support denormals according to some sources.
355  if (!Subtarget->hasFP32Denormals())
357 
358  if (!Subtarget->hasBFI()) {
359  // fcopysign can be done in a single instruction with BFI.
362  }
363 
364  if (!Subtarget->hasBCNT(32))
366 
367  if (!Subtarget->hasBCNT(64))
369 
370  if (Subtarget->hasFFBH())
372 
373  if (Subtarget->hasFFBL())
375 
376  // We only really have 32-bit BFE instructions (and 16-bit on VI).
377  //
378  // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
379  // effort to match them now. We want this to be false for i64 cases when the
380  // extraction isn't restricted to the upper or lower half. Ideally we would
381  // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
382  // span the midpoint are probably relatively rare, so don't worry about them
383  // for now.
384  if (Subtarget->hasBFE())
385  setHasExtractBitsInsn(true);
386 
391 
392 
393  // These are really only legal for ieee_mode functions. We should be avoiding
394  // them for functions that don't have ieee_mode enabled, so just say they are
395  // legal.
400 
401 
402  if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
406  } else {
411  }
412 
414 
419 
420  if (Subtarget->has16BitInsts()) {
422 
425 
428 
431 
434 
439 
442 
448 
450 
452 
454 
456 
461 
466 
467  // F16 - Constant Actions.
469 
470  // F16 - Load/Store Actions.
475 
476  // F16 - VOP1 Actions.
485 
486  // F16 - VOP2 Actions.
489 
491 
492  // F16 - VOP3 Actions.
494  if (!Subtarget->hasFP16Denormals())
496 
497  for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
498  for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
499  switch (Op) {
500  case ISD::LOAD:
501  case ISD::STORE:
502  case ISD::BUILD_VECTOR:
503  case ISD::BITCAST:
509  break;
510  case ISD::CONCAT_VECTORS:
512  break;
513  default:
515  break;
516  }
517  }
518  }
519 
520  // XXX - Do these do anything? Vector constants turn into build_vector.
523 
526 
531 
536 
543 
548 
553 
558 
562 
563  if (!Subtarget->hasVOP3PInsts()) {
566  }
567 
569  // This isn't really legal, but this avoids the legalizer unrolling it (and
570  // allows matching fneg (fabs x) patterns)
572 
577 
580 
583  }
584 
585  if (Subtarget->hasVOP3PInsts()) {
596 
600 
603 
605 
608 
615 
620 
623 
626 
630 
634  }
635 
638 
639  if (Subtarget->has16BitInsts()) {
644  } else {
645  // Legalization hack.
648 
651  }
652 
655  }
656 
682 
683  // All memory operations. Some folding on the pointer operand is done to help
684  // matching the constant offsets in the addressing modes.
702 
704 
705  // SI at least has hardware support for floating point exceptions, but no way
706  // of using or handling them is implemented. They are also optional in OpenCL
707  // (Section 7.3)
709 }
710 
712  return Subtarget;
713 }
714 
715 //===----------------------------------------------------------------------===//
716 // TargetLowering queries
717 //===----------------------------------------------------------------------===//
718 
719 // v_mad_mix* support a conversion from f16 to f32.
720 //
721 // There is only one special case when denormals are enabled we don't currently,
722 // where this is OK to use.
724  EVT DestVT, EVT SrcVT) const {
725  return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
726  (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
727  DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
728  SrcVT.getScalarType() == MVT::f16;
729 }
730 
732  // SI has some legal vector types, but no legal vector operations. Say no
733  // shuffles are legal in order to prefer scalarizing some vector operations.
734  return false;
735 }
736 
738  CallingConv::ID CC,
739  EVT VT) const {
740  // TODO: Consider splitting all arguments into 32-bit pieces.
741  if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
742  EVT ScalarVT = VT.getScalarType();
743  unsigned Size = ScalarVT.getSizeInBits();
744  if (Size == 32)
745  return ScalarVT.getSimpleVT();
746 
747  if (Size == 64)
748  return MVT::i32;
749 
750  if (Size == 16 && Subtarget->has16BitInsts())
751  return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
752  }
753 
754  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
755 }
756 
758  CallingConv::ID CC,
759  EVT VT) const {
760  if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
761  unsigned NumElts = VT.getVectorNumElements();
762  EVT ScalarVT = VT.getScalarType();
763  unsigned Size = ScalarVT.getSizeInBits();
764 
765  if (Size == 32)
766  return NumElts;
767 
768  if (Size == 64)
769  return 2 * NumElts;
770 
771  if (Size == 16 && Subtarget->has16BitInsts())
772  return (VT.getVectorNumElements() + 1) / 2;
773  }
774 
775  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
776 }
777 
780  EVT VT, EVT &IntermediateVT,
781  unsigned &NumIntermediates, MVT &RegisterVT) const {
782  if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
783  unsigned NumElts = VT.getVectorNumElements();
784  EVT ScalarVT = VT.getScalarType();
785  unsigned Size = ScalarVT.getSizeInBits();
786  if (Size == 32) {
787  RegisterVT = ScalarVT.getSimpleVT();
788  IntermediateVT = RegisterVT;
789  NumIntermediates = NumElts;
790  return NumIntermediates;
791  }
792 
793  if (Size == 64) {
794  RegisterVT = MVT::i32;
795  IntermediateVT = RegisterVT;
796  NumIntermediates = 2 * NumElts;
797  return NumIntermediates;
798  }
799 
800  // FIXME: We should fix the ABI to be the same on targets without 16-bit
801  // support, but unless we can properly handle 3-vectors, it will be still be
802  // inconsistent.
803  if (Size == 16 && Subtarget->has16BitInsts()) {
804  RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
805  IntermediateVT = RegisterVT;
806  NumIntermediates = (NumElts + 1) / 2;
807  return NumIntermediates;
808  }
809  }
810 
812  Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
813 }
814 
816  const CallInst &CI,
817  MachineFunction &MF,
818  unsigned IntrID) const {
819  if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
820  AMDGPU::lookupRsrcIntrinsic(IntrID)) {
822  (Intrinsic::ID)IntrID);
823  if (Attr.hasFnAttribute(Attribute::ReadNone))
824  return false;
825 
827 
828  if (RsrcIntr->IsImage) {
829  Info.ptrVal = MFI->getImagePSV(
831  CI.getArgOperand(RsrcIntr->RsrcArg));
832  Info.align = 0;
833  } else {
834  Info.ptrVal = MFI->getBufferPSV(
836  CI.getArgOperand(RsrcIntr->RsrcArg));
837  }
838 
840  if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
842  Info.memVT = MVT::getVT(CI.getType());
844  } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
845  Info.opc = ISD::INTRINSIC_VOID;
846  Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
848  } else {
849  // Atomic
851  Info.memVT = MVT::getVT(CI.getType());
855 
856  // XXX - Should this be volatile without known ordering?
858  }
859  return true;
860  }
861 
862  switch (IntrID) {
863  case Intrinsic::amdgcn_atomic_inc:
864  case Intrinsic::amdgcn_atomic_dec:
865  case Intrinsic::amdgcn_ds_fadd:
866  case Intrinsic::amdgcn_ds_fmin:
867  case Intrinsic::amdgcn_ds_fmax: {
869  Info.memVT = MVT::getVT(CI.getType());
870  Info.ptrVal = CI.getOperand(0);
871  Info.align = 0;
873 
874  const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
875  if (!Vol || !Vol->isZero())
877 
878  return true;
879  }
880 
881  default:
882  return false;
883  }
884 }
885 
888  Type *&AccessTy) const {
889  switch (II->getIntrinsicID()) {
890  case Intrinsic::amdgcn_atomic_inc:
891  case Intrinsic::amdgcn_atomic_dec:
892  case Intrinsic::amdgcn_ds_fadd:
893  case Intrinsic::amdgcn_ds_fmin:
894  case Intrinsic::amdgcn_ds_fmax: {
895  Value *Ptr = II->getArgOperand(0);
896  AccessTy = II->getType();
897  Ops.push_back(Ptr);
898  return true;
899  }
900  default:
901  return false;
902  }
903 }
904 
905 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
906  if (!Subtarget->hasFlatInstOffsets()) {
907  // Flat instructions do not have offsets, and only have the register
908  // address.
909  return AM.BaseOffs == 0 && AM.Scale == 0;
910  }
911 
912  // GFX9 added a 13-bit signed offset. When using regular flat instructions,
913  // the sign bit is ignored and is treated as a 12-bit unsigned offset.
914 
915  // Just r + i
916  return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
917 }
918 
919 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
920  if (Subtarget->hasFlatGlobalInsts())
921  return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
922 
923  if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
924  // Assume the we will use FLAT for all global memory accesses
925  // on VI.
926  // FIXME: This assumption is currently wrong. On VI we still use
927  // MUBUF instructions for the r + i addressing mode. As currently
928  // implemented, the MUBUF instructions only work on buffer < 4GB.
929  // It may be possible to support > 4GB buffers with MUBUF instructions,
930  // by setting the stride value in the resource descriptor which would
931  // increase the size limit to (stride * 4GB). However, this is risky,
932  // because it has never been validated.
933  return isLegalFlatAddressingMode(AM);
934  }
935 
936  return isLegalMUBUFAddressingMode(AM);
937 }
938 
939 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
940  // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
941  // additionally can do r + r + i with addr64. 32-bit has more addressing
942  // mode options. Depending on the resource constant, it can also do
943  // (i64 r0) + (i32 r1) * (i14 i).
944  //
945  // Private arrays end up using a scratch buffer most of the time, so also
946  // assume those use MUBUF instructions. Scratch loads / stores are currently
947  // implemented as mubuf instructions with offen bit set, so slightly
948  // different than the normal addr64.
949  if (!isUInt<12>(AM.BaseOffs))
950  return false;
951 
952  // FIXME: Since we can split immediate into soffset and immediate offset,
953  // would it make sense to allow any immediate?
954 
955  switch (AM.Scale) {
956  case 0: // r + i or just i, depending on HasBaseReg.
957  return true;
958  case 1:
959  return true; // We have r + r or r + i.
960  case 2:
961  if (AM.HasBaseReg) {
962  // Reject 2 * r + r.
963  return false;
964  }
965 
966  // Allow 2 * r as r + r
967  // Or 2 * r + i is allowed as r + r + i.
968  return true;
969  default: // Don't allow n * r
970  return false;
971  }
972 }
973 
975  const AddrMode &AM, Type *Ty,
976  unsigned AS, Instruction *I) const {
977  // No global is ever allowed as a base.
978  if (AM.BaseGV)
979  return false;
980 
981  if (AS == AMDGPUAS::GLOBAL_ADDRESS)
982  return isLegalGlobalAddressingMode(AM);
983 
984  if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
986  // If the offset isn't a multiple of 4, it probably isn't going to be
987  // correctly aligned.
988  // FIXME: Can we get the real alignment here?
989  if (AM.BaseOffs % 4 != 0)
990  return isLegalMUBUFAddressingMode(AM);
991 
992  // There are no SMRD extloads, so if we have to do a small type access we
993  // will use a MUBUF load.
994  // FIXME?: We also need to do this if unaligned, but we don't know the
995  // alignment here.
996  if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
997  return isLegalGlobalAddressingMode(AM);
998 
999  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1000  // SMRD instructions have an 8-bit, dword offset on SI.
1001  if (!isUInt<8>(AM.BaseOffs / 4))
1002  return false;
1003  } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1004  // On CI+, this can also be a 32-bit literal constant offset. If it fits
1005  // in 8-bits, it can use a smaller encoding.
1006  if (!isUInt<32>(AM.BaseOffs / 4))
1007  return false;
1008  } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1009  // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1010  if (!isUInt<20>(AM.BaseOffs))
1011  return false;
1012  } else
1013  llvm_unreachable("unhandled generation");
1014 
1015  if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1016  return true;
1017 
1018  if (AM.Scale == 1 && AM.HasBaseReg)
1019  return true;
1020 
1021  return false;
1022 
1023  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1024  return isLegalMUBUFAddressingMode(AM);
1025  } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1026  AS == AMDGPUAS::REGION_ADDRESS) {
1027  // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1028  // field.
1029  // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1030  // an 8-bit dword offset but we don't know the alignment here.
1031  if (!isUInt<16>(AM.BaseOffs))
1032  return false;
1033 
1034  if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1035  return true;
1036 
1037  if (AM.Scale == 1 && AM.HasBaseReg)
1038  return true;
1039 
1040  return false;
1041  } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1043  // For an unknown address space, this usually means that this is for some
1044  // reason being used for pure arithmetic, and not based on some addressing
1045  // computation. We don't have instructions that compute pointers with any
1046  // addressing modes, so treat them as having no offset like flat
1047  // instructions.
1048  return isLegalFlatAddressingMode(AM);
1049  } else {
1050  llvm_unreachable("unhandled address space");
1051  }
1052 }
1053 
1054 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1055  const SelectionDAG &DAG) const {
1056  if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1057  return (MemVT.getSizeInBits() <= 4 * 32);
1058  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1059  unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1060  return (MemVT.getSizeInBits() <= MaxPrivateBits);
1061  } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
1062  return (MemVT.getSizeInBits() <= 2 * 32);
1063  }
1064  return true;
1065 }
1066 
1068  unsigned AddrSpace,
1069  unsigned Align,
1070  bool *IsFast) const {
1071  if (IsFast)
1072  *IsFast = false;
1073 
1074  // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1075  // which isn't a simple VT.
1076  // Until MVT is extended to handle this, simply check for the size and
1077  // rely on the condition below: allow accesses if the size is a multiple of 4.
1078  if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1079  VT.getStoreSize() > 16)) {
1080  return false;
1081  }
1082 
1083  if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1084  AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1085  // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1086  // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1087  // with adjacent offsets.
1088  bool AlignedBy4 = (Align % 4 == 0);
1089  if (IsFast)
1090  *IsFast = AlignedBy4;
1091 
1092  return AlignedBy4;
1093  }
1094 
1095  // FIXME: We have to be conservative here and assume that flat operations
1096  // will access scratch. If we had access to the IR function, then we
1097  // could determine if any private memory was used in the function.
1098  if (!Subtarget->hasUnalignedScratchAccess() &&
1099  (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1100  AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1101  bool AlignedBy4 = Align >= 4;
1102  if (IsFast)
1103  *IsFast = AlignedBy4;
1104 
1105  return AlignedBy4;
1106  }
1107 
1108  if (Subtarget->hasUnalignedBufferAccess()) {
1109  // If we have an uniform constant load, it still requires using a slow
1110  // buffer instruction if unaligned.
1111  if (IsFast) {
1112  *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1113  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1114  (Align % 4 == 0) : true;
1115  }
1116 
1117  return true;
1118  }
1119 
1120  // Smaller than dword value must be aligned.
1121  if (VT.bitsLT(MVT::i32))
1122  return false;
1123 
1124  // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1125  // byte-address are ignored, thus forcing Dword alignment.
1126  // This applies to private, global, and constant memory.
1127  if (IsFast)
1128  *IsFast = true;
1129 
1130  return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1131 }
1132 
1133 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1134  unsigned SrcAlign, bool IsMemset,
1135  bool ZeroMemset,
1136  bool MemcpyStrSrc,
1137  MachineFunction &MF) const {
1138  // FIXME: Should account for address space here.
1139 
1140  // The default fallback uses the private pointer size as a guess for a type to
1141  // use. Make sure we switch these to 64-bit accesses.
1142 
1143  if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1144  return MVT::v4i32;
1145 
1146  if (Size >= 8 && DstAlign >= 4)
1147  return MVT::v2i32;
1148 
1149  // Use the default.
1150  return MVT::Other;
1151 }
1152 
1153 static bool isFlatGlobalAddrSpace(unsigned AS) {
1154  return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1155  AS == AMDGPUAS::FLAT_ADDRESS ||
1157 }
1158 
1160  unsigned DestAS) const {
1161  return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1162 }
1163 
1165  const MemSDNode *MemNode = cast<MemSDNode>(N);
1166  const Value *Ptr = MemNode->getMemOperand()->getValue();
1167  const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1168  return I && I->getMetadata("amdgpu.noclobber");
1169 }
1170 
1172  unsigned DestAS) const {
1173  // Flat -> private/local is a simple truncate.
1174  // Flat -> global is no-op
1175  if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1176  return true;
1177 
1178  return isNoopAddrSpaceCast(SrcAS, DestAS);
1179 }
1180 
1182  const MemSDNode *MemNode = cast<MemSDNode>(N);
1183 
1184  return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1185 }
1186 
1189  if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1190  return TypeSplitVector;
1191 
1193 }
1194 
1196  Type *Ty) const {
1197  // FIXME: Could be smarter if called for vector constants.
1198  return true;
1199 }
1200 
1202  if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1203  switch (Op) {
1204  case ISD::LOAD:
1205  case ISD::STORE:
1206 
1207  // These operations are done with 32-bit instructions anyway.
1208  case ISD::AND:
1209  case ISD::OR:
1210  case ISD::XOR:
1211  case ISD::SELECT:
1212  // TODO: Extensions?
1213  return true;
1214  default:
1215  return false;
1216  }
1217  }
1218 
1219  // SimplifySetCC uses this function to determine whether or not it should
1220  // create setcc with i1 operands. We don't have instructions for i1 setcc.
1221  if (VT == MVT::i1 && Op == ISD::SETCC)
1222  return false;
1223 
1224  return TargetLowering::isTypeDesirableForOp(Op, VT);
1225 }
1226 
1227 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1228  const SDLoc &SL,
1229  SDValue Chain,
1230  uint64_t Offset) const {
1231  const DataLayout &DL = DAG.getDataLayout();
1232  MachineFunction &MF = DAG.getMachineFunction();
1234 
1235  const ArgDescriptor *InputPtrReg;
1236  const TargetRegisterClass *RC;
1237 
1238  std::tie(InputPtrReg, RC)
1240 
1243  SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1244  MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1245 
1246  return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1247 }
1248 
1249 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1250  const SDLoc &SL) const {
1251  uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1252  FIRST_IMPLICIT);
1253  return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1254 }
1255 
1256 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1257  const SDLoc &SL, SDValue Val,
1258  bool Signed,
1259  const ISD::InputArg *Arg) const {
1260  if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1261  VT.bitsLT(MemVT)) {
1262  unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1263  Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1264  }
1265 
1266  if (MemVT.isFloatingPoint())
1267  Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1268  else if (Signed)
1269  Val = DAG.getSExtOrTrunc(Val, SL, VT);
1270  else
1271  Val = DAG.getZExtOrTrunc(Val, SL, VT);
1272 
1273  return Val;
1274 }
1275 
1276 SDValue SITargetLowering::lowerKernargMemParameter(
1277  SelectionDAG &DAG, EVT VT, EVT MemVT,
1278  const SDLoc &SL, SDValue Chain,
1279  uint64_t Offset, unsigned Align, bool Signed,
1280  const ISD::InputArg *Arg) const {
1281  Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1283  MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1284 
1285  // Try to avoid using an extload by loading earlier than the argument address,
1286  // and extracting the relevant bits. The load should hopefully be merged with
1287  // the previous argument.
1288  if (MemVT.getStoreSize() < 4 && Align < 4) {
1289  // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1290  int64_t AlignDownOffset = alignDown(Offset, 4);
1291  int64_t OffsetDiff = Offset - AlignDownOffset;
1292 
1293  EVT IntVT = MemVT.changeTypeToInteger();
1294 
1295  // TODO: If we passed in the base kernel offset we could have a better
1296  // alignment than 4, but we don't really need it.
1297  SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1298  SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1301 
1302  SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1303  SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1304 
1305  SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1306  ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1307  ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1308 
1309 
1310  return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1311  }
1312 
1313  SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1314  SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1317 
1318  SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1319  return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1320 }
1321 
1322 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1323  const SDLoc &SL, SDValue Chain,
1324  const ISD::InputArg &Arg) const {
1325  MachineFunction &MF = DAG.getMachineFunction();
1326  MachineFrameInfo &MFI = MF.getFrameInfo();
1327 
1328  if (Arg.Flags.isByVal()) {
1329  unsigned Size = Arg.Flags.getByValSize();
1330  int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1331  return DAG.getFrameIndex(FrameIdx, MVT::i32);
1332  }
1333 
1334  unsigned ArgOffset = VA.getLocMemOffset();
1335  unsigned ArgSize = VA.getValVT().getStoreSize();
1336 
1337  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1338 
1339  // Create load nodes to retrieve arguments from the stack.
1340  SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1341  SDValue ArgValue;
1342 
1343  // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1345  MVT MemVT = VA.getValVT();
1346 
1347  switch (VA.getLocInfo()) {
1348  default:
1349  break;
1350  case CCValAssign::BCvt:
1351  MemVT = VA.getLocVT();
1352  break;
1353  case CCValAssign::SExt:
1354  ExtType = ISD::SEXTLOAD;
1355  break;
1356  case CCValAssign::ZExt:
1357  ExtType = ISD::ZEXTLOAD;
1358  break;
1359  case CCValAssign::AExt:
1360  ExtType = ISD::EXTLOAD;
1361  break;
1362  }
1363 
1364  ArgValue = DAG.getExtLoad(
1365  ExtType, SL, VA.getLocVT(), Chain, FIN,
1367  MemVT);
1368  return ArgValue;
1369 }
1370 
1371 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1372  const SIMachineFunctionInfo &MFI,
1373  EVT VT,
1375  const ArgDescriptor *Reg;
1376  const TargetRegisterClass *RC;
1377 
1378  std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1379  return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1380 }
1381 
1383  CallingConv::ID CallConv,
1385  BitVector &Skipped,
1386  FunctionType *FType,
1387  SIMachineFunctionInfo *Info) {
1388  for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1389  const ISD::InputArg *Arg = &Ins[I];
1390 
1391  assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1392  "vector type argument should have been split");
1393 
1394  // First check if it's a PS input addr.
1395  if (CallConv == CallingConv::AMDGPU_PS &&
1396  !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1397 
1398  bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1399 
1400  // Inconveniently only the first part of the split is marked as isSplit,
1401  // so skip to the end. We only want to increment PSInputNum once for the
1402  // entire split argument.
1403  if (Arg->Flags.isSplit()) {
1404  while (!Arg->Flags.isSplitEnd()) {
1405  assert(!Arg->VT.isVector() &&
1406  "unexpected vector split in ps argument type");
1407  if (!SkipArg)
1408  Splits.push_back(*Arg);
1409  Arg = &Ins[++I];
1410  }
1411  }
1412 
1413  if (SkipArg) {
1414  // We can safely skip PS inputs.
1415  Skipped.set(Arg->getOrigArgIndex());
1416  ++PSInputNum;
1417  continue;
1418  }
1419 
1420  Info->markPSInputAllocated(PSInputNum);
1421  if (Arg->Used)
1422  Info->markPSInputEnabled(PSInputNum);
1423 
1424  ++PSInputNum;
1425  }
1426 
1427  Splits.push_back(*Arg);
1428  }
1429 }
1430 
1431 // Allocate special inputs passed in VGPRs.
1433  MachineFunction &MF,
1434  const SIRegisterInfo &TRI,
1435  SIMachineFunctionInfo &Info) {
1436  if (Info.hasWorkItemIDX()) {
1437  unsigned Reg = AMDGPU::VGPR0;
1438  MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1439 
1440  CCInfo.AllocateReg(Reg);
1442  }
1443 
1444  if (Info.hasWorkItemIDY()) {
1445  unsigned Reg = AMDGPU::VGPR1;
1446  MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1447 
1448  CCInfo.AllocateReg(Reg);
1450  }
1451 
1452  if (Info.hasWorkItemIDZ()) {
1453  unsigned Reg = AMDGPU::VGPR2;
1454  MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1455 
1456  CCInfo.AllocateReg(Reg);
1458  }
1459 }
1460 
1461 // Try to allocate a VGPR at the end of the argument list, or if no argument
1462 // VGPRs are left allocating a stack slot.
1464  ArrayRef<MCPhysReg> ArgVGPRs
1465  = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1466  unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1467  if (RegIdx == ArgVGPRs.size()) {
1468  // Spill to stack required.
1469  int64_t Offset = CCInfo.AllocateStack(4, 4);
1470 
1471  return ArgDescriptor::createStack(Offset);
1472  }
1473 
1474  unsigned Reg = ArgVGPRs[RegIdx];
1475  Reg = CCInfo.AllocateReg(Reg);
1476  assert(Reg != AMDGPU::NoRegister);
1477 
1478  MachineFunction &MF = CCInfo.getMachineFunction();
1479  MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1480  return ArgDescriptor::createRegister(Reg);
1481 }
1482 
1484  const TargetRegisterClass *RC,
1485  unsigned NumArgRegs) {
1486  ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1487  unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1488  if (RegIdx == ArgSGPRs.size())
1489  report_fatal_error("ran out of SGPRs for arguments");
1490 
1491  unsigned Reg = ArgSGPRs[RegIdx];
1492  Reg = CCInfo.AllocateReg(Reg);
1493  assert(Reg != AMDGPU::NoRegister);
1494 
1495  MachineFunction &MF = CCInfo.getMachineFunction();
1496  MF.addLiveIn(Reg, RC);
1497  return ArgDescriptor::createRegister(Reg);
1498 }
1499 
1501  return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1502 }
1503 
1505  return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1506 }
1507 
1509  MachineFunction &MF,
1510  const SIRegisterInfo &TRI,
1511  SIMachineFunctionInfo &Info) {
1512  if (Info.hasWorkItemIDX())
1513  Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1514 
1515  if (Info.hasWorkItemIDY())
1516  Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1517 
1518  if (Info.hasWorkItemIDZ())
1519  Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1520 }
1521 
1523  MachineFunction &MF,
1524  const SIRegisterInfo &TRI,
1525  SIMachineFunctionInfo &Info) {
1526  auto &ArgInfo = Info.getArgInfo();
1527 
1528  // TODO: Unify handling with private memory pointers.
1529 
1530  if (Info.hasDispatchPtr())
1531  ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1532 
1533  if (Info.hasQueuePtr())
1534  ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1535 
1536  if (Info.hasKernargSegmentPtr())
1537  ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1538 
1539  if (Info.hasDispatchID())
1540  ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1541 
1542  // flat_scratch_init is not applicable for non-kernel functions.
1543 
1544  if (Info.hasWorkGroupIDX())
1545  ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1546 
1547  if (Info.hasWorkGroupIDY())
1548  ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1549 
1550  if (Info.hasWorkGroupIDZ())
1551  ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1552 
1553  if (Info.hasImplicitArgPtr())
1554  ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1555 }
1556 
1557 // Allocate special inputs passed in user SGPRs.
1558 static void allocateHSAUserSGPRs(CCState &CCInfo,
1559  MachineFunction &MF,
1560  const SIRegisterInfo &TRI,
1561  SIMachineFunctionInfo &Info) {
1562  if (Info.hasImplicitBufferPtr()) {
1563  unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1564  MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1565  CCInfo.AllocateReg(ImplicitBufferPtrReg);
1566  }
1567 
1568  // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1569  if (Info.hasPrivateSegmentBuffer()) {
1570  unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1571  MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1572  CCInfo.AllocateReg(PrivateSegmentBufferReg);
1573  }
1574 
1575  if (Info.hasDispatchPtr()) {
1576  unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1577  MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1578  CCInfo.AllocateReg(DispatchPtrReg);
1579  }
1580 
1581  if (Info.hasQueuePtr()) {
1582  unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1583  MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1584  CCInfo.AllocateReg(QueuePtrReg);
1585  }
1586 
1587  if (Info.hasKernargSegmentPtr()) {
1588  unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1589  MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1590  CCInfo.AllocateReg(InputPtrReg);
1591  }
1592 
1593  if (Info.hasDispatchID()) {
1594  unsigned DispatchIDReg = Info.addDispatchID(TRI);
1595  MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1596  CCInfo.AllocateReg(DispatchIDReg);
1597  }
1598 
1599  if (Info.hasFlatScratchInit()) {
1600  unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1601  MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1602  CCInfo.AllocateReg(FlatScratchInitReg);
1603  }
1604 
1605  // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1606  // these from the dispatch pointer.
1607 }
1608 
1609 // Allocate special input registers that are initialized per-wave.
1610 static void allocateSystemSGPRs(CCState &CCInfo,
1611  MachineFunction &MF,
1612  SIMachineFunctionInfo &Info,
1613  CallingConv::ID CallConv,
1614  bool IsShader) {
1615  if (Info.hasWorkGroupIDX()) {
1616  unsigned Reg = Info.addWorkGroupIDX();
1617  MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1618  CCInfo.AllocateReg(Reg);
1619  }
1620 
1621  if (Info.hasWorkGroupIDY()) {
1622  unsigned Reg = Info.addWorkGroupIDY();
1623  MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1624  CCInfo.AllocateReg(Reg);
1625  }
1626 
1627  if (Info.hasWorkGroupIDZ()) {
1628  unsigned Reg = Info.addWorkGroupIDZ();
1629  MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1630  CCInfo.AllocateReg(Reg);
1631  }
1632 
1633  if (Info.hasWorkGroupInfo()) {
1634  unsigned Reg = Info.addWorkGroupInfo();
1635  MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1636  CCInfo.AllocateReg(Reg);
1637  }
1638 
1639  if (Info.hasPrivateSegmentWaveByteOffset()) {
1640  // Scratch wave offset passed in system SGPR.
1641  unsigned PrivateSegmentWaveByteOffsetReg;
1642 
1643  if (IsShader) {
1644  PrivateSegmentWaveByteOffsetReg =
1646 
1647  // This is true if the scratch wave byte offset doesn't have a fixed
1648  // location.
1649  if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1650  PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1651  Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1652  }
1653  } else
1654  PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1655 
1656  MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1657  CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1658  }
1659 }
1660 
1662  MachineFunction &MF,
1663  const SIRegisterInfo &TRI,
1664  SIMachineFunctionInfo &Info) {
1665  // Now that we've figured out where the scratch register inputs are, see if
1666  // should reserve the arguments and use them directly.
1667  MachineFrameInfo &MFI = MF.getFrameInfo();
1668  bool HasStackObjects = MFI.hasStackObjects();
1669 
1670  // Record that we know we have non-spill stack objects so we don't need to
1671  // check all stack objects later.
1672  if (HasStackObjects)
1673  Info.setHasNonSpillStackObjects(true);
1674 
1675  // Everything live out of a block is spilled with fast regalloc, so it's
1676  // almost certain that spilling will be required.
1677  if (TM.getOptLevel() == CodeGenOpt::None)
1678  HasStackObjects = true;
1679 
1680  // For now assume stack access is needed in any callee functions, so we need
1681  // the scratch registers to pass in.
1682  bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1683 
1684  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1685  if (ST.isAmdHsaOrMesa(MF.getFunction())) {
1686  if (RequiresStackAccess) {
1687  // If we have stack objects, we unquestionably need the private buffer
1688  // resource. For the Code Object V2 ABI, this will be the first 4 user
1689  // SGPR inputs. We can reserve those and use them directly.
1690 
1691  unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1693  Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1694 
1695  if (MFI.hasCalls()) {
1696  // If we have calls, we need to keep the frame register in a register
1697  // that won't be clobbered by a call, so ensure it is copied somewhere.
1698 
1699  // This is not a problem for the scratch wave offset, because the same
1700  // registers are reserved in all functions.
1701 
1702  // FIXME: Nothing is really ensuring this is a call preserved register,
1703  // it's just selected from the end so it happens to be.
1704  unsigned ReservedOffsetReg
1706  Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1707  } else {
1708  unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1710  Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1711  }
1712  } else {
1713  unsigned ReservedBufferReg
1715  unsigned ReservedOffsetReg
1717 
1718  // We tentatively reserve the last registers (skipping the last two
1719  // which may contain VCC). After register allocation, we'll replace
1720  // these with the ones immediately after those which were really
1721  // allocated. In the prologue copies will be inserted from the argument
1722  // to these reserved registers.
1723  Info.setScratchRSrcReg(ReservedBufferReg);
1724  Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1725  }
1726  } else {
1727  unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1728 
1729  // Without HSA, relocations are used for the scratch pointer and the
1730  // buffer resource setup is always inserted in the prologue. Scratch wave
1731  // offset is still in an input SGPR.
1732  Info.setScratchRSrcReg(ReservedBufferReg);
1733 
1734  if (HasStackObjects && !MFI.hasCalls()) {
1735  unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1737  Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1738  } else {
1739  unsigned ReservedOffsetReg
1741  Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1742  }
1743  }
1744 }
1745 
1748  return !Info->isEntryFunction();
1749 }
1750 
1752 
1753 }
1754 
1756  MachineBasicBlock *Entry,
1757  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1759 
1760  const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1761  if (!IStart)
1762  return;
1763 
1764  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1765  MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1766  MachineBasicBlock::iterator MBBI = Entry->begin();
1767  for (const MCPhysReg *I = IStart; *I; ++I) {
1768  const TargetRegisterClass *RC = nullptr;
1769  if (AMDGPU::SReg_64RegClass.contains(*I))
1770  RC = &AMDGPU::SGPR_64RegClass;
1771  else if (AMDGPU::SReg_32RegClass.contains(*I))
1772  RC = &AMDGPU::SGPR_32RegClass;
1773  else
1774  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1775 
1776  unsigned NewVR = MRI->createVirtualRegister(RC);
1777  // Create copy from CSR to a virtual register.
1778  Entry->addLiveIn(*I);
1779  BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1780  .addReg(*I);
1781 
1782  // Insert the copy-back instructions right before the terminator.
1783  for (auto *Exit : Exits)
1784  BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1785  TII->get(TargetOpcode::COPY), *I)
1786  .addReg(NewVR);
1787  }
1788 }
1789 
1791  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1792  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1793  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1795 
1796  MachineFunction &MF = DAG.getMachineFunction();
1797  const Function &Fn = MF.getFunction();
1798  FunctionType *FType = MF.getFunction().getFunctionType();
1800  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1801 
1802  if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1803  DiagnosticInfoUnsupported NoGraphicsHSA(
1804  Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1805  DAG.getContext()->diagnose(NoGraphicsHSA);
1806  return DAG.getEntryNode();
1807  }
1808 
1809  // Create stack objects that are used for emitting debugger prologue if
1810  // "amdgpu-debugger-emit-prologue" attribute was specified.
1811  if (ST.debuggerEmitPrologue())
1812  createDebuggerPrologueStackObjects(MF);
1813 
1816  BitVector Skipped(Ins.size());
1817  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1818  *DAG.getContext());
1819 
1820  bool IsShader = AMDGPU::isShader(CallConv);
1821  bool IsKernel = AMDGPU::isKernel(CallConv);
1822  bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1823 
1824  if (!IsEntryFunc) {
1825  // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1826  // this when allocating argument fixed offsets.
1827  CCInfo.AllocateStack(4, 4);
1828  }
1829 
1830  if (IsShader) {
1831  processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1832 
1833  // At least one interpolation mode must be enabled or else the GPU will
1834  // hang.
1835  //
1836  // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1837  // set PSInputAddr, the user wants to enable some bits after the compilation
1838  // based on run-time states. Since we can't know what the final PSInputEna
1839  // will look like, so we shouldn't do anything here and the user should take
1840  // responsibility for the correct programming.
1841  //
1842  // Otherwise, the following restrictions apply:
1843  // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1844  // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1845  // enabled too.
1846  if (CallConv == CallingConv::AMDGPU_PS) {
1847  if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1848  ((Info->getPSInputAddr() & 0xF) == 0 &&
1849  Info->isPSInputAllocated(11))) {
1850  CCInfo.AllocateReg(AMDGPU::VGPR0);
1851  CCInfo.AllocateReg(AMDGPU::VGPR1);
1852  Info->markPSInputAllocated(0);
1853  Info->markPSInputEnabled(0);
1854  }
1855  if (Subtarget->isAmdPalOS()) {
1856  // For isAmdPalOS, the user does not enable some bits after compilation
1857  // based on run-time states; the register values being generated here are
1858  // the final ones set in hardware. Therefore we need to apply the
1859  // workaround to PSInputAddr and PSInputEnable together. (The case where
1860  // a bit is set in PSInputAddr but not PSInputEnable is where the
1861  // frontend set up an input arg for a particular interpolation mode, but
1862  // nothing uses that input arg. Really we should have an earlier pass
1863  // that removes such an arg.)
1864  unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1865  if ((PsInputBits & 0x7F) == 0 ||
1866  ((PsInputBits & 0xF) == 0 &&
1867  (PsInputBits >> 11 & 1)))
1868  Info->markPSInputEnabled(
1870  }
1871  }
1872 
1873  assert(!Info->hasDispatchPtr() &&
1874  !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1875  !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1876  !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1877  !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1878  !Info->hasWorkItemIDZ());
1879  } else if (IsKernel) {
1880  assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1881  } else {
1882  Splits.append(Ins.begin(), Ins.end());
1883  }
1884 
1885  if (IsEntryFunc) {
1886  allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1887  allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1888  }
1889 
1890  if (IsKernel) {
1891  analyzeFormalArgumentsCompute(CCInfo, Ins);
1892  } else {
1893  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1894  CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1895  }
1896 
1897  SmallVector<SDValue, 16> Chains;
1898 
1899  // FIXME: This is the minimum kernel argument alignment. We should improve
1900  // this to the maximum alignment of the arguments.
1901  //
1902  // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
1903  // kern arg offset.
1904  const unsigned KernelArgBaseAlign = 16;
1905 
1906  for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1907  const ISD::InputArg &Arg = Ins[i];
1908  if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
1909  InVals.push_back(DAG.getUNDEF(Arg.VT));
1910  continue;
1911  }
1912 
1913  CCValAssign &VA = ArgLocs[ArgIdx++];
1914  MVT VT = VA.getLocVT();
1915 
1916  if (IsEntryFunc && VA.isMemLoc()) {
1917  VT = Ins[i].VT;
1918  EVT MemVT = VA.getLocVT();
1919 
1920  const uint64_t Offset = VA.getLocMemOffset();
1921  unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
1922 
1923  SDValue Arg = lowerKernargMemParameter(
1924  DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
1925  Chains.push_back(Arg.getValue(1));
1926 
1927  auto *ParamTy =
1928  dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1929  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
1930  ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1931  // On SI local pointers are just offsets into LDS, so they are always
1932  // less than 16-bits. On CI and newer they could potentially be
1933  // real pointers, so we can't guarantee their size.
1934  Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1935  DAG.getValueType(MVT::i16));
1936  }
1937 
1938  InVals.push_back(Arg);
1939  continue;
1940  } else if (!IsEntryFunc && VA.isMemLoc()) {
1941  SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1942  InVals.push_back(Val);
1943  if (!Arg.Flags.isByVal())
1944  Chains.push_back(Val.getValue(1));
1945  continue;
1946  }
1947 
1948  assert(VA.isRegLoc() && "Parameter must be in a register!");
1949 
1950  unsigned Reg = VA.getLocReg();
1951  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1952  EVT ValVT = VA.getValVT();
1953 
1954  Reg = MF.addLiveIn(Reg, RC);
1955  SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1956 
1957  if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1958  // The return object should be reasonably addressable.
1959 
1960  // FIXME: This helps when the return is a real sret. If it is a
1961  // automatically inserted sret (i.e. CanLowerReturn returns false), an
1962  // extra copy is inserted in SelectionDAGBuilder which obscures this.
1963  unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1964  Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1965  DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1966  }
1967 
1968  // If this is an 8 or 16-bit value, it is really passed promoted
1969  // to 32 bits. Insert an assert[sz]ext to capture this, then
1970  // truncate to the right size.
1971  switch (VA.getLocInfo()) {
1972  case CCValAssign::Full:
1973  break;
1974  case CCValAssign::BCvt:
1975  Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1976  break;
1977  case CCValAssign::SExt:
1978  Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1979  DAG.getValueType(ValVT));
1980  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1981  break;
1982  case CCValAssign::ZExt:
1983  Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1984  DAG.getValueType(ValVT));
1985  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1986  break;
1987  case CCValAssign::AExt:
1988  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1989  break;
1990  default:
1991  llvm_unreachable("Unknown loc info!");
1992  }
1993 
1994  InVals.push_back(Val);
1995  }
1996 
1997  if (!IsEntryFunc) {
1998  // Special inputs come after user arguments.
1999  allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2000  }
2001 
2002  // Start adding system SGPRs.
2003  if (IsEntryFunc) {
2004  allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2005  } else {
2006  CCInfo.AllocateReg(Info->getScratchRSrcReg());
2007  CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2008  CCInfo.AllocateReg(Info->getFrameOffsetReg());
2009  allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2010  }
2011 
2012  auto &ArgUsageInfo =
2014  ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2015 
2016  unsigned StackArgSize = CCInfo.getNextStackOffset();
2017  Info->setBytesInStackArgArea(StackArgSize);
2018 
2019  return Chains.empty() ? Chain :
2020  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2021 }
2022 
2023 // TODO: If return values can't fit in registers, we should return as many as
2024 // possible in registers before passing on stack.
2026  CallingConv::ID CallConv,
2027  MachineFunction &MF, bool IsVarArg,
2028  const SmallVectorImpl<ISD::OutputArg> &Outs,
2029  LLVMContext &Context) const {
2030  // Replacing returns with sret/stack usage doesn't make sense for shaders.
2031  // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2032  // for shaders. Vector types should be explicitly handled by CC.
2033  if (AMDGPU::isEntryFunctionCC(CallConv))
2034  return true;
2035 
2037  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2038  return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2039 }
2040 
2041 SDValue
2043  bool isVarArg,
2044  const SmallVectorImpl<ISD::OutputArg> &Outs,
2045  const SmallVectorImpl<SDValue> &OutVals,
2046  const SDLoc &DL, SelectionDAG &DAG) const {
2047  MachineFunction &MF = DAG.getMachineFunction();
2049 
2050  if (AMDGPU::isKernel(CallConv)) {
2051  return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2052  OutVals, DL, DAG);
2053  }
2054 
2055  bool IsShader = AMDGPU::isShader(CallConv);
2056 
2057  Info->setIfReturnsVoid(Outs.empty());
2058  bool IsWaveEnd = Info->returnsVoid() && IsShader;
2059 
2060  // CCValAssign - represent the assignment of the return value to a location.
2063 
2064  // CCState - Info about the registers and stack slots.
2065  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2066  *DAG.getContext());
2067 
2068  // Analyze outgoing return values.
2069  CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2070 
2071  SDValue Flag;
2072  SmallVector<SDValue, 48> RetOps;
2073  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2074 
2075  // Add return address for callable functions.
2076  if (!Info->isEntryFunction()) {
2078  SDValue ReturnAddrReg = CreateLiveInRegister(
2079  DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2080 
2081  // FIXME: Should be able to use a vreg here, but need a way to prevent it
2082  // from being allcoated to a CSR.
2083 
2084  SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2085  MVT::i64);
2086 
2087  Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2088  Flag = Chain.getValue(1);
2089 
2090  RetOps.push_back(PhysReturnAddrReg);
2091  }
2092 
2093  // Copy the result values into the output registers.
2094  for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2095  ++I, ++RealRVLocIdx) {
2096  CCValAssign &VA = RVLocs[I];
2097  assert(VA.isRegLoc() && "Can only return in registers!");
2098  // TODO: Partially return in registers if return values don't fit.
2099  SDValue Arg = OutVals[RealRVLocIdx];
2100 
2101  // Copied from other backends.
2102  switch (VA.getLocInfo()) {
2103  case CCValAssign::Full:
2104  break;
2105  case CCValAssign::BCvt:
2106  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2107  break;
2108  case CCValAssign::SExt:
2109  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2110  break;
2111  case CCValAssign::ZExt:
2112  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2113  break;
2114  case CCValAssign::AExt:
2115  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2116  break;
2117  default:
2118  llvm_unreachable("Unknown loc info!");
2119  }
2120 
2121  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2122  Flag = Chain.getValue(1);
2123  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2124  }
2125 
2126  // FIXME: Does sret work properly?
2127  if (!Info->isEntryFunction()) {
2128  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2129  const MCPhysReg *I =
2131  if (I) {
2132  for (; *I; ++I) {
2133  if (AMDGPU::SReg_64RegClass.contains(*I))
2134  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2135  else if (AMDGPU::SReg_32RegClass.contains(*I))
2136  RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2137  else
2138  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2139  }
2140  }
2141  }
2142 
2143  // Update chain and glue.
2144  RetOps[0] = Chain;
2145  if (Flag.getNode())
2146  RetOps.push_back(Flag);
2147 
2148  unsigned Opc = AMDGPUISD::ENDPGM;
2149  if (!IsWaveEnd)
2151  return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2152 }
2153 
2155  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2156  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2157  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2158  SDValue ThisVal) const {
2159  CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2160 
2161  // Assign locations to each value returned by this call.
2163  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2164  *DAG.getContext());
2165  CCInfo.AnalyzeCallResult(Ins, RetCC);
2166 
2167  // Copy all of the result registers out of their specified physreg.
2168  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2169  CCValAssign VA = RVLocs[i];
2170  SDValue Val;
2171 
2172  if (VA.isRegLoc()) {
2173  Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2174  Chain = Val.getValue(1);
2175  InFlag = Val.getValue(2);
2176  } else if (VA.isMemLoc()) {
2177  report_fatal_error("TODO: return values in memory");
2178  } else
2179  llvm_unreachable("unknown argument location type");
2180 
2181  switch (VA.getLocInfo()) {
2182  case CCValAssign::Full:
2183  break;
2184  case CCValAssign::BCvt:
2185  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2186  break;
2187  case CCValAssign::ZExt:
2188  Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2189  DAG.getValueType(VA.getValVT()));
2190  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2191  break;
2192  case CCValAssign::SExt:
2193  Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2194  DAG.getValueType(VA.getValVT()));
2195  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2196  break;
2197  case CCValAssign::AExt:
2198  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2199  break;
2200  default:
2201  llvm_unreachable("Unknown loc info!");
2202  }
2203 
2204  InVals.push_back(Val);
2205  }
2206 
2207  return Chain;
2208 }
2209 
2210 // Add code to pass special inputs required depending on used features separate
2211 // from the explicit user arguments present in the IR.
2213  CallLoweringInfo &CLI,
2214  CCState &CCInfo,
2215  const SIMachineFunctionInfo &Info,
2216  SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2217  SmallVectorImpl<SDValue> &MemOpChains,
2218  SDValue Chain) const {
2219  // If we don't have a call site, this was a call inserted by
2220  // legalization. These can never use special inputs.
2221  if (!CLI.CS)
2222  return;
2223 
2224  const Function *CalleeFunc = CLI.CS.getCalledFunction();
2225  assert(CalleeFunc);
2226 
2227  SelectionDAG &DAG = CLI.DAG;
2228  const SDLoc &DL = CLI.DL;
2229 
2230  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2231 
2232  auto &ArgUsageInfo =
2234  const AMDGPUFunctionArgInfo &CalleeArgInfo
2235  = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2236 
2237  const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2238 
2239  // TODO: Unify with private memory register handling. This is complicated by
2240  // the fact that at least in kernels, the input argument is not necessarily
2241  // in the same location as the input.
2254  };
2255 
2256  for (auto InputID : InputRegs) {
2257  const ArgDescriptor *OutgoingArg;
2258  const TargetRegisterClass *ArgRC;
2259 
2260  std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2261  if (!OutgoingArg)
2262  continue;
2263 
2264  const ArgDescriptor *IncomingArg;
2265  const TargetRegisterClass *IncomingArgRC;
2266  std::tie(IncomingArg, IncomingArgRC)
2267  = CallerArgInfo.getPreloadedValue(InputID);
2268  assert(IncomingArgRC == ArgRC);
2269 
2270  // All special arguments are ints for now.
2271  EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2272  SDValue InputReg;
2273 
2274  if (IncomingArg) {
2275  InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2276  } else {
2277  // The implicit arg ptr is special because it doesn't have a corresponding
2278  // input for kernels, and is computed from the kernarg segment pointer.
2279  assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2280  InputReg = getImplicitArgPtr(DAG, DL);
2281  }
2282 
2283  if (OutgoingArg->isRegister()) {
2284  RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2285  } else {
2286  unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2287  SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2288  SpecialArgOffset);
2289  MemOpChains.push_back(ArgStore);
2290  }
2291  }
2292 }
2293 
2295  return CC == CallingConv::Fast;
2296 }
2297 
2298 /// Return true if we might ever do TCO for calls with this calling convention.
2300  switch (CC) {
2301  case CallingConv::C:
2302  return true;
2303  default:
2304  return canGuaranteeTCO(CC);
2305  }
2306 }
2307 
2309  SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2310  const SmallVectorImpl<ISD::OutputArg> &Outs,
2311  const SmallVectorImpl<SDValue> &OutVals,
2312  const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2313  if (!mayTailCallThisCC(CalleeCC))
2314  return false;
2315 
2316  MachineFunction &MF = DAG.getMachineFunction();
2317  const Function &CallerF = MF.getFunction();
2318  CallingConv::ID CallerCC = CallerF.getCallingConv();
2320  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2321 
2322  // Kernels aren't callable, and don't have a live in return address so it
2323  // doesn't make sense to do a tail call with entry functions.
2324  if (!CallerPreserved)
2325  return false;
2326 
2327  bool CCMatch = CallerCC == CalleeCC;
2328 
2330  if (canGuaranteeTCO(CalleeCC) && CCMatch)
2331  return true;
2332  return false;
2333  }
2334 
2335  // TODO: Can we handle var args?
2336  if (IsVarArg)
2337  return false;
2338 
2339  for (const Argument &Arg : CallerF.args()) {
2340  if (Arg.hasByValAttr())
2341  return false;
2342  }
2343 
2344  LLVMContext &Ctx = *DAG.getContext();
2345 
2346  // Check that the call results are passed in the same way.
2347  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2348  CCAssignFnForCall(CalleeCC, IsVarArg),
2349  CCAssignFnForCall(CallerCC, IsVarArg)))
2350  return false;
2351 
2352  // The callee has to preserve all registers the caller needs to preserve.
2353  if (!CCMatch) {
2354  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2355  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2356  return false;
2357  }
2358 
2359  // Nothing more to check if the callee is taking no arguments.
2360  if (Outs.empty())
2361  return true;
2362 
2364  CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2365 
2366  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2367 
2368  const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2369  // If the stack arguments for this call do not fit into our own save area then
2370  // the call cannot be made tail.
2371  // TODO: Is this really necessary?
2372  if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2373  return false;
2374 
2375  const MachineRegisterInfo &MRI = MF.getRegInfo();
2376  return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2377 }
2378 
2380  if (!CI->isTailCall())
2381  return false;
2382 
2383  const Function *ParentFn = CI->getParent()->getParent();
2384  if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2385  return false;
2386 
2387  auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2388  return (Attr.getValueAsString() != "true");
2389 }
2390 
2391 // The wave scratch offset register is used as the global base pointer.
2393  SmallVectorImpl<SDValue> &InVals) const {
2394  SelectionDAG &DAG = CLI.DAG;
2395  const SDLoc &DL = CLI.DL;
2397  SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2399  SDValue Chain = CLI.Chain;
2400  SDValue Callee = CLI.Callee;
2401  bool &IsTailCall = CLI.IsTailCall;
2402  CallingConv::ID CallConv = CLI.CallConv;
2403  bool IsVarArg = CLI.IsVarArg;
2404  bool IsSibCall = false;
2405  bool IsThisReturn = false;
2406  MachineFunction &MF = DAG.getMachineFunction();
2407 
2408  if (IsVarArg) {
2409  return lowerUnhandledCall(CLI, InVals,
2410  "unsupported call to variadic function ");
2411  }
2412 
2413  if (!CLI.CS.getInstruction())
2414  report_fatal_error("unsupported libcall legalization");
2415 
2416  if (!CLI.CS.getCalledFunction()) {
2417  return lowerUnhandledCall(CLI, InVals,
2418  "unsupported indirect call to function ");
2419  }
2420 
2421  if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2422  return lowerUnhandledCall(CLI, InVals,
2423  "unsupported required tail call to function ");
2424  }
2425 
2427  // Note the issue is with the CC of the calling function, not of the call
2428  // itself.
2429  return lowerUnhandledCall(CLI, InVals,
2430  "unsupported call from graphics shader of function ");
2431  }
2432 
2433  // The first 4 bytes are reserved for the callee's emergency stack slot.
2434  if (IsTailCall) {
2435  IsTailCall = isEligibleForTailCallOptimization(
2436  Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2437  if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2438  report_fatal_error("failed to perform tail call elimination on a call "
2439  "site marked musttail");
2440  }
2441 
2442  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2443 
2444  // A sibling call is one where we're under the usual C ABI and not planning
2445  // to change that but can still do a tail call:
2446  if (!TailCallOpt && IsTailCall)
2447  IsSibCall = true;
2448 
2449  if (IsTailCall)
2450  ++NumTailCalls;
2451  }
2452 
2454 
2455  // Analyze operands of the call, assigning locations to each operand.
2457  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2458  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2459 
2460  // The first 4 bytes are reserved for the callee's emergency stack slot.
2461  CCInfo.AllocateStack(4, 4);
2462 
2463  CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2464 
2465  // Get a count of how many bytes are to be pushed on the stack.
2466  unsigned NumBytes = CCInfo.getNextStackOffset();
2467 
2468  if (IsSibCall) {
2469  // Since we're not changing the ABI to make this a tail call, the memory
2470  // operands are already available in the caller's incoming argument space.
2471  NumBytes = 0;
2472  }
2473 
2474  // FPDiff is the byte offset of the call's argument area from the callee's.
2475  // Stores to callee stack arguments will be placed in FixedStackSlots offset
2476  // by this amount for a tail call. In a sibling call it must be 0 because the
2477  // caller will deallocate the entire stack and the callee still expects its
2478  // arguments to begin at SP+0. Completely unused for non-tail calls.
2479  int32_t FPDiff = 0;
2480  MachineFrameInfo &MFI = MF.getFrameInfo();
2482 
2483  SDValue CallerSavedFP;
2484 
2485  // Adjust the stack pointer for the new arguments...
2486  // These operations are automatically eliminated by the prolog/epilog pass
2487  if (!IsSibCall) {
2488  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2489 
2490  unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2491 
2492  // In the HSA case, this should be an identity copy.
2493  SDValue ScratchRSrcReg
2494  = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2495  RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2496 
2497  // TODO: Don't hardcode these registers and get from the callee function.
2498  SDValue ScratchWaveOffsetReg
2499  = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2500  RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2501 
2502  if (!Info->isEntryFunction()) {
2503  // Avoid clobbering this function's FP value. In the current convention
2504  // callee will overwrite this, so do save/restore around the call site.
2505  CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2506  Info->getFrameOffsetReg(), MVT::i32);
2507  }
2508  }
2509 
2510  SmallVector<SDValue, 8> MemOpChains;
2511  MVT PtrVT = MVT::i32;
2512 
2513  // Walk the register/memloc assignments, inserting copies/loads.
2514  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2515  ++i, ++realArgIdx) {
2516  CCValAssign &VA = ArgLocs[i];
2517  SDValue Arg = OutVals[realArgIdx];
2518 
2519  // Promote the value if needed.
2520  switch (VA.getLocInfo()) {
2521  case CCValAssign::Full:
2522  break;
2523  case CCValAssign::BCvt:
2524  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2525  break;
2526  case CCValAssign::ZExt:
2527  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2528  break;
2529  case CCValAssign::SExt:
2530  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2531  break;
2532  case CCValAssign::AExt:
2533  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2534  break;
2535  case CCValAssign::FPExt:
2536  Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2537  break;
2538  default:
2539  llvm_unreachable("Unknown loc info!");
2540  }
2541 
2542  if (VA.isRegLoc()) {
2543  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2544  } else {
2545  assert(VA.isMemLoc());
2546 
2547  SDValue DstAddr;
2548  MachinePointerInfo DstInfo;
2549 
2550  unsigned LocMemOffset = VA.getLocMemOffset();
2551  int32_t Offset = LocMemOffset;
2552 
2553  SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2554  unsigned Align = 0;
2555 
2556  if (IsTailCall) {
2557  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2558  unsigned OpSize = Flags.isByVal() ?
2559  Flags.getByValSize() : VA.getValVT().getStoreSize();
2560 
2561  // FIXME: We can have better than the minimum byval required alignment.
2562  Align = Flags.isByVal() ? Flags.getByValAlign() :
2563  MinAlign(Subtarget->getStackAlignment(), Offset);
2564 
2565  Offset = Offset + FPDiff;
2566  int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2567 
2568  DstAddr = DAG.getFrameIndex(FI, PtrVT);
2569  DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2570 
2571  // Make sure any stack arguments overlapping with where we're storing
2572  // are loaded before this eventual operation. Otherwise they'll be
2573  // clobbered.
2574 
2575  // FIXME: Why is this really necessary? This seems to just result in a
2576  // lot of code to copy the stack and write them back to the same
2577  // locations, which are supposed to be immutable?
2578  Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2579  } else {
2580  DstAddr = PtrOff;
2581  DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2582  Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2583  }
2584 
2585  if (Outs[i].Flags.isByVal()) {
2586  SDValue SizeNode =
2587  DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2588  SDValue Cpy = DAG.getMemcpy(
2589  Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2590  /*isVol = */ false, /*AlwaysInline = */ true,
2591  /*isTailCall = */ false, DstInfo,
2594 
2595  MemOpChains.push_back(Cpy);
2596  } else {
2597  SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2598  MemOpChains.push_back(Store);
2599  }
2600  }
2601  }
2602 
2603  // Copy special input registers after user input arguments.
2604  passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2605 
2606  if (!MemOpChains.empty())
2607  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2608 
2609  // Build a sequence of copy-to-reg nodes chained together with token chain
2610  // and flag operands which copy the outgoing args into the appropriate regs.
2611  SDValue InFlag;
2612  for (auto &RegToPass : RegsToPass) {
2613  Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2614  RegToPass.second, InFlag);
2615  InFlag = Chain.getValue(1);
2616  }
2617 
2618 
2619  SDValue PhysReturnAddrReg;
2620  if (IsTailCall) {
2621  // Since the return is being combined with the call, we need to pass on the
2622  // return address.
2623 
2625  SDValue ReturnAddrReg = CreateLiveInRegister(
2626  DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2627 
2628  PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2629  MVT::i64);
2630  Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2631  InFlag = Chain.getValue(1);
2632  }
2633 
2634  // We don't usually want to end the call-sequence here because we would tidy
2635  // the frame up *after* the call, however in the ABI-changing tail-call case
2636  // we've carefully laid out the parameters so that when sp is reset they'll be
2637  // in the correct location.
2638  if (IsTailCall && !IsSibCall) {
2639  Chain = DAG.getCALLSEQ_END(Chain,
2640  DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2641  DAG.getTargetConstant(0, DL, MVT::i32),
2642  InFlag, DL);
2643  InFlag = Chain.getValue(1);
2644  }
2645 
2646  std::vector<SDValue> Ops;
2647  Ops.push_back(Chain);
2648  Ops.push_back(Callee);
2649 
2650  if (IsTailCall) {
2651  // Each tail call may have to adjust the stack by a different amount, so
2652  // this information must travel along with the operation for eventual
2653  // consumption by emitEpilogue.
2654  Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2655 
2656  Ops.push_back(PhysReturnAddrReg);
2657  }
2658 
2659  // Add argument registers to the end of the list so that they are known live
2660  // into the call.
2661  for (auto &RegToPass : RegsToPass) {
2662  Ops.push_back(DAG.getRegister(RegToPass.first,
2663  RegToPass.second.getValueType()));
2664  }
2665 
2666  // Add a register mask operand representing the call-preserved registers.
2667 
2668  auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2669  const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2670  assert(Mask && "Missing call preserved mask for calling convention");
2671  Ops.push_back(DAG.getRegisterMask(Mask));
2672 
2673  if (InFlag.getNode())
2674  Ops.push_back(InFlag);
2675 
2676  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2677 
2678  // If we're doing a tall call, use a TC_RETURN here rather than an
2679  // actual call instruction.
2680  if (IsTailCall) {
2681  MFI.setHasTailCall();
2682  return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2683  }
2684 
2685  // Returns a chain and a flag for retval copy to use.
2686  SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2687  Chain = Call.getValue(0);
2688  InFlag = Call.getValue(1);
2689 
2690  if (CallerSavedFP) {
2691  SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2692  Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2693  InFlag = Chain.getValue(1);
2694  }
2695 
2696  uint64_t CalleePopBytes = NumBytes;
2697  Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2698  DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2699  InFlag, DL);
2700  if (!Ins.empty())
2701  InFlag = Chain.getValue(1);
2702 
2703  // Handle result values, copying them out of physregs into vregs that we
2704  // return.
2705  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2706  InVals, IsThisReturn,
2707  IsThisReturn ? OutVals[0] : SDValue());
2708 }
2709 
2710 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2711  SelectionDAG &DAG) const {
2712  unsigned Reg = StringSwitch<unsigned>(RegName)
2713  .Case("m0", AMDGPU::M0)
2714  .Case("exec", AMDGPU::EXEC)
2715  .Case("exec_lo", AMDGPU::EXEC_LO)
2716  .Case("exec_hi", AMDGPU::EXEC_HI)
2717  .Case("flat_scratch", AMDGPU::FLAT_SCR)
2718  .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2719  .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2720  .Default(AMDGPU::NoRegister);
2721 
2722  if (Reg == AMDGPU::NoRegister) {
2723  report_fatal_error(Twine("invalid register name \""
2724  + StringRef(RegName) + "\"."));
2725 
2726  }
2727 
2728  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2729  Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2730  report_fatal_error(Twine("invalid register \""
2731  + StringRef(RegName) + "\" for subtarget."));
2732  }
2733 
2734  switch (Reg) {
2735  case AMDGPU::M0:
2736  case AMDGPU::EXEC_LO:
2737  case AMDGPU::EXEC_HI:
2738  case AMDGPU::FLAT_SCR_LO:
2739  case AMDGPU::FLAT_SCR_HI:
2740  if (VT.getSizeInBits() == 32)
2741  return Reg;
2742  break;
2743  case AMDGPU::EXEC:
2744  case AMDGPU::FLAT_SCR:
2745  if (VT.getSizeInBits() == 64)
2746  return Reg;
2747  break;
2748  default:
2749  llvm_unreachable("missing register type checking");
2750  }
2751 
2752  report_fatal_error(Twine("invalid type for register \""
2753  + StringRef(RegName) + "\"."));
2754 }
2755 
2756 // If kill is not the last instruction, split the block so kill is always a
2757 // proper terminator.
2759  MachineBasicBlock *BB) const {
2760  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2761 
2762  MachineBasicBlock::iterator SplitPoint(&MI);
2763  ++SplitPoint;
2764 
2765  if (SplitPoint == BB->end()) {
2766  // Don't bother with a new block.
2768  return BB;
2769  }
2770 
2771  MachineFunction *MF = BB->getParent();
2772  MachineBasicBlock *SplitBB
2774 
2775  MF->insert(++MachineFunction::iterator(BB), SplitBB);
2776  SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2777 
2778  SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2779  BB->addSuccessor(SplitBB);
2780 
2782  return SplitBB;
2783 }
2784 
2785 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2786 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2787 // will only do one iteration. In the worst case, this will loop 64 times.
2788 //
2789 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2791  const SIInstrInfo *TII,
2793  MachineBasicBlock &OrigBB,
2794  MachineBasicBlock &LoopBB,
2795  const DebugLoc &DL,
2796  const MachineOperand &IdxReg,
2797  unsigned InitReg,
2798  unsigned ResultReg,
2799  unsigned PhiReg,
2800  unsigned InitSaveExecReg,
2801  int Offset,
2802  bool UseGPRIdxMode,
2803  bool IsIndirectSrc) {
2804  MachineBasicBlock::iterator I = LoopBB.begin();
2805 
2806  unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2807  unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2808  unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2809  unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2810 
2811  BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2812  .addReg(InitReg)
2813  .addMBB(&OrigBB)
2814  .addReg(ResultReg)
2815  .addMBB(&LoopBB);
2816 
2817  BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2818  .addReg(InitSaveExecReg)
2819  .addMBB(&OrigBB)
2820  .addReg(NewExec)
2821  .addMBB(&LoopBB);
2822 
2823  // Read the next variant <- also loop target.
2824  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2825  .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2826 
2827  // Compare the just read M0 value to all possible Idx values.
2828  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2829  .addReg(CurrentIdxReg)
2830  .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2831 
2832  // Update EXEC, save the original EXEC value to VCC.
2833  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2834  .addReg(CondReg, RegState::Kill);
2835 
2836  MRI.setSimpleHint(NewExec, CondReg);
2837 
2838  if (UseGPRIdxMode) {
2839  unsigned IdxReg;
2840  if (Offset == 0) {
2841  IdxReg = CurrentIdxReg;
2842  } else {
2843  IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2844  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2845  .addReg(CurrentIdxReg, RegState::Kill)
2846  .addImm(Offset);
2847  }
2848  unsigned IdxMode = IsIndirectSrc ?
2850  MachineInstr *SetOn =
2851  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2852  .addReg(IdxReg, RegState::Kill)
2853  .addImm(IdxMode);
2854  SetOn->getOperand(3).setIsUndef();
2855  } else {
2856  // Move index from VCC into M0
2857  if (Offset == 0) {
2858  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2859  .addReg(CurrentIdxReg, RegState::Kill);
2860  } else {
2861  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2862  .addReg(CurrentIdxReg, RegState::Kill)
2863  .addImm(Offset);
2864  }
2865  }
2866 
2867  // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2868  MachineInstr *InsertPt =
2869  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2870  .addReg(AMDGPU::EXEC)
2871  .addReg(NewExec);
2872 
2873  // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2874  // s_cbranch_scc0?
2875 
2876  // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2877  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2878  .addMBB(&LoopBB);
2879 
2880  return InsertPt->getIterator();
2881 }
2882 
2883 // This has slightly sub-optimal regalloc when the source vector is killed by
2884 // the read. The register allocator does not understand that the kill is
2885 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2886 // subregister from it, using 1 more VGPR than necessary. This was saved when
2887 // this was expanded after register allocation.
2889  MachineBasicBlock &MBB,
2890  MachineInstr &MI,
2891  unsigned InitResultReg,
2892  unsigned PhiReg,
2893  int Offset,
2894  bool UseGPRIdxMode,
2895  bool IsIndirectSrc) {
2896  MachineFunction *MF = MBB.getParent();
2898  const DebugLoc &DL = MI.getDebugLoc();
2900 
2901  unsigned DstReg = MI.getOperand(0).getReg();
2902  unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2903  unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2904 
2905  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2906 
2907  // Save the EXEC mask
2908  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2909  .addReg(AMDGPU::EXEC);
2910 
2911  // To insert the loop we need to split the block. Move everything after this
2912  // point to a new block, and insert a new empty block between the two.
2914  MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2915  MachineFunction::iterator MBBI(MBB);
2916  ++MBBI;
2917 
2918  MF->insert(MBBI, LoopBB);
2919  MF->insert(MBBI, RemainderBB);
2920 
2921  LoopBB->addSuccessor(LoopBB);
2922  LoopBB->addSuccessor(RemainderBB);
2923 
2924  // Move the rest of the block into a new block.
2925  RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2926  RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2927 
2928  MBB.addSuccessor(LoopBB);
2929 
2930  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2931 
2932  auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2933  InitResultReg, DstReg, PhiReg, TmpExec,
2934  Offset, UseGPRIdxMode, IsIndirectSrc);
2935 
2936  MachineBasicBlock::iterator First = RemainderBB->begin();
2937  BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2938  .addReg(SaveExec);
2939 
2940  return InsPt;
2941 }
2942 
2943 // Returns subreg index, offset
2944 static std::pair<unsigned, int>
2946  const TargetRegisterClass *SuperRC,
2947  unsigned VecReg,
2948  int Offset) {
2949  int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2950 
2951  // Skip out of bounds offsets, or else we would end up using an undefined
2952  // register.
2953  if (Offset >= NumElts || Offset < 0)
2954  return std::make_pair(AMDGPU::sub0, Offset);
2955 
2956  return std::make_pair(AMDGPU::sub0 + Offset, 0);
2957 }
2958 
2959 // Return true if the index is an SGPR and was set.
2962  MachineInstr &MI,
2963  int Offset,
2964  bool UseGPRIdxMode,
2965  bool IsIndirectSrc) {
2966  MachineBasicBlock *MBB = MI.getParent();
2967  const DebugLoc &DL = MI.getDebugLoc();
2969 
2970  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2971  const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2972 
2973  assert(Idx->getReg() != AMDGPU::NoRegister);
2974 
2975  if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2976  return false;
2977 
2978  if (UseGPRIdxMode) {
2979  unsigned IdxMode = IsIndirectSrc ?
2981  if (Offset == 0) {
2982  MachineInstr *SetOn =
2983  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2984  .add(*Idx)
2985  .addImm(IdxMode);
2986 
2987  SetOn->getOperand(3).setIsUndef();
2988  } else {
2989  unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2990  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2991  .add(*Idx)
2992  .addImm(Offset);
2993  MachineInstr *SetOn =
2994  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2995  .addReg(Tmp, RegState::Kill)
2996  .addImm(IdxMode);
2997 
2998  SetOn->getOperand(3).setIsUndef();
2999  }
3000 
3001  return true;
3002  }
3003 
3004  if (Offset == 0) {
3005  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3006  .add(*Idx);
3007  } else {
3008  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3009  .add(*Idx)
3010  .addImm(Offset);
3011  }
3012 
3013  return true;
3014 }
3015 
3016 // Control flow needs to be inserted if indexing with a VGPR.
3018  MachineBasicBlock &MBB,
3019  const GCNSubtarget &ST) {
3020  const SIInstrInfo *TII = ST.getInstrInfo();
3021  const SIRegisterInfo &TRI = TII->getRegisterInfo();
3022  MachineFunction *MF = MBB.getParent();
3024 
3025  unsigned Dst = MI.getOperand(0).getReg();
3026  unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3027  int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3028 
3029  const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3030 
3031  unsigned SubReg;
3032  std::tie(SubReg, Offset)
3033  = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3034 
3035  bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3036 
3037  if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3039  const DebugLoc &DL = MI.getDebugLoc();
3040 
3041  if (UseGPRIdxMode) {
3042  // TODO: Look at the uses to avoid the copy. This may require rescheduling
3043  // to avoid interfering with other uses, so probably requires a new
3044  // optimization pass.
3045  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3046  .addReg(SrcReg, RegState::Undef, SubReg)
3047  .addReg(SrcReg, RegState::Implicit)
3048  .addReg(AMDGPU::M0, RegState::Implicit);
3049  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3050  } else {
3051  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3052  .addReg(SrcReg, RegState::Undef, SubReg)
3053  .addReg(SrcReg, RegState::Implicit);
3054  }
3055 
3056  MI.eraseFromParent();
3057 
3058  return &MBB;
3059  }
3060 
3061  const DebugLoc &DL = MI.getDebugLoc();
3063 
3064  unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3065  unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3066 
3067  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3068 
3069  auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3070  Offset, UseGPRIdxMode, true);
3071  MachineBasicBlock *LoopBB = InsPt->getParent();
3072 
3073  if (UseGPRIdxMode) {
3074  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3075  .addReg(SrcReg, RegState::Undef, SubReg)
3076  .addReg(SrcReg, RegState::Implicit)
3077  .addReg(AMDGPU::M0, RegState::Implicit);
3078  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3079  } else {
3080  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3081  .addReg(SrcReg, RegState::Undef, SubReg)
3082  .addReg(SrcReg, RegState::Implicit);
3083  }
3084 
3085  MI.eraseFromParent();
3086 
3087  return LoopBB;
3088 }
3089 
3090 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3091  const TargetRegisterClass *VecRC) {
3092  switch (TRI.getRegSizeInBits(*VecRC)) {
3093  case 32: // 4 bytes
3094  return AMDGPU::V_MOVRELD_B32_V1;
3095  case 64: // 8 bytes
3096  return AMDGPU::V_MOVRELD_B32_V2;
3097  case 128: // 16 bytes
3098  return AMDGPU::V_MOVRELD_B32_V4;
3099  case 256: // 32 bytes
3100  return AMDGPU::V_MOVRELD_B32_V8;
3101  case 512: // 64 bytes
3102  return AMDGPU::V_MOVRELD_B32_V16;
3103  default:
3104  llvm_unreachable("unsupported size for MOVRELD pseudos");
3105  }
3106 }
3107 
3109  MachineBasicBlock &MBB,
3110  const GCNSubtarget &ST) {
3111  const SIInstrInfo *TII = ST.getInstrInfo();
3112  const SIRegisterInfo &TRI = TII->getRegisterInfo();
3113  MachineFunction *MF = MBB.getParent();
3115 
3116  unsigned Dst = MI.getOperand(0).getReg();
3117  const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3118  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3119  const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3120  int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3121  const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3122 
3123  // This can be an immediate, but will be folded later.
3124  assert(Val->getReg());
3125 
3126  unsigned SubReg;
3127  std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3128  SrcVec->getReg(),
3129  Offset);
3130  bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3131 
3132  if (Idx->getReg() == AMDGPU::NoRegister) {
3134  const DebugLoc &DL = MI.getDebugLoc();
3135 
3136  assert(Offset == 0);
3137 
3138  BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3139  .add(*SrcVec)
3140  .add(*Val)
3141  .addImm(SubReg);
3142 
3143  MI.eraseFromParent();
3144  return &MBB;
3145  }
3146 
3147  if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3149  const DebugLoc &DL = MI.getDebugLoc();
3150 
3151  if (UseGPRIdxMode) {
3152  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3153  .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3154  .add(*Val)
3155  .addReg(Dst, RegState::ImplicitDefine)
3156  .addReg(SrcVec->getReg(), RegState::Implicit)
3157  .addReg(AMDGPU::M0, RegState::Implicit);
3158 
3159  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3160  } else {
3161  const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3162 
3163  BuildMI(MBB, I, DL, MovRelDesc)
3164  .addReg(Dst, RegState::Define)
3165  .addReg(SrcVec->getReg())
3166  .add(*Val)
3167  .addImm(SubReg - AMDGPU::sub0);
3168  }
3169 
3170  MI.eraseFromParent();
3171  return &MBB;
3172  }
3173 
3174  if (Val->isReg())
3175  MRI.clearKillFlags(Val->getReg());
3176 
3177  const DebugLoc &DL = MI.getDebugLoc();
3178 
3179  unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3180 
3181  auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3182  Offset, UseGPRIdxMode, false);
3183  MachineBasicBlock *LoopBB = InsPt->getParent();
3184 
3185  if (UseGPRIdxMode) {
3186  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3187  .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3188  .add(*Val) // src0
3190  .addReg(PhiReg, RegState::Implicit)
3191  .addReg(AMDGPU::M0, RegState::Implicit);
3192  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3193  } else {
3194  const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3195 
3196  BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3197  .addReg(Dst, RegState::Define)
3198  .addReg(PhiReg)
3199  .add(*Val)
3200  .addImm(SubReg - AMDGPU::sub0);
3201  }
3202 
3203  MI.eraseFromParent();
3204 
3205  return LoopBB;
3206 }
3207 
3209  MachineInstr &MI, MachineBasicBlock *BB) const {
3210 
3211  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3212  MachineFunction *MF = BB->getParent();
3214 
3215  if (TII->isMIMG(MI)) {
3216  if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3217  report_fatal_error("missing mem operand from MIMG instruction");
3218  }
3219  // Add a memoperand for mimg instructions so that they aren't assumed to
3220  // be ordered memory instuctions.
3221 
3222  return BB;
3223  }
3224 
3225  switch (MI.getOpcode()) {
3226  case AMDGPU::S_ADD_U64_PSEUDO:
3227  case AMDGPU::S_SUB_U64_PSEUDO: {
3229  const DebugLoc &DL = MI.getDebugLoc();
3230 
3231  MachineOperand &Dest = MI.getOperand(0);
3232  MachineOperand &Src0 = MI.getOperand(1);
3233  MachineOperand &Src1 = MI.getOperand(2);
3234 
3235  unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3236  unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3237 
3238  MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3239  Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3240  &AMDGPU::SReg_32_XM0RegClass);
3241  MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3242  Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3243  &AMDGPU::SReg_32_XM0RegClass);
3244 
3245  MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3246  Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3247  &AMDGPU::SReg_32_XM0RegClass);
3248  MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3249  Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3250  &AMDGPU::SReg_32_XM0RegClass);
3251 
3252  bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3253 
3254  unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3255  unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3256  BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3257  .add(Src0Sub0)
3258  .add(Src1Sub0);
3259  BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3260  .add(Src0Sub1)
3261  .add(Src1Sub1);
3262  BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3263  .addReg(DestSub0)
3264  .addImm(AMDGPU::sub0)
3265  .addReg(DestSub1)
3266  .addImm(AMDGPU::sub1);
3267  MI.eraseFromParent();
3268  return BB;
3269  }
3270  case AMDGPU::SI_INIT_M0: {
3271  BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3272  TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3273  .add(MI.getOperand(0));
3274  MI.eraseFromParent();
3275  return BB;
3276  }
3277  case AMDGPU::SI_INIT_EXEC:
3278  // This should be before all vector instructions.
3279  BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3280  AMDGPU::EXEC)
3281  .addImm(MI.getOperand(0).getImm());
3282  MI.eraseFromParent();
3283  return BB;
3284 
3285  case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3286  // Extract the thread count from an SGPR input and set EXEC accordingly.
3287  // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3288  //
3289  // S_BFE_U32 count, input, {shift, 7}
3290  // S_BFM_B64 exec, count, 0
3291  // S_CMP_EQ_U32 count, 64
3292  // S_CMOV_B64 exec, -1
3293  MachineInstr *FirstMI = &*BB->begin();
3295  unsigned InputReg = MI.getOperand(0).getReg();
3296  unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3297  bool Found = false;
3298 
3299  // Move the COPY of the input reg to the beginning, so that we can use it.
3300  for (auto I = BB->begin(); I != &MI; I++) {
3301  if (I->getOpcode() != TargetOpcode::COPY ||
3302  I->getOperand(0).getReg() != InputReg)
3303  continue;
3304 
3305  if (I == FirstMI) {
3306  FirstMI = &*++BB->begin();
3307  } else {
3308  I->removeFromParent();
3309  BB->insert(FirstMI, &*I);
3310  }
3311  Found = true;
3312  break;
3313  }
3314  assert(Found);
3315  (void)Found;
3316 
3317  // This should be before all vector instructions.
3318  BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3319  .addReg(InputReg)
3320  .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3321  BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3322  AMDGPU::EXEC)
3323  .addReg(CountReg)
3324  .addImm(0);
3325  BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3326  .addReg(CountReg, RegState::Kill)
3327  .addImm(64);
3328  BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3329  AMDGPU::EXEC)
3330  .addImm(-1);
3331  MI.eraseFromParent();
3332  return BB;
3333  }
3334 
3335  case AMDGPU::GET_GROUPSTATICSIZE: {
3336  DebugLoc DL = MI.getDebugLoc();
3337  BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3338  .add(MI.getOperand(0))
3339  .addImm(MFI->getLDSSize());
3340  MI.eraseFromParent();
3341  return BB;
3342  }
3343  case AMDGPU::SI_INDIRECT_SRC_V1:
3344  case AMDGPU::SI_INDIRECT_SRC_V2:
3345  case AMDGPU::SI_INDIRECT_SRC_V4:
3346  case AMDGPU::SI_INDIRECT_SRC_V8:
3347  case AMDGPU::SI_INDIRECT_SRC_V16:
3348  return emitIndirectSrc(MI, *BB, *getSubtarget());
3349  case AMDGPU::SI_INDIRECT_DST_V1:
3350  case AMDGPU::SI_INDIRECT_DST_V2:
3351  case AMDGPU::SI_INDIRECT_DST_V4:
3352  case AMDGPU::SI_INDIRECT_DST_V8:
3353  case AMDGPU::SI_INDIRECT_DST_V16:
3354  return emitIndirectDst(MI, *BB, *getSubtarget());
3355  case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3356  case AMDGPU::SI_KILL_I1_PSEUDO:
3357  return splitKillBlock(MI, BB);
3358  case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3360 
3361  unsigned Dst = MI.getOperand(0).getReg();
3362  unsigned Src0 = MI.getOperand(1).getReg();
3363  unsigned Src1 = MI.getOperand(2).getReg();
3364  const DebugLoc &DL = MI.getDebugLoc();
3365  unsigned SrcCond = MI.getOperand(3).getReg();
3366 
3367  unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3368  unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3369  unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3370 
3371  BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3372  .addReg(SrcCond);
3373  BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3374  .addReg(Src0, 0, AMDGPU::sub0)
3375  .addReg(Src1, 0, AMDGPU::sub0)
3376  .addReg(SrcCondCopy);
3377  BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3378  .addReg(Src0, 0, AMDGPU::sub1)
3379  .addReg(Src1, 0, AMDGPU::sub1)
3380  .addReg(SrcCondCopy);
3381 
3382  BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3383  .addReg(DstLo)
3384  .addImm(AMDGPU::sub0)
3385  .addReg(DstHi)
3386  .addImm(AMDGPU::sub1);
3387  MI.eraseFromParent();
3388  return BB;
3389  }
3390  case AMDGPU::SI_BR_UNDEF: {
3391  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3392  const DebugLoc &DL = MI.getDebugLoc();
3393  MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3394  .add(MI.getOperand(0));
3395  Br->getOperand(1).setIsUndef(true); // read undef SCC
3396  MI.eraseFromParent();
3397  return BB;
3398  }
3399  case AMDGPU::ADJCALLSTACKUP:
3400  case AMDGPU::ADJCALLSTACKDOWN: {
3402  MachineInstrBuilder MIB(*MF, &MI);
3403 
3404  // Add an implicit use of the frame offset reg to prevent the restore copy
3405  // inserted after the call from being reorderd after stack operations in the
3406  // the caller's frame.
3407  MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3408  .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3409  .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3410  return BB;
3411  }
3412  case AMDGPU::SI_CALL_ISEL:
3413  case AMDGPU::SI_TCRETURN_ISEL: {
3414  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3415  const DebugLoc &DL = MI.getDebugLoc();
3416  unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3417 
3419  unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3420  MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3421  assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3422 
3423  const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3424 
3425  MachineInstrBuilder MIB;
3426  if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3427  MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3428  .add(MI.getOperand(0))
3429  .addGlobalAddress(G);
3430  } else {
3431  MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3432  .add(MI.getOperand(0))
3433  .addGlobalAddress(G);
3434 
3435  // There is an additional imm operand for tcreturn, but it should be in the
3436  // right place already.
3437  }
3438 
3439  for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3440  MIB.add(MI.getOperand(I));
3441 
3442  MIB.cloneMemRefs(MI);
3443  MI.eraseFromParent();
3444  return BB;
3445  }
3446  default:
3448  }
3449 }
3450 
3452  return isTypeLegal(VT.getScalarType());
3453 }
3454 
3456  // This currently forces unfolding various combinations of fsub into fma with
3457  // free fneg'd operands. As long as we have fast FMA (controlled by
3458  // isFMAFasterThanFMulAndFAdd), we should perform these.
3459 
3460  // When fma is quarter rate, for f64 where add / sub are at best half rate,
3461  // most of these combines appear to be cycle neutral but save on instruction
3462  // count / code size.
3463  return true;
3464 }
3465 
3467  EVT VT) const {
3468  if (!VT.isVector()) {
3469  return MVT::i1;
3470  }
3471  return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3472 }
3473 
3475  // TODO: Should i16 be used always if legal? For now it would force VALU
3476  // shifts.
3477  return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3478 }
3479 
3480 // Answering this is somewhat tricky and depends on the specific device which
3481 // have different rates for fma or all f64 operations.
3482 //
3483 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3484 // regardless of which device (although the number of cycles differs between
3485 // devices), so it is always profitable for f64.
3486 //
3487 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3488 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3489 // which we can always do even without fused FP ops since it returns the same
3490 // result as the separate operations and since it is always full
3491 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3492 // however does not support denormals, so we do report fma as faster if we have
3493 // a fast fma device and require denormals.
3494 //
3496  VT = VT.getScalarType();
3497 
3498  switch (VT.getSimpleVT().SimpleTy) {
3499  case MVT::f32: {
3500  // This is as fast on some subtargets. However, we always have full rate f32
3501  // mad available which returns the same result as the separate operations
3502  // which we should prefer over fma. We can't use this if we want to support
3503  // denormals, so only report this in these cases.
3504  if (Subtarget->hasFP32Denormals())
3505  return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3506 
3507  // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3508  return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3509  }
3510  case MVT::f64:
3511  return true;
3512  case MVT::f16:
3513  return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3514  default:
3515  break;
3516  }
3517 
3518  return false;
3519 }
3520 
3521 //===----------------------------------------------------------------------===//
3522 // Custom DAG Lowering Operations
3523 //===----------------------------------------------------------------------===//
3524 
3525 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3526 // wider vector type is legal.
3528  SelectionDAG &DAG) const {
3529  unsigned Opc = Op.getOpcode();
3530  EVT VT = Op.getValueType();
3531  assert(VT == MVT::v4f16);
3532 
3533  SDValue Lo, Hi;
3534  std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3535 
3536  SDLoc SL(Op);
3537  SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3538  Op->getFlags());
3539  SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3540  Op->getFlags());
3541 
3542  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3543 }
3544 
3545 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3546 // wider vector type is legal.
3548  SelectionDAG &DAG) const {
3549  unsigned Opc = Op.getOpcode();
3550  EVT VT = Op.getValueType();
3551  assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3552 
3553  SDValue Lo0, Hi0;
3554  std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3555  SDValue Lo1, Hi1;
3556  std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3557 
3558  SDLoc SL(Op);
3559 
3560  SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3561  Op->getFlags());
3562  SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3563  Op->getFlags());
3564 
3565  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3566 }
3567 
3569  switch (Op.getOpcode()) {
3570  default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3571  case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3572  case ISD::LOAD: {
3573  SDValue Result = LowerLOAD(Op, DAG);
3574  assert((!Result.getNode() ||
3575  Result.getNode()->getNumValues() == 2) &&
3576  "Load should return a value and a chain");
3577  return Result;
3578  }
3579 
3580  case ISD::FSIN:
3581  case ISD::FCOS:
3582  return LowerTrig(Op, DAG);
3583  case ISD::SELECT: return LowerSELECT(Op, DAG);
3584  case ISD::FDIV: return LowerFDIV(Op, DAG);
3585  case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3586  case ISD::STORE: return LowerSTORE(Op, DAG);
3587  case ISD::GlobalAddress: {
3588  MachineFunction &MF = DAG.getMachineFunction();
3590  return LowerGlobalAddress(MFI, Op, DAG);
3591  }
3592  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3593  case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3594  case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3595  case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3597  return lowerINSERT_VECTOR_ELT(Op, DAG);
3599  return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3600  case ISD::BUILD_VECTOR:
3601  return lowerBUILD_VECTOR(Op, DAG);
3602  case ISD::FP_ROUND:
3603  return lowerFP_ROUND(Op, DAG);
3604  case ISD::TRAP:
3605  return lowerTRAP(Op, DAG);
3606  case ISD::DEBUGTRAP:
3607  return lowerDEBUGTRAP(Op, DAG);
3608  case ISD::FABS:
3609  case ISD::FNEG:
3610  case ISD::FCANONICALIZE:
3611  return splitUnaryVectorOp(Op, DAG);
3612  case ISD::FMINNUM:
3613  case ISD::FMAXNUM:
3614  return lowerFMINNUM_FMAXNUM(Op, DAG);
3615  case ISD::SHL:
3616  case ISD::SRA:
3617  case ISD::SRL:
3618  case ISD::ADD:
3619  case ISD::SUB:
3620  case ISD::MUL:
3621  case ISD::SMIN:
3622  case ISD::SMAX:
3623  case ISD::UMIN:
3624  case ISD::UMAX:
3625  case ISD::FADD:
3626  case ISD::FMUL:
3627  case ISD::FMINNUM_IEEE:
3628  case ISD::FMAXNUM_IEEE:
3629  return splitBinaryVectorOp(Op, DAG);
3630  }
3631  return SDValue();
3632 }
3633 
3635  const SDLoc &DL,
3636  SelectionDAG &DAG, bool Unpacked) {
3637  if (!LoadVT.isVector())
3638  return Result;
3639 
3640  if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3641  // Truncate to v2i16/v4i16.
3642  EVT IntLoadVT = LoadVT.changeTypeToInteger();
3643 
3644  // Workaround legalizer not scalarizing truncate after vector op
3645  // legalization byt not creating intermediate vector trunc.
3647  DAG.ExtractVectorElements(Result, Elts);
3648  for (SDValue &Elt : Elts)
3649  Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3650 
3651  Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3652 
3653  // Bitcast to original type (v2f16/v4f16).
3654  return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3655  }
3656 
3657  // Cast back to the original packed type.
3658  return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3659 }
3660 
3661 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3662  MemSDNode *M,
3663  SelectionDAG &DAG,
3664  ArrayRef<SDValue> Ops,
3665  bool IsIntrinsic) const {
3666  SDLoc DL(M);
3667 
3668  bool Unpacked = Subtarget->hasUnpackedD16VMem();
3669  EVT LoadVT = M->getValueType(0);
3670 
3671  EVT EquivLoadVT = LoadVT;
3672  if (Unpacked && LoadVT.isVector()) {
3673  EquivLoadVT = LoadVT.isVector() ?
3675  LoadVT.getVectorNumElements()) : LoadVT;
3676  }
3677 
3678  // Change from v4f16/v2f16 to EquivLoadVT.
3679  SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3680 
3681  SDValue Load
3682  = DAG.getMemIntrinsicNode(
3683  IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3684  VTList, Ops, M->getMemoryVT(),
3685  M->getMemOperand());
3686  if (!Unpacked) // Just adjusted the opcode.
3687  return Load;
3688 
3689  SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3690 
3691  return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3692 }
3693 
3695  SDNode *N, SelectionDAG &DAG) {
3696  EVT VT = N->getValueType(0);
3697  const auto *CD = dyn_cast<ConstantSDNode>(N->getOperand(3));
3698  if (!CD)
3699  return DAG.getUNDEF(VT);
3700 
3701  int CondCode = CD->getSExtValue();
3702  if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3703  CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3704  return DAG.getUNDEF(VT);
3705 
3706  ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3707 
3708 
3709  SDValue LHS = N->getOperand(1);
3710  SDValue RHS = N->getOperand(2);
3711 
3712  SDLoc DL(N);
3713 
3714  EVT CmpVT = LHS.getValueType();
3715  if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
3716  unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
3718  LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
3719  RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
3720  }
3721 
3722  ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3723 
3724  return DAG.getNode(AMDGPUISD::SETCC, DL, VT, LHS, RHS,
3725  DAG.getCondCode(CCOpcode));
3726 }
3727 
3729  SDNode *N, SelectionDAG &DAG) {
3730  EVT VT = N->getValueType(0);
3731  const auto *CD = dyn_cast<ConstantSDNode>(N->getOperand(3));
3732  if (!CD)
3733  return DAG.getUNDEF(VT);
3734 
3735  int CondCode = CD->getSExtValue();
3736  if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3737  CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
3738  return DAG.getUNDEF(VT);
3739  }
3740 
3741  SDValue Src0 = N->getOperand(1);
3742  SDValue Src1 = N->getOperand(2);
3743  EVT CmpVT = Src0.getValueType();
3744  SDLoc SL(N);
3745 
3746  if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
3747  Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3748  Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3749  }
3750 
3751  FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3752  ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3753  return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src0,
3754  Src1, DAG.getCondCode(CCOpcode));
3755 }
3756 
3759  SelectionDAG &DAG) const {
3760  switch (N->getOpcode()) {
3761  case ISD::INSERT_VECTOR_ELT: {
3762  if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3763  Results.push_back(Res);
3764  return;
3765  }
3766  case ISD::EXTRACT_VECTOR_ELT: {
3767  if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3768  Results.push_back(Res);
3769  return;
3770  }
3771  case ISD::INTRINSIC_WO_CHAIN: {
3772  unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3773  switch (IID) {
3774  case Intrinsic::amdgcn_cvt_pkrtz: {
3775  SDValue Src0 = N->getOperand(1);
3776  SDValue Src1 = N->getOperand(2);
3777  SDLoc SL(N);
3779  Src0, Src1);
3780  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3781  return;
3782  }
3783  case Intrinsic::amdgcn_cvt_pknorm_i16:
3784  case Intrinsic::amdgcn_cvt_pknorm_u16:
3785  case Intrinsic::amdgcn_cvt_pk_i16:
3786  case Intrinsic::amdgcn_cvt_pk_u16: {
3787  SDValue Src0 = N->getOperand(1);
3788  SDValue Src1 = N->getOperand(2);
3789  SDLoc SL(N);
3790  unsigned Opcode;
3791 
3792  if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3794  else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3796  else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3797  Opcode = AMDGPUISD::CVT_PK_I16_I32;
3798  else
3799  Opcode = AMDGPUISD::CVT_PK_U16_U32;
3800 
3801  EVT VT = N->getValueType(0);
3802  if (isTypeLegal(VT))
3803  Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
3804  else {
3805  SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3806  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3807  }
3808  return;
3809  }
3810  }
3811  break;
3812  }
3813  case ISD::INTRINSIC_W_CHAIN: {
3814  if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3815  Results.push_back(Res);
3816  Results.push_back(Res.getValue(1));
3817  return;
3818  }
3819 
3820  break;
3821  }
3822  case ISD::SELECT: {
3823  SDLoc SL(N);
3824  EVT VT = N->getValueType(0);
3825  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3826  SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3827  SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3828 
3829  EVT SelectVT = NewVT;
3830  if (NewVT.bitsLT(MVT::i32)) {
3831  LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3832  RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3833  SelectVT = MVT::i32;
3834  }
3835 
3836  SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3837  N->getOperand(0), LHS, RHS);
3838 
3839  if (NewVT != SelectVT)
3840  NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3841  Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3842  return;
3843  }
3844  case ISD::FNEG: {
3845  if (N->getValueType(0) != MVT::v2f16)
3846  break;
3847 
3848  SDLoc SL(N);
3849  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3850 
3851  SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3852  BC,
3853  DAG.getConstant(0x80008000, SL, MVT::i32));
3854  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3855  return;
3856  }
3857  case ISD::FABS: {
3858  if (N->getValueType(0) != MVT::v2f16)
3859  break;
3860 
3861  SDLoc SL(N);
3862  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3863 
3864  SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3865  BC,
3866  DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3867  Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3868  return;
3869  }
3870  default:
3871  break;
3872  }
3873 }
3874 
3875 /// Helper function for LowerBRCOND
3876 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3877 
3878  SDNode *Parent = Value.getNode();
3879  for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3880  I != E; ++I) {
3881 
3882  if (I.getUse().get() != Value)
3883  continue;
3884 
3885  if (I->getOpcode() == Opcode)
3886  return *I;
3887  }
3888  return nullptr;
3889 }
3890 
3891 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3892  if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3893  switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3894  case Intrinsic::amdgcn_if:
3895  return AMDGPUISD::IF;
3896  case Intrinsic::amdgcn_else:
3897  return AMDGPUISD::ELSE;
3898  case Intrinsic::amdgcn_loop:
3899  return AMDGPUISD::LOOP;
3900  case Intrinsic::amdgcn_end_cf:
3901  llvm_unreachable("should not occur");
3902  default:
3903  return 0;
3904  }
3905  }
3906 
3907  // break, if_break, else_break are all only used as inputs to loop, not
3908  // directly as branch conditions.
3909  return 0;
3910 }
3911 
3912 void SITargetLowering::createDebuggerPrologueStackObjects(
3913  MachineFunction &MF) const {
3914  // Create stack objects that are used for emitting debugger prologue.
3915  //
3916  // Debugger prologue writes work group IDs and work item IDs to scratch memory
3917  // at fixed location in the following format:
3918  // offset 0: work group ID x
3919  // offset 4: work group ID y
3920  // offset 8: work group ID z
3921  // offset 16: work item ID x
3922  // offset 20: work item ID y
3923  // offset 24: work item ID z
3925  int ObjectIdx = 0;
3926 
3927  // For each dimension:
3928  for (unsigned i = 0; i < 3; ++i) {
3929  // Create fixed stack object for work group ID.
3930  ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3931  Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3932  // Create fixed stack object for work item ID.
3933  ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3934  Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3935  }
3936 }
3937 
3938 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3939  const Triple &TT = getTargetMachine().getTargetTriple();
3940  return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
3943 }
3944 
3945 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3946  return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
3949  !shouldEmitFixup(GV) &&
3951 }
3952 
3953 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3954  return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3955 }
3956 
3957 /// This transforms the control flow intrinsics to get the branch destination as
3958 /// last parameter, also switches branch target with BR if the need arise
3959 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3960  SelectionDAG &DAG) const {
3961  SDLoc DL(BRCOND);
3962 
3963  SDNode *Intr = BRCOND.getOperand(1).getNode();
3964  SDValue Target = BRCOND.getOperand(2);
3965  SDNode *BR = nullptr;
3966  SDNode *SetCC = nullptr;
3967 
3968  if (Intr->getOpcode() == ISD::SETCC) {
3969  // As long as we negate the condition everything is fine
3970  SetCC = Intr;
3971  Intr = SetCC->getOperand(0).getNode();
3972 
3973  } else {
3974  // Get the target from BR if we don't negate the condition
3975  BR = findUser(BRCOND, ISD::BR);
3976  Target = BR->getOperand(1);
3977  }
3978 
3979  // FIXME: This changes the types of the intrinsics instead of introducing new
3980  // nodes with the correct types.
3981  // e.g. llvm.amdgcn.loop
3982 
3983  // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3984  // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3985 
3986  unsigned CFNode = isCFIntrinsic(Intr);
3987  if (CFNode == 0) {
3988  // This is a uniform branch so we don't need to legalize.
3989  return BRCOND;
3990  }
3991 
3992  bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3993  Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3994 
3995  assert(!SetCC ||
3996  (SetCC->getConstantOperandVal(1) == 1 &&
3997  cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3998  ISD::SETNE));
3999 
4000  // operands of the new intrinsic call
4002  if (HaveChain)
4003  Ops.push_back(BRCOND.getOperand(0));
4004 
4005  Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
4006  Ops.push_back(Target);
4007 
4008  ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4009 
4010  // build the new intrinsic call
4011  SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4012 
4013  if (!HaveChain) {
4014  SDValue Ops[] = {
4015  SDValue(Result, 0),
4016  BRCOND.getOperand(0)
4017  };
4018 
4019  Result = DAG.getMergeValues(Ops, DL).getNode();
4020  }
4021 
4022  if (BR) {
4023  // Give the branch instruction our target
4024  SDValue Ops[] = {
4025  BR->getOperand(0),
4026  BRCOND.getOperand(2)
4027  };
4028  SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4029  DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4030  BR = NewBR.getNode();
4031  }
4032 
4033  SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4034 
4035  // Copy the intrinsic results to registers
4036  for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4038  if (!CopyToReg)
4039  continue;
4040 
4041  Chain = DAG.getCopyToReg(
4042  Chain, DL,
4043  CopyToReg->getOperand(1),
4044  SDValue(Result, i - 1),
4045  SDValue());
4046 
4047  DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4048  }
4049 
4050  // Remove the old intrinsic from the chain
4052  SDValue(Intr, Intr->getNumValues() - 1),
4053  Intr->getOperand(0));
4054 
4055  return Chain;
4056 }
4057 
4058 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4059  SDValue Op,
4060  const SDLoc &DL,
4061  EVT VT) const {
4062  return Op.getValueType().bitsLE(VT) ?
4063  DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4064  DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4065 }
4066 
4067 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4068  assert(Op.getValueType() == MVT::f16 &&
4069  "Do not know how to custom lower FP_ROUND for non-f16 type");
4070 
4071  SDValue Src = Op.getOperand(0);
4072  EVT SrcVT = Src.getValueType();
4073  if (SrcVT != MVT::f64)
4074  return Op;
4075 
4076  SDLoc DL(Op);
4077 
4078  SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4079  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4080  return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4081 }
4082 
4083 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4084  SelectionDAG &DAG) const {
4085  EVT VT = Op.getValueType();
4086  bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
4087 
4088  // FIXME: Assert during eslection that this is only selected for
4089  // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4090  // mode functions, but this happens to be OK since it's only done in cases
4091  // where there is known no sNaN.
4092  if (IsIEEEMode)
4093  return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4094 
4095  if (VT == MVT::v4f16)
4096  return splitBinaryVectorOp(Op, DAG);
4097  return Op;
4098 }
4099 
4100 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4101  SDLoc SL(Op);
4102  SDValue Chain = Op.getOperand(0);
4103 
4104  if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4105  !Subtarget->isTrapHandlerEnabled())
4106  return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4107 
4108  MachineFunction &MF = DAG.getMachineFunction();
4110  unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4111  assert(UserSGPR != AMDGPU::NoRegister);
4112  SDValue QueuePtr = CreateLiveInRegister(
4113  DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4114  SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4115  SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4116  QueuePtr, SDValue());
4117  SDValue Ops[] = {
4118  ToReg,
4120  SGPR01,
4121  ToReg.getValue(1)
4122  };
4123  return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4124 }
4125 
4126 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4127  SDLoc SL(Op);
4128  SDValue Chain = Op.getOperand(0);
4129  MachineFunction &MF = DAG.getMachineFunction();
4130 
4131  if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4132  !Subtarget->isTrapHandlerEnabled()) {
4134  "debugtrap handler not supported",
4135  Op.getDebugLoc(),
4136  DS_Warning);
4137  LLVMContext &Ctx = MF.getFunction().getContext();
4138  Ctx.diagnose(NoTrap);
4139  return Chain;
4140  }
4141 
4142  SDValue Ops[] = {
4143  Chain,
4145  };
4146  return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4147 }
4148 
4149 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4150  SelectionDAG &DAG) const {
4151  // FIXME: Use inline constants (src_{shared, private}_base) instead.
4152  if (Subtarget->hasApertureRegs()) {
4153  unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4156  unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4159  unsigned Encoding =
4161  Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4162  WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4163 
4164  SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4165  SDValue ApertureReg = SDValue(
4166  DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4167  SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4168  return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4169  }
4170 
4171  MachineFunction &MF = DAG.getMachineFunction();
4173  unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4174  assert(UserSGPR != AMDGPU::NoRegister);
4175 
4176  SDValue QueuePtr = CreateLiveInRegister(
4177  DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4178 
4179  // Offset into amd_queue_t for group_segment_aperture_base_hi /
4180  // private_segment_aperture_base_hi.
4181  uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4182 
4183  SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4184 
4185  // TODO: Use custom target PseudoSourceValue.
4186  // TODO: We should use the value from the IR intrinsic call, but it might not
4187  // be available and how do we get it?
4190 
4191  MachinePointerInfo PtrInfo(V, StructOffset);
4192  return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4193  MinAlign(64, StructOffset),
4196 }
4197 
4198 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4199  SelectionDAG &DAG) const {
4200  SDLoc SL(Op);
4201  const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4202 
4203  SDValue Src = ASC->getOperand(0);
4204  SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4205 
4206  const AMDGPUTargetMachine &TM =
4207  static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4208 
4209  // flat -> local/private
4211  unsigned DestAS = ASC->getDestAddressSpace();
4212 
4213  if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4214  DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4215  unsigned NullVal = TM.getNullPointerValue(DestAS);
4216  SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4217  SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4218  SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4219 
4220  return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4221  NonNull, Ptr, SegmentNullPtr);
4222  }
4223  }
4224 
4225  // local/private -> flat
4227  unsigned SrcAS = ASC->getSrcAddressSpace();
4228 
4229  if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4230  SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4231  unsigned NullVal = TM.getNullPointerValue(SrcAS);
4232  SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4233 
4234  SDValue NonNull
4235  = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4236 
4237  SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4238  SDValue CvtPtr
4239  = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4240 
4241  return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4242  DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4243  FlatNullPtr);
4244  }
4245  }
4246 
4247  // global <-> flat are no-ops and never emitted.
4248 
4249  const MachineFunction &MF = DAG.getMachineFunction();
4250  DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4251  MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4252  DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4253 
4254  return DAG.getUNDEF(ASC->getValueType(0));
4255 }
4256 
4257 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4258  SelectionDAG &DAG) const {
4259  SDValue Vec = Op.getOperand(0);
4260  SDValue InsVal = Op.getOperand(1);
4261  SDValue Idx = Op.getOperand(2);
4262  EVT VecVT = Vec.getValueType();
4263  EVT EltVT = VecVT.getVectorElementType();
4264  unsigned VecSize = VecVT.getSizeInBits();
4265  unsigned EltSize = EltVT.getSizeInBits();
4266 
4267 
4268  assert(VecSize <= 64);
4269 
4270  unsigned NumElts = VecVT.getVectorNumElements();
4271  SDLoc SL(Op);
4272  auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4273 
4274  if (NumElts == 4 && EltSize == 16 && KIdx) {
4275  SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4276 
4277  SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4278  DAG.getConstant(0, SL, MVT::i32));
4279  SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4280  DAG.getConstant(1, SL, MVT::i32));
4281 
4282  SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4283  SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4284 
4285  unsigned Idx = KIdx->getZExtValue();
4286  bool InsertLo = Idx < 2;
4287  SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4288  InsertLo ? LoVec : HiVec,
4289  DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4290  DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4291 
4292  InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4293 
4294  SDValue Concat = InsertLo ?
4295  DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4296  DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4297 
4298  return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4299  }
4300 
4301  if (isa<ConstantSDNode>(Idx))
4302  return SDValue();
4303 
4304  MVT IntVT = MVT::getIntegerVT(VecSize);
4305 
4306  // Avoid stack access for dynamic indexing.
4307  SDValue Val = InsVal;
4308  if (InsVal.getValueType() == MVT::f16)
4309  Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal);
4310 
4311  // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4312  SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val);
4313 
4314  assert(isPowerOf2_32(EltSize));
4315  SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4316 
4317  // Convert vector index to bit-index.
4318  SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4319 
4320  SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4321  SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4322  DAG.getConstant(0xffff, SL, IntVT),
4323  ScaledIdx);
4324 
4325  SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4326  SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4327  DAG.getNOT(SL, BFM, IntVT), BCVec);
4328 
4329  SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4330  return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4331 }
4332 
4333 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4334  SelectionDAG &DAG) const {
4335  SDLoc SL(Op);
4336 
4337  EVT ResultVT = Op.getValueType();
4338  SDValue Vec = Op.getOperand(0);
4339  SDValue Idx = Op.getOperand(1);
4340  EVT VecVT = Vec.getValueType();
4341  unsigned VecSize = VecVT.getSizeInBits();
4342  EVT EltVT = VecVT.getVectorElementType();
4343  assert(VecSize <= 64);
4344 
4345  DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4346 
4347  // Make sure we do any optimizations that will make it easier to fold
4348  // source modifiers before obscuring it with bit operations.
4349 
4350  // XXX - Why doesn't this get called when vector_shuffle is expanded?
4351  if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4352  return Combined;
4353 
4354  unsigned EltSize = EltVT.getSizeInBits();
4355  assert(isPowerOf2_32(EltSize));
4356 
4357  MVT IntVT = MVT::getIntegerVT(VecSize);
4358  SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4359 
4360  // Convert vector index to bit-index (* EltSize)
4361  SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4362 
4363  SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4364  SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4365 
4366  if (ResultVT == MVT::f16) {
4367  SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4368  return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4369  }
4370 
4371  return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4372 }
4373 
4374 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4375  SelectionDAG &DAG) const {
4376  SDLoc SL(Op);
4377  EVT VT = Op.getValueType();
4378 
4379  if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4381 
4382  // Turn into pair of packed build_vectors.
4383  // TODO: Special case for constants that can be materialized with s_mov_b64.
4384  SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4385  { Op.getOperand(0), Op.getOperand(1) });
4386  SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4387  { Op.getOperand(2), Op.getOperand(3) });
4388 
4389  SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4390  SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4391 
4392  SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4393  return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4394  }
4395 
4396  assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4397  assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4398 
4399  SDValue Lo = Op.getOperand(0);
4400  SDValue Hi = Op.getOperand(1);
4401 
4402  // Avoid adding defined bits with the zero_extend.
4403  if (Hi.isUndef()) {
4404  Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4405  SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4406  return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4407  }
4408 
4409  Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4410  Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4411 
4412  SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4413  DAG.getConstant(16, SL, MVT::i32));
4414  if (Lo.isUndef())
4415  return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4416 
4417  Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4418  Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4419 
4420  SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4421  return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4422 }
4423 
4424 bool
4426  // We can fold offsets for anything that doesn't require a GOT relocation.
4427  return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4430  !shouldEmitGOTReloc(GA->getGlobal());
4431 }
4432 
4433 static SDValue
4435  const SDLoc &DL, unsigned Offset, EVT PtrVT,
4436  unsigned GAFlags = SIInstrInfo::MO_NONE) {
4437  // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4438  // lowered to the following code sequence:
4439  //
4440  // For constant address space:
4441  // s_getpc_b64 s[0:1]
4442  // s_add_u32 s0, s0, $symbol
4443  // s_addc_u32 s1, s1, 0
4444  //
4445