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