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