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